Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): harden member lifecycle consistency
Gener749c9a1318b0
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex 5d2b85297..b59a401ab 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -564,6 +564,42 @@ export async function deleteChannelMember(return rows[0] ?? null;}+/**+ * Atomically removes an access row and all notify rows below that access+ * unit. The child cleanup uses a subquery so the batch has no read/write gap.+ */+export async function deleteChannelMemberAndChildParticipants(+ db: Database,+ channelId: string,+ userId: string,+) {+ const removeAccess = db+ .delete(communityChannelMember)+ .where(+ and(+ eq(communityChannelMember.channelId, channelId),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "access"),+ ),+ )+ .returning();+ const childIds = db+ .select({ id: communityChannel.id })+ .from(communityChannel)+ .where(eq(communityChannel.parentChannelId, channelId));+ const removeChildParticipants = db+ .delete(communityChannelMember)+ .where(+ and(+ inArray(communityChannelMember.channelId, childIds),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "notify"),+ ),+ );+ const results = (await db.batch([removeAccess, removeChildParticipants] as any)) as any[];+ return (results[0] as Array<typeof communityChannelMember.$inferSelect>)[0] ?? null;+}+/*** ACCESS members explicitly added to a channel, joined to `user` for display.* Scoped to one channel id — cross-channel ids never resolve. Notify rowsdiff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.tsindex 820738e3e..d546f5cb4 100644--- a/src/shared/src/db/queries/community/invite.ts+++ b/src/shared/src/db/queries/community/invite.ts@@ -1,4 +1,5 @@-import { eq, sql } from "drizzle-orm";+import { and, eq, exists, gt, isNull, lt, or, sql } from "drizzle-orm";+import { nanoid } from "nanoid";import {communityServerInvite,communityServerMember,@@ -13,8 +14,43 @@ export async function createInvite(createdBy: string;maxUses?: number;expiresAt?: string;+ maxActive?: number;}) {+ if (data.maxActive !== undefined) {+ const id = nanoid();+ const token = nanoid(10);+ const createdAt = new Date().toISOString();+ const rows = await db+ .insert(communityServerInvite)+ .select(+ db+ .select({+ id: sql<string>`${id}`.as("id"),+ serverId: sql<string>`${data.serverId}`.as("server_id"),+ createdBy: sql<string>`${data.createdBy}`.as("created_by"),+ token: sql<string>`${token}`.as("token"),+ maxUses: sql<number | null>`${data.maxUses ?? null}`.as("max_uses"),+ uses: sql<number>`0`.as("uses"),+ expiresAt: sql<string | null>`${data.expiresAt ?? null}`.as("expires_at"),+ createdAt: sql<string>`${createdAt}`.as("created_at"),+ })+ .from(sql`(select 1)`)+ .where(+ lt(+ sql<number>`(+ select count(*)+ from ${communityServerInvite}+ where ${communityServerInvite.serverId} = ${data.serverId}+ )`,+ data.maxActive,+ ),+ ),+ )+ .returning();+ return rows[0] ?? null;+ }+const rows = await db.insert(communityServerInvite).values({@@ -24,7 +60,7 @@ export async function createInvite(expiresAt: data.expiresAt ?? null,}).returning();- return rows[0]!;+ return rows[0] ?? null;}export async function getInvite(db: Database, inviteId: string) {@@ -76,26 +112,62 @@ export async function useInvite(return null;}- // Insert new server member FIRST — the `(serverId, userId)` UNIQUE- // constraint may reject this ("already a member") or D1 may transiently- // fail. Incrementing `uses` before the insert would burn an invite slot- // on every rejected attempt (bots retrying a failed join can exhaust- // `maxUses` without a single successful join).- const memberRows = await db+ // Consume capacity and create membership in one D1 batch. The INSERT itself+ // re-checks expiry/quota inside the write transaction, so two users racing+ // for the last use cannot both join. The UPDATE is gated on this request's+ // freshly-minted member id; a zero-row INSERT therefore cannot burn a use.+ // Conversely, a UNIQUE membership failure aborts the batch and rolls the+ // counter back, preserving the route's "Already a member" branch.+ const memberId = nanoid();+ const joinedAt = now;+ const insertMember = db.insert(communityServerMember)- .values({- serverId: invite.serverId,- userId,- role: "member",- })+ .select(+ db+ .select({+ id: sql<string>`${memberId}`.as("id"),+ serverId: communityServerInvite.serverId,+ userId: sql<string>`${userId}`.as("user_id"),+ role: sql<string>`${"member"}`.as("role"),+ railOrder: sql<number>`0`.as("rail_order"),+ joinedAt: sql<string>`${joinedAt}`.as("joined_at"),+ })+ .from(communityServerInvite)+ .where(+ and(+ eq(communityServerInvite.id, invite.id),+ or(+ isNull(communityServerInvite.expiresAt),+ gt(communityServerInvite.expiresAt, now),+ ),+ or(+ isNull(communityServerInvite.maxUses),+ lt(+ sql<number>`coalesce(${communityServerInvite.uses}, 0)`,+ communityServerInvite.maxUses,+ ),+ ),+ ),+ ),+ ).returning();- const insertedMember = memberRows[0]!;-- // Atomic increment uses — only after the insert has committed.- await db+ const incrementUse = db.update(communityServerInvite)- .set({ uses: sql`${communityServerInvite.uses} + 1` })- .where(eq(communityServerInvite.id, invite.id));+ .set({ uses: sql`coalesce(${communityServerInvite.uses}, 0) + 1` })+ .where(+ and(+ eq(communityServerInvite.id, invite.id),+ exists(+ db+ .select({ id: communityServerMember.id })+ .from(communityServerMember)+ .where(eq(communityServerMember.id, memberId)),+ ),+ ),+ );+ const batchResults = (await db.batch([insertMember, incrementUse] as any)) as any[];+ const insertedMember = (batchResults[0] as Array<typeof communityServerMember.$inferSelect>)[0];+ if (!insertedMember) return null;// Join the joined-user row so WS listeners can render name/avatar without// waiting for the next /members refetch.diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 834632965..e430cf074 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -34,6 +34,31 @@ export async function removeMember(db: Database, memberId: string) {return rows[0] ?? null;}+/**+ * Removes a server member and the owner's in-server bots in one D1 batch.+ * The target delete is scoped by both ids so a stale/cross-server member id+ * cannot make the cascade appear successful.+ */+export async function removeMemberAndOwnerBots(+ db: Database,+ memberId: string,+ serverId: string,+ botUserIds: string[],+) {+ const removeTarget = db+ .delete(communityServerMember)+ .where(+ and(+ eq(communityServerMember.id, memberId),+ eq(communityServerMember.serverId, serverId),+ ),+ )+ .returning();+ const removeBots = removeOwnerBotsFromServerStatement(db, serverId, botUserIds);+ const results = (await db.batch([removeTarget, removeBots] as any)) as any[];+ return (results[0] as Array<typeof communityServerMember.$inferSelect>)[0] ?? null;+}+export async function updateRole(db: Database, memberId: string, role: string) {const rows = await db.update(communityServerMember)diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex 3ab09999b..f1fde4827 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -62,13 +62,14 @@ export async function addThreadParticipants(threadChannelId: string,rows: { userId: string; source: ThreadParticipantSource }[]) {- if (rows.length === 0) return;+ if (rows.length === 0) return [];// communityChannelMember emits 6 bind params/row (id $defaultFn, channel_id,// user_id, relation, source, added_at $defaultFn; added_by is an unsupplied// literal null, not a param), so cap at floor(100/6)=16 rows for D1's 100-param// limit. `onConflictDoNothing` adds no VALUES params.+ const insertedUserIds: string[] = [];for (const batch of chunk(rows, maxRowsPerInsert(6))) {- await db+ const inserted = await db.insert(communityChannelMember).values(batch.map((r) => ({@@ -78,8 +79,11 @@ export async function addThreadParticipants(source: r.source,})))- .onConflictDoNothing({ target: [...NOTIFY_CONFLICT_TARGET] });+ .onConflictDoNothing({ target: [...NOTIFY_CONFLICT_TARGET] })+ .returning({ userId: communityChannelMember.userId });+ for (const row of inserted) insertedUserIds.push(row.userId);}+ return insertedUserIds;}// The NOTIFY set: every participant userId. This is what thread fan-out /diff --git a/src/shared/test/queries/community-channel-access.test.ts b/src/shared/test/queries/community-channel-access.test.tsindex e603dbdbb..9b8343a25 100644--- a/src/shared/test/queries/community-channel-access.test.ts+++ b/src/shared/test/queries/community-channel-access.test.ts@@ -72,6 +72,35 @@ describe("canSeePrivateChannel — shared rule", () => {})})+describe("deleteChannelMemberAndChildParticipants", () => {+ it("batches access removal with child notify cleanup", async () => {+ const accessStatement: any = {};+ accessStatement.where = vi.fn(() => accessStatement);+ accessStatement.returning = vi.fn(() => accessStatement);+ const notifyStatement: any = {};+ notifyStatement.where = vi.fn(() => notifyStatement);+ const selectStatement: any = {};+ selectStatement.from = vi.fn(() => selectStatement);+ selectStatement.where = vi.fn(() => selectStatement);+ const db: any = {+ delete: vi+ .fn()+ .mockReturnValueOnce(accessStatement)+ .mockReturnValueOnce(notifyStatement),+ select: vi.fn(() => selectStatement),+ batch: vi.fn().mockResolvedValue([[{ id: "cm1" }], { rowsAffected: 3 }]),+ };++ await expect(channelQueries.deleteChannelMemberAndChildParticipants(+ db,+ "c1",+ "u2",+ )).resolves.toEqual({ id: "cm1" });++ expect(db.batch).toHaveBeenCalledWith([accessStatement, notifyStatement]);+ });+});+describe("getChannelForMember — private visibility", () => {// Every queue leads with `[]` — the new `type='dm'` probe returns no row for// a non-DM channel, then the original server-member → private-category flowdiff --git a/src/shared/test/queries/community-invite.test.ts b/src/shared/test/queries/community-invite.test.tsindex b4337ec59..9c8c506de 100644--- a/src/shared/test/queries/community-invite.test.ts+++ b/src/shared/test/queries/community-invite.test.ts@@ -1,119 +1,99 @@-import { describe, it, expect, vi } from "vitest";-import * as invite from "../../src/db/queries/community/invite";+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { createInvite, useInvite } from "../../src/db/queries/community/invite";-/**- * Build a mock db chain that records the order of high-level operations- * (`select`, `update`, `insert`) into `ops`. Each terminal method- * (`.where(...)` on selects, `.returning()` on updates/inserts) resolves- * with the next queued row set from `rowsQueue`.- */-function createOrderTrackingDb(rowsQueue: any[][]) {- const ops: string[] = [];- const chain: any = {};- const takeRows = () => Promise.resolve(rowsQueue.shift() ?? []);+describe("community invite quota consumption", () => {+ let sqlite: Sqlite.Database;+ let db: ReturnType<typeof drizzle>;- chain.select = vi.fn(() => {- ops.push("select");- return chain;+ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ image TEXT,+ discriminator TEXT+ );+ CREATE TABLE community_server_invite (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ created_by TEXT,+ token TEXT NOT NULL UNIQUE,+ max_uses INTEGER,+ uses INTEGER DEFAULT 0,+ expires_at TEXT,+ created_at TEXT NOT NULL+ );+ CREATE TABLE community_server_member (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ role TEXT DEFAULT 'member',+ rail_order INTEGER DEFAULT 0,+ joined_at TEXT NOT NULL,+ UNIQUE(server_id, user_id)+ );+ `);+ db = drizzle(sqlite);+ // better-sqlite3's Drizzle adapter has transactions but no D1-style batch.+ // Execute the generated statements in one native SQLite transaction so the+ // query's all-or-nothing quota contract is exercised against real SQL.+ (db as any).batch = (statements: Array<{ toSQL: () => { sql: string; params: unknown[] } }>) =>+ sqlite.transaction(() =>+ statements.map((statement) => {+ const query = statement.toSQL();+ const prepared = sqlite.prepare(query.sql);+ return prepared.reader+ ? prepared.all(...query.params)+ : prepared.run(...query.params);+ }),+ )();+ sqlite.prepare("INSERT INTO user (id, name, discriminator) VALUES (?, ?, ?)").run("u1", "One", "0001");+ sqlite.prepare("INSERT INTO user (id, name, discriminator) VALUES (?, ?, ?)").run("u2", "Two", "0002");});- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => takeRows());- chain.limit = vi.fn(() => takeRows());- chain.insert = vi.fn(() => {- ops.push("insert");- return chain;- });- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => takeRows());+ afterEach(() => sqlite.close());- chain.update = vi.fn(() => {- ops.push("update");- return chain;- });- chain.set = vi.fn(() => chain);+ function seedInvite(maxUses: number | null = 1) {+ sqlite.prepare(`+ INSERT INTO community_server_invite+ (id, server_id, created_by, token, max_uses, uses, created_at)+ VALUES ('iv1', 's1', 'owner', 'token1', ?, 0, '2026-01-01T00:00:00.000Z')+ `).run(maxUses);+ }- // For update() the terminal method is `.where(...)` — Drizzle's update- // builder awaits at `.where()`. Handle both shapes by returning a- // then-able chain that also is awaitable.- return { chain, ops };-}+ it("admits only one member for the final finite use", async () => {+ seedInvite(1);+ await expect(useInvite(db as never, "token1", "u1")).resolves.not.toBeNull();+ await expect(useInvite(db as never, "token1", "u2")).resolves.toBeNull();-describe("useInvite — counter does not increment until member insert succeeds", () => {- it("runs member INSERT before invite UPDATE (uses ← uses+1)", async () => {- // Sequence of `.where()`/`.returning()` results, in call order:- // 1. select invite by token → the invite row- // 2. insert communityServerMember → returning the inserted row- // 3. update communityServerInvite (increment uses) — resolves as- // Drizzle's update-chain terminal- // 4. select user (hydration) → user row- const inviteRow = {- id: "inv_1",- token: "tok",- serverId: "srv_1",- maxUses: null,- uses: 0,- expiresAt: null,- };- const memberRow = { id: "mem_1", serverId: "srv_1", userId: "u_1", role: "member" };- const userRow = { name: "Alice", image: null, discriminator: "0001" };+ expect(sqlite.prepare("SELECT uses FROM community_server_invite WHERE id='iv1'").get())+ .toEqual({ uses: 1 });+ expect(sqlite.prepare("SELECT user_id FROM community_server_member ORDER BY user_id").all())+ .toEqual([{ user_id: "u1" }]);+ });- const { chain, ops } = createOrderTrackingDb([- [inviteRow],- [memberRow],- [], // update .where(...) result — no rows returned needed- [userRow],- ]);+ it("rolls the counter back when the membership UNIQUE constraint rejects", async () => {+ seedInvite(null);+ await useInvite(db as never, "token1", "u1");+ await expect(useInvite(db as never, "token1", "u1")).rejects.toThrow();- const result = await invite.useInvite(chain, "tok", "u_1");- expect(result).not.toBeNull();- // The load-bearing ordering assertion: insert must come before update.- const insertIdx = ops.indexOf("insert");- const updateIdx = ops.indexOf("update");- expect(insertIdx).toBeGreaterThanOrEqual(0);- expect(updateIdx).toBeGreaterThan(insertIdx);+ expect(sqlite.prepare("SELECT uses FROM community_server_invite WHERE id='iv1'").get())+ .toEqual({ uses: 1 });});- it("does NOT run the invite UPDATE if the member INSERT throws (UNIQUE 'already a member')", async () => {- const inviteRow = {- id: "inv_1",- token: "tok",- serverId: "srv_1",- maxUses: 3,- uses: 0,- expiresAt: null,- };+ it("enforces the active invite cap inside the insert statement", async () => {+ seedInvite(null);- const ops: string[] = [];- const chain: any = {};- const rowsQueue: any[][] = [[inviteRow]];- chain.select = vi.fn(() => {- ops.push("select");- return chain;- });- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve(rowsQueue.shift() ?? []));- chain.limit = vi.fn(() => Promise.resolve(rowsQueue.shift() ?? []));- chain.insert = vi.fn(() => {- ops.push("insert");- return chain;- });- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() =>- Promise.reject(- Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" }),- ),- );- chain.update = vi.fn(() => {- ops.push("update");- return chain;- });- chain.set = vi.fn(() => chain);+ await expect(createInvite(db as never, {+ serverId: "s1",+ createdBy: "u1",+ maxActive: 1,+ })).resolves.toBeNull();- await expect(invite.useInvite(chain, "tok", "u_dup")).rejects.toThrow(/UNIQUE/);- expect(ops).toContain("insert");- // The critical invariant: no UPDATE happened, so `uses` was not- // incremented on the failed join attempt.- expect(ops).not.toContain("update");+ expect(sqlite.prepare("SELECT count(*) AS count FROM community_server_invite WHERE server_id='s1'").get())+ .toEqual({ count: 1 });});});diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.tsindex 55f4ca972..23d7e4d3b 100644--- a/src/shared/test/queries/community-member.test.ts+++ b/src/shared/test/queries/community-member.test.ts@@ -38,6 +38,35 @@ describe("community/member exports", () => {it("exports listMembersPaginated", () => {expect(typeof memberQueries.listMembersPaginated).toBe("function");});+ it("exports the atomic member + owner-bot removal", () => {+ expect(typeof memberQueries.removeMemberAndOwnerBots).toBe("function");+ });+});++describe("removeMemberAndOwnerBots", () => {+ it("batches the target and bot deletes and returns the removed target", async () => {+ const targetStatement: any = {};+ targetStatement.where = vi.fn(() => targetStatement);+ targetStatement.returning = vi.fn(() => targetStatement);+ const botsStatement: any = {};+ botsStatement.where = vi.fn(() => botsStatement);+ const db: any = {+ delete: vi+ .fn()+ .mockReturnValueOnce(targetStatement)+ .mockReturnValueOnce(botsStatement),+ batch: vi.fn().mockResolvedValue([[{ id: "mem_1" }], { rowsAffected: 2 }]),+ };++ await expect(memberQueries.removeMemberAndOwnerBots(+ db,+ "mem_1",+ "srv_1",+ ["bot_1", "bot_2"],+ )).resolves.toEqual({ id: "mem_1" });++ expect(db.batch).toHaveBeenCalledWith([targetStatement, botsStatement]);+ });});describe("listMemberUserIds", () => {diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.tsindex 1197253e0..5d64826a1 100644--- a/src/shared/test/queries/community-thread.test.ts+++ b/src/shared/test/queries/community-thread.test.ts@@ -209,17 +209,21 @@ describe("addThreadParticipants — bulk", () => {});it("inserts one row per (userId, source) pair with onConflictDoNothing", async () => {- const values = vi.fn(() => ({ onConflictDoNothing: vi.fn(() => Promise.resolve()) }));+ const returning = vi.fn(() => Promise.resolve([{ userId: "u1" }, { userId: "u2" }]));+ const values = vi.fn(() => ({+ onConflictDoNothing: vi.fn(() => ({ returning })),+ }));const chain: any = { insert: vi.fn(() => ({ values })) };- await threadQueries.addThreadParticipants(chain, "t1", [+ await expect(threadQueries.addThreadParticipants(chain, "t1", [{ userId: "u1", source: "spoke" },{ userId: "u2", source: "mention" },- ]);+ ])).resolves.toEqual(["u1", "u2"]);expect(chain.insert).toHaveBeenCalledTimes(1); // single bulk insert, not Nexpect(values).toHaveBeenCalledWith([{ channelId: "t1", userId: "u1", relation: "notify", source: "spoke" },{ channelId: "t1", userId: "u2", relation: "notify", source: "mention" },]);+ expect(returning).toHaveBeenCalledTimes(1);});});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.tsindex 18eeb01fb..dd63dcd2c 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@@ -6,11 +6,10 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockResolveChannelAccessContext = vi.fn()-const mockDeleteChannelMember = vi.fn()+const mockDeleteChannelMemberAndChildParticipants = vi.fn()const mockGetPrivateChannelAudienceUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()const mockLogAudit = vi.fn()-const mockRemoveParticipantFromChildChannels = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -21,12 +20,10 @@ vi.mock("@alook/shared", async () => {queries: {communityChannel: {resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),- deleteChannelMember: (...a: unknown[]) => mockDeleteChannelMember(...a),+ deleteChannelMemberAndChildParticipants: (...a: unknown[]) =>+ mockDeleteChannelMemberAndChildParticipants(...a),getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),},- communityThread: {- removeParticipantFromChildChannels: (...a: unknown[]) => mockRemoveParticipantFromChildChannels(...a),- },},}})@@ -77,17 +74,19 @@ describe("DELETE /channels/[id]/members/[userId]", () => {beforeEach(() => {vi.clearAllMocks()mockResolveChannelAccessContext.mockResolvedValue(managerCtx())- mockDeleteChannelMember.mockResolvedValue({ id: "cm1" })+ mockDeleteChannelMemberAndChildParticipants.mockResolvedValue({ id: "cm1" })mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])})it("creator/admin removes a member", async () => {const res = await DELETE(req(), ctx)expect(res.status).toBe(204)- expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "c1", "u2")+ expect(mockDeleteChannelMemberAndChildParticipants).toHaveBeenCalledWith(+ expect.anything(),+ "c1",+ "u2",+ )expect(mockBroadcastToUserSafe).toHaveBeenCalled()- // A removed channel member also loses their child-thread notify rows.- expect(mockRemoveParticipantFromChildChannels).toHaveBeenCalledWith(expect.anything(), "c1", "u2")})it("removing a FORUM member cascades: drops their participant rows across posts", async () => {@@ -101,10 +100,11 @@ describe("DELETE /channels/[id]/members/[userId]", () => {{ params: { id: "f1", userId: "u2" } } as any,)expect(res.status).toBe(204)- expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "f1", "u2")- // The ex-member's leftover notify rows on the forum's posts are cleaned so- // fan-out stops pushing new-post messages they can no longer read.- expect(mockRemoveParticipantFromChildChannels).toHaveBeenCalledWith(expect.anything(), "f1", "u2")+ expect(mockDeleteChannelMemberAndChildParticipants).toHaveBeenCalledWith(+ expect.anything(),+ "f1",+ "u2",+ )})it("cannot remove the creator (400)", async () => {@@ -113,7 +113,7 @@ describe("DELETE /channels/[id]/members/[userId]", () => {{ params: { id: "c1", userId: "u1" } } as any,)expect(res.status).toBe(400)- expect(mockDeleteChannelMember).not.toHaveBeenCalled()+ expect(mockDeleteChannelMemberAndChildParticipants).not.toHaveBeenCalled()})it("rejects a non-creator removing someone else (403)", async () => {@@ -138,7 +138,11 @@ describe("DELETE /channels/[id]/members/[userId]", () => {{ params: { id: "c1", userId: "u1" } } as any,)expect(res.status).toBe(204)- expect(mockDeleteChannelMember).toHaveBeenCalledWith(expect.anything(), "c1", "u1")+ expect(mockDeleteChannelMemberAndChildParticipants).toHaveBeenCalledWith(+ expect.anything(),+ "c1",+ "u1",+ )})it("creator cannot self-leave their own channel (400)", async () => {@@ -149,6 +153,6 @@ describe("DELETE /channels/[id]/members/[userId]", () => {{ params: { id: "c1", userId: "u1" } } as any,)expect(res.status).toBe(400)- expect(mockDeleteChannelMember).not.toHaveBeenCalled()+ expect(mockDeleteChannelMemberAndChildParticipants).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.tsindex 00bb44214..4016bd564 100644--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts@@ -37,15 +37,13 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const isSelf = targetUserId === ctx.userIdif (!isSelf && !access.value.isCreator) return writeError("forbidden", 403)- const removed = await queries.communityChannel.deleteChannelMember(db, channelId, targetUserId)+ const removed = await queries.communityChannel.deleteChannelMemberAndChildParticipants(+ db,+ channelId,+ targetUserId,+ )if (!removed) return writeError("member not found", 404)- // A removed member loses access to every child unit (a channel's/forum's- // threads); drop their leftover participant (notify) rows across- // those children so fan-out stops pushing new post/thread messages they can no- // longer read. A later mention/speak (which requires access) re-adds them.- await queries.communityThread.removeParticipantFromChildChannels(db, channelId, targetUserId)-const event = {type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,serverId: channel.serverId,diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.tsindex da68c6603..0359c2017 100644--- 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@@ -7,6 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockResolveChannelAccessContext = vi.fn()const mockRemoveThreadParticipant = vi.fn()+const mockListThreadParticipantUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -24,6 +25,7 @@ vi.mock("@alook/shared", async () => {},communityThread: {removeThreadParticipant: (...a: unknown[]) => mockRemoveThreadParticipant(...a),+ listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),},},}@@ -67,6 +69,7 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {vi.clearAllMocks()mockResolveChannelAccessContext.mockResolvedValue(threadCtx())mockRemoveThreadParticipant.mockResolvedValue({ id: "tp1" })+ mockListThreadParticipantUserIds.mockResolvedValue(["u2", "u3"])})it("viewer leaves the thread (removes own row)", async () => {@@ -79,6 +82,10 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {channelId: "t1",userId: "u1",})+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u3", expect.objectContaining({+ type: "community:channel.member_remove",+ userId: "u1",+ }))})it("thread creator can remove another participant", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.tsindex 0d78d3f5f..31aae90e2 100644--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.ts@@ -37,11 +37,17 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const removed = await queries.communityThread.removeThreadParticipant(db, channelId, targetUserId)if (!removed) return writeError("participant not found", 404)- await broadcastToUserSafe(targetUserId, {+ const event = {type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,serverId: access.value.channel.serverId,channelId,userId: targetUserId,- })+ } as const+ const remaining = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ await Promise.all(+ [...new Set([...remaining, targetUserId])].map((userId) =>+ broadcastToUserSafe(userId, event),+ ),+ )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.tsindex a365f0362..380757aa9 100644--- a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts@@ -8,6 +8,7 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockResolveChannelAccessContext = vi.fn()const mockListThreadParticipants = vi.fn()const mockAddThreadParticipant = vi.fn()+const mockListThreadParticipantUserIds = vi.fn()const mockResolveScopeMemberUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()@@ -26,6 +27,7 @@ vi.mock("@alook/shared", async () => {},communityThread: {listThreadParticipants: (...a: unknown[]) => mockListThreadParticipants(...a),+ listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),addThreadParticipant: (...a: unknown[]) => mockAddThreadParticipant(...a),},},@@ -81,6 +83,7 @@ describe("POST /channels/[id]/participants", () => {// Parent-channel audience (same source the read gate/fan-out uses).mockResolveScopeMemberUserIds.mockResolvedValue(["u1", "u2"])mockAddThreadParticipant.mockResolvedValue({ id: "tp1" })+ mockListThreadParticipantUserIds.mockResolvedValue(["u1", "u2", "u3"])})it("any participant adds a parent-channel member as a participant", async () => {@@ -89,7 +92,11 @@ describe("POST /channels/[id]/participants", () => {expect(mockAddThreadParticipant).toHaveBeenCalledWith(expect.anything(), {threadChannelId: "t1", userId: "u2", source: "added",})- expect(mockBroadcastToUserSafe).toHaveBeenCalled()+ expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(3)+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u3", expect.objectContaining({+ type: "community:channel.member_add",+ userId: "u2",+ }))})it("a non-creator participant can still add (no creator gate)", async () => {diff --git a/src/web/src/app/api/community/channels/[id]/participants/route.ts b/src/web/src/app/api/community/channels/[id]/participants/route.tsindex c5510e077..95bdecd01 100644--- a/src/web/src/app/api/community/channels/[id]/participants/route.ts+++ b/src/web/src/app/api/community/channels/[id]/participants/route.ts@@ -65,15 +65,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {source: PARTICIPANT_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).+ // Notify the full participant set so every open Members drawer refreshes,+ // not just the target and the actor's optimistic mutation. Only on a+ // genuinely-new row (null = already a participant).if (created) {- void broadcastToUserSafe(targetUserId, {+ const event = {type: WS_EVENTS.CHANNEL_MEMBER_ADD,serverId: channel.serverId,channelId,userId: targetUserId,- })+ } as const+ const recipients = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ await Promise.all(+ [...new Set(recipients)].map((userId) => broadcastToUserSafe(userId, event)),+ )}return writeJSON({ ok: true }, 201)diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.test.ts b/src/web/src/app/api/community/servers/[id]/invites/route.test.tsindex 6f1cb114c..0749e73a2 100644--- a/src/web/src/app/api/community/servers/[id]/invites/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/invites/route.test.ts@@ -6,7 +6,6 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockGetMember = vi.fn()-const mockListServerInvites = vi.fn()const mockCreateInvite = vi.fn()const mockLogAction = vi.fn()const mockFanOut = vi.fn()@@ -27,7 +26,6 @@ vi.mock("@alook/shared", async () => {queries: {communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },communityInvite: {- listServerInvites: (...a: unknown[]) => mockListServerInvites(...a),createInvite: (...a: unknown[]) => mockCreateInvite(...a),},communityAuditLog: {@@ -73,7 +71,6 @@ describe("POST /api/community/servers/[id]/invites", () => {vi.clearAllMocks()// Admin caller by default.mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "admin" })- mockListServerInvites.mockResolvedValue([])mockCreateInvite.mockResolvedValue({id: "inv_1",token: "tok_1",@@ -92,6 +89,13 @@ describe("POST /api/community/servers/[id]/invites", () => {expect(res.status).toBe(201)const body = (await res.json()) as { invite: { id: string } }expect(body.invite.id).toBe("inv_1")+ expect(mockCreateInvite).toHaveBeenCalledWith(expect.anything(), {+ serverId: "s1",+ createdBy: "u1",+ maxUses: undefined,+ expiresAt: undefined,+ maxActive: 50,+ })expect(mockLogAction).toHaveBeenCalledTimes(1)expect(mockLogAction).toHaveBeenCalledWith(expect.anything(), {@@ -103,6 +107,16 @@ describe("POST /api/community/servers/[id]/invites", () => {})})+ it("returns 409 when the atomic insert reports the active invite cap", async () => {+ mockCreateInvite.mockResolvedValue(null)++ const res = await POST(postReq({}), ctx)++ expect(res.status).toBe(409)+ expect(mockLogAction).not.toHaveBeenCalled()+ expect(mockFanOut).not.toHaveBeenCalled()+ })+it("still returns 201 when the audit write rejects (regression for the awaited outlier)", async () => {// Before the fix this call was `await queries.communityAuditLog.logAction(...)`// and would 500 the request. logAudit is fire-and-forget — the responsediff --git a/src/web/src/app/api/community/servers/[id]/invites/route.ts b/src/web/src/app/api/community/servers/[id]/invites/route.tsindex 5c55de922..ae38cc78e 100644--- a/src/web/src/app/api/community/servers/[id]/invites/route.ts+++ b/src/web/src/app/api/community/servers/[id]/invites/route.ts@@ -72,21 +72,19 @@ export const POST = withAuth(async (req, ctx) => {}}- // Cap active invites per server to bound token-table growth + enumeration risk.- const existing = await queries.communityInvite.listServerInvites(db, serverId)- if (existing.length >= MAX_ACTIVE_INVITES_PER_SERVER) {- return writeError(- `server has reached the active invite cap (${MAX_ACTIVE_INVITES_PER_SERVER}); revoke an existing invite first`,- 409,- )- }-const invite = await queries.communityInvite.createInvite(db, {serverId,createdBy: ctx.userId,maxUses: body.maxUses,expiresAt: body.expiresAt,+ maxActive: MAX_ACTIVE_INVITES_PER_SERVER,})+ if (!invite) {+ return writeError(+ `server has reached the active invite cap (${MAX_ACTIVE_INVITES_PER_SERVER}); revoke an existing invite first`,+ 409,+ )+ }logAudit(db, {serverId,diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts b/src/web/src/app/api/community/servers/[id]/leave/route.test.tsindex b267d2e84..cba49f33e 100644--- a/src/web/src/app/api/community/servers/[id]/leave/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/leave/route.test.ts@@ -6,11 +6,11 @@ vi.mock("@opennextjs/cloudflare", () => ({}))const mockGetMember = vi.fn()-const mockRemoveMember = vi.fn()-const mockRemoveOwnerBotsFromServer = vi.fn()+const mockRemoveMemberAndOwnerBots = vi.fn()const mockListOwnerBotsInServer = vi.fn()const mockLogAudit = vi.fn()const mockFanOut = vi.fn()+const mockBroadcastToUserSafe = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -21,9 +21,8 @@ vi.mock("@alook/shared", async () => {queries: {communityMember: {getMember: (...a: unknown[]) => mockGetMember(...a),- removeMember: (...a: unknown[]) => mockRemoveMember(...a),+ removeMemberAndOwnerBots: (...a: unknown[]) => mockRemoveMemberAndOwnerBots(...a),listOwnerBotsInServer: (...a: unknown[]) => mockListOwnerBotsInServer(...a),- removeOwnerBotsFromServer: (...a: unknown[]) => mockRemoveOwnerBotsFromServer(...a),},},}@@ -39,6 +38,7 @@ vi.mock("@/lib/community/audit", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),}))vi.mock("@/lib/middleware/auth", () => ({@@ -70,10 +70,10 @@ describe("POST /api/community/servers/[id]/leave", () => {beforeEach(() => {vi.clearAllMocks()mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })- mockRemoveMember.mockResolvedValue(true)+ mockRemoveMemberAndOwnerBots.mockResolvedValue({ id: "mem_1" })mockListOwnerBotsInServer.mockResolvedValue([])- mockRemoveOwnerBotsFromServer.mockResolvedValue(undefined)mockFanOut.mockResolvedValue(undefined)+ mockBroadcastToUserSafe.mockResolvedValue(undefined)})it("returns 204 and audits member_leave with the target member's id", async () => {@@ -96,7 +96,7 @@ describe("POST /api/community/servers/[id]/leave", () => {const res = await POST(postReq(), ctx)expect(res.status).toBe(403)expect(mockLogAudit).not.toHaveBeenCalled()- expect(mockRemoveMember).not.toHaveBeenCalled()+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()})it("returns 400 when the owner tries to leave (and does not audit)", async () => {@@ -105,7 +105,7 @@ describe("POST /api/community/servers/[id]/leave", () => {const res = await POST(postReq(), ctx)expect(res.status).toBe(400)expect(mockLogAudit).not.toHaveBeenCalled()- expect(mockRemoveMember).not.toHaveBeenCalled()+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()})it("bulk-removes owner bots in one call instead of getMember loops", async () => {@@ -113,8 +113,9 @@ describe("POST /api/community/servers/[id]/leave", () => {const res = await POST(postReq(), ctx)expect(res.status).toBe(204)- expect(mockRemoveOwnerBotsFromServer).toHaveBeenCalledWith(+ expect(mockRemoveMemberAndOwnerBots).toHaveBeenCalledWith(expect.anything(),+ "mem_1","s1",["bot_1", "bot_2"],)diff --git a/src/web/src/app/api/community/servers/[id]/leave/route.ts b/src/web/src/app/api/community/servers/[id]/leave/route.tsindex 5e011899e..7d19e8e59 100644--- a/src/web/src/app/api/community/servers/[id]/leave/route.ts+++ b/src/web/src/app/api/community/servers/[id]/leave/route.ts@@ -2,7 +2,7 @@ import { withAuth } from "@/lib/middleware/auth"import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries, isServerOwner, WS_EVENTS } from "@alook/shared"-import { fanOutToServerMembers } from "@/lib/community/fanout"+import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"import { requireServerMember } from "@/lib/community/permissions"@@ -30,8 +30,13 @@ export const POST = withAuth(async (_req, ctx) => {ctx.userId,)- await queries.communityMember.removeMember(db, member.id)- await queries.communityMember.removeOwnerBotsFromServer(db, serverId, botIdsToCascade)+ const removed = await queries.communityMember.removeMemberAndOwnerBots(+ db,+ member.id,+ serverId,+ botIdsToCascade,+ )+ if (!removed) return writeError("member not found", 404)logAudit(db, {serverId,@@ -51,18 +56,25 @@ export const POST = withAuth(async (_req, ctx) => {})}- fanOutToServerMembers(serverId, {+ const viewerLeaveEvent = {type: WS_EVENTS.MEMBER_LEAVE,serverId,userId: ctx.userId,- })- for (const botId of botIdsToCascade) {- fanOutToServerMembers(serverId, {+ } as const+ const botLeaveEvents = botIdsToCascade.map((botId) => ({type: WS_EVENTS.MEMBER_LEAVE,serverId,userId: botId,- })- }+ } as const))++ await Promise.all([+ fanOutToServerMembers(serverId, viewerLeaveEvent),+ broadcastToUserSafe(ctx.userId, viewerLeaveEvent),+ ...botLeaveEvents.flatMap((event) => [+ fanOutToServerMembers(serverId, event),+ broadcastToUserSafe(event.userId, event),+ ]),+ ])return new Response(null, { status: 204 })})diff --git a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.tsindex ad17c2b84..544d75281 100644--- a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.test.ts@@ -13,11 +13,11 @@ const mockGetMember = vi.fn()const mockGetMemberById = vi.fn()const mockListMembers = vi.fn()const mockUpdateRole = vi.fn()-const mockRemoveMember = vi.fn()-const mockRemoveOwnerBotsFromServer = vi.fn()+const mockRemoveMemberAndOwnerBots = vi.fn()const mockListOwnerBotsInServer = vi.fn()const mockLogAudit = vi.fn()const mockFanOut = vi.fn()+const mockBroadcastToUserSafe = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -31,8 +31,7 @@ vi.mock("@alook/shared", async () => {getMemberById: (...a: unknown[]) => mockGetMemberById(...a),listMembers: (...a: unknown[]) => mockListMembers(...a),updateRole: (...a: unknown[]) => mockUpdateRole(...a),- removeMember: (...a: unknown[]) => mockRemoveMember(...a),- removeOwnerBotsFromServer: (...a: unknown[]) => mockRemoveOwnerBotsFromServer(...a),+ removeMemberAndOwnerBots: (...a: unknown[]) => mockRemoveMemberAndOwnerBots(...a),listOwnerBotsInServer: (...a: unknown[]) => mockListOwnerBotsInServer(...a),},user: {@@ -57,6 +56,7 @@ vi.mock("@/lib/community/audit", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),}))vi.mock("@/lib/middleware/auth", () => ({@@ -119,6 +119,7 @@ describe("PATCH /api/community/servers/[id]/members/[memberId]", () => {role: "admin",})mockFanOut.mockResolvedValue(undefined)+ mockBroadcastToUserSafe.mockResolvedValue(undefined)})it("succeeds and calls getMemberById exactly once, listMembers zero times", async () => {@@ -190,10 +191,10 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {userEmail: "[email protected]",userImage: null,})- mockRemoveMember.mockResolvedValue({ id: "mem_target" })+ mockRemoveMemberAndOwnerBots.mockResolvedValue({ id: "mem_target" })mockListOwnerBotsInServer.mockResolvedValue([])- mockRemoveOwnerBotsFromServer.mockResolvedValue(undefined)mockFanOut.mockResolvedValue(undefined)+ mockBroadcastToUserSafe.mockResolvedValue(undefined)})it("succeeds and calls getMemberById exactly once, listMembers zero times", async () => {@@ -204,18 +205,27 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {expect(mockGetMemberById).toHaveBeenCalledWith(expect.anything(), "mem_target", { serverId: "srv_1" })expect(mockListMembers).not.toHaveBeenCalled()- expect(mockRemoveMember).toHaveBeenCalledWith(expect.anything(), "mem_target")+ expect(mockRemoveMemberAndOwnerBots).toHaveBeenCalledWith(+ expect.anything(),+ "mem_target",+ "srv_1",+ [],+ )expect(mockLogAudit).toHaveBeenCalledTimes(1)// Broadcast payload uses target.userId — proves the scoped helper's row// is what the fan-out reads.expect(mockFanOut).toHaveBeenCalledWith("srv_1", expect.objectContaining({ userId: "u_target" }))+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith(+ "u_target",+ expect.objectContaining({ type: "community:member.leave", userId: "u_target" }),+ )})it("returns 404 when the target member is not scoped to this server", async () => {mockGetMemberById.mockResolvedValue(null)const res = await DELETE(deleteReq(), ctx)expect(res.status).toBe(404)- expect(mockRemoveMember).not.toHaveBeenCalled()+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()expect(mockListMembers).not.toHaveBeenCalled()})@@ -231,7 +241,7 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {})const res = await DELETE(deleteReq(), ctx)expect(res.status).toBe(403)- expect(mockRemoveMember).not.toHaveBeenCalled()+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()})it("returns 403 when an admin tries to kick another admin (owner-only)", async () => {@@ -246,7 +256,7 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {})const res = await DELETE(deleteReq(), ctx)expect(res.status).toBe(403)- expect(mockRemoveMember).not.toHaveBeenCalled()+ expect(mockRemoveMemberAndOwnerBots).not.toHaveBeenCalled()})it("bulk-removes cascaded owner bots after kicking a human member", async () => {@@ -254,10 +264,15 @@ describe("DELETE /api/community/servers/[id]/members/[memberId]", () => {const res = await DELETE(deleteReq(), ctx)expect(res.status).toBe(204)- expect(mockRemoveOwnerBotsFromServer).toHaveBeenCalledWith(+ expect(mockRemoveMemberAndOwnerBots).toHaveBeenCalledWith(expect.anything(),+ "mem_target","srv_1",["bot_1"],)+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith(+ "bot_1",+ expect.objectContaining({ type: "community:member.leave", userId: "bot_1" }),+ )})})diff --git a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.tsindex e6247917d..ed4bab50b 100644--- a/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/[memberId]/route.ts@@ -10,7 +10,7 @@ import {ASSIGNABLE_ROLES,WS_EVENTS,} from "@alook/shared"-import { fanOutToServerMembers } from "@/lib/community/fanout"+import { broadcastToUserSafe, fanOutToServerMembers } from "@/lib/community/fanout"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"import { requireServerAdmin } from "@/lib/community/permissions"@@ -112,11 +112,14 @@ export const DELETE = withAuth(async (_req, ctx) => {)}- const removed = await queries.communityMember.removeMember(db, memberId)+ const removed = await queries.communityMember.removeMemberAndOwnerBots(+ db,+ memberId,+ serverId,+ botIdsToCascade,+ )if (!removed) return writeError("member not found", 404)- await queries.communityMember.removeOwnerBotsFromServer(db, serverId, botIdsToCascade)-logAudit(db, {serverId,actorId: ctx.userId,@@ -140,18 +143,28 @@ export const DELETE = withAuth(async (_req, ctx) => {})}- fanOutToServerMembers(serverId, {+ const targetLeaveEvent = {type: WS_EVENTS.MEMBER_LEAVE,serverId,userId: target.userId,- })- for (const botId of botIdsToCascade) {- fanOutToServerMembers(serverId, {+ } as const+ const botLeaveEvents = botIdsToCascade.map((botId) => ({type: WS_EVENTS.MEMBER_LEAVE,serverId,userId: botId,- })- }+ } as const))++ // The server-wide fan-out resolves recipients after the membership delete,+ // so the removed identities are no longer in that set. Send them directly+ // as well: their other tabs/daemons need the event to eject stale access.+ await Promise.all([+ fanOutToServerMembers(serverId, targetLeaveEvent),+ broadcastToUserSafe(target.userId, targetLeaveEvent),+ ...botLeaveEvents.flatMap((event) => [+ fanOutToServerMembers(serverId, event),+ broadcastToUserSafe(event.userId, event),+ ]),+ ])return new Response(null, { status: 204 })})diff --git a/src/web/src/components/community/community-panel-sheet.tsx b/src/web/src/components/community/community-panel-sheet.tsxindex 0f9d1b119..0c60f2425 100644--- a/src/web/src/components/community/community-panel-sheet.tsx+++ b/src/web/src/components/community/community-panel-sheet.tsx@@ -54,7 +54,7 @@ export function CommunityPanelSheet({threadsLoading?: booleanonOpenThread: (id: string) => voidonOpenProfile?: OpenProfile- onSetRole?: (name: string, role: Role) => void+ onSetRole?: (memberId: string, role: Role) => voidonKickMember?: (memberId: string) => Promise<unknown> | voidmyRole?: RoleonJumpToMessage?: (seq: number) => voiddiff --git a/src/web/src/components/community/member-list.test.ts b/src/web/src/components/community/member-list.test.tsindex 0ab17887e..0c8c4b83c 100644--- a/src/web/src/components/community/member-list.test.ts+++ b/src/web/src/components/community/member-list.test.ts@@ -1,4 +1,7 @@import { describe, it, expect } from "vitest"+import fs from "node:fs"+import path from "node:path"+import { fileURLToPath } from "node:url"import { computeDuplicateNames, hasMemberMenu } from "./member-list"import type { Member } from "./_types"@@ -64,3 +67,14 @@ describe("hasMemberMenu", () => {expect(hasMemberMenu(true, "admin")).toBe(true)})})++describe("member action identity contract", () => {+ it("sends the stable member id, never the display name, to role mutations", () => {+ const source = fs.readFileSync(+ path.join(path.dirname(fileURLToPath(import.meta.url)), "member-list.tsx"),+ "utf8",+ )+ expect(source).toContain("onSetRole?.(mem.id, r)")+ expect(source).not.toContain("onSetRole?.(mem.name, r)")+ })+})diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsxindex 45ff30b9c..b232285de 100644--- a/src/web/src/components/community/member-list.tsx+++ b/src/web/src/components/community/member-list.tsx@@ -114,7 +114,7 @@ export function MemberList({manageContext?: MemberManageContextmyRole?: RoleonOpenProfile?: OpenProfile- onSetRole?: (name: string, role: Role) => void+ onSetRole?: (memberId: string, role: Role) => voidonKick?: (memberId: string) => Promise<unknown> | void}) {// Kick target stores BOTH the display name (for the confirm title) and the@@ -148,6 +148,10 @@ export function MemberList({...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,count: items.length,getScrollElement: () => scrollRef.current,+ // React also keys these rows by `item.key`. Keep TanStack Virtual on the+ // same identity axis so an insert/re-group does not leave a reused DOM+ // node registered under its old numeric index in direct-DOM mode.+ getItemKey: (index) => items[index]?.key ?? index,estimateSize: (index) => (items[index]?.kind === "header" ? HEADER_HEIGHT : ROW_HEIGHT),overscan: 8,})@@ -337,7 +341,7 @@ function MemberRow({// `#0042` discriminator is worth showing.showDiscriminator: booleanonOpenProfile?: OpenProfile- onSetRole?: (name: string, role: Role) => void+ onSetRole?: (memberId: string, role: Role) => void// Opens the server-kick confirm — receives the member so the caller can key// the DELETE on the member row id (not the display name).onKick: (mem: Member) => void@@ -416,7 +420,7 @@ function MemberRow({</ContextMenuSubTrigger><ContextMenuSubContent>{SETTABLE_ROLES.map((r) => (- <ContextMenuItem key={r} onClick={() => onSetRole?.(mem.name, r)}>+ <ContextMenuItem key={r} onClick={() => onSetRole?.(mem.id, r)}><span className="flex-1">{capitalize(r)}</span>{mem.role === r && <Check className="size-4" />}</ContextMenuItem>diff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/right-panel.tsxindex 8ae28f7da..6704fc87e 100644--- a/src/web/src/components/community/right-panel.tsx+++ b/src/web/src/components/community/right-panel.tsx@@ -41,7 +41,7 @@ export function RightPanelContent({showSearchInput?: booleanonOpenThread: (id: string) => voidonOpenProfile?: OpenProfile- onSetRole?: (name: string, role: Role) => void+ onSetRole?: (memberId: string, role: Role) => voidonKickMember?: (memberId: string) => Promise<unknown> | voidmyRole?: Role// Jump to a pinned message by its per-channel seq — routes through the samediff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsxindex 3fe887f0d..a539551e4 100644--- a/src/web/src/components/community/server-settings.tsx+++ b/src/web/src/components/community/server-settings.tsx@@ -252,6 +252,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,count: members.length,getScrollElement: () => scrollRef.current,+ getItemKey: (index) => members[index]?.id ?? index,estimateSize: () => SETTINGS_ROW_HEIGHT,overscan: 8,})diff --git a/src/web/src/components/community/virtualizer-direct-dom.contract.test.ts b/src/web/src/components/community/virtualizer-direct-dom.contract.test.tsindex d9e1fb7d7..509dfdf09 100644--- a/src/web/src/components/community/virtualizer-direct-dom.contract.test.ts+++ b/src/web/src/components/community/virtualizer-direct-dom.contract.test.ts@@ -37,6 +37,7 @@ describe("community virtualizer direct DOM contract", () => {expect(memberList).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")expect(memberList).toContain("ref={rowVirtualizer.containerRef}")expect(memberList).toContain("ref={rowVirtualizer.measureElement}")+ expect(memberList).toContain("getItemKey: (index) => items[index]?.key ?? index")expect(memberList).not.toContain("rowVirtualizer.getTotalSize()")expect(memberList).not.toContain("virtualRow.start")})@@ -47,6 +48,7 @@ describe("community virtualizer direct DOM contract", () => {expect(serverSettings).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")expect(serverSettings).toContain("ref={rowVirtualizer.containerRef}")expect(serverSettings).toContain("ref={rowVirtualizer.measureElement}")+ expect(serverSettings).toContain("getItemKey: (index) => members[index]?.id ?? index")expect(serverSettings).not.toContain("rowVirtualizer.getTotalSize()")expect(serverSettings).not.toContain("virtualRow.start")})diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.tsindex 985432c91..6d7350be5 100644--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts@@ -2,6 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate } from "@alook/shared"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import { communityKeys } from "@/lib/query-keys"+import {+ subscribeMemberOverlayEvents,+ type MemberOverlayEvent,+} from "@/hooks/community/use-server-members"import {capturedOnMessage,capturedQueryClient,@@ -70,6 +74,34 @@ describe("useCommunityWs — member events", () => {expect(cache?.pages[0].total).toBe(1)})+ it("forwards WS membership changes onto the server-scoped search overlay bus", async () => {+ await mountHook()+ const received: MemberOverlayEvent[] = []+ const unsubscribe = subscribeMemberOverlayEvents((event) => received.push(event))++ capturedOnMessage!({+ type: "community:member.leave",+ serverId: "srv_1",+ userId: "u_gone",+ } satisfies CommunityMemberLeave)+ capturedOnMessage!({+ type: "community:member.update",+ serverId: "srv_1",+ memberId: "mem_1",+ changes: { role: "admin" },+ } satisfies CommunityMemberUpdate)+ unsubscribe()++ expect(received).toEqual([+ { type: "leave", serverId: "srv_1", userId: "u_gone" },+ {+ type: "update",+ serverId: "srv_1",+ event: expect.objectContaining({ memberId: "mem_1" }),+ },+ ])+ })+it("a self-rename (member.update with userId + changes.nickname) patches authorName in every cached channel/DM message list", async () => {await mountHook()useMessageStreamStore.getState().dispatch(diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 7ddb49228..bb3c23746 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -12,6 +12,7 @@ import {patchCacheJoin,patchCacheLeave,patchCacheUpdate,+ dispatchMemberOverlayEvent,type MembersEnvelope,} from "@/hooks/community/use-server-members"import {@@ -116,6 +117,7 @@ export function handleMemberJoin(key,(cache) => patchCacheJoin(cache, event),)+ dispatchMemberOverlayEvent({ type: "refresh", serverId: event.serverId })finishMemberEvent(event, context)}@@ -129,6 +131,11 @@ export function handleMemberLeave(key,(cache) => patchCacheLeave(cache, event),)+ dispatchMemberOverlayEvent({+ type: "leave",+ serverId: event.serverId,+ userId: event.userId,+ })// If the leaver is the viewer (kick from another tab / owner// cascade), the viewer's server rail is stale — invalidate it// so the layout's eject effect can detect the drop and route@@ -160,6 +167,11 @@ export function handleMemberUpdate(key,(cache) => patchCacheUpdate(cache, event),)+ dispatchMemberOverlayEvent({+ type: "update",+ serverId: event.serverId,+ event,+ })// A self-rename carries `userId` + `changes.nickname` — patch// every cached message list's `authorName` snapshot for that// author. A role-only change has no `userId`/`nickname`, sodiff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 33676703b..680f759ba 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -55,6 +55,11 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {k[3] === "messages",),).toBe(true)+ expect(+ invalidatedKeys.some(+ (k) => JSON.stringify(k) === JSON.stringify(communityKeys.channelMembers("ch_focus")),+ ),+ ).toBe(true)// Read-state snapshot MUST NOT be invalidated: the snapshot hook latches// its first value (gcTime: 0, frozen ref) so a refetch can't move the// "New" divider — it only flips `isFetching` back to true, which the@@ -112,6 +117,11 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {k[2] === "srv_open",),).toBe(true)+ expect(+ invalidatedKeys.some(+ (k) => JSON.stringify(k) === JSON.stringify(communityKeys.members("srv_open")),+ ),+ ).toBe(true)})it("drops every inactive retained/meta/hint access result before reconnect validation", async () => {diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.tsindex 22c5a1252..d570c5dcd 100644--- a/src/web/src/hooks/community/community-ws/reconnect.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.ts@@ -48,6 +48,12 @@ export function reconcileCommunityWsReconnect(queryClient: QueryClient) {void queryClient.invalidateQueries({queryKey: communityKeys.channelMessages(sub.channelId),})+ // Channel/thread rosters are live-patched from membership/message events.+ // A socket gap can miss those patches even while navigator.onLine remains+ // true, so TanStack's refetchOnReconnect is not a sufficient backstop.+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelMembers(sub.channelId),+ })}if (sub.dmConversationId) {void queryClient.invalidateQueries({@@ -77,6 +83,10 @@ export function reconcileCommunityWsReconnect(queryClient: QueryClient) {queryKey: communityKeys.server(currentServerId),exact: true,})+ void queryClient.invalidateQueries({+ queryKey: communityKeys.members(currentServerId),+ exact: true,+ })void invalidateForumSidebarBaseExact(queryClient, currentServerId)queryClient.removeQueries({queryKey: communityKeys.forumSidebarRetainedRoot(currentServerId),diff --git a/src/web/src/hooks/community/mutations/members.test.ts b/src/web/src/hooks/community/mutations/members.test.tsindex c63d9ac54..a56c9f14a 100644--- a/src/web/src/hooks/community/mutations/members.test.ts+++ b/src/web/src/hooks/community/mutations/members.test.ts@@ -82,12 +82,16 @@ describe("useSetMemberRole — optimistic + rollback", () => {})apiFetchMock.mockRejectedValueOnce(new Error("boom"))const mod = await load()+ const received: MemberOverlayEvent[] = []+ const unsub = mod.shared.subscribeMemberOverlayEvents((ev) => received.push(ev))mod.useSetMemberRole()await runMutation({ serverId: "srv_1", memberId: "mem_1", role: "admin" }).catch(() => {})+ unsub()const cache = capturedQc.getQueryData<{ pages: { members: { role: string }[] }[] }>(communityKeys.members("srv_1"),)expect(cache?.pages[0].members[0].role).toBe("member")+ expect(received).toContainEqual({ type: "refresh", serverId: "srv_1" })})it("dispatches a member-overlay 'role' event so search results mirror the change", async () => {@@ -98,7 +102,12 @@ describe("useSetMemberRole — optimistic + rollback", () => {mod.useSetMemberRole()await runMutation({ serverId: "srv_1", memberId: "mem_1", role: "admin" })unsub()- expect(received).toContainEqual({ type: "role", memberId: "mem_1", role: "admin" })+ expect(received).toContainEqual({+ type: "role",+ serverId: "srv_1",+ memberId: "mem_1",+ role: "admin",+ })})})@@ -119,12 +128,16 @@ describe("useKickMember — optimistic + rollback", () => {})apiFetchMock.mockRejectedValueOnce(new Error("boom"))const mod = await load()+ const received: MemberOverlayEvent[] = []+ const unsub = mod.shared.subscribeMemberOverlayEvents((ev) => received.push(ev))mod.useKickMember()await runMutation({ serverId: "srv_1", memberId: "mem_1" }).catch(() => {})+ unsub()const cache = capturedQc.getQueryData<{ pages: { members: { id: string }[] }[] }>(communityKeys.members("srv_1"),)expect(cache?.pages[0].members).toHaveLength(1)+ expect(received).toContainEqual({ type: "refresh", serverId: "srv_1" })})it("dispatches a member-overlay 'kick' event so search results drop the row", async () => {@@ -135,6 +148,6 @@ describe("useKickMember — optimistic + rollback", () => {mod.useKickMember()await runMutation({ serverId: "srv_1", memberId: "mem_1" })unsub()- expect(received).toContainEqual({ type: "kick", memberId: "mem_1" })+ expect(received).toContainEqual({ type: "kick", serverId: "srv_1", memberId: "mem_1" })})})diff --git a/src/web/src/hooks/community/mutations/members.ts b/src/web/src/hooks/community/mutations/members.tsindex c40eb3cd0..20ae2d8b5 100644--- a/src/web/src/hooks/community/mutations/members.ts+++ b/src/web/src/hooks/community/mutations/members.ts@@ -51,11 +51,17 @@ export function useSetMemberRole() {// is in flight (and after — the server won't fan out a MEMBER_UPDATE// to the acting client, so this is the only source of truth for the// overlay).- dispatchMemberOverlayEvent({ type: "role", memberId: args.memberId, role: args.role })+ dispatchMemberOverlayEvent({+ type: "role",+ serverId: args.serverId,+ memberId: args.memberId,+ role: args.role,+ })return { snapshot }},onError: (_err, args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.members(args.serverId), ctx.snapshot)+ dispatchMemberOverlayEvent({ type: "refresh", serverId: args.serverId })},})}@@ -80,11 +86,16 @@ export function useKickMember() {patchCacheKick(cache, args.memberId),)// Mirror the removal onto any active search overlay.- dispatchMemberOverlayEvent({ type: "kick", memberId: args.memberId })+ dispatchMemberOverlayEvent({+ type: "kick",+ serverId: args.serverId,+ memberId: args.memberId,+ })return { snapshot }},onError: (_err, args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.members(args.serverId), ctx.snapshot)+ dispatchMemberOverlayEvent({ type: "refresh", serverId: args.serverId })},})}diff --git a/src/web/src/hooks/community/use-server-members.test.ts b/src/web/src/hooks/community/use-server-members.test.tsindex 5436989ef..42225bdf5 100644--- a/src/web/src/hooks/community/use-server-members.test.ts+++ b/src/web/src/hooks/community/use-server-members.test.ts@@ -324,13 +324,13 @@ describe("member overlay bus", () => {it("delivers dispatched events to subscribers, and unsubscribe stops delivery", () => {const received: MemberOverlayEvent[] = []const unsub = subscribeMemberOverlayEvents((ev) => received.push(ev))- dispatchMemberOverlayEvent({ type: "kick", memberId: "mem_1" })- dispatchMemberOverlayEvent({ type: "role", memberId: "mem_1", role: "admin" })+ dispatchMemberOverlayEvent({ type: "kick", serverId: "srv_1", memberId: "mem_1" })+ dispatchMemberOverlayEvent({ type: "role", serverId: "srv_1", memberId: "mem_1", role: "admin" })expect(received).toHaveLength(2)- expect(received[0]).toEqual({ type: "kick", memberId: "mem_1" })- expect(received[1]).toEqual({ type: "role", memberId: "mem_1", role: "admin" })+ expect(received[0]).toEqual({ type: "kick", serverId: "srv_1", memberId: "mem_1" })+ expect(received[1]).toEqual({ type: "role", serverId: "srv_1", memberId: "mem_1", role: "admin" })unsub()- dispatchMemberOverlayEvent({ type: "kick", memberId: "mem_2" })+ dispatchMemberOverlayEvent({ type: "kick", serverId: "srv_1", memberId: "mem_2" })expect(received).toHaveLength(2)})@@ -345,7 +345,7 @@ describe("member overlay bus", () => {overlay = overlay.filter((x) => x.id !== ev.memberId)}})- dispatchMemberOverlayEvent({ type: "kick", memberId: "mem_2" })+ dispatchMemberOverlayEvent({ type: "kick", serverId: "srv_1", memberId: "mem_2" })expect(overlay?.map((x) => x.id)).toEqual(["mem_1", "mem_3"])unsub()})diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex 42a18e4a7..6aa768ca8 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -219,13 +219,14 @@ export function patchCacheRole(//// The bus below lets mutations broadcast overlay-affecting events without// coupling to the hook instance. `useServerMembers` subscribes and mirror--// patches its `searchResults` state; if there's no active search the events+// patches its search overlay state; if there's no active search the events// are a no-op.export type MemberOverlayEvent =- | { type: "kick"; memberId: string }- | { type: "role"; memberId: string; role: CommunityRole }- | { type: "update"; event: CommunityMemberUpdate }- | { type: "leave"; userId: string }+ | { type: "kick"; serverId: string; memberId: string }+ | { type: "role"; serverId: string; memberId: string; role: CommunityRole }+ | { type: "update"; serverId: string; event: CommunityMemberUpdate }+ | { type: "leave"; serverId: string; userId: string }+ | { type: "refresh"; serverId: string }const memberOverlayBus =typeof EventTarget !== "undefined" ? new EventTarget() : null@@ -263,7 +264,6 @@ export type UseServerMembers = {loadMore: () => voidreset: () => voidrefresh: () => void- handleMemberEvent: (event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate) => voidsearchMembers: (q: string) => void// Optimistic-UI hooks for the caller's role/kick mutations. The server// fans out MEMBER_UPDATE / MEMBER_LEAVE on success; these keep the local@@ -283,11 +283,10 @@ export type UseServerMembers = {* (no pagination, no cursor) and we don't want to blow away cursor state* when the user starts typing.*- * WS events flow through `handleMemberEvent`, which patches the cache- * directly via `queryClient.setQueryData`. Callers of `applyRoleChange` /- * `applyKick` do the same for optimistic mutations. Search-view state is- * patched in parallel so the visible list stays consistent while the user- * is searching.+ * WS events patch the shared paged cache in `community-ws/membership-events`+ * and notify the overlay bus above. Optimistic mutations use the same cache+ * helpers. Search-view state is patched or re-fetched in parallel so it+ * cannot diverge from the paged view.*/export function useServerMembers(serverId: string | null): UseServerMembers {const enabled = !!serverId@@ -319,16 +318,20 @@ export function useServerMembers(serverId: string | null): UseServerMembers {enabled,// WS `member.join/leave/update` live-patch this roster cache, so a remount// doesn't need to refetch — this is a once-per-server seed. staleTime:- // Infinity stops the per-channel-switch refetch; refetchOnReconnect- // backstops the socket-gap case (the WS reconnect handler does not re-seed- // the member roster), so events missed while offline can't leave it- // permanently stale.+ // Infinity stops the per-channel-switch refetch. Browser network reconnect+ // and the explicit WS reconnect reconciler both re-seed this query so an+ // event missed during a socket-only gap cannot leave it permanently stale.staleTime: Infinity,refetchOnReconnect: true,})// ── Search state ────────────────────────────────────────────────────────- const [searchResults, setSearchResults] = useState<Member[] | null>(null)+ const [searchOverlay, setSearchOverlay] = useState<{+ serverId: string | null+ members: Member[]+ } | null>(null)+ const activeSearchQuery = useRef("")+ const searchActive = useRef(false)const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null)// Monotonic sequence so out-of-order responses drop old results silently.const searchSeq = useRef(0)@@ -351,7 +354,9 @@ export function useServerMembers(serverId: string | null): UseServerMembers {}, [infinite])const reset = useCallback(() => {- setSearchResults(null)+ activeSearchQuery.current = ""+ searchActive.current = false+ setSearchOverlay(null)if (searchTimer.current) {clearTimeout(searchTimer.current)searchTimer.current = null@@ -371,7 +376,9 @@ export function useServerMembers(serverId: string | null): UseServerMembers {// serverId so they don't need explicit teardown — TanStack Query GC's them// and enable=false stops any in-flight fetch).useEffect(() => {- setSearchResults(null)+ activeSearchQuery.current = ""+ searchActive.current = false+ setSearchOverlay(null)if (searchTimer.current) {clearTimeout(searchTimer.current)searchTimer.current = null@@ -379,38 +386,6 @@ export function useServerMembers(serverId: string | null): UseServerMembers {searchSeq.current += 1}, [serverId])- const handleMemberEvent = useCallback(- (event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate) => {- if (!enabled) return- if (event.type === "community:member.join") {- queryClient.setQueryData<MembersPageCache | undefined>(queryKey, (cache) =>- patchCacheJoin(cache, event),- )- return- }- if (event.type === "community:member.leave") {- queryClient.setQueryData<MembersPageCache | undefined>(queryKey, (cache) =>- patchCacheLeave(cache, event),- )- // Keep the search overlay consistent so the visible list matches.- setSearchResults((prev) =>- prev === null ? null : prev.filter((m) => m.userId !== event.userId),- )- return- }- // member.update- queryClient.setQueryData<MembersPageCache | undefined>(queryKey, (cache) =>- patchCacheUpdate(cache, event),- )- setSearchResults((prev) =>- prev === null- ? null- : applyUpdateEvent(prev, event),- )- },- [enabled, queryClient, queryKey],- )-const runSearch = useCallback(async (q: string, seq: number) => {if (!enabled) return@@ -421,10 +396,10 @@ export function useServerMembers(serverId: string | null): UseServerMembers {)// Guard against out-of-order responses.if (searchSeq.current !== seq) return- setSearchResults(data.members)+ setSearchOverlay({ serverId, members: data.members })} catch (e) {if (searchSeq.current === seq) {- setSearchResults([])+ setSearchOverlay({ serverId, members: [] })toastApiError(e, "Search failed")}}@@ -441,9 +416,13 @@ export function useServerMembers(serverId: string | null): UseServerMembers {}searchSeq.current += 1if (trimmed.length === 0) {- setSearchResults(null)+ activeSearchQuery.current = ""+ searchActive.current = false+ setSearchOverlay(null)return}+ activeSearchQuery.current = trimmed+ searchActive.current = trueconst seq = searchSeq.currentsearchTimer.current = setTimeout(() => {searchTimer.current = null@@ -459,8 +438,15 @@ export function useServerMembers(serverId: string | null): UseServerMembers {queryClient.setQueryData<MembersPageCache | undefined>(queryKey, (cache) =>patchCacheRole(cache, memberId, role),)- setSearchResults((prev) =>- prev === null ? null : prev.map((m) => (m.id === memberId ? { ...m, role } : m)),+ setSearchOverlay((prev) =>+ prev === null+ ? null+ : {+ ...prev,+ members: prev.members.map((m) =>+ m.id === memberId ? { ...m, role } : m,+ ),+ },)},[enabled, queryClient, queryKey],@@ -472,8 +458,10 @@ export function useServerMembers(serverId: string | null): UseServerMembers {queryClient.setQueryData<MembersPageCache | undefined>(queryKey, (cache) =>patchCacheKick(cache, memberId),)- setSearchResults((prev) =>- prev === null ? null : prev.filter((m) => m.id !== memberId),+ setSearchOverlay((prev) =>+ prev === null+ ? null+ : { ...prev, members: prev.members.filter((m) => m.id !== memberId) },)},[enabled, queryClient, queryKey],@@ -487,40 +475,68 @@ export function useServerMembers(serverId: string | null): UseServerMembers {}}, [])- // Mirror-patch the search overlay from mutation-side events. Member ids are- // server-scoped so a filter/map by memberId is safe regardless of which- // server currently owns the overlay.+ const refreshSearchOverlay = useCallback(() => {+ if (!searchActive.current) return+ const q = activeSearchQuery.current+ if (!q) return+ searchSeq.current += 1+ const seq = searchSeq.current+ void runSearch(q, seq)+ }, [runSearch])++ // Mirror-patch the search overlay from mutation and WS events. Every event+ // carries serverId so a transitioning hook cannot patch results retained+ // from another server. Nickname/join/rollback events re-run the active+ // search because they can change whether a row matches at all.useEffect(() => {return subscribeMemberOverlayEvents((ev) => {- setSearchResults((prev) => {+ if (ev.serverId !== serverId) return+ if (ev.type === "refresh") {+ refreshSearchOverlay()+ return+ }+ if (ev.type === "update" && ev.event.changes.nickname !== undefined) {+ refreshSearchOverlay()+ return+ }+ setSearchOverlay((prev) => {if (prev === null) return prevswitch (ev.type) {case "kick":- return prev.filter((m) => m.id !== ev.memberId)+ return { ...prev, members: prev.members.filter((m) => m.id !== ev.memberId) }case "role":- return prev.map((m) => (m.id === ev.memberId ? { ...m, role: ev.role } : m))+ return {+ ...prev,+ members: prev.members.map((m) =>+ m.id === ev.memberId ? { ...m, role: ev.role } : m,+ ),+ }case "update":- return applyUpdateEvent(prev, ev.event)+ return { ...prev, members: applyUpdateEvent(prev.members, ev.event) }case "leave":- return prev.filter((m) => m.userId !== ev.userId)+ return { ...prev, members: prev.members.filter((m) => m.userId !== ev.userId) }default:return prev}})})- }, [])+ }, [refreshSearchOverlay, serverId])++ // A server switch renders before the cleanup effect above runs. Never expose+ // the previous server's local search overlay during that transition frame.+ const isSearchingCurrentServer =+ searchOverlay !== null && searchOverlay.serverId === serverIdreturn {- members: searchResults ?? pagedMembers,+ members: isSearchingCurrentServer ? searchOverlay.members : pagedMembers,loading: infinite.isPending && enabled,loadingMore: infinite.isFetchingNextPage,hasMore,total,- isSearching: searchResults !== null,+ isSearching: isSearchingCurrentServer,loadMore,reset,refresh,- handleMemberEvent,searchMembers,applyRoleChange,applyKick,diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 9e5576822..6b74908cc 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -150,6 +150,31 @@ describe("fanOutToServerMembers", () => {)})+ it("registers recipient resolution with waitUntil before the D1 read settles", async () => {+ const waitUntil = vi.fn()+ mockGetCloudflareContext.mockImplementation(() => ({+ env: { DB: {} },+ ctx: { waitUntil },+ }))+ let release!: (ids: string[]) => void+ mockListMemberUserIds.mockReturnValue(new Promise<string[]>((resolve) => {+ release = resolve+ }))++ const work = fanOutToServerMembers("srv_1", {+ type: WS_EVENTS.MEMBER_UPDATE,+ serverId: "srv_1",+ memberId: "m1",+ changes: { role: "admin" },+ })++ expect(waitUntil).toHaveBeenCalledWith(work)+ expect(mockBroadcastToUsers).not.toHaveBeenCalled()+ release(["u1"])+ await work+ expect(mockBroadcastToUsers).toHaveBeenCalledTimes(1)+ })+it("fanOutToChannel resolves recipients via the shared channel recipient resolver", async () => {mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex bcbec7b6e..9f1c976dc 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -242,22 +242,39 @@ export async function fanOutStatusUpdate(/*** Fan out an event to all members of a server.*/-export async function fanOutToServerMembers(+export function fanOutToServerMembers(serverId: string,event: BroadcastableEvent,opts?: { excludeUserId?: string }): Promise<void> {try {- const { env } = getCloudflareContext()+ const { env, ctx } = getCloudflareContext()const db = getDb((env as Env).DB)- const userIds = await getServerMemberUserIds(db, serverId)- await broadcastToRecipients(userIds, event, opts?.excludeUserId)+ // Register the whole recipient-resolution + broadcast chain immediately.+ // Most mutation routes intentionally fire-and-forget this helper; without+ // an outer waitUntil the worker may finish after the D1 await but before+ // broadcastToUsers gets a chance to register its own lifetime promise.+ const work = (async () => {+ try {+ const userIds = await getServerMemberUserIds(db, serverId)+ await broadcastToRecipients(userIds, event, opts?.excludeUserId)+ } catch (err) {+ log.warn("fanout_to_server_members_failed", {+ eventType: event.type,+ targetId: serverId,+ err: String(err),+ })+ }+ })()+ try { ctx.waitUntil(work) } catch { /* non-CF test/runtime context */ }+ return work} catch (err) {log.warn("fanout_to_server_members_failed", {eventType: event.type,targetId: serverId,err: String(err),})+ return Promise.resolve()}}diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 8fe165d7d..b81fb8d71 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -640,6 +640,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-adit("thread: author joins as 'spoke'; a non-audience mention is dropped (no channel auto-add)", async () => {mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob", channelId: "t1" }))+ mockAddThreadParticipants.mockResolvedValueOnce(["author_1"])await createCommunityMessage({db: {} as never,@@ -657,6 +658,12 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad// and NEVER auto-added to the channel roster.expect(mockCreateChannelMember).not.toHaveBeenCalled()expect(mockCreateMentions).not.toHaveBeenCalled()+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("author_1", {+ type: "community:channel.member_add",+ serverId: "srv_1",+ channelId: "t1",+ userId: "author_1",+ })})it("thread: an in-audience @mention joins as a participant + gets a mention row", async () => {diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 869009b58..74f0381bd 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -14,7 +14,7 @@ import {} from "@alook/shared"import type { MentionType } from "@alook/shared"import type { Database } from "@alook/shared"-import { fanOutToChannel, resolveChannelRecipients } from "./fanout"+import { broadcastToUserSafe, fanOutToChannel, resolveChannelRecipients } from "./fanout"import { dispatchMessageNotify } from "./notify"import { mapMessageForWs } from "./message-payload"import { attachmentUrl } from "./storage"@@ -691,6 +691,7 @@ export async function createCommunityMessage(params: {// parent CHILD_CHANNEL_UPDATE tick), which merely coincides with participant-set// for today's types — a future type could have a parent but server reach, or// participant reach without a parent, so the two rules stay separate.+ let joinedParticipantUserIds: string[] = []if (reachIsParticipantSet(target.kind) && !skipMentions) {const rows: { userId: string; source: typeof PARTICIPANT_SOURCE.SPOKE | typeof PARTICIPANT_SOURCE.MENTION }[] = [{ userId: authorId, source: PARTICIPANT_SOURCE.SPOKE },@@ -704,7 +705,8 @@ export async function createCommunityMessage(params: {if (id !== authorId) rows.push({ userId: id, source: PARTICIPANT_SOURCE.MENTION })}// One bulk insert (author + mentioned) instead of N+1 sequential inserts.- await queries.communityThread.addThreadParticipants(db, target.channelId, rows)+ joinedParticipantUserIds =+ await queries.communityThread.addThreadParticipants(db, target.channelId, rows) ?? []}// Mention/reply ROW writes are persistence, not broadcast — they run inline@@ -779,6 +781,19 @@ export async function createCommunityMessage(params: {// self-contained, defaulting to `all`).const recipients = await resolveChannelRecipients(db, target.channelId)+ // Normal message fan-out excludes the author because their optimistic row+ // is reconciled from the POST response. If this send newly enrolled them+ // in a thread's notify set, send a membership event directly so their own+ // open Members drawer and sidebar participation state also refresh.+ if (joinedParticipantUserIds.includes(authorId) && !isDmTarget(target)) {+ void broadcastToUserSafe(authorId, {+ type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ serverId: target.serverId,+ channelId: target.channelId,+ userId: authorId,+ })+ }+fanOutToChannel(target.channelId,{