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(web): separate thread content and notification audiences (#722)
Gener4e81a2ffc803
diff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjsindex ec75b225e..aad81b592 100644--- a/scripts/ci/changed-scopes.mjs+++ b/scripts/ci/changed-scopes.mjs@@ -43,6 +43,7 @@ const COVERAGE_EXCLUDES = [/^src\/web\/readme-capture\//,/^src\/web\/src\/.*\.tsx$/,/^src\/web\/src\/test\/fixtures\//,+ /^src\/web\/src\/test\/(?:e2e|e2e-ui)\//,/^src\/web\/src\/hooks\/(?:use-agent-chat|use-chat-sheets|use-file-attachments|use-message-flags|use-text-selection-quote)\.ts$/,/^src\/web\/src\/components\/agent-chat\/use-rotating-placeholder\.ts$/,]diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.tsindex 51d8de5d2..0fed85b1d 100644--- a/scripts/ci/changed-scopes.test.ts+++ b/scripts/ci/changed-scopes.test.ts@@ -310,6 +310,23 @@ describe("canonical execution plan", () => {})describe("coverage name-status contract", () => {+ it("excludes E2E support files according to Web's Vitest project boundary", () => {+ const webConfig = readFileSync("src/web/vitest.config.ts", "utf8")+ expect(webConfig).toContain('"src/test/e2e/**"')+ expect(webConfig).toContain('"src/test/e2e-ui/**"')+ const fixtures = [+ "src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts",+ "src/web/src/test/e2e-ui/_setup/global-setup.ts",+ "src/web/src/test/e2e/_fixtures/session.ts",+ ]+ const product = "src/web/src/lib/community/message-dispatcher.ts"+ const lookalike = "src/web/src/test/e2e-ui-helpers/session.ts"+ const result = plan([...fixtures, product, lookalike])+ expect(result.coverage.required_changed_files).toEqual([product, lookalike])+ expect(result.jobs.ui_e2e).toBe(true)+ expect(result.coverage.targets).toContain("web")+ })+it("requires surviving A/M and rename/copy new sides but not deleted or old paths", () => {const result = buildExecutionPlan([{ status: "A", path: "src/cli/src/added.ts" },diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 3d04e2b6f..cd1881d8f 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -71,7 +71,7 @@ describe("planE2eShards", () => {expect(first).toHaveLength(E2E_SHARD_COUNT)expect([...assigned].sort()).toEqual(specs)expect(new Set(assigned).size).toBe(specs.length)- expect(totals.sort((left, right) => left - right)).toEqual([582, 585, 585, 586, 587])+ expect(totals.sort((left, right) => left - right)).toEqual([597, 597, 597, 597, 597])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex 71f4252f3..357ef3507 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -191,6 +191,11 @@"key": "src/shared/src/db/queries/community/channel.ts:deleteChannelMemberAndChildParticipants:inArray:1","strategy": "subquery"},+ {+ "key": "src/shared/src/db/queries/community/channel.ts:filterChannelReadableUserIds:inArray:1",+ "strategy": "exact-chunk",+ "fixedParams": 10+ },{"key": "src/shared/src/db/queries/community/channel.ts:getChannelsByIds:inArray:1","strategy": "exact-chunk",@@ -206,6 +211,11 @@"strategy": "exact-chunk","fixedParams": 10},+ {+ "key": "src/shared/src/db/queries/community/channel.ts:listReadableChannelsForUser:inArray:1",+ "strategy": "exact-chunk",+ "fixedParams": 10+ },{"key": "src/shared/src/db/queries/community/channel.ts:resolveVisibleChannelIdSet:inArray:1","strategy": "exact-chunk",diff --git a/scripts/ci/verify-coverage-plan.test.ts b/scripts/ci/verify-coverage-plan.test.tsindex 0a9715c38..70d13926a 100644--- a/scripts/ci/verify-coverage-plan.test.ts+++ b/scripts/ci/verify-coverage-plan.test.ts@@ -30,6 +30,22 @@ function resignPlan(value) {}describe("verifyCoveragePlan", () => {+ it("permits an excluded E2E fixture without hiding missing product coverage", () => {+ const fixture = "src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts"+ const product = "src/web/src/lib/community/message-dispatcher.ts"+ const plan = buildExecutionPlan([+ { status: "A", path: fixture },+ { status: "M", path: product },+ ], { baseSha, headSha })+ const report = { [resolve(product)]: coveredFile(resolve(product)) }+ expect(verifyCoveragePlan(plan, report).required_changed_files).toEqual([product])+ expect(() => verifyCoveragePlan(plan, {+ [resolve("src/web/src/lib/config.ts")]: coveredFile(resolve("src/web/src/lib/config.ts")),+ })).toThrow(`required changed coverage file is missing from merged report: ${product}`)+ const fixtureOnly = buildExecutionPlan([{ status: "A", path: fixture }], { baseSha, headSha })+ expect(() => verifyCoveragePlan(fixtureOnly, {})).toThrow("nonempty denominator")+ })+it("proves required changed files and a nonempty passing Codecov project denominator", () => {const changed = "src/cli/commands/update.ts"const plan = buildExecutionPlan([{ status: "M", path: changed }], { baseSha, headSha })diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex 15b1d57b7..1e897e13f 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -11,6 +11,7 @@ import {import type { Database } from "../../index";import { PARTICIPANT_SOURCE } from "../../../constants/community";import { canSeePrivateChannel, visibilityIsDmParticipant } from "../../../utils/community-roles";+import { user } from "../../schema";import { chunk, D1_MAX_IN_PARAMS, maxInParams } from "../_chunk";// Column selection shared by every read query.@@ -82,6 +83,59 @@ export function channelReadableSql(}+export async function listReadableChannelsForUser(+ db: Database,+ userId: string,+ channelIds: readonly string[],+) {+ const ids = [...new Set(channelIds)];+ const batches = chunk(ids, D1_MAX_IN_PARAMS).map((part) => db+ .select({+ id: communityChannel.id,+ serverId: communityChannel.serverId,+ parentChannelId: communityChannel.parentChannelId,+ })+ .from(communityChannel)+ .where(and(+ inArray(communityChannel.id, part),+ channelReadableSql(userId, CHANNEL_COLUMNS),+ )));+ return (await Promise.all(batches)).flat();+}++export async function getReadableMessageChannelId(+ db: Database,+ userId: string,+ messageId: string,+): Promise<string | null> {+ const rows = await db.select({ channelId: communityChannel.id })+ .from(communityMessage)+ .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))+ .where(and(eq(communityMessage.id, messageId), channelReadableSql(userId, CHANNEL_COLUMNS)))+ .limit(1);+ return rows[0]?.channelId ?? null;+}++export async function filterChannelReadableUserIds(+ db: Database,+ channelId: string,+ userIds: readonly string[],+): Promise<string[]> {+ const ids = [...new Set(userIds)];+ const batches = chunk(ids, D1_MAX_IN_PARAMS).map((part) => db+ .select({ userId: user.id })+ .from(communityChannel)+ .innerJoin(user, inArray(user.id, part))+ .where(and(+ eq(communityChannel.id, channelId),+ channelReadableSql(user.id, CHANNEL_COLUMNS),+ )));+ const rows = (await Promise.all(batches)).flat();+ const readable = new Set(rows.map((row) => row.userId));+ return ids.filter((id) => readable.has(id));+}++export async function createChannel(db: Database,data: {diff --git a/src/shared/src/db/queries/community/members-resolver.ts b/src/shared/src/db/queries/community/members-resolver.tsindex 3c025e81a..d0d5e4213 100644--- a/src/shared/src/db/queries/community/members-resolver.ts+++ b/src/shared/src/db/queries/community/members-resolver.ts@@ -12,6 +12,7 @@ import {} from "../../../utils/community-roles";import {getChannelType,+ filterChannelReadableUserIds,getPrivateChannelAudienceUserIds,isChannelPrivate,listChannelMemberUserIds,@@ -19,11 +20,6 @@ import {import { listMemberUserIds } from "./member";import { listThreadParticipantUserIds } from "./thread";-// The ACCESS scopes — units that own (or inherit) a stored/derived access-// roster. `forum` resolves like a top-level text channel (its own roster);-// `channel` is a top-level text channel. Child threads are NOT here: they-// are the NOTIFICATION dimension (participant set), resolved at the call site-// via `listThreadParticipantUserIds` — never through this resolver.export type ScopeKind = "channel" | "forum";// Why a user is in the resolved set. Lets callers distinguish an explicitly@@ -41,7 +37,8 @@ export type ChannelRecipientQueryPhase =| "channel-type"| "thread-participants"| "dm-members"- | "scope-members";+ | "scope-members"+ | "readable-members";export type ChannelRecipientQueryRunner = <T>(phase: ChannelRecipientQueryPhase,@@ -50,7 +47,7 @@ export type ChannelRecipientQueryRunner = <T>(const runChannelRecipientQuery: ChannelRecipientQueryRunner = (_phase, query) => query();-export async function resolveChannelRecipientUserIds(+export async function resolveChannelNotificationRecipientUserIds(db: Database,channelId: string,runQuery: ChannelRecipientQueryRunner = runChannelRecipientQuery,@@ -74,6 +71,21 @@ export async function resolveChannelRecipientUserIds(}}+export async function resolveChannelContentRecipientUserIds(+ db: Database,+ channelId: string,+ runQuery: ChannelRecipientQueryRunner = runChannelRecipientQuery,+): Promise<string[]> {+ const type = await runQuery("channel-type", () => getChannelType(db, channelId));+ if (!isStoredChannelType(type)) return [];+ const candidates = type === "dm"+ ? await runQuery("dm-members", () => listChannelMemberUserIds(db, channelId))+ : await runQuery("scope-members", () => resolveScopeMemberUserIds(db, {+ scope: "channel", scopeId: channelId,+ }));+ return runQuery("readable-members", () => filterChannelReadableUserIds(db, channelId, candidates));+}+/*** The single source of truth for "who can access this scope." Consolidates the* public/private split for the ACCESS dimension:@@ -85,9 +97,6 @@ export async function resolveChannelRecipientUserIds(* creator (delegates to `getPrivateChannelAudienceUserIds`, which climbs* `parentChannelId` so a forum resolves its own roster like a text channel).*- * Only ACCESS units (`channel`/`forum`) reach here. Child threads resolve their- * recipient set from the participant table at the- * call site.*/export async function resolveScopeMemberUserIds(db: Database,diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex e44f90b4c..495b750b2 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -80,8 +80,6 @@ export async function addThreadParticipants(return insertedUserIds;}-// The NOTIFY set: every participant userId. This is what thread fan-out /-// mention rows / inbox unread scope to.export async function listThreadParticipantUserIds(db: Database,threadChannelId: stringdiff --git a/src/shared/test/queries/community-members-resolver.test.ts b/src/shared/test/queries/community-members-resolver.test.tsindex 6bd9dbaf7..007a7d48d 100644--- a/src/shared/test/queries/community-members-resolver.test.ts+++ b/src/shared/test/queries/community-members-resolver.test.ts@@ -27,7 +27,7 @@ vi.mock("../../src/db/queries/community/thread", () => ({}));import {- resolveChannelRecipientUserIds,+ resolveChannelNotificationRecipientUserIds,resolveScopeMemberUserIds,resolveScopeMembers,} from "../../src/db/queries/community/members-resolver";@@ -76,7 +76,7 @@ beforeEach(() => {mockListMemberUserIds.mockResolvedValue([]);});-describe("resolveChannelRecipientUserIds", () => {+describe("resolveChannelNotificationRecipientUserIds", () => {const runWithPhaseLog = (phases: string[]) =>async <T>(phase: string, query: () => Promise<T>): Promise<T> => {phases.push(phase);@@ -89,7 +89,7 @@ describe("resolveChannelRecipientUserIds", () => {const phases: string[] = [];await expect(- resolveChannelRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),+ resolveChannelNotificationRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),).resolves.toEqual(["p1", "p2"]);expect(phases).toEqual(["channel-type", "thread-participants"]);@@ -103,7 +103,7 @@ describe("resolveChannelRecipientUserIds", () => {const phases: string[] = [];await expect(- resolveChannelRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),+ resolveChannelNotificationRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),).resolves.toEqual(["u1", "u2"]);expect(phases).toEqual(["channel-type", "dm-members"]);@@ -117,7 +117,7 @@ describe("resolveChannelRecipientUserIds", () => {const phases: string[] = [];const db = makeDb({ select: [[{ serverId: "srv-1" }]] });- await expect(resolveChannelRecipientUserIds(db, CHANNEL, runWithPhaseLog(phases)))+ await expect(resolveChannelNotificationRecipientUserIds(db, CHANNEL, runWithPhaseLog(phases))).resolves.toEqual(["u1", "u2"]);expect(phases).toEqual(["channel-type", "scope-members"]);@@ -131,7 +131,7 @@ describe("resolveChannelRecipientUserIds", () => {const phases: string[] = [];const db = makeDb({ select: [[{ serverId: "srv-1" }]] });- await expect(resolveChannelRecipientUserIds(db, CHANNEL, runWithPhaseLog(phases)))+ await expect(resolveChannelNotificationRecipientUserIds(db, CHANNEL, runWithPhaseLog(phases))).resolves.toEqual(["fallback"]);expect(phases).toEqual(["channel-type", "scope-members"]);});@@ -143,7 +143,7 @@ describe("resolveChannelRecipientUserIds", () => {const phases: string[] = [];await expect(- resolveChannelRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),+ resolveChannelNotificationRecipientUserIds({} as Database, CHANNEL, runWithPhaseLog(phases)),).rejects.toBe(failure);expect(phases).toEqual(["channel-type", "thread-participants"]);});diff --git a/src/shared/test/queries/community-realtime-audiences.test.ts b/src/shared/test/queries/community-realtime-audiences.test.tsnew file mode 100644index 000000000..d2f18f907--- /dev/null+++ b/src/shared/test/queries/community-realtime-audiences.test.ts@@ -0,0 +1,89 @@+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { Database } from "../../src/db";+import { resolveChannelContentRecipientUserIds, resolveChannelNotificationRecipientUserIds } from "../../src/db/queries/community/members-resolver";+import { filterChannelReadableUserIds, listReadableChannelsForUser, getReadableMessageChannelId } from "../../src/db/queries/community/channel";++describe("realtime channel audiences with canonical SQLite permissions", () => {+ let sqlite: Sqlite.Database;+ let db: Database;+ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE user (id TEXT PRIMARY KEY);+ CREATE TABLE community_server_member (id TEXT PRIMARY KEY, server_id TEXT, user_id TEXT, role TEXT);+ CREATE TABLE community_category (id TEXT PRIMARY KEY, private INTEGER);+ CREATE TABLE community_channel (id TEXT PRIMARY KEY, server_id TEXT, category_id TEXT, type TEXT, parent_channel_id TEXT, creator_id TEXT);+ CREATE TABLE community_channel_member (id TEXT PRIMARY KEY, channel_id TEXT, user_id TEXT, relation TEXT);+ CREATE TABLE community_message (id TEXT PRIMARY KEY, channel_id TEXT);+ INSERT INTO user VALUES ('author'),('participant'),('reader'),('admin'),('outsider'),('departed');+ INSERT INTO community_server_member VALUES ('a','server','author','owner'),('p','server','participant','member'),('r','server','reader','member'),('x','server','admin','admin');+ INSERT INTO community_category VALUES ('private',1),('public',0);+ INSERT INTO community_channel VALUES+ ('text','server','public','text',NULL,'author'),+ ('forum','server','public','forum',NULL,'author'),+ ('private-text','server','private','text',NULL,'author'),+ ('private-forum','server','private','forum',NULL,'author'),+ ('thread','server',NULL,'thread','text','author'),+ ('post','server',NULL,'thread','forum','author'),+ ('private-thread','server',NULL,'thread','private-text','author'),+ ('private-post','server',NULL,'thread','private-forum','author'),+ ('dm',NULL,NULL,'dm',NULL,'author');+ INSERT INTO community_channel_member VALUES+ ('ptp','private-text','participant','access'),('ptr','private-text','reader','access'),('ptd','private-text','departed','access'),+ ('pfp','private-forum','participant','access'),('pfr','private-forum','reader','access'),+ ('t','thread','participant','notify'),('p','post','participant','notify'),+ ('pt','private-thread','participant','notify'),('pp','private-post','participant','notify'),+ ('stale','private-thread','outsider','notify'),+ ('da','dm','author','access'),('dr','dm','reader','access');+ INSERT INTO community_message VALUES ('message','private-thread');+ `);+ db = drizzle(sqlite) as unknown as Database;+ });+ afterEach(() => sqlite.close());++ it.each(["thread", "post", "private-thread", "private-post"])("%s delivers content to readable nonparticipants", async (id) => {+ const content = await resolveChannelContentRecipientUserIds(db, id);+ expect(content).toContain("reader");+ expect(content).toContain("author");+ expect(content).not.toContain("outsider");+ expect(content).not.toContain("departed");+ expect(content.includes("admin")).toBe(!id.startsWith("private"));+ expect(await resolveChannelNotificationRecipientUserIds(db, id)).not.toContain("reader");+ expect(sqlite.prepare("SELECT count(*) AS n FROM community_channel_member WHERE channel_id=? AND user_id='reader'").get(id)).toEqual({ n: 0 });+ });++ it("keeps DM pair and missing/unknown scopes closed", async () => {+ expect(await resolveChannelContentRecipientUserIds(db, "dm")).toEqual(["author", "reader"]);+ expect(await resolveChannelContentRecipientUserIds(db, "missing")).toEqual([]);+ sqlite.prepare("UPDATE community_channel SET type='future' WHERE id='text'").run();+ expect(await resolveChannelContentRecipientUserIds(db, "text")).toEqual([]);+ });++ it("rechecks parent access and server membership for delayed target checks", async () => {+ expect(await getReadableMessageChannelId(db, "reader", "message")).toBe("private-thread");+ sqlite.prepare("DELETE FROM community_channel_member WHERE channel_id='private-text' AND user_id='reader'").run();+ expect(await listReadableChannelsForUser(db, "reader", ["private-thread", "private-text"])).toEqual([]);+ expect(await getReadableMessageChannelId(db, "reader", "message")).toBeNull();+ sqlite.prepare("DELETE FROM community_server_member WHERE user_id='author'").run();+ expect(await filterChannelReadableUserIds(db, "private-thread", ["author", "reader", "participant", "participant"])).toEqual(["participant"]);+ });++ it("leaving participation preserves content and batched visibility matches membership", async () => {+ sqlite.prepare("DELETE FROM community_channel_member WHERE channel_id='private-post' AND relation='notify'").run();+ expect(await resolveChannelNotificationRecipientUserIds(db, "private-post")).toEqual([]);+ expect(await resolveChannelContentRecipientUserIds(db, "private-post")).toContain("participant");+ expect(await listReadableChannelsForUser(db, "reader", ["private-thread", "post", "missing", "post"])).toHaveLength(2);+ expect(await filterChannelReadableUserIds(db, "thread", [])).toEqual([]);+ });++ it("chunks a large readable audience without dropping or duplicating users", async () => {+ const ids = Array.from({ length: 200 }, (_, i) => `reader-${i}`);+ for (const id of ids) {+ sqlite.prepare("INSERT INTO user VALUES (?)").run(id);+ sqlite.prepare("INSERT INTO community_server_member VALUES (?, 'server', ?, 'member')").run(id, id);+ }+ expect(await filterChannelReadableUserIds(db, "thread", [...ids, ...ids])).toEqual(ids);+ });+});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 4e69f1d44..690a419bc 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@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+import { decodeCommunityBrowserEvent } from "@alook/shared"vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -9,7 +10,7 @@ const mockResolveChannelAccessContext = vi.fn()const mockResolveTargetForMember = vi.fn()const mockParseRef = vi.hoisted(() => vi.fn())const mockDeleteThreadParticipantWithCreatorHandoff = vi.fn()-const mockListThreadParticipantUserIds = vi.fn()+const mockResolveChannelContentRecipientUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -33,8 +34,8 @@ vi.mock("@alook/shared", async () => {deleteThreadParticipantWithCreatorHandoff: (...a: unknown[]) =>mockDeleteThreadParticipantWithCreatorHandoff(...a),},- communityThread: {- listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),+ communityMembersResolver: {+ resolveChannelContentRecipientUserIds: (...a: unknown[]) => mockResolveChannelContentRecipientUserIds(...a),},},}@@ -86,12 +87,16 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {mockResolveChannelAccessContext.mockResolvedValue(threadCtx())mockResolveTargetForMember.mockResolvedValue({ kind: "channel", channelId: "t1" })mockDeleteThreadParticipantWithCreatorHandoff.mockResolvedValue({ id: "tp1" })- mockListThreadParticipantUserIds.mockResolvedValue(["u2", "u3"])+ mockResolveChannelContentRecipientUserIds.mockResolvedValue(["u2", "u3"])})it("thread creator leaves after creator handoff and removes their own row", async () => {const res = await DELETE(delReq(), { params: { id: "t1", userId: "u1" } } as any)expect(res.status).toBe(204)+ for (const [, event] of mockBroadcastToUserSafe.mock.calls) {+ expect(Object.keys(event).sort()).toEqual(["channelId", "serverId", "type", "userId"])+ expect(decodeCommunityBrowserEvent(event).ok).toBe(true)+ }expect(mockDeleteThreadParticipantWithCreatorHandoff).toHaveBeenCalledWith(expect.anything(),"t1",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 5761dcf2b..48f9fba0a 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@@ -77,7 +77,7 @@ export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {channelId,userId: targetUserId,} as const- const remaining = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ const remaining = await queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db, channelId)await Promise.all([...new Set([...remaining, targetUserId])].map((userId) =>broadcastToUserSafe(userId, event),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 380757aa9..ca7a32455 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@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"+import { decodeCommunityBrowserEvent } from "@alook/shared"vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -8,7 +9,7 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockResolveChannelAccessContext = vi.fn()const mockListThreadParticipants = vi.fn()const mockAddThreadParticipant = vi.fn()-const mockListThreadParticipantUserIds = vi.fn()+const mockResolveChannelContentRecipientUserIds = vi.fn()const mockResolveScopeMemberUserIds = vi.fn()const mockBroadcastToUserSafe = vi.fn()@@ -23,11 +24,11 @@ vi.mock("@alook/shared", async () => {resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),},communityMembersResolver: {+ resolveChannelContentRecipientUserIds: (...a: unknown[]) => mockResolveChannelContentRecipientUserIds(...a),resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),},communityThread: {listThreadParticipants: (...a: unknown[]) => mockListThreadParticipants(...a),- listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),addThreadParticipant: (...a: unknown[]) => mockAddThreadParticipant(...a),},},@@ -83,12 +84,16 @@ 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"])+ mockResolveChannelContentRecipientUserIds.mockResolvedValue(["u1", "u2", "u3"])})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)+ for (const [, event] of mockBroadcastToUserSafe.mock.calls) {+ expect(Object.keys(event).sort()).toEqual(["channelId", "serverId", "type", "userId"])+ expect(decodeCommunityBrowserEvent(event).ok).toBe(true)+ }expect(mockAddThreadParticipant).toHaveBeenCalledWith(expect.anything(), {threadChannelId: "t1", userId: "u2", source: "added",})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 95bdecd01..36e4b8c6c 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,9 +65,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {source: PARTICIPANT_SOURCE.ADDED,})- // 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) {const event = {type: WS_EVENTS.CHANNEL_MEMBER_ADD,@@ -75,7 +72,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {channelId,userId: targetUserId,} as const- const recipients = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ const recipients = await queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db, channelId)await Promise.all([...new Set(recipients)].map((userId) => broadcastToUserSafe(userId, event)),)diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.tsindex cc5e7c439..83101222a 100644--- a/src/web/src/hooks/community/account-unread-projection.ts+++ b/src/web/src/hooks/community/account-unread-projection.ts@@ -1180,6 +1180,15 @@ export class AccountUnreadProjection {this.publish()}+ retireNotificationScope(scope: AccountUnreadScope) {+ if (this.disposed) return+ const ordinal = ++this.ordinal+ this.recordRawRetirementFloor(scope, ordinal)+ this.pruneScope(scope, ordinal)+ this.publish()+ this.requestReconcile()+ }+retireAccessScope(scope: AccountUnreadScope) {if (this.disposed) returnconst token = this.beginScopeRetirement(scope)diff --git a/src/web/src/hooks/community/channel-metadata.test.ts b/src/web/src/hooks/community/channel-metadata.test.tsnew file mode 100644index 000000000..a7f282d81--- /dev/null+++ b/src/web/src/hooks/community/channel-metadata.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { useCommunityWsStore } from "@/stores/community/ws"+import { communityKeys } from "@/lib/query-keys"+import { fetchChannelMetadata } from "./channel-metadata"++const fetchMock = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => fetchMock(...args) }))++const metadata = {+ id: "child", serverId: "server", type: "thread", name: "Child",+ parentChannelId: "parent", parentMessageId: "opener", creatorId: "owner",+ archived: 0, lastMessageAt: null, createdAt: "2026-09-05T00:00:00Z",+}++beforeEach(() => {+ fetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("alice")+})++describe("canonical channel metadata lifecycle", () => {+ it.each(["account", "parent", "server", "reconnect", "membership"] as const)(+ "rejects an old successful HTTP response after %s changes",+ async (change) => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let release!: (value: unknown) => void+ fetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))+ const key = communityKeys.channelMeta("server", "child")+ const result = client.fetchQuery({+ queryKey: key,+ queryFn: ({ signal }) => fetchChannelMetadata("server", "child", signal),+ })+ const rejection = expect(result).rejects.toMatchObject({ name: "AbortError" })+ const state = useCommunityWsStore.getState()+ if (change === "account") {+ state.activateProfileAccount("bob")+ useCommunityWsStore.getState().activateProfileAccount("alice")+ } else if (change === "parent") state.revokeChannelAccess("server", "parent")+ else if (change === "server") state.revokeServerAccess("server")+ else if (change === "membership") state.beginChannelMembershipChange("server", "child")+ else { state.markAccessDisconnected(); state.markAccessConnected() }+ release(metadata)+ await rejection+ expect(client.getQueryData(key)).toBeUndefined()+ expect(useCommunityWsStore.getState().channelAccessScopes.get("child")?.parentChannelId).toBeUndefined()+ client.clear()+ },+ )++ it("restores readable child and parent only from a current authoritative response", async () => {+ const state = useCommunityWsStore.getState()+ state.revokeChannelAccess("server", "parent")+ state.revokeChannelAccess("server", "child")+ state.revokeServerAccess("server")+ fetchMock.mockResolvedValue(metadata)+ await expect(fetchChannelMetadata("server", "child")).resolves.toMatchObject({+ archived: false, activityAt: metadata.createdAt,+ })+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("child")).toBe(false)+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("parent")).toBe(false)+ })++ it.each([{ id: "other" }, { serverId: "other" }, { type: "unknown" }])(+ "does not grant access from mismatched metadata %j",+ async (overrides) => {+ useCommunityWsStore.getState().revokeChannelAccess("server", "child")+ fetchMock.mockResolvedValue({ ...metadata, ...overrides })+ await expect(fetchChannelMetadata("server", "child")).rejects.toThrow("scope mismatch")+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("child")).toBe(true)+ },+ )+})diff --git a/src/web/src/hooks/community/channel-metadata.ts b/src/web/src/hooks/community/channel-metadata.tsnew file mode 100644index 000000000..8ac7f11b1--- /dev/null+++ b/src/web/src/hooks/community/channel-metadata.ts@@ -0,0 +1,49 @@+import { apiFetch } from "@/lib/api/client"+import { useCommunityWsStore } from "@/stores/community/ws"++export type ChannelMetadata = {+ id: string+ serverId: string+ name: string+ type: string+ parentChannelId: string | null+ parentMessageId: string | null+ creatorId: string | null+ archived: boolean | number+ lastMessageAt: string | null+ createdAt: string+}++export function captureChannelMetadataToken(channelId: string) {+ const state = useCommunityWsStore.getState()+ return {+ viewerId: state.profileViewerId,+ accountEpoch: state.profileAccountEpoch,+ accessEpoch: state.accessEpoch,+ channelId,+ generation: state.channelAccessScopes.get(channelId)?.generation ?? 0,+ }+}++export function isChannelMetadataTokenCurrent(token: ReturnType<typeof captureChannelMetadataToken>) {+ const state = useCommunityWsStore.getState()+ return state.profileViewerId === token.viewerId+ && state.profileAccountEpoch === token.accountEpoch+ && state.accessEpoch === token.accessEpoch+ && (state.channelAccessScopes.get(token.channelId)?.generation ?? 0) === token.generation+}++export async function fetchChannelMetadata(+ serverId: string,+ channelId: string,+ signal?: AbortSignal,+) {+ const token = captureChannelMetadataToken(channelId)+ const meta = await apiFetch<ChannelMetadata>(`/api/community/channels/${channelId}`, { signal })+ if (!isChannelMetadataTokenCurrent(token) || signal?.aborted) throw new DOMException("Stale channel metadata", "AbortError")+ if (meta.id !== channelId || meta.serverId !== serverId || !["text", "forum", "thread"].includes(meta.type)) throw new Error("Channel metadata scope mismatch")+ useCommunityWsStore.getState().grantServerAccess(serverId)+ useCommunityWsStore.getState().rememberChannelAccess(serverId, channelId, meta.parentChannelId)+ return { ...meta, archived: meta.archived === true || meta.archived === 1,+ activityAt: meta.lastMessageAt ?? meta.createdAt, verifiedEpoch: token.accessEpoch }+}diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.tsindex b04f42eee..fb9932dc5 100644--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts@@ -217,6 +217,7 @@ describe("useCommunityWs — operation bundles", () => {...message,message: { ...message.message, id: "message-next", seq: 2 },})+ capturedOnMessage!({ type: "community:unread.bump", userId: "viewer-1", channelId: "dm-1" })releaseRead()await vi.advanceTimersByTimeAsync(500)@@ -263,6 +264,7 @@ describe("useCommunityWs — operation bundles", () => {)capturedOnMessage!(message)+ capturedOnMessage!({ type: "community:unread.bump", userId: "viewer-1", channelId: "dm-1" })expect(submitReadIntent(lease, {kind: "timeline",channelId: "ch-1",@@ -330,6 +332,7 @@ describe("useCommunityWs — operation bundles", () => {)capturedOnMessage!(message)+ capturedOnMessage!({ type: "community:unread.bump", userId: "viewer-1", channelId: "dm-1" })expect(submitReadIntent(lease, {kind: "timeline",channelId: "ch-1",@@ -388,7 +391,7 @@ describe("useCommunityWs — operation bundles", () => {expect(invalidationCount(communityKeys.servers())).toBe(1)await vi.advanceTimersByTimeAsync(500)expect(invalidationCount(communityKeys.inbox())).toBe(1)- expect(invalidationCount(communityKeys.dms())).toBe(1)+ expect(invalidationCount(communityKeys.dms())).toBe(0)const callsAfterFirst = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.lengthcapturedOnMessage!(frame)@@ -497,7 +500,7 @@ describe("useCommunityWs — operation bundles", () => {expect(invalidationCount(communityKeys.servers())).toBe(1)await vi.advanceTimersByTimeAsync(500)expect(invalidationCount(communityKeys.inbox())).toBe(1)- expect(invalidationCount(communityKeys.dms())).toBe(1)+ expect(invalidationCount(communityKeys.dms())).toBe(0)} finally {vi.useRealTimers()}@@ -891,7 +894,7 @@ describe("useCommunityWs — operation bundles", () => {const original = await batchFor("bounded-operation", [{...message,message: { ...message.message, id: "bounded-operation" },- }])+ }, mentionEvents[1]!])capturedOnMessage!(original)const conflicts: Awaited<ReturnType<typeof batchFor>>[] = []for (let index = 0; index < SEEN_DELIVERY_OPERATION_MAX; index += 1) {@@ -902,7 +905,7 @@ describe("useCommunityWs — operation bundles", () => {id: "bounded-operation",content: `conflict-${index}`,},- }])+ }, mentionEvents[1]!])conflicts.push(conflict)capturedOnMessage!(conflict)}diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.test.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.test.tsnew file mode 100644index 000000000..57c58e7fe--- /dev/null+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.test.ts@@ -0,0 +1,161 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import type { CommunityWsEvent } from "@alook/shared"+import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"+import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"+import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"+import {+ capturedOnMessage,+ capturedQueryClient,+ cleanupCommunityWsHarness,+ getCommunityApiFetchMock,+ mountHook,+ resetCommunityWsHarness,+} from "./test-harness"++beforeEach(resetCommunityWsHarness)+afterEach(cleanupCommunityWsHarness)++function seedThreads(serverId: string, parentId: string, children: string[], shape: "text" | "forum") {+ if (shape === "text") {+ const data: ThreadsResponse = {+ serverId,+ parentChannelId: parentId,+ parentType: "text",+ threads: children.map((id) => ({+ id, name: id, messageCount: 1, lastMessageAt: "2026-09-06T00:00:00Z",+ parent: { authorName: "Author", text: "Opener" },+ parentSeq: 1, openerMessageId: `opener_${id}`,+ })),+ }+ capturedQueryClient.setQueryData(communityKeys.threads(parentId), data)+ } else {+ const pages: ForumFeedPage[] = children.map((id) => ({+ serverId,+ parentType: "forum",+ threads: [{+ id, name: id, creatorId: "author", messageCount: 1,+ parentMessageId: `opener_${id}`, lastMessageAt: "2026-09-06T00:00:00Z",+ createdAt: "2026-09-06T00:00:00Z", activityAt: "2026-09-06T00:00:00Z",+ }],+ included: { parentMessages: [], firstMessages: [], tags: [], participants: [] },+ hasMore: true,+ nextCursor: id,+ }))+ capturedQueryClient.setQueryData(communityKeys.forumFeed(parentId, null), {+ pages, pageParams: children.map((_, index) => index === 0 ? null : children[index - 1]),+ })+ }+}++const preview = {+ notFound: false,+ anchorId: "sensitive_message",+ messages: [{ id: "sensitive_message", content: "Private preview", reactions: [{ emoji: "👍", count: 1 }] }],+}++const controls: CommunityWsEvent[] = [+ { type: "community:channel.member_remove", serverId: "server", channelId: "parent", userId: "u_me" },+ { type: "community:channel.delete", serverId: "server", channelId: "parent" },+ { type: "community:member.leave", serverId: "server", userId: "u_me" },+ { type: "community:server.delete", serverId: "server" },+]++describe.each(["text", "forum"] as const)("%s canonical thread scope eviction", (shape) => {+ it.each(controls)("evicts preview-only descendants on $type and rejects a late preview response", async (event) => {+ await mountHook({ viewerUserId: "u_me" })+ const parentControl = "channelId" in event+ if (parentControl) {+ capturedQueryClient.setQueryData(communityKeys.channelMeta("server", "parent"), {+ id: "parent", type: shape, verifiedEpoch: useCommunityWsStore.getState().accessEpoch,+ })+ }+ seedThreads("server", "parent", ["active_child", "preview_child"], shape)+ seedThreads("server", "other_parent", ["other_child"], shape)+ seedThreads("other_server", "foreign_parent", ["foreign_child"], shape)+ const contextKey = communityKeys.messageContext("channel", "preview_child", 1)+ const pendingKey = communityKeys.messageContext("channel", "preview_child", 2)+ const otherKey = communityKeys.messageContext("channel", "other_child", 1)+ const foreignKey = communityKeys.messageContext("channel", "foreign_child", 1)+ const dmKey = communityKeys.messageContext("dm", "preview_child", 1)+ for (const key of [contextKey, otherKey, foreignKey, dmKey]) capturedQueryClient.setQueryData(key, preview)+ capturedQueryClient.setQueryData(communityKeys.channelMessages("preview_child"), { pages: [{ messages: preview.messages }] })+ capturedQueryClient.setQueryData(communityKeys.pins("preview_child"), { pins: preview.messages })+ capturedQueryClient.setQueryData(communityKeys.reactionDetails("sensitive_message"), {+ scope: { channelId: "preview_child", serverId: "server" }, actors: [{ id: "author" }],+ })+ let release!: (value: typeof preview) => void+ let requestSignal!: AbortSignal+ const pending = capturedQueryClient.fetchQuery({+ queryKey: pendingKey,+ queryFn: ({ signal }) => {+ requestSignal = signal+ return new Promise<typeof preview>((resolve) => { release = resolve })+ },+ }).catch(() => undefined)+ expect(capturedQueryClient.getQueryState(communityKeys.channelMeta("server", "preview_child"))).toBeUndefined()+ expect(useCommunityWsStore.getState().channelAccessScopes.has("preview_child")).toBe(false)+ const apiCalls = getCommunityApiFetchMock().mock.calls.length++ capturedOnMessage!(event)++ expect(capturedQueryClient.getQueryState(contextKey)).toBeUndefined()+ expect(capturedQueryClient.getQueryState(pendingKey)).toBeUndefined()+ expect(capturedQueryClient.getQueryState(communityKeys.channelMessages("preview_child"))).toBeUndefined()+ expect(capturedQueryClient.getQueryState(communityKeys.pins("preview_child"))).toBeUndefined()+ expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("sensitive_message"))).toBeUndefined()+ expect(capturedQueryClient.getQueriesData({ queryKey: communityKeys.threads("parent") })).toEqual([])+ expect(requestSignal.aborted).toBe(true)+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("preview_child", "server")).toBe(true)+ expect(capturedQueryClient.getQueryData(otherKey)).toEqual(parentControl ? preview : undefined)+ expect(capturedQueryClient.getQueryData(foreignKey)).toEqual(preview)+ expect(capturedQueryClient.getQueryData(dmKey)).toEqual(preview)+ expect(getCommunityApiFetchMock()).toHaveBeenCalledTimes(apiCalls)++ release(preview)+ await pending+ await Promise.resolve()+ expect(capturedQueryClient.getQueryState(contextKey)).toBeUndefined()+ expect(capturedQueryClient.getQueryState(pendingKey)).toBeUndefined()+ })+})++it("cancels an unresolved parent thread list before its child rows can arrive", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const key = communityKeys.threads("parent")+ let release!: (value: ThreadsResponse) => void+ let requestSignal!: AbortSignal+ const pending = capturedQueryClient.fetchQuery({+ queryKey: key,+ queryFn: ({ signal }) => {+ requestSignal = signal+ return new Promise<ThreadsResponse>((resolve) => { release = resolve })+ },+ }).catch(() => undefined)++ capturedOnMessage!({ type: "community:channel.delete", serverId: "server", channelId: "parent" })++ expect(requestSignal.aborted).toBe(true)+ expect(capturedQueryClient.getQueryState(key)).toBeUndefined()+ release({ serverId: "server", parentChannelId: "parent", parentType: "text", threads: [] })+ await pending+ expect(capturedQueryClient.getQueryState(key)).toBeUndefined()+})++it("preserves readable previews when leaving only a thread's notify membership", async () => {+ await mountHook({ viewerUserId: "u_me" })+ seedThreads("server", "parent", ["preview_child"], "text")+ capturedQueryClient.setQueryData(communityKeys.channelMeta("server", "preview_child"), {+ id: "preview_child", type: "thread", parentChannelId: "parent",+ verifiedEpoch: useCommunityWsStore.getState().accessEpoch,+ })+ const key = communityKeys.messageContext("channel", "preview_child", 1)+ capturedQueryClient.setQueryData(key, preview)++ capturedOnMessage!({+ type: "community:channel.member_remove", serverId: "server", channelId: "preview_child", userId: "u_me",+ })++ expect(capturedQueryClient.getQueryData(key)).toEqual(preview)+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("preview_child", "server")).toBe(false)+})diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.tsindex 9b42ef6bf..1a6956c9d 100644--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts@@ -1,6 +1,8 @@-import type { QueryClient } from "@tanstack/react-query"+import type { QueryClient, Query } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import type { ServerDetail } from "@/hooks/community/use-servers"+import { useCommunityWsStore } from "@/stores/community/ws"+import { clearTypingIndicator } from "./typing"import { useCommunityStore } from "@/stores/community"import { useMessageStreamStore } from "@/stores/community/message-stream"import { clearLastChannel } from "@/lib/community/last-channel"@@ -8,6 +10,7 @@ import { channelHref } from "@/lib/community/community-route"import type { PageCache } from "./cache"import { removeThreadFromCache } from "./cache"import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"+import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"import { removeForumPostFromFeed } from "@/hooks/community/forum-feed-tag-transition"import type { InfiniteData } from "@tanstack/react-query"import {@@ -25,27 +28,106 @@ export function projectChannelScopeEviction(serverId: string,channelId: string,) {+ const ids = collectChannelScopeIds(queryClient, serverId, channelId)+ const store = useCommunityWsStore.getState()+ for (const id of store.revokeChannelAccess(serverId, channelId)) ids.add(id)projection.project(() => {- evictChannelScopeQueryCaches(queryClient, serverId, channelId)- if (useCommunityStore.getState().currentChannelId === channelId) {- useCommunityStore.getState().setCurrentChannelMeta(null)+ for (const id of ids) {+ store.revokeChannelAccess(serverId, id)+ getActiveAccountUnreadProjection(queryClient).retireAccessScope({ kind: "channel", channelId: id })+ evictChannelScopeQueryCaches(queryClient, serverId, id)+ evictScopeContent(queryClient, serverId, id)}- useMessageStreamStore.getState().removeScope({- kind: "channel",- id: channelId,- serverId,- })- queryClient.removeQueries({ queryKey: communityKeys.channelMessages(channelId) })- queryClient.removeQueries({ queryKey: communityKeys.pins(channelId) })- queryClient.removeQueries({ queryKey: communityKeys.threads(channelId) })})}+function collectChannelScopeIds(queryClient: QueryClient, serverId: string, channelId?: string) {+ const ids = new Set<string>(channelId ? [channelId] : [])+ const store = useCommunityStore.getState()+ const current = store.currentChannelMeta+ if (store.currentServerId === serverId && store.currentChannelId+ && (!channelId || current?.parentChannelId === channelId)) ids.add(store.currentChannelId)+ for (const [id, scope] of useCommunityWsStore.getState().channelAccessScopes) {+ if (scope.serverId === serverId && (!channelId || scope.parentChannelId === channelId)) ids.add(id)+ }+ for (const [, meta] of queryClient.getQueriesData<{ id: string; parentChannelId?: string }>(+ { queryKey: communityKeys.channelMetaRoot(serverId) },+ )) {+ if (meta && (!channelId || meta.parentChannelId === channelId)) ids.add(meta.id)+ }+ for (const { scope } of useMessageStreamStore.getState().entries.values()) {+ if (!channelId && scope.kind === "channel" && scope.serverId === serverId) ids.add(scope.id)+ }+ const visit = (value: unknown) => {+ if (Array.isArray(value)) { value.forEach(visit); return }+ if (!value || typeof value !== "object") return+ const row = value as Record<string, unknown>+ if (!channelId || row.parentChannelId === channelId) {+ if (typeof row.childChannelId === "string") ids.add(row.childChannelId)+ if (typeof row.id === "string" && (row.type === "thread" || row.type === "text" || row.type === "forum")) ids.add(row.id)+ }+ for (const child of Object.values(row)) if (child && typeof child === "object") visit(child)+ }+ for (const [, data] of queryClient.getQueriesData({ queryKey: communityKeys.server(serverId) })) visit(data)+ for (const [key, data] of queryClient.getQueriesData<ThreadsResponse | InfiniteData<ForumFeedPage>>({+ queryKey: ["community", "channel"],+ predicate: (query) => query.queryKey[3] === "threads" && (!channelId || query.queryKey[2] === channelId),+ })) {+ if (!data) continue+ const pages = "pages" in data ? data.pages : [data]+ for (const page of pages) {+ if (page.serverId !== serverId) continue+ ids.add(key[2] as string)+ for (const thread of page.threads) ids.add(thread.id)+ }+ }+ return ids+}++function scopeQuery(query: Query, serverId: string, channelId: string) {+ const key = query.queryKey+ if (key[0] !== "community") return false+ if (key[1] === "channel" && key[2] === channelId) return true+ if (key[1] === "message-context" && key[2] === "channel" && key[3] === channelId) return true+ if (key[1] === "servers" && key[2] === serverId+ && (key[3] === "channel-meta" || key[3] === "forum-sidebar-retained") && key[4] === channelId) return true+ if (key[1] !== "message" && key[1] !== "reaction-details") return false+ const data = query.state.data as { channelId?: string; scope?: { channelId?: string } } | undefined+ const ownerChannelId = data?.channelId ?? data?.scope?.channelId+ return !ownerChannelId || ownerChannelId === channelId+}++function evictScopeContent(queryClient: QueryClient, serverId: string, channelId: string) {+ const predicate = (query: Query) => scopeQuery(query, serverId, channelId)+ void queryClient.cancelQueries({ predicate })+ queryClient.removeQueries({ predicate })+ useMessageStreamStore.getState().removeScope({ kind: "channel", id: channelId, serverId })+ const store = useCommunityStore.getState()+ for (const userId of store.typingByScope.get(`ch:${channelId}`)?.keys() ?? []) clearTypingIndicator(`ch:${channelId}`, userId)+ if (store.currentChannelId === channelId) {+ store.setCurrentChannelMeta(null)+ store.setCurrentChannelId(null)+ }+ if (store.subscription.channelId === channelId || store.subscription.secondaryChannelId === channelId) {+ const subscription = { ...store.subscription }+ if (subscription.channelId === channelId) delete subscription.channelId+ if (subscription.secondaryChannelId === channelId) delete subscription.secondaryChannelId+ useCommunityStore.setState({ subscription, ...(store.subscription.secondaryChannelId === channelId ? { secondaryChannelOwner: null } : {}) })+ }+}++export function evictServerChannelScopes(queryClient: QueryClient, serverId: string) {+ useCommunityWsStore.getState().revokeServerAccess(serverId)+ for (const id of collectChannelScopeIds(queryClient, serverId)) evictScopeContent(queryClient, serverId, id)+ void queryClient.cancelQueries({ queryKey: communityKeys.server(serverId) })+}+function evictChannelScopeQueryCaches(queryClient: QueryClient,serverId: string,channelId: string,) {+ void queryClient.cancelQueries({ queryKey: ["community", "channel", channelId] })const nonForum = isKnownNonForumSidebarChannel(queryClient, serverId, channelId)if (!nonForum) {removeForumSidebarUnreadChild(queryClient, serverId, channelId)@@ -131,11 +213,14 @@ export function applyForumPostUnitClientEffects(queryClient: QueryClient,unit: ForumPostUnitIdentity,) {+ const wasCurrent = useCommunityStore.getState().currentChannelId === unit.childChannelId+ useCommunityWsStore.getState().revokeChannelAccess(unit.serverId, unit.childChannelId)getActiveAccountUnreadProjection(queryClient).retireAccessScope({kind: "channel",channelId: unit.childChannelId,})evictForumPostUnitQueryCaches(queryClient, unit)+ evictScopeContent(queryClient, unit.serverId, unit.childChannelId)useMessageStreamStore.getState().removeScope({kind: "channel",id: unit.childChannelId,@@ -150,7 +235,7 @@ export function applyForumPostUnitClientEffects(messageId: unit.openerMessageId,})const store = useCommunityStore.getState()- if (store.currentChannelId === unit.childChannelId) {+ if (wasCurrent) {store.setCurrentChannelMeta(null)store.setCurrentChannelId(unit.forumChannelId)clearLastChannel(unit.serverId)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 7b4a9e090..d87067a03 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@@ -49,6 +49,15 @@ describe("useCommunityWs — member events", () => {actors: [],})+ useMessageStreamStore.getState().dispatch(+ { kind: "channel", id: "stream-only-child", serverId: "srv_1" },+ { type: "wsMessage", message: {+ id: "stream-only-message", seq: 1, authorId: "author", authorName: "Author",+ authorAvatar: "", authorAvatarVersion: 0, content: "private", type: "chat",+ createdAt: "2026-09-05T00:00:00.000Z",+ } },+ )+capturedOnMessage!({type: "community:member.leave",serverId: "srv_1",@@ -396,65 +405,21 @@ describe("useCommunityWs — member events", () => {})})describe("useCommunityWs — channel.member_add/remove → invalidate rosters", () => {- it("keeps a viewer's cached raw row fenced across remove then add until fresh access confirms", async () => {+ it("retires notification arrivals on participant removal without retiring access", async () => {await mountHook({ viewerUserId: "u_me" })- const sidebarKey = communityKeys.forumSidebarThreads("srv_1")- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["private"]))- const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")- unreadProjection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 1 })-- capturedOnMessage!({- type: "community:channel.member_remove",- serverId: "srv_1",- channelId: "private",- userId: "u_me",- })- expect(unreadProjection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)-- const apiFetch = getCommunityApiFetchMock()- apiFetch.mockImplementation(async (url: string) => {- if (url === "/api/community/users/me/read-state") {- return { revision: 0, readStates: [] }- }- if (url.startsWith("/api/community/servers/srv_1/channels?")) {- return {- channels: [],- canonicalChannels: [],- retainedChannel: {- id: "private",- name: "Private",- parentChannelId: "forum_1",- parentMessageId: "opener-private",- activityAt: "2026-08-01T00:00:00.000Z",- expiresAt: "2099-08-04T00:00:00.000Z",- unread: false,- serverId: "srv_1",- type: "thread",- },- retainedDisposition: "eligible",- included: {- parentMessages: [{ id: "opener-private", content: "Private" }],- },- serverNow: "2026-08-01T00:00:00.000Z",- }- }- throw new Error(`unexpected API fetch: ${url}`)- })- capturedOnMessage!({- type: "community:channel.member_add",- serverId: "srv_1",- channelId: "private",- userId: "u_me",- })- await vi.waitFor(() => expect(- capturedQueryClient.getQueryData(communityKeys.forumSidebarRetained("srv_1", "private")),- ).toMatchObject({ id: "private" }))- expect(unreadProjection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)-- unreadProjection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 2 })- expect(unreadProjection.projectUnread("inbox-unreads", "private", true, 2)).toBe(true)+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ const epoch = useCommunityWsStore.getState().accessEpoch+ capturedQueryClient.setQueryData(communityKeys.channelMeta("srv_1", "private"), { type: "thread", verifiedEpoch: epoch })+ const projection = getAccountUnreadProjection(capturedQueryClient, "u_me")+ projection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 1 })+ capturedOnMessage!({ type: "community:channel.member_remove", serverId: "srv_1", channelId: "private", userId: "u_me" })+ expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("private")).toBe(false)+ projection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 2 })+ expect(projection.projectUnread("inbox-unreads", "private", false)).toBe(true)})+it("member_add invalidates channelMembers AND threadParticipants for a child thread", async () => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")@@ -547,6 +512,10 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",parentMessageId: "opener-post_1",})+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ for (const id of ["post_1", "post_2"]) capturedQueryClient.setQueryData(+ communityKeys.channelMeta("srv_1", id), { type: "thread", verifiedEpoch: useCommunityWsStore.getState().accessEpoch },+ )capturedOnMessage!({type: "community:channel.member_remove",serverId: "srv_1",@@ -554,7 +523,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",userId: "u_me",})expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])- expect(useCommunityStore.getState().currentChannelMeta).toBeNull()+ expect(useCommunityStore.getState().currentChannelMeta?.name).toBe("Private forum title")capturedQueryClient.setQueryData(key, forumSidebarFixture([]))capturedOnMessage!({@@ -632,3 +601,81 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",expect(useCommunityStore.getState().currentChannelMeta).toBeNull()})})++describe("membership metadata and access lifetime", () => {+ it("resolves a cold notify removal without evicting readable content", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const api = getCommunityApiFetchMock()+ api.mockResolvedValue({ id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", name: "Child", archived: false })+ const key = communityKeys.channelMessages("child")+ const content = { pages: [{ messages: [{ id: "m1", content: "readable" }] }] }+ capturedQueryClient.setQueryData(key, content)+ capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ type: "thread" }))+ expect(capturedQueryClient.getQueryData(key)).toEqual(content)+ })++ it.each([403, 404, 500])("distinguishes authoritative %s from a temporary metadata failure", async (status) => {+ await mountHook({ viewerUserId: "u_me" })+ const { ApiError } = await import("@/lib/errors")+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ getCommunityApiFetchMock().mockRejectedValue(new ApiError("lookup failed", status))+ const key = communityKeys.channelMessages("child")+ capturedQueryClient.setQueryData(key, { pages: [] })+ capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith("/api/community/channels/child", expect.anything()))+ await vi.waitFor(() => expect(capturedQueryClient.getQueryState(communityKeys.channelMeta("server", "child"))?.fetchStatus ?? "idle").toBe("idle"))+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("child")).toBe(status !== 500)+ expect(capturedQueryClient.getQueryData(key) === undefined).toBe(status !== 500)+ })++ it("discards a slow removal after a newer add and a slow metadata result after server leave", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ let release!: (value: unknown) => void+ const api = getCommunityApiFetchMock()+ api.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))+ capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })+ await vi.waitFor(() => expect(release).toBeTypeOf("function"))+ const meta = { id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", archived: false }+ api.mockResolvedValue(meta)+ capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ type: "thread" }))+ release({ ...meta, type: "text", parentChannelId: null })+ await Promise.resolve()+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("child")).toBe(false)+ expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ type: "thread" })++ let releaseAfterLeave!: (value: unknown) => void+ api.mockImplementationOnce(() => new Promise((resolve) => { releaseAfterLeave = resolve }))+ capturedOnMessage!({ type: "community:channel.member_add", channelId: "other", serverId: "server", userId: "u_me" })+ await vi.waitFor(() => expect(releaseAfterLeave).toBeTypeOf("function"))+ capturedOnMessage!({ type: "community:member.leave", serverId: "server", userId: "u_me" })+ releaseAfterLeave({ ...meta, id: "other" })+ await Promise.resolve()+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("other", "server")).toBe(true)+ expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "other"))).toBeUndefined()+ })++ it("evicts private descendants and ignores late content after parent removal", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const { useCommunityWsStore } = await import("@/stores/community/ws")+ const { useCommunityStore } = await import("@/stores/community")+ const ws = useCommunityWsStore.getState()+ ws.rememberChannelAccess("server", "parent")+ ws.rememberChannelAccess("server", "child", "parent")+ capturedQueryClient.setQueryData(communityKeys.channelMeta("server", "parent"), { id: "parent", type: "forum", verifiedEpoch: ws.accessEpoch })+ capturedQueryClient.setQueryData(communityKeys.channelMeta("server", "child"), { id: "child", type: "thread", parentChannelId: "parent" })+ capturedQueryClient.setQueryData(communityKeys.pins("child"), { pins: [{ id: "m1" }] })+ useCommunityStore.getState().setCurrentServerId("server")+ useCommunityStore.getState().setCurrentChannelId("child")+ useCommunityStore.getState().subscribe({ channelId: "child" })+ capturedOnMessage!({ type: "community:channel.member_remove", channelId: "parent", serverId: "server", userId: "u_me" })+ expect(capturedQueryClient.getQueryData(communityKeys.pins("child"))).toBeUndefined()+ expect(useCommunityStore.getState().currentChannelId).toBeNull()+ capturedOnMessage!({ type: "community:message.create", channelId: "child", parentChannelId: "parent", serverId: "server", message: {+ id: "late", seq: 2, authorId: "author", authorName: "Author", authorAvatarVersion: 0, content: "late", type: "chat", createdAt: "2026-09-06T00:00:00.000Z",+ } })+ expect(getMessageOverlay({ kind: "channel", id: "child", serverId: "server" }).liveById.size).toBe(0)+ })+})diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 9629c1554..14185c83d 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -16,14 +16,20 @@ import {type MembersEnvelope,} from "@/hooks/community/use-server-members"import {- grantForumSidebarChild,+ removeForumSidebarProjectionExact,+ invalidateForumSidebarBaseExact,isKnownNonForumSidebarChannel,} from "@/hooks/community/use-forum-sidebar-threads"+import { ApiError } from "@/lib/errors"+import { useCommunityWsStore } from "@/stores/community/ws"+import { fetchChannelMetadata, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"+import { runCommunityWsProjectionTransaction } from "./projection-transaction"import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"-import { projectChannelScopeEviction } from "./channel-scope-projection"+import { projectChannelScopeEviction, evictServerChannelScopes } from "./channel-scope-projection"import { avatarInitial } from "@/lib/community/avatar"import {invalidateChannelRefDirectory,+ invalidateInbox,invalidateChannelRoster,invalidateInvitableFriends,invalidatePresence,@@ -43,56 +49,74 @@ type ChannelMemberEvent = Extract<export function handleChannelMemberEvent(event: ChannelMemberEvent,- { queryClient, viewerUserIdRef, projection }: MembershipEventContext,+ context: MembershipEventContext,) {- // Re-run the viewer-scoped server tree so the sidebar gains/loses the- // private channel. On REMOVE for the viewer, evict that channel's- // scoped caches so no private content lingers locally (mirrors the- // channel.delete eviction above).- if (- event.type === "community:channel.member_remove" &&- event.userId === viewerUserIdRef.current- ) {- const viewerId = viewerUserIdRef.current- if (viewerId) {- getAccountUnreadProjection(queryClient, viewerId).retireAccessScope({- kind: "channel",- channelId: event.channelId,- })+ const { queryClient, viewerUserIdRef, projection } = context+ invalidateServerDetail(projection, event.serverId)+ invalidateChannelRefDirectory(projection)+ invalidateChannelRoster(projection, event.channelId)+ if (event.userId !== viewerUserIdRef.current) return+ invalidateInbox(projection)+ invalidateServersList(projection)+ void invalidateForumSidebarBaseExact(queryClient, event.serverId).catch(() => undefined)+ const store = useCommunityWsStore.getState()+ store.beginChannelMembershipChange(event.serverId, event.channelId)+ const token = captureChannelMetadataToken(event.channelId)+ const key = communityKeys.channelMeta(event.serverId, event.channelId)+ const cached = queryClient.getQueryData<{ type: string; verifiedEpoch: number }>(key)+ const apply = (type: string, activeProjection = projection) => {+ if (type === "thread") {+ if (event.type === "community:channel.member_remove") {+ getAccountUnreadProjection(queryClient, event.userId).retireNotificationScope({+ kind: "channel", channelId: event.channelId,+ })+ removeForumSidebarProjectionExact(queryClient, event.serverId, event.channelId)+ }+ void invalidateForumSidebarBaseExact(queryClient, event.serverId).catch(() => undefined)+ invalidateInbox(activeProjection)+ invalidateServersList(activeProjection)+ return}- projectChannelScopeEviction(- projection,- queryClient,- event.serverId,- event.channelId,- )- } else if (- event.type === "community:channel.member_add" &&- event.userId === viewerUserIdRef.current- ) {- const viewerId = viewerUserIdRef.current- if (viewerId) {- getAccountUnreadProjection(queryClient, viewerId).grantAccessScope({- kind: "channel",- channelId: event.channelId,+ if (event.type === "community:channel.member_remove") {+ getAccountUnreadProjection(queryClient, event.userId).retireAccessScope({+ kind: "channel", channelId: event.channelId,+ })+ projectChannelScopeEviction(activeProjection, queryClient, event.serverId, event.channelId)+ } else {+ useCommunityWsStore.getState().rememberChannelAccess(event.serverId, event.channelId)+ getAccountUnreadProjection(queryClient, event.userId).grantAccessScope({+ kind: "channel", channelId: event.channelId,})- }- if (!isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {- void grantForumSidebarChild(queryClient, event.serverId, event.channelId)- .catch(() => undefined)}}- invalidateServerDetail(projection, event.serverId)- invalidateChannelRefDirectory(projection)- // Refetch the channel roster so an open private-channel Members drawer- // (and the manage-members dialog) reflect the add/remove live.- // 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.- // A forum thread's "Add participant" emits this same MEMBER_ADD event —- // its Members panel is the participant set, so refetch it too. No-op- // for a plain channel (participants query disabled there).- invalidateChannelRoster(projection, event.channelId)+ if (cached?.verifiedEpoch === store.accessEpoch) {+ apply(cached.type)+ return+ }+ if (isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {+ apply("text")+ return+ }+ void (async () => {+ await queryClient.cancelQueries({ queryKey: key, exact: true })+ if (!isChannelMetadataTokenCurrent(token)) return+ try {+ const meta = await queryClient.fetchQuery({+ queryKey: key,+ queryFn: ({ signal }) => fetchChannelMetadata(event.serverId, event.channelId, signal),+ staleTime: 0,+ })+ if (!isChannelMetadataTokenCurrent(token)) return+ runCommunityWsProjectionTransaction(queryClient, (current) => apply(meta.type, current))+ } catch (error) {+ if (!isChannelMetadataTokenCurrent(token)) return+ if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {+ runCommunityWsProjectionTransaction(queryClient, (current) => {+ projectChannelScopeEviction(current, queryClient, event.serverId, event.channelId)+ })+ }+ }+ })()}function finishMemberEvent(@@ -137,6 +161,7 @@ export function handleMemberJoin(if (event.member.userId === viewerUserIdRef.current) {const viewerId = viewerUserIdRef.currentif (viewerId) {+ useCommunityWsStore.getState().grantServerAccess(event.serverId)getAccountUnreadProjection(queryClient, viewerId).grantAccessScope({kind: "server",serverId: event.serverId,@@ -170,6 +195,7 @@ export function handleMemberLeave(// the user away from the now-forbidden URL.if (event.userId === viewerUserIdRef.current) {const viewerId = viewerUserIdRef.current+ evictServerChannelScopes(queryClient, event.serverId)if (viewerId) {getAccountUnreadProjection(queryClient, viewerId).retireAccessScope({kind: "server",diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.tsindex ca2dc1537..4060b6bc9 100644--- a/src/web/src/hooks/community/community-ws/message-events.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts@@ -114,7 +114,7 @@ describe("useCommunityWs — message.create", () => {expect(invalidateSpy).not.toHaveBeenCalledWith({ queryKey: communityKeys.forumSidebarThreads("srv_1") })})- it("invalidates the forum-sidebar collection when the active child is not loaded", async () => {+ it("does not infer sidebar participation from content for an unloaded child", async () => {await mountHook()seedParent("srv_1", "forum_1", "forum")const key = communityKeys.forumSidebarThreads("srv_1")@@ -127,12 +127,12 @@ describe("useCommunityWs — message.create", () => {} satisfies CommunityMessageCreate)await vi.waitFor(() => {- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(false)})})it.each([false, true])(- "invalidates canonical base for a retained-only child (active=%s) so it survives route exit",+ "patches retained content without promoting participation (active=%s)",async (active) => {if (active) {const { useCommunityStore } = await import("@/stores/community")@@ -161,7 +161,7 @@ describe("useCommunityWs — message.create", () => {expiresAt: "2026-07-06T00:00:00.000Z",})await vi.waitFor(() => {- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(false)})capturedQueryClient.setQueryData(key, forumSidebarFixture(["post_retained"]))@@ -544,12 +544,15 @@ describe("useCommunityWs — message.create", () => {}})- it("debounces inbox invalidation — 10 messages ⇒ 1 invalidate call", async () => {+ it("debounces inbox invalidation — 10 real unread signals produce 1 invalidate call", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_me" })const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")- for (let i = 0; i < 10; i++) capturedOnMessage!(messageCreate("ch_x", `m_${i}`))+ for (let i = 0; i < 10; i++) {+ capturedOnMessage!(messageCreate("ch_x", `m_${i}`))+ capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: "ch_x", serverId: "s1" })+ }// Before debounce window, no invalidate.expect(invalidateSpy).not.toHaveBeenCalled()// Advance past the debounce window — exactly one invalidate.@@ -588,6 +591,7 @@ describe("useCommunityWs — message.create", () => {const event = messageCreate("ch_focused", "m_focused")capturedOnMessage!(event)+ capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: event.channelId })capturedOnMessage!(event)expect(order).toEqual(["candidate"])@@ -704,6 +708,7 @@ describe("useCommunityWs — message.create", () => {const event = messageCreate("ch_focused", "m_visible")capturedOnMessage!(event)+ capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: event.channelId })expect(submitReadIntent(lease, {kind: "timeline",channelId: "ch_focused",@@ -1044,11 +1049,11 @@ describe("useCommunityWs — DM message.create", () => {it("writes the focused DM overlay, leaves Query base-only, and invalidates dms()", async () => {vi.useFakeTimers()try {- await mountHook()+ await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })resetHookMemoization()- await mountHook()+ await mountHook({ viewerUserId: "u_me" })capturedQueryClient.setQueryData(communityKeys.dmMessages("dm_1"), {pages: [{ messages: [], hasMore: false }],@@ -1073,6 +1078,7 @@ describe("useCommunityWs — DM message.create", () => {},}capturedOnMessage!(event)+ capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: event.channelId })const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(communityKeys.dmMessages("dm_1"),)diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex 556165b98..dc59dca09 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -11,10 +11,7 @@ import { projectCommunityMessageCreate } from "@/lib/community/message-wire"import { useCommunityStore } from "@/stores/community"import { useMessageStreamStore } from "@/stores/community/message-stream"import {- getForumSidebarBase,- hasForumSidebarThread,isForumSidebarParent,- invalidateForumSidebarBaseExact,patchForumSidebarActivityExact,} from "@/hooks/community/use-forum-sidebar-threads"import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"@@ -50,9 +47,7 @@ export function handleMessageCreate(wsStore,sub,viewerUserIdRef,- deliveryMode,matchesFocus,- scheduleInboxInvalidate,projection,}: MessageEventContext,) {@@ -96,9 +91,6 @@ export function handleMessageCreate({ type: "wsMessage", message: projected },)}- if (deliveryMode === "batch" && event.message.authorId !== viewerId) {- scheduleInboxInvalidate({ inbox: true, dms: true })- }if (hasSeenMessage) returnwsStore.markSeenMessage(event.message.id)// Sending a message is an implicit typing.stop for its author —@@ -109,19 +101,12 @@ export function handleMessageCreate(// regular channel (`ch:`) so the pill clears in the right bucket.clearTypingIndicator(typingScopeKey(event, sub), event.message.authorId)- // Participation, not unread state, is the sidebar truth. A child- // message reaches every notify member even when muted; use its- // explicit server/parent metadata to re-rank a loaded row without a- // GET, or refetch when the active post is currently absent/expired.+if (event.serverId &&event.parentChannelId &&isForumSidebarParent(queryClient, event.serverId, event.parentChannelId)) {- const canonical = hasForumSidebarThread(- getForumSidebarBase(queryClient, event.serverId),- event.channelId,- )patchForumSidebarActivityExact(queryClient,event.serverId,@@ -129,28 +114,17 @@ export function handleMessageCreate(event.parentChannelId,event.message.createdAt,)- if (!canonical) {- void invalidateForumSidebarBaseExact(queryClient, event.serverId)- }}// 1) A child channel enrolls its sender and mentioned users in its// member set server-side, so refresh an open child roster live.if (- event.channelId === sub.channelId &&- communityStore.currentChannelId === event.channelId &&- communityStore.currentChannelMeta?.parentChannelId+ (event.channelId === sub.channelId || event.channelId === sub.secondaryChannelId) &&+ (event.parentChannelId || (communityStore.currentChannelId === event.channelId && communityStore.currentChannelMeta?.parentChannelId))) {invalidateChannelMembers(projection, event.channelId)}- // 2) Every message.create — regardless of focus — schedules a- // debounced inbox invalidation. Skip messages authored by the- // viewer since they never affect their own unreads.- if (deliveryMode === "single" && event.message.authorId !== viewerId) {- scheduleInboxInvalidate({ inbox: true, dms: true })- }-// 3) Live channel-sidebar unread dot is NO LONGER flipped here.// Unread is per-recipient and mute-gated on the server now, so it// rides the dedicated `community:unread.bump` event (below) — adiff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.tsindex e3515c71c..02fda1252 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts@@ -5,6 +5,7 @@ import {QueryObserver,} from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"import { ApiError } from "@/lib/errors"import {reconcileFocusedMessageQueries,@@ -82,9 +83,35 @@ function seedEmptyActiveQuery(beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()})describe("focused message reconnect catch-up", () => {+ it.each(["account", "parent", "replacement"] as const)("drops old reconnect data after %s changes", async (change) => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const key = communityKeys.channelMessages("child")+ const { unsubscribe } = seedActiveQuery(queryClient, key)+ let release!: (value: unknown) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))+ const result = reconcileFocusedMessageQueries(queryClient, "channel", "child")+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())+ const state = useCommunityWsStore.getState()+ if (change === "account") {+ state.activateProfileAccount("b")+ useCommunityWsStore.getState().activateProfileAccount("a")+ } else if (change === "parent") state.revokeChannelAccess("server", "parent")+ else {+ queryClient.removeQueries({ queryKey: key, exact: true })+ queryClient.setQueryData(key, { pages: [{ messages: [{ id: "new-account-message" }] }], pageParams: [] })+ }+ const expected = queryClient.getQueryData(key)+ release({ messages: [{ id: "old-reconnect-message" }], latestSeq: 2, hasMore: false })+ await result+ expect(queryClient.getQueryData(key)).toBe(expected)+ unsubscribe()+ queryClient.clear()+ })+it("does not repair exact-next, duplicate, or out-of-order frames", () => {const queryClient = new QueryClient()const queryKey = communityKeys.channelMessages("ch_contiguous")diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.tsindex 3993aaf4f..b471ae084 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts@@ -1,6 +1,7 @@import type { InfiniteData, QueryClient, QueryKey } from "@tanstack/react-query"import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { ApiError } from "@/lib/errors"+import { captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"import { communityKeys } from "@/lib/query-keys"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import type {@@ -300,7 +301,10 @@ export async function reconcileFocusedMessageQueries(queryKey,type: "active",})+ const token = captureChannelMetadataToken(scopeId)const operations = queries.map(async (query) => {+ const isCurrent = () => isChannelMetadataTokenCurrent(token)+ && queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query// Infinite-query pagination computes its result from the data snapshot at// fetch start. If that generation completes after reconciliation, TanStack// can replace the reconciled cache with its stale snapshot. Capture the@@ -312,6 +316,7 @@ export async function reconcileFocusedMessageQueries({ revert: true, silent: true },)+ if (!isCurrent()) returnlet accessDenied = falsetry {const window = warmReconnectWindow(query.queryKey, query.state.data)@@ -327,21 +332,24 @@ export async function reconcileFocusedMessageQueries(window.pageParam,window.tag,)+ if (!isCurrent()) returnconst catchUp = window.cursor !== null&& (refreshed.latestSeq ?? 0) > window.latestSeq? await fetchCatchUp(scopeId, window.cursor, window.tag): null+ if (!isCurrent()) returnqueryClient.setQueryData<MessageCache>(query.queryKey, (current) => (isMessageCache(current)? mergeReconciledPages(current, refreshed, catchUp): current))} catch (error) {+ if (!isCurrent()) returnif (!isDefinitiveAccessDenial(error)) throw erroraccessDenied = trueclearDeniedMessageScope(queryClient, kind, scopeId)} finally {- if (pendingDirection && !accessDenied) {+ if (pendingDirection && !accessDenied && isCurrent()) {await query.fetch(undefined, {meta: { fetchMore: { direction: pendingDirection } },})diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 1818c95b9..8c779621a 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -121,16 +121,16 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {it("reactivates the Inbox owner after a Strict Effects cleanup/setup replay", async () => {vi.useFakeTimers()- await mountHook()+ await mountHook({ viewerUserId: "u_me" })flushEffects()unmountHook()resetHookMemoization()- await mountHook()+ await mountHook({ viewerUserId: "u_me" })flushEffects()const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")- capturedOnMessage?.(messageCreate("ch_effect_replay"))+ capturedOnMessage?.({ type: "community:unread.bump", channelId: "dm_effect_replay", userId: "u_me", isMention: false })await vi.advanceTimersByTimeAsync(500)expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex d33a08922..59bbf8f02 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -1,3 +1,4 @@+import { useCommunityWsStore } from "@/stores/community/ws"import type { CommunityWsEvent } from "@alook/shared"import type { CommunityWsReconcilePolicy } from "@/lib/analytics"import type {@@ -163,6 +164,16 @@ export function dispatchCommunityWsEvents(messageEvidenceByChannel,}for (const event of events) {+ const channelId = "channelId" in event ? event.channelId+ : event.type === "community:channel.child_create" ? event.channel.id+ : event.type === "community:channel.create" ? event.channel.id+ : undefined+ const serverId = "serverId" in event ? event.serverId : undefined+ const parentChannelId = "parentChannelId" in event ? event.parentChannelId : undefined+ if (channelId+ && !["community:channel.member_add", "community:channel.member_remove", "community:channel.delete"].includes(event.type)+ && useCommunityWsStore.getState().isChannelAccessRevoked(channelId, serverId, parentChannelId ?? undefined)) continue+ if (channelId && serverId) useCommunityWsStore.getState().observeChannelScope(serverId, channelId, parentChannelId)const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>entry.handler(event, handlerContext)}diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.tsindex 5faf66aeb..d9bbfcdaa 100644--- a/src/web/src/hooks/community/community-ws/social-events.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts@@ -161,7 +161,7 @@ describe("useCommunityWs — account unread projection", () => {.projectServerUnread("s1", [])).toBe(false)})- it("keeps focused content sync and the existing debounced Inbox refresh", async () => {+ it("syncs focused content without refreshing notification surfaces", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_me" })@@ -182,7 +182,7 @@ describe("useCommunityWs — account unread projection", () => {}).liveById.has("m_1")).toBe(true)expect(invalidateSpy.mock.calls.some((call) => ((call[0]?.queryKey as unknown[] | undefined)?.includes("inbox")- ))).toBe(true)+ ))).toBe(false)} finally {vi.useRealTimers()}@@ -249,7 +249,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {it("routes mention.create through the debounced Inbox owner", async () => {vi.useFakeTimers()try {- await mountHook()+ await mountHook({ viewerUserId: "u_1" })const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")const event: CommunityMentionCreate = {type: "community:mention.create",@@ -269,7 +269,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {})it("mention.create invalidates servers so authoritative source counts refresh", async () => {- await mountHook()+ await mountHook({ viewerUserId: "u_1" })const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")const event: CommunityMentionCreate = {type: "community:mention.create",diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex 954c3ae65..6b3993b62 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -117,6 +117,7 @@ export function handleMentionCreate(}: SocialEventContext,) {const viewerId = viewerUserIdRef.current+ if (!viewerId || event.userId !== viewerId) returnif (viewerId && event.userId === viewerId && event.channelId) {const candidate = messageEvidenceByChannel?.get(event.channelId)const evidence = candidate?.messageId === event.messageId ? candidate : undefineddiff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.tsindex d88d9d70a..41340112e 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts@@ -36,6 +36,7 @@ import {import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"import {projectChannelScopeEviction,+ evictServerChannelScopes,projectForumPostUnitEviction,} from "./channel-scope-projection"import {@@ -308,6 +309,7 @@ export function handleServerDelete(event: CommunityServerDelete,{ queryClient, projection }: StructureTreeEventContext,) {+ evictServerChannelScopes(queryClient, event.serverId)getActiveAccountUnreadProjection(queryClient).retireAccessScope({kind: "server",serverId: event.serverId,diff --git a/src/web/src/hooks/community/use-child-channel-meta.test.ts b/src/web/src/hooks/community/use-child-channel-meta.test.tsindex 902226da3..74b40b2d4 100644--- a/src/web/src/hooks/community/use-child-channel-meta.test.ts+++ b/src/web/src/hooks/community/use-child-channel-meta.test.ts@@ -92,7 +92,7 @@ describe("child channel metadata stale rendering", () => {})await waitFor(() => apiFetchMock.mock.calls.length === 1)- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/post-1")+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/post-1", { signal: expect.any(AbortSignal) })expect(queryClient.getQueryData(communityKeys.channelMeta("server-1", "post-1"),)).toMatchObject({ id: "post-1", parentChannelId: "forum-1" })diff --git a/src/web/src/hooks/community/use-child-channel-meta.ts b/src/web/src/hooks/community/use-child-channel-meta.tsindex 02c85de7d..7f5441662 100644--- a/src/web/src/hooks/community/use-child-channel-meta.ts+++ b/src/web/src/hooks/community/use-child-channel-meta.ts@@ -2,25 +2,12 @@import { useQuery } from "@tanstack/react-query"import { useEffect, useState } from "react"-import { apiFetch } from "@/lib/api/client"+import { fetchChannelMetadata, type ChannelMetadata } from "@/hooks/community/channel-metadata"import { communityKeys } from "@/lib/query-keys"import type { ChildChannelMeta } from "@/hooks/community/use-forum-sidebar-threads"import { useCommunityWsStore } from "@/stores/community/ws"-type ChannelMetaPayload = {- id: string- serverId: string- name: string- type: string- parentChannelId: string | null- parentMessageId: string | null- creatorId: string | null- archived: boolean | number- lastMessageAt: string | null- createdAt: string-}--function projectChildMeta(payload: ChannelMetaPayload, verifiedEpoch: number): ChildChannelMeta {+function projectChildMeta(payload: ChannelMetadata, verifiedEpoch: number): ChildChannelMeta {if (!payload.parentChannelId || !payload.parentMessageId) {throw new Error("invalid child channel metadata")}@@ -56,12 +43,9 @@ export function useChildChannelMeta(const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)const query = useQuery<ChildChannelMeta>({queryKey: communityKeys.channelMeta(serverId, channelId),- queryFn: async () => {- const requestEpoch = useCommunityWsStore.getState().accessEpoch- return projectChildMeta(- await apiFetch<ChannelMetaPayload>(`/api/community/channels/${channelId}`),- requestEpoch,- )+ queryFn: async ({ signal }) => {+ const meta = await fetchChannelMetadata(serverId, channelId, signal)+ return projectChildMeta(meta, meta.verifiedEpoch)},enabled,staleTime: Infinity,diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex eff5dbe84..703e66dee 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -109,14 +109,11 @@ function deliveryInboxRefresh(let inbox = falselet dms = falsefor (const event of events) {- if (- event.type === "community:message.create"- && event.message.authorId !== viewerId- ) {+ if (event.type === "community:unread.bump" && event.userId === viewerId) {inbox = true- dms = true+ dms ||= !event.serverId}- if (event.type === "community:mention.create") inbox = true+ if (event.type === "community:mention.create" && event.userId === viewerId) inbox = true}return inbox ? { inbox: true, dms } : null}diff --git a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.tsindex a07e6d2b9..6fb74e796 100644--- a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts+++ b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts@@ -3,6 +3,7 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { useMessages } from "./use-messages"+import { useCommunityWsStore } from "@/stores/community/ws"import { communityKeys } from "@/lib/query-keys"const apiFetchMock = vi.fn()@@ -12,6 +13,7 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()})function Capture({ onRender, channelId, lastReadMessageId }: {@@ -48,11 +50,40 @@ async function waitForSettled(predicate: () => boolean, tries = 40) {function deferred<T>() {let resolve!: (value: T) => void- const promise = new Promise<T>((done) => { resolve = done })- return { promise, resolve }+ let reject!: (error: Error) => void+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail })+ return { promise, resolve, reject }}describe("useMessages — Fix 3 anchor re-validation", () => {+ it.each(["resolves", "rejects"])("does not restore evicted content when an old anchor repair %s", async (outcome) => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const key = communityKeys.channelMessages("child")+ client.setQueryData(key, {+ pages: [{ messages: [{ id: "newest", seq: 3 }], hasMoreOlder: true }],+ pageParams: [{ mode: "newest" }],+ }, { updatedAt: Date.now() - 120_000 })+ const pending = deferred<{ messages: Array<{ id: string; seq: number }> }>()+ apiFetchMock.mockReturnValue(pending.promise)+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(QueryClientProvider, { client },+ React.createElement(Capture, { onRender: () => undefined, channelId: "child", lastReadMessageId: "anchor" })))+ })+ await waitForSettled(() => apiFetchMock.mock.calls.length > 0)+ expect(apiFetchMock).toHaveBeenCalled()+ act(() => {+ useCommunityWsStore.getState().revokeChannelAccess("s1", "parent")+ client.removeQueries({ queryKey: key, exact: true })+ renderer.unmount()+ })+ if (outcome === "resolves") pending.resolve({ messages: [{ id: "old-secret", seq: 2 }] })+ else pending.reject(new Error("old request failed"))+ await flush()+ expect(client.getQueryData(key)).toBeUndefined()+ client.clear()+ })+it("shares one pending anchor repair across an asynchronous route remount", async () => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })const key = communityKeys.channelMessages("ch_remount")diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 70dc166ec..90e11bc5f 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -9,6 +9,7 @@ import {} from "@tanstack/react-query"import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"+import { captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"import { communityKeys } from "@/lib/query-keys"import type {MessagesPage,@@ -529,7 +530,11 @@ function useMessagesInner(// - STALE cache (cross-session IDB hydration): the loaded window is// untrustworthy, so REPLACE it with just the fresh anchor page.const anchorPageParam: MessagesPageParam = { mode: "anchor", anchor: anchorId }- const anchorRequestKey = JSON.stringify([queryKey, anchorPageParam])+ const accessToken = captureChannelMetadataToken(scopeId!)+ const currentQuery = queryClient.getQueryCache().find({ queryKey, exact: true })+ const isCurrent = () => isChannelMetadataTokenCurrent(accessToken)+ && queryClient.getQueryCache().find({ queryKey, exact: true }) === currentQuery+ const anchorRequestKey = JSON.stringify([queryKey, anchorPageParam, accessToken])fetchSharedAnchorRepair(queryClient,anchorRequestKey,@@ -539,7 +544,7 @@ function useMessagesInner(// Re-check right before the swap — a concurrent send/WS update or a// second re-anchor attempt in the interim shouldn't be clobbered by// a now-outdated fetch result landing late.- if (anchorResetKeyRef.current !== resetKey) return+ if (anchorResetKeyRef.current !== resetKey || !isCurrent()) returnqueryClient.setQueryData<PageCache>(queryKey, (current) => {// Stale replace-path: use the fresh page even if `current` is// somehow absent — never fall back to leaving an un-anchored@@ -572,6 +577,7 @@ function useMessagesInner(})}).catch(() => {+ if (!isCurrent()) return// Out-of-band fetch failed — fall back to the reset path so the// scope isn't stuck showing a stale, un-anchored window forever.// This is the ONLY `resetQueries` path left: an outright fetchdiff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex 5ca230686..f12ae9c4b 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -36,7 +36,7 @@ vi.mock("@alook/shared", async () => {},communityMembersResolver: {resolveScopeMemberUserIds: (...a: unknown[]) => mockResolveScopeMemberUserIds(...a),- resolveChannelRecipientUserIds: (...a: unknown[]) => mockResolveChannelRecipientUserIds(...a),+ resolveChannelContentRecipientUserIds: (...a: unknown[]) => mockResolveChannelRecipientUserIds(...a),},communityThread: {listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),@@ -211,7 +211,7 @@ describe("fanOutToServerMembers", () => {)})- it("fanOutToChannel routes a THREAD to its participant set (not the channel audience)", async () => {+ it("fanOutToChannel delegates thread content to the shared readable audience", async () => {mockResolveChannelRecipientUserIds.mockResolvedValue(["u1", "u2"])await fanOutToChannel("t1", {diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex 65b0de744..4b5dcb152 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -29,32 +29,15 @@ async function getServerMemberUserIds(db: Database, serverId: string): Promise<sreturn queries.communityMember.listMemberUserIds(db, serverId)}-/**- * Resolves the recipient set for a channel event.- *- * - THREAD (`type="thread"`, including a post — a thread rooted directly- * under a forum) → the unit's NOTIFY set (its participant rows) — the- * notification dimension: message events reach only participants (join by- * spoke/mention/added), NOT the whole parent channel or server, and NOT- * admins (never auto-participants). A public post therefore doesn't blast- * the whole server, and a private post doesn't ping every roster member on- * every message — only the people actually involved.- * - DM (`type="dm"`) → its two `relation='access'` members. A DM has- * `server_id = NULL`, so it must NOT fall through to the server-scoped- * resolver (which would query `server_id = NULL` and return an empty set).- * - channel / forum → the access audience via the shared resolver- * (public/private split; a forum owns its roster like a text channel).- *- * The split lives here so fan-out and bot-wake use the same recipient set.- */async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {const retryRoute = {"channel-type": "fanout:channel-type","thread-participants": "fanout:thread-participants","dm-members": "fanout:dm-members","scope-members": "fanout:scope-members",+ "readable-members": "fanout:readable-members",} as const- return queries.communityMembersResolver.resolveChannelRecipientUserIds(+ return queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db,channelId,(phase, query) => withD1Retry(query, { route: retryRoute[phase] }),diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.tsindex 2e385b5fb..29e21af56 100644--- a/src/web/src/lib/community/message-dispatcher.test.ts+++ b/src/web/src/lib/community/message-dispatcher.test.ts@@ -12,6 +12,7 @@ const mockGetChannel = vi.fn()const mockListAttention = vi.fn()const mockListAttachments = vi.fn()const mockResolveRecipients = vi.fn()+const mockResolveNotificationRecipients = vi.fn()const mockResolveEligibility = vi.fn()const mockFindWakeCandidates = vi.fn()@@ -37,7 +38,8 @@ vi.mock("@alook/shared", async () => {listMessageAttachments: (...args: unknown[]) => mockListAttachments(...args),},communityMembersResolver: {- resolveChannelRecipientUserIds: (...args: unknown[]) => mockResolveRecipients(...args),+ resolveChannelContentRecipientUserIds: (...args: unknown[]) => mockResolveRecipients(...args),+ resolveChannelNotificationRecipientUserIds: (...args: unknown[]) => mockResolveNotificationRecipients(...args),},communityNotificationEligibility: {resolveNotificationEligibilityForUsers: (...args: unknown[]) => mockResolveEligibility(...args),@@ -127,6 +129,7 @@ describe("planCommittedMessage", () => {? ["author_1", "u_all", "u_mentions", "bot_1"]: [],)+ mockResolveNotificationRecipients.mockImplementation((db, id, run) => run("thread-participants", () => mockResolveRecipients(db, id)))mockResolveEligibility.mockResolvedValue(new Map([["author_1", state()],["u_all", state()],@@ -156,7 +159,7 @@ describe("planCommittedMessage", () => {})expect(mockResolveEligibility).toHaveBeenCalledWith({},- ["author_1", "u_all", "u_mentions", "bot_1", "u_mention_only"],+ ["u_all", "u_mentions", "bot_1", "u_mention_only"],"msg_1",)expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, {@@ -166,6 +169,24 @@ describe("planCommittedMessage", () => {})})+ it("delivers content to passive readers without adding unread, mention, or wake candidates", async () => {+ mockGetChannel.mockResolvedValue({ ...channel, type: "thread", parentChannelId: "parent" })+ mockResolveRecipients.mockResolvedValue(["author_1", "reader", "passive_bot", "u_all"])+ mockResolveNotificationRecipients.mockResolvedValue(["author_1", "u_all"])+ mockListAttention.mockResolvedValue([])+ mockResolveEligibility.mockResolvedValue(new Map([["u_all", state()]]))+ mockFindWakeCandidates.mockResolvedValue([{ botUserId: "passive_bot" }])+ const plan = await planCommittedMessage({} as never, "msg_1")+ expect(plan.contentUserIds).toContain("reader")+ expect(plan.contentUserIds).toContain("passive_bot")+ expect(plan.unreadPlainUserIds).toEqual(["u_all"])+ expect(plan.unreadMentionUserIds).toEqual([])+ expect(plan.mentionUserIds).toEqual([])+ expect(plan.wakeBotUserIds).toEqual([])+ expect(mockResolveEligibility).toHaveBeenCalledWith({}, ["u_all"], "msg_1")+ expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, expect.objectContaining({ recipients: ["u_all"] }))+ })+it("rehydrates attachment dimensions and reply preview from committed rows", async () => {mockGetMessage.mockResolvedValue({ ...message, replyToId: "reply_1" })mockGetMessageInScope.mockResolvedValue({@@ -332,6 +353,8 @@ describe("planCommittedMessage", () => {})it("removes a stale participant that no longer has readable access", async () => {+ mockResolveRecipients.mockResolvedValue(["author_1", "u_mentions"])+ mockResolveNotificationRecipients.mockResolvedValue(["author_1", "u_all", "u_mentions", "bot_1"])mockResolveEligibility.mockResolvedValue(new Map([["author_1", state()],["u_all", state({ isReadable: false })],@@ -344,6 +367,19 @@ describe("planCommittedMessage", () => {expect(plan.wakeBotUserIds).toEqual([])})+ it("deduplicates notification and attention candidates without consulting passive readers", async () => {+ mockResolveRecipients.mockResolvedValue(["author_1", "reader", "u_all", "u_mentions"])+ mockResolveNotificationRecipients.mockResolvedValue(["author_1", "u_all", "u_all", "u_mentions", "outside"])+ mockListAttention.mockResolvedValue(["author_1", "u_mentions", "u_mentions", "u_mention_only"])+ const plan = await planCommittedMessage({} as never, "msg_1")+ expect(mockResolveEligibility).toHaveBeenCalledWith({}, ["u_all", "u_mentions", "outside", "u_mention_only"], "msg_1")+ expect(plan.contentUserIds).toEqual(["author_1", "reader", "u_all", "u_mentions"])+ expect(plan.unreadPlainUserIds).toEqual(["u_all"])+ expect(plan.unreadMentionUserIds).toEqual(["u_mentions"])+ expect(plan.mentionUserIds).toEqual(["u_mentions", "u_mention_only"])+ expect(plan.wakeBotUserIds).toEqual([])+ })+it("is stable when rerun from the same committed facts", async () => {const first = await planCommittedMessage({} as never, "msg_1")const second = await planCommittedMessage({} as never, "msg_1")diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.tsindex 0d37d5e01..d9b49edc7 100644--- a/src/web/src/lib/community/message-dispatcher.ts+++ b/src/web/src/lib/community/message-dispatcher.ts@@ -35,10 +35,11 @@ const recipientRetryRoute = {"thread-participants": "message-dispatcher:thread-participants","dm-members": "message-dispatcher:dm-members","scope-members": "message-dispatcher:scope-members",+ "readable-members": "message-dispatcher:readable-members",} as constasync function resolveRecipients(db: Database, channelId: string): Promise<string[]> {- return queries.communityMembersResolver.resolveChannelRecipientUserIds(+ return queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db,channelId,(phase, query) => withD1Retry(query, { route: recipientRetryRoute[phase] }),@@ -81,9 +82,17 @@ export async function planCommittedMessage(throw new Error("committed message scope not found")}- const candidateContentUserIds = unique(await resolveRecipients(db, channel.id))+ const [contentCandidates, notificationCandidates] = await Promise.all([+ resolveRecipients(db, channel.id),+ queries.communityMembersResolver.resolveChannelNotificationRecipientUserIds(+ db, channel.id,+ (phase, query) => withD1Retry(query, { route: recipientRetryRoute[phase] }),+ ),+ ])+ const contentUserIds = unique(contentCandidates)+ const candidateNotificationUserIds = unique(notificationCandidates).filter((id) => id !== message.authorId)const attentionIds = unique(attentionUserIds).filter((id) => id !== message.authorId)- const eligibilityUserIds = unique([...candidateContentUserIds, ...attentionIds])+ const eligibilityUserIds = unique([...candidateNotificationUserIds, ...attentionIds])const [eligibility, replyTarget] = await Promise.all([withD1Retry(@@ -106,13 +115,13 @@ export async function planCommittedMessage(: Promise.resolve(null),])- const contentUserIds = candidateContentUserIds.filter(- (id) => eligibility.get(id)?.isReadable,+ const contentSet = new Set(contentUserIds)+ const notificationUserIds = candidateNotificationUserIds.filter(+ (id) => contentSet.has(id),)- const notifyContentUserIds = contentUserIds.filter((id) => id !== message.authorId)const wakeCandidates = await withD1Retry(() => queries.communityBot.findWakeCandidates(db, {- recipients: notifyContentUserIds,+ recipients: notificationUserIds,channelId: message.channelId,newSeq: message.seq,}),@@ -130,23 +139,23 @@ export async function planCommittedMessage())}- const unreadMentionUserIds = notifyContentUserIds.filter((id) => {+ const unreadMentionUserIds = notificationUserIds.filter((id) => {const state = eligibility.get(id)return allowed(id) && Boolean(state?.hasAttention)})const unreadMentionSet = new Set(unreadMentionUserIds)- const unreadPlainUserIds = notifyContentUserIds.filter(+ const unreadPlainUserIds = notificationUserIds.filter((id) => allowed(id) && !unreadMentionSet.has(id),)const mentionUserIds = attentionIds.filter((id) => {const state = eligibility.get(id)return allowed(id) && Boolean(state?.hasAttention)})- const notifyContentSet = new Set(notifyContentUserIds)+ const notificationSet = new Set(notificationUserIds)const wakeBotUserIds = unique(wakeCandidates.map((candidate) => candidate.botUserId)- .filter((id) => notifyContentSet.has(id) && allowed(id)),+ .filter((id) => notificationSet.has(id) && allowed(id)),)const replyMap = new Map<string, {diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.tsindex 0832010c6..8bd506f34 100644--- a/src/web/src/stores/community/ws.ts+++ b/src/web/src/stores/community/ws.ts@@ -65,8 +65,24 @@ export type CommunityWsConnectionStatus = "connected" | "reconnecting" | "failedconst NOOP_RECONNECT = () => undefined+type ChannelAccessScope = {+ serverId: string+ parentChannelId?: string | null+ generation: number+ revoked: boolean+}+export type CommunityWsStoreState = {accessEpoch: number+ channelAccessScopes: Map<string, ChannelAccessScope>+ revokedServerIds: Set<string>+ beginChannelMembershipChange: (serverId: string, channelId: string) => number+ observeChannelScope: (serverId: string, channelId: string, parentChannelId?: string | null) => void+ rememberChannelAccess: (serverId: string, channelId: string, parentChannelId?: string | null) => void+ revokeChannelAccess: (serverId: string, channelId: string) => string[]+ revokeServerAccess: (serverId: string) => void+ grantServerAccess: (serverId: string) => void+ isChannelAccessRevoked: (channelId: string, serverId?: string, parentChannelId?: string) => booleanaccessConnected: booleanconnectionStatus: CommunityWsConnectionStatusreconnectNow: () => void@@ -118,10 +134,12 @@ const initialState = (): Pick<"profileViewerId" | "profileAccountEpoch" | "profileRevision"| "profilesByUserId" | "profileRevisionsByUserId"| "seenMessageIds" | "seenDeliveryOperations" | "botAuditEvents"- | "accessEpoch" | "accessConnected"+ | "accessEpoch" | "accessConnected" | "channelAccessScopes" | "revokedServerIds"| "connectionStatus" | "reconnectNow"> => ({accessEpoch: 0,+ channelAccessScopes: new Map(),+ revokedServerIds: new Set(),accessConnected: false,connectionStatus: "connected",reconnectNow: NOOP_RECONNECT,@@ -232,7 +250,9 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {set({profileViewerId: viewerId,profileAccountEpoch,- profileRevision: 0,+ accessEpoch: state.accessEpoch + 1,+ channelAccessScopes: new Map(),+ revokedServerIds: new Set(), profileRevision: 0,profilesByUserId: new Map(),profileRevisionsByUserId: new Map(),})@@ -301,6 +321,69 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {return true},+ beginChannelMembershipChange: (serverId, channelId) => {+ const scopes = new Map(get().channelAccessScopes)+ const previous = scopes.get(channelId)+ const generation = (previous?.generation ?? 0) + 1+ scopes.set(channelId, { serverId, revoked: false, ...previous, generation })+ set({ channelAccessScopes: scopes })+ return generation+ },++ observeChannelScope: (serverId, channelId, parentChannelId) => {+ const previous = get().channelAccessScopes.get(channelId)+ if (previous?.serverId === serverId && (!parentChannelId || previous.parentChannelId === parentChannelId)) return+ const scopes = new Map(get().channelAccessScopes)+ scopes.set(channelId, { generation: 0, revoked: false, ...previous, serverId, ...(parentChannelId ? { parentChannelId } : {}) })+ set({ channelAccessScopes: scopes })+ },++ rememberChannelAccess: (serverId, channelId, parentChannelId) => {+ const scopes = new Map(get().channelAccessScopes)+ const previous = scopes.get(channelId)+ scopes.set(channelId, { serverId, parentChannelId, generation: previous?.generation ?? 0, revoked: false })+ if (parentChannelId && scopes.get(parentChannelId)?.revoked) {+ const parent = scopes.get(parentChannelId)!+ scopes.set(parentChannelId, { ...parent, revoked: false })+ }+ set({ channelAccessScopes: scopes })+ },++ revokeChannelAccess: (serverId, channelId) => {+ const scopes = new Map(get().channelAccessScopes)+ const affected = new Set([channelId])+ for (const [id, scope] of scopes) {+ if (scope.serverId === serverId && scope.parentChannelId === channelId) affected.add(id)+ }+ for (const id of affected) {+ const previous = scopes.get(id)+ scopes.set(id, { serverId, ...previous, generation: (previous?.generation ?? 0) + 1, revoked: true })+ }+ set({ channelAccessScopes: scopes, accessEpoch: get().accessEpoch + 1 })+ return [...affected]+ },++ revokeServerAccess: (serverId) => {+ const revokedServerIds = new Set(get().revokedServerIds).add(serverId)+ set({ revokedServerIds, accessEpoch: get().accessEpoch + 1 })+ },++ grantServerAccess: (serverId) => {+ const revokedServerIds = new Set(get().revokedServerIds)+ revokedServerIds.delete(serverId)+ set({ revokedServerIds })+ },++ isChannelAccessRevoked: (channelId, serverId, parentChannelId) => {+ const state = get()+ const scope = state.channelAccessScopes.get(channelId)+ const server = serverId ?? scope?.serverId+ const parent = parentChannelId ?? scope?.parentChannelId+ return Boolean(scope?.revoked+ || (server && state.revokedServerIds.has(server))+ || (parent && state.channelAccessScopes.get(parent)?.revoked))+ },+markAccessDisconnected: () => set((state) => ({accessEpoch: state.accessEpoch + 1,accessConnected: false,diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex 02b919699..63c5927f2 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -4,18 +4,16 @@ import { tid } from "./_fixtures/testids"import { sendMessage } from "./_fixtures/actions"import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { seedDm, seedBlock, seedDmMessage } from "./_fixtures/seed"+import { captureNotificationRequests, gotoAfterNotificationStartup, notificationPaths, notificationResponsesFinished } from "./_fixtures/community-notification-requests"// Journey 4 — DMs. human↔human needs only not-blocked (no friendship). Covers// the new-conversation-appears-live path and the blocked-composer regression.test.describe.serial("direct messages", () => {- test("an Inbox first-DM click commits immediately and stays on the conversation", async ({ asUser }) => {+ test("an Inbox first-DM click commits immediately and stays on the conversation", async ({ asUser }, testInfo) => {const bob = await asUser("bob")- const initialDms = bob.page.waitForResponse((response) =>- response.request().method() === "GET"- && new URL(response.url()).pathname === "/api/community/users/me/dms",- )- await bob.page.goto("/c/me")- expect((await initialDms).status()).toBe(200)+ const trace = captureNotificationRequests(bob.page)+ const proxy = await gotoAfterNotificationStartup(bob.page, bob.context, trace)+ trace.phase("notification")let releaseCanonical!: () => voidlet canonicalFinished!: () => void@@ -39,9 +37,13 @@ test.describe.serial("direct messages", () => {}})+ const notificationRefresh = notificationResponsesFinished(bob.page, notificationPaths.filter((path) => path.includes("/inbox/")))const dmId = await seedDm("alice", userId("bob"))const body = `first inbox DM ${Date.now()}`const messageId = await seedDmMessage("alice", dmId, body)+ await expect.poll(() => trace.events.some((event) =>+ event.type === "community:unread.bump" && event.channelId === dmId && event.userId === userId("bob"))).toBe(true)+ await notificationRefreshawait expect.poll(() => dmsGets).toBe(1)const routeHistory: string[] = []const recordRoute = (frame: Frame) => {@@ -53,7 +55,9 @@ test.describe.serial("direct messages", () => {await bob.page.getByRole("button", { name: "Inbox" }).click()const inboxRow = bob.page.getByTestId(tid.inboxUnreadDm(dmId))await expect(inboxRow).toBeVisible({ timeout: 20_000 })+ trace.phase("click")const dmsGetsBeforeClick = dmsGets+ expect(dmsGetsBeforeClick).toBe(1)await inboxRow.click()await bob.page.waitForURL(new RegExp(`/c/me/${dmId}$`), {@@ -70,12 +74,17 @@ test.describe.serial("direct messages", () => {await expect(bob.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })await expect(bob.page).toHaveURL(new RegExp(`/c/me/${dmId}$`))expect(routeHistory).not.toContain("/c/me")+ trace.phase("click-complete")expect(dmsGets - dmsGetsBeforeClick).toBe(0)} finally {releaseCanonical()await canonicalSettledbob.page.off("framenavigated", recordRoute)await bob.page.unroute(dmsPattern)+ await testInfo.attach("community-request-timeline", {+ body: JSON.stringify({ connectionFrames: proxy.connectionFrames, timeline: trace.timeline, dmsGets }, null, 2),+ contentType: "application/json",+ })}})diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.tsindex 41f98bc5a..df726f4d4 100644--- a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts@@ -25,7 +25,7 @@ function messageFrame(frame: CapturedCommunityFrame, channelId: string, content:}test.describe.serial("committed message delivery QA", () => {- test("Q4: a parent-only forum viewer gets the parent projection and no child message", async ({ asUser }) => {+ test("Q4: a readable nonparticipant gets child content and parent projection without notifications", async ({ asUser }) => {const serverId = await seedServer("alice", `Parent projection ${Date.now()}`)const forumId = await seedChannel("alice", serverId, "parent-projection", "forum")await seedJoinServer("alice", "bob", serverId)@@ -33,11 +33,13 @@ test.describe.serial("committed message delivery QA", () => {const threadId = await seedForumThread("alice", forumId, `Projection ${Date.now()}`, "opener")const carol = await asUser("carol")- let armed = falseconst carolProxy = await proxyCommunityWebSockets(carol.context)await gotoAfterUserWsAuth(carol.page, `/c/channels/${serverId}/${forumId}`)await expect(carol.page.getByTestId(tid.forumThreadCard(threadId))).toBeVisible({ timeout: 20_000 })- armed = true+ const membersBefore = await carol.page.request.get(`/api/community/channels/${threadId}/members`)+ expect(membersBefore.status()).toBe(200)+ expect((await membersBefore.json() as { members: Array<{ id: string }> }).members.map((member) => member.id)).not.toContain(userId("carol"))+ const frameStart = carolProxy.frames.lengthconst bob = await asUser("bob")await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${threadId}`)@@ -45,12 +47,20 @@ test.describe.serial("committed message delivery QA", () => {const body = `participant reply ${Date.now()}`await sendMessage(bob.page, body)- await expect.poll(() => carolProxy.frames.some((frame) => armed- && communityFrameEvents(frame).some((event) =>+ await expect.poll(() => carolProxy.frames.slice(frameStart).some((frame) => communityFrameEvents(frame).some((event) =>event.type === "community:channel.child_update"&& event.parentChannelId === forumId&& event.channelId === threadId)), { timeout: 20_000 }).toBe(true)- expect(carolProxy.frames.some((frame) => messageFrame(frame, threadId, body))).toBe(false)+ await expect.poll(() => carolProxy.frames.slice(frameStart).some((frame) => messageFrame(frame, threadId, body))).toBe(true)+ const childDelivery = carolProxy.frames.slice(frameStart).find((frame) => messageFrame(frame, threadId, body))!+ expect(communityFrameEvents(childDelivery).filter((event) =>+ event.type === "community:unread.bump" || event.type === "community:mention.create")).toEqual([])+ expect(carolProxy.frames.slice(frameStart).flatMap(communityFrameEvents).filter((event) =>+ event.channelId === threadId && event.userId === userId("carol")+ && (event.type === "community:unread.bump" || event.type === "community:mention.create" || event.type === "community:channel.member_add"))).toEqual([])+ const membersAfter = await carol.page.request.get(`/api/community/channels/${threadId}/members`)+ expect(membersAfter.status()).toBe(200)+ expect((await membersAfter.json() as { members: Array<{ id: string }> }).members.map((member) => member.id)).not.toContain(userId("carol"))await expect(carol.page.getByText(body, { exact: false })).toHaveCount(0)})diff --git a/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts b/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.tsnew file mode 100644index 000000000..bfa1d431f--- /dev/null+++ b/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts@@ -0,0 +1,71 @@+import { test, expect, sessionCookie, userId } from "./_fixtures/community-fixture"+import { captureNotificationRequests, gotoAfterNotificationStartup } from "./_fixtures/community-notification-requests"+import { seedCategory, seedChannel, seedChannelMember, seedForumThread, seedJoinServer, seedMessage, seedServer, seedThread } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"+import { WEB_URL } from "./_setup/paths"++async function mutate(path: string, method: string, body?: unknown) {+ return fetch(`${WEB_URL}${path}`, {+ method,+ headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL, "Content-Type": "application/json" },+ ...(body ? { body: JSON.stringify(body) } : {}),+ })+}++for (const parentType of ["text", "forum"] as const) {+ for (const privateParent of [false, true]) {+ test(`${privateParent ? "private" : "public"} ${parentType} child separates readable content from participation`, async ({ asUser }, testInfo) => {+ test.setTimeout(120_000)+ const serverId = await seedServer("alice", `Realtime ${Date.now()}`)+ const categoryId = privateParent ? await seedCategory("alice", serverId, "Restricted realtime", { private: true }) : undefined+ const parentId = await seedChannel("alice", serverId, "realtime", parentType, categoryId)+ await seedJoinServer("alice", "bob", serverId)+ if (privateParent) await seedChannelMember("alice", parentId, userId("bob"))+ const childId = parentType === "forum"+ ? await seedForumThread("alice", parentId, "Live post", "Initial content")+ : await seedThread("alice", await seedMessage("alice", parentId, "Thread opener"), "Live thread")+ const bob = await asUser("bob")+ const trace = captureNotificationRequests(bob.page)+ const proxy = await gotoAfterNotificationStartup(bob.page, bob.context, trace)+ try {+ trace.phase("content")+ trace.events.length = 0+ trace.requests.length = 0++ const firstId = await seedMessage("alice", childId, "Passive reader receives this")+ await expect.poll(() => trace.events.some((event) => event.type === "community:message.create" && event.message.id === firstId)).toBe(true)+ await bob.page.waitForTimeout(750)+ expect(trace.events.filter((event) => (event.type === "community:unread.bump" || event.type === "community:mention.create") && event.channelId === childId)).toEqual([])+ expect(trace.requests.filter((path) => path.startsWith("/api/community/users/me/inbox/") || path === "/api/community/users/me/dms" || path === `/api/community/channels/${childId}/read`)).toEqual([])++ await bob.page.goto(`/c/channels/${serverId}/${childId}`)+ await expect(bob.page.getByTestId(tid.message(firstId))).toBeVisible()+ const added = await mutate(`/api/community/channels/${childId}/participants`, "POST", { userId: userId("bob") })+ expect(added.status).toBe(201)+ await expect.poll(() => trace.events.some((event) => event.type === "community:channel.member_add" && event.channelId === childId && event.userId === userId("bob"))).toBe(true)+ const removed = await bob.page.request.delete(`/api/community/channels/${childId}/participants/${userId("bob")}`)+ expect(removed.status()).toBe(204)+ await expect.poll(() => trace.events.some((event) => event.type === "community:channel.member_remove" && event.channelId === childId && event.userId === userId("bob"))).toBe(true)+ await expect(bob.page.getByTestId(tid.message(firstId))).toBeVisible()+ const secondId = await seedMessage("alice", childId, "Still readable after leaving participation")+ await expect(bob.page.getByTestId(tid.message(secondId))).toBeVisible()++ if (privateParent) {+ const revoked = await mutate(`/api/community/channels/${parentId}/members/${userId("bob")}`, "DELETE")+ expect(revoked.status).toBe(204)+ await expect(bob.page.getByTestId(tid.message(secondId))).toHaveCount(0)+ const denied = await bob.page.request.get(`/api/community/channels/${childId}`)+ expect([403, 404]).toContain(denied.status())+ const lastId = await seedMessage("alice", childId, "Revoked reader cannot receive this")+ await bob.page.waitForTimeout(750)+ expect(trace.events.some((event) => event.type === "community:message.create" && event.message.id === lastId)).toBe(false)+ }+ } finally {+ await testInfo.attach("community-request-timeline", {+ body: JSON.stringify({ connectionFrames: proxy.connectionFrames, timeline: trace.timeline }, null, 2),+ contentType: "application/json",+ })+ }+ })+ }+}diff --git a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.tsindex 26f0d335a..e2d2b9469 100644--- a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts+++ b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts@@ -60,6 +60,7 @@ async function seedForum(label: string) {const threadId = await seedForumThread("alice", forumId, `Post ${Date.now()}`, "tag editor body")return {route: `/c/channels/${serverId}/${forumId}`,+ forumId,threadId,}}@@ -219,7 +220,7 @@ test.describe.serial("forum tag editor", () => {})test("converges Archive and Unarchive across two tabs", async ({ asUser }) => {- const { route, threadId } = await seedForum("Archive cross tab")+ const { route, forumId, threadId } = await seedForum("Archive cross tab")const tabA = await asUser("alice")const tabB = await asUser("alice")await Promise.all([@@ -253,12 +254,31 @@ test.describe.serial("forum tag editor", () => {&& new URL(response.url()).pathname.endsWith("/tags")))await tabB.page.getByTestId(tid.forumThreadArchiveBtn(threadId)).click()- expect((await unarchived).status()).toBe(200)- await expect(cardA).toHaveCount(0)-- await tabA.page.getByTestId(tid.forumTagAll).click()- await expect(cardA).toBeVisible()- await expect(tabA.page.getByTestId(tid.forumThreadCard(threadId))).toHaveCount(1)+ const unarchivedResponse = await unarchived+ expect(unarchivedResponse.status()).toBe(200)+ expect(await unarchivedResponse.json()).toEqual({ tags: [] })+ await expect.poll(async () => {+ const [tags, feed] = await Promise.all([+ tabA.page.request.get(`/api/community/channels/${forumId}/messages/tags`),+ tabA.page.request.get(`/api/community/channels/${forumId}/threads`),+ ])+ expect(tags.status()).toBe(200)+ expect(feed.status()).toBe(200)+ return {+ tags: (await tags.json() as { tags: string[] }).tags,+ threads: (await feed.json() as { threads: Array<{ id: string }> }).threads.map((thread) => thread.id),+ }+ }).toEqual({ tags: [], threads: [threadId] })+ for (const { page } of [tabA, tabB]) {+ await expect(page.getByTestId(tid.forumTagChip("archived"))).toHaveCount(0)+ await expect(page.getByTestId(tid.forumTagAll)).toHaveCount(0)+ await expect.poll(() => page.evaluate((id) => localStorage.getItem(`alook:forum-tag:${id}`), forumId)).toBeNull()+ const card = page.getByTestId(tid.forumThreadCard(threadId))+ await expect(card).toBeVisible()+ await expect(card).toHaveCount(1)+ await expect(page.getByTestId(tid.forumThreadArchiveBtn(threadId))).toHaveAttribute("aria-label", "Archive post")+ await expect(page.getByTestId(tid.forumThreadArchiveBtn(threadId))).toHaveAttribute("aria-pressed", "false")+ }})test("discards implicit close and commits only explicit Save", async ({ asUser }) => {diff --git a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.tsnew file mode 100644index 000000000..af2f2d810--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts@@ -0,0 +1,83 @@+import type { CommunityWsEvent } from "@alook/shared"+import { expect, type BrowserContext, type Page, type Request } from "@playwright/test"+import { proxyCommunityWebSockets } from "./community-ws-proxy"++export const notificationPaths = [+ "/api/community/users/me/inbox/unreads",+ "/api/community/users/me/inbox/mentions",+ "/api/community/users/me/dms",+]++export async function notificationResponsesFinished(page: Page, paths = notificationPaths) {+ await Promise.all(paths.map(async (path) => {+ const response = await page.waitForResponse((candidate) =>+ candidate.request().method() === "GET" && new URL(candidate.url()).pathname === path,+ )+ expect(response.status()).toBe(200)+ expect(await response.finished()).toBeNull()+ }))+}++export function captureNotificationRequests(page: Page) {+ const events: CommunityWsEvent[] = []+ const requests: string[] = []+ const pendingNotifications = new Set<Request>()+ const requestIds = new Map<Request, number>()+ const timeline: Array<Record<string, unknown>> = []+ let phase = "initial"+ const record = (data: Record<string, unknown>) => timeline.push({ at: Date.now(), phase, ...data })+ page.on("websocket", (socket) => {+ socket.on("framereceived", ({ payload }) => {+ try {+ const frame = JSON.parse(payload.toString()) as CommunityWsEvent | { type: "community:events.batch"; events: CommunityWsEvent[] }+ record({ kind: "frame", type: frame.type })+ if (!frame.type.startsWith("community:")) return+ for (const event of frame.type === "community:events.batch" ? frame.events : [frame]) {+ events.push(event)+ record({ kind: "event", type: event.type,+ channelId: "channelId" in event ? event.channelId : undefined,+ messageId: event.type === "community:message.create" ? event.message.id : undefined })+ }+ } catch {}+ })+ })+ page.on("request", (request) => {+ const path = new URL(request.url()).pathname+ requestIds.set(request, requestIds.size + 1)+ requests.push(path)+ record({ kind: "request-start", id: requestIds.get(request), path, method: request.method() })+ if (notificationPaths.includes(path)) pendingNotifications.add(request)+ })+ page.on("requestfinished", (request) => {+ pendingNotifications.delete(request)+ record({ kind: "request-finished", id: requestIds.get(request), path: new URL(request.url()).pathname })+ })+ page.on("requestfailed", (request) => {+ pendingNotifications.delete(request)+ record({ kind: "request-failed", id: requestIds.get(request), path: new URL(request.url()).pathname })+ })+ return { events, requests, pendingNotifications, timeline,+ phase: (next: string) => { phase = next; record({ kind: "phase" }) } }+}++export async function gotoAfterNotificationStartup(+ page: Page,+ context: BrowserContext,+ trace: ReturnType<typeof captureNotificationRequests>,+) {+ let holdAuthentication = true+ const proxy = await proxyCommunityWebSockets(context, {+ decideConnectionFrame: (frame) => frame.type === "auth.ok" && holdAuthentication ? "hold" : "forward",+ })+ const initial = notificationResponsesFinished(page)+ await page.goto("/c/me", { waitUntil: "commit" })+ await initial+ await expect.poll(() => proxy.heldConnectionCount()).toBe(1)+ trace.phase("auth-release")+ const authenticatedRefresh = notificationResponsesFinished(page)+ holdAuthentication = false+ expect(proxy.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)+ await authenticatedRefresh+ await expect.poll(() => trace.pendingNotifications.size).toBe(0)+ return proxy+}diff --git a/src/ws-do/src/community-content-access.test.ts b/src/ws-do/src/community-content-access.test.tsnew file mode 100644index 000000000..0acb08c4d--- /dev/null+++ b/src/ws-do/src/community-content-access.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { WS_EVENTS } from "@alook/shared"+import { communityWsEventFixtures } from "../../shared/test/community-ws-events.fixtures"+import { canDeliverCommunityContent, communityContentAccessKinds } from "./community-content-access"++const { readable, messageScope } = vi.hoisted(() => ({ readable: vi.fn(), messageScope: vi.fn() }))+vi.mock("@alook/shared", async (importOriginal) => ({+ ...await importOriginal<typeof import("@alook/shared")>(),+ queries: { communityChannel: { listReadableChannelsForUser: readable, getReadableMessageChannelId: messageScope } },+}))+beforeEach(() => {+ vi.clearAllMocks()+ readable.mockResolvedValue([{ id: "channel-1", serverId: "server-1", parentChannelId: "parent-1" }])+ messageScope.mockResolvedValue("channel-1")+})++describe("community target content access", () => {+ it("fails closed for an event outside the declared contract", async () => {+ expect(await canDeliverCommunityContent({} as never, "user-1", [{ type: "community:future" } as never])).toBe(false)+ })+ it("classifies the entire current event contract", () => {+ expect(Object.keys(communityContentAccessKinds).sort()).toEqual(Object.values(WS_EVENTS).sort())+ })+ it.each(Object.values(communityWsEventFixtures))("enforces the declared gate for $type", async (event) => {+ if (communityContentAccessKinds[event.type] === "control") {+ expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(true)+ expect(readable).not.toHaveBeenCalled()+ } else {+ readable.mockResolvedValue([])+ messageScope.mockResolvedValue(null)+ expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(false)+ }+ })+ it("never lets a control child bypass mixed content access", async () => {+ readable.mockResolvedValue([])+ expect(await canDeliverCommunityContent({} as never, "user-1", [+ communityWsEventFixtures["community:channel.member_add"],+ communityWsEventFixtures["community:message.create"],+ ])).toBe(false)+ })+ it("validates current scope and server identity", async () => {+ const event = communityWsEventFixtures["community:message.create"]+ expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(true)+ expect(await canDeliverCommunityContent({} as never, "user-1", [{ ...event, serverId: "wrong" }])).toBe(false)+ expect(await canDeliverCommunityContent({} as never, "user-1", [{ ...event, parentChannelId: "wrong" }])).toBe(false)+ })+ it("validates child-parent relationships and notification targets", async () => {+ const event = { type: "community:channel.child_update" as const, channelId: "child", parentChannelId: "parent", changes: {} }+ readable.mockResolvedValue([{ id: "parent", serverId: "server" }, { id: "child", serverId: "server", parentChannelId: "parent" }])+ expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(true)+ readable.mockResolvedValue([{ id: "parent" }, { id: "child", parentChannelId: "wrong" }])+ expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(false)+ expect(await canDeliverCommunityContent({} as never, "user-1", [{ type: "community:unread.bump", userId: "other", channelId: "child" }])).toBe(false)+ })+ it("resolves legacy attention scope and propagates transient lookup failure", async () => {+ const event = { type: "community:mention.create" as const, userId: "user-1", messageId: "message-1", authorName: "Author" }+ expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(true)+ expect(messageScope).toHaveBeenCalledWith({}, "user-1", "message-1")+ readable.mockRejectedValue(new Error("D1 unavailable"))+ await expect(canDeliverCommunityContent({} as never, "user-1", [event])).rejects.toThrow("D1 unavailable")+ })+})diff --git a/src/ws-do/src/community-content-access.ts b/src/ws-do/src/community-content-access.tsnew file mode 100644index 000000000..fac1c4b11--- /dev/null+++ b/src/ws-do/src/community-content-access.ts@@ -0,0 +1,123 @@+import { queries, type CommunityWsEvent, type Database } from "@alook/shared"++type AccessKind = "channel" | "child-create" | "child-update" | "channel-create" | "mention" | "notification" | "control"++export const communityContentAccessKinds = {+ "community:message.create": "channel",+ "community:message.updated": "channel",+ "community:message.edited": "channel",+ "community:reaction.add": "channel",+ "community:reaction.remove": "channel",+ "community:pin.add": "channel",+ "community:pin.remove": "channel",+ "community:typing.start": "channel",+ "community:typing.stop": "channel",+ "community:channel.child_create": "child-create",+ "community:channel.child_update": "child-update",+ "community:channel.create": "channel-create",+ "community:channel.update": "channel",+ "community:unread.bump": "notification",+ "community:mention.create": "mention",+ "community:channel.delete": "control",+ "community:channel.member_remove": "control",+ "community:member.leave": "control",+ "community:server.delete": "control",+ "community:channel.member_add": "control",+ "community:member.join": "control",+ "community:server.update": "control",+ "community:channel.reorder": "control",+ "community:category.create": "control",+ "community:category.update": "control",+ "community:category.delete": "control",+ "community:category.reorder": "control",+ "community:member.update": "control",+ "community:invite.create": "control",+ "community:friend.request": "control",+ "community:friend.accept": "control",+ "community:friend.reject": "control",+ "community:friend.remove": "control",+ "community:friend.block": "control",+ "community:read_state.advanced": "control",+ "community:inbox.changed": "control",+ "community:presence.update": "control",+ "community:status.update": "control",+ "community:identity.update": "control",+ "community:profile.update": "control",+ "community:machine.created": "control",+ "community:machine.status": "control",+ "community:machine.updated": "control",+ "community:machine.removed": "control",+ "community:bot.audit_event": "control",+} as const satisfies Record<CommunityWsEvent["type"], AccessKind>++type Scope = { id: string; serverId?: string; parentChannelId?: string }++export async function canDeliverCommunityContent(+ db: Database,+ targetUserId: string,+ events: readonly CommunityWsEvent[],+): Promise<boolean> {+ const scopes: Scope[] = []+ for (const event of events) {+ const kind = communityContentAccessKinds[event.type]+ if (kind === "control") continue+ switch (event.type) {+ case "community:mention.create": {+ if (event.userId !== targetUserId) return false+ const id = event.channelId ?? await queries.communityChannel.getReadableMessageChannelId(+ db, targetUserId, event.messageId,+ )+ if (!id) return false+ scopes.push({ id })+ break+ }+ case "community:unread.bump":+ if (event.userId !== targetUserId) return false+ scopes.push({ id: event.channelId, serverId: event.serverId })+ break+ case "community:channel.child_create":+ scopes.push({ id: event.parentChannelId }, {+ id: event.channel.id, parentChannelId: event.parentChannelId,+ })+ break+ case "community:channel.child_update":+ scopes.push({ id: event.parentChannelId }, {+ id: event.channelId, parentChannelId: event.parentChannelId,+ })+ break+ case "community:channel.create":+ scopes.push({ id: event.channel.id, serverId: event.serverId })+ break+ case "community:message.create":+ case "community:message.edited":+ scopes.push({ id: event.channelId, serverId: event.serverId,+ parentChannelId: event.parentChannelId })+ break+ case "community:channel.update":+ scopes.push({ id: event.channelId, serverId: event.serverId })+ break+ case "community:message.updated":+ case "community:reaction.add":+ case "community:reaction.remove":+ case "community:pin.add":+ case "community:pin.remove":+ case "community:typing.start":+ case "community:typing.stop":+ scopes.push({ id: event.channelId })+ break+ default:+ return false+ }+ }+ if (scopes.length === 0) return true+ const rows = await queries.communityChannel.listReadableChannelsForUser(+ db, targetUserId, scopes.map((scope) => scope.id),+ )+ const readable = new Map(rows.map((row) => [row.id, row]))+ return scopes.every((scope) => {+ const row = readable.get(scope.id)+ return row !== undefined+ && (scope.serverId === undefined || row.serverId === scope.serverId)+ && (scope.parentChannelId === undefined || row.parentChannelId === scope.parentChannelId)+ })+}diff --git a/src/ws-do/src/community-delivery-receipt.test.ts b/src/ws-do/src/community-delivery-receipt.test.tsindex 293c1be41..9958a4706 100644--- a/src/ws-do/src/community-delivery-receipt.test.ts+++ b/src/ws-do/src/community-delivery-receipt.test.ts@@ -3,6 +3,7 @@ import { deriveCommunityDeliveryOperationId } from "@alook/shared"import {createCommunityDeliveryReceipt,isExactCommunityDeliveryReceipt,+ isExactCommunityDeliveryCancellation,} from "./community-delivery-receipt"describe("community delivery receipt conservation", () => {@@ -101,3 +102,19 @@ describe("community delivery receipt conservation", () => {})).toBe(false)})})++describe("terminal community cancellation", () => {+ it("binds every field to the original target bundle and remains separate from sent receipts", async () => {+ const expected = { targetUserId: "user-1", operationId: await deriveCommunityDeliveryOperationId("message-1"), operationDigest: "b".repeat(64), eventCount: 3 }+ const cancellation = { status: "cancelled", reason: "access-revoked", ...expected }+ expect(isExactCommunityDeliveryCancellation(cancellation, expected)).toBe(true)+ expect(isExactCommunityDeliveryReceipt(cancellation, expected)).toBe(false)+ for (const invalid of [null, [], 1, {}, { ...cancellation, targetUserId: "other" },+ { ...cancellation, operationId: await deriveCommunityDeliveryOperationId("other") },+ { ...cancellation, operationDigest: "c".repeat(64) }, { ...cancellation, eventCount: 2 },+ { ...cancellation, eventCount: 0 }, { ...cancellation, reason: "temporary" },+ { ...cancellation, status: "complete" }, { ...cancellation, validated: true }]) {+ expect(isExactCommunityDeliveryCancellation(invalid, expected)).toBe(false)+ }+ })+})diff --git a/src/ws-do/src/community-delivery-receipt.ts b/src/ws-do/src/community-delivery-receipt.tsindex 9bef1dcd1..90dfdc5f2 100644--- a/src/ws-do/src/community-delivery-receipt.ts+++ b/src/ws-do/src/community-delivery-receipt.ts@@ -1,6 +1,7 @@import {isCommunityDeliveryDigest,isCommunityDeliveryOperationId,+ isValidCommunityUserTarget,} from "@alook/shared"type CommunityDeliveryOutcome =@@ -205,3 +206,31 @@ export function isExactCommunityDeliveryReceipt(&& value.failed === 0&& value.ambiguousClosed === 0}++export type CommunityDeliveryCancellation = {+ status: "cancelled"+ reason: "access-revoked"+ targetUserId: string+ operationId: string+ operationDigest: string+ eventCount: number+}++export function isExactCommunityDeliveryCancellation(+ value: unknown,+ expected: { targetUserId: string; operationId: string; operationDigest: string; eventCount: number },+): value is CommunityDeliveryCancellation {+ return isRecord(value)+ && hasExactKeys(value, ["status", "reason", "targetUserId", "operationId", "operationDigest", "eventCount"])+ && value.status === "cancelled"+ && value.reason === "access-revoked"+ && isValidCommunityUserTarget(value.targetUserId)+ && value.targetUserId === expected.targetUserId+ && isCommunityDeliveryOperationId(value.operationId)+ && value.operationId === expected.operationId+ && isCommunityDeliveryDigest(value.operationDigest)+ && value.operationDigest === expected.operationDigest+ && isNonNegativeInteger(value.eventCount)+ && (value.eventCount as number) > 0+ && value.eventCount === expected.eventCount+}diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.tsindex b3cdc7065..686f1013c 100644--- a/src/ws-do/src/routes/message-delivery.test.ts+++ b/src/ws-do/src/routes/message-delivery.test.ts@@ -94,6 +94,34 @@ describe("message delivery route", () => {vi.resetModules()})+ it("settles mixed delivered and revoked targets while retaining temporary failures for retry", async () => {+ const inputs = new Map<string, InternalBundleBody[]>()+ let failTransient = true+ doMock.stubFetch.mockImplementation(async (request: Request) => {+ const target = decodeURIComponent(request.headers.get(INTERNAL_USER_TARGET_HEADER)!)+ const body = await request.clone().json() as InternalBundleBody+ inputs.set(target, [...(inputs.get(target) ?? []), body])+ if (target === "revoked") return Response.json({+ status: "cancelled", reason: "access-revoked", targetUserId: target,+ operationId: body.operationId, operationDigest: body.operationDigest, eventCount: body.events.length,+ })+ if (target === "transient" && failTransient) return Response.json({ error: "D1 unavailable" }, { status: 503 })+ return successfulReceipt(request)+ })+ const mixed = { messageId: batch.messageId, messageEvent, contentUserIds: ["success", "revoked", "transient"], unreadPlainUserIds: ["success", "revoked", "transient"], unreadMentionUserIds: [], mentionUserIds: [] }+ const first = await handler.fetch(await deliveryRequest(mixed), env as never)+ expect(first.status).toBe(207)+ expect(await first.json()).toEqual({ failedUserIds: ["transient"] })+ failTransient = false+ const retry = { ...mixed, contentUserIds: ["transient"], unreadPlainUserIds: ["transient"] }+ const second = await handler.fetch(await deliveryRequest(retry), env as never)+ expect(await second.json()).toEqual({ failedUserIds: [] })+ expect(inputs.get("success")).toHaveLength(1)+ expect(inputs.get("revoked")).toHaveLength(1)+ expect(inputs.get("transient")).toHaveLength(2)+ expect(inputs.get("transient")![0]).toEqual(inputs.get("transient")![1])+ })+it("inverts buckets into one ordered bundle per user", async () => {doMock.stubFetch.mockImplementation(successfulReceipt)diff --git a/src/ws-do/src/routes/message-delivery.ts b/src/ws-do/src/routes/message-delivery.tsindex 4e08f535a..dc44ff2e1 100644--- a/src/ws-do/src/routes/message-delivery.ts+++ b/src/ws-do/src/routes/message-delivery.ts@@ -10,7 +10,7 @@ import {type CommunityWsEvent,} from "@alook/shared"import { readBoundedJsonRequest } from "../community-browser-event-ingress"-import { isExactCommunityDeliveryReceipt } from "../community-delivery-receipt"+import { isExactCommunityDeliveryReceipt, isExactCommunityDeliveryCancellation } from "../community-delivery-receipt"import { createInternalCommunityUserBundleRequest } from "../internal-user-broadcast"import type { RouterContext } from "../router-context"import { settleInBatches } from "../settle-in-batches"@@ -18,7 +18,7 @@ import { settleInBatches } from "../settle-in-batches"const targetBatchSize = 40type TargetResult =- | { ok: true }+ | { ok: true; outcome: "delivered" | "cancelled" }| { ok: false; kind: "throw" | "non-ok" | "invalid-json" | "invalid-receipt" }function addEvent(@@ -56,6 +56,9 @@ async function deliverTarget(} catch {return { ok: false, kind: "invalid-json" }}+ if (response.status === 200 && isExactCommunityDeliveryCancellation(receipt, {+ targetUserId: userId, operationId, operationDigest: prepared.prepared.digest, eventCount: events.length,+ })) return { ok: true, outcome: "cancelled" }if (!isExactCommunityDeliveryReceipt(receipt, {operationId,operationDigest: prepared.prepared.digest,@@ -63,7 +66,7 @@ async function deliverTarget(})) {return { ok: false, kind: "invalid-receipt" }}- return { ok: true }+ return { ok: true, outcome: "delivered" }} catch {return { ok: false, kind: "throw" }}@@ -171,6 +174,8 @@ export async function handleMessageDelivery(targetBatchSize,)const failedUserIds: string[] = []+ let deliveredCount = 0+ let cancelledCount = 0const failureCounts = { throw: 0, "non-ok": 0, "invalid-json": 0, "invalid-receipt": 0 }for (const [index, result] of results.entries()) {const target = entries[index]!@@ -180,6 +185,10 @@ export async function handleMessageDelivery(} else if (!result.value.ok) {failedUserIds.push(target[0])failureCounts[result.value.kind] += 1+ } else if (result.value.outcome === "cancelled") {+ cancelledCount += 1+ } else {+ deliveredCount += 1}}log.info("message_delivery_complete", {@@ -187,6 +196,8 @@ export async function handleMessageDelivery(messageId: batch.messageId,operationId,targetCount: entries.length,+ deliveredCount,+ cancelledCount,failedCount: failedUserIds.length,failureCounts,durationMs: Date.now() - startedAt,diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.tsindex dbabf7de7..2ff73d0dd 100644--- a/src/ws-do/src/ws-durable/presence-typing.test.ts+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts@@ -782,11 +782,11 @@ describe("WebSocketDurableObject", () => {expect(mockStubFetch).toHaveBeenCalledTimes(1)})- it("thread: typing fans out to PARTICIPANTS, not the channel audience", async () => {+ it("thread: typing reaches readable nonparticipants", async () => {const { durable, env } = createDO()mockGetChannelForMember.mockResolvedValueOnce({ id: "t-1", serverId: "server-1" })mockGetChannelType.mockResolvedValueOnce("thread")- mockListThreadParticipantUserIds.mockResolvedValueOnce(["sender-1", "part-1"])+ mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "reader-1"])const ws = createMockWebSocket()ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true })@@ -797,10 +797,9 @@ describe("WebSocketDurableObject", () => {)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(mockListThreadParticipantUserIds).not.toHaveBeenCalled()+ expect(mockResolveScopeMemberUserIds).toHaveBeenCalled()+ expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:reader-1")expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")expect(mockStubFetch).toHaveBeenCalledTimes(1)})diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.tsindex f49f3f516..2e6f1b36b 100644--- a/src/ws-do/src/ws-durable/presence-typing.ts+++ b/src/ws-do/src/ws-durable/presence-typing.ts@@ -144,7 +144,7 @@ export async function fanOutTyping(return}recipientUserIds = await withD1Retry(- () => queries.communityMembersResolver.resolveChannelRecipientUserIds(db, channelId),+ () => queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db, channelId),{ route: "ws-do:agent-typing-recipients" },)recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)@@ -179,7 +179,7 @@ export async function fanOutTypingStop(return}let recipientUserIds = await withD1Retry(- () => queries.communityMembersResolver.resolveChannelRecipientUserIds(db, channelId),+ () => queries.communityMembersResolver.resolveChannelContentRecipientUserIds(db, channelId),{ route: "ws-do:agent-typing-stop-recipients" },)recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex 9b2ecc784..ab572d13f 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -97,6 +97,8 @@ export const mockTimeoutPendingDiagnosticReportsForMachine = vi.fn().mockResolveexport const mockGetNextPendingDiagnosticDeadlineForMachine = vi.fn().mockResolvedValue(null)export const mockGetCoMemberUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])export const mockGetFriendUserIds = vi.fn<(db: unknown, userId: string) => Promise<string[]>>().mockResolvedValue([])+export const mockListReadableChannelsForUser = vi.fn()+const mockGetReadableMessageChannelId = vi.fn()export const mockGetChannelForMember = vi.fn()export const mockListChannelMemberUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])export const mockIsChannelPrivate = vi.fn<(db: unknown, channelId: string) => Promise<boolean>>().mockResolvedValue(false)@@ -105,13 +107,12 @@ export const mockResolveScopeMemberUserIds = vi.fn<(db: unknown, opts: { scope:// Default: non-thread channel → typing uses the shared resolver path.export const mockGetChannelType = vi.fn<(db: unknown, channelId: string) => Promise<string | null>>().mockResolvedValue("text")export const mockListThreadParticipantUserIds = vi.fn<(db: unknown, channelId: string) => Promise<string[]>>().mockResolvedValue([])-async function resolveChannelRecipientUserIdsMock(db: unknown, channelId: string): Promise<string[]> {+async function resolveChannelContentRecipientUserIdsMock(db: unknown, channelId: string): Promise<string[]> {const type = await mockGetChannelType(db, channelId)- if (type === "thread") return mockListThreadParticipantUserIds(db, channelId)if (type === "dm") return mockListChannelMemberUserIds(db, channelId)return mockResolveScopeMemberUserIds(db, { scope: "channel", scopeId: channelId })}-export const mockResolveChannelRecipientUserIds = vi.fn(resolveChannelRecipientUserIdsMock)+export const mockResolveChannelRecipientUserIds = vi.fn(resolveChannelContentRecipientUserIdsMock)export const mockWithD1Retry = vi.fn(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())export const mockGetDM = vi.fn()export const mockListMembers = vi.fn()@@ -442,6 +443,8 @@ vi.mock("@alook/shared", async () => {getFriendUserIds: (...a: [unknown, string]) => mockGetFriendUserIds(...a),},communityChannel: {+ listReadableChannelsForUser: (...a: unknown[]) => mockListReadableChannelsForUser(...a),+ getReadableMessageChannelId: (...a: unknown[]) => mockGetReadableMessageChannelId(...a),getChannelForMember: (...a: any[]) => mockGetChannelForMember(...a),getChannelType: (...a: any[]) => mockGetChannelType(...a),listChannelMemberUserIds: (...a: any[]) => mockListChannelMemberUserIds(...a),@@ -450,7 +453,7 @@ vi.mock("@alook/shared", async () => {},communityMembersResolver: {resolveScopeMemberUserIds: (...a: any[]) => mockResolveScopeMemberUserIds(...a),- resolveChannelRecipientUserIds: (...a: [unknown, string]) =>+ resolveChannelContentRecipientUserIds: (...a: [unknown, string]) =>mockResolveChannelRecipientUserIds(...a),},communityThread: {@@ -514,6 +517,8 @@ export const flushAsyncWork = async () => {}export function resetHarness() {vi.clearAllMocks()+ mockListReadableChannelsForUser.mockImplementation(async (_db, _userId, ids: string[]) => ids.map((id) => ({ id, serverId: null, parentChannelId: null })))+ mockGetReadableMessageChannelId.mockResolvedValue("ch-1")// `clearAllMocks` doesn't undo a `mockResolvedValue` set by a prior test —// re-pin these two to their empty default so presence-audience tests// don't leak state into unrelated auth-flow tests.@@ -530,7 +535,7 @@ export function resetHarness() {mockListThreadParticipantUserIds.mockResolvedValue([])mockListChannelMemberUserIds.mockResolvedValue([])mockResolveScopeMemberUserIds.mockResolvedValue([])- mockResolveChannelRecipientUserIds.mockImplementation(resolveChannelRecipientUserIdsMock)+ mockResolveChannelRecipientUserIds.mockImplementation(resolveChannelContentRecipientUserIdsMock)mockWithD1Retry.mockImplementation(async <T>(fn: () => Promise<T>, _opts?: unknown): Promise<T> => fn())mockGetBotBinding.mockResolvedValue(null)mockGetBotBindingWithOwner.mockResolvedValue(null)diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.tsindex 8aaf3b5a9..37a90dd02 100644--- a/src/ws-do/src/ws-durable/user-auth.test.ts+++ b/src/ws-do/src/ws-durable/user-auth.test.ts@@ -20,6 +20,7 @@ import {mockGetBotBinding,mockGetBotBindingWithOwner,mockGetChannelForMember,+ mockListReadableChannelsForUser,mockGetChannelType,mockGetCoMemberUserIds,mockGetDM,@@ -114,6 +115,47 @@ describe("WebSocketDurableObject", () => {})})+ it("gates single content, preserves removal controls, and reports transient D1 failure", async () => {+ const { durable, ctx } = createDO()+ const socket = createMockWebSocket()+ socket.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([socket])+ const send = (event: unknown) => durable.fetch(new Request("http://internal/community-broadcast", {+ method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },+ body: JSON.stringify(event),+ }))+ const typing = { type: "community:typing.start", channelId: "private", userId: "author" }+ mockListReadableChannelsForUser.mockResolvedValueOnce([])+ await expect((await send(typing)).json()).resolves.toEqual({ sent: 0 })+ expect(socket.send).not.toHaveBeenCalled()+ mockListReadableChannelsForUser.mockRejectedValueOnce(new Error("D1 temporary"))+ expect((await send(typing)).status).toBe(503)+ expect(socket.send).not.toHaveBeenCalled()+ const control = { type: "community:channel.member_remove", channelId: "private", serverId: "server", userId: "user-42" }+ expect((await send(control)).status).toBe(200)+ expect(socket.send).toHaveBeenCalledOnce()+ })++ it.each(["none", "unauthenticated", "other-user", "daemon"])("skips single-content D1 checks for %s sockets after strict validation", async (kind) => {+ const { durable, ctx } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: kind === "daemon" ? "daemon" : "user", userId: kind === "other-user" ? "other" : "user-42", authenticated: kind !== "unauthenticated" })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(kind === "none" ? [] : [ws])+ const send = (event: unknown) => durable.fetch(new Request("http://internal/community-broadcast", {+ method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },+ body: JSON.stringify(event),+ }))+ const event = { type: "community:typing.start", channelId: "private", userId: "author" }+ mockListReadableChannelsForUser.mockRejectedValue(new Error("offline D1 must not run"))+ expect((await send({ ...event, extra: true })).status).toBe(400)+ await expect((await send(event)).json()).resolves.toEqual({ sent: 0 })+ expect(mockCreateDb).not.toHaveBeenCalled()+ expect(mockListReadableChannelsForUser).not.toHaveBeenCalled()+ expect(ws.send).not.toHaveBeenCalled()+ })+describe("fetch — strict community ordered bundle", () => {const events = [{@@ -162,6 +204,54 @@ describe("WebSocketDurableObject", () => {})}+ it("cancels revoked content without changing progress, and retries transient failures", async () => {+ const { durable, ctx } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])+ const request = await requestFor()+ const original = ws.deserializeAttachment()+ const body = await request.clone().json() as { operationId: string; operationDigest: string; events: unknown[] }+ mockListReadableChannelsForUser.mockResolvedValueOnce([])+ const denied = await durable.fetch(request.clone())+ expect(await denied.json()).toEqual({ status: "cancelled", reason: "access-revoked", targetUserId: "user-42", operationId: body.operationId, operationDigest: body.operationDigest, eventCount: body.events.length })+ expect(ws.send).not.toHaveBeenCalled()+ expect(ws.deserializeAttachment()).toEqual(original)+ mockListReadableChannelsForUser.mockRejectedValueOnce(new Error("temporary"))+ expect((await durable.fetch(request.clone())).status).toBe(503)+ expect(ws.send).not.toHaveBeenCalled()+ expect((await durable.fetch(request.clone())).status).toBe(200)+ expect(ws.send).toHaveBeenCalledTimes(1)+ mockListReadableChannelsForUser.mockResolvedValueOnce([])+ expect((await (await durable.fetch(request.clone())).json()).status).toBe("cancelled")+ expect((await durable.fetch(request.clone())).status).toBe(200)+ expect(ws.send).toHaveBeenCalledTimes(1)+ })++ it("reads current sockets and progress only after concurrent authorization awaits", async () => {+ const { durable, ctx } = createDO()+ const old = createMockWebSocket()+ old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>+ sockets.mockReturnValue([old])+ const releases: Array<(rows: Array<{ id: string }>) => void> = []+ mockListReadableChannelsForUser.mockImplementation(() => new Promise((resolve) => releases.push(resolve)))+ const request = await requestFor()+ const first = durable.fetch(request.clone())+ await vi.waitFor(() => expect(releases).toHaveLength(1))+ const second = durable.fetch(request.clone())+ await vi.waitFor(() => expect(releases).toHaveLength(2))+ const current = createMockWebSocket()+ current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ sockets.mockReturnValue([current])+ releases[1]!([{ id: "ch-1" }])+ await second+ releases[0]!([{ id: "ch-1" }])+ await first+ expect(old.send).not.toHaveBeenCalled()+ expect(current.send).toHaveBeenCalledTimes(1)+ })+it("rejects an invalid internal target before decoding the bundle", async () => {const { durable } = createDO()const response = await durable.fetch(new Request(@@ -430,15 +520,25 @@ describe("WebSocketDurableObject", () => {expect(second.send).not.toHaveBeenCalled()})- it("returns an exact complete zero-socket receipt", async () => {+ it.each(["none", "unauthenticated", "other-user", "daemon"])("returns an exact zero-matched receipt without D1 for %s sockets", async (kind) => {const { durable, ctx } = createDO()- ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([])-- const response = await durable.fetch(await requestFor())+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: kind === "daemon" ? "daemon" : "user", userId: kind === "other-user" ? "other" : "user-42", authenticated: kind !== "unauthenticated" })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(kind === "none" ? [] : [ws])+ mockListReadableChannelsForUser.mockRejectedValue(new Error("offline D1 must not run"))++ const request = await requestFor()+ const body = await request.clone().json() as { operationId: string; operationDigest: string; events: unknown[] }+ const invalid = await requestFor(events, { operationDigest: "0".repeat(64) })+ expect((await durable.fetch(invalid)).status).toBe(400)+ const response = await durable.fetch(request)expect(response.status).toBe(200)await expect(response.json()).resolves.toMatchObject({status: "complete",validated: true,+ operationId: body.operationId,+ operationDigest: body.operationDigest,+ eventCount: body.events.length,matched: 0,attempted: 0,enqueued: 0,@@ -450,6 +550,44 @@ describe("WebSocketDurableObject", () => {ambiguousClosed: 0,results: [],})+ expect(mockCreateDb).not.toHaveBeenCalled()+ expect(mockListReadableChannelsForUser).not.toHaveBeenCalled()+ expect(ws.send).not.toHaveBeenCalled()+ })++ it("checks current access when a target connects after zero-match completion", async () => {+ const { durable, ctx } = createDO()+ const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>+ sockets.mockReturnValue([])+ const request = await requestFor()+ await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ matched: 0, enqueued: 0 })+ expect(mockCreateDb).not.toHaveBeenCalled()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ sockets.mockReturnValue([ws])+ mockListReadableChannelsForUser.mockResolvedValueOnce([])+ await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ status: "cancelled", targetUserId: "user-42" })+ expect(ws.send).not.toHaveBeenCalled()+ await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ matched: 1, enqueued: 1 })+ expect(mockListReadableChannelsForUser).toHaveBeenCalledTimes(2)+ expect(ws.send).toHaveBeenCalledOnce()+ })++ it("returns zero matches when the last target closes during its access query", async () => {+ const { durable, ctx } = createDO()+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>+ sockets.mockReturnValue([ws])+ let release!: (rows: Array<{ id: string }>) => void+ mockListReadableChannelsForUser.mockImplementation(() => new Promise((resolve) => { release = resolve }))+ const pending = durable.fetch(await requestFor())+ await vi.waitFor(() => expect(mockListReadableChannelsForUser).toHaveBeenCalledOnce())+ sockets.mockReturnValue([])+ release([{ id: "ch-1" }])+ await expect((await pending).json()).resolves.toMatchObject({ matched: 0, enqueued: 0 })+ expect(ws.send).not.toHaveBeenCalled()+ expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "user-42", authenticated: true })})it("closes a socket and reports ambiguity when attachment persistence fails after send", async () => {diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.tsindex 354b4fc05..cdf0f553b 100644--- a/src/ws-do/src/ws-durable/user-auth.ts+++ b/src/ws-do/src/ws-durable/user-auth.ts@@ -10,6 +10,7 @@ import {import {createCommunityDeliveryReceipt,type CommunityDeliverySocketResult,+ type CommunityDeliveryCancellation,} from "../community-delivery-receipt"import type {CommunityMachineConnectionState,@@ -38,6 +39,7 @@ import {withCommunityDeliveryProgress,type CommunityDeliveryProgress,} from "./community-delivery-state"+import { canDeliverCommunityContent } from "../community-content-access"import { handleUserAgentInterrupt } from "./agent-interrupt"export async function handleUserFetch(@@ -57,6 +59,24 @@ export async function handleUserFetch(logCommunityBrowserEventRejected(context.log, "target-do-bundle", bundle)return deliveryErrorResponse(400, { operationId: null, code: "invalid_request" })}+ if (!hasAuthenticatedTargetSocket(context, targetUserId)) {+ return deliverCommunityBundle(context, bundle, targetUserId)+ }+ try {+ if (!await canDeliverCommunityContent(createDb(context.env.DB), targetUserId, bundle.prepared.events)) {+ return jsonResponse({+ status: "cancelled",+ reason: "access-revoked",+ targetUserId,+ operationId: bundle.operationId,+ operationDigest: bundle.operationDigest,+ eventCount: bundle.eventCount,+ } satisfies CommunityDeliveryCancellation, 200)+ }+ } catch (error) {+ context.log.warn("community_delivery_access_failed", { targetUserId, error: String(error) })+ return jsonResponse({ operationId: bundle.operationId, error: "access_check_failed" }, 503)+ }return deliverCommunityBundle(context, bundle, targetUserId)}@@ -72,6 +92,18 @@ export async function handleUserFetch(logCommunityBrowserEventRejected(context.log, "target-do", event)return invalidCommunityBrowserEventResponse(event)}+ if (!hasAuthenticatedTargetSocket(context, targetUserId)) {+ return jsonResponse({ sent: broadcast(context, event.body, targetUserId) })+ }+ try {+ if (!await canDeliverCommunityContent(createDb(context.env.DB), targetUserId, [event.event])) {+ context.log.info("community_content_access_denied", { targetUserId, type: event.event.type })+ return jsonResponse({ sent: 0 }, 200)+ }+ } catch (error) {+ context.log.warn("community_content_access_failed", { targetUserId, error: String(error) })+ return jsonResponse({ error: "access_check_failed" }, 503)+ }const sent = broadcast(context, event.body, targetUserId)return new Response(JSON.stringify({ sent }), {headers: { "Content-Type": "application/json" },@@ -336,6 +368,13 @@ export async function handleWebSocketError(try { ws.close(1011, "Internal error") } catch { }}+function hasAuthenticatedTargetSocket(context: WsDurableContext, targetUserId: string): boolean {+ return context.ctx.getWebSockets().some((ws) => {+ const state = ws.deserializeAttachment() as ConnectionState+ return state?.type === "user" && state.authenticated && state.userId === targetUserId+ })+}+function broadcast(context: WsDurableContext,message: string,