Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): nested membership model — access vs notification (#364)

Gener67ca8bdde540
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index c5973b497..4df53da20 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -769,12 +769,15 @@ describe("truncateThinking", () => {
});
describe("AgentProcessManager — bot audit event emission", () => {
- it("emits `thinking` with truncated+chars fields", () => {
+ it("emits `thinking` with truncated+chars fields (flushed at the next event)", () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
mgr.deliver("a1", { seq: 1, text: "hello" });
+ // A reasoning block buffers until a non-thinking event flushes it.
session.fire("runtime_event", { kind: "thinking", text: "think about it" });
+ expect(onBotAuditEvent).not.toHaveBeenCalled();
+ session.fire("runtime_event", { kind: "turn_end" });
expect(onBotAuditEvent).toHaveBeenCalledWith(
"a1",
@@ -790,6 +793,31 @@ describe("AgentProcessManager — bot audit event emission", () => {
);
});
+ it("coalesces delta-streamed thinking into ONE row and drops empty deltas", () => {
+ const onBotAuditEvent = vi.fn();
+ const { mgr, session } = makeManager({ onBotAuditEvent });
+ mgr.deliver("a1", { seq: 1, text: "hello" });
+
+ // Delta-streaming drivers (codex/pi) emit token fragments + empty markers.
+ session.fire("runtime_event", { kind: "thinking", text: "" });
+ session.fire("runtime_event", { kind: "thinking", text: "let me " });
+ session.fire("runtime_event", { kind: "thinking", text: "count" });
+ session.fire("runtime_event", { kind: "thinking", text: "" });
+ // Flush on the following tool_call.
+ session.fire("runtime_event", { kind: "tool_call", name: "Read", input: {} });
+
+ const thinkingCalls = onBotAuditEvent.mock.calls.filter(
+ ([, ev]) => (ev as { kind?: string })?.kind === "thinking"
+ );
+ expect(thinkingCalls).toHaveLength(1);
+ expect(thinkingCalls[0]![1]).toEqual(
+ expect.objectContaining({
+ kind: "thinking",
+ payload: expect.objectContaining({ text: "let me count", chars: 12 }),
+ })
+ );
+ });
+
it("emits `tool_call` with name only (strips input)", () => {
const onBotAuditEvent = vi.fn();
const { mgr, session } = makeManager({ onBotAuditEvent });
diff --git a/src/daemon/src/manager/managerRuntime.ts b/src/daemon/src/manager/managerRuntime.ts
index 10d599829..24b0b5867 100644
--- a/src/daemon/src/manager/managerRuntime.ts
+++ b/src/daemon/src/manager/managerRuntime.ts
@@ -216,6 +216,14 @@ export class AgentProcessManager {
private readonly launchIds = new Map<string, string>();
/** agentId → live runtime sessionId (learned from session_init), for resync. */
private readonly liveSessions = new Map<string, string>();
+ /**
+ * agentId → accumulated `thinking` text for the current reasoning block.
+ * Several drivers (codex, pi, copilot) stream thinking token-by-token; we
+ * buffer the deltas and flush ONE audit row at the next non-thinking event /
+ * turn boundary / exit, instead of a D1 insert+prune per token. Block-based
+ * drivers (claude, cursor) emit one full-text event → one row, unchanged.
+ */
+ private readonly thinkingBuffers = new Map<string, string>();
/**
* agentId → the current spawn's per-session end-tracking flags, shared
* between `doSpawn`'s closure (turn_end / exit) and `applyEffect` (stop /
@@ -563,6 +571,8 @@ export class AgentProcessManager {
// termination wasn't already logged under a more specific reason (see
// `suppressExitLog` above).
if (state.hasEstablished && !state.suppressExitLog) this.logSessionEnded(agentId, "exit");
+ // Flush any reasoning block that never saw a following event before exit.
+ this.flushThinkingAudit(agentId);
this.sessions.delete(agentId);
this.liveSessions.delete(agentId);
if (this.activeSpawnState.get(agentId) === state) this.activeSpawnState.delete(agentId);
@@ -594,6 +604,29 @@ export class AgentProcessManager {
});
}
+ /**
+ * Emit the buffered reasoning block as a single `thinking` audit row, then
+ * clear the buffer. No-op when nothing accumulated (empty deltas were never
+ * buffered). Called before any non-thinking event and on session exit so a
+ * block always flushes even if the turn ends without a following tool call.
+ */
+ private flushThinkingAudit(agentId: string): void {
+ const buffered = this.thinkingBuffers.get(agentId);
+ if (!buffered) return;
+ this.thinkingBuffers.delete(agentId);
+ if (!this.opts.onBotAuditEvent) return;
+ const { text, truncated, chars } = truncateThinking(buffered);
+ try {
+ this.opts.onBotAuditEvent(agentId, {
+ kind: "thinking",
+ payload: { text, truncated, chars },
+ }, {
+ sessionId: this.liveSessions.get(agentId) ?? null,
+ launchId: this.launchIds.get(agentId) ?? null,
+ });
+ } catch { /* observational */ }
+ }
+
private onRuntimeEvent(agentId: string, e: unknown, runtimeId: string): void {
const ev = e as { kind?: string; sessionId?: string; text?: string; name?: string };
if (!ev?.kind) return;
@@ -604,29 +637,32 @@ export class AgentProcessManager {
// event fires BEFORE the runtime has emitted its handshake, sessionId is
// null and the row records the launch without a session id.
if (this.opts.onBotAuditEvent) {
- const context = {
- sessionId: this.liveSessions.get(agentId) ?? null,
- launchId: this.launchIds.get(agentId) ?? null,
- };
if (ev.kind === "thinking" && typeof ev.text === "string") {
- const { text, truncated, chars } = truncateThinking(ev.text);
- try {
- this.opts.onBotAuditEvent(agentId, {
- kind: "thinking",
- payload: { text, truncated, chars },
- }, context);
- } catch { /* observational */ }
- } else if (ev.kind === "tool_call" && typeof ev.name === "string") {
- // Bash suppression — the credential proxy emits the authoritative
- // `cli_invocation` when the agent invokes `alook` from a shell, and
- // raw non-`alook` Bash isn't user-visible in the audit spec.
- if (ev.name !== "Bash") {
- try {
- this.opts.onBotAuditEvent(agentId, {
- kind: "tool_call",
- payload: { name: ev.name },
- }, context);
- } catch { /* observational */ }
+ // Accumulate; a delta-streaming driver emits many of these per block.
+ // The flush happens at the next non-thinking event / turn / exit so one
+ // reasoning block becomes one audit row, not one row per token.
+ if (ev.text.length > 0) {
+ this.thinkingBuffers.set(agentId, (this.thinkingBuffers.get(agentId) ?? "") + ev.text);
+ }
+ } else {
+ // Any non-thinking event ends the current reasoning block — flush it
+ // first so the audit log preserves thinking→action ordering.
+ this.flushThinkingAudit(agentId);
+ if (ev.kind === "tool_call" && typeof ev.name === "string") {
+ // Bash suppression — the credential proxy emits the authoritative
+ // `cli_invocation` when the agent invokes `alook` from a shell, and
+ // raw non-`alook` Bash isn't user-visible in the audit spec.
+ if (ev.name !== "Bash") {
+ try {
+ this.opts.onBotAuditEvent(agentId, {
+ kind: "tool_call",
+ payload: { name: ev.name },
+ }, {
+ sessionId: this.liveSessions.get(agentId) ?? null,
+ launchId: this.launchIds.get(agentId) ?? null,
+ });
+ } catch { /* observational */ }
+ }
}
}
}
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index 7a0d84734..1a964e3ce 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -76,10 +76,12 @@ export const communityChannel: SQLiteTableWithColumns<any> = sqliteTable(
);
// 3b. community_channel_member
-// Explicit per-channel membership. Rows exist ONLY for channels in PRIVATE
-// categories (creator + directly-added members). Public/uncategorized channels
-// imply access via server membership and store nothing here; threads inherit
-// their parent channel's audience and never get their own rows.
+// Explicit per-channel ACCESS membership. Rows exist ONLY for private access
+// units — a top-level channel in a PRIVATE category, or a forum_post under a
+// private forum (creator + directly-added members). Public/uncategorized
+// channels imply access via server membership and store nothing here. Threads
+// are the NOTIFICATION dimension, not access — they never get access rows here;
+// their notify set lives in `community_thread_participant` below.
export const communityChannelMember = sqliteTable(
"community_channel_member",
{
@@ -99,6 +101,37 @@ export const communityChannelMember = sqliteTable(
]
);
+// 3c. community_thread_participant
+// The NOTIFICATION set for a thread (`community_channel` row of type "thread").
+// A thread is NOT an access unit — any member of its parent channel can READ
+// it. This table decides only WHO gets notified (mention pings + inbox unread)
+// for new thread activity. `source` records how the user joined:
+// - "mention" — @-mentioned in the thread (a parent-channel member).
+// - "spoke" — posted a message in the thread.
+// - "added" — added by another participant via the participant picker.
+// Leaving a thread deletes the row (a later mention/speak re-adds). Admins are
+// NOT auto-added — a thread's notify set is exactly its rows. Muting a thread is
+// the OUTER channel-header notification level (per-layer, same control a channel
+// uses), NOT a column here — participation is add/leave only.
+export const communityThreadParticipant = sqliteTable(
+ "community_thread_participant",
+ {
+ id: text("id").primaryKey().$defaultFn(() => nanoid()),
+ threadChannelId: text("thread_channel_id")
+ .notNull()
+ .references(() => communityChannel.id, { onDelete: "cascade" }),
+ userId: text("user_id")
+ .notNull()
+ .references(() => user.id, { onDelete: "cascade" }),
+ source: text("source").notNull().default("mention"),
+ addedAt: text("added_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [
+ unique("uq_thread_participant").on(t.threadChannelId, t.userId),
+ index("idx_thread_participant_user").on(t.userId),
+ ]
+);
+
// 4. community_dm_conversation
export const communityDmConversation = sqliteTable(
"community_dm_conversation",
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 650ecab08..c84f68226 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -35,6 +35,7 @@ export * as communityChannel from "./queries/community/channel";
export * as communityCategory from "./queries/community/category";
export * as communityMember from "./queries/community/member";
export * as communityMembersResolver from "./queries/community/members-resolver";
+export * as communityThread from "./queries/community/thread";
export * as communityMessage from "./queries/community/message";
export * as communityFriendship from "./queries/community/friendship";
export * as communityDm from "./queries/community/dm";
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index e9c706be3..b8ead2481 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -97,6 +97,22 @@ export async function getChannel(db: Database, channelId: string) {
return row ? mapChannelRow(row) : null;
}
+// Just the `type` of a channel ("text" | "forum" | "forum_post" | "thread" |
+// null). A one-column probe for hot paths that only need to branch by type
+// (e.g. fan-out routing a thread to its participant set). Returns null when the
+// channel doesn't exist.
+export async function getChannelType(
+ db: Database,
+ channelId: string
+): Promise<string | null> {
+ const rows = await db
+ .select({ type: communityChannel.type })
+ .from(communityChannel)
+ .where(eq(communityChannel.id, channelId))
+ .limit(1);
+ return rows[0]?.type ?? null;
+}
+
/**
* Fetch a channel scoped to what `userId` may READ/POST — the read/post gate
* used by every message-scoped route. Server membership is the base gate
@@ -123,10 +139,20 @@ export async function getChannelForMember(db: Database, channelId: string, userI
if (!row) return null;
const { memberRole, ...channelRow } = row;
- // Resolve the anchor (self for a top-level channel, parent for a thread) and
- // check its privacy + the viewer's access. Only runs the extra lookups when
- // the anchor is actually in a private category.
- const anchorId = channelRow.parentChannelId ?? channelRow.id;
+ // 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 = channelRow.type === "forum_post";
+ const privacyAnchorId = channelRow.parentChannelId ?? channelRow.id;
+ const rosterAnchorId = isPost ? channelRow.id : privacyAnchorId;
+
const anchor = await db
.select({
creatorId: communityChannel.creatorId,
@@ -134,18 +160,26 @@ export async function getChannelForMember(db: Database, channelId: string, userI
})
.from(communityChannel)
.leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
- .where(eq(communityChannel.id, anchorId))
+ .where(eq(communityChannel.id, privacyAnchorId))
.limit(1);
const isPrivate = (anchor[0]?.categoryPrivate ?? 0) === 1;
if (isPrivate) {
- const isCreator = anchor[0]?.creatorId === userId;
- // Skip the member-row lookup when role/creator already grant access.
- const isMember =
- canManageServer(memberRole) || isCreator
- ? false
- : await isChannelMember(db, anchorId, userId);
- if (!canSeePrivateChannel({ role: memberRole, isCreator, isChannelMember: isMember })) {
+ // 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 isForum = channelRow.type === "forum";
+ const isMember = isCreator
+ ? false
+ : isForum
+ ? await isMemberOfAnyChildPost(db, channelRow.id, userId)
+ : await isChannelMember(db, rosterAnchorId, userId);
+ if (!canSeePrivateChannel({ isCreator, isChannelMember: isMember })) {
return null;
}
}
@@ -252,9 +286,7 @@ export async function listChannelsForMember(db: Database, serverId: string, user
)
.limit(1);
if (member.length === 0) return [];
- return listServerChannelsForViewer(db, serverId, userId, {
- isAdmin: canManageServer(member[0]!.role),
- });
+ return listServerChannelsForViewer(db, serverId, userId);
}
/**
@@ -511,6 +543,59 @@ 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,
@@ -553,13 +638,15 @@ export async function countChannelsInCategory(
/**
* The full recipient audience for a PRIVATE channel: explicit members ∪ the
- * anchor channel's creator ∪ every server admin/owner. Resolves the anchor
- * first (a thread — `parentChannelId` set — inherits its parent's audience).
- * Only meaningful for a private anchor; callers guard on `isChannelPrivate`
- * first (fan-out short-circuits public channels to `listMemberUserIds` and
- * never calls this). Called on a public/uncategorized anchor it would return
- * just admins + creator, NOT all members — do not use it as a public-channel
- * recipient resolver.
+ * 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).
+ *
+ * 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
+ * member. Admins have no implicit content access.
*/
export async function getPrivateChannelAudienceUserIds(
db: Database,
@@ -569,168 +656,221 @@ export async function getPrivateChannelAudienceUserIds(
.select({
id: communityChannel.id,
serverId: communityChannel.serverId,
+ type: communityChannel.type,
+ creatorId: communityChannel.creatorId,
parentChannelId: communityChannel.parentChannelId,
})
.from(communityChannel)
.where(eq(communityChannel.id, channelId))
.limit(1);
if (target.length === 0) return [];
- const anchorId = target[0]!.parentChannelId ?? target[0]!.id;
- const serverId = target[0]!.serverId;
+ const type = target[0]!.type;
- // Anchor row: creator + its category privacy.
- const anchor = await db
- .select({
- creatorId: communityChannel.creatorId,
- categoryPrivate: communityCategory.private,
- })
- .from(communityChannel)
- .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
- .where(eq(communityChannel.id, anchorId))
- .limit(1);
- if (anchor.length === 0) return [];
+ const set = new Set<string>();
- // Server admins/owner always belong to the audience.
- const admins = await db
- .select({ userId: communityServerMember.userId })
- .from(communityServerMember)
- .where(
- and(
- eq(communityServerMember.serverId, serverId),
- or(
- eq(communityServerMember.role, "owner"),
- eq(communityServerMember.role, "admin")
- )
- )
- );
- const members = await listChannelMemberUserIds(db, anchorId);
+ // 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 (type === "forum") {
+ // 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];
+ }
- const set = new Set<string>();
- for (const a of admins) set.add(a.userId);
- for (const m of members) set.add(m);
- if (anchor[0]!.creatorId) set.add(anchor[0]!.creatorId as string);
+ // post → roster on self; thread/channel → climb to the anchor.
+ const rosterAnchorId =
+ type === "forum_post" ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);
+ const rosterCreatorId =
+ type === "forum_post"
+ ? target[0]!.creatorId
+ : (await db
+ .select({ creatorId: communityChannel.creatorId })
+ .from(communityChannel)
+ .where(eq(communityChannel.id, rosterAnchorId))
+ .limit(1))[0]?.creatorId;
+
+ for (const m of await listChannelMemberUserIds(db, rosterAnchorId)) set.add(m);
+ if (rosterCreatorId) set.add(rosterCreatorId);
return [...set];
}
/**
* Top-level channels a viewer may SEE in a server (backs the server-detail
- * tree). Rule, all in SQL (no JS post-filter):
+ * tree). Nested-membership model:
* - admin/owner → every top-level channel.
- * - otherwise → all public/uncategorized channels, PLUS private-category
- * channels where the viewer is the creator OR has a member row.
- * `parentChannelId IS NULL` (threads excluded, mirroring `listServerChannels`).
+ * - 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).
+ * `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.
*/
export async function listServerChannelsForViewer(
db: Database,
serverId: string,
- userId: string,
- opts: { isAdmin: boolean }
+ userId: string
) {
const base = and(
eq(communityChannel.serverId, serverId),
isNull(communityChannel.parentChannelId)
);
- if (opts.isAdmin) {
- const rows = await db
+ // No admin fast-path: admins have NO special visibility into private content
+ // (they manage via admin-gated routes / the future Browse Channels surface).
+ // Everyone — admins included — sees public channels + the private ones they
+ // belong to.
+ const [rows, visibleSet] = await Promise.all([
+ db
.select(CHANNEL_COLUMNS)
.from(communityChannel)
.where(base)
- .orderBy(asc(communityChannel.position));
- return rows.map(mapChannelRow);
- }
+ .orderBy(asc(communityChannel.position)),
+ resolveVisibleChannelIdSet(db, userId, { serverIds: [serverId] }),
+ ]);
+ return rows.filter((r) => visibleSet.has(r.id)).map(mapChannelRow);
+}
+
+// Shared visibility computation for the nested-membership model. Assembles the
+// set of channel ids a viewer may see across the given servers, applying:
+// - top-level TEXT channel (private) → creator OR own member row.
+// - FORUM (private) → creator OR member of ANY child post (derived visibility;
+// forum membership is the union of its posts).
+// - THREAD → inherits parent channel visibility (WIDE — any channel member).
+// - FORUM_POST → if its forum is public, visible; if private, creator OR own
+// member row (NARROW — a private post is its own access unit).
+// NO admin fast-path: admins/owner have NO special visibility into private
+// content — they see exactly what a member sees (public ∪ private-they-belong-to).
+// Done in JS because the thread-wide / post-narrow / forum-derived split is too
+// branchy for one safe SQL predicate. Scoped by serverId up front (AGENTS.md).
+//
+// PERF (accepted trade-off): this reads all channel rows for the viewer's
+// servers into memory and filters in JS, rather than filtering private
+// visibility in SQL and returning only ids. Channel count per server is small
+// (tens–hundreds — orders of magnitude below message volume), so this is fine
+// in practice. If a server ever grows enough channels to matter, split into a
+// cheap SQL id-query for public/uncategorized channels + a JS pass only for
+// private units (forum-derived / post-narrow). Not done pre-emptively.
+async function resolveVisibleChannelIdSet(
+ db: Database,
+ userId: string,
+ opts: { serverIds: string[] }
+): Promise<Set<string>> {
+ const visible = new Set<string>();
+ const { serverIds } = opts;
+ if (serverIds.length === 0) return visible;
const rows = await db
- .select(CHANNEL_COLUMNS)
+ .select({
+ id: communityChannel.id,
+ type: communityChannel.type,
+ categoryId: communityChannel.categoryId,
+ categoryPrivate: communityCategory.private,
+ creatorId: communityChannel.creatorId,
+ parentChannelId: communityChannel.parentChannelId,
+ })
.from(communityChannel)
.leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
- .leftJoin(
- communityChannelMember,
- and(
- eq(communityChannelMember.channelId, communityChannel.id),
- eq(communityChannelMember.userId, userId)
- )
- )
+ .where(inArray(communityChannel.serverId, serverIds));
+
+ // The viewer's explicit channel/post member rows in these servers.
+ const memberRows = await db
+ .select({ channelId: communityChannelMember.channelId })
+ .from(communityChannelMember)
+ .innerJoin(communityChannel, eq(communityChannel.id, communityChannelMember.channelId))
.where(
and(
- base,
- or(
- // public / uncategorized
- isNull(communityChannel.categoryId),
- eq(communityCategory.private, 0),
- // private but visible to this viewer
- eq(communityChannel.creatorId, userId),
- isNotNull(communityChannelMember.id)
- )
+ eq(communityChannelMember.userId, userId),
+ inArray(communityChannel.serverId, serverIds)
)
- )
- .orderBy(asc(communityChannel.position));
- return rows.map(mapChannelRow);
+ );
+ 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 (r.type === "forum_post" && 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.
+ for (const r of rows) {
+ if (r.parentChannelId != null) continue;
+ if (!isPrivate(r) || r.creatorId === userId) {
+ visible.add(r.id);
+ continue;
+ }
+ if (r.type === "forum") {
+ 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)) {
+ visible.add(r.id);
+ }
+ }
+
+ // Pass 2 — children (threads inherit; forum posts are their own access unit).
+ for (const r of rows) {
+ if (r.parentChannelId == null) continue;
+ const parent = byId.get(r.parentChannelId);
+ if (!parent) continue;
+ if (r.type === "forum_post") {
+ // 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.
+ visible.add(r.id);
+ }
+ }
+
+ return visible;
}
/**
- * The set of channel ids (top-level AND child/thread channels) a viewer may
- * see — backs read-path scoping for search / inbox / mark-all-read / mentions.
- * A thread inherits its parent's visibility, so it's included iff its
- * `parentChannelId` is in the visible top-level set. Scoping is done entirely
- * in SQL (the second query is scoped by the first's id set via `inArray`) —
- * no fetch-all-then-filter-in-JS leak.
+ * 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.
*/
export async function listVisibleChannelIds(
db: Database,
serverId: string,
- userId: string,
- opts: { isAdmin: boolean }
+ userId: string
): Promise<string[]> {
- if (opts.isAdmin) {
- const rows = await db
- .select({ id: communityChannel.id })
- .from(communityChannel)
- .where(eq(communityChannel.serverId, serverId));
- return rows.map((r) => r.id);
- }
-
- // Visible TOP-LEVEL channels: public/uncategorized ∪ private-where-viewer-is
- // creator-or-member.
- const topLevel = await db
- .select({ id: communityChannel.id })
- .from(communityChannel)
- .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
- .leftJoin(
- communityChannelMember,
- and(
- eq(communityChannelMember.channelId, communityChannel.id),
- eq(communityChannelMember.userId, userId)
- )
- )
- .where(
- and(
- eq(communityChannel.serverId, serverId),
- isNull(communityChannel.parentChannelId),
- or(
- isNull(communityChannel.categoryId),
- eq(communityCategory.private, 0),
- eq(communityChannel.creatorId, userId),
- isNotNull(communityChannelMember.id)
- )
- )
- );
- const topLevelIds = topLevel.map((r) => r.id);
- if (topLevelIds.length === 0) return [];
-
- // Threads inherit from their parent: include children of visible top-level
- // channels (scoped by the id set — SQL, not JS). No `type` filter on the
- // children subquery, so forum_posts are covered alongside threads.
- const children = await db
- .select({ id: communityChannel.id })
- .from(communityChannel)
- .where(
- and(
- eq(communityChannel.serverId, serverId),
- inArray(communityChannel.parentChannelId, topLevelIds)
- )
- );
- return [...topLevelIds, ...children.map((r) => r.id)];
+ const set = await resolveVisibleChannelIdSet(db, userId, { serverIds: [serverId] });
+ return [...set];
}
/**
@@ -740,90 +880,29 @@ export async function listVisibleChannelIds(
* consumers (unread + mentions + mark-all), which span every server the viewer
* belongs to.
*
- * Same rule as the per-server form: admin/owner sees every channel in that
- * server; a non-admin sees public/uncategorized channels plus private-category
- * channels where they're the creator or have a member row. A child inherits its
- * parent's visibility (included iff its `parentChannelId` is in the visible
- * top-level set). Scoping is entirely in SQL.
+ * 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.
*
* Bound-parameter ceiling (accepted risk): a viewer across many large servers
* can produce a big id set; feeding it whole into a downstream `inArray`
* approaches SQLite's bound-param limit. Same unchunked pattern as
- * `searchMessagesInServer` (single-server there, larger here). Chunk only if it
- * proves a real limit in practice.
+ * `searchMessagesInServer`. Chunk only if it proves a real limit in practice.
*/
export async function listVisibleChannelIdsForUser(
db: Database,
userId: string
): Promise<string[]> {
const memberships = await db
- .select({
- serverId: communityServerMember.serverId,
- role: communityServerMember.role,
- })
+ .select({ serverId: communityServerMember.serverId })
.from(communityServerMember)
.where(eq(communityServerMember.userId, userId));
if (memberships.length === 0) return [];
- const adminServerIds: string[] = [];
- const memberServerIds: string[] = [];
- for (const m of memberships) {
- if (canManageServer(m.role)) adminServerIds.push(m.serverId);
- else memberServerIds.push(m.serverId);
- }
-
- const topLevelIds: string[] = [];
-
- // Admin servers: every top-level channel, no privacy filter.
- if (adminServerIds.length > 0) {
- const rows = await db
- .select({ id: communityChannel.id })
- .from(communityChannel)
- .where(
- and(
- inArray(communityChannel.serverId, adminServerIds),
- isNull(communityChannel.parentChannelId)
- )
- );
- for (const r of rows) topLevelIds.push(r.id);
- }
-
- // Member (non-admin) servers: public/uncategorized ∪ private-where-viewer-is
- // creator-or-member.
- if (memberServerIds.length > 0) {
- const rows = await db
- .select({ id: communityChannel.id })
- .from(communityChannel)
- .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
- .leftJoin(
- communityChannelMember,
- and(
- eq(communityChannelMember.channelId, communityChannel.id),
- eq(communityChannelMember.userId, userId)
- )
- )
- .where(
- and(
- inArray(communityChannel.serverId, memberServerIds),
- isNull(communityChannel.parentChannelId),
- or(
- isNull(communityChannel.categoryId),
- eq(communityCategory.private, 0),
- eq(communityChannel.creatorId, userId),
- isNotNull(communityChannelMember.id)
- )
- )
- );
- for (const r of rows) topLevelIds.push(r.id);
- }
-
- if (topLevelIds.length === 0) return [];
-
- const children = await db
- .select({ id: communityChannel.id })
- .from(communityChannel)
- .where(inArray(communityChannel.parentChannelId, topLevelIds));
- return [...topLevelIds, ...children.map((r) => r.id)];
+ const set = await resolveVisibleChannelIdSet(db, userId, {
+ serverIds: memberships.map((m) => m.serverId),
+ });
+ return [...set];
}
/**
@@ -873,6 +952,14 @@ 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 = channel.type === "forum_post";
+ const rosterAnchorId = isPost ? channel.id : anchorId;
+ const rosterCreatorId = isPost ? channel.creatorId : anchor.creatorId;
+
let categoryPrivate = 0;
if (anchor.categoryId) {
const cat = await db
@@ -883,9 +970,14 @@ 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 isForum = channel.type === "forum";
const memberFlag =
categoryPrivate === 1
- ? await isChannelMember(db, anchorId, userId)
+ ? isForum
+ ? await isMemberOfAnyChildPost(db, channel.id, userId)
+ : await isChannelMember(db, rosterAnchorId, userId)
: false;
return {
@@ -894,5 +986,8 @@ 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,
};
}
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index 96832de45..a3d0fc996 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -8,6 +8,7 @@ import {
} from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
+import { listParticipatingThreadIds } from "./thread";
export interface UnreadChannelRow {
channelId: string;
@@ -109,15 +110,27 @@ export async function listUnreadChannels(
)
);
- return rows
- .filter((r) =>
- isChannelUnread({
- archived: r.archived,
- lastMessageAt: r.lastMessageAt,
- lastReadAt: r.lastReadAt,
- joinedAt: r.joinedAt,
- })
- )
+ const unread = rows.filter((r) =>
+ isChannelUnread({
+ archived: r.archived,
+ lastMessageAt: r.lastMessageAt,
+ lastReadAt: r.lastReadAt,
+ joinedAt: r.joinedAt,
+ })
+ );
+
+ // Thread unreads are scoped to PARTICIPATION (notification dimension): a
+ // thread surfaces in the inbox only for its participants (muted=0), NOT for
+ // every parent-channel member who can merely read it. Posts and channels flow
+ // through the visibility path above unchanged. Only threads are re-filtered.
+ const threadIds = unread.filter((r) => r.type === "thread").map((r) => r.channelId);
+ const participatingThreadIds =
+ threadIds.length > 0
+ ? new Set(await listParticipatingThreadIds(db, threadIds, userId))
+ : new Set<string>();
+
+ return unread
+ .filter((r) => r.type !== "thread" || participatingThreadIds.has(r.channelId))
.map((r) => ({
channelId: r.channelId,
channelName: r.channelName,
diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.ts
index 5c8f8ea0d..9b21aae94 100644
--- a/src/shared/src/db/queries/community/member.ts
+++ b/src/shared/src/db/queries/community/member.ts
@@ -69,6 +69,41 @@ export async function listMembers(db: Database, serverId: string) {
.where(and(eq(communityServerMember.serverId, serverId), isNull(user.deletedAt)));
}
+export async function getMembersByUserIds(
+ db: Database,
+ serverId: string,
+ userIds: string[]
+) {
+ if (userIds.length === 0) return [];
+ return db
+ .select({
+ id: communityServerMember.id,
+ serverId: communityServerMember.serverId,
+ userId: communityServerMember.userId,
+ role: communityServerMember.role,
+ nickname: communityServerMember.nickname,
+ joinedAt: communityServerMember.joinedAt,
+ userName: user.name,
+ userEmail: user.email,
+ userImage: user.image,
+ userIsBot: user.isBot,
+ userOwnerUserId: user.ownerUserId,
+ discriminator: user.discriminator,
+ statusEmoji: communityUserProfile.statusEmoji,
+ statusText: communityUserProfile.statusText,
+ })
+ .from(communityServerMember)
+ .innerJoin(user, eq(communityServerMember.userId, user.id))
+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id))
+ .where(
+ and(
+ eq(communityServerMember.serverId, serverId),
+ inArray(communityServerMember.userId, userIds),
+ isNull(user.deletedAt)
+ )
+ );
+}
+
export async function updateRailOrder(
db: Database,
serverId: string,
@@ -412,7 +447,8 @@ export async function canBotReadWakeScope(
if (!ctx.isPrivate) return true;
return canSeePrivateChannel({
role: ctx.role,
- isCreator: ctx.anchor.creatorId === botUserId,
+ // Roster-anchor creator (post's own creator for a post), from the context.
+ isCreator: ctx.isCreator,
isChannelMember: ctx.isChannelMember,
});
}
diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.ts
index 5c48ee059..971c218f3 100644
--- a/src/shared/src/db/queries/community/members-resolver.ts
+++ b/src/shared/src/db/queries/community/members-resolver.ts
@@ -1,7 +1,6 @@
import { eq } from "drizzle-orm";
import {
communityChannel,
- communityCategory,
communityServerMember,
} from "../../community-schema";
import type { Database } from "../../index";
@@ -80,6 +79,8 @@ export async function resolveScopeMembers(
.select({
id: communityChannel.id,
serverId: communityChannel.serverId,
+ type: communityChannel.type,
+ creatorId: communityChannel.creatorId,
parentChannelId: communityChannel.parentChannelId,
})
.from(communityChannel)
@@ -87,7 +88,7 @@ export async function resolveScopeMembers(
.limit(1);
if (target.length === 0) return [];
const serverId = target[0]!.serverId;
- const anchorId = target[0]!.parentChannelId ?? target[0]!.id;
+ const type = target[0]!.type;
// Server roles for every resolved user — scoped to this server up front.
const roleRows = await db
@@ -99,19 +100,41 @@ export async function resolveScopeMembers(
const isPrivate = await isChannelPrivate(db, scopeId);
- // For a private anchor, "explicit" = the added channel members ∪ the anchor
- // creator. Everyone else in the set is an admin/owner.
+ // "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.
const explicit = new Set<string>();
if (isPrivate) {
- for (const id of await listChannelMemberUserIds(db, anchorId)) explicit.add(id);
- const anchor = await db
- .select({ creatorId: communityChannel.creatorId })
- .from(communityChannel)
- .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))
- .where(eq(communityChannel.id, anchorId))
- .limit(1);
- const creatorId = anchor[0]?.creatorId;
- if (creatorId) explicit.add(creatorId);
+ if (type === "forum") {
+ 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 =
+ type === "forum_post" ? target[0]!.id : (target[0]!.parentChannelId ?? target[0]!.id);
+ for (const id of await listChannelMemberUserIds(db, rosterAnchorId)) explicit.add(id);
+ const rosterCreatorId =
+ type === "forum_post"
+ ? 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);
+ }
}
return userIds.map((userId) => {
diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.ts
new file mode 100644
index 000000000..2600efabe
--- /dev/null
+++ b/src/shared/src/db/queries/community/thread.ts
@@ -0,0 +1,143 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { communityThreadParticipant } from "../../community-schema";
+import { user } from "../../schema";
+import type { Database } from "../../index";
+
+// The NOTIFICATION set for a thread (see `community_thread_participant`). A
+// thread is not an access unit — any parent-channel member can read it — so
+// these rows only decide who gets pinged / sees the thread as unread. Admins
+// are NOT auto-included: the notify set is exactly these rows.
+//
+// There is no per-participant mute here — muting a thread is the OUTER channel-
+// header notification level (per-layer, same control a channel uses), not a
+// property of participation. Participation is add / leave only.
+
+export type ThreadParticipantSource = "mention" | "spoke" | "added";
+
+// Idempotent add. `onConflictDoNothing` so a re-mention/re-speak of an existing
+// participant is a no-op (does NOT overwrite `source`).
+// Returns the inserted row, or null when the participant already existed.
+export async function addThreadParticipant(
+ db: Database,
+ data: { threadChannelId: string; userId: string; source: ThreadParticipantSource }
+) {
+ const rows = await db
+ .insert(communityThreadParticipant)
+ .values({
+ threadChannelId: data.threadChannelId,
+ userId: data.userId,
+ source: data.source,
+ })
+ .onConflictDoNothing({
+ target: [communityThreadParticipant.threadChannelId, communityThreadParticipant.userId],
+ })
+ .returning();
+ return rows[0] ?? null;
+}
+
+// Bulk idempotent add — one INSERT for many (userId, source) pairs. Used on the
+// message-send hot path where a post can add the author + N mentioned users at
+// once. Skips the query for an empty list. Does not overwrite existing rows.
+export async function addThreadParticipants(
+ db: Database,
+ threadChannelId: string,
+ rows: { userId: string; source: ThreadParticipantSource }[]
+) {
+ if (rows.length === 0) return;
+ await db
+ .insert(communityThreadParticipant)
+ .values(rows.map((r) => ({ threadChannelId, userId: r.userId, source: r.source })))
+ .onConflictDoNothing({
+ target: [communityThreadParticipant.threadChannelId, communityThreadParticipant.userId],
+ });
+}
+
+// The NOTIFY set: every participant userId. This is what thread fan-out /
+// mention rows / inbox unread scope to. (Per-user notification suppression is
+// the outer channel-header notif level, not stored here.)
+export async function listThreadParticipantUserIds(
+ db: Database,
+ threadChannelId: string
+): Promise<string[]> {
+ const rows = await db
+ .select({ userId: communityThreadParticipant.userId })
+ .from(communityThreadParticipant)
+ .where(eq(communityThreadParticipant.threadChannelId, threadChannelId));
+ return rows.map((r) => r.userId);
+}
+
+// Full participant list hydrated for display — the thread's participant panel.
+export async function listThreadParticipants(
+ db: Database,
+ threadChannelId: string
+) {
+ return db
+ .select({
+ userId: communityThreadParticipant.userId,
+ source: communityThreadParticipant.source,
+ addedAt: communityThreadParticipant.addedAt,
+ userName: user.name,
+ userImage: user.image,
+ discriminator: user.discriminator,
+ })
+ .from(communityThreadParticipant)
+ .innerJoin(user, eq(user.id, communityThreadParticipant.userId))
+ .where(eq(communityThreadParticipant.threadChannelId, threadChannelId));
+}
+
+export async function isThreadParticipant(
+ db: Database,
+ threadChannelId: string,
+ userId: string
+): Promise<boolean> {
+ const rows = await db
+ .select({ id: communityThreadParticipant.id })
+ .from(communityThreadParticipant)
+ .where(
+ and(
+ eq(communityThreadParticipant.threadChannelId, threadChannelId),
+ eq(communityThreadParticipant.userId, userId)
+ )
+ )
+ .limit(1);
+ return rows.length > 0;
+}
+
+// Leave: drop the row entirely (a later mention/speak re-adds). Returns the
+// removed row or null.
+export async function removeThreadParticipant(
+ db: Database,
+ threadChannelId: string,
+ userId: string
+) {
+ const rows = await db
+ .delete(communityThreadParticipant)
+ .where(
+ and(
+ eq(communityThreadParticipant.threadChannelId, threadChannelId),
+ eq(communityThreadParticipant.userId, userId)
+ )
+ )
+ .returning();
+ return rows[0] ?? null;
+}
+
+// Of the given thread ids, which the user participates in. Batch form for the
+// inbox unread-threads filter.
+export async function listParticipatingThreadIds(
+ db: Database,
+ threadChannelIds: string[],
+ userId: string
+): Promise<string[]> {
+ if (threadChannelIds.length === 0) return [];
+ const rows = await db
+ .select({ threadChannelId: communityThreadParticipant.threadChannelId })
+ .from(communityThreadParticipant)
+ .where(
+ and(
+ inArray(communityThreadParticipant.threadChannelId, threadChannelIds),
+ eq(communityThreadParticipant.userId, userId)
+ )
+ );
+ return rows.map((r) => r.threadChannelId);
+}
diff --git a/src/shared/src/utils/community-roles.ts b/src/shared/src/utils/community-roles.ts
index 81f41a127..36350b56c 100644
--- a/src/shared/src/utils/community-roles.ts
+++ b/src/shared/src/utils/community-roles.ts
@@ -24,16 +24,23 @@ export function isServerOwner(role?: string | null): boolean {
* The single private-channel visibility rule, shared by both access predicates
* (`getChannelForMember` — read/post path — and `requireChannelAccess` /
* `resolveChannelAccessContext` — manage path) plus `canBotReadWakeScope`, so
- * the rule can never drift between them. A server admin/owner, the anchor's
- * creator, or an explicit channel member may see a private channel. Callers
- * only invoke this once they know the anchor is private. Pure.
+ * the rule can never drift between them. Only the unit's creator or an explicit
+ * member may see a private channel/post. Callers only invoke this once they
+ * know the anchor is private. Pure.
+ *
+ * NOTE: a server admin/owner has NO special CONTENT access to private units —
+ * they see/read/post a private channel only if they created it or were added,
+ * exactly like a normal member. Admins manage servers via admin-gated routes
+ * (and the future Browse Channels settings surface), not by implicitly seeing
+ * every private conversation. `role` is retained in the signature for callers
+ * that still pass it, but it no longer grants visibility.
*/
export function canSeePrivateChannel(input: {
- role: string | null | undefined
+ role?: string | null | undefined
isCreator: boolean
isChannelMember: boolean
}): boolean {
- return canManageServer(input.role) || input.isCreator || input.isChannelMember
+ return input.isCreator || input.isChannelMember
}
export function isAssignableRole(role: unknown): role is AssignableRole {
diff --git a/src/shared/test/queries/community-channel-access.test.ts b/src/shared/test/queries/community-channel-access.test.ts
index 64d2ed5c2..0e46cfa07 100644
--- a/src/shared/test/queries/community-channel-access.test.ts
+++ b/src/shared/test/queries/community-channel-access.test.ts
@@ -52,9 +52,13 @@ function makeSeqDb(queue: any[][]) {
}
describe("canSeePrivateChannel — shared rule", () => {
- it("admin/owner sees it regardless of membership", () => {
- expect(canSeePrivateChannel({ role: "admin", isCreator: false, isChannelMember: false })).toBe(true)
- expect(canSeePrivateChannel({ role: "owner", isCreator: false, isChannelMember: false })).toBe(true)
+ it("admin/owner does NOT see it without membership (no content privilege)", () => {
+ expect(canSeePrivateChannel({ role: "admin", isCreator: false, isChannelMember: false })).toBe(false)
+ expect(canSeePrivateChannel({ role: "owner", isCreator: false, isChannelMember: false })).toBe(false)
+ })
+ it("admin who is also a member/creator sees it (via those, not role)", () => {
+ expect(canSeePrivateChannel({ role: "admin", isCreator: false, isChannelMember: true })).toBe(true)
+ expect(canSeePrivateChannel({ role: "admin", isCreator: true, isChannelMember: false })).toBe(true)
})
it("creator sees it", () => {
expect(canSeePrivateChannel({ role: "member", isCreator: true, isChannelMember: false })).toBe(true)
@@ -91,10 +95,20 @@ describe("getChannelForMember — private visibility", () => {
expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();
});
- it("private channel + admin → returns the channel without a member row", async () => {
+ it("private channel + admin, NOT a member/creator → null (no content privilege)", async () => {
const db = makeSeqDb([
[{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],
[{ creatorId: "creator", categoryPrivate: 1 }],
+ [], // isChannelMember → no row; admin role no longer short-circuits
+ ]);
+ expect(await channelQueries.getChannelForMember(db, "c1", "u1")).toBeNull();
+ });
+
+ it("private channel + admin who IS an added member → returns the channel", async () => {
+ const db = makeSeqDb([
+ [{ ...channelRow({ categoryId: "cat1" }), memberRole: "admin" }],
+ [{ creatorId: "creator", categoryPrivate: 1 }],
+ [{ id: "cm1" }], // isChannelMember → row present
]);
const res = await channelQueries.getChannelForMember(db, "c1", "u1");
expect(res?.id).toBe("c1");
diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.ts
index 479c5e4c2..a62cf58ff 100644
--- a/src/shared/test/queries/community-inbox.test.ts
+++ b/src/shared/test/queries/community-inbox.test.ts
@@ -242,6 +242,51 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_old"]);
expect(result).toEqual([]);
});
+
+ // Thread unreads are scoped to PARTICIPATION. The function issues a SECOND
+ // query (listParticipatingThreadIds) when the unread set contains threads.
+ // This mock returns the unread rows on the first `.where()` and the
+ // participating-thread ids on the second.
+ function createTwoQueryMock(unreadRows: any[], participatingThreadIds: string[]) {
+ let call = 0;
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
+ chain.leftJoin = vi.fn(() => chain);
+ chain.where = vi.fn(() => {
+ call += 1;
+ return Promise.resolve(
+ call === 1 ? unreadRows : participatingThreadIds.map((id) => ({ threadChannelId: id }))
+ );
+ });
+ return chain;
+ }
+
+ const unreadThreadRow = (channelId: string) => ({
+ channelId,
+ channelName: "a thread",
+ serverId: "srv_1",
+ serverName: "server 1",
+ type: "thread",
+ parentChannelId: "ch_parent",
+ lastMessageAt: "2026-07-06T00:00:05.000Z",
+ lastReadAt: "2026-07-06T00:00:00.000Z",
+ archived: false,
+ joinedAt: j,
+ });
+
+ it("thread the viewer participates in surfaces as unread", async () => {
+ const db = createTwoQueryMock([unreadThreadRow("t_in")], ["t_in"]);
+ const result = await inboxQueries.listUnreadChannels(db, "u_1", ["t_in"]);
+ expect(result.map((r) => r.channelId)).toEqual(["t_in"]);
+ });
+
+ it("thread the viewer does NOT participate in is filtered out (even if unread)", async () => {
+ const db = createTwoQueryMock([unreadThreadRow("t_out")], []);
+ const result = await inboxQueries.listUnreadChannels(db, "u_1", ["t_out"]);
+ expect(result).toEqual([]);
+ });
});
describe("isDmUnread — predicate", () => {
diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.ts
index a1e8cb236..55f4ca972 100644
--- a/src/shared/test/queries/community-member.test.ts
+++ b/src/shared/test/queries/community-member.test.ts
@@ -284,6 +284,41 @@ describe("searchMembers", () => {
});
});
+describe("getMembersByUserIds", () => {
+ // `.leftJoin().where()` is terminal here (no orderBy/limit).
+ function createMock(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
+ chain.leftJoin = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ return chain;
+ }
+
+ it("exports getMembersByUserIds", () => {
+ expect(typeof memberQueries.getMembersByUserIds).toBe("function");
+ });
+
+ it("returns [] without querying when the id list is empty", async () => {
+ const db = createMock([{ id: "should_not_be_used" }]);
+ const res = await memberQueries.getMembersByUserIds(db, "srv_1", []);
+ expect(res).toEqual([]);
+ expect(db.select).not.toHaveBeenCalled();
+ });
+
+ it("returns hydrated rows (incl. status columns) for the given ids", async () => {
+ const rows = [
+ { id: "m1", userId: "u_1", userName: "Ann", statusEmoji: "🎧", statusText: "Vibing", userIsBot: false, userOwnerUserId: null },
+ { id: "m2", userId: "u_2", userName: "Bob", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },
+ ];
+ const db = createMock(rows);
+ const res = await memberQueries.getMembersByUserIds(db, "srv_1", ["u_1", "u_2"]);
+ expect(res.map((r) => r.userId)).toEqual(["u_1", "u_2"]);
+ expect(res[0]).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" });
+ });
+});
+
describe("getMemberById", () => {
function createMock(rows: any[]) {
const chain: any = {};
diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.ts
new file mode 100644
index 000000000..75e52b76f
--- /dev/null
+++ b/src/shared/test/queries/community-thread.test.ts
@@ -0,0 +1,104 @@
+import { describe, it, expect, vi } from "vitest";
+import * as threadQueries from "../../src/db/queries/community/thread";
+
+describe("community/thread exports", () => {
+ it("exports the participant CRUD", () => {
+ expect(typeof threadQueries.addThreadParticipant).toBe("function");
+ expect(typeof threadQueries.listThreadParticipantUserIds).toBe("function");
+ expect(typeof threadQueries.listThreadParticipants).toBe("function");
+ expect(typeof threadQueries.removeThreadParticipant).toBe("function");
+ expect(typeof threadQueries.listParticipatingThreadIds).toBe("function");
+ });
+});
+
+describe("addThreadParticipant", () => {
+ function insertMock(returned: any[]) {
+ const chain: any = {};
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.onConflictDoNothing = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(returned));
+ return chain;
+ }
+
+ it("returns the inserted row for a new participant", async () => {
+ const db = insertMock([{ id: "tp1", threadChannelId: "t1", userId: "u1" }]);
+ const res = await threadQueries.addThreadParticipant(db, {
+ threadChannelId: "t1",
+ userId: "u1",
+ source: "spoke",
+ });
+ expect(res).toMatchObject({ id: "tp1" });
+ });
+
+ it("returns null on conflict (already a participant)", async () => {
+ const db = insertMock([]);
+ const res = await threadQueries.addThreadParticipant(db, {
+ threadChannelId: "t1",
+ userId: "u1",
+ source: "mention",
+ });
+ expect(res).toBeNull();
+ });
+});
+
+describe("addThreadParticipants — bulk", () => {
+ it("skips the query entirely for an empty rows list", async () => {
+ const chain: any = { insert: vi.fn() };
+ await threadQueries.addThreadParticipants(chain, "t1", []);
+ expect(chain.insert).not.toHaveBeenCalled();
+ });
+
+ it("inserts one row per (userId, source) pair with onConflictDoNothing", async () => {
+ const values = vi.fn(() => ({ onConflictDoNothing: vi.fn(() => Promise.resolve()) }));
+ const chain: any = { insert: vi.fn(() => ({ values })) };
+ await threadQueries.addThreadParticipants(chain, "t1", [
+ { userId: "u1", source: "spoke" },
+ { userId: "u2", source: "mention" },
+ ]);
+ expect(chain.insert).toHaveBeenCalledTimes(1); // single bulk insert, not N
+ expect(values).toHaveBeenCalledWith([
+ { threadChannelId: "t1", userId: "u1", source: "spoke" },
+ { threadChannelId: "t1", userId: "u2", source: "mention" },
+ ]);
+ });
+});
+
+describe("listThreadParticipantUserIds — notify set", () => {
+ function whereMock(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ return chain;
+ }
+
+ it("returns every participant's userId", async () => {
+ const db = whereMock([{ userId: "u1" }, { userId: "u2" }]);
+ const res = await threadQueries.listThreadParticipantUserIds(db, "t1");
+ expect(res).toEqual(["u1", "u2"]);
+ });
+});
+
+describe("listParticipatingThreadIds", () => {
+ function whereMock(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ return chain;
+ }
+
+ it("returns [] without querying for an empty id list", async () => {
+ const db = whereMock([{ threadChannelId: "should_not_be_used" }]);
+ const res = await threadQueries.listParticipatingThreadIds(db, [], "u1");
+ expect(res).toEqual([]);
+ expect(db.select).not.toHaveBeenCalled();
+ });
+
+ it("returns the participating thread ids", async () => {
+ const db = whereMock([{ threadChannelId: "t1" }, { threadChannelId: "t3" }]);
+ const res = await threadQueries.listParticipatingThreadIds(db, ["t1", "t2", "t3"], "u1");
+ expect(res).toEqual(["t1", "t3"]);
+ });
+});
diff --git a/src/web/migrations/0058_community_thread_participant.sql b/src/web/migrations/0058_community_thread_participant.sql
new file mode 100644
index 000000000..cbf5104de
--- /dev/null
+++ b/src/web/migrations/0058_community_thread_participant.sql
@@ -0,0 +1,23 @@
+-- Thread participant / notification set.
+-- See plans/nested-membership-model.md (Phase C).
+--
+-- A thread (community_channel row of type "thread") is the NOTIFICATION
+-- dimension, not access: any member of its parent channel can READ it. This
+-- table records who gets NOTIFIED (mention pings + inbox unread) for new thread
+-- activity. `source` = how they joined (mention | spoke | added). Admins are
+-- NOT auto-added. Muting a thread is the outer channel-header notification
+-- level (per-layer), NOT a column here — participation is add/leave only.
+
+CREATE TABLE community_thread_participant (
+ id TEXT PRIMARY KEY,
+ thread_channel_id TEXT NOT NULL REFERENCES community_channel(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ source TEXT NOT NULL DEFAULT 'mention',
+ added_at TEXT NOT NULL
+);
+
+-- One participant row per (thread, user).
+CREATE UNIQUE INDEX uq_thread_participant ON community_thread_participant(thread_channel_id, user_id);
+
+-- Reverse lookup: which threads a user participates in (inbox unread scoping).
+CREATE INDEX idx_thread_participant_user ON community_thread_participant(user_id);
diff --git a/src/web/migrations/0059_backfill_post_rosters.sql b/src/web/migrations/0059_backfill_post_rosters.sql
new file mode 100644
index 000000000..65bb0aaff
--- /dev/null
+++ b/src/web/migrations/0059_backfill_post_rosters.sql
@@ -0,0 +1,30 @@
+-- Backfill: give existing forum POSTS their own member roster.
+-- See plans/nested-membership-model.md (Phase D).
+--
+-- Before the nested-membership model, a forum_post inherited its forum's
+-- audience. Now a post owns its roster. Without this backfill, existing posts
+-- under a private forum would have an empty roster → their members lose access
+-- on deploy. Copy the FORUM's explicit community_channel_member rows onto each
+-- child post.
+--
+-- IMPORTANT: copy only the forum's EXPLICIT member rows — NOT the resolved
+-- audience (which would include server admins/creator). Admins/creator are
+-- re-derived at query time; storing them as explicit post rows would make them
+-- removable and mis-sourced.
+--
+-- Idempotent: INSERT OR IGNORE against the uq_channel_member unique index, so
+-- re-running (or a post that already has some rows) is a no-op for existing
+-- pairs. `hex(randomblob(16))` generates a fresh row id per copied membership.
+
+INSERT OR IGNORE INTO community_channel_member (id, channel_id, user_id, added_by, added_at)
+SELECT
+ lower(hex(randomblob(16))),
+ post.id,
+ fm.user_id,
+ fm.added_by,
+ fm.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 fm ON fm.channel_id = forum.id
+WHERE post.type = 'forum_post';
diff --git a/src/web/migrations/0060_backfill_thread_participants.sql b/src/web/migrations/0060_backfill_thread_participants.sql
new file mode 100644
index 000000000..ab7c558ac
--- /dev/null
+++ b/src/web/migrations/0060_backfill_thread_participants.sql
@@ -0,0 +1,49 @@
+-- Backfill: seed participant rows for existing THREADS.
+-- See plans/nested-membership-model.md (Phase D).
+--
+-- Before the nested-membership model, every parent-channel member was notified
+-- of thread activity. Now only participants are. Without this backfill, ongoing
+-- threads would notify nobody on deploy. Seed each thread's participant set
+-- from the people who demonstrably engaged with it:
+-- - distinct authors of messages IN the thread (they "spoke"),
+-- - the thread's creator,
+-- - the author of the message the thread was started from (parent message).
+--
+-- All tagged source='spoke' (the closest existing signal; the distinction only
+-- matters for future joins, not for who-gets-notified). Idempotent via
+-- INSERT OR IGNORE on uq_thread_participant. `hex(randomblob(16))` = row id.
+
+-- 1. Message authors in the thread.
+INSERT OR IGNORE INTO community_thread_participant (id, thread_channel_id, user_id, source, added_at)
+SELECT DISTINCT
+ lower(hex(randomblob(16))),
+ t.id,
+ m.author_id,
+ 'spoke',
+ t.created_at
+FROM community_channel AS t
+JOIN community_message AS m ON m.channel_id = t.id
+WHERE t.type = 'thread';
+
+-- 2. Thread creator (may not have posted in it).
+INSERT OR IGNORE INTO community_thread_participant (id, thread_channel_id, user_id, source, added_at)
+SELECT
+ lower(hex(randomblob(16))),
+ t.id,
+ t.creator_id,
+ 'spoke',
+ t.created_at
+FROM community_channel AS t
+WHERE t.type = 'thread' AND t.creator_id IS NOT NULL;
+
+-- 3. Author of the parent message the thread hangs off.
+INSERT OR IGNORE INTO community_thread_participant (id, thread_channel_id, user_id, source, added_at)
+SELECT
+ lower(hex(randomblob(16))),
+ t.id,
+ pm.author_id,
+ 'spoke',
+ t.created_at
+FROM community_channel AS t
+JOIN community_message AS pm ON pm.id = t.parent_message_id
+WHERE t.type = 'thread' AND t.parent_message_id IS NOT NULL;
diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.ts
new file mode 100644
index 000000000..cc6827cfd
--- /dev/null
+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+const mockGetBotOwnedBy = vi.fn()
+const mockUpdateBot = vi.fn()
+const mockGetUserPublic = vi.fn()
+const mockPushBotEventToMachine = vi.fn()
+const mockLogAudit = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityBot: {
+ getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
+ updateBot: (...a: unknown[]) => mockUpdateBot(...a),
+ },
+ user: {
+ getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/bot-push", () => ({
+ pushBotEventToMachine: (...a: unknown[]) => mockPushBotEventToMachine(...a),
+}))
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: vi.fn(),
+}))
+vi.mock("@/lib/community/audit", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
+ return { ...actual, logAudit: (...a: unknown[]) => mockLogAudit(...a) }
+})
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ },
+}))
+
+vi.mock("@/lib/middleware/helpers", async () => {
+ const { NextResponse } = require("next/server")
+ const actual = await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")
+ return {
+ ...actual,
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { PATCH } from "./route"
+
+function patchReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/bots/b1", {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ })
+}
+const ctx = { params: { id: "b1" } } as any
+
+describe("PATCH /api/community/bots/[id]", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetBotOwnedBy.mockResolvedValue({
+ id: "b1", name: "Old", description: "old desc", machineId: "mac1", ownerUserId: "u1",
+ })
+ mockUpdateBot.mockResolvedValue({
+ id: "b1", name: "New", discriminator: "0001", description: "new desc", image: null,
+ })
+ mockGetUserPublic.mockResolvedValue({ id: "u1", name: "Owner", discriminator: "9999" })
+ })
+
+ it("updates and pushes bot:updated to the daemon when the name changed", async () => {
+ const res = await PATCH(patchReq({ name: "New" }), ctx)
+ expect(res.status).toBe(200)
+ expect(mockUpdateBot).toHaveBeenCalled()
+ expect(mockPushBotEventToMachine).toHaveBeenCalledWith(
+ expect.anything(),
+ "mac1",
+ expect.objectContaining({ type: "bot:updated", name: "New", ownerName: "Owner" }),
+ )
+ })
+
+ it("resolves the owner BEFORE mutating: an unresolvable owner fails 500 without writing", async () => {
+ mockGetUserPublic.mockResolvedValue(null)
+ const res = await PATCH(patchReq({ name: "New" }), ctx)
+ expect(res.status).toBe(500)
+ // The row must NOT have been mutated — otherwise a retry sees no diff and
+ // never pushes, leaving the daemon prompt permanently stale.
+ expect(mockUpdateBot).not.toHaveBeenCalled()
+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()
+ })
+
+ it("image-only change does not resolve the owner or push (display-only)", async () => {
+ mockUpdateBot.mockResolvedValue({ id: "b1", name: "Old", discriminator: "0001", description: "old desc", image: "avatar:sunset" })
+ const res = await PATCH(patchReq({ image: "avatar:sunset" }), ctx)
+ expect(res.status).toBe(200)
+ expect(mockGetUserPublic).not.toHaveBeenCalled()
+ expect(mockPushBotEventToMachine).not.toHaveBeenCalled()
+ expect(mockUpdateBot).toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index bcd0832d7..6282f1740 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -25,6 +25,22 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const before = await queries.communityBot.getBotOwnedBy(db, id, ctx.userId)
if (!before) return writeError("bot not found", 404)
+ const nameChanged = body.name !== undefined && body.name !== before.name
+ const descriptionChanged =
+ body.description !== undefined && body.description !== before.description
+ // Will we push bot:updated to the daemon? (Iff name/description changed —
+ // image-only is display-only and doesn't affect the system prompt.) If so,
+ // resolve the owner handle BEFORE mutating the row: the frame shape must stay
+ // consistent with bot:added, and if the owner can't be resolved (soft-delete,
+ // integrity bug) we must fail WITHOUT having already written — otherwise a
+ // retry sees `before === updated`, computes no change, and never pushes,
+ // leaving the daemon's running system prompt permanently stale.
+ const willPush = (nameChanged || descriptionChanged) && !!before.machineId
+ const owner = willPush ? await queries.user.getUserPublic(db, before.ownerUserId) : null
+ if (willPush && !owner) {
+ return writeError("bot owner not resolvable — refusing to push a bot update with unknown ownership", 500)
+ }
+
const updated = await queries.communityBot.updateBot(db, id, ctx.userId, {
name: body.name,
description: body.description,
@@ -32,21 +48,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
})
if (!updated) return writeError("bot not found", 404)
- const nameChanged = body.name !== undefined && body.name !== before.name
- const descriptionChanged =
- body.description !== undefined && body.description !== before.description
- // Emit bot:updated to the daemon iff name or description changed. Image-only
- // is display-only and does not affect the daemon's system-prompt assembly.
- if ((nameChanged || descriptionChanged) && before.machineId) {
- // Ownership is immutable post-creation, but bot:updated's frame shape
- // must stay consistent with bot:added — resolve the (unchanged) owner
- // handle fresh rather than adding a second frame type. If the owner
- // row can't be resolved (soft-delete, integrity bug), fail the PATCH
- // rather than push empty owner fields — the daemon's truthy gate would
- // otherwise silently drop the "owned by" privacy paragraph from the
- // running system prompt on next spawn.
- const owner = await queries.user.getUserPublic(db, before.ownerUserId)
- if (!owner) return writeError("bot owner not resolvable — refusing to push a bot update with unknown ownership", 500)
+ if (willPush && owner && before.machineId) {
await pushBotEventToMachine(ctx.env, before.machineId, {
type: "bot:updated",
botId: id,
diff --git a/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts b/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts
index 1c1717ea7..b6f5090f5 100644
--- a/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/addable-members/route.test.ts
@@ -49,11 +49,12 @@ function req() {
function managerCtx() {
return {
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
+ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "u1" },
anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
role: "member",
isPrivate: true,
isChannelMember: true,
+ isCreator: true,
}
}
@@ -77,15 +78,22 @@ describe("GET /channels/[id]/addable-members", () => {
expect(ids).toEqual(["u3"]) // u1 = creator, u2 = already member
})
- it("rejects a non-manager (403)", async () => {
+ it("allows a plain member (not just creator) to load the picker", async () => {
mockResolveChannelAccessContext.mockResolvedValue({
...managerCtx(),
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" },
+ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "other" },
anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" },
role: "member",
isChannelMember: true,
+ isCreator: false,
})
const res = await GET(req(), ctx)
+ expect(res.status).toBe(200)
+ })
+
+ it("rejects a non-member outsider (403 from the access gate)", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(null)
+ const res = await GET(req(), ctx)
expect(res.status).toBe(403)
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/addable-members/route.ts b/src/web/src/app/api/community/channels/[id]/addable-members/route.ts
index 2166ac3c8..054e11c02 100644
--- a/src/web/src/app/api/community/channels/[id]/addable-members/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/addable-members/route.ts
@@ -17,9 +17,10 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
if (!channelId) return writeError("missing channel id", 400)
const db = getDb(ctx.env.DB)
+ // Any current member may add, so the add-picker is available to anyone who
+ // passes the access gate (creator or member; admins have no implicit access).
const access = await requireChannelAccess(db, channelId, ctx.userId)
if (!access.ok) return writeError(access.error, access.status)
- if (!access.value.canManage) return writeError("forbidden", 403)
const channel = access.value.channel
const [members, channelMemberIds] = await Promise.all([
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.test.ts
index 4f80302b0..d93e81b32 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
@@ -59,11 +59,13 @@ const ctx = { params: { id: "c1", userId: "u2" } } as any
function managerCtx(creatorId = "u1") {
return {
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId },
+ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId },
anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId },
role: "member",
isPrivate: true,
isChannelMember: true,
+ // Caller in these tests is "u1"; creator gate is roster-anchor creator.
+ isCreator: creatorId === "u1",
}
}
@@ -91,7 +93,7 @@ describe("DELETE /channels/[id]/members/[userId]", () => {
expect(mockDeleteChannelMember).not.toHaveBeenCalled()
})
- it("rejects a non-manager (403)", async () => {
+ it("rejects a non-creator removing someone else (403)", async () => {
mockResolveChannelAccessContext.mockResolvedValue({
...managerCtx("other"),
isChannelMember: true,
@@ -100,4 +102,30 @@ describe("DELETE /channels/[id]/members/[userId]", () => {
const res = await DELETE(req(), ctx)
expect(res.status).toBe(403)
})
+
+ it("self-leave: a non-creator member may remove themselves (204)", async () => {
+ // Caller u1 (not the creator), removing their OWN row u1.
+ mockResolveChannelAccessContext.mockResolvedValue({
+ ...managerCtx("other"), // creator is someone else → isCreator false
+ isChannelMember: true,
+ role: "member",
+ })
+ const res = await DELETE(
+ new NextRequest("http://localhost/api/community/channels/c1/members/u1", { method: "DELETE" }),
+ { params: { id: "c1", userId: "u1" } } as any,
+ )
+ expect(res.status).toBe(204)
+ expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "c1", "u1")
+ })
+
+ it("creator cannot self-leave their own channel (400)", async () => {
+ // Caller u1 is the creator; trying to leave own channel.
+ mockResolveChannelAccessContext.mockResolvedValue(managerCtx("u1"))
+ const res = await DELETE(
+ new NextRequest("http://localhost/api/community/channels/c1/members/u1", { method: "DELETE" }),
+ { params: { id: "c1", userId: "u1" } } as any,
+ )
+ expect(res.status).toBe(400)
+ expect(mockDeleteChannelMember).not.toHaveBeenCalled()
+ })
})
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.ts
index b0e5908ef..3adbb0903 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
@@ -8,10 +8,13 @@ import { logAudit } from "@/lib/community/audit"
import { requireChannelAccess } from "@/lib/community/permissions"
/**
- * Remove a member from a private-category channel. Only creator/admins
- * (canManage) may remove, and the channel creator can never be removed (they
- * always retain access). The removed user gets a CHANNEL_MEMBER_REMOVE so
- * their sidebar drops the channel + evicts its caches.
+ * Remove a member from a private access unit (channel or forum post).
+ * - Self-leave: any member may remove THEMSELVES (drop their own access).
+ * - Remove others: CREATOR only (add is open to members, but evicting someone
+ * else is the creator's call; admins have no content privilege here).
+ * - The creator can never be removed OR self-leave (they own the unit).
+ * The removed user gets a CHANNEL_MEMBER_REMOVE so their sidebar drops the
+ * channel + evicts its caches.
*/
export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -21,12 +24,15 @@ 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.canManage) return writeError("forbidden", 403)
const channel = access.value.channel
if (channel.creatorId === targetUserId) {
+ // Covers both "creator can't be removed" and "creator can't leave".
return writeError("can't remove the channel creator", 400)
}
+ // Self-leave is always allowed; removing anyone else is creator-only.
+ const isSelf = targetUserId === ctx.userId
+ if (!isSelf && !access.value.isCreator) return writeError("forbidden", 403)
const removed = await queries.communityChannel.deleteChannelMember(db, channelId, targetUserId)
if (!removed) return writeError("member not found", 404)
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.ts
index 9814e9c80..11f18aea6 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
@@ -11,6 +11,8 @@ const mockCreateChannelMember = vi.fn()
const mockListChannelMembers = vi.fn()
const mockGetPrivateChannelAudienceUserIds = vi.fn()
const mockGetUsersByIds = vi.fn()
+const mockResolveScopeMembers = vi.fn()
+const mockGetMembersByUserIds = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
const mockLogAudit = vi.fn()
@@ -27,7 +29,13 @@ vi.mock("@alook/shared", async () => {
listChannelMembers: (...a: unknown[]) => mockListChannelMembers(...a),
getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),
},
- communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },
+ communityMember: {
+ getMember: (...a: unknown[]) => mockGetMember(...a),
+ getMembersByUserIds: (...a: unknown[]) => mockGetMembersByUserIds(...a),
+ },
+ communityMembersResolver: {
+ resolveScopeMembers: (...a: unknown[]) => mockResolveScopeMembers(...a),
+ },
user: { getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a) },
},
}
@@ -66,14 +74,15 @@ function postReq(body: unknown) {
})
}
-// A private top-level channel the caller can manage.
+// A private top-level channel the caller can manage (caller u1 is the creator).
function managerCtx() {
return {
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
+ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "u1" },
anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
role: "member",
isPrivate: true,
isChannelMember: true,
+ isCreator: true,
}
}
@@ -81,16 +90,76 @@ describe("GET /channels/[id]/members", () => {
beforeEach(() => {
vi.clearAllMocks()
mockResolveChannelAccessContext.mockResolvedValue(managerCtx())
- mockListChannelMembers.mockResolvedValue([{ userId: "u1", addedBy: "u1", addedAt: "t", channelId: "c1", id: "cm1" }])
- mockGetUsersByIds.mockResolvedValue([{ id: "u1", name: "Ann", image: null, discriminator: "0001" }])
+ // Full resolved audience: creator (u1), an added member (u2), an admin (u3).
+ mockResolveScopeMembers.mockResolvedValue([
+ { userId: "u1", role: "member", source: "explicit" },
+ { userId: "u2", role: "member", source: "explicit" },
+ { userId: "u3", role: "admin", source: "admin" },
+ ])
+ mockGetMembersByUserIds.mockResolvedValue([
+ { id: "m1", serverId: "s1", userId: "u1", role: "member", nickname: null, userName: "Ann", userImage: null, discriminator: "0001", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },
+ { id: "m2", serverId: "s1", userId: "u2", role: "member", nickname: null, userName: "Bob", userImage: null, discriminator: "0002", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },
+ { id: "m3", serverId: "s1", userId: "u3", role: "admin", nickname: null, userName: "Cy", userImage: null, discriminator: "0003", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },
+ ])
})
- it("lists members for a caller with access", async () => {
+ it("lists the full audience with role + source + isCreator", async () => {
const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)
expect(res.status).toBe(200)
const body = await res.json()
+ expect(body.members).toHaveLength(3)
+ const creator = body.members.find((m: any) => m.userId === "u1")
+ expect(creator.isCreator).toBe(true)
+ expect(creator.source).toBe("explicit")
+ const added = body.members.find((m: any) => m.userId === "u2")
+ expect(added.isCreator).toBe(false)
+ expect(added.source).toBe("explicit")
+ const admin = body.members.find((m: any) => m.userId === "u3")
+ expect(admin.source).toBe("admin")
+ expect(admin.role).toBe("admin")
+ })
+
+ it("drops audience members with no hydrated (non-deleted) server row", async () => {
+ mockGetMembersByUserIds.mockResolvedValue([
+ { id: "m1", serverId: "s1", userId: "u1", role: "member", nickname: null, userName: "Ann", userImage: null, discriminator: "0001", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },
+ ])
+ const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)
+ const body = await res.json()
+ expect(body.members).toHaveLength(1)
expect(body.members[0].userId).toBe("u1")
- expect(body.members[0].isCreator).toBe(true)
+ })
+
+ it("resolves a thread to its anchor channel's audience", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue({
+ channel: { id: "t1", serverId: "s1", parentChannelId: "c1", creatorId: "u1" },
+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
+ role: "admin", isPrivate: true, isChannelMember: true,
+ })
+ const res = await 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))
+ })
+
+ 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).
+ 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,
+ })
+ mockResolveScopeMembers.mockResolvedValue([
+ { userId: "u1", role: "member", source: "explicit" },
+ { userId: "u2", role: "member", source: "explicit" },
+ ])
+ 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(body.members.find((m: any) => m.userId === "u2").isCreator).toBe(true)
+ expect(body.members.find((m: any) => m.userId === "u1").isCreator).toBe(false)
})
it("403 for a caller without access", async () => {
@@ -123,10 +192,19 @@ describe("POST /channels/[id]/members", () => {
expect(mockCreateChannelMember).not.toHaveBeenCalled()
})
- it("rejects a non-manager (403)", async () => {
- mockResolveChannelAccessContext.mockResolvedValue({ ...managerCtx(), creatorId: "other", channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" }, anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" }, isChannelMember: true, role: "member" })
+ it("allows any current member (not just creator) to add", async () => {
+ // Caller is a plain added member, not the creator — add is open to members.
+ mockResolveChannelAccessContext.mockResolvedValue({ ...managerCtx(), creatorId: "other", channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "other" }, anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "other" }, isChannelMember: true, role: "member", isCreator: false })
+ const res = await POST(postReq({ userId: "u2" }), ctx)
+ expect(res.status).toBe(201)
+ })
+
+ it("rejects a non-member outsider (403 from the access gate)", async () => {
+ // resolveChannelAccessContext returns null for someone with no access.
+ mockResolveChannelAccessContext.mockResolvedValue(null)
const res = await POST(postReq({ userId: "u2" }), ctx)
expect(res.status).toBe(403)
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
})
it("rejects adding to a public/uncategorized channel (400)", async () => {
@@ -141,11 +219,37 @@ describe("POST /channels/[id]/members", () => {
it("rejects adding on a thread channel (400)", 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,
})
const res = await POST(postReq({ userId: "u2" }), { params: { id: "t1" } } as any)
expect(res.status).toBe(400)
})
+
+ it("rejects adding to a FORUM (400): forum membership is derived from its 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 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()
+ })
+
+ it("allows adding to a private forum post (own access unit)", 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",
+ })
+ })
})
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.ts
index b7be62950..f24d44c28 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
@@ -6,11 +6,15 @@ import { queries, WS_EVENTS } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { logAudit } from "@/lib/community/audit"
import { requireChannelAccess } from "@/lib/community/permissions"
-import { avatarInitial } from "@/lib/community/avatar"
+import { mapMemberForApi } from "@/lib/community/member-payload"
/**
- * List the explicit members of a private-category channel. Any caller with
- * access to the channel may read the roster (creator, added members, admins).
+ * List the full resolved audience of a channel — the canonical "who is in this
+ * channel" endpoint. For a private-category channel that's admins ∪ creator ∪
+ * explicit members; for a public/uncategorized channel it's every server
+ * member. Each row carries `role`, `source` ("explicit" | "inherited" |
+ * "admin"), and `isCreator` so the drawer can group and the manage-members
+ * dialog can decide which rows are removable. Any caller with access may read.
*/
export const GET = withAuth(async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -20,31 +24,52 @@ 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 rows = await queries.communityChannel.listChannelMembers(db, channelId)
- const users = await queries.user.getUsersByIds(db, rows.map((r) => r.userId))
- const byId = new Map(users.map((u) => [u.id, u]))
- const creatorId = access.value.channel.creatorId
-
- const members = rows.map((r) => {
- const u = byId.get(r.userId)
- return {
- userId: r.userId,
- name: u?.name ?? null,
- discriminator: u?.discriminator ?? null,
- avatar: u?.image ?? avatarInitial(u?.name ?? ""),
- addedAt: r.addedAt,
- isCreator: r.userId === creatorId,
- }
+ const { anchor } = access.value
+ const scopeMembers = await queries.communityMembersResolver.resolveScopeMembers(db, {
+ scope: "channel",
+ scopeId: channelId,
})
+ const rows = await queries.communityMember.getMembersByUserIds(
+ db,
+ anchor.serverId,
+ scopeMembers.map((m) => m.userId),
+ )
+ 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 =
+ access.value.channel.type === "forum_post"
+ ? 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
+ .map((sm) => {
+ const row = rowByUser.get(sm.userId)
+ if (!row) return null
+ return mapMemberForApi(row, ctx.userId, {
+ isCreator: sm.userId === rosterCreatorId,
+ source: sm.source,
+ })
+ })
+ .filter((m): m is NonNullable<typeof m> => m !== null)
return writeJSON({ members })
})
/**
- * Add a server member to a private-category channel. Only the creator/admins
- * (canManage) may add. The target must be an existing server member, and the
- * channel must be a top-level channel in a PRIVATE category (threads inherit
- * their parent's roster — their own `categoryId` is NULL — so they're rejected).
+ * 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).
*/
export const POST = withAuth(async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -53,14 +78,22 @@ export const POST = 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.canManage) return writeError("forbidden", 403)
const channel = access.value.channel
- if (channel.parentChannelId) {
+ // 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 (channel.type === "thread" || channel.parentMessageId) {
return writeError("threads inherit their parent channel's members", 400)
}
- // Top-level channel → its anchor is itself, so `isPrivate` reflects its own
- // category. Public/uncategorized channels have no explicit roster.
+ // 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 (channel.type === "forum") {
+ 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.
if (!access.value.isPrivate) {
return writeError("channel is not in a private category", 400)
}
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index bb24c54c1..508a135b2 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -65,6 +65,9 @@ vi.mock("@alook/shared", async () => {
communityMention: {
createMentions: (...a: unknown[]) => mockCreateMentions(...a),
},
+ communityThread: {
+ addThreadParticipants: vi.fn(async () => undefined),
+ },
communityAttachment: {
createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),
listByMessageIds: (...a: unknown[]) => mockListByMessageIds(...a),
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
new file mode 100644
index 000000000..dbbddfad3
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+const mockResolveChannelAccessContext = vi.fn()
+const mockRemoveThreadParticipant = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityChannel: {
+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),
+ },
+ communityThread: {
+ removeThreadParticipant: (...a: unknown[]) => mockRemoveThreadParticipant(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { DELETE } from "./route"
+
+// Caller is "u1". `channel.creatorId` is the THREAD's own creator (the gate for
+// removing others); `anchor.creatorId` is the parent channel's creator, which
+// `isCreator` reflects — deliberately DIFFERENT here so a regression to the old
+// `access.value.isCreator` gate is caught.
+function threadCtx(over: Record<string, unknown> = {}) {
+ return {
+ channel: { id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "u1" },
+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "parent-owner" },
+ role: "member", isPrivate: true, isChannelMember: true, isCreator: false,
+ ...over,
+ }
+}
+function delReq() {
+ return new NextRequest("http://localhost/x", { method: "DELETE" })
+}
+
+describe("DELETE /channels/[id]/participants/[userId] — leave", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx())
+ mockRemoveThreadParticipant.mockResolvedValue({ id: "tp1" })
+ })
+
+ it("viewer leaves the thread (removes own row)", async () => {
+ const res = await DELETE(delReq(), { params: { id: "t1", userId: "u1" } } as any)
+ expect(res.status).toBe(204)
+ expect(mockRemoveThreadParticipant).toHaveBeenCalledWith(expect.anything(), "t1", "u1")
+ })
+
+ it("thread creator can remove another participant", async () => {
+ // channel.creatorId === "u1" (caller) even though anchor/isCreator differ.
+ const res = await DELETE(delReq(), { params: { id: "t1", userId: "u2" } } as any)
+ expect(res.status).toBe(204)
+ })
+
+ it("a non-thread-creator cannot remove someone else (403), even the parent-channel creator", async () => {
+ // Parent-channel creator (isCreator true) but NOT the thread's creator.
+ mockResolveChannelAccessContext.mockResolvedValue(
+ threadCtx({
+ channel: { id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "someone-else" },
+ isCreator: true,
+ }),
+ )
+ const res = await DELETE(delReq(), { params: { id: "t1", userId: "u2" } } as any)
+ expect(res.status).toBe(403)
+ expect(mockRemoveThreadParticipant).not.toHaveBeenCalled()
+ })
+})
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.ts
new file mode 100644
index 000000000..6ea0cc04c
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts
@@ -0,0 +1,38 @@
+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 { 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.
+ *
+ * (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.)
+ */
+export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
+ const channelId = ctx.params?.id
+ const targetUserId = ctx.params?.userId
+ if (!channelId || !targetUserId) return writeError("missing params", 400)
+
+ const db = getDb(ctx.env.DB)
+ const access = await requireChannelAccess(db, channelId, ctx.userId)
+ if (!access.ok) return writeError(access.error, access.status)
+ if (access.value.channel.type !== "thread") return writeError("not a thread", 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.
+ const isSelf = targetUserId === ctx.userId
+ const isThreadCreator = access.value.channel.creatorId === ctx.userId
+ if (!isSelf && !isThreadCreator) return writeError("forbidden", 403)
+
+ const removed = await queries.communityThread.removeThreadParticipant(db, channelId, targetUserId)
+ if (!removed) return writeError("participant not found", 404)
+ return new Response(null, { status: 204 })
+})
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.ts
new file mode 100644
index 000000000..6d37dc761
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
@@ -0,0 +1,143 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+const mockResolveChannelAccessContext = vi.fn()
+const mockListThreadParticipants = vi.fn()
+const mockAddThreadParticipant = vi.fn()
+const mockResolveScopeMemberUserIds = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityChannel: {
+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),
+ },
+ communityMembersResolver: {
+ resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),
+ },
+ communityThread: {
+ listThreadParticipants: (...a: unknown[]) => mockListThreadParticipants(...a),
+ addThreadParticipant: (...a: unknown[]) => mockAddThreadParticipant(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { GET, POST } from "./route"
+
+const ctx = { params: { id: "t1" } } as any
+function postReq(body: unknown) {
+ return new NextRequest("http://localhost/api/community/channels/t1/participants", {
+ method: "POST",
+ body: JSON.stringify(body),
+ })
+}
+
+// A thread the caller (u1) created, under parent channel c1.
+function threadCtx(over: Record<string, unknown> = {}) {
+ return {
+ channel: { id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "u1" },
+ anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
+ role: "member", isPrivate: true, isChannelMember: true, isCreator: true,
+ ...over,
+ }
+}
+
+describe("GET /channels/[id]/participants", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx())
+ mockListThreadParticipants.mockResolvedValue([
+ { userId: "u1", userName: "Ann", userImage: null, discriminator: "0001", source: "spoke" },
+ { userId: "u2", userName: "Bob", userImage: null, discriminator: "0002", source: "mention" },
+ ])
+ })
+
+ it("lists participants with source", async () => {
+ const res = await GET(new NextRequest("http://localhost/api/community/channels/t1/participants"), ctx)
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.participants).toHaveLength(2)
+ expect(body.participants[1]).toMatchObject({ userId: "u2", source: "mention" })
+ expect(body.participants[1]).not.toHaveProperty("muted")
+ })
+
+ it("400 when the channel is not a thread", 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)
+ })
+
+ it("403 for a caller who can't see the thread", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(null)
+ const res = await GET(new NextRequest("http://localhost/api/community/channels/t1/participants"), ctx)
+ expect(res.status).toBe(403)
+ })
+})
+
+describe("POST /channels/[id]/participants", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx())
+ // Parent-channel audience (same source the read gate/fan-out uses).
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])
+ mockAddThreadParticipant.mockResolvedValue({ id: "tp1" })
+ })
+
+ it("any participant adds a parent-channel member as a participant", async () => {
+ const res = await POST(postReq({ userId: "u2" }), ctx)
+ expect(res.status).toBe(201)
+ expect(mockAddThreadParticipant).toHaveBeenCalledWith(expect.anything(), {
+ threadChannelId: "t1", userId: "u2", source: "added",
+ })
+ expect(mockBroadcastToUserSafe).toHaveBeenCalled()
+ })
+
+ it("a non-creator participant can still add (no creator gate)", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx({ isCreator: false }))
+ const res = await POST(postReq({ userId: "u2" }), ctx)
+ expect(res.status).toBe(201)
+ expect(mockAddThreadParticipant).toHaveBeenCalled()
+ })
+
+ it("rejects adding someone not in the parent channel audience (400)", async () => {
+ mockResolveScopeMemberUserIds.mockResolvedValue(["u1"]) // u2 not in parent
+ const res = await POST(postReq({ userId: "u2" }), ctx)
+ expect(res.status).toBe(400)
+ expect(mockAddThreadParticipant).not.toHaveBeenCalled()
+ })
+
+ it("400 when the channel is not a thread", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(threadCtx({ channel: { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId: "u1" } }))
+ const res = await POST(postReq({ userId: "u2" }), 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.ts
new file mode 100644
index 000000000..ea9adc818
--- /dev/null
+++ b/src/web/src/app/api/community/channels/[id]/participants/route.ts
@@ -0,0 +1,102 @@
+import { NextRequest } from "next/server"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { getDb } from "@/lib/db"
+import { queries, WS_EVENTS } from "@alook/shared"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+import { 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.
+ */
+export const GET = withAuth(async (_req: NextRequest, ctx) => {
+ const channelId = ctx.params?.id
+ if (!channelId) return writeError("missing channel id", 400)
+
+ const db = getDb(ctx.env.DB)
+ const access = await requireChannelAccess(db, channelId, ctx.userId)
+ if (!access.ok) return writeError(access.error, access.status)
+ if (access.value.channel.type !== "thread") {
+ return writeError("not a thread", 400)
+ }
+
+ const rows = await queries.communityThread.listThreadParticipants(db, channelId)
+ const participants = rows.map((r) => ({
+ userId: r.userId,
+ name: r.userName ?? null,
+ discriminator: r.discriminator ?? null,
+ avatar: r.userImage ?? avatarInitial(r.userName ?? ""),
+ source: r.source,
+ }))
+ return writeJSON({ participants })
+})
+
+/**
+ * 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).
+ */
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const channelId = ctx.params?.id
+ if (!channelId) return writeError("missing channel id", 400)
+
+ const db = getDb(ctx.env.DB)
+ const access = await requireChannelAccess(db, channelId, ctx.userId)
+ if (!access.ok) return writeError(access.error, access.status)
+ const channel = access.value.channel
+ if (channel.type !== "thread") return writeError("not a thread", 400)
+
+ let body: { userId?: string }
+ try {
+ body = await req.json()
+ } catch {
+ return writeError("invalid request body", 400)
+ }
+ const targetUserId = body.userId
+ if (!targetUserId || typeof targetUserId !== "string") {
+ return writeError("userId is required", 400)
+ }
+
+ // The target must be able to see the parent channel. Resolve its audience via
+ // the SAME source fan-out/read-gate uses (`resolveScopeMemberUserIds`), so the
+ // "can this user see the parent" definition can't drift between add-validation
+ // and who-actually-gets-messages (public → all server members; private → the
+ // channel roster).
+ const parentId = channel.parentChannelId
+ if (!parentId) return writeError("thread has no parent channel", 400)
+ const parentAudience = new Set(
+ await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
+ scope: "channel",
+ scopeId: parentId,
+ })
+ )
+ if (!parentAudience.has(targetUserId)) {
+ return writeError("user is not a member of the parent channel", 400)
+ }
+
+ const created = await queries.communityThread.addThreadParticipant(db, {
+ threadChannelId: channelId,
+ userId: targetUserId,
+ source: "added",
+ })
+
+ // Notify the added user so their inbox/thread view reflects the new
+ // participation. Only on a genuinely-new row (null = already a participant).
+ if (created) {
+ void broadcastToUserSafe(targetUserId, {
+ type: WS_EVENTS.CHANNEL_MEMBER_ADD,
+ serverId: channel.serverId,
+ channelId,
+ userId: targetUserId,
+ })
+ }
+
+ return writeJSON({ ok: true }, 201)
+})
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.ts
index e54f3529f..d9aa1990d 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
@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
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()
@@ -25,6 +27,8 @@ vi.mock("@alook/shared", async () => {
queries: {
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
@@ -146,7 +150,13 @@ describe("POST /api/community/channels/[id]/posts — name normalization", () =>
describe("GET /api/community/channels/[id]/posts — authorId", () => {
beforeEach(() => {
vi.clearAllMocks()
- mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })
+ // GET now uses requireChannelAccess. Public forum → isPrivate:false so the
+ // per-post visibility filter is skipped.
+ 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: false, isChannelMember: false, isCreator: true,
+ })
mockGetFirstMessageByChannelIds.mockResolvedValue([])
})
@@ -179,3 +189,79 @@ describe("GET /api/community/channels/[id]/posts — authorId", () => {
expect(body.posts[0].authorId).toBe("")
})
})
+
+describe("GET /api/community/channels/[id]/posts — private-forum post visibility", () => {
+ const posts = [
+ { id: "p_mine", name: "Mine", messageCount: 1, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_other", tags: [] },
+ { id: "p_hidden", name: "Secret", messageCount: 1, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u_other", tags: [] },
+ { id: "p_created", name: "By me", messageCount: 1, lastMessageAt: null, createdAt: "2026-07-01T00:00:00.000Z", creatorId: "u1", tags: [] },
+ ]
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetFirstMessageByChannelIds.mockResolvedValue([])
+ mockGetUsersByIds.mockResolvedValue([])
+ mockListChildChannels.mockResolvedValue(posts)
+ })
+
+ function getReq() {
+ return 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).
+ 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
+ })
+
+ 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.
+ 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: "admin", isPrivate: true, isChannelMember: true, isCreator: false,
+ })
+
+ const 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 () => {
+ 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.
+ 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()
+ })
+})
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.ts
index fc0852320..8443a110b 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,9 +9,10 @@ import {
MESSAGE_PREVIEW_LENGTH,
WS_EVENTS,
slugify,
+ canManageServer,
} from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
-import { requireChannelMember } from "@/lib/community/permissions"
+import { requireChannelMember, requireChannelAccess } from "@/lib/community/permissions"
import { avatarInitial } from "@/lib/community/avatar"
import { createCommunityMessage } from "@/lib/community/message-handler"
@@ -21,9 +22,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
- const auth = await requireChannelMember(db, channelId, ctx.userId)
+ const auth = await requireChannelAccess(db, channelId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const channel = auth.value
+ const channel = auth.value.channel
if (channel.type !== "forum") {
return writeError("channel is not a forum", 400)
@@ -40,6 +41,25 @@ 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),
+ )
+ }
+
// Batch-fetch all creators in one query
const creatorIds = [...new Set(childChannels.map((t) => t.creatorId).filter(Boolean) as string[])]
const creators = creatorIds.length > 0 ? await queries.user.getUsersByIds(db, creatorIds) : []
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.ts
index e918eb440..a6b2dcc16 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
@@ -106,13 +106,15 @@ function accessCtx(over: Partial<{
creatorId = "u1"
ctxIsPrivate = true
}
- const channel = { id: "c1", serverId: "s1", parentChannelId: null, creatorId, categoryId: anchorCategoryId }
+ const channel = { id: "c1", serverId: "s1", type: "text", parentChannelId: null, parentMessageId: null, creatorId, categoryId: anchorCategoryId }
return {
channel,
anchor: { ...channel },
role,
isPrivate: ctxIsPrivate,
isChannelMember: !canManage, // member-only access for the non-manage case
+ // Roster-anchor creator gate; caller in these tests is always "u1".
+ isCreator: creatorId === "u1",
}
}
diff --git a/src/web/src/app/api/community/search/route.test.ts b/src/web/src/app/api/community/search/route.test.ts
index f407a4c2b..765de1d10 100644
--- a/src/web/src/app/api/community/search/route.test.ts
+++ b/src/web/src/app/api/community/search/route.test.ts
@@ -54,11 +54,12 @@ describe("GET /api/community/search — server scope", () => {
{ params: {} } as any,
)
expect(res.status).toBe(200)
+ // Visibility no longer takes an isAdmin flag — admins get the same
+ // member-scoped visibility as everyone (no special private access).
expect(mockListVisibleChannelIds).toHaveBeenCalledWith(
expect.anything(),
"s1",
"u1",
- { isAdmin: false },
)
expect(mockSearchMessagesInServer).toHaveBeenCalledWith(
expect.anything(),
@@ -66,14 +67,14 @@ describe("GET /api/community/search — server scope", () => {
)
})
- it("resolves isAdmin from the caller's role", async () => {
+ it("admin gets the same member-scoped visibility (no isAdmin flag)", async () => {
mockGetMember.mockResolvedValue({ id: "m1", role: "owner" })
await GET(
new NextRequest("http://localhost/api/community/search?q=hello&serverId=s1"),
{ params: {} } as any,
)
expect(mockListVisibleChannelIds).toHaveBeenCalledWith(
- expect.anything(), "s1", "u1", { isAdmin: true },
+ expect.anything(), "s1", "u1",
)
})
})
diff --git a/src/web/src/app/api/community/search/route.ts b/src/web/src/app/api/community/search/route.ts
index 652441d32..5961822a7 100644
--- a/src/web/src/app/api/community/search/route.ts
+++ b/src/web/src/app/api/community/search/route.ts
@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, canManageServer, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"
+import { queries, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"
import {
requireServerMember,
requireChannelMember,
@@ -38,7 +38,6 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
db,
serverId,
ctx.userId,
- { isAdmin: canManageServer(auth.value!.role) },
)
const results = await queries.communitySearch.searchMessagesInServer(db, {
query: q,
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.test.ts
index 76c4a7ee2..72e356cb8 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.test.ts
@@ -187,6 +187,27 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {
expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: "" })
})
+ it("owner-scoped isBot gating: own bot exposes isBot/ownerUserId; other bots pass as humans", async () => {
+ const rows = [
+ { ...buildRow(1), userId: "own_bot", userIsBot: true, userOwnerUserId: "u1" },
+ { ...buildRow(2), userId: "other_bot", userIsBot: true, userOwnerUserId: "someone_else" },
+ { ...buildRow(3), userId: "human", userIsBot: false, userOwnerUserId: null },
+ ]
+ mockListMembersPaginated.mockResolvedValue({ members: rows, hasMore: false, cursor: undefined })
+ mockCountMembers.mockResolvedValue(3)
+
+ const res = await GET(getReq(), ctx)
+ const body = await res.json() as { members: Array<{ userId: string; isBot?: boolean; ownerUserId?: string }> }
+ const own = body.members.find((m) => m.userId === "own_bot")!
+ expect(own.isBot).toBe(true)
+ expect(own.ownerUserId).toBe("u1")
+ const other = body.members.find((m) => m.userId === "other_bot")!
+ expect(other.isBot).toBeUndefined()
+ expect(other.ownerUserId).toBeUndefined()
+ const human = body.members.find((m) => m.userId === "human")!
+ expect(human.isBot).toBeUndefined()
+ })
+
it("returns 403 for non-members (permission check ahead of the query)", async () => {
mockGetMember.mockResolvedValue(null)
const res = await GET(getReq(), ctx)
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.ts b/src/web/src/app/api/community/servers/[id]/members/route.ts
index f5d653e58..5f7847059 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.ts
@@ -8,7 +8,7 @@ import {
} from "@alook/shared"
import { requireServerMember } from "@/lib/community/permissions"
import { parseBoundedInt, parseMemberCursor, buildMemberPaginatedResponse } from "@/lib/community/messages"
-import { avatarInitial } from "@/lib/community/avatar"
+import { mapMemberForApi } from "@/lib/community/member-payload"
export const GET = withAuth(async (req, ctx) => {
const serverId = ctx.params?.id
@@ -39,28 +39,13 @@ export const GET = withAuth(async (req, ctx) => {
// client has no joinedAt field and shouldn't gain one.
const envelope = buildMemberPaginatedResponse(page.members, page.hasMore)
- // Owner-scoped isBot/ownerUserId projection:
- // - The caller sees `isBot: true` + `ownerUserId` ONLY on rows they own.
- // - Other bots (owned by other users) appear as normal humans — no
- // isBot/ownerUserId fields at all.
- // This is the load-bearing pass-as-human projection at the member-list layer.
- const members = envelope.members.map((r) => {
- const display = r.nickname ?? r.userName ?? ""
- const isOwnBot = r.userIsBot === true && r.userOwnerUserId === ctx.userId
- return {
- id: r.id,
- userId: r.userId,
- name: display,
- discriminator: r.discriminator ?? undefined,
- avatar: r.userImage ?? avatarInitial(display),
- status: (r.userId === ctx.userId ? "online" : "offline") as "online" | "offline",
- sub: "",
- role: r.role ?? "member",
- statusEmoji: r.statusEmoji ?? null,
- statusText: r.statusText ?? "",
- ...(isOwnBot ? { isBot: true as const, ownerUserId: r.userOwnerUserId! } : {}),
- }
- })
+ // Owner-scoped isBot/ownerUserId projection (via the shared mapper's
+ // `botGating` opt): the caller sees `isBot`/`ownerUserId` ONLY on rows they
+ // own; other bots appear as normal humans. This is the load-bearing
+ // pass-as-human projection at the member-list layer.
+ const members = envelope.members.map((r) =>
+ mapMemberForApi(r, ctx.userId, { botGating: true }),
+ )
return writeJSON({ members, hasMore: envelope.hasMore, cursor: envelope.cursor, limit, total })
})
diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
index 6ba944775..8aa8431b2 100644
--- a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
@@ -95,6 +95,17 @@ describe("GET /api/community/servers/[id]/members/search", () => {
expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: "" })
})
+ it("never emits isBot/ownerUserId (no bot gating on search — byte-identical)", async () => {
+ // Even if a row carried bot columns, search passes them through as humans.
+ mockSearchMembers.mockResolvedValue([
+ { ...buildRow(1, "Botty"), userId: "own_bot", userIsBot: true, userOwnerUserId: "u1" },
+ ])
+ const res = await GET(getReq("?q=Bot"), ctx)
+ const body = await res.json() as { members: Array<{ isBot?: boolean; ownerUserId?: string }> }
+ expect(body.members[0].isBot).toBeUndefined()
+ expect(body.members[0].ownerUserId).toBeUndefined()
+ })
+
it("rejects empty q with 400", async () => {
const res = await GET(getReq(""), ctx)
expect(res.status).toBe(400)
diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.ts
index 6c01d99be..f3f62abb1 100644
--- a/src/web/src/app/api/community/servers/[id]/members/search/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.ts
@@ -4,7 +4,7 @@ import { getDb } from "@/lib/db"
import { queries, MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"
import { requireServerMember } from "@/lib/community/permissions"
import { parseBoundedInt } from "@/lib/community/messages"
-import { avatarInitial } from "@/lib/community/avatar"
+import { mapMemberForApi } from "@/lib/community/member-payload"
export const GET = withAuth(async (req, ctx) => {
const serverId = ctx.params?.id
@@ -25,21 +25,9 @@ export const GET = withAuth(async (req, ctx) => {
)
const rows = await queries.communityMember.searchMembers(db, serverId, q, { limit })
- const members = rows.map((r) => {
- const display = r.nickname ?? r.userName ?? ""
- return {
- id: r.id,
- userId: r.userId,
- name: display,
- discriminator: r.discriminator ?? undefined,
- avatar: r.userImage ?? avatarInitial(display),
- status: (r.userId === ctx.userId ? "online" : "offline") as "online" | "offline",
- sub: "",
- role: r.role ?? "member",
- statusEmoji: r.statusEmoji ?? null,
- statusText: r.statusText ?? "",
- }
- })
+ // No bot gating here — `searchMembers` never selected the bot columns and this
+ // route never emitted `isBot`/`ownerUserId`. Byte-identical to before.
+ const members = rows.map((r) => mapMemberForApi(r, ctx.userId))
return writeJSON({ members, limit })
})
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index e7c80d1e4..91453ea21 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -4,7 +4,6 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
queries,
- canManageServer,
isServerOwner,
MAX_SERVER_NAME_LENGTH,
MAX_SERVER_DESCRIPTION_LENGTH,
@@ -23,15 +22,15 @@ export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const auth = await requireServerMember(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const isAdmin = canManageServer(auth.value!.role)
const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
const [server, rawChannels, categories, unreadRows] = await Promise.all([
queries.communityServer.getServer(db, serverId),
// Viewer-scoped: private-category channels are only returned if the viewer
- // is an admin, the channel creator, or an added member. Private category
- // HEADERS still appear (below) so members can create channels in them.
- queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.userId, { isAdmin }),
+ // is the channel creator or an added member (admins get NO special
+ // visibility). Private category HEADERS still appear (below) so members can
+ // create channels in them.
+ queries.communityChannel.listServerChannelsForViewer(db, serverId, ctx.userId),
db.query.communityCategory.findMany({
where: (t, { eq }) => eq(t.serverId, serverId),
orderBy: (t, { asc }) => [asc(t.position)],
diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
index d9eb643db..2fa469539 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -1,7 +1,7 @@
"use client"
import { useCallback, useEffect, useMemo, useState } from "react"
-import { useParams, useRouter } from "next/navigation"
+import { useParams, useRouter, useSearchParams } from "next/navigation"
import { toast } from "sonner"
import { apiFetch, toastApiError } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
@@ -11,6 +11,7 @@ import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/co
import { ForumView, ForumViewSkeleton } from "@/components/community/forum-view"
import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"
import { ThreadOpener } from "@/components/community/thread-opener"
+import { AddMembersDialog } from "@/components/community/add-members-dialog"
import type { RightPanel, Msg, OpenProfile, Role } from "@/components/community/_types"
import { canManageServer } from "@/components/community/_types"
import type { MentionType } from "@alook/shared"
@@ -23,6 +24,8 @@ import {
import { useCurrentUser } from "@/contexts/community/current-user"
import { useServer } from "@/hooks/community/use-servers"
import { useServerMembers } from "@/hooks/community/use-server-members"
+import { useChannelMembers, useAddableMembers, useAddChannelMember, useRemoveChannelMember } from "@/hooks/community/use-channel-members"
+import { useThreadParticipants, useAddThreadParticipant, useRemoveThreadParticipant } from "@/hooks/community/use-thread-participants"
import { useMessages } from "@/hooks/community/use-messages"
import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"
import { useChannelWatermark } from "@/hooks/community/use-channel-watermark"
@@ -72,8 +75,15 @@ export default function ChannelPage() {
function ChannelView() {
const params = useParams<{ serverId: string; channelId: string }>()
const router = useRouter()
+ const searchParams = useSearchParams()
const serverId = decodeURIComponent(params.serverId)
const channelId = params.channelId
+ // Cross-channel "jump to message" target, captured ONCE at mount from `?msg=`.
+ // `ChannelView` is keyed by `serverId/channelId`, so a fresh jump remounts and
+ // re-reads this. The param is stripped from the URL right after (below) so a
+ // refresh/back doesn't re-trigger the jump; this frozen copy still drives the
+ // anchor + scroll for this mount.
+ const [jumpTargetId] = useState<string | null>(() => searchParams.get("msg"))
const bp = useBreakpoint()
const currentUser = useCurrentUser()
const uiHandlers = useUiHandlers()
@@ -101,13 +111,6 @@ function ChannelView() {
}),
[membersHook.members, onlineUserIds, currentUser.id, userStatuses],
)
- // Roster passed to the @-mention popover — filters the viewer out.
- // `members` (above) still includes the viewer for the roster / typing lookup;
- // only the composer needs to drop self, since you can't @-mention yourself.
- const composerMembers = useMemo(
- () => members.filter((m) => m.userId !== currentUser.id),
- [members, currentUser.id],
- )
// Type-gate the forum-posts fetch: only forum channels have a valid
// /posts endpoint; text channels return 400. Compute the flag BEFORE the
// hook call so `useForumPosts` can stay disabled for non-forum channels.
@@ -117,6 +120,150 @@ function ChannelView() {
}, [currentServer, channelId])
const isForum = channelInServer?.type === "forum"
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
+
+ // Local filter for the private-channel Members drawer (the channel audience is
+ // small, so search is client-side — no scoped search endpoint).
+ const [memberQuery, setMemberQuery] = useState("")
+ // Whether the manage-members dialog is open (Add button in the private drawer).
+ const [manageMembersOpen, setManageMembersOpen] = useState(false)
+
+ // Is the current channel (or its anchor, for a thread) inside a PRIVATE
+ // category? Drives the Members drawer's data source: private → the channel
+ // audience via `useChannelMembers`; public → the server roster. The server
+ // re-checks privacy anyway (`requireChannelAccess`), so an over-eager `true`
+ // only risks calling the channel endpoint when it wasn't needed — safe.
+ const currentChannelPrivate = useMemo(() => {
+ const cats = currentServer?.categories ?? []
+ // Thread/forum-post: privacy is governed by the anchor channel's category.
+ const anchorId = isChildChannel
+ ? (currentChannelMeta?.parentChannelId ?? channelId)
+ : channelId
+ 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)
+ 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)
+ 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
+ const parentChannelMembersHook = useChannelMembers(threadParentId ?? "", !!threadParentId)
+
+ // Members shown in the right-panel Members drawer:
+ // - thread → its notify participants (mapped to the roster shape).
+ // - private channel/post → the resolved channel audience (locally filtered).
+ // - public → the server roster.
+ // All enriched with live presence for the correct dot.
+ const panelMembers = useMemo(() => {
+ const q = memberQuery.trim().toLowerCase()
+ const withPresence = (m: {
+ userId: string; name: string; discriminator?: string; avatar: string
+ statusEmoji?: string | null; statusText?: string | null
+ isCreator?: boolean; source?: "explicit" | "inherited" | "admin"
+ }) => {
+ const liveStatus = userStatuses.get(m.userId)
+ return {
+ id: m.userId,
+ userId: m.userId,
+ name: m.name,
+ discriminator: m.discriminator,
+ avatar: m.avatar,
+ sub: "",
+ role: "member" as const,
+ status:
+ m.userId === currentUser.id || onlineUserIds.has(m.userId)
+ ? ("online" as const)
+ : ("offline" as const),
+ statusEmoji: liveStatus ? liveStatus.emoji : (m.statusEmoji ?? null),
+ statusText: liveStatus ? liveStatus.text : (m.statusText ?? ""),
+ isCreator: m.isCreator,
+ source: m.source,
+ }
+ }
+ const matches = (name: string, disc?: string | null) =>
+ !q || name.toLowerCase().includes(q) || (disc ?? "").toLowerCase().includes(q)
+
+ if (isThread) {
+ const threadCreatorId = currentChannelMeta?.creatorId
+ return threadParticipantsHook.participants
+ .filter((p) => matches(p.name ?? "", p.discriminator))
+ .map((p) => withPresence({
+ userId: p.userId,
+ name: p.name ?? "Unknown",
+ discriminator: p.discriminator ?? undefined,
+ avatar: p.avatar,
+ // Thread rows are all real participants (removable); the thread
+ // creator's row is locked.
+ isCreator: p.userId === threadCreatorId,
+ }))
+ }
+ if (!currentChannelPrivate) return members
+ return channelMembersHook.members
+ .filter((m) => matches(m.name, m.discriminator))
+ .map((m) => withPresence(m))
+ }, [
+ isThread,
+ threadParticipantsHook.participants,
+ currentChannelMeta,
+ currentChannelPrivate,
+ members,
+ channelMembersHook.members,
+ memberQuery,
+ onlineUserIds,
+ currentUser.id,
+ userStatuses,
+ ])
+
+ // Roster passed to the @-mention popover — filters the viewer out.
+ // `members` still includes the viewer for the roster / typing lookup; only the
+ // composer needs to drop self (you can't @-mention yourself).
+ //
+ // Scoping (nested-membership model): in a private channel/post the popover
+ // lists only that unit's members; in a thread it lists the parent channel's
+ // members (the channel-members endpoint climbs a thread to its anchor). Public
+ // channels keep the whole-server roster. Uses `channelMembersHook.members`
+ // (unfiltered by the drawer's search box), enriched with live presence to
+ // match the server-roster path.
+ const composerMembers = useMemo(() => {
+ 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
+ return scopedRoster
+ .filter((m) => m.userId !== currentUser.id)
+ .map((m) => {
+ const liveStatus = userStatuses.get(m.userId)
+ return {
+ ...m,
+ status: onlineUserIds.has(m.userId) ? ("online" as const) : ("offline" as const),
+ statusEmoji: liveStatus ? liveStatus.emoji : m.statusEmoji,
+ statusText: liveStatus ? liveStatus.text : m.statusText,
+ }
+ })
+ }, [
+ currentChannelPrivate,
+ isThread,
+ members,
+ channelMembersHook.members,
+ parentChannelMembersHook.members,
+ onlineUserIds,
+ currentUser.id,
+ userStatuses,
+ ])
// `/`-autocomplete candidates for both Composer call sites below — single
// server, so no directory hook needed here (see `me/[dmId]/page.tsx` for
@@ -145,6 +292,7 @@ function ChannelView() {
lastReadMessageId: readSnapshotFetching
? undefined
: (readSnapshot?.lastReadMessageId ?? null),
+ anchorMessageId: jumpTargetId,
})
const {
messages,
@@ -273,7 +421,7 @@ function ChannelView() {
communityWsSubscribe({ channelId })
// Child channel — fetch meta so the breadcrumb shows the new parent name
if (isChildChannel) {
- apiFetch<{ id: string; name: string; parentChannelId: string | null; parentMessageId: string | null }>(`/api/community/threads/${channelId}`)
+ apiFetch<{ id: string; name: string; parentChannelId: string | null; parentMessageId: string | null; creatorId: string | null }>(`/api/community/threads/${channelId}`)
.then((data) =>
useCommunityStore
.getState()
@@ -281,6 +429,7 @@ function ChannelView() {
name: data.name,
parentChannelId: data.parentChannelId,
parentMessageId: data.parentMessageId,
+ creatorId: data.creatorId,
}),
)
.catch((e) => {
@@ -301,16 +450,54 @@ function ChannelView() {
const [localName, setLocalName] = useState<string | null>(null)
const [searchQuery, setSearchQuery] = useState("")
const [searchResults, setSearchResults] = useState<Msg[]>([])
- const [scrollToMessageId, setScrollToMessageId] = useState<string | null>(null)
+ // Seed the scroll target from the mount-time jump target (if any) so
+ // `MessageList` scrolls to + highlights the message once the anchored window
+ // loads it. Unlike the reply-pill path (100ms fixed-timer clear), this is
+ // cleared by an effect once the row is actually present (below) — the anchor
+ // page is still being fetched over the network, so a fixed timer would race
+ // and lose the "guaranteed land".
+ const [scrollToMessageId, setScrollToMessageId] = useState<string | null>(jumpTargetId)
+
+ // Strip `?msg=` from the URL right after mount so a refresh/back doesn't
+ // re-trigger the jump. The frozen `jumpTargetId` + seeded `scrollToMessageId`
+ // still drive this mount's anchor and scroll; this only cleans the address.
+ useEffect(() => {
+ if (!jumpTargetId) return
+ router.replace(`/community/channels/${params.serverId}/${channelId}`, { scroll: false })
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump
+ }, [])
- // Channel switch — reset every piece of UI state scoped to the previous channel.
+ // Clear the jump scroll target once the target row is present in the loaded
+ // window (guaranteed-land: don't clear on a fixed timer while the anchor page
+ // is still in flight). Fallback: if the load has fully SETTLED (not
+ // loading/fetching) and the row still isn't here — e.g. the message was
+ // deleted between navigation and load, or the anchor fetch failed — the row
+ // will never appear, so release the state rather than leak it for the mount.
+ useEffect(() => {
+ if (!scrollToMessageId) return
+ if (messages.some((m) => m.id === scrollToMessageId)) {
+ const t = setTimeout(() => setScrollToMessageId((v) => (v === scrollToMessageId ? null : v)), 1600)
+ return () => clearTimeout(t)
+ }
+ const settled =
+ !messagesLoading && !isFetchingOlderMessages && !isFetchingNewerMessages
+ if (settled) setScrollToMessageId((v) => (v === scrollToMessageId ? null : v))
+ }, [scrollToMessageId, messages, messagesLoading, isFetchingOlderMessages, isFetchingNewerMessages])
+
+ // Channel switch — reset every piece of UI state scoped to the previous
+ // channel. `ChannelView` is keyed by `serverId/channelId`, so this remounts on
+ // switch; the effect is a belt-and-suspenders reset. NB: `scrollToMessageId`
+ // is intentionally NOT reset here — it's seeded from the mount-time jump
+ // target and cleared by its own effect once the row lands; clearing it here
+ // would clobber a `?msg=` jump on the first render.
useEffect(() => {
setReplyTo(null)
setRightPanel(null)
setSearchQuery("")
setSearchResults([])
setLocalName(null)
- setScrollToMessageId(null)
+ setMemberQuery("")
+ setManageMembersOpen(false)
}, [channelId])
const doSearch = useCallback(async (q: string) => {
@@ -491,14 +678,54 @@ function ChannelView() {
}
const myRole = members.find((m) => m.userId === currentUser.id)?.role
+ // The unit's creator (thread/channel/post) — drives the manage-context
+ // creator rules. For a thread the id lives on `currentChannelMeta`; for a
+ // top-level channel/post it's on the channel row in the server tree.
+ const unitCreatorId = isChildChannel
+ ? currentChannelMeta?.creatorId
+ : channelInServer?.creatorId
+ const 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)
+ // 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
+ ? {
+ viewerUserId: currentUser.id,
+ viewerIsCreator: viewerIsUnitCreator,
+ onLeave: (userId: string) =>
+ (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutate(userId, {
+ onError: (e) => toastApiError(e, "Failed to leave"),
+ }),
+ onRemove: (userId: string) =>
+ (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutate(userId, {
+ onError: (e) => toastApiError(e, "Failed to remove"),
+ }),
+ }
+ : undefined
const panelProps = {
onOpenThread: enterThread,
- members,
- membersLoading: membersHook.loading,
- membersLoadingMore: membersHook.loadingMore,
- membersHasMore: membersHook.hasMore,
- onLoadMoreMembers: membersHook.loadMore,
- onSearchMembers: membersHook.searchMembers,
+ members: panelMembers,
+ membersLoading: isThread
+ ? threadParticipantsHook.isLoading
+ : currentChannelPrivate ? channelMembersHook.isLoading : membersHook.loading,
+ membersLoadingMore: scopedDrawer ? false : membersHook.loadingMore,
+ membersHasMore: scopedDrawer ? false : membersHook.hasMore,
+ onLoadMoreMembers: scopedDrawer ? undefined : membersHook.loadMore,
+ // Scoped drawer: local filter (small set). Public: server search.
+ onSearchMembers: scopedDrawer ? setMemberQuery : membersHook.searchMembers,
+ onAddMember: showManageButton ? () => setManageMembersOpen(true) : undefined,
+ manageContext,
pinned,
pinnedLoading,
searchResults,
@@ -525,6 +752,49 @@ 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).
+ // 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) {
+ const participantIds = new Set(threadParticipantsHook.participants.map((p) => p.userId))
+ const candidates = parentChannelMembersHook.members
+ .filter((m) => !participantIds.has(m.userId) && m.userId !== currentUser.id)
+ .map((m) => ({ userId: m.userId, name: m.name ?? null, avatar: m.avatar }))
+ return (
+ <AddMembersDialog
+ title={`Add participants to /${currentChannelMeta?.name ?? channelName}`}
+ subtitle="Added people are notified of new replies. Anyone with access can already read the thread."
+ candidates={candidates}
+ addPending={addThreadParticipantMut.isPending}
+ onAdd={async (userId) => { await addThreadParticipantMut.mutateAsync(userId) }}
+ onClose={() => setManageMembersOpen(false)}
+ />
+ )
+ }
+ const candidates = addableChannelMembers.members.map((m) => ({
+ userId: m.userId,
+ name: m.name ?? null,
+ avatar: m.avatar,
+ }))
+ return (
+ <AddMembersDialog
+ title={`Add members to /${channelName}`}
+ subtitle="Added members can see and post in this channel."
+ candidates={candidates}
+ addPending={addChannelMemberMut.isPending}
+ onAdd={async (userId) => { await addChannelMemberMut.mutateAsync(userId) }}
+ onClose={() => setManageMembersOpen(false)}
+ />
+ )
+ })()
+
const isPotentialChild = !channelInServer && !!currentServer?.categories
const bodyLoading = isForum ? forumPostsLoading : messagesLoading
const channelHydrated =
@@ -583,6 +853,14 @@ function ChannelView() {
a.download = url.split("/").pop() ?? "file"
a.click()
}}
+ onJump={
+ parentId
+ ? () =>
+ router.push(
+ `/community/channels/${params.serverId}/${parentId}?msg=${parentMessageId}`,
+ )
+ : undefined
+ }
/>
) : undefined
return (
@@ -656,6 +934,7 @@ function ChannelView() {
onOpenProfile={openProfile}
/>
)}
+ {manageMembersDialog}
</>
)
}
@@ -707,6 +986,7 @@ function ChannelView() {
onOpenProfile={openProfile}
/>
)}
+ {manageMembersDialog}
</>
)
}
@@ -780,6 +1060,7 @@ function ChannelView() {
onOpenProfile={openProfile}
/>
)}
+ {manageMembersDialog}
</>
)
}
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 2d46a1786..44d9588ac 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -172,6 +172,14 @@ export type Member = {
// Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.
statusEmoji?: string | null
statusText?: string | null
+ // Populated only when the drawer shows a private channel/post roster or a
+ // thread participant set — drives the row's Leave/Remove right-click menu.
+ // - isCreator: this user owns the unit (row locked — never removable/leaveable).
+ // - source: for a channel/post, only "explicit" rows are removable (an
+ // admin-by-role or inherited public member isn't an explicit roster row).
+ // Thread participants are always "explicit"-equivalent (a real row).
+ isCreator?: boolean
+ source?: "explicit" | "inherited" | "admin"
}
export type Friend = {
@@ -317,3 +325,17 @@ export type OpenProfile = (
discriminator?: string,
userId?: string,
) => void
+
+// Passed to the Members drawer when it's showing a private channel/post roster
+// OR a thread's participants — the row right-click menu becomes Leave (self,
+// non-creator) / Remove (viewer is the unit creator, on other explicit members)
+// instead of the server-scoped Role/Kick menu. Remove is CREATOR-ONLY on every
+// unit (admins have no content privilege). The creator's own row is locked.
+export type MemberManageContext = {
+ viewerUserId: string
+ // The viewer created this unit → their own row shows no Leave (owners keep
+ // the unit), and they may Remove other explicit members.
+ viewerIsCreator: boolean
+ onLeave: (userId: string) => void
+ onRemove: (userId: string) => void
+}
diff --git a/src/web/src/components/community/add-members-dialog.tsx b/src/web/src/components/community/add-members-dialog.tsx
new file mode 100644
index 000000000..5ba44eea7
--- /dev/null
+++ b/src/web/src/components/community/add-members-dialog.tsx
@@ -0,0 +1,94 @@
+"use client"
+
+import { useMemo, useState } from "react"
+import { Search } from "lucide-react"
+import { toast } from "sonner"
+import { Dialog, DialogContent } from "@/components/ui/dialog"
+import { Input } from "@/components/ui/input"
+import { Button } from "@/components/ui/button"
+import { Avatar } from "./avatar"
+
+export type AddableCandidate = {
+ userId: string
+ name: string | null
+ avatar: string
+}
+
+/**
+ * Shared "add members" picker for every private unit — a channel/post roster or
+ * a thread participant set. Pure add: the current-member list and its
+ * leave/remove controls live in the Members drawer's row right-click menu
+ * (`MemberList` `manageContext`), not here.
+ *
+ * The caller resolves the candidate pool (server members not in a channel, or
+ * parent-channel members not yet participating) and supplies `onAdd`.
+ */
+export function AddMembersDialog({
+ title,
+ subtitle,
+ candidates,
+ addPending,
+ onAdd,
+ onClose,
+}: {
+ title: string
+ subtitle: string
+ candidates: AddableCandidate[]
+ addPending: boolean
+ onAdd: (userId: string) => Promise<void> | void
+ onClose: () => void
+}) {
+ const [query, setQuery] = useState("")
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase()
+ if (!q) return candidates
+ return candidates.filter((m) => (m.name ?? "").toLowerCase().includes(q))
+ }, [candidates, query])
+
+ const add = async (userId: string) => {
+ try {
+ await onAdd(userId)
+ } catch (err) {
+ toast(err instanceof Error ? err.message : "Couldn't add member")
+ }
+ }
+
+ return (
+ <Dialog open onOpenChange={(o) => { if (!o) onClose() }}>
+ <DialogContent className="flex max-h-[80vh] w-full flex-col gap-0 p-0 sm:max-w-md">
+ <header className="border-b border-border px-4 py-3">
+ <h2 className="truncate text-sm font-semibold">{title}</h2>
+ <p className="text-xs text-muted-foreground">{subtitle}</p>
+ </header>
+
+ <div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar px-2 py-2">
+ <label className="relative mx-2 mb-2 block">
+ <Search aria-hidden className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search members"
+ className="pl-9"
+ />
+ </label>
+ {filtered.length === 0 ? (
+ <p className="py-4 text-center text-sm text-muted-foreground">
+ {query ? "No matches." : "Everyone is already here."}
+ </p>
+ ) : (
+ filtered.map((m) => (
+ <div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">
+ <Avatar label={m.avatar || m.name || ""} seed={m.userId} size={32} />
+ <div className="min-w-0 flex-1 truncate text-sm font-medium">{m.name ?? "Unknown"}</div>
+ <Button size="sm" disabled={addPending} onClick={() => add(m.userId)}>
+ Add
+ </Button>
+ </div>
+ ))
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/web/src/components/community/channel-add-members-dialog.tsx b/src/web/src/components/community/channel-add-members-dialog.tsx
new file mode 100644
index 000000000..118227aee
--- /dev/null
+++ b/src/web/src/components/community/channel-add-members-dialog.tsx
@@ -0,0 +1,50 @@
+"use client"
+
+import { toast } from "sonner"
+import { AddMembersDialog } from "./add-members-dialog"
+import {
+ useAddableMembers,
+ useAddChannelMember,
+} from "@/hooks/community/use-channel-members"
+
+/**
+ * Channel/post add-members dialog: a thin wrapper that resolves the addable
+ * server members (not-yet-in-channel) and wires the add mutation, then renders
+ * the shared `AddMembersDialog`. Add-only — the current roster and its
+ * remove/leave controls live in the Members drawer's row right-click menu.
+ */
+export function ChannelAddMembersDialog({
+ channelId,
+ channelName,
+ onClose,
+}: {
+ channelId: string
+ channelName: string
+ onClose: () => void
+}) {
+ const { members: addable } = useAddableMembers(channelId)
+ const addMember = useAddChannelMember(channelId)
+
+ const candidates = addable.map((m) => ({
+ userId: m.userId,
+ name: m.name ?? null,
+ avatar: m.avatar,
+ }))
+
+ return (
+ <AddMembersDialog
+ title={`Add members to /${channelName}`}
+ subtitle="Added members can see and post in this channel."
+ candidates={candidates}
+ addPending={addMember.isPending}
+ onAdd={async (userId) => {
+ try {
+ await addMember.mutateAsync(userId)
+ } catch (err) {
+ toast(err instanceof Error ? err.message : "Couldn't add member")
+ }
+ }}
+ onClose={onClose}
+ />
+ )
+}
diff --git a/src/web/src/components/community/channel-members-dialog.tsx b/src/web/src/components/community/channel-members-dialog.tsx
deleted file mode 100644
index 0e373e0ce..000000000
--- a/src/web/src/components/community/channel-members-dialog.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-"use client"
-
-import { useMemo, useState } from "react"
-import { Search, X } from "lucide-react"
-import { toast } from "sonner"
-import { Dialog, DialogContent } from "@/components/ui/dialog"
-import { Input } from "@/components/ui/input"
-import { Button } from "@/components/ui/button"
-import { Skeleton } from "@/components/ui/skeleton"
-import { Avatar } from "./avatar"
-import {
- useChannelMembers,
- useAddableMembers,
- useAddChannelMember,
- useRemoveChannelMember,
-} from "@/hooks/community/use-channel-members"
-
-/**
- * Manage the roster of a private-category channel: current members (creator
- * locked, everyone else removable) plus a picker of server members not yet in
- * the channel. Adding grants read/post access immediately; removing evicts.
- */
-export function ChannelMembersDialog({
- channelId,
- channelName,
- serverId: _serverId,
- onClose,
-}: {
- channelId: string
- channelName: string
- serverId: string
- onClose: () => void
-}) {
- const { members, isLoading: membersLoading } = useChannelMembers(channelId)
- const { members: addable, isLoading: addableLoading } = useAddableMembers(channelId)
- const addMember = useAddChannelMember(channelId)
- const removeMember = useRemoveChannelMember(channelId)
- const [query, setQuery] = useState("")
-
- const filteredAddable = useMemo(() => {
- const q = query.trim().toLowerCase()
- if (!q) return addable
- return addable.filter((m) => (m.name ?? "").toLowerCase().includes(q))
- }, [addable, query])
-
- const onAdd = async (userId: string) => {
- try {
- await addMember.mutateAsync(userId)
- } catch (err) {
- toast(err instanceof Error ? err.message : "Couldn't add member")
- }
- }
-
- const onRemove = async (userId: string) => {
- try {
- await removeMember.mutateAsync(userId)
- } catch (err) {
- toast(err instanceof Error ? err.message : "Couldn't remove member")
- }
- }
-
- return (
- <Dialog open onOpenChange={(o) => { if (!o) onClose() }}>
- <DialogContent className="flex max-h-[80vh] w-full flex-col gap-0 p-0 sm:max-w-md">
- <header className="border-b border-border px-4 py-3">
- <h2 className="truncate text-sm font-semibold">Members of /{channelName}</h2>
- <p className="text-xs text-muted-foreground">
- Only these members and admins can see and post in this channel.
- </p>
- </header>
-
- <div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar px-2 py-2">
- {membersLoading && members.length === 0 ? (
- <div className="space-y-2 px-2">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3">
- <Skeleton className="size-8 rounded-full" />
- <Skeleton className="h-3 w-32 rounded" />
- </div>
- ))}
- </div>
- ) : (
- members.map((m) => (
- <div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">
- <Avatar label={m.avatar || m.name || ""} seed={m.userId} size={32} />
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">
- {m.name ?? "Unknown"}
- {m.isCreator && (
- <span className="ml-2 text-xs font-normal text-muted-foreground">Creator</span>
- )}
- </div>
- </div>
- {!m.isCreator && (
- <button
- onClick={() => onRemove(m.userId)}
- disabled={removeMember.isPending}
- className="grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed"
- aria-label={`Remove ${m.name ?? "member"}`}
- title="Remove member"
- >
- <X className="size-4" />
- </button>
- )}
- </div>
- ))
- )}
- </div>
-
- <footer className="border-t border-border px-4 py-3">
- <div className="mb-2 text-xs font-medium text-muted-foreground">Add members</div>
- <label className="relative block">
- <Search aria-hidden className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder="Search members"
- className="pl-9"
- />
- </label>
- <div className="mt-2 max-h-48 overflow-y-auto thin-scrollbar">
- {addableLoading && addable.length === 0 ? (
- <div className="space-y-2 py-2">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center gap-3">
- <Skeleton className="size-8 rounded-full" />
- <Skeleton className="h-3 w-28 rounded" />
- </div>
- ))}
- </div>
- ) : filteredAddable.length === 0 ? (
- <p className="py-4 text-center text-sm text-muted-foreground">
- {addable.length === 0
- ? "Everyone in the server is already here."
- : "No matches."}
- </p>
- ) : (
- filteredAddable.map((m) => (
- <div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">
- <Avatar label={m.avatar || m.name || ""} seed={m.userId} size={32} />
- <div className="min-w-0 flex-1 truncate text-sm font-medium">{m.name ?? "Unknown"}</div>
- <Button size="sm" disabled={addMember.isPending} onClick={() => onAdd(m.userId)}>
- Add
- </Button>
- </div>
- ))
- )}
- </div>
- </footer>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsx
index 27e71b38f..58ff98c07 100644
--- a/src/web/src/components/community/channel-sidebar.tsx
+++ b/src/web/src/components/community/channel-sidebar.tsx
@@ -16,7 +16,7 @@ import { CreateCategoryDialog } from "./create-category-dialog"
import { CategorySettingsDialog } from "./category-settings-dialog"
import { catId, catOf, isCat, type ChannelTree } from "./use-channel-tree"
import { InviteDialog } from "./invite-dialog"
-import { ChannelMembersDialog } from "./channel-members-dialog"
+import { ChannelAddMembersDialog } from "./channel-add-members-dialog"
import { ServerCrumb } from "./channel-header"
import type { Channel, SettingsSection } from "./_types"
import type { ChannelType } from "@alook/shared"
@@ -316,10 +316,9 @@ export const ChannelSidebar = memo(function ChannelSidebar({
/>
)}
{dialog?.kind === "manage-members" && serverId && (
- <ChannelMembersDialog
+ <ChannelAddMembersDialog
channelId={dialog.channelId}
channelName={dialog.channelName}
- serverId={serverId}
onClose={() => setDialog(null)}
/>
)}
diff --git a/src/web/src/components/community/community-panel-sheet.tsx b/src/web/src/components/community/community-panel-sheet.tsx
index ae65c4de8..1cc56dd08 100644
--- a/src/web/src/components/community/community-panel-sheet.tsx
+++ b/src/web/src/components/community/community-panel-sheet.tsx
@@ -3,7 +3,7 @@
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"
import { useSheetResize, SheetResizeHandle } from "@/components/ui/sheet-resize-handle"
import { RightPanelContent } from "./right-panel"
-import type { RightPanel, Member, Role, Msg, Thread, OpenProfile } from "./_types"
+import type { RightPanel, Member, Role, Msg, Thread, OpenProfile, MemberManageContext } from "./_types"
// Sheet-based right panel for the community channel UI.
// Renders the channel's threads / pinned / members / search panel as a non-modal Sheet:
@@ -19,6 +19,8 @@ export function CommunityPanelSheet({
membersHasMore,
onLoadMoreMembers,
onSearchMembers,
+ onAddMember,
+ manageContext,
pinned,
pinnedLoading,
searchResults,
@@ -42,6 +44,8 @@ export function CommunityPanelSheet({
membersHasMore?: boolean
onLoadMoreMembers?: () => void
onSearchMembers?: (q: string) => void
+ onAddMember?: () => void
+ manageContext?: MemberManageContext
pinned: Msg[]
pinnedLoading?: boolean
searchResults: Msg[]
@@ -80,6 +84,8 @@ export function CommunityPanelSheet({
membersHasMore={membersHasMore}
onLoadMoreMembers={onLoadMoreMembers}
onSearchMembers={onSearchMembers}
+ onAddMember={onAddMember}
+ manageContext={manageContext}
pinned={pinned}
pinnedLoading={pinnedLoading}
searchResults={searchResults}
diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsx
index a4782a39a..2eabe974d 100644
--- a/src/web/src/components/community/member-list.tsx
+++ b/src/web/src/components/community/member-list.tsx
@@ -2,7 +2,7 @@
import { useEffect, useMemo, useRef, useState } from "react"
import { useVirtualizer } from "@tanstack/react-virtual"
-import { Shield, UserMinus, Check, Search } from "lucide-react"
+import { Shield, UserMinus, Check, Search, UserPlus, LogOut } from "lucide-react"
import {
ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator,
ContextMenuSub, ContextMenuSubTrigger, ContextMenuSubContent,
@@ -12,7 +12,7 @@ import { Input } from "@/components/ui/input"
import { Avatar } from "./avatar"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { hasStatus } from "./status-presets"
-import type { Member, Role, OpenProfile } from "./_types"
+import type { Member, Role, OpenProfile, MemberManageContext } from "./_types"
import { canManageServer } from "./_types"
const SETTABLE_ROLES: Role[] = ["admin", "member"]
@@ -87,6 +87,8 @@ export function MemberList({
loadingMore,
onLoadMore,
onSearch,
+ onAddMember,
+ manageContext,
myRole,
onOpenProfile,
onSetRole,
@@ -98,6 +100,12 @@ export function MemberList({
loadingMore?: boolean
onLoadMore?: () => void
onSearch?: (q: string) => void
+ onAddMember?: () => void
+ // When set, rows are a private channel/post roster or a thread's participants:
+ // the right-click menu offers "Leave" on the viewer's own row and "Remove" on
+ // other explicit members (creator only), instead of the server-scoped
+ // Role/Kick menu. Presence of this prop switches the row menu.
+ manageContext?: MemberManageContext
myRole?: Role
onOpenProfile?: OpenProfile
onSetRole?: (name: string, role: Role) => void
@@ -165,15 +173,30 @@ export function MemberList({
onConfirm={() => { if (kickTarget) onKick?.(kickTarget); setKickTarget(null) }}
/>
<aside className="flex h-full flex-col bg-background">
- {onSearch && (
- <div className="relative shrink-0 border-b border-border px-4 py-3">
- <Search className="absolute left-6 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- className="h-9 pl-8"
- placeholder="Search members"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- />
+ {(onSearch || onAddMember) && (
+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-3">
+ {onSearch && (
+ <div className="relative flex-1">
+ <Search className="absolute left-2 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ className="h-9 pl-8"
+ placeholder="Search members"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ )}
+ {onAddMember && (
+ <button
+ type="button"
+ onClick={onAddMember}
+ className="grid size-9 shrink-0 place-items-center rounded-md border border-border text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ aria-label="Add members"
+ title="Add members"
+ >
+ <UserPlus className="size-4" />
+ </button>
+ )}
</div>
)}
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto thin-scrollbar">
@@ -209,6 +232,7 @@ export function MemberList({
onOpenProfile={onOpenProfile}
onSetRole={onSetRole}
onKick={setKickTarget}
+ manageContext={manageContext}
/>
)}
</div>
@@ -241,6 +265,7 @@ function MemberRow({
onOpenProfile,
onSetRole,
onKick,
+ manageContext,
}: {
mem: Member
canManage: boolean
@@ -252,6 +277,7 @@ function MemberRow({
onOpenProfile?: OpenProfile
onSetRole?: (name: string, role: Role) => void
onKick: (name: string) => void
+ manageContext?: MemberManageContext
}) {
const button = (
<button
@@ -272,6 +298,44 @@ function MemberRow({
</div>
</button>
)
+
+ // Private channel/post roster or thread participant row: Leave (self) /
+ // Remove (unit creator on other explicit members). Replaces the server-scoped
+ // Role/Kick menu — eviction here is unit membership/participation, not a
+ // server kick. Remove is creator-only (admins have no content privilege); the
+ // creator's own row is locked (no Leave, never removable).
+ if (manageContext) {
+ const isSelf = mem.userId === manageContext.viewerUserId
+ // Self may leave unless they're the creator (owners keep the unit).
+ const canLeave = isSelf && !mem.isCreator
+ // Creator may remove other EXPLICIT members, but never the creator row.
+ // `source` is undefined for thread participants (all real rows) → treat as
+ // removable; for channel/post only explicit rows are removable.
+ const canRemove =
+ !isSelf &&
+ manageContext.viewerIsCreator &&
+ !mem.isCreator &&
+ (mem.source === undefined || mem.source === "explicit")
+ if (!canLeave && !canRemove) return button
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger render={button} />
+ <ContextMenuContent className="w-48">
+ <div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">{mem.name}</div>
+ {canLeave ? (
+ <ContextMenuItem onClick={() => manageContext.onLeave(mem.userId)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive">
+ <LogOut className="size-4" /> Leave
+ </ContextMenuItem>
+ ) : (
+ <ContextMenuItem onClick={() => manageContext.onRemove(mem.userId)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive">
+ <UserMinus className="size-4" /> Remove {mem.name}
+ </ContextMenuItem>
+ )}
+ </ContextMenuContent>
+ </ContextMenu>
+ )
+ }
+
if (!hasMemberMenu(canManage, mem.role)) return button
return (
<ContextMenu>
diff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/right-panel.tsx
index 155556637..23f06d2dd 100644
--- a/src/web/src/components/community/right-panel.tsx
+++ b/src/web/src/components/community/right-panel.tsx
@@ -8,13 +8,14 @@ import { PanelShell } from "./panel-shell"
import { MemberList } from "./member-list"
import { Message } from "./message"
import { formatRelativeTime } from "./format-time"
-import type { RightPanel, Member, Role, Msg, RenderMsg, Thread, OpenProfile } from "./_types"
+import type { RightPanel, Member, Role, Msg, RenderMsg, Thread, OpenProfile, MemberManageContext } from "./_types"
// Right-panel content router — members / pinned / search / threads. Data via props.
// Always wraps the active section in PanelShell — the surrounding Sheet provides the
// outer frame and its own close button, so we don't need a panel-level close affordance.
export function RightPanelContent({
kind, members, membersLoading, membersLoadingMore, membersHasMore, onLoadMoreMembers, onSearchMembers,
+ onAddMember, manageContext,
pinned, pinnedLoading, searchResults, searchQuery,
threads, threadsLoading, showSearchInput = true, onOpenThread, onOpenProfile,
onSetRole, onKickMember, myRole, onJumpToMessage, onSearch,
@@ -26,6 +27,8 @@ export function RightPanelContent({
membersHasMore?: boolean
onLoadMoreMembers?: () => void
onSearchMembers?: (q: string) => void
+ onAddMember?: () => void
+ manageContext?: MemberManageContext
pinned: Msg[]
pinnedLoading?: boolean
searchResults: Msg[]
@@ -51,6 +54,8 @@ export function RightPanelContent({
loadingMore={membersLoadingMore}
onLoadMore={onLoadMoreMembers}
onSearch={onSearchMembers}
+ onAddMember={onAddMember}
+ manageContext={manageContext}
myRole={myRole}
onOpenProfile={onOpenProfile}
onSetRole={onSetRole}
diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsx
index e3df2567d..78074fbdc 100644
--- a/src/web/src/components/community/thread-opener.tsx
+++ b/src/web/src/components/community/thread-opener.tsx
@@ -1,6 +1,6 @@
"use client"
-import { MessagesSquare, FileText, Download } from "lucide-react"
+import { MessagesSquare, FileText, Download, ArrowUpRight } from "lucide-react"
import { Avatar } from "./avatar"
import { MessageBody } from "./message-body"
import { attachmentAspectRatio } from "./message"
@@ -30,11 +30,15 @@ export function ThreadOpener({
onOpenProfile,
onPreviewImage,
onDownloadFile,
+ onJump,
}: {
parentMessageId: string
onOpenProfile?: OpenProfile
onPreviewImage?: (url: string) => void
onDownloadFile?: (url: string) => void
+ // Jump to the parent message in its channel. When provided, a hover-revealed
+ // "Jump" button appears in the opener's top-right.
+ onJump?: () => void
}) {
const { message: msg, isLoading, isError } = useMessage(parentMessageId)
@@ -58,12 +62,25 @@ export function ThreadOpener({
const avatarLabel = msg.authorAvatar || avatarInitial(msg.authorName)
return (
- <div>
+ <div className="group relative">
<div className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground">
<MessagesSquare className="size-3.5" />
<span>Thread started from</span>
</div>
+ {onJump && (
+ <button
+ type="button"
+ onClick={onJump}
+ className="absolute right-0 top-0 flex h-7 items-center gap-1 rounded-md px-2 text-xs font-medium text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none group-hover:opacity-100"
+ aria-label="Jump to message"
+ title="Jump to message"
+ >
+ <ArrowUpRight className="size-3.5" />
+ Jump
+ </button>
+ )}
+
<div className="flex gap-3">
<button
onClick={(e) => onOpenProfile?.(msg.authorName, e, undefined, msg.authorId)}
diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.ts
index 3b81602a6..0abc1f342 100644
--- a/src/web/src/hooks/community/use-channel-members.ts
+++ b/src/web/src/hooks/community/use-channel-members.ts
@@ -3,13 +3,24 @@
import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
+import type { CommunityRole } from "@alook/shared"
+// Canonical member shape (superset of the pre-audience roster). `source` tags
+// why the user is in the channel: "explicit" (added member or creator),
+// "inherited" (public-channel server member), or "admin" (server admin/owner).
+// Only `source === "explicit" && !isCreator` rows are removable.
export type ChannelMember = {
+ id: string
userId: string
- name: string | null
- discriminator: string | null
+ name: string
+ discriminator: string | undefined
avatar: string
- addedAt: string
+ sub: string
+ role: CommunityRole
+ status: "online" | "offline"
+ statusEmoji: string | null
+ statusText: string
+ source: "explicit" | "inherited" | "admin"
isCreator: boolean
}
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 62fc953a5..a78154ab8 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -715,6 +715,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
queryClient.removeQueries({ queryKey: communityKeys.forumPosts(event.channelId) })
}
void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+ // Refetch the channel roster so an open private-channel Members drawer
+ // (and the manage-members dialog) reflect the add/remove live.
+ void queryClient.invalidateQueries({ queryKey: communityKeys.channelMembers(event.channelId) })
+ // The addable-members candidate pool is the complement of the roster —
+ // 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) })
return
}
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 63c1c093f..9a86ec0f2 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -162,6 +162,14 @@ type MessagesOpts = {
* newest-mode. A string = fetch `?anchor=<id>` on the first page.
*/
lastReadMessageId?: string | null
+ /**
+ * Explicit jump target (e.g. a cross-channel "jump to message"). Takes
+ * precedence over `lastReadMessageId` so the channel opens centered on the
+ * requested message rather than the viewer's unread marker. When set, it
+ * also satisfies the enable-gate on its own — a jump firing before the
+ * read snapshot resolves must NOT leave the query disabled.
+ */
+ anchorMessageId?: string | null
}
// Shared pagination + reducer used by both channel and DM hooks. Kept inline
@@ -177,9 +185,13 @@ function useMessagesInner(
// `undefined` = anchor snapshot is still resolving; gate the query on it
// being a resolved value (string OR null). Owners without a snapshot
- // (currently DM) pass `null` explicitly.
- const anchorResolved = opts?.lastReadMessageId !== undefined
- const anchorId = opts?.lastReadMessageId ?? null
+ // (currently DM) pass `null` explicitly. An explicit `anchorMessageId`
+ // (jump target) satisfies the gate on its own — a jump must not wait on the
+ // read snapshot.
+ const anchorResolved =
+ opts?.anchorMessageId != null || opts?.lastReadMessageId !== undefined
+ // Jump target wins over the read pointer for the initial anchor window.
+ const anchorId = opts?.anchorMessageId ?? opts?.lastReadMessageId ?? null
const enabled = !!scopeId && anchorResolved
// Force-newest override — flipped by `jumpToPresent`. Held in state so
diff --git a/src/web/src/hooks/community/use-thread-participants.ts b/src/web/src/hooks/community/use-thread-participants.ts
new file mode 100644
index 000000000..d47a85ce1
--- /dev/null
+++ b/src/web/src/hooks/community/use-thread-participants.ts
@@ -0,0 +1,61 @@
+"use client"
+
+import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+
+export type ThreadParticipant = {
+ userId: string
+ name: string | null
+ discriminator: string | null
+ avatar: string
+ source: "mention" | "spoke" | "added"
+}
+
+const EMPTY: readonly ThreadParticipant[] = Object.freeze([])
+
+/** A thread's notify participants. */
+export function useThreadParticipants(
+ channelId: string,
+ enabled = true,
+): UseQueryResult<{ participants: ThreadParticipant[] }> & { participants: ThreadParticipant[] } {
+ const query = useQuery({
+ queryKey: communityKeys.threadParticipants(channelId),
+ queryFn: () =>
+ apiFetch<{ participants: ThreadParticipant[] }>(
+ `/api/community/channels/${encodeURIComponent(channelId)}/participants`,
+ ),
+ enabled: enabled && !!channelId,
+ })
+ return { ...query, participants: query.data?.participants ?? (EMPTY as ThreadParticipant[]) }
+}
+
+/** Any participant adds a parent-channel member to the thread. */
+export function useAddThreadParticipant(channelId: string) {
+ const qc = useQueryClient()
+ return useMutation({
+ mutationFn: (userId: string) =>
+ apiFetch(`/api/community/channels/${encodeURIComponent(channelId)}/participants`, {
+ method: "POST",
+ body: JSON.stringify({ userId }),
+ }),
+ onSuccess: () => {
+ void qc.invalidateQueries({ queryKey: communityKeys.threadParticipants(channelId) })
+ },
+ })
+}
+
+/** Leave a thread (remove your own participation, or the creator removes someone). */
+export function useRemoveThreadParticipant(channelId: string) {
+ const qc = useQueryClient()
+ return useMutation({
+ mutationFn: (userId: string) =>
+ apiFetch(
+ `/api/community/channels/${encodeURIComponent(channelId)}/participants/${encodeURIComponent(userId)}`,
+ { method: "DELETE" },
+ ),
+ onSuccess: () => {
+ void qc.invalidateQueries({ queryKey: communityKeys.threadParticipants(channelId) })
+ },
+ })
+}
diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.ts
index 1faaae165..522c8050a 100644
--- a/src/web/src/lib/community/fanout.test.ts
+++ b/src/web/src/lib/community/fanout.test.ts
@@ -25,12 +25,16 @@ vi.mock("@alook/shared", async () => {
},
communityChannel: {
getChannel: (...a: unknown[]) => mockGetChannel(...a),
+ getChannelType: (...a: unknown[]) => mockGetChannelType(...a),
isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),
getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),
},
communityMembersResolver: {
resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),
},
+ communityThread: {
+ listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),
+ },
communityDm: {
getDM: (...a: unknown[]) => mockGetDM(...a),
},
@@ -64,6 +68,9 @@ const mockGetDM = vi.fn()
const mockGetCoMemberUserIds = vi.fn()
const mockGetFriendUserIds = vi.fn()
const mockResolveScopeMemberUserIds = vi.fn(() => [] as string[])
+// Default: non-thread channel → fan-out uses the shared resolver path.
+const mockGetChannelType = vi.fn(() => "text" as string | null)
+const mockListThreadParticipantUserIds = vi.fn(() => [] as string[])
import {
fanOutToServerMembers,
@@ -79,6 +86,10 @@ describe("fanOutToServerMembers", () => {
vi.clearAllMocks()
mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
mockBroadcastToUser.mockResolvedValue(undefined)
+ // Default to a non-thread channel so fan-out uses the shared resolver path;
+ // the thread test overrides this. (clearAllMocks resets call history, not
+ // the resolved-value impl, so re-assert the default each test.)
+ mockGetChannelType.mockResolvedValue("text")
})
it("resolves recipients via listMemberUserIds (not listMembers) and skips excludeUserId", async () => {
@@ -136,6 +147,22 @@ describe("fanOutToServerMembers", () => {
expect(mockListMembers).not.toHaveBeenCalled()
expect(mockBroadcastToUser).toHaveBeenCalledTimes(2)
})
+
+ it("fanOutToChannel routes a THREAD to its participant set (not the channel audience)", async () => {
+ mockGetChannelType.mockResolvedValue("thread")
+ mockListThreadParticipantUserIds.mockResolvedValue(["u1", "u2"])
+
+ await fanOutToChannel("t1", {
+ type: WS_EVENTS.MESSAGE_CREATE,
+ channelId: "t1",
+ message: {} as never,
+ } as never)
+
+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "t1")
+ // Thread fan-out must NOT fall back to the channel-audience resolver.
+ expect(mockResolveScopeMemberUserIds).not.toHaveBeenCalled()
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(2)
+ })
})
describe("fanOutStatusUpdate", () => {
@@ -143,6 +170,10 @@ describe("fanOutStatusUpdate", () => {
vi.clearAllMocks()
mockGetCloudflareContext.mockImplementation(() => ({ env: { DB: {} } }))
mockBroadcastToUser.mockResolvedValue(undefined)
+ // Default to a non-thread channel so fan-out uses the shared resolver path;
+ // the thread test overrides this. (clearAllMocks resets call history, not
+ // the resolved-value impl, so re-assert the default each test.)
+ mockGetChannelType.mockResolvedValue("text")
})
it("broadcasts to the deduped union of co-members and friends", async () => {
diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.ts
index 4b623819c..25540a8d9 100644
--- a/src/web/src/lib/community/fanout.ts
+++ b/src/web/src/lib/community/fanout.ts
@@ -41,11 +41,22 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<s
}
/**
- * Resolves the recipient set for a channel event. The public/private split
- * (and thread/post parent-climbing) lives in the shared member resolver — this
- * is a thin delegate so fan-out, the WS DO, and any future surface all agree.
+ * Resolves the recipient set for a channel event.
+ *
+ * - THREAD (`type="thread"`) → the thread's NOTIFY set (participants with
+ * `muted=0`). A thread is the notification dimension: message events reach
+ * only its participants, NOT the whole parent channel (and NOT admins, who
+ * are never auto-participants). Nested-membership model.
+ * - channel / post / forum → the access audience via the shared resolver
+ * (public/private split + post-own-roster / forum-union).
+ *
+ * The split lives here so fan-out and bot-wake use the same recipient set.
*/
async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {
+ const rows = await queries.communityChannel.getChannelType(db, channelId)
+ if (rows === "thread") {
+ return queries.communityThread.listThreadParticipantUserIds(db, channelId)
+ }
return queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
scope: "channel",
scopeId: channelId,
diff --git a/src/web/src/lib/community/member-payload.test.ts b/src/web/src/lib/community/member-payload.test.ts
new file mode 100644
index 000000000..33775a920
--- /dev/null
+++ b/src/web/src/lib/community/member-payload.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from "vitest"
+import { mapMemberForApi, type MemberRow } from "./member-payload"
+
+function row(overrides: Partial<MemberRow> = {}): MemberRow {
+ return {
+ id: "m1",
+ userId: "u1",
+ role: "member",
+ nickname: null,
+ userName: "Ann",
+ userImage: null,
+ discriminator: "0001",
+ statusEmoji: null,
+ statusText: null,
+ ...overrides,
+ }
+}
+
+describe("mapMemberForApi", () => {
+ it("produces the canonical display shape with sub, defaults, and nickname fallback", () => {
+ const m = mapMemberForApi(row({ nickname: "Annie" }), "viewer")
+ expect(m).toMatchObject({
+ id: "m1",
+ userId: "u1",
+ name: "Annie", // nickname wins over userName
+ discriminator: "0001",
+ status: "offline",
+ sub: "",
+ role: "member",
+ statusEmoji: null,
+ statusText: "",
+ })
+ // No opt-in flags → no isCreator/source/isBot fields.
+ expect("isCreator" in m).toBe(false)
+ expect("source" in m).toBe(false)
+ expect("isBot" in m).toBe(false)
+ })
+
+ it("marks the viewer's own row online", () => {
+ expect(mapMemberForApi(row({ userId: "viewer" }), "viewer").status).toBe("online")
+ })
+
+ it("falls back to userName then avatarInitial when nickname/image absent", () => {
+ const m = mapMemberForApi(row({ nickname: null, userName: "Zed", userImage: null }), "viewer")
+ expect(m.name).toBe("Zed")
+ expect(m.avatar).toBeTruthy()
+ })
+
+ it("botGating exposes isBot/ownerUserId only on the viewer's own bot", () => {
+ const own = mapMemberForApi(
+ row({ userId: "b1", userIsBot: true, userOwnerUserId: "viewer" }),
+ "viewer",
+ { botGating: true },
+ )
+ expect(own.isBot).toBe(true)
+ expect(own.ownerUserId).toBe("viewer")
+
+ const other = mapMemberForApi(
+ row({ userId: "b2", userIsBot: true, userOwnerUserId: "someone_else" }),
+ "viewer",
+ { botGating: true },
+ )
+ expect(other.isBot).toBeUndefined()
+ expect(other.ownerUserId).toBeUndefined()
+ })
+
+ it("without botGating, never emits isBot even for an own bot (search parity)", () => {
+ const m = mapMemberForApi(
+ row({ userId: "b1", userIsBot: true, userOwnerUserId: "viewer" }),
+ "viewer",
+ )
+ expect(m.isBot).toBeUndefined()
+ expect(m.ownerUserId).toBeUndefined()
+ })
+
+ it("passes through isCreator and source when provided", () => {
+ const m = mapMemberForApi(row(), "viewer", { isCreator: true, source: "explicit" })
+ expect(m.isCreator).toBe(true)
+ expect(m.source).toBe("explicit")
+ })
+})
diff --git a/src/web/src/lib/community/member-payload.ts b/src/web/src/lib/community/member-payload.ts
new file mode 100644
index 000000000..cff47b39b
--- /dev/null
+++ b/src/web/src/lib/community/member-payload.ts
@@ -0,0 +1,72 @@
+import { avatarInitial } from "./avatar"
+
+// Canonical row shape the member-list queries produce. Bot columns
+// (`userIsBot`/`userOwnerUserId`) are optional — `searchMembers` doesn't select
+// them, so search callers pass rows without them (and `botGating: false`).
+export type MemberRow = {
+ id: string
+ userId: string
+ role: string | null
+ nickname: string | null
+ userName: string | null
+ userImage: string | null
+ discriminator: string | null
+ statusEmoji: string | null
+ statusText: string | null
+ userIsBot?: boolean
+ userOwnerUserId?: string | null
+}
+
+export type MappedMember = {
+ id: string
+ userId: string
+ name: string
+ discriminator: string | undefined
+ avatar: string
+ status: "online" | "offline"
+ sub: string
+ role: string
+ statusEmoji: string | null
+ statusText: string
+ isCreator?: boolean
+ source?: string
+ isBot?: true
+ ownerUserId?: string
+}
+
+// The single canonical member-DTO mapper shared by every UI member-list
+// endpoint. Centralizes the `nickname ?? userName` display fallback, the
+// `avatarInitial` default, the self-→`online` status guess, the constant
+// `sub: ""` (the client `Member` type requires `sub: string`), and the
+// owner-scoped `isBot`/`ownerUserId` projection.
+//
+// `botGating` is opt-in: only the server-members LIST route applies the
+// owner-scoped `isBot`/`ownerUserId` projection. The search route never emitted
+// bot fields (and doesn't select the columns), so it passes `botGating: false`
+// to stay byte-identical.
+export function mapMemberForApi(
+ row: MemberRow,
+ viewerUserId: string,
+ opts?: { botGating?: boolean; isCreator?: boolean; source?: string },
+): MappedMember {
+ const display = row.nickname ?? row.userName ?? ""
+ const isOwnBot =
+ !!opts?.botGating &&
+ row.userIsBot === true &&
+ row.userOwnerUserId === viewerUserId
+ return {
+ id: row.id,
+ userId: row.userId,
+ name: display,
+ discriminator: row.discriminator ?? undefined,
+ avatar: row.userImage ?? avatarInitial(display),
+ status: row.userId === viewerUserId ? "online" : "offline",
+ sub: "",
+ role: row.role ?? "member",
+ statusEmoji: row.statusEmoji ?? null,
+ statusText: row.statusText ?? "",
+ ...(opts?.isCreator !== undefined ? { isCreator: opts.isCreator } : {}),
+ ...(opts?.source !== undefined ? { source: opts.source } : {}),
+ ...(isOwnBot ? { isBot: true as const, ownerUserId: row.userOwnerUserId! } : {}),
+ }
+}
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 7bb2046ca..beda3c312 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
+const mockGetMessageInScope = vi.fn()
const mockGetUserInternal = vi.fn()
const mockCreateAttachment = vi.fn()
const mockListMembers = vi.fn()
@@ -10,6 +11,8 @@ const mockCreateMentions = vi.fn()
const mockGetChannel = vi.fn()
const mockIsChannelPrivate = vi.fn(() => false)
const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])
+const mockCreateChannelMember = vi.fn()
+const mockAddThreadParticipants = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -19,6 +22,7 @@ vi.mock("@alook/shared", async () => {
communityMessage: {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
+ getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),
},
communityAttachment: {
createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),
@@ -34,6 +38,10 @@ vi.mock("@alook/shared", async () => {
getChannel: (...a: unknown[]) => mockGetChannel(...a),
isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),
getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),
+ createChannelMember: (...a: unknown[]) => mockCreateChannelMember(...a),
+ },
+ communityThread: {
+ addThreadParticipants: (...a: unknown[]) => mockAddThreadParticipants(...a),
},
user: {
getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
@@ -44,9 +52,11 @@ vi.mock("@alook/shared", async () => {
const mockFanOutToChannel = vi.fn()
const mockFanOutToDM = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
vi.mock("./fanout", () => ({
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
fanOutToDM: (...a: unknown[]) => mockFanOutToDM(...a),
+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
const mockBroadcastToUser = vi.fn()
@@ -344,3 +354,195 @@ describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
})
})
})
+
+describe("createCommunityMessage — private-channel mention scoping (no auto-add)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })
+ mockFanOutToChannel.mockResolvedValue(undefined)
+ mockFanOutToDM.mockResolvedValue(undefined)
+ mockBroadcastToUser.mockResolvedValue(undefined)
+ mockBroadcastToUserSafe.mockResolvedValue(undefined)
+ mockGetUserInternal.mockResolvedValue({ id: "author_1", isBot: false, deletedAt: null })
+ mockListMembers.mockResolvedValue([
+ { userId: "author_1", userName: "Author", discriminator: "1111" },
+ { userId: "bob_1", userName: "Bob", discriminator: "0001" },
+ { userId: "cara_1", userName: "Cara", discriminator: "0002" },
+ ])
+ mockIsChannelPrivate.mockResolvedValue(true)
+ // Audience = author + Cara. Bob is a server member but NOT in the channel.
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])
+ })
+
+ it("drops an @mention of a non-member: no auto-add, no CHANNEL_MEMBER_ADD, no mention row", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "hey @Bob" },
+ })
+
+ // Channel roster is NOT expanded by a mention.
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
+ // Bob was outside the audience → dropped → no mention row.
+ expect(mockCreateMentions).not.toHaveBeenCalled()
+ })
+
+ it("keeps an @mention of an existing channel member", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "hey @Cara" },
+ })
+
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {
+ messageId: "msg_1",
+ userIds: ["cara_1"],
+ kind: "mention",
+ })
+ })
+
+ it("@everyone/@here is clamped to the audience (author excluded → only Cara)", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ content: "@everyone hi", mentionType: "everyone" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "@everyone hi", mentionType: "everyone" },
+ })
+
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ // Bob (non-member) not notified; only the in-audience Cara.
+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {
+ messageId: "msg_1",
+ userIds: ["cara_1"],
+ kind: "mention",
+ })
+ })
+
+ it("thread: author joins as 'spoke'; a non-audience mention is dropped (no channel auto-add)", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob", channelId: "t1" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "srv_1" },
+ body: { content: "hey @Bob" },
+ })
+
+ // Author joins the thread's notify set by speaking (bulk insert; Bob is
+ // outside the parent audience so he's not in the rows).
+ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ { userId: "author_1", source: "spoke" },
+ ])
+ // Bob is outside the (private) parent audience → dropped, no mention row,
+ // and NEVER auto-added to the channel roster.
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ expect(mockCreateMentions).not.toHaveBeenCalled()
+ })
+
+ it("thread: an in-audience @mention joins as a participant + gets a mention row", async () => {
+ // Cara is in the parent audience; add her to it.
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara", channelId: "t1" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "srv_1" },
+ body: { content: "hey @Cara" },
+ })
+
+ // Bulk insert: author (spoke) + Cara (mention).
+ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ { userId: "author_1", source: "spoke" },
+ { userId: "cara_1", source: "mention" },
+ ])
+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {
+ messageId: "msg_1",
+ userIds: ["cara_1"],
+ kind: "mention",
+ })
+ // Thread participation is NOT a channel roster row.
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ })
+
+ it("thread: @everyone notifies the audience but only the author is enrolled as a participant", async () => {
+ // Audience = author + Cara; @everyone should ping Cara once but NOT
+ // subscribe her permanently to the thread (only speaking / an explicit
+ // @mention enrolls a participant).
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])
+ mockGetMessage.mockResolvedValue(messageRow({ content: "@everyone heads up", channelId: "t1", mentionType: "everyone" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "srv_1" },
+ body: { content: "@everyone heads up", mentionType: "everyone" },
+ })
+
+ // Only the author joins the notify set — the mass mention does NOT enroll Cara.
+ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ { userId: "author_1", source: "spoke" },
+ ])
+ // Cara is still notified once by the @everyone (a mention row is written).
+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {
+ messageId: "msg_1",
+ userIds: ["cara_1"],
+ kind: "mention",
+ })
+ })
+
+ it("thread: a direct REPLY under @everyone still enrolls the replied-to user", async () => {
+ // Regression guard: @everyone catches Cara into mentionTargets, and the
+ // 'mention beats reply' dedup strips her from replyTargets. She must still
+ // be enrolled as a participant because the author directly replied to her.
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])
+ mockGetMessageInScope.mockResolvedValue({
+ id: "parent_msg", authorId: "cara_1", authorName: "Cara", content: "prior",
+ })
+ mockGetMessage.mockResolvedValue(
+ messageRow({ content: "@everyone see above", channelId: "t1", mentionType: "everyone", replyToId: "parent_msg" }),
+ )
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "srv_1" },
+ body: { content: "@everyone see above", mentionType: "everyone", replyToId: "parent_msg" },
+ })
+
+ // Author (spoke) + Cara (enrolled via the reply, despite @everyone dedup).
+ expect(mockAddThreadParticipants).toHaveBeenCalledWith({}, "t1", [
+ { userId: "author_1", source: "spoke" },
+ { userId: "cara_1", source: "mention" },
+ ])
+ })
+
+ it("public channel: mention of any server member is kept, no roster row", async () => {
+ mockIsChannelPrivate.mockResolvedValue(false)
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "hey @Bob" },
+ })
+
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ expect(mockCreateMentions).toHaveBeenCalledWith({}, {
+ messageId: "msg_1",
+ userIds: ["bob_1"],
+ kind: "mention",
+ })
+ })
+})
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 140ab7232..f0a8cfc82 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -283,15 +283,38 @@ export async function createCommunityMessage(params: {
// Mention extraction is channel/thread only — DMs have no member roster
// and no @-anyone semantics.
//
- // Split the query by need: broadcast wants userIds only; @-candidate
- // extraction wants (userId, userName) tuples. When both branches fire we
- // still issue a single `listMembers` call — it's a superset of userIds,
- // never double-query.
+ // Candidate scoping: a message can only mention/notify users in the unit's
+ // OWN audience. For a private channel/post/thread that's the (climb-based)
+ // audience — a channel/post can only mention its own members; a thread climbs
+ // to its parent channel's audience. `@everyone`/`@here` and reply targets are
+ // likewise clamped to that audience. There is NO invite-by-mention at the
+ // channel level (roster changes only via owner-add). Public/uncategorized
+ // channels are unchanged (whole-server candidates).
const mentionTargets = new Set<string>()
+ // Subset of `mentionTargets` that came from an EXPLICIT `@user` (not a mass
+ // `@everyone`/`@here`). Only explicit mentions enroll someone as a permanent
+ // thread participant — a broadcast `@everyone` notifies once but must not
+ // subscribe the whole channel/server to every future reply (that would defeat
+ // the notification dimension). See the thread-participation block below.
+ const explicitMentionTargets = new Set<string>()
if (!skipMentions && target.kind !== "dm") {
+ // Resolve the audience up front when private; `null` = public (no clamp).
+ // PERF (accepted): `isChannelPrivate` and `getPrivateChannelAudienceUserIds`
+ // each climb `parentChannelId` for a thread — two parent lookups per message
+ // on the send path. Cheap (indexed id lookups) and not merged to keep both
+ // helpers single-purpose; revisit only if the send path shows up hot.
+ const isPrivate = await queries.communityChannel.isChannelPrivate(db, target.channelId)
+ const audienceIds = isPrivate
+ ? new Set(await queries.communityChannel.getPrivateChannelAudienceUserIds(db, target.channelId))
+ : null
+
const hasAtMention = typeof row.content === "string" && row.content.includes("@")
if (hasAtMention) {
- const members = await queries.communityMember.listMembers(db, target.serverId)
+ const allMembers = await queries.communityMember.listMembers(db, target.serverId)
+ // Scope candidates to the audience when private.
+ const members = audienceIds
+ ? allMembers.filter((m) => audienceIds.has(m.userId))
+ : allMembers
if (mentionType === "everyone" || mentionType === "here") {
for (const m of members) {
if (m.userId !== authorId) mentionTargets.add(m.userId)
@@ -303,32 +326,58 @@ export async function createCommunityMessage(params: {
.map((m) => ({ userId: m.userId, name: m.userName as string, discriminator: m.discriminator }))
for (const id of extractMentionedUserIds(row.content, candidates)) {
mentionTargets.add(id)
+ explicitMentionTargets.add(id)
}
}
} else if (mentionType === "everyone" || mentionType === "here") {
- const userIds = await queries.communityMember.listMemberUserIds(db, target.serverId)
+ const userIds = audienceIds
+ ? [...audienceIds]
+ : await queries.communityMember.listMemberUserIds(db, target.serverId)
for (const uid of userIds) {
if (uid !== authorId) mentionTargets.add(uid)
}
}
+
+ // Reply targets outside the private audience are dropped (a former member
+ // whose message is being replied to shouldn't get a notification for a
+ // channel they can no longer see).
+ if (audienceIds) {
+ for (const id of [...replyTargets]) if (!audienceIds.has(id)) replyTargets.delete(id)
+ }
}
+ // Snapshot the (audience-filtered) reply targets for thread enrollment BEFORE
+ // the mention-row dedup below strips them. A direct reply always enrolls the
+ // replied-to user as a participant — even when a co-occurring `@everyone`
+ // also caught them (in which case they'd otherwise vanish from `replyTargets`
+ // AND be absent from `explicitMentionTargets`).
+ const replyParticipants = new Set(replyTargets)
+
// Mention beats reply — never double-count the same user.
for (const id of mentionTargets) replyTargets.delete(id)
- // Private-channel scoping: a message in a channel inside a PRIVATE category
- // can only mention/reply-notify users in that channel's audience (members ∪
- // creator ∪ admins). Otherwise an @-mention would push private content into
- // a non-member's Mentions tab. Public/uncategorized channels are unchanged.
- if (target.kind !== "dm" && (mentionTargets.size > 0 || replyTargets.size > 0)) {
- const isPrivate = await queries.communityChannel.isChannelPrivate(db, target.channelId)
- if (isPrivate) {
- const audience = new Set(
- await queries.communityChannel.getPrivateChannelAudienceUserIds(db, target.channelId)
- )
- for (const id of [...mentionTargets]) if (!audience.has(id)) mentionTargets.delete(id)
- for (const id of [...replyTargets]) if (!audience.has(id)) replyTargets.delete(id)
+ // Thread participation (notification dimension). A thread's NOTIFY set is its
+ // participant rows — join by:
+ // - speaking: the author becomes a participant (source "spoke").
+ // - @mention: an explicitly mentioned/replied parent-channel member becomes
+ // a participant (source "mention"). `mentionTargets`/`replyTargets` are
+ // already scoped to the parent-channel audience by the block above.
+ // Admins are NOT auto-added — only real participation joins the set. System /
+ // card messages (`skipMentions`) don't add the author.
+ if (target.kind === "thread" && !skipMentions) {
+ const rows: { userId: string; source: "spoke" | "mention" }[] = [
+ { userId: authorId, source: "spoke" },
+ ]
+ // Only EXPLICIT `@user` mentions + reply targets enroll as participants. A
+ // mass `@everyone`/`@here` is in `mentionTargets` (so everyone is notified
+ // once) but NOT in `explicitMentionTargets`, so it doesn't permanently
+ // subscribe the whole channel/server to the thread. `replyParticipants` is
+ // the pre-dedup snapshot so a reply still enrolls even under `@everyone`.
+ for (const id of new Set([...explicitMentionTargets, ...replyParticipants])) {
+ if (id !== authorId) rows.push({ userId: id, source: "mention" })
}
+ // One bulk insert (author + mentioned) instead of N+1 sequential inserts.
+ await queries.communityThread.addThreadParticipants(db, target.channelId, rows)
}
// Mention/reply ROW writes are persistence, not broadcast — they run inline
diff --git a/src/web/src/lib/community/permissions.test.ts b/src/web/src/lib/community/permissions.test.ts
index 31bf575d0..ecd56d3bc 100644
--- a/src/web/src/lib/community/permissions.test.ts
+++ b/src/web/src/lib/community/permissions.test.ts
@@ -51,13 +51,16 @@ function ctxRow(over: Partial<{
isPrivate = false,
isChannelMember = false,
} = over
- const channel = { id: channelId, serverId, parentChannelId, creatorId }
+ const channel = { id: channelId, serverId, type: "text", parentChannelId, parentMessageId: null, creatorId }
return {
channel,
anchor: parentChannelId ? { id: parentChannelId, serverId, parentChannelId: null, creatorId } : channel,
role,
isPrivate,
isChannelMember,
+ // resolveChannelAccessContext now returns the roster-anchor creator flag;
+ // the caller in these tests is always "u1".
+ isCreator: creatorId === "u1",
}
}
@@ -174,11 +177,19 @@ describe("requireChannelAccess", () => {
expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })
})
- it("private channel: admin always has access + canManage", async () => {
+ it("private channel: admin NOT a member/creator is forbidden (no content privilege)", async () => {
resolveChannelAccessContext.mockResolvedValue(
ctxRow({ role: "owner", isPrivate: true, creatorId: "other", isChannelMember: false }),
)
const res = await requireChannelAccess(db, "c1", "u1")
+ expect(res).toEqual({ ok: false, status: 403, error: "forbidden" })
+ })
+
+ it("private channel: admin who IS a member has access + canManage", async () => {
+ resolveChannelAccessContext.mockResolvedValue(
+ ctxRow({ role: "owner", isPrivate: true, creatorId: "other", isChannelMember: true }),
+ )
+ const res = await requireChannelAccess(db, "c1", "u1")
expect(res.ok).toBe(true)
if (res.ok) expect(res.value.canManage).toBe(true)
})
diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.ts
index e1bc81381..76e121abe 100644
--- a/src/web/src/lib/community/permissions.ts
+++ b/src/web/src/lib/community/permissions.ts
@@ -63,6 +63,7 @@ export type ChannelAccess = {
anchor: ChannelAccessContext["anchor"]
member: { role: string | null }
canManage: boolean
+ isCreator: boolean
isPrivate: boolean
}
@@ -71,12 +72,16 @@ export type ChannelAccess = {
* (target + anchor + category privacy + member role + channel-member flag),
* then applies the rule:
* - not a server member → 403
- * - admin/owner → access + canManage
* - public/uncategorized → access; canManage only for admins
- * - private → access iff creator or added member; canManage iff admin or
- * anchor creator
+ * - 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`), so thread member rows never exist.
+ * `parentChannelId`); a forum post is its own access unit (roster on the post).
+ *
+ * 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
+ * only reachable once they can see the channel. Out-of-channel admin management
+ * lives on admin-gated routes / the future Browse Channels surface, not here.
*/
export async function requireChannelAccess(
db: Database,
@@ -87,13 +92,16 @@ export async function requireChannelAccess(
if (!ctx) return err(403, "forbidden")
const isAdmin = canManageServer(ctx.role)
- const isCreator = ctx.anchor.creatorId === userId
-
- // Visibility: public → any server member; private → the shared
- // canSeePrivateChannel rule (admin | creator | member). Manage: admin
- // anywhere, plus the creator of a private channel.
+ // `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.
+ const isCreator = ctx.isCreator
+
+ // Visibility: public → any server member; private → creator or added member
+ // (canSeePrivateChannel; admins are NOT auto-granted). Manage: admin (who
+ // passed the access gate) or the unit creator.
const hasAccess = ctx.isPrivate
- ? canSeePrivateChannel({ role: ctx.role, isCreator, isChannelMember: ctx.isChannelMember })
+ ? canSeePrivateChannel({ isCreator, isChannelMember: ctx.isChannelMember })
: true
const canManage = isAdmin || (ctx.isPrivate && isCreator)
@@ -103,6 +111,7 @@ export async function requireChannelAccess(
anchor: ctx.anchor,
member: { role: ctx.role },
canManage,
+ isCreator,
isPrivate: ctx.isPrivate,
})
}
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index dff9e8812..e7599e2eb 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -59,6 +59,10 @@ export const communityKeys = {
channelAddableMembers: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "addable-members"] as const,
+ // A thread's notify participant set.
+ threadParticipants: (channelId: string) =>
+ [...communityKeys.all, "channel", channelId, "participants"] as const,
+
pins: (channelId: string) =>
[...communityKeys.all, "channel", channelId, "pins"] as const,
threads: (channelId: string) =>
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index f7f5f5ccf..36cee41ac 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -59,6 +59,7 @@ type CurrentChannelMeta = {
name: string
parentChannelId: string | null
parentMessageId?: string | null
+ creatorId?: string | null
}
type CommunitySubscription = {
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index ff97335a4..bcd76720f 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -80,6 +80,9 @@ const mockGetChannelForMember = vi.fn()
const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)
const mockGetPrivateChannelAudienceUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope: string; scopeId: string }) => Promise<string[]>>().mockResolvedValue([])
+// Default: non-thread channel → typing uses the shared resolver path.
+const mockGetChannelType = vi.fn<(db: unknown, channelId: string) => Promise<string | null>>().mockResolvedValue("text")
+const mockListThreadParticipantUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])
const mockGetDM = vi.fn()
const mockListMembers = vi.fn()
const mockListBotsForMachine = vi.fn<(db: unknown, machineId: string) => Promise<Array<{ id: string; name: string; discriminator: string; description: string }>>>().mockResolvedValue([])
@@ -261,12 +264,16 @@ vi.mock("@alook/shared", () => {
},
communityChannel: {
getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),
+ getChannelType: (...a: any[]) => mockGetChannelType(...a),
isChannelPrivate: (...a: any[]) => mockIsChannelPrivate(...a),
getPrivateChannelAudienceUserIds: (...a: any[]) => mockGetPrivateChannelAudienceUserIds(...a),
},
communityMembersResolver: {
resolveScopeMemberUserIds: (...a: any[]) => mockResolveScopeMemberUserIds(...a),
},
+ communityThread: {
+ listThreadParticipantUserIds: (...a: any[]) => mockListThreadParticipantUserIds(...a),
+ },
communityDm: {
getDM: (...a: any[]) => mockGetDM(...a),
},
@@ -319,6 +326,10 @@ describe("WebSocketDurableObject", () => {
mockGetUserInternal.mockResolvedValue(null)
mockIsChannelPrivate.mockResolvedValue(false)
mockGetPrivateChannelAudienceUserIds.mockResolvedValue([])
+ // Non-thread default so typing uses the shared resolver path; the
+ // thread-typing test overrides this.
+ mockGetChannelType.mockResolvedValue("text")
+ mockListThreadParticipantUserIds.mockResolvedValue([])
mockGetBotBinding.mockResolvedValue(null)
mockUpdateProfile.mockResolvedValue({})
mockGetProfile.mockResolvedValue(null)
@@ -1871,6 +1882,29 @@ describe("WebSocketDurableObject", () => {
expect(mockStubFetch).toHaveBeenCalledTimes(1)
})
+ it("thread: typing fans out to PARTICIPANTS, not the channel audience", async () => {
+ const { durable, env } = createDO()
+ mockGetChannelForMember.mockResolvedValueOnce({ id: "t-1", serverId: "server-1" })
+ mockGetChannelType.mockResolvedValueOnce("thread")
+ 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", threadId: "t-1" }),
+ )
+ await flush()
+
+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "t-1")
+ // Thread typing must NOT fall back to the channel-audience resolver.
+ 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.ts
index b66f8daa4..2e23f6c5e 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -1046,16 +1046,21 @@ export class WebSocketDurableObject extends DurableObject<Env> {
log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId: targetId })
return
}
- // Private-category channels (and their threads) fan out only to the
- // channel audience — never leak "X is typing" to non-members. Also
- // re-gates the sender: a server member who isn't in the private
- // channel won't appear in its own audience, so they broadcast to
- // nobody. Public/uncategorized channels stay server-wide. The
- // public/private split lives in the shared member resolver.
- recipientUserIds = await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
- scope: "channel",
- scopeId: targetId,
- })
+ // 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.
+ const channelType = await queries.communityChannel.getChannelType(db, targetId)
+ recipientUserIds =
+ channelType === "thread"
+ ? await queries.communityThread.listThreadParticipantUserIds(db, targetId)
+ : await queries.communityMembersResolver.resolveScopeMemberUserIds(db, {
+ scope: "channel",
+ scopeId: targetId,
+ })
}
}
diff --git a/tests/integration/cli/community-rate-limit.test.ts b/tests/integration/cli/community-rate-limit.test.ts
index ad4c1a5a4..0db2b239b 100644
--- a/tests/integration/cli/community-rate-limit.test.ts
+++ b/tests/integration/cli/community-rate-limit.test.ts
@@ -75,31 +75,45 @@ afterAll(() => {
})
describe("community message rate limit — DO-backed", () => {
- it("allows the first 30 sends inside one window, then returns 429 with Retry-After", async () => {
- const results: number[] = []
- for (let i = 0; i < 31; i++) {
- const res = await sessionRequest(
- `/api/community/channels/${channelId}/messages`,
- cookie,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ content: `rate-limit-e2e ${i}` }),
- },
- )
- results.push(res.status)
- if (i === 30) {
- // The 31st request must be blocked, not fail-open. The Retry-After
- // header is set by writeError() when the DO returns { allowed: false }.
- const retryAfter = res.headers.get("retry-after")
- expect(retryAfter).toBeTruthy()
- expect(Number(retryAfter)).toBeGreaterThan(0)
- }
+ it("accepts up to the per-window max, then returns 429 with Retry-After", async () => {
+ // Policy: community:msgSend = 30 sends / 10s fixed window (see
+ // `RATE_LIMITS` in src/shared/src/lib/rate-limits.ts). Fire the whole
+ // burst CONCURRENTLY so every request provably lands inside one window —
+ // a sequential loop can take >10s on a slow runner, letting the fixed
+ // window reset mid-loop so the counter never reaches the ceiling and no
+ // 429 is ever emitted (the old flake). The DO counter is
+ // strongly-consistent, so concurrency still yields a deterministic split.
+ const MAX = 30
+ const responses = await Promise.all(
+ Array.from({ length: MAX + 1 }, (_, i) =>
+ sessionRequest(
+ `/api/community/channels/${channelId}/messages`,
+ cookie,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content: `rate-limit-e2e ${i}` }),
+ },
+ ),
+ ),
+ )
+
+ const accepted = responses.filter((r) => r.status === 201).length
+ const rejected = responses.filter((r) => r.status === 429)
+
+ // Exactly the ceiling is accepted; the overflow is blocked (not fail-open).
+ // If `accepted` < 30, the counter started with stale state from a previous
+ // run — reset with `pnpm db:reset`.
+ expect(accepted).toBe(MAX)
+ expect(rejected).toHaveLength(1)
+
+ // Every 429 carries a positive Retry-After (set by writeError() when the
+ // DO returns { allowed: false }). Asserted per-response so a fail-open
+ // (429 without the header) is caught regardless of ordering.
+ for (const res of rejected) {
+ const retryAfter = res.headers.get("retry-after")
+ expect(retryAfter).toBeTruthy()
+ expect(Number(retryAfter)).toBeGreaterThan(0)
}
- // First 30 accepted (201). If any of them 429, the counter started with
- // stale state from a previous run — reset with `pnpm db:reset`.
- const accepted = results.slice(0, 30).filter((s) => s === 201).length
- expect(accepted).toBe(30)
- expect(results[30]).toBe(429)
}, 30_000)
})