Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): unify read, cache and event boundaries
Gener9b4e83a1cbe2
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex 8cc416c5d..fe94c1657 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -703,12 +703,12 @@"fixedParams": 10},{- "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentions:inArray:1",+ "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentionScopes:inArray:1","strategy": "exact-chunk","fixedParams": 10},{- "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentionScopes:inArray:1",+ "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentions:inArray:1","strategy": "exact-chunk","fixedParams": 10},@@ -731,13 +731,23 @@"strategy": "bounded-public-input","maxExport": "MAX_ATTACHMENTS_PER_MESSAGE"},+ {+ "key": "src/shared/src/db/queries/community/message.ts:getFirstMessageResourcesByChannelIds:inArray:1",+ "strategy": "exact-chunk",+ "fixedParams": 10+ },{"key": "src/shared/src/db/queries/community/message.ts:getMessagesByIds:inArray:1","strategy": "exact-chunk","fixedParams": 10},{- "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInScope:inArray:1",+ "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInChannels:inArray:1",+ "strategy": "exact-chunk",+ "fixedParams": 10+ },+ {+ "key": "src/shared/src/db/queries/community/message.ts:getMessagesByIdsInChannels:inArray:2","strategy": "exact-chunk","fixedParams": 10},@@ -776,11 +786,6 @@"strategy": "exact-chunk","fixedParams": 10},- {- "key": "src/shared/src/db/queries/community/message.ts:runChunk:inArray:2",- "strategy": "exact-chunk",- "fixedParams": 10- },{"key": "src/shared/src/db/queries/community/notification-eligibility.ts:runChunk:inArray:1","strategy": "exact-chunk",diff --git a/src/shared/src/community-contract.ts b/src/shared/src/community-contract.tsnew file mode 100644index 000000000..d86f920dd--- /dev/null+++ b/src/shared/src/community-contract.ts@@ -0,0 +1,8 @@+export const COMMUNITY_CONTRACT_HEADER = "X-Alook-Community-Contract"+export const COMMUNITY_CONTRACT_VERSION = 2 as const++export type CommunityContract = 1 | typeof COMMUNITY_CONTRACT_VERSION++export function requestsCommunityContract(headers: Pick<Headers, "get">): boolean {+ return headers.get(COMMUNITY_CONTRACT_HEADER) === String(COMMUNITY_CONTRACT_VERSION)+}diff --git a/src/shared/src/community-friend-approval.ts b/src/shared/src/community-friend-approval.tsnew file mode 100644index 000000000..0162b0929--- /dev/null+++ b/src/shared/src/community-friend-approval.ts@@ -0,0 +1,21 @@+import { z } from "zod"++const profile = z.strictObject({+ id: z.string(),+ name: z.string(),+ discriminator: z.string(),+ image: z.string().nullable(),+ avatarVersion: z.number().int().nonnegative(),+})++export const FriendApprovalPayloadSchema = z.strictObject({+ friendshipId: z.string(),+ status: z.enum(["pending", "approved", "denied", "superseded", "cancelled"]),+ waitingOn: z.enum(["you", "other-owner", "addressee"]).nullable(),+ otherProfile: profile,+ botProfile: profile,+ waitingOnProfile: profile.nullable().optional(),+})++export type FriendApprovalPayload = z.infer<typeof FriendApprovalPayloadSchema>+export type FriendApprovalProfile = FriendApprovalPayload["otherProfile"]diff --git a/src/shared/src/community-message-delivery.ts b/src/shared/src/community-message-delivery.tsindex 8c9ba1fc4..696433b25 100644--- a/src/shared/src/community-message-delivery.ts+++ b/src/shared/src/community-message-delivery.ts@@ -27,6 +27,8 @@ export type MessageDeliveryBatch = {unreadMentionUserIds: string[];mentionUserIds: string[];memberAdded?: MessageDeliveryMemberAdded;+ joinedParticipantUserIds?: string[];+ rosterRefreshUserId?: string;parentProjection?: CommunityChildChannelUpdate;parentProjectionUserIds?: string[];};@@ -49,6 +51,8 @@ const batchShape = z.strictObject({unreadMentionUserIds: targetList,mentionUserIds: targetList,memberAdded: memberAddedSchema.optional(),+ joinedParticipantUserIds: targetList.optional(),+ rosterRefreshUserId: target.optional(),parentProjection: z.unknown().optional(),parentProjectionUserIds: targetList.optional(),});@@ -124,6 +128,9 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP}}+ if ((data.joinedParticipantUserIds === undefined) !== (data.rosterRefreshUserId === undefined)+ || (data.joinedParticipantUserIds && (hasDuplicates(data.joinedParticipantUserIds)+ || !isSubset(data.joinedParticipantUserIds, content) || !message.data.serverId))) return { ok: false, reason: "invalid-payload" };const allTargets = new Set(lists.flat());if (allTargets.size > MESSAGE_DELIVERY_MAX_USERS) {return { ok: false, reason: "too-many-targets" };@@ -143,6 +150,7 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchPunreadMentionUserIds: data.unreadMentionUserIds,mentionUserIds: data.mentionUserIds,...(data.memberAdded ? { memberAdded: data.memberAdded } : {}),+ ...(data.joinedParticipantUserIds ? { joinedParticipantUserIds: data.joinedParticipantUserIds, rosterRefreshUserId: data.rosterRefreshUserId } : {}),...(parentProjection ? { parentProjection } : {}),...(data.parentProjectionUserIds? { parentProjectionUserIds: data.parentProjectionUserIds }diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.tsnew file mode 100644index 000000000..fccfbddd9--- /dev/null+++ b/src/shared/src/community-resources.ts@@ -0,0 +1,199 @@+import { z } from "zod"+import { COMMUNITY_CONTRACT_VERSION } from "./community-contract"+import { FriendApprovalPayloadSchema } from "./community-friend-approval"++const id = z.string().min(1)+const nullableId = id.nullable()+const legacyArchivedSchema = z.union([z.boolean(), z.literal(0), z.literal(1)]).transform((value) => value === true || value === 1)++export const CommunityChannelResourceSchema = z.strictObject({+ id,+ type: z.enum(["text", "forum", "thread", "dm"]),+ serverId: nullableId,+ categoryId: nullableId,+ name: z.string().nullable(),+ topic: z.string(),+ parentChannelId: nullableId,+ parentMessageId: nullableId,+ creatorId: nullableId,+ position: z.number(),+ archived: z.boolean(),+ createdAt: z.string(),+ lastMessageAt: z.string().nullable(),+ messageCount: z.number().int().nonnegative(),+})++export const CommunityChannelIdentitySchema = CommunityChannelResourceSchema.pick({+ id: true, type: true, serverId: true, name: true, parentChannelId: true,+ parentMessageId: true, creatorId: true, archived: true, lastMessageAt: true, createdAt: true,+}).partial({ createdAt: true }).strip()++const legacyChannelIdentitySchema = CommunityChannelIdentitySchema.extend({+ archived: legacyArchivedSchema,+ parentChannelId: nullableId.default(null),+ parentMessageId: nullableId.default(null),+ creatorId: nullableId.default(null),+ lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null),+})++export function normalizeCommunityChannelIdentity(value: unknown) {+ return legacyChannelIdentitySchema.parse(value)+}++export const CommunityAccessDecisionSchema = z.strictObject({+ channelId: id,+ canRead: z.boolean(),+ canSend: z.boolean(),+ canCreateDiscussion: z.boolean(),+})++export const CommunityMessageAttachmentSchema = z.strictObject({+ kind: z.enum(["image", "file"]),+ name: z.string(),+ url: z.string(),+ thumbnailUrl: z.string().optional(),+ contentType: z.string().optional(),+ size: z.string().optional(),+ sizeBytes: z.number().nonnegative().optional(),+ width: z.number().nonnegative().optional(),+ height: z.number().nonnegative().optional(),+})++export const CommunityMessageResourceSchema = z.strictObject({+ id,+ channelId: id,+ seq: z.number().int().nonnegative(),+ authorId: id,+ createdAt: z.string(),+ type: z.enum(["chat", "system"]),+ content: z.string(),+ replyToId: nullableId,+ clientNonce: z.string().nullable(),+ attachments: z.array(CommunityMessageAttachmentSchema),+ systemKind: z.literal("thread").optional(),+ authorName: z.string().optional(),+ authorAvatar: z.string().optional(),+ authorAvatarVersion: z.number().int().nonnegative().optional(),+ mentionType: z.literal("everyone").nullable().optional(),+ replyTo: z.strictObject({+ id,+ authorId: id.optional(),+ authorName: z.string(),+ text: z.string(),+ deleted: z.boolean().optional(),+ }).optional(),+ embeds: z.array(z.unknown()).optional(),+ reactions: z.array(z.strictObject({+ emoji: z.string(),+ count: z.number().int().nonnegative(),+ me: z.boolean(),+ userIds: z.array(id),+ })).optional(),+ thread: z.strictObject({+ id,+ name: z.string(),+ messageCount: z.number().int().nonnegative(),+ lastReplyAt: z.string().optional(),+ tags: z.array(z.string()).optional(),+ preview: z.string().optional(),+ participants: z.array(z.strictObject({ id, name: z.string(), avatar: z.string(), avatarVersion: z.number().int().nonnegative() })).optional(),+ participantCount: z.number().int().nonnegative().optional(),+ }).optional(),+ approval: FriendApprovalPayloadSchema.optional(),+})++export const CommunityReadStateResourceSchema = z.strictObject({+ channelId: id,+ lastReadMessageId: nullableId,+ lastReadAt: z.string().nullable(),+ lastReadSeq: z.number().int().nonnegative(),+})++export const CommunityMemberRelationSchema = z.strictObject({+ channelId: id,+ userId: id,+ relation: z.enum(["access", "notify"]),+ source: z.string(),+ isCreator: z.boolean(),+ role: z.string().nullable(),+ memberId: nullableId,+})++export const CommunityResourceProfileSchema = z.strictObject({+ id,+ name: z.string(),+ discriminator: z.string().nullable(),+ avatar: z.string().nullable(),+ avatarVersion: z.number().int().nonnegative(),+ statusEmoji: z.string().nullable(),+ statusText: z.string(),+})++export const CommunityPageSchema = z.strictObject({+ olderCursor: z.string().nullable(),+ newerCursor: z.string().nullable(),+ hasMoreOlder: z.boolean(),+ hasMoreNewer: z.boolean(),+ latestSeq: z.number().int().nonnegative(),+})++const envelope = { contractVersion: z.literal(COMMUNITY_CONTRACT_VERSION), channelId: id }+export const CommunityChannelReadSchema = z.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema })+export const CommunityMessagesReadSchema = z.strictObject({ ...envelope, messages: z.array(CommunityMessageResourceSchema), page: CommunityPageSchema,+ surfaceReceipt: z.strictObject({ channelId: id, surfaceKind: z.enum(["channel", "forum", "thread", "dm"]) }) })+export const CommunityReadStateReadSchema = z.strictObject({ ...envelope, readState: CommunityReadStateResourceSchema })+export const CommunityMembersReadSchema = z.strictObject({ ...envelope, relation: z.enum(["access", "notify"]), members: z.array(CommunityMemberRelationSchema), profiles: z.array(CommunityResourceProfileSchema) })+export const CommunityThreadsReadSchema = z.strictObject({ ...envelope, channel: CommunityChannelResourceSchema,+ threads: z.array(CommunityChannelResourceSchema),+ included: z.strictObject({ messages: z.array(CommunityMessageResourceSchema), members: z.array(CommunityMemberRelationSchema), profiles: z.array(CommunityResourceProfileSchema),+ tags: z.array(z.strictObject({ messageId: id, tag: z.string() })),+ participantCounts: z.array(z.strictObject({ channelId: id, count: z.number().int().nonnegative() })) }),+ page: z.strictObject({ nextCursor: z.string().nullable(), hasMore: z.boolean() }) })+export const CommunityReadAdvanceSchema = z.strictObject({ ...envelope, changed: z.boolean(), targetSeq: z.number().int().nonnegative(), revision: z.number().int().nonnegative() })+export const CommunityReadErrorSchema = z.strictObject({ contractVersion: z.literal(COMMUNITY_CONTRACT_VERSION), error: z.strictObject({+ code: z.enum(["invalid_input", "invalid_reply_target", "unauthenticated", "not_found", "not_allowed", "blocked", "idempotency_conflict", "rate_limited", "temporarily_unavailable"]),+ message: z.string(), retryable: z.boolean(),+}) })++export type CommunityChannelResource = z.infer<typeof CommunityChannelResourceSchema>+export type CommunityChannelIdentity = z.infer<typeof CommunityChannelIdentitySchema>+export type CommunityMessageResource = z.infer<typeof CommunityMessageResourceSchema>+export type CommunityMemberRelation = z.infer<typeof CommunityMemberRelationSchema>+export type CommunityReadStateResource = z.infer<typeof CommunityReadStateResourceSchema>+export type CommunityAccessDecision = z.infer<typeof CommunityAccessDecisionSchema>+export type CommunityResourceProfile = z.infer<typeof CommunityResourceProfileSchema>+export type CommunityMessageAttachment = z.infer<typeof CommunityMessageAttachmentSchema>+export type CommunityMessagesRead = z.infer<typeof CommunityMessagesReadSchema>+export type CommunityThreadsRead = z.infer<typeof CommunityThreadsReadSchema>+export type CommunityMembersRead = z.infer<typeof CommunityMembersReadSchema>+export type CommunityMessageSurfaceReceipt = CommunityMessagesRead["surfaceReceipt"]++const legacyChannelResourceSchema = CommunityChannelResourceSchema.strip().extend({+ topic: CommunityChannelResourceSchema.shape.topic.nullish().transform((value) => value ?? ""),+ position: CommunityChannelResourceSchema.shape.position.nullish().transform((value) => value ?? 0),+ messageCount: CommunityChannelResourceSchema.shape.messageCount.nullish().transform((value) => value ?? 0),+ categoryId: nullableId.default(null),+ parentChannelId: nullableId.default(null),+ parentMessageId: nullableId.default(null),+ creatorId: nullableId.default(null),+ lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null),+ archived: legacyArchivedSchema,+})++export function normalizeCommunityChannelResource(value: unknown): CommunityChannelResource {+ return legacyChannelResourceSchema.parse(value)+}++const legacyMessageResourceSchema = CommunityMessageResourceSchema.strip().extend({+ channelId: id.optional(),+ replyToId: nullableId.optional(),+ clientNonce: CommunityMessageResourceSchema.shape.clientNonce.default(null),+ attachments: CommunityMessageResourceSchema.shape.attachments.default([]),+ embeds: CommunityMessageResourceSchema.shape.embeds.nullable().transform((value) => value ?? undefined),+})++export function normalizeCommunityMessageResource(value: unknown, channelId: string): CommunityMessageResource {+ const raw = legacyMessageResourceSchema.parse(value)+ if (raw.channelId !== undefined && raw.channelId !== channelId) throw new Error("Message resource scope mismatch")+ return { ...raw, channelId: id.parse(channelId), replyToId: raw.replyToId ?? raw.replyTo?.id ?? null }+}diff --git a/src/shared/src/community-ws-bundle.ts b/src/shared/src/community-ws-bundle.tsindex 07478e773..72afd2d76 100644--- a/src/shared/src/community-ws-bundle.ts+++ b/src/shared/src/community-ws-bundle.ts@@ -6,8 +6,15 @@ import {type CommunityWsEvent,} from "./community-ws-events"import { MESSAGE_DELIVERY_MAX_EVENTS_PER_USER } from "./community-message-delivery"+import { COMMUNITY_CONTRACT_VERSION, type CommunityContract } from "./community-contract"export const COMMUNITY_BROWSER_EVENT_BATCH_TYPE = "community:events.batch" as const++export function communityBrowserEventBatchType(contract: number = COMMUNITY_CONTRACT_VERSION) {+ if (contract === 1) return COMMUNITY_BROWSER_EVENT_BATCH_TYPE+ if (contract === COMMUNITY_CONTRACT_VERSION) return `${COMMUNITY_BROWSER_EVENT_BATCH_TYPE}.v${COMMUNITY_CONTRACT_VERSION}` as const+ throw new Error("unsupported community event contract")+}export const COMMUNITY_DELIVERY_OPERATION_ID_PREFIX = "message:" as constexport const COMMUNITY_DELIVERY_OPERATION_ID_HEADER = "x-alook-community-operation-id" as constexport const COMMUNITY_DELIVERY_OPERATION_ID_BYTES = 51@@ -24,7 +31,8 @@ export type CommunityDeliveryOperationId = `${typeof COMMUNITY_DELIVERY_OPERATIOexport type CommunityDeliveryDigest = stringexport type CommunityBrowserEventBatch = {- type: typeof COMMUNITY_BROWSER_EVENT_BATCH_TYPE+ type: ReturnType<typeof communityBrowserEventBatchType>+ wireDigest?: CommunityDeliveryDigestoperationId: CommunityDeliveryOperationIdoperationDigest: CommunityDeliveryDigestevents: CommunityWsEvent[]@@ -243,6 +251,7 @@ export function encodePreparedCommunityBrowserEventBatch(input: {operationId: unknownoperationDigest: unknownprepared: PreparedCommunityDeliveryEvents+ sourceDigest?: CommunityDeliveryDigest}): CommunityBrowserEventBatchEncodeResult {if (!isCommunityDeliveryOperationId(input.operationId)) {return { ok: false, reason: "invalid-operation-id" }@@ -257,20 +266,21 @@ export function encodePreparedCommunityBrowserEventBatch(input: {actualDigest: input.prepared.digest,}}- const prefix = JSON.stringify({- type: COMMUNITY_BROWSER_EVENT_BATCH_TYPE,+ if (input.sourceDigest !== undefined && !isCommunityDeliveryDigest(input.sourceDigest)) return { ok: false, reason: "invalid-operation-digest" }+ const envelope = {+ type: communityBrowserEventBatchType(input.sourceDigest === undefined ? 1 : COMMUNITY_CONTRACT_VERSION),operationId: input.operationId,- operationDigest: input.operationDigest,- }).slice(0, -1)+ operationDigest: input.sourceDigest ?? input.operationDigest,+ ...(input.sourceDigest === undefined ? {} : { wireDigest: input.prepared.digest }),+ }+ const prefix = JSON.stringify(envelope).slice(0, -1)const body = `${prefix},"events":[${input.prepared.bodies.join(",")}]}`const byteLength = utf8ByteLength(body)if (byteLength > COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES) {return { ok: false, reason: "batch-invariant-oversized", byteLength }}const batch: CommunityBrowserEventBatch = {- type: COMMUNITY_BROWSER_EVENT_BATCH_TYPE,- operationId: input.operationId,- operationDigest: input.operationDigest,+ ...envelope,events: input.prepared.envelopes,}return { ok: true, batch, body, byteLength, childBodies: input.prepared.bodies }@@ -278,8 +288,8 @@ export function encodePreparedCommunityBrowserEventBatch(input: {export function isCommunityBrowserEventBatchCandidate(value: unknown,-): value is Record<string, unknown> & { type: typeof COMMUNITY_BROWSER_EVENT_BATCH_TYPE } {- return isRecord(value) && value.type === COMMUNITY_BROWSER_EVENT_BATCH_TYPE+): value is Record<string, unknown> & { type: ReturnType<typeof communityBrowserEventBatchType> } {+ return isRecord(value) && (value.type === COMMUNITY_BROWSER_EVENT_BATCH_TYPE || value.type === communityBrowserEventBatchType())}export function decodeCommunityBrowserEventBatch(@@ -294,7 +304,7 @@ export function decodeCommunityBrowserEventBatch(if (typeof value.type !== "string" || value.type.length === 0) {return { ok: false, reason: "missing-type" }}- if (value.type !== COMMUNITY_BROWSER_EVENT_BATCH_TYPE) {+ if (value.type !== COMMUNITY_BROWSER_EVENT_BATCH_TYPE && value.type !== communityBrowserEventBatchType()) {return { ok: false, reason: "wrong-type" }}if (!isCommunityDeliveryOperationId(value.operationId)) {@@ -303,8 +313,10 @@ export function decodeCommunityBrowserEventBatch(if (!isCommunityDeliveryDigest(value.operationDigest)) {return { ok: false, reason: "invalid-operation-digest" }}+ const current = value.type === communityBrowserEventBatchType()if (- Object.keys(value).length !== 4+ Object.keys(value).length !== (current ? 5 : 4)+ || (current && !isCommunityDeliveryDigest(value.wireDigest))|| !Object.hasOwn(value, "type")|| !Object.hasOwn(value, "operationId")|| !Object.hasOwn(value, "operationDigest")@@ -332,7 +344,8 @@ export function decodeCommunityBrowserEventBatch(return {ok: true,batch: {- type: COMMUNITY_BROWSER_EVENT_BATCH_TYPE,+ type: value.type,+ ...(current ? { wireDigest: value.wireDigest as string } : {}),operationId: value.operationId,operationDigest: value.operationDigest,events: envelopes,@@ -340,3 +353,33 @@ export function decodeCommunityBrowserEventBatch(events,}}++export function projectCommunityEventForContract(event: CommunityWsEvent, contract: CommunityContract): CommunityWsEvent | null {+ if (contract === COMMUNITY_CONTRACT_VERSION) return event+ if (event.type === "community:friend.block") return { type: event.type, userId: event.userId }+ if (event.type !== "community:channel.membership.change") return event+ if (event.serverId === null) return null+ return { type: event.present ? "community:channel.member_add" : "community:channel.member_remove",+ serverId: event.serverId, channelId: event.channelId, userId: event.userId }+}++export async function encodeCommunityBrowserEventBatchForContract(input: {+ operationId: CommunityDeliveryOperationId; prepared: PreparedCommunityDeliveryEvents; contract: CommunityContract;+}): Promise<CommunityBrowserEventBatchEncodeResult> {+ const source = await prepareCommunityDeliveryEvents(input.prepared.events)+ if (!source.ok) return source+ if (source.prepared.digest !== input.prepared.digest) return { ok: false, reason: "digest-mismatch", actualDigest: source.prepared.digest }+ const events = input.prepared.events.map((event) => projectCommunityEventForContract(event, input.contract))+ if (events.some((event) => event === null)) return { ok: false, reason: "invalid-child" }+ const wire = await prepareCommunityDeliveryEvents(events)+ if (!wire.ok) return wire+ return encodePreparedCommunityBrowserEventBatch({ operationId: input.operationId, operationDigest: wire.prepared.digest,+ prepared: wire.prepared, ...(input.contract === COMMUNITY_CONTRACT_VERSION ? { sourceDigest: input.prepared.digest } : {}) })+}++export function admitCommunityBrowserEventBatch(value: unknown): CommunityBrowserEventBatchDecodeResult | Promise<CommunityBrowserEventBatchDecodeResult> {+ const decoded = decodeCommunityBrowserEventBatch(value)+ if (!decoded.ok || decoded.batch.type === COMMUNITY_BROWSER_EVENT_BATCH_TYPE) return decoded+ return computeCommunityDeliveryDigestFromBodies((value as { events: unknown[] }).events.map((event) => JSON.stringify(event)))+ .then((digest) => digest === decoded.batch.wireDigest ? decoded : { ok: false, reason: "invalid-payload" })+}diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 60ffeef8c..b816685a2 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -1,27 +1,14 @@import { z } from "zod"import { CommunityMachineRuntimeSchema } from "./schemas"+import { FriendApprovalPayloadSchema } from "./community-friend-approval"+import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMemberRelationSchema } from "./community-resources"++export { FriendApprovalPayloadSchema } from "./community-friend-approval"+export type { FriendApprovalPayload, FriendApprovalProfile } from "./community-friend-approval"const string = z.string()const nullableString = string.nullable()-const channelTypeSchema = z.enum(["text", "forum"])-const mentionTypeSchema = z.literal("everyone")--const friendApprovalProfileSchema = z.strictObject({- id: string,- name: string,- discriminator: string,- image: nullableString,- avatarVersion: z.number().int().nonnegative(),-})--export const FriendApprovalPayloadSchema = z.strictObject({- friendshipId: string,- status: z.enum(["pending", "approved", "denied", "superseded", "cancelled"]),- waitingOn: z.enum(["you", "other-owner", "addressee"]).nullable(),- otherProfile: friendApprovalProfileSchema,- botProfile: friendApprovalProfileSchema,- waitingOnProfile: friendApprovalProfileSchema.nullable().optional(),-})+const channelTypeSchema = CommunityChannelResourceSchema.shape.type.extract(["text", "forum"])const messageAttachmentSchema = z.strictObject({id: string,@@ -34,30 +21,22 @@ const messageAttachmentSchema = z.strictObject({height: z.number().nullable().optional(),})-const messageSchema = z.strictObject({+const messageSchema = CommunityMessageResourceSchema.pick({+ content: true, type: true, systemKind: true, authorAvatar: true, authorAvatarVersion: true,+ mentionType: true, embeds: true, createdAt: true, approval: true,+}).extend({id: string,seq: z.number(),authorId: string,authorName: string,- authorAvatar: string.optional(),- authorAvatarVersion: z.number().int().nonnegative(),- content: string,- type: z.enum(["chat", "system"]),- systemKind: z.literal("thread").optional(),- mentionType: mentionTypeSchema.nullable().optional(),+ authorAvatarVersion: CommunityMessageResourceSchema.shape.authorAvatarVersion.unwrap(),replyToId: nullableString.optional(),- replyTo: z.strictObject({+ replyTo: CommunityMessageResourceSchema.shape.replyTo.unwrap().extend({id: string,authorId: string.optional(),- authorName: string,- text: string,- deleted: z.boolean().optional(),}).optional(),- embeds: z.array(z.unknown()).optional(),attachments: z.array(messageAttachmentSchema).optional(),- createdAt: string,clientNonce: string.optional(),- approval: FriendApprovalPayloadSchema.optional(),})const communityMessageCreateSchema = z.strictObject({@@ -231,6 +210,15 @@ const communityChannelMemberRemoveSchema = z.strictObject({userId: string,})+const communityChannelMembershipChangeSchema = z.strictObject({+ type: z.literal("community:channel.membership.change"),+ channelId: string,+ serverId: string.nullable(),+ userId: string,+ relation: CommunityMemberRelationSchema.shape.relation,+ present: z.boolean(),+})+const communityCategoryCreateSchema = z.strictObject({type: z.literal("community:category.create"),serverId: string,@@ -328,6 +316,7 @@ const communityFriendRemoveSchema = z.strictObject({const communityFriendBlockSchema = z.strictObject({type: z.literal("community:friend.block"),userId: string,+ blockedByViewer: z.boolean().optional(),})const communityInviteCreateSchema = z.strictObject({@@ -492,6 +481,7 @@ const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [communityChannelReorderSchema,communityChannelMemberAddSchema,communityChannelMemberRemoveSchema,+ communityChannelMembershipChangeSchema,communityCategoryCreateSchema,communityCategoryUpdateSchema,communityCategoryDeleteSchema,@@ -560,6 +550,7 @@ export type CommunityChannelDelete = Extract<CommunityWsEvent, { type: "communitexport type CommunityChannelReorder = Extract<CommunityWsEvent, { type: "community:channel.reorder" }>export type CommunityChannelMemberAdd = Extract<CommunityWsEvent, { type: "community:channel.member_add" }>export type CommunityChannelMemberRemove = Extract<CommunityWsEvent, { type: "community:channel.member_remove" }>+export type CommunityChannelMembershipChange = Extract<CommunityWsEvent, { type: "community:channel.membership.change" }>export type CommunityCategoryCreate = Extract<CommunityWsEvent, { type: "community:category.create" }>export type CommunityCategoryUpdate = Extract<CommunityWsEvent, { type: "community:category.update" }>export type CommunityCategoryDelete = Extract<CommunityWsEvent, { type: "community:category.delete" }>@@ -588,8 +579,6 @@ export type CommunityMachineRemoved = Extract<CommunityWsEvent, { type: "communiexport type CommunityBotAuditEvent = Extract<CommunityWsEvent, { type: "community:bot.audit_event" }>export type CommunityMachineSummary = z.infer<typeof CommunityMachineSummarySchema>export type CommunityMachineRuntime = CommunityMachineSummary["availableRuntimes"][number]-export type FriendApprovalPayload = z.infer<typeof FriendApprovalPayloadSchema>-export type FriendApprovalProfile = FriendApprovalPayload["otherProfile"]export type BotAddedFrame = {type: "bot:added"@@ -634,6 +623,7 @@ export const WS_EVENTS = {CHANNEL_REORDER: "community:channel.reorder",CHANNEL_MEMBER_ADD: "community:channel.member_add",CHANNEL_MEMBER_REMOVE: "community:channel.member_remove",+ CHANNEL_MEMBERSHIP_CHANGE: "community:channel.membership.change",CATEGORY_CREATE: "community:category.create",CATEGORY_UPDATE: "community:category.update",CATEGORY_DELETE: "community:category.delete",diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.tsindex e272f55ca..4f6b2658d 100644--- a/src/shared/src/constants/community.ts+++ b/src/shared/src/constants/community.ts@@ -169,7 +169,7 @@ export function normalizeNotifLevel(input: string): NotificationLevelValue {// Participant `source` — how a user joined a child thread's notify set: an// `@`-mention, having spoken in it, or explicitly added.// Anchors `community_channel_member.source` / thread-participant `source`.-// Single value source for the literals; `ThreadParticipantSource`+// Single value source for the literals; `ParticipantSource`// (queries/community/thread.ts) derives from this via const-assert so the two// can never drift.export const PARTICIPANT_SOURCE = {diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 5bbe45e64..82a208caf 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -1,4 +1,4 @@-import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, isNull, count, type SQL } from "drizzle-orm";+import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, isNull, count, min, type SQL, type GetColumnData } from "drizzle-orm";import {communityMessage,communityChannel,@@ -555,7 +555,7 @@ async function hardDeleteMessageAttempt(// Shared select projection for the three list-messages paths (`listMessages`,// `listMessagesAround`, `listMessagesSince`). Keeps their row shape identical// so downstream mappers (`mapMessageForApi`) don't have to branch on source.-const listedMessageProjection = {+const messageProjection = {id: communityMessage.id,authorId: communityMessage.authorId,content: communityMessage.content,@@ -563,35 +563,24 @@ const listedMessageProjection = {mentionType: communityMessage.mentionType,replyToId: communityMessage.replyToId,embeds: communityMessage.embeds,- seq: communityMessage.seq,createdAt: communityMessage.createdAt,channelId: communityMessage.channelId,- friendshipId: communityMessage.friendshipId,- clientNonce: communityMessage.clientNonce,authorName: user.name,- authorEmail: user.email,authorImage: user.image,authorAvatarVersion: user.avatarVersion,} as const;-export type ListedMessageRow = {- id: string;- authorId: string;- content: string;- type: string;- mentionType: string | null;- replyToId: string | null;- embeds: unknown | undefined;- seq: number;- createdAt: string;- channelId: string;- friendshipId: string | null;- clientNonce: string | null;- authorName: string;- authorEmail: string;- authorImage: string | null;- authorAvatarVersion: number;-};+const listedMessageProjection = {+ ...messageProjection,+ seq: communityMessage.seq,+ friendshipId: communityMessage.friendshipId,+ clientNonce: communityMessage.clientNonce,+ authorEmail: user.email,+} as const;++export type ListedMessageRow = Omit<{+ [K in keyof typeof listedMessageProjection]: GetColumnData<typeof listedMessageProjection[K]>+}, "embeds"> & { embeds: unknown };const wakeContextMessageProjection = {id: communityMessage.id,@@ -608,17 +597,7 @@ const wakeContextMessageProjection = {} as const;export type WakeContextMessageRow = {- id: string;- authorId: string;- authorName: string;- authorDiscriminator: string;- authorIsBot: boolean;- content: string;- type: string;- replyToId: string | null;- seq: number;- createdAt: string;- channelId: string;+ [K in keyof typeof wakeContextMessageProjection]: GetColumnData<typeof wakeContextMessageProjection[K]>};export async function listWakeContextMessagesBefore(@@ -659,8 +638,9 @@ export async function getWakeContextMessageInScope(return rows[0] ?? null;}-function parseEmbeds(r: { id: string; embeds: string | null } & Record<string, unknown>): ListedMessageRow {- return { ...(r as unknown as ListedMessageRow), embeds: safeParseEmbeds(r.embeds, r.id) };+function parseEmbeds<T extends { id: string; embeds: string | null }>(row: T) {+ const { embeds, ...rest } = row;+ return { ...rest, embeds: safeParseEmbeds(embeds, row.id) };}export async function listMessages(@@ -935,7 +915,6 @@ export async function getLatestMessage(* writing a read-state row without a `lastReadMessageId`, so the caller must* be able to tell "no message → no write" from a single lookup.*- * Same MIN/MAX-per-channel subquery pattern as `getFirstMessageByChannelIds`* — one SQL round-trip regardless of channel count.*/export async function getLatestMessagesByChannelIds(@@ -1002,49 +981,7 @@ export async function getLatestMessagesByChannelIds(return Array.from(bestByChannel.values());}-export async function getFirstMessageByChannelIds(db: Database, channelIds: string[]) {- if (channelIds.length === 0) return [];- // Use a subquery to get the min createdAt per channel, then join to get the- // content. Chunk the `inArray` for D1's 100-param limit — GROUP BY channelId- // partitions cleanly across chunks (defensive; input is page-bounded today).- const runChunk = (ids: string[]) => {- const firstDates = db- .select({- channelId: communityMessage.channelId,- minCreatedAt: sql<string>`MIN(${communityMessage.createdAt})`.as("min_created_at"),- })- .from(communityMessage)- .where(inArray(communityMessage.channelId, ids))- .groupBy(communityMessage.channelId)- .as("first_dates");- return db- .select({- channelId: communityMessage.channelId,- content: communityMessage.content,- })- .from(communityMessage)- .innerJoin(- firstDates,- and(- eq(communityMessage.channelId, firstDates.channelId),- eq(communityMessage.createdAt, firstDates.minCreatedAt)- )- );- };-- const rows = (- await Promise.all(chunk(channelIds, D1_MAX_IN_PARAMS).map(runChunk))- ).flat();-- // Deduplicate in case of exact same createdAt within a channel- const seen = new Set<string>();- return rows.filter((r) => {- if (!r.channelId || seen.has(r.channelId)) return false;- seen.add(r.channelId);- return true;- });-}/*** Look up a single message by (channel-or-DM scope, seq). `seq === 0` is the@@ -1124,28 +1061,16 @@ export async function getWakeMessageScopeById(export async function getMessage(db: Database, messageId: string) {const rows = await db.select({- id: communityMessage.id,- authorId: communityMessage.authorId,- content: communityMessage.content,- type: communityMessage.type,- mentionType: communityMessage.mentionType,- replyToId: communityMessage.replyToId,- embeds: communityMessage.embeds,- createdAt: communityMessage.createdAt,- channelId: communityMessage.channelId,- // Needed by committed-message delivery and agent projections.+ ...messageProjection,seq: communityMessage.seq,- authorName: user.name,authorEmail: user.email,- authorImage: user.image,- authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id)).where(eq(communityMessage.id, messageId));const row = rows[0];if (!row) return null;- return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };+ return parseEmbeds(row);}/**@@ -1179,20 +1104,9 @@ export async function getMessageByAuthorAndNonce() {const rows = await db.select({- id: communityMessage.id,- authorId: communityMessage.authorId,- content: communityMessage.content,- type: communityMessage.type,- mentionType: communityMessage.mentionType,- replyToId: communityMessage.replyToId,- embeds: communityMessage.embeds,- createdAt: communityMessage.createdAt,- channelId: communityMessage.channelId,+ ...messageProjection,seq: communityMessage.seq,- authorName: user.name,authorEmail: user.email,- authorImage: user.image,- authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))@@ -1205,7 +1119,7 @@ export async function getMessageByAuthorAndNonce(.limit(1);const row = rows[0];if (!row) return null;- return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };+ return parseEmbeds(row);}/** Update only the author's own message content. The author predicate lives in@@ -1237,20 +1151,9 @@ export async function getMessagesByIds(db: Database, ids: string[]) {chunk(ids, D1_MAX_IN_PARAMS).map((batch) =>db.select({- id: communityMessage.id,- authorId: communityMessage.authorId,- content: communityMessage.content,- type: communityMessage.type,- mentionType: communityMessage.mentionType,- replyToId: communityMessage.replyToId,- embeds: communityMessage.embeds,- createdAt: communityMessage.createdAt,- channelId: communityMessage.channelId,+ ...messageProjection,seq: communityMessage.seq,- authorName: user.name,authorEmail: user.email,- authorImage: user.image,- authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))@@ -1258,7 +1161,7 @@ export async function getMessagesByIds(db: Database, ids: string[]) {))).flat();- return rows.map((r) => ({ ...r, embeds: safeParseEmbeds(r.embeds, r.id) }));+ return rows.map(parseEmbeds);}/**@@ -1328,59 +1231,59 @@ function scopeCondition(scope: MessageScope) {export async function getMessageInScope(db: Database, messageId: string, scope: MessageScope) {const rows = await db.select({- id: communityMessage.id,- authorId: communityMessage.authorId,- content: communityMessage.content,- type: communityMessage.type,- mentionType: communityMessage.mentionType,- replyToId: communityMessage.replyToId,- embeds: communityMessage.embeds,- createdAt: communityMessage.createdAt,- channelId: communityMessage.channelId,- authorName: user.name,+ ...messageProjection,authorEmail: user.email,- authorImage: user.image,- authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id)).where(and(eq(communityMessage.id, messageId), scopeCondition(scope)));const row = rows[0];if (!row) return null;- return { ...row, embeds: safeParseEmbeds(row.embeds, row.id) };+ return parseEmbeds(row);}/** Batched form of `getMessageInScope` — see its doc comment for the "why". */export async function getMessagesByIdsInScope(db: Database, ids: string[], scope: MessageScope) {- if (ids.length === 0) return [];+ return getMessagesByIdsInChannels(db, ids, [scope.channelId]);+}++export async function getMessagesByIdsInChannels(db: Database, ids: string[], channelIds: string[]) {+ if (ids.length === 0 || channelIds.length === 0) return [];// `ids` are the reply-target ids of a message page (up to ~200), so this// `inArray` is unbounded — chunk for D1's 100-param limit; no order/limit → concat.const rows = (await Promise.all(- chunk(ids, D1_MAX_IN_PARAMS).map((batch) =>+ chunk([...new Set(channelIds)], Math.floor(D1_MAX_IN_PARAMS / 2)).flatMap((channels) =>+ chunk([...new Set(ids)], D1_MAX_IN_PARAMS - channels.length).map((batch) =>db.select({- id: communityMessage.id,- authorId: communityMessage.authorId,- content: communityMessage.content,- type: communityMessage.type,- mentionType: communityMessage.mentionType,- replyToId: communityMessage.replyToId,- embeds: communityMessage.embeds,+ ...messageProjection,seq: communityMessage.seq,- createdAt: communityMessage.createdAt,- channelId: communityMessage.channelId,- authorName: user.name,+ clientNonce: communityMessage.clientNonce,discriminator: user.discriminator,authorEmail: user.email,- authorImage: user.image,- authorAvatarVersion: user.avatarVersion,}).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id))- .where(and(inArray(communityMessage.id, batch), scopeCondition(scope)))- )+ .where(and(inArray(communityMessage.id, batch), inArray(communityMessage.channelId, channels)))+ )))).flat();- return rows.map((r) => ({ ...r, embeds: safeParseEmbeds(r.embeds, r.id) }));+ return rows.map(parseEmbeds);+}++export async function getFirstMessageResourcesByChannelIds(db: Database, channelIds: string[]) {+ if (channelIds.length === 0) return [];+ const rows = (await Promise.all(chunk([...new Set(channelIds)], D1_MAX_IN_PARAMS).map((ids) => {+ const first = db.select({ channelId: communityMessage.channelId, seq: min(communityMessage.seq).as("first_seq") })+ .from(communityMessage).where(inArray(communityMessage.channelId, ids)).groupBy(communityMessage.channelId).as("first_messages");+ return db.select({+ ...messageProjection,+ seq: communityMessage.seq,+ clientNonce: communityMessage.clientNonce,+ })+ .from(communityMessage).innerJoin(first, and(eq(communityMessage.channelId, first.channelId), eq(communityMessage.seq, first.seq)))+ .innerJoin(user, eq(user.id, communityMessage.authorId));+ }))).flat();+ return rows.map(parseEmbeds);}diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.tsindex 495b750b2..071450717 100644--- a/src/shared/src/db/queries/community/thread.ts+++ b/src/shared/src/db/queries/community/thread.ts@@ -20,8 +20,6 @@ import { compareAsciiSqliteBinary } from "../../../lib/sqlite-binary";// Derived from PARTICIPANT_SOURCE (constants/community.ts) so the type and the// literal set can never drift.-export type ThreadParticipantSource = ParticipantSource;-const NOTIFY_CONFLICT_TARGET = [communityChannelMember.channelId,communityChannelMember.userId,@@ -33,7 +31,7 @@ const NOTIFY_CONFLICT_TARGET = [// Returns the inserted row, or null when the participant already existed.export async function addThreadParticipant(db: Database,- data: { threadChannelId: string; userId: string; source: ThreadParticipantSource }+ data: { threadChannelId: string; userId: string; source: ParticipantSource }) {const rows = await db.insert(communityChannelMember)@@ -54,7 +52,7 @@ export async function addThreadParticipant(export async function addThreadParticipants(db: Database,threadChannelId: string,- rows: { userId: string; source: ThreadParticipantSource }[]+ rows: { userId: string; source: ParticipantSource }[]) {if (rows.length === 0) return [];// communityChannelMember emits 6 bind params/row (id $defaultFn, channel_id,diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 2df8ee1f9..ba9c433a5 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -609,6 +609,7 @@ export type {CommunityChannelReorder,CommunityChannelMemberAdd,CommunityChannelMemberRemove,+ CommunityChannelMembershipChange,CommunityCategoryCreate,CommunityCategoryUpdate,CommunityCategoryDelete,@@ -670,6 +671,7 @@ export type {CommunityBrowserEventBatchDecodeResult,} from "./community-ws-bundle";export {+ communityBrowserEventBatchType,COMMUNITY_BROWSER_EVENT_BATCH_TYPE,COMMUNITY_DELIVERY_OPERATION_ID_PREFIX,COMMUNITY_DELIVERY_OPERATION_ID_HEADER,@@ -686,6 +688,9 @@ export {encodePreparedCommunityBrowserEventBatch,isCommunityBrowserEventBatchCandidate,decodeCommunityBrowserEventBatch,+ admitCommunityBrowserEventBatch,+ projectCommunityEventForContract,+ encodeCommunityBrowserEventBatchForContract,} from "./community-ws-bundle";// Database@@ -816,3 +821,5 @@ export { parseReleaseVersion, releaseVersionGte, semverGte } from "./semver";export type { ReleaseVersion } from "./semver";export { resolveMode, cliCommand, cliPackageName, updateCommand, daemonCommand, getBaseUrl, isTauri, isDesktop, isMobile, tauriInvoke } from "./mode";export type { AlookMode, ModeSignals, BaseUrlSignals } from "./mode";+export { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestsCommunityContract, type CommunityContract } from "./community-contract";+export * from "./community-resources";diff --git a/src/shared/test/community-message-delivery.test.ts b/src/shared/test/community-message-delivery.test.tsindex 5c1f33307..40ec539b0 100644--- a/src/shared/test/community-message-delivery.test.ts+++ b/src/shared/test/community-message-delivery.test.ts@@ -36,6 +36,17 @@ const valid = {};describe("message delivery batch", () => {+ it("accepts the committed join set and rejects incomplete or unrelated roster changes", () => {+ const joined = { ...valid, joinedParticipantUserIds: ["u1", "u2"], rosterRefreshUserId: "u1" };+ expect(parseMessageDeliveryBatch(joined)).toEqual({ ok: true, batch: joined });+ for (const batch of [+ { ...joined, rosterRefreshUserId: undefined },+ { ...valid, rosterRefreshUserId: "u1" },+ { ...joined, joinedParticipantUserIds: ["u1", "u1"] },+ { ...joined, joinedParticipantUserIds: ["outside"] },+ { ...joined, messageEvent: { ...messageEvent, serverId: undefined, parentChannelId: undefined }, memberAdded: undefined, parentProjection: undefined, parentProjectionUserIds: undefined },+ ]) expect(parseMessageDeliveryBatch(batch)).toEqual({ ok: false, reason: "invalid-payload" });+ });it("accepts a strict message-specific batch with separate parent audience", () => {expect(parseMessageDeliveryBatch(valid)).toEqual({ ok: true, batch: valid });});diff --git a/src/shared/test/community-resources.contract.test.ts b/src/shared/test/community-resources.contract.test.tsnew file mode 100644index 000000000..0f6d900a8--- /dev/null+++ b/src/shared/test/community-resources.contract.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from "vitest"+import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, normalizeCommunityChannelIdentity, normalizeCommunityChannelResource, normalizeCommunityMessageResource } from "../src"+import { COMMUNITY_CONTRACT_HEADER, requestsCommunityContract } from "../src/community-contract"++describe("common community resources", () => {+ it.each([undefined, "1", "2", "02", "3"])("negotiates only the exact supported read contract %s", (version) => {+ const headers = new Headers(version === undefined ? undefined : { [COMMUNITY_CONTRACT_HEADER]: version })+ expect(requestsCommunityContract(headers)).toBe(version === "2")+ })+ it.each(["text", "forum", "thread", "dm"] as const)("normalizes the %s channel without inventing an owner", (type) => {+ const channel = normalizeCommunityChannelResource({ id: "channel", type, serverId: type === "dm" ? null : "server", name: type === "dm" ? null : "Channel",+ archived: 0, createdAt: "2026-10-07T12:00:00Z" })+ expect(channel).toMatchObject({ type, archived: false, parentChannelId: null, parentMessageId: null, categoryId: null, creatorId: null, lastMessageAt: null, messageCount: 0 })+ expect(CommunityChannelResourceSchema.safeParse({ ...channel, pending: true }).success).toBe(false)+ })+ it("validates legacy channel identity without requiring full-read fields", () => {+ const input = { id: "post", type: "thread", serverId: "server", name: "Post", archived: 1, extra: "legacy" }+ expect(normalizeCommunityChannelIdentity(input)).toEqual({ id: "post", type: "thread", serverId: "server", name: "Post", archived: true,+ parentChannelId: null, parentMessageId: null, creatorId: null, lastMessageAt: null })+ expect(() => normalizeCommunityChannelIdentity({ ...input, id: "" })).toThrow()+ expect(() => normalizeCommunityChannelIdentity({ ...input, archived: 2 })).toThrow()+ })+ it("requires committed message identity and rejects foreign scope", () => {+ const message = { id: "message", seq: 1, authorId: "author", createdAt: "2026-10-07T12:00:00Z", type: "chat", content: "hello" }+ expect(normalizeCommunityMessageResource(message, "channel")).toMatchObject({ channelId: "channel", replyToId: null, clientNonce: null, attachments: [] })+ expect(() => normalizeCommunityMessageResource({ ...message, channelId: "other" }, "channel")).toThrow("scope mismatch")+ expect(() => normalizeCommunityMessageResource({ ...message, seq: undefined }, "channel")).toThrow()+ const normalized = normalizeCommunityMessageResource(message, "channel")+ expect(CommunityMessageResourceSchema.safeParse({ ...normalized, type: "pending" }).success).toBe(false)+ })++ it("returns a complete canonical resource while stripping only legacy envelope extras", () => {+ const channel = normalizeCommunityChannelResource({ id: "channel", type: "thread", serverId: "server", name: null, archived: 1,+ createdAt: "now", topic: null, position: null, messageCount: null, extra: "legacy" })+ expect(CommunityChannelResourceSchema.parse(channel)).toEqual(channel)+ expect(channel).toMatchObject({ archived: true, topic: "", position: 0, messageCount: 0 })+ expect(channel).not.toHaveProperty("extra")+ const message = normalizeCommunityMessageResource({ id: "message", seq: 0, authorId: "author", createdAt: "now", type: "chat", content: "",+ replyToId: null, replyTo: { id: "reply", authorName: "Author", text: "prior" }, clientNonce: null, embeds: null, extra: "legacy" }, "channel")+ expect(CommunityMessageResourceSchema.parse(message)).toEqual(message)+ expect(message).toMatchObject({ replyToId: "reply", clientNonce: null, attachments: [] })+ expect(message).not.toHaveProperty("extra")+ })++ it.each([{ seq: -1 }, { seq: 0.5 }, { authorId: "" }, { attachments: null },+ { attachments: [{ kind: "file", name: "file", url: "/file", extra: true }] },+ { replyTo: { id: "reply", authorName: "Author", text: "prior", extra: true } },+ ])("rejects invalid committed message fields %j", (fields) => {+ expect(() => normalizeCommunityMessageResource({ id: "message", seq: 0, authorId: "author", createdAt: "now", type: "chat", content: "", ...fields }, "channel")).toThrow()+ })++ it("rejects an empty publication scope and invalid channel defaults", () => {+ expect(() => normalizeCommunityMessageResource({ id: "message", seq: 0, authorId: "author", createdAt: "now", type: "chat", content: "" }, "")).toThrow()+ for (const fields of [{ messageCount: -1 }, { messageCount: 0.5 }, { position: Infinity }, { archived: 2 }, { name: undefined }, { serverId: undefined }]) {+ expect(() => normalizeCommunityChannelResource({ id: "channel", type: "text", serverId: "server", name: "Channel", archived: 0, createdAt: "now", ...fields })).toThrow()+ }+ })+})diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.tsindex a4d3ef03d..7c0b557f6 100644--- a/src/shared/test/community-ws-bundle.contract.test.ts+++ b/src/shared/test/community-ws-bundle.contract.test.ts@@ -2,6 +2,9 @@ import { describe, expect, it, vi } from "vitest"import {COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,COMMUNITY_BROWSER_EVENT_BATCH_TYPE,+ communityBrowserEventBatchType,+ encodeCommunityBrowserEventBatchForContract,+ admitCommunityBrowserEventBatch,COMMUNITY_BROWSER_EVENT_MAX_BYTES,COMMUNITY_DELIVERY_OPERATION_ID_BYTES,computeCommunityDeliveryDigestFromBodies,@@ -44,6 +47,59 @@ function maximizeAuditPadding(): CommunityBotAuditEvent {}describe("community WS batch transport contract", () => {+ it("derives both wire names from one family and the supported contract", () => {+ expect(communityBrowserEventBatchType(1)).toBe("community:events.batch")+ expect(communityBrowserEventBatchType()).toBe("community:events.batch.v2")+ expect(communityBrowserEventBatchType(2)).toBe("community:events.batch.v2")+ expect(() => communityBrowserEventBatchType(0)).toThrow("unsupported community event contract")+ expect(() => communityBrowserEventBatchType(3)).toThrow("unsupported community event contract")+ })+ it("keeps the source digest while projecting one strict format per connection", async () => {+ const change = { type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE, channelId: "thread", serverId: "server", userId: "joined", relation: "notify", present: true } as const+ const prepared = await prepareCommunityDeliveryEvents([change])+ if (!prepared.ok) throw new Error("invalid fixture")+ const operationId = await deriveCommunityDeliveryOperationId("joined-message")+ for (const contract of [1, 2] as const) {+ await expect(encodeCommunityBrowserEventBatchForContract({ operationId, prepared: { ...prepared.prepared, digest: "0".repeat(64) }, contract }))+ .resolves.toMatchObject({ ok: false, reason: "digest-mismatch" })+ }+ const old = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 1 })+ const current = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 2 })+ if (!old.ok || !current.ok) throw new Error("invalid projection")+ expect(old.body).toBe("{\"type\":\"community:events.batch\",\"operationId\":\"message:qbWQs0jZgHxxQP2XnrG_JaBwIEH7tss-wN83NwGGFco\",\"operationDigest\":\"02f419257acb00e467b673a0d10295eacaa0176c6f6700926ced78aabd78f053\",\"events\":[{\"type\":\"community:channel.member_add\",\"serverId\":\"server\",\"channelId\":\"thread\",\"userId\":\"joined\"}]}")+ expect(old.byteLength).toBe(296)+ expect(current.body).toBe("{\"type\":\"community:events.batch.v2\",\"operationId\":\"message:qbWQs0jZgHxxQP2XnrG_JaBwIEH7tss-wN83NwGGFco\",\"operationDigest\":\"256d83c615e1feac6685548ba38cfa9296913b0e0b64fd11ec8d4331711390b6\",\"wireDigest\":\"256d83c615e1feac6685548ba38cfa9296913b0e0b64fd11ec8d4331711390b6\",\"events\":[{\"type\":\"community:channel.membership.change\",\"channelId\":\"thread\",\"serverId\":\"server\",\"userId\":\"joined\",\"relation\":\"notify\",\"present\":true}]}")+ expect(current.byteLength).toBe(421)+ expect(admitCommunityBrowserEventBatch(old.batch)).not.toBeInstanceOf(Promise)+ expect(admitCommunityBrowserEventBatch(old.batch)).toMatchObject({ ok: true })+ expect(admitCommunityBrowserEventBatch(current.batch)).toBeInstanceOf(Promise)+ expect(old.batch.type).toBe(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)+ expect(Object.keys(old.batch)).toHaveLength(4)+ expect(old.batch.events).toEqual([{ type: WS_EVENTS.CHANNEL_MEMBER_ADD, serverId: "server", channelId: "thread", userId: "joined" }])+ expect(old.batch.operationDigest).not.toBe(prepared.prepared.digest)+ expect(current.batch).toMatchObject({ type: communityBrowserEventBatchType(), operationDigest: prepared.prepared.digest, wireDigest: prepared.prepared.digest })+ expect(await admitCommunityBrowserEventBatch(JSON.parse(current.body))).toMatchObject({ ok: true })+ expect(decodeCommunityBrowserEventBatch({ ...old.batch, wireDigest: current.batch.wireDigest }).ok).toBe(false)+ const tampered = JSON.parse(current.body)+ tampered.events[0].present = false+ expect(await admitCommunityBrowserEventBatch(tampered)).toMatchObject({ ok: false })+ const invalid = JSON.parse(current.body)+ invalid.events[0].extra = true+ expect(await admitCommunityBrowserEventBatch(invalid)).toMatchObject({ ok: false })+ })+ it.each([false, true])("keeps owned Block=%s in the current wire and emits the original peer shape for legacy", async (blockedByViewer) => {+ const event = { type: WS_EVENTS.FRIEND_BLOCK, userId: "peer", blockedByViewer } as const+ const prepared = await prepareCommunityDeliveryEvents([event])+ if (!prepared.ok) throw new Error("invalid block fixture")+ const operationId = await deriveCommunityDeliveryOperationId("blocked-peer")+ const old = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 1 })+ const current = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 2 })+ if (!old.ok || !current.ok) throw new Error("invalid block projection")+ expect(old.batch.events).toEqual([{ type: WS_EVENTS.FRIEND_BLOCK, userId: "peer" }])+ expect(current.batch.events).toEqual([event])+ expect(await admitCommunityBrowserEventBatch(current.batch)).toMatchObject({ ok: true })+ })+const children: CommunityWsEvent[] = [communityWsEventFixtures["community:message.create"],communityWsEventFixtures["community:unread.bump"],@@ -88,7 +144,7 @@ describe("community WS batch transport contract", () => {expect(isCommunityDeliveryDigest("a".repeat(63))).toBe(false)})- it("round-trips one strict outer frame without entering the 45-event union", async () => {+ it("round-trips one strict outer frame without entering the 46-event union", async () => {const operationId = await deriveCommunityDeliveryOperationId("message-1")const prepared = await prepareCommunityDeliveryEvents(children)expect(prepared.ok).toBe(true)@@ -116,7 +172,7 @@ describe("community WS batch transport contract", () => {})expect(isCommunityBrowserEventBatchCandidate(encoded.batch)).toBe(true)expect(Object.values(WS_EVENTS)).not.toContain(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)- expect(Object.values(WS_EVENTS)).toHaveLength(45)+ expect(Object.values(WS_EVENTS)).toHaveLength(46)})it("rejects invalid count, child, operation metadata, digest mismatch, and strict outer keys", async () => {diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.tsindex a9f07c528..c0633c4e1 100644--- a/src/shared/test/community-ws-events.contract.test.ts+++ b/src/shared/test/community-ws-events.contract.test.ts@@ -65,13 +65,13 @@ describe("Community browser event runtime contract", () => {const fixtures = Object.values(communityWsEventFixtures)const names = Object.values(WS_EVENTS).sort()- it("locks the exact 45-event inventory", () => {- expect(names).toHaveLength(45)+ it("locks the exact 46-event inventory", () => {+ expect(names).toHaveLength(46)expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)})- it("decodes and canonically encodes all 45 current event fixtures", () => {+ it("decodes and canonically encodes all 46 current event fixtures", () => {for (const fixture of fixtures) {expect(decodeCommunityBrowserEvent(fixture)).toEqual({ ok: true, event: fixture })const encoded = encodeCommunityBrowserEvent(fixture)diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.tsindex b7a6c7ea5..196b87077 100644--- a/src/shared/test/community-ws-events.fixtures.ts+++ b/src/shared/test/community-ws-events.fixtures.ts@@ -153,6 +153,9 @@ export const communityWsEventFixtures = {channelId: "channel-1",userId: "user-1",},+ "community:channel.membership.change": {+ type: "community:channel.membership.change", serverId: "server-1", channelId: "channel-1", userId: "user-1", relation: "notify", present: true,+ },"community:category.create": {type: "community:category.create",serverId: "server-1",@@ -311,6 +314,7 @@ export const requiredFixturePaths = {"community:channel.reorder": ["channels"],"community:channel.member_add": ["userId"],"community:channel.member_remove": ["userId"],+ "community:channel.membership.change": ["relation"],"community:category.create": ["category"],"community:category.update": ["changes"],"community:category.delete": ["categoryId"],diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.tsindex ce2f170d2..f695f340d 100644--- a/src/shared/test/community-ws-events.test.ts+++ b/src/shared/test/community-ws-events.test.ts@@ -64,7 +64,7 @@ describe("CommunityMessageEdited address contract", () => {describe("isCommunityEvent", () => {it("accepts every exact event declared by WS_EVENTS", () => {- expect(Object.values(WS_EVENTS)).toHaveLength(45);+ expect(Object.values(WS_EVENTS)).toHaveLength(46);for (const type of Object.values(WS_EVENTS)) {expect(isCommunityEvent({ type })).toBe(true);}diff --git a/src/shared/test/queries/community-forum-message-pagination.test.ts b/src/shared/test/queries/community-forum-message-pagination.test.tsindex 0928beb0b..f62bf515f 100644--- a/src/shared/test/queries/community-forum-message-pagination.test.ts+++ b/src/shared/test/queries/community-forum-message-pagination.test.ts@@ -16,6 +16,7 @@ describe("forum opener message pagination against real SQLite", () => {id TEXT PRIMARY KEY,name TEXT NOT NULL,email TEXT NOT NULL,+ discriminator TEXT NOT NULL DEFAULT '0001',image TEXT,avatarVersion INTEGER NOT NULL DEFAULT 0,avatarObjectKey TEXT@@ -61,6 +62,28 @@ describe("forum opener message pagination against real SQLite", () => {afterEach(() => sqlite.close())+ it("preserves each reader's exact columns while sharing body and parsed embeds", async () => {+ sqlite.prepare("UPDATE community_message SET embeds = ?, client_nonce = ?, friendship_id = ? WHERE id = ?")+ .run('[{"title":"Native"}]', "nonce", "friendship", "m1")+ const reads = [+ { row: await messageQueries.getMessage(db as never, "m1"), extra: ["seq", "authorEmail"] },+ { row: await messageQueries.getMessageByAuthorAndNonce(db as never, "u1", "nonce"), extra: ["seq", "authorEmail"] },+ { row: (await messageQueries.getMessagesByIds(db as never, ["m1"]))[0], extra: ["seq", "authorEmail"] },+ { row: await messageQueries.getMessageInScope(db as never, "m1", { channelId: "c1" }), extra: ["authorEmail"] },+ { row: (await messageQueries.getMessagesByIdsInChannels(db as never, ["m1"], ["c1"]))[0], extra: ["seq", "clientNonce", "discriminator", "authorEmail"] },+ { row: (await messageQueries.getFirstMessageResourcesByChannelIds(db as never, ["c1"]))[0], extra: ["seq", "clientNonce"] },+ { row: (await messageQueries.listMessages(db as never, { channelId: "c1", limit: 6 })).find((row) => row.id === "m1"), extra: ["seq", "clientNonce", "friendshipId", "authorEmail"] },+ ]+ const common = ["id", "authorId", "content", "type", "mentionType", "replyToId", "embeds", "createdAt", "channelId", "authorName", "authorImage", "authorAvatarVersion"]+ for (const { row, extra } of reads) {+ if (!row) throw new Error("Expected native fixture message")+ expect(Object.keys(row).sort()).toEqual([...common, ...extra].sort())+ expect(row).toMatchObject({ id: "m1", channelId: "c1", content: "message 1", authorName: "Alice", authorImage: null, authorAvatarVersion: 0, embeds: [{ title: "Native" }] })+ }+ expect(await messageQueries.getMessageInScope(db as never, "m1", { channelId: "c2" })).toBeNull()+ expect(await messageQueries.getMessagesByIdsInChannels(db as never, ["m1"], ["c2"])).toEqual([])+ })+it("filters by channel and tag before LIMIT, yielding a full page with no cross-channel leak", async () => {const rows = await messageQueries.listMessages(db as never, { channelId: "c1", tag: "bug", limit: 3 })expect(rows.map((row) => row.id)).toEqual(["m6", "m4", "m2"])@@ -101,4 +124,15 @@ describe("forum opener message pagination against real SQLite", () => {await expect(tagQueries.listDistinctTagsForChannel(db as never, "c1")).resolves.toEqual(["bug", "feature"])})++ it("returns the real first resource for each requested channel without duplicates or foreign rows", async () => {+ sqlite.prepare("UPDATE community_message SET client_nonce = ?, embeds = ? WHERE id = ?")+ .run("first-client-nonce", JSON.stringify([{ url: "https://example.test/first" }]), "m1")+ const rows = await messageQueries.getFirstMessageResourcesByChannelIds(db as never, ["c1", "c1", "empty"])+ expect(rows).toHaveLength(1)+ expect(rows[0]).toMatchObject({ id: "m1", channelId: "c1", seq: 1, authorId: "u1", authorName: "Alice", authorAvatarVersion: 0, clientNonce: "first-client-nonce", embeds: [{ url: "https://example.test/first" }] })+ expect(rows[0]).not.toHaveProperty("authorEmail")+ expect((await messageQueries.getFirstMessageResourcesByChannelIds(db as never, ["c2", "c1"])).map((row) => row.id).sort()).toEqual(["m1", "x1"])+ await expect(messageQueries.getFirstMessageResourcesByChannelIds(db as never, [])).resolves.toEqual([])+ })})diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.tsindex 82be2d7b4..36b9f2f8a 100644--- a/src/web/cloudflare-env.d.ts+++ b/src/web/cloudflare-env.d.ts@@ -1,5 +1,5 @@/* eslint-disable */-// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 6d732cfc124161cdc189fd746880d10e)+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 5e4ba6c8ad02e084794491e734aadb54)// Runtime types generated with [email protected] 2026-09-07 global_fetch_strictly_public,nodejs_compatinterface __BaseEnv_CloudflareEnv {CACHE_KV: KVNamespace;@@ -12,6 +12,7 @@ interface __BaseEnv_CloudflareEnv {TASK_QUEUE: Queue;CF_VERSION_METADATA: WorkerVersionMetadata;ASSETS: Fetcher;+ COMMUNITY_EVENT_CONTRACT: "1";RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";MIN_CLI_VERSION: "0.0.159";BLOG_DISCOVERY_REQUIRED: "true";@@ -54,7 +55,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;};declare namespace NodeJS {- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "JEV_PROVIDER" | "JEV_WAKE_THRESHOLD" | "OPENROUTER_JEV_BASE_URL" | "OPENROUTER_JEV_MODEL" | "TYPESAFE_JEV_BASE_URL" | "TYPESAFE_JEV_MODEL" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "DEVICE_CLIENT_IDS" | "OPENROUTER_API_KEY" | "TYPESAFE_API_KEY">> {}+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "COMMUNITY_EVENT_CONTRACT" | "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "JEV_PROVIDER" | "JEV_WAKE_THRESHOLD" | "OPENROUTER_JEV_BASE_URL" | "OPENROUTER_JEV_MODEL" | "TYPESAFE_JEV_BASE_URL" | "TYPESAFE_JEV_MODEL" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "DEVICE_CLIENT_IDS" | "OPENROUTER_API_KEY" | "TYPESAFE_API_KEY">> {}}// Begin runtime typesdiff --git a/src/web/scripts/perf-query-cache.test.ts b/src/web/scripts/perf-query-cache.test.tsnew file mode 100644index 000000000..0c91671a7--- /dev/null+++ b/src/web/scripts/perf-query-cache.test.ts@@ -0,0 +1,132 @@+import { IDBFactory } from "fake-indexeddb"+import { createStore, get, set } from "idb-keyval"+import { readFileSync } from "node:fs"+import { ScriptTarget, ModuleKind, transpileModule } from "typescript"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { createIdbPersister, PERSIST_BUSTER, PERSIST_CACHE_PREFIX, PERSIST_VERSION } from "../src/lib/query-persister"+import { communityKeys } from "../src/lib/query-keys"+import { operatePerfQueryCache } from "../src/test/e2e-ui/perf/perf-query-cache"++let store: ReturnType<typeof createStore>+const key = `${PERSIST_CACHE_PREFIX}:viewer:client`+const expected = {+ key,+ action: "contains" as const,+ version: PERSIST_VERSION,+ buster: PERSIST_BUSTER,+ queryKey: communityKeys.communityDbCollection("viewer", "messages"),+ channelIds: ["reload", "disk-target"],+}+const snapshot = () => ({+ version: PERSIST_VERSION,+ buster: PERSIST_BUSTER,+ channelFences: [],+ clientState: {+ queries: [{+ queryKey: [...expected.queryKey] as unknown[],+ state: { status: "success", data: [{ id: "r1", channelId: "reload" }, { id: "r2", channelId: "disk-target" }] },+ }],+ },+})++beforeEach(() => {+ vi.stubGlobal("indexedDB", new IDBFactory())+ store = createStore("keyval-store", "keyval")+})+afterEach(() => vi.unstubAllGlobals())++describe("perf switch current disk qualification", () => {+ it.each(["contains", "remove"] as const)("allows the first current persister write after %s starts without a database", async action => {+ expect(await operatePerfQueryCache(action === "contains" ? expected : { key, action })).toBe(action === "remove")+ vi.resetModules()+ const { createIdbPersister: createFreshPersister } = await import("../src/lib/query-persister")+ const persister = createFreshPersister("viewer")+ expect(await persister.isCurrent()).toBe(true)+ await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { mutations: [], queries: [] } })+ await vi.waitFor(async () => {+ const raw = await get<string>(key, store)+ expect(JSON.parse(raw ?? "null")).toMatchObject({ version: PERSIST_VERSION, buster: PERSIST_BUSTER })+ }, { timeout: 2_000 })+ })++ it("executes the browser-serialized operation against the actual canonical collection rows", async () => {+ await set(key, JSON.stringify(snapshot()), store)+ expect(await operatePerfQueryCache(expected)).toBe(true)+ const source = readFileSync(new URL("../src/test/e2e-ui/perf/perf-query-cache.ts", import.meta.url), "utf8")+ const compiled = transpileModule(source, { compilerOptions: { target: ScriptTarget.ESNext, module: ModuleKind.CommonJS } }).outputText+ const exports = {} as { operatePerfQueryCache: typeof operatePerfQueryCache }+ new Function("exports", compiled)(exports)+ const browserOperation = new Function(`return (${exports.operatePerfQueryCache.toString()})`)() as typeof operatePerfQueryCache+ expect(await browserOperation(expected)).toBe(true)+ })++ it.each(["version", "buster", "fences", "account", "transport", "missing-target", "row-id", "pending"])("rejects %s instead of recording a false disk-warm result", async variant => {+ const value = snapshot()+ const query = value.clientState.queries[0]+ if (variant === "version") value.version -= 1+ if (variant === "buster") value.buster = "obsolete"+ if (variant === "fences") Reflect.deleteProperty(value, "channelFences")+ if (variant === "account") query.queryKey = communityKeys.communityDbCollection("another-viewer", "messages")+ if (variant === "transport") query.queryKey = ["community", "channel", "disk-target", "messages"]+ if (variant === "missing-target") query.state.data = query.state.data.slice(0, 1)+ if (variant === "row-id") query.state.data[1].id = ""+ if (variant === "pending") query.state.status = "pending"+ await set(key, JSON.stringify(value), store)+ expect(await operatePerfQueryCache(expected)).toBe(false)+ })++ it.each(["{", "null", "[]", "{}"]) ("waits for a current payload after malformed value %s", async value => {+ await set(key, value, store)+ expect(await operatePerfQueryCache(expected)).toBe(false)+ })++ it("rejects an absent payload and an empty target set", async () => {+ await set("unrelated", "value", store)+ expect(await operatePerfQueryCache(expected)).toBe(false)+ await set(key, JSON.stringify(snapshot()), store)+ expect(await operatePerfQueryCache({ ...expected, channelIds: [] })).toBe(false)+ })++ it("rejects a database without the query store while preserving its other store", async () => {+ const otherFamily = createStore("keyval-store", "another-family")+ await set("sentinel", { value: "keep" }, otherFamily)+ await expect(operatePerfQueryCache(expected)).rejects.toThrow("query cache store unavailable")+ await expect(operatePerfQueryCache({ key, action: "remove" })).rejects.toThrow("query cache store unavailable")+ expect(await get("sentinel", otherFamily)).toEqual({ value: "keep" })+ })++ it("removes only the measured account payload and leaves the captured writer eligible", async () => {+ const persister = createIdbPersister("viewer")+ expect(await persister.isCurrent()).toBe(true)+ const retained = new Map<string, unknown>([+ ["alook:qc:device-epoch", await get("alook:qc:device-epoch", store)],+ [`${PERSIST_CACHE_PREFIX}:viewer:account-epoch`, await get(`${PERSIST_CACHE_PREFIX}:viewer:account-epoch`, store)],+ [`${PERSIST_CACHE_PREFIX}:viewer:account-epoch:channels`, await get(`${PERSIST_CACHE_PREFIX}:viewer:account-epoch:channels`, store)],+ [`${key}:epoch`, await get(`${key}:epoch`, store)],+ [`${PERSIST_CACHE_PREFIX}:another-viewer:client`, "other payload"],+ ["another-cache-family", "other family"],+ ])+ for (const [retainedKey, value] of retained) await set(retainedKey, value, store)+ await set(key, JSON.stringify(snapshot()), store)+ expect(await operatePerfQueryCache({ key, action: "remove" })).toBe(true)+ expect(await get(key, store)).toBeUndefined()+ for (const [retainedKey, value] of retained) expect(await get(retainedKey, store)).toEqual(value)+ expect(await persister.isCurrent()).toBe(true)+ await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { mutations: [], queries: [] } })+ await vi.waitFor(async () => {+ const raw = await get<string>(key, store)+ expect(JSON.parse(raw ?? "null")).toMatchObject({ version: PERSIST_VERSION, buster: PERSIST_BUSTER })+ }, { timeout: 2_000 })+ })++ it("reports open failure instead of claiming cold or warm cache success", async () => {+ const failure = new DOMException("storage unavailable", "UnknownError")+ vi.stubGlobal("indexedDB", { open: () => {+ const request = { error: failure, onerror: null as (() => void) | null }+ queueMicrotask(() => request.onerror?.())+ return request+ } })+ await expect(operatePerfQueryCache(expected)).rejects.toThrow("storage unavailable")+ await expect(operatePerfQueryCache({ key, action: "remove" })).rejects.toThrow("storage unavailable")+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.tsindex 8e7c9ac9d..3b4802510 100644--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts@@ -77,7 +77,9 @@ export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {if (!removed) return writeError("member not found", 404)const event = {- type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,+ relation: "access",+ present: false,serverId: channel.serverId,channelId,userId: targetUserId,diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.tsindex 2f3b2f3d7..a76825398 100644--- a/src/web/src/app/api/community/channels/[id]/members/route.ts+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts@@ -18,6 +18,9 @@ import { requireChannelAccess } from "@/lib/community/permissions"import { resolveTargetForMember } from "@/lib/community/resolve-ref"import { mapMemberForApi } from "@/lib/community/member-payload"import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-presence"+import { requestsCommunityContract } from "@alook/shared"+import { readCommunityMembers } from "@/lib/community/member-read"+import { resolveMessageTarget } from "@/lib/community/message-door"// A bot addresses by ref-in-query (`?ref=`, the folded `channelMember` verb);// the path `[id]` is then the `resolve` placeholder (a ref carries `/`). A@@ -41,6 +44,14 @@ const REF_PLACEHOLDER_ID = "resolve"export const GET = withCommunityActor(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)+ if (requestsCommunityContract(req.headers)) {+ const ref = req.nextUrl.searchParams.get("ref")+ const target = ctx.actor.kind === "bot" && ref ? { ref } : { id: ctx.params?.id ?? "" }+ const resolved = await resolveMessageTarget(db, ctx.actor.userId, target, ctx.actor.kind)+ if (!resolved.ok) return writeError(resolved.error, resolved.status)+ return readCommunityMembers(db, resolved.value.target.channelId, ctx.actor.userId, req.nextUrl.searchParams.get("relation"))+ }+if (ctx.actor.kind === "bot") {return handleBotChannelMember(db, ctx.env, ctx.actor.userId, req)}@@ -170,7 +181,9 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {})const event = {- type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,+ relation: "access",+ present: true,serverId: channel.serverId,channelId,userId: targetUserId,diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex a703a1c1d..dbc27711a 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -493,6 +493,31 @@ describe("POST /api/community/channels/[id]/messages", () => {})})+ it.each([false, true])("keeps scoped reply presentation on POST with replay=%s", async (replay) => {+ const row = { id: "reply_message", seq: 8, clientNonce: "n1", channelId: "c1", authorId: "u1", authorName: "Alice",+ authorImage: null, authorAvatarVersion: 0, content: "@Bob reply", type: "default", mentionType: null,+ replyToId: "reply_target", embeds: null, createdAt: "2026-06-30T00:00:00.000Z" }+ mockGetMessage.mockResolvedValue(row)+ if (replay) mockGetMessageByAuthorAndNonce.mockResolvedValue(row)+ mockGetMessageInScope.mockResolvedValue({ id: "reply_target", channelId: "c1", authorId: "u2", authorName: "Bob", content: "prior" })+ mockGetMessagesByIdsInScope.mockResolvedValue([{ id: "reply_target", channelId: "c1", authorId: "u2", authorName: "Bob", content: "prior" }])+ const response = await POST(postReq({ content: "@Bob reply", nonce: "n1", replyToId: "reply_target" }), ctx)+ expect(response.status).toBe(replay ? 200 : 201)+ expect((await response.json()).message).toMatchObject({ id: row.id, replyToId: "reply_target",+ replyTo: { id: "reply_target", authorId: "u2", authorName: "Bob", text: "prior" } })+ expect(mockGetMessagesByIdsInScope).toHaveBeenCalledWith(expect.anything(), ["reply_target"], { channelId: "c1" })+ })++ it("does not revive a deleted or out-of-scope reply in a deduplicated POST", async () => {+ mockGetMessageByAuthorAndNonce.mockResolvedValue({ id: "reply_message", seq: 8, clientNonce: "n1", channelId: "c1", authorId: "u1", authorName: "Alice",+ authorImage: null, authorAvatarVersion: 0, content: "reply", type: "default", mentionType: null,+ replyToId: "reply_target", embeds: null, createdAt: "2026-06-30T00:00:00.000Z" })+ mockGetMessagesByIdsInScope.mockResolvedValue([{ id: "reply_target", channelId: "other", authorId: "u2", authorName: "Secret", content: "private" }])+ const response = await POST(postReq({ content: "reply", nonce: "n1" }), ctx)+ expect(response.status).toBe(200)+ expect((await response.json()).message.replyTo).toEqual({ id: "reply_target", authorName: "Deleted user", text: "", deleted: true })+ })+it("returns the original canonical contract for a same-nonce replay", async () => {mockGetMessageByAuthorAndNonce.mockResolvedValue({id: "m-existing",@@ -746,13 +771,13 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith({}, "thread_1")expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(2)expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("bot_1", {- type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE, relation: "notify", present: true,serverId: "s1",channelId: "thread_1",userId: "bot_1",})expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u2", expect.objectContaining({- type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE, relation: "notify", present: true,channelId: "thread_1",userId: "bot_1",}))@@ -998,6 +1023,16 @@ describe("GET /api/community/channels/[id]/messages", () => {mockGetLatestMessageSeq.mockResolvedValue(0)})+ it("rejects a malformed V2 window before querying messages", async () => {+ const req = new NextRequest("http://localhost/api/community/channels/c1/messages?anchor=one&since=two", { headers: { "X-Alook-Community-Contract": "2" } })+ const res = await GET(req, ctx)+ expect(res.status).toBe(400)+ expect((await res.json()).error).toEqual(expect.any(String))+ expect(mockListMessages).not.toHaveBeenCalled()+ expect(mockListMessagesAround).not.toHaveBeenCalled()+ expect(mockListMessagesSince).not.toHaveBeenCalled()+ })+it("keeps the read path on the unconstrained replica-capable session", async () => {mockListMessages.mockResolvedValue([])diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex 0ab6ff3a0..b63709453 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -1,18 +1,22 @@import { flattenError } from "zod"import { NextRequest, NextResponse } from "next/server"import { withCommunityActor } from "@/lib/middleware/community-actor"-import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { writeError } from "@/lib/middleware/helpers"import { getDb, getPrimaryDb } from "@/lib/db"import { queries, withD1Retry, CommunityAgentSendRequestSchema, MAX_FORUM_TAG_LENGTH, utcDayKey, WS_EVENTS, PARTICIPANT_SOURCE } from "@alook/shared"import {parseCursor,parseAnchor,parsePageSize,+ parseCommunityMessageWindow,buildPaginatedResponse,buildAnchorResponse,buildSinceResponse,} from "@/lib/community/messages"+import { mapPostedMessageForApi } from "@/lib/community/message-payload"import { enrichMessages } from "@/lib/community/enrich-messages"+import { requestsCommunityContract } from "@alook/shared"+import { writeCommunityMessagesRead } from "@/lib/community/read-contract"import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage, getCommunityMessageReplay } from "@/lib/community/message-handler"import { createMessageWithThread } from "@/lib/community/create-channels"@@ -102,7 +106,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {// (set-equality) — only pagination-window + projection differ, no arm adds a where.// ── bot arm: seq-anchored window → agent-message projection → {items} ──- if (ctx.actor.kind === "bot") {+ if (ctx.actor.kind === "bot" && !requestsCommunityContract(req.headers)) {const readParams = {before: parseIntParam(params.get("before")),after: parseIntParam(params.get("after")),@@ -120,14 +124,16 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {// ── human arm: createdAt-anchored window → enrich → {messages} ──const userId = ctx.actor.userId- const anchorId = parseAnchor(params.get("anchor"))- const since = parseCursor(params.get("since"))- const cursor = parseCursor(params.get("cursor"))+ let window+ try { window = requestsCommunityContract(req.headers) ? parseCommunityMessageWindow(params) : {+ anchorId: parseAnchor(params.get("anchor")), since: parseCursor(params.get("since")),+ cursor: parseCursor(params.get("cursor")), pageSize: parsePageSize(params.get("limit")),+ } } catch (error) { return writeError(error instanceof Error ? error.message : "invalid message window", 400) }+ const { anchorId, since, cursor, pageSize } = windowconst rawTag = params.get("tag")const tag = rawTag?.trim().toLowerCase()if (rawTag !== null && !tag) return writeError("tag must not be empty", 400)if (tag && tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)- const pageSize = parsePageSize(params.get("limit"))if (anchorId) {const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { channelId })@@ -147,7 +153,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {)const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)- return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq, surfaceReceipt })+ return writeCommunityMessagesRead(req, channelId, { messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq, surfaceReceipt })}if (since) {@@ -159,7 +165,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {})const { items, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor } = buildSinceResponse(rows, pageSize)const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)- return writeJSON({ messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq, surfaceReceipt })+ return writeCommunityMessagesRead(req, channelId, { messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq, surfaceReceipt })}const rows = await queries.communityMessage.listMessages(db, {@@ -171,7 +177,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items.slice().reverse())- return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq, surfaceReceipt })+ return writeCommunityMessagesRead(req, channelId, { messages, hasMore, cursor: nextCursor, latestSeq, surfaceReceipt })})/**@@ -284,7 +290,7 @@ async function handleHumanSend(clientNonce,})if (replay) {- return NextResponse.json({ message: replay.row, deduped: true }, { status: 200 })+ return NextResponse.json({ message: await mapPostedMessageForApi(db, target.channelId, replay.row), deduped: true }, { status: 200 })}const result = await createCommunityMessage({@@ -298,7 +304,7 @@ async function handleHumanSend(attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,})if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })- return NextResponse.json({ message: result.row, deduped: result.deduped }, { status: 201 })+ return NextResponse.json({ message: await mapPostedMessageForApi(db, target.channelId, result.row), deduped: result.deduped }, { status: 201 })}/**@@ -387,7 +393,9 @@ async function handleBotSend()if (created) {const event = {- type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,+ relation: "notify",+ present: true,serverId: target.serverId,channelId,userId: botUserId,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 690a419bc..c246e3269 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@@ -94,7 +94,7 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {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(Object.keys(event).sort()).toEqual(["channelId", "present", "relation", "serverId", "type", "userId"])expect(decodeCommunityBrowserEvent(event).ok).toBe(true)}expect(mockDeleteThreadParticipantWithCreatorHandoff).toHaveBeenCalledWith(@@ -103,13 +103,13 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {"u1",)expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", {- type: "community:channel.member_remove",+ type: "community:channel.membership.change", relation: "notify", present: false,serverId: "s1",channelId: "t1",userId: "u1",})expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u3", expect.objectContaining({- type: "community:channel.member_remove",+ type: "community:channel.membership.change", relation: "notify", present: false,userId: "u1",}))})@@ -158,7 +158,7 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {"bot1",)expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("bot1", expect.objectContaining({- type: "community:channel.member_remove",+ type: "community:channel.membership.change", relation: "notify", present: false,userId: "bot1",}))})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 48f9fba0a..a33fb43f8 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@@ -72,7 +72,9 @@ export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {)if (!removed) return writeError("participant not found", 404)const event = {- type: WS_EVENTS.CHANNEL_MEMBER_REMOVE,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,+ relation: "notify",+ present: false,serverId: access.value.channel.serverId,channelId,userId: targetUserId,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 ca7a32455..03c3ebf31 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@@ -91,7 +91,7 @@ describe("POST /channels/[id]/participants", () => {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(Object.keys(event).sort()).toEqual(["channelId", "present", "relation", "serverId", "type", "userId"])expect(decodeCommunityBrowserEvent(event).ok).toBe(true)}expect(mockAddThreadParticipant).toHaveBeenCalledWith(expect.anything(), {@@ -99,7 +99,7 @@ describe("POST /channels/[id]/participants", () => {})expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(3)expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u3", expect.objectContaining({- type: "community:channel.member_add",+ type: "community:channel.membership.change", relation: "notify", present: true,userId: "u2",}))})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 36e4b8c6c..ba1341ba7 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@@ -67,7 +67,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (created) {const event = {- type: WS_EVENTS.CHANNEL_MEMBER_ADD,+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,+ relation: "notify",+ present: true,serverId: channel.serverId,channelId,userId: targetUserId,diff --git a/src/web/src/app/api/community/channels/[id]/read-state/route.ts b/src/web/src/app/api/community/channels/[id]/read-state/route.tsindex c19662577..06cdf8251 100644--- a/src/web/src/app/api/community/channels/[id]/read-state/route.ts+++ b/src/web/src/app/api/community/channels/[id]/read-state/route.ts@@ -1,9 +1,10 @@import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries, withD1Retry } from "@alook/shared"import { requireMessageSurfaceAccess } from "@/lib/community/permissions"+import { writeCommunityReadState } from "@/lib/community/read-contract"/*** GET /api/community/channels/:id/read-state@@ -21,7 +22,7 @@ import { requireMessageSurfaceAccess } from "@/lib/community/permissions"* DM's read-state through this channel route (the incidental P0 the trunk* closes; the old path only ran the access-member check, never the block).*/-export const GET = withAuth(async (_req: NextRequest, ctx) => {+export const GET = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)@@ -42,7 +43,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {{ route: "community/channels/read-state" },)- return writeJSON({+ return writeCommunityReadState(req, channelId, {lastReadMessageId: row?.lastReadMessageId ?? null,lastReadAt: row?.lastReadAt ?? null,// Seq is the numeric equivalent of the (createdAt, id) pointer — useddiff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.tsindex cd6d05c05..cfcda2e9c 100644--- a/src/web/src/app/api/community/channels/[id]/read/route.ts+++ b/src/web/src/app/api/community/channels/[id]/read/route.ts@@ -1,3 +1,5 @@+import { COMMUNITY_CONTRACT_VERSION, requestsCommunityContract, CommunityReadAdvanceSchema } from "@alook/shared"+import { writeCommunityContractJSON } from "@/lib/community/read-contract"import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"@@ -121,5 +123,6 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {})}+ if (requestsCommunityContract(req.headers)) return writeCommunityContractJSON(CommunityReadAdvanceSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId, changed, targetSeq: target.seq, revision }))return writeJSON({ changed, targetSeq: target.seq, revision })})diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.tsindex f6d07cf46..3740a2b57 100644--- a/src/web/src/app/api/community/channels/[id]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/route.ts@@ -15,34 +15,25 @@ import {slugify,} from "@alook/shared"import { fanOutToServerMembers, fanOutToChannel, broadcastToUserSafe } from "@/lib/community/fanout"-import { requireChannelAccess, requireChannelMember } from "@/lib/community/permissions"+import { requireChannelAccess, requireMessageSurfaceAccess } from "@/lib/community/permissions"+import { writeCommunityChannelRead } from "@/lib/community/read-contract"import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"-/**- * GET /api/community/channels/[id] — single channel metadata (the- * `getChannelForMember` row: id, name, type, parentChannelId, parentMessageId,- * creatorId, …). The canonical home for reading ANY channel's meta — a- * top-level channel, a thread, or a forum post (a DM's meta is not read this- * way; DMs surface through the DM list). Folds the old `threads/[id]` GET, which- * only ever served child-thread metadata but was channel metadata by another- * name (a thread IS a channel row). The thread-view opener + child-channel- * bootstrap read it.- *- * Two-step check preserves the 404-vs-403 contract sibling channel routes honor:- * unknown channel → 404, known channel + non-member → 403 (`requireChannelMember`- * alone collapses both to 403 because the membership JOIN can't tell them apart).- */-export const GET = withAuth(async (_req: NextRequest, ctx) => {+export const GET = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)const db = getDb(ctx.env.DB)- const channel = await queries.communityChannel.getChannel(db, channelId)- if (!channel) return writeError("channel not found", 404)- const auth = await requireChannelMember(db, channelId, ctx.userId)+ const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)-- return writeJSON(auth.value)+ const channel = auth.value.surface === "channel" ? auth.value.channel+ : await queries.communityChannel.getChannelForMember(db, channelId, ctx.userId)+ if (!channel) return writeError("not found", 404)+ const readable = !channel.archived+ const communicable = readable && (auth.value.surface !== "dm"+ || await queries.communityFriendship.areFriends(db, ctx.userId, auth.value.dm.otherUserId))+ return writeCommunityChannelRead(req, channelId, channel, { canRead: readable, canSend: communicable,+ canCreateDiscussion: readable && !channel.parentChannelId && (channel.type === "text" || channel.type === "forum") })})export const PATCH = withAuth(async (req: NextRequest, ctx) => {diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.tsindex 0e445f11f..c3a581438 100644--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts@@ -28,6 +28,10 @@ vi.mock("@alook/shared", async () => {...actual,queries: {communityChannel: {+ getChannelForMember: async () => {+ const scope = await mockResolveChannelAccessContext()+ return scope && (!scope.isPrivate || actual.canSeePrivateChannel(scope)) ? scope.channel : null+ },getChannel: (...a: unknown[]) => mockGetChannel(...a),listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),@@ -37,8 +41,8 @@ vi.mock("@alook/shared", async () => {},communityMessage: {getMessage: (...a: unknown[]) => mockGetMessage(...a),- getMessagesByIds: (...a: unknown[]) => mockGetMessagesByIds(...a),- getFirstMessageByChannelIds: (...a: unknown[]) => mockGetFirstMessageByChannelIds(...a),+ getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIds(...a),+ getFirstMessageResourcesByChannelIds: (...a: unknown[]) => mockGetFirstMessageByChannelIds(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),},communityMessageTag: {@@ -156,6 +160,22 @@ describe("GET /api/community/channels/[id]/threads", () => {expect(mockListMessages).not.toHaveBeenCalled()})+ it("loads requested included resources for the regular child collection through the same scoped batches", async () => {+ mockListChildChannels.mockResolvedValue([{ id: "t1", parentMessageId: "opener1" }])+ mockGetMessagesByIds.mockResolvedValue([{ id: "opener1", channelId: "c1" }])+ mockGetFirstMessageByChannelIds.mockResolvedValue([{ channelId: "t1", content: "first" }])+ mockListTagsForMessages.mockResolvedValue([{ messageId: "opener1", tag: "bug" }])+ mockListParticipantsForChannels.mockResolvedValue([{ channelId: "t1", userId: "u1" }])+ const response = await GET(req("http://localhost/api/community/channels/c1/threads?include=parentMessage,firstMessage,tags,participants"), ctx)+ expect(response.status).toBe(200)+ expect(await response.json()).toMatchObject({ threads: [{ id: "t1" }], hasMore: false, included: {+ parentMessages: [{ id: "opener1", channelId: "c1" }], firstMessages: [{ channelId: "t1", content: "first" }],+ tags: [{ messageId: "opener1", tag: "bug" }], participants: [{ channelId: "t1", userId: "u1" }],+ } })+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["opener1"], { channelId: "c1" })+ expect(mockListParticipantsForChannels).toHaveBeenCalledWith(expect.anything(), ["t1"], 5)+ })+it("keeps non-forum child collections unchanged without querying archive tags", async () => {mockResolveChannelAccessContext.mockResolvedValue({channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "text" },@@ -266,7 +286,7 @@ describe("GET /api/community/channels/[id]/threads", () => {parentChannelId: "c1",limit: 3,})- expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["m3", "m2"])+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["m3", "m2"], { channelId: "c1" })expect(mockGetFirstMessageByChannelIds).toHaveBeenCalledWith(expect.anything(), ["t3", "t2"])expect(mockListParticipantsForChannels).toHaveBeenCalledWith(expect.anything(), ["t3", "t2"], 5)diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.tsindex 31c5ebc63..36804327f 100644--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts@@ -2,8 +2,9 @@ import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"-import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH } from "@alook/shared"-import { requireChannelAccess } from "@/lib/community/permissions"+import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH, requestsCommunityContract } from "@alook/shared"+import { requireMessageSurfaceAccess } from "@/lib/community/permissions"+import { writeCommunityThreadsRead } from "@/lib/community/thread-read"import { parseBoundedInt } from "@/lib/community/messages"import { encodeForumCreatedAtCursor, parseForumCreatedAtCursor } from "@/lib/community/forum-feed-cursor"@@ -13,11 +14,14 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)- // Gate through the shared access predicate: a channel in a PRIVATE category- // must not leak its thread titles/previews to non-members. Public channels- // behave as before (any server member).- const access = await requireChannelAccess(db, channelId, ctx.userId)- if (!access.ok) return writeError(access.error, access.status)+ const currentContract = requestsCommunityContract(req.headers)+ const access = await requireMessageSurfaceAccess(db, channelId, ctx.userId)+ if (!access.ok) return writeError(currentContract ? access.error : "forbidden", currentContract ? access.status : 403)+ if (!currentContract && access.value.surface === "dm") return writeError("forbidden", 403)+ const channel = access.value.surface === "channel" ? access.value.channel+ : await queries.communityChannel.getChannelForMember(db, channelId, ctx.userId)+ if (!channel) return writeError("not found", 404)+ if (channel.type === "dm") return writeCommunityThreadsRead(db, ctx.userId, channel, [])const archivedParam = req.nextUrl.searchParams.get("archived")const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefined@@ -30,19 +34,23 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const order = req.nextUrl.searchParams.get("order")if (order !== null && order !== "createdAt") return writeError("invalid order", 400)+ const includes = new Set(+ (req.nextUrl.searchParams.get("include") ?? "")+ .split(",")+ .map((value) => value.trim())+ .filter(Boolean),+ )+ const allowedIncludes = new Set(["parentMessage", "firstMessage", "tags", "participants"])+ if ([...includes].some((value) => !allowedIncludes.has(value))) {+ return writeError("invalid include", 400)+ }++ let threads: Awaited<ReturnType<typeof queries.communityChannel.listChildChannels>> | Awaited<ReturnType<typeof queries.communityThread.listForumThreadsByCreatedAt>>+ let hasMore = false+ let nextCursor: string | undefinedif (order === "createdAt") {- if (!isForum(access.value.channel.type)) return writeError("not a forum", 400)+ if (!isForum(channel.type)) return writeError("not a forum", 400)if (archived === true) return writeError("createdAt order only supports active threads", 400)- const includes = new Set(- (req.nextUrl.searchParams.get("include") ?? "")- .split(",")- .map((value) => value.trim())- .filter(Boolean),- )- const allowedIncludes = new Set(["parentMessage", "firstMessage", "tags", "participants"])- if ([...includes].some((value) => !allowedIncludes.has(value))) {- return writeError("invalid include", 400)- }const pageSize = parseBoundedInt(req.nextUrl.searchParams.get("limit"), 50, 100)const cursor = parseForumCreatedAtCursor(req.nextUrl.searchParams.get("cursor"), {parentChannelId: channelId,@@ -56,10 +64,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {...(cursor ? { cursor } : {}),limit: pageSize + 1,})- const hasMore = rows.length > pageSize- const threads = hasMore ? rows.slice(0, pageSize) : rows+ hasMore = rows.length > pageSize+ threads = hasMore ? rows.slice(0, pageSize) : rowsconst last = threads.at(-1)- const nextCursor = hasMore && last+ nextCursor = hasMore && last? encodeForumCreatedAtCursor({parentChannelId: channelId,createdAt: last.createdAt,@@ -68,67 +76,60 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {}): undefined- const parentMessageIds = threads- .map((thread) => thread.parentMessageId)- .filter((id): id is string => !!id)- const threadIds = threads.map((thread) => thread.id)- const [parentMessages, firstMessages, tags, participants] = await Promise.all([- includes.has("parentMessage")- ? queries.communityMessage.getMessagesByIds(db, parentMessageIds)- : Promise.resolve([]),- includes.has("firstMessage")- ? queries.communityMessage.getFirstMessageByChannelIds(db, threadIds)- : Promise.resolve([]),- includes.has("tags")- ? queries.communityMessageTag.listTagsForMessages(db, parentMessageIds)- : Promise.resolve([]),- includes.has("participants")- ? queries.communityThread.listParticipantsForChannels(db, threadIds, 5)- : Promise.resolve([]),- ])-- return writeJSON({- serverId: access.value.channel.serverId,- parentType: access.value.channel.type,- threads,- included: { parentMessages, firstMessages, tags, participants },- hasMore,- ...(nextCursor ? { nextCursor } : {}),- })- }-- let childChannels = await queries.communityChannel.listChildChannels(db, channelId, {+ } else {+ threads = await queries.communityChannel.listChildChannels(db, channelId, {archived,type: "thread",})- const forum = isForum(access.value.channel.type)- const openerIds = childChannels.map((child) => child.parentMessageId).filter((id): id is string => !!id)- const archivedOpeners = forum- ? new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, FORUM_ARCHIVE_TAG))- : new Set<string>()+ const forum = isForum(channel.type)+ const openerIds = threads.map((child) => child.parentMessageId).filter((id): id is string => !!id)+ const archivedOpeners = forum+ ? new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, FORUM_ARCHIVE_TAG))+ : new Set<string>()- if (rawTag !== null) {- const matching = tag === FORUM_ARCHIVE_TAG- ? archivedOpeners- : new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, tag!))- childChannels = childChannels.filter((child) => (- !!child.parentMessageId- && matching.has(child.parentMessageId)- && (tag === FORUM_ARCHIVE_TAG || !archivedOpeners.has(child.parentMessageId))- ))- } else if (forum) {- childChannels = childChannels.filter((child) => (- !child.parentMessageId || !archivedOpeners.has(child.parentMessageId)- ))+ if (rawTag !== null) {+ const matching = tag === FORUM_ARCHIVE_TAG+ ? archivedOpeners+ : new Set(await queries.communityMessageTag.filterMessageIdsByTag(db, openerIds, tag!))+ threads = threads.filter((child) => (+ !!child.parentMessageId+ && matching.has(child.parentMessageId)+ && (tag === FORUM_ARCHIVE_TAG || !archivedOpeners.has(child.parentMessageId))+ ))+ } else if (forum) {+ threads = threads.filter((child) => (+ !child.parentMessageId || !archivedOpeners.has(child.parentMessageId)+ ))+ }}- // Plain nested collection representation. View-specific parent previews,- // first messages, tags, participants, and creator presentation are composed- // by consumers through the generic batch resource reads.+ const parentMessageIds = threads+ .map((thread) => thread.parentMessageId)+ .filter((id): id is string => !!id)+ const threadIds = threads.map((thread) => thread.id)+ const [parentMessages, firstMessages, tags, participants] = await Promise.all([+ includes.has("parentMessage")+ ? queries.communityMessage.getMessagesByIdsInScope(db, parentMessageIds, { channelId })+ : Promise.resolve([]),+ includes.has("firstMessage")+ ? queries.communityMessage.getFirstMessageResourcesByChannelIds(db, threadIds)+ : Promise.resolve([]),+ includes.has("tags")+ ? queries.communityMessageTag.listTagsForMessages(db, parentMessageIds)+ : Promise.resolve([]),+ includes.has("participants")+ ? queries.communityThread.listParticipantsForChannels(db, threadIds, 5)+ : Promise.resolve([]),+ ])++ if (currentContract) {+ return writeCommunityThreadsRead(db, ctx.userId, channel, threads, { messages: [...parentMessages, ...firstMessages], tags, participants }, { hasMore, nextCursor: nextCursor ?? null })+ }return writeJSON({- serverId: access.value.channel.serverId,- parentType: access.value.channel.type,- threads: childChannels,+ serverId: channel.serverId,+ parentType: channel.type,+ threads,+ ...(order === "createdAt" || includes.size ? { included: { parentMessages, firstMessages: firstMessages.map(({ channelId, content }) => ({ channelId, content })), tags, participants }, hasMore, ...(nextCursor ? { nextCursor } : {}) } : {}),})})diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.tsindex 044021b8a..acbe26e0c 100644--- a/src/web/src/app/api/community/messages/[id]/route.ts+++ b/src/web/src/app/api/community/messages/[id]/route.ts@@ -18,8 +18,7 @@ import {fanOutToChannel,fanOutToServerMembers,} from "@/lib/community/fanout"-import { groupAttachments, groupReactions } from "@/lib/community/messages"-import { mapMessageForApi } from "@/lib/community/message-payload"+import { loadApiMessageContext, mapMessageForApi } from "@/lib/community/message-payload"import { scheduleForumPostMediaCleanup } from "@/lib/community/forum-post-media-cleanup"// A bot addresses by ref-in-query (`?ref=` + `?seq=`, the folded `resolve`@@ -242,21 +241,11 @@ async function handleHumanGet(if (!auth.ok) return writeError(auth.error, auth.status)}- const [allAttachments, allReactions, replyMessages] = await Promise.all([- queries.communityAttachment.listByMessageIds(db, [messageId]),- queries.communityReaction.listReactionsByMessageIds(db, [messageId], userId),- message.replyToId+ const contextForChannel = await loadApiMessageContext(db, userId, [messageId], () => message.replyToId? queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId], { channelId: message.channelId }): Promise.resolve([]),- ])-- const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, userId)- // Reply target already scoped to the SAME surface as the parent — a reply- // preview must not leak content from a different channel/DM.- const replyMap = new Map(replyMessages.map((m) => [m.id, m]))-- const payload = mapMessageForApi(message, { replyMap, attachmentsByMessage, reactionsByMessage })+ )+ const payload = mapMessageForApi(message, contextForChannel(message.channelId))return writeJSON({ ...payload, channelId: message.channelId })}diff --git a/src/web/src/app/api/community/messages/batch/route.test.ts b/src/web/src/app/api/community/messages/batch/route.test.tsindex cedbe8667..617a855f9 100644--- a/src/web/src/app/api/community/messages/batch/route.test.ts+++ b/src/web/src/app/api/community/messages/batch/route.test.ts@@ -18,7 +18,7 @@ vi.mock("@alook/shared", async () => {communityMessage: {...actual.queries.communityMessage,getMessagesByIdsInScope: (...args: unknown[]) => mockGetMessagesByIdsInScope(...args),- getFirstMessageByChannelIds: (...args: unknown[]) => mockGetFirstMessageByChannelIds(...args),+ getFirstMessageResourcesByChannelIds: (...args: unknown[]) => mockGetFirstMessageByChannelIds(...args),},communityChannel: {...actual.queries.communityChannel,diff --git a/src/web/src/app/api/community/messages/batch/route.ts b/src/web/src/app/api/community/messages/batch/route.tsindex d1960c364..acc9bb959 100644--- a/src/web/src/app/api/community/messages/batch/route.ts+++ b/src/web/src/app/api/community/messages/batch/route.ts@@ -21,6 +21,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const messages = await queries.communityMessage.getMessagesByIdsInScope(db, ids, { channelId: body.channelId })const childThreads = await queries.communityChannel.getDirectChildThreadsByIds(db, body.channelId, firstInChannelIds)if (childThreads.length !== firstInChannelIds.length) return writeError("thread not found", 404)- const firstMessages = await queries.communityMessage.getFirstMessageByChannelIds(db, firstInChannelIds)+ const firstMessages = await queries.communityMessage.getFirstMessageResourcesByChannelIds(db, firstInChannelIds).then((rows) => rows.map(({ channelId, content }) => ({ channelId, content })))return writeJSON({ messages, firstMessages })})diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.tsindex 32505ce24..fa9225e5c 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {},communityMessage: {...actual.queries.communityMessage,- getMessagesByIds: (...args: unknown[]) => mockGetMessagesByIds(...args),+ getMessagesByIdsInChannels: (...args: unknown[]) => mockGetMessagesByIds(...args),},communityInbox: {...actual.queries.communityInbox,@@ -120,7 +120,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {serverNow: "2026-08-08T12:00:00.000Z",})expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["thread_1"])- expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["message_1"])+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["message_1"], ["forum_visible"])} finally {vi.useRealTimers()}@@ -193,7 +193,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {retainedDisposition: "opener-archived",included: { parentMessages: [] },})- expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), [])+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), [], ["forum_visible"])})it("rejects a partial or oversized sidebar query without reading child threads", async () => {diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.tsindex a235d72c0..cfdf36d3d 100644--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts@@ -74,7 +74,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {.map((channel) => channel.parentMessageId).filter((id): id is string => !!id)const [parentMessages, unreadRows] = await Promise.all([- queries.communityMessage.getMessagesByIds(db, parentMessageIds),+ queries.communityMessage.getMessagesByIdsInChannels(db, parentMessageIds, forumIds),queries.communityInbox.listEligibleUnreadChannels(db, ctx.actor.userId, rows.map((channel) => channel.id)),])const unreadIds = new Set(unreadRows.map((row) => row.channelId))diff --git a/src/web/src/app/api/community/users/[userId]/block/route.test.ts b/src/web/src/app/api/community/users/[userId]/block/route.test.tsindex 80bb763c0..4f3b76cad 100644--- a/src/web/src/app/api/community/users/[userId]/block/route.test.ts+++ b/src/web/src/app/api/community/users/[userId]/block/route.test.ts@@ -65,6 +65,9 @@ describe("POST /api/community/users/[userId]/block", () => {expect(blockCall).toBeDefined()expect(blockCall![0]).toBe("u2")expect(blockCall![1]).toEqual({ type: "community:friend.block", userId: "u1" })+ expect(broadcastToUser.mock.calls.filter(([target]) => target === "u1")).toEqual([+ ["u1", { type: "community:friend.block", userId: "u2", blockedByViewer: true }],+ ])})it("blocking an existing friend also broadcasts friend.remove with the prior friendship id", async () => {diff --git a/src/web/src/app/api/community/users/[userId]/block/route.ts b/src/web/src/app/api/community/users/[userId]/block/route.tsindex eb4cd1cc5..325a190ee 100644--- a/src/web/src/app/api/community/users/[userId]/block/route.ts+++ b/src/web/src/app/api/community/users/[userId]/block/route.ts@@ -26,6 +26,7 @@ export const POST = withAuth(async (_req, ctx) => {type: WS_EVENTS.FRIEND_BLOCK,userId: ctx.userId,})+ broadcastToUserSafe(ctx.userId, { type: WS_EVENTS.FRIEND_BLOCK, userId: targetId, blockedByViewer: true })// If blocking tore down an existing accepted friendship, tell the other// side so their friend list reflects it.diff --git a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx b/src/web/src/app/c/QueryProvider.observability.dom.test.tsxindex a0a95669a..f50d5c137 100644--- a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx+++ b/src/web/src/app/c/QueryProvider.observability.dom.test.tsx@@ -3,7 +3,7 @@ import { useLayoutEffect } from "react"import { dehydrate, QueryClient, useIsRestoring, useQueryClient } from "@tanstack/react-query"import { afterEach, beforeEach, expect, it, vi } from "vitest"import { act, render, waitFor } from "@/test/react-dom-harness"-import { clearAllPersistedCaches, createIdbPersister, PERSIST_BUSTER } from "@/lib/query-persister"+import { clearAllPersistedCaches, createIdbPersister, PERSIST_BUSTER, PERSIST_CACHE_PREFIX } from "@/lib/query-persister"import { communityKeys } from "@/lib/query-keys"import { valueEvidence } from "@/lib/observability/data-source"import { setTelemetryUser } from "@/lib/observability/client"@@ -40,11 +40,10 @@ async function seed(id: string) {function holdRead(id: string) {const original = IDBObjectStore.prototype.getlet release: (() => void) | undefined- let held = false+ let reads = 0vi.spyOn(IDBObjectStore.prototype, "get").mockImplementation(function (this: IDBObjectStore, requestKey: IDBValidKey | IDBKeyRange) {const request = original.call(this, requestKey)- if (requestKey === `alook:qc:v3:${id}:client` && !held) {- held = true+ if (requestKey === `${PERSIST_CACHE_PREFIX}:${id}:client` && ++reads === 2) {let success: IDBRequest["onsuccess"] = nullObject.defineProperty(request, "onsuccess", {configurable: true,diff --git a/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx b/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsxindex 96f12497a..0cfa61507 100644--- a/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx+++ b/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx@@ -26,6 +26,7 @@ const persister = vi.hoisted(() => ({removeClient: vi.fn(() => Promise.resolve()),isCurrent: vi.fn(async () => true),retireAccount: vi.fn(async () => {}),+ retireChannels: vi.fn(async () => {}),}))const session = vi.hoisted(() => ({ viewer: "restore-order-viewer" }))vi.mock("@/lib/auth-client", () => ({@@ -50,14 +51,11 @@ import { applyTypingIndicator } from "@/hooks/community/community-ws/typing"import { useCommunityStore } from "@/stores/community"import { apiFetchProfiles } from "@/lib/community/profile-seed"import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn() }) }))+vi.mock("next/navigation", () => ({ usePathname: () => "/c/channels/server-1/post-1", useRouter: () => ({ replace: vi.fn() }) }))vi.mock("@/hooks/community/use-servers", async (importOriginal) => ({...await importOriginal<typeof import("@/hooks/community/use-servers")>(),useServer: () => ({ server: { id: "strict-server", categories: [{ id: "strict-category", channels: [{ id: "strict-route", type: "text" }] }] } }),}))-vi.mock("@/hooks/community/use-child-channel-meta", () => ({- useChildChannelMeta: () => ({ isVerified: true, isFetching: false, isError: false, refetch: vi.fn() }),-}))afterEach(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex 411d4b4f4..75432c0ad 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -169,7 +169,7 @@ function ScopedQueryProvider({const [persister] = useState(() => createIdbPersister(userId))const active = useSelector(communityDb.runtime.lifecycle, (state) => state.active)const router = useRouter()- useLayoutEffect(() => { communityDb.bindAuthentication(sessionViewer, persister.retireAccount) }, [communityDb, sessionViewer, persister])+ useLayoutEffect(() => { communityDb.bindAuthentication(sessionViewer, persister.retireAccount, persister.retireChannels) }, [communityDb, sessionViewer, persister])const retireTelemetryIdentity = useRef<() => void>(() => undefined)useLayoutEffect(() => { setTelemetryUser(userId); retireTelemetryIdentity.current = captureTelemetryIdentityRetirement() }, [userId])const identityRetired = useRef(false)diff --git a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.tsindex af647a14a..7fda08d59 100644--- a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts+++ b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts@@ -11,10 +11,14 @@ const {mockDms,mockStore,mockHistory,+ mockBlocked,+ mockNavigationGate,} = vi.hoisted(() => ({mockDismissConversation: vi.fn(),mockCommitRoute: vi.fn(),- mockHistory: { allowed: true, error: null as Error | null, retry: vi.fn() },+ mockHistory: { allowed: true, denied: false, error: null as Error | null, retry: vi.fn() },+ mockBlocked: [] as Array<{ userId: string }>,+ mockNavigationGate: { allowed: true, failed: false, retry: vi.fn() },mockDms: {dms: [] as Array<{id: string@@ -41,7 +45,9 @@ vi.mock("next/navigation", () => ({}))vi.mock("sonner", () => ({ toast: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))-vi.mock("@/components/community/channels/dm-header", () => ({ DmHeader: () => null }))+vi.mock("@/components/community/channels/dm-header", () => ({+ DmHeader: ({ dm }: { dm: { name: string } }) => React.createElement("div", { "data-testid": "dm-header" }, dm.name),+}))vi.mock("@/components/community/channels/dm-loading-frame", () => ({DmLoadingFrame: () => React.createElement("div", { "data-testid": "dm-loading" }),}))@@ -52,7 +58,11 @@ vi.mock("@/components/community/channels/conversation-resolution-error-frame", (ConversationResolutionErrorFrame: ({ onRetry }: { onRetry: () => void }) => React.createElement("button", { onClick: onRetry, "data-testid": "history-error" }, "Retry"),}))vi.mock("@/hooks/community/use-channel-metadata", () => ({- useChannelMetadata: () => ({ isVerified: true, data: { historyVerification: mockHistory.allowed ? {} : undefined } }),+ useChannelMetadata: () => ({ canRead: mockHistory.allowed, denied: mockHistory.denied, data: { readProof: mockHistory.allowed ? {} : undefined } }),+}))+vi.mock("@/lib/community/conversation-navigation-proof", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/lib/community/conversation-navigation-proof")>(),+ useConversationNavigationGate: () => mockNavigationGate,}))vi.mock("@/hooks/community/channel-metadata", () => ({ isChannelMetadataTokenCurrent: () => true }))vi.mock("@/lib/community/last-community-route", () => ({ commitCommunityChannelRoute: mockCommitRoute }))@@ -82,7 +92,7 @@ vi.mock("@/lib/community/display-name", () => ({}))vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => mockDms }))vi.mock("@/hooks/community/use-friends", () => ({- useFriends: () => ({ friends: [], blocked: [] }),+ useFriends: () => ({ friends: [], blocked: mockBlocked }),}))vi.mock("@/hooks/community/use-messages", () => ({useDmMessages: () => ({@@ -146,7 +156,8 @@ vi.mock("@/lib/community-onboarding", () => ({advanceCommunityOnboarding: vi.fn(),readCommunityOnboardingState: () => null,}))-vi.mock("@alook/shared", () => ({ notifLevelDisplay: () => "all" }))+vi.mock("@alook/shared", async (importOriginal) => ({+ ...await importOriginal<typeof import("@alook/shared")>(), notifLevelDisplay: () => "all" }))vi.mock("@/hooks/community/use-notification-settings", () => ({useNotificationSettings: () => ({ channel: {} }),}))@@ -154,7 +165,6 @@ vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))vi.mock("@/lib/community/reply-content", () => ({ displayReplyContent: () => "" }))vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),useCanonicalProfilesByUserId: () => new Map(),- useReadStateProjection: () => null,}))vi.mock("@/hooks/community/use-native-system-notifications", () => ({useNativeSystemNotificationConversationDismissal: (...args: unknown[]) =>@@ -167,8 +177,13 @@ describe("DM notification dismissal readiness", () => {mockCommitRoute.mockClear()mockDmMessages.navigationBlocked = falsemockHistory.allowed = true+ mockHistory.denied = falsemockHistory.error = nullmockHistory.retry.mockClear()+ mockBlocked.length = 0+ mockNavigationGate.allowed = true+ mockNavigationGate.failed = false+ mockNavigationGate.retry.mockClear()mockDms.dms = []mockDms.isLoading = false})@@ -217,4 +232,66 @@ describe("DM notification dismissal readiness", () => {expect(view.container.querySelector('[data-testid="composer"]')).not.toBeNull()expect(mockCommitRoute).toHaveBeenCalledExactlyOnceWith("viewer_1", null, "dm_1")})++ it.each([+ ["own Block", "pending"],+ ["own Block", "failed"],+ ["denied", "pending"],+ ["denied", "failed"],+ ] as const)("keeps %s terminal state visible over %s navigation and an old read error", (terminal, navigation) => {+ mockDms.dms = [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }]+ mockHistory.allowed = false+ mockHistory.denied = terminal === "denied"+ mockHistory.error = new Error("old read failure")+ if (terminal === "own Block") mockBlocked.push({ userId: "peer_1" })+ mockDmMessages.navigationBlocked = true+ mockNavigationGate.allowed = false+ mockNavigationGate.failed = navigation === "failed"++ const view = render(React.createElement(DmView, { dmId: "dm_1" }))++ expect(view.container.querySelector('[data-testid="dm-header"]')?.textContent).toBe("Peer")+ expect(view.container.querySelector('[data-slot="community-conversation-surface"][data-channel-id="dm_1"]')).not.toBeNull()+ for (const testId of ["dm-loading", "dm-error", "history-error", "history-body", "composer", "composer-pending"]) {+ expect(view.container.querySelector(`[data-testid="${testId}"]`)).toBeNull()+ }+ expect(view.container.textContent).not.toContain("Retry")+ if (terminal === "own Block") {+ expect(view.container.querySelector('[data-testid="dm-blocked"]')?.textContent).toContain("You have blocked this user.")+ expect(view.container.querySelector('[role="alert"]')).toBeNull()+ } else {+ expect(view.container.querySelector('[role="alert"]')?.textContent).toBe("You can no longer read this conversation.")+ expect(view.container.querySelector('[data-testid="dm-blocked"]')).toBeNull()+ }+ expect(mockCommitRoute).not.toHaveBeenCalled()+ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith("viewer_1", { kind: "dm", channelId: "dm_1" }, false)+ expect(mockHistory.retry).not.toHaveBeenCalled()+ expect(mockNavigationGate.retry).not.toHaveBeenCalled()+ })++ it.each(["pending", "failed"] as const)("retains the %s navigation gate for a readable DM", (navigation) => {+ mockDms.dms = [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }]+ mockDmMessages.navigationBlocked = true+ mockNavigationGate.allowed = false+ mockNavigationGate.failed = navigation === "failed"++ const view = render(React.createElement(DmView, { dmId: "dm_1" }))++ expect(view.container.querySelector('[data-testid="dm-header"]')).toBeNull()+ expect(view.container.querySelector('[data-testid="history-body"]')).toBeNull()+ expect(view.container.querySelector('[data-testid="composer"]')).toBeNull()+ expect(view.container.querySelector('[data-testid="dm-blocked"]')).toBeNull()+ expect(view.container.querySelector('[role="alert"]')).toBeNull()+ if (navigation === "pending") {+ expect(view.container.querySelector('[data-testid="dm-loading"]')).not.toBeNull()+ expect(view.container.querySelector('[data-testid="history-error"]')).toBeNull()+ } else {+ expect(view.container.querySelector('[data-testid="dm-loading"]')).toBeNull()+ view.container.querySelector<HTMLButtonElement>('[data-testid="history-error"]')!.click()+ expect(mockNavigationGate.retry).toHaveBeenCalledOnce()+ expect(mockHistory.retry).not.toHaveBeenCalled()+ }+ expect(mockCommitRoute).not.toHaveBeenCalled()+ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith("viewer_1", { kind: "dm", channelId: "dm_1" }, false)+ })})diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.tsindex ad4300f4d..b841612bf 100644--- a/src/web/src/app/c/me/[dmId]/page.test.ts+++ b/src/web/src/app/c/me/[dmId]/page.test.ts@@ -10,7 +10,8 @@ describe("DM page loading ownership", () => {expect(source).not.toContain("currentChannelMatches")expect(source).not.toContain("readSnapshotFetching ||\n messagesLoading")expect(source).toContain("waitForAnchor: true")- expect(source).toContain("if (navigationBlocked)")+ expect(source).toContain("if (!metadata.denied && !dmBlocked && navigationBlocked)")+ expect(source).toContain("if (!metadata.denied && !dmBlocked && navigationGate.failed)")expect(source).toContain("if (loadingOwnership.fullFramePending)")expect(source).toContain("<DmHeader\n")expect(source).toContain("<Composer\n")diff --git a/src/web/src/app/sw.test.ts b/src/web/src/app/sw.test.tsindex f5ec7080d..bcdbd5010 100644--- a/src/web/src/app/sw.test.ts+++ b/src/web/src/app/sw.test.ts@@ -1,159 +1,27 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import type { PrecacheEntry, Route, Serwist } from "serwist"--type WorkerOptions = ConstructorParameters<typeof Serwist>[0]--const boundary = vi.hoisted(() => ({- options: [] as WorkerOptions[],- routes: [] as Route[],- match: vi.fn(),- listeners: vi.fn(),-}))--vi.mock("serwist", async importOriginal => {- const actual = await importOriginal<typeof import("serwist")>()- return {- ...actual,- Serwist: class {- routes: Map<"GET", Route[]>-- constructor(options: WorkerOptions) {- const route = new actual.Route(boundary.match, async () => new Response("public bytes"))- this.routes = new Map([["GET", [route]]])- boundary.options.push(options)- boundary.routes.push(route)- }-- addEventListeners() {- boundary.listeners(this.routes)- }- },- }-})--const origin = "https://alook.ai"-const asset = "/_next/static/chunks/public-a.js"-const manifest: PrecacheEntry[] = [{ url: asset, revision: "revision-a" }]-const params = { cacheKey: `${origin}${asset}?__SW_REVISION__=revision-a` }-const request = (path = asset, init?: RequestInit) => new Request(new URL(path, origin), init)-const event = () => new Event("fetch") as FetchEvent-const matchOptions = (req: Request) => ({ request: req, url: new URL(req.url), sameOrigin: new URL(req.url).origin === origin, event: event() })-const response = (headers?: HeadersInit, status = 200) => new Response("public bytes", {- status,- headers: { "Cache-Control": "public, max-age=31536000, immutable", "Content-Type": "application/javascript", ...headers },-})--async function loadWorker(entries: PrecacheEntry[] | undefined = manifest) {- vi.stubGlobal("self", { __SW_MANIFEST: entries, location: { origin } })- await import("./sw")- expect(boundary.options).toHaveLength(1)- expect(boundary.routes).toHaveLength(1)- return { options: boundary.options[0], route: boundary.routes[0] }-}--describe("public service worker entry", () => {- beforeEach(() => {- vi.resetModules()- boundary.options.length = 0- boundary.routes.length = 0- boundary.match.mockReset().mockReturnValue(params)- boundary.listeners.mockReset()- })-- afterEach(() => vi.unstubAllGlobals())-- it("hands the injected manifest to the public precache without broad runtime caching", async () => {- const { options } = await loadWorker()- expect(options.precacheEntries).toBe(manifest)- expect(options).toMatchObject({- cacheId: "alook-public-v1",- clientsClaim: true,- precacheOptions: {- cacheName: "alook-public-precache-v1",- cleanURLs: false,- directoryIndex: null,- ignoreURLParametersMatching: [],- },- })- expect(options.precacheOptions?.plugins).toHaveLength(1)- expect(options).not.toHaveProperty("runtimeCaching")- expect(options).not.toHaveProperty("skipWaiting")- })-- it("does not invent a manifest when injection is absent", async () => {- vi.stubGlobal("self", { __SW_MANIFEST: undefined, location: { origin } })+import { afterEach, describe, expect, it, vi } from "vitest"++afterEach(() => { vi.unstubAllGlobals(); vi.resetModules() })++describe("public worker activation", () => {+ it("runs actual Serwist activation and deletes old custom cache names without changing the current cache", async () => {+ const names = new Set(["alook-public-precache-v0", "alook-public-precache-v1", "alook-public-v99-runtime", "unrelated-cache"])+ const storage = { keys: vi.fn(async () => [...names]), delete: vi.fn(async (name: string) => names.delete(name)),+ open: vi.fn(async (name: string) => { names.add(name); return { keys: async () => [] as Request[] } }) }+ const listeners = new Map<string, Array<(event: { waitUntil: (promise: Promise<unknown>) => void }) => unknown>>()+ const location = new URL("https://example.test/sw.js")+ const worker = { __SW_MANIFEST: [], location, caches: storage, registration: { scope: "https://example.test/" }, clients: { claim: vi.fn(async () => undefined) },+ addEventListener: (type: string, listener: (event: { waitUntil: (promise: Promise<unknown>) => void }) => unknown) => listeners.set(type, [...listeners.get(type) ?? [], listener]) }+ vi.stubGlobal("self", worker)+ vi.stubGlobal("location", location)+ vi.stubGlobal("caches", storage)await import("./sw")- expect(boundary.options[0].precacheEntries).toBeUndefined()- })-- it("installs the request guard before attaching listeners and preserves revision parameters", async () => {- boundary.listeners.mockImplementation((routes: Map<"GET", Route[]>) => {- const route = routes.get("GET")![0]- expect(route.match(matchOptions(request(asset, { headers: { Authorization: "test" } })))).toBe(false)- expect(route.match(matchOptions(request()))).toBe(params)- })- const { route } = await loadWorker()- expect(boundary.listeners).toHaveBeenCalledOnce()- expect(boundary.match).toHaveBeenCalledOnce()- expect(route.match(matchOptions(request()))).toBe(params)- })-- it("rejects private, RSC, credential, navigation, write, query and cross-origin requests", async () => {- const { route } = await loadWorker()- const navigation = request()- Object.defineProperty(navigation, "mode", { value: "navigate" })- const document = request()- Object.defineProperty(document, "destination", { value: "document" })- const rejected = [- request("/api/auth/get-session"),- request("/c"),- request(asset, { headers: { RSC: "1" } }),- request(asset, { headers: { Cookie: "session=test" } }),- request(asset, { headers: { Authorization: "test" } }),- request(asset, { method: "POST" }),- request(`${asset}?_rsc=account`),- request(`https://other.example${asset}`),- navigation,- document,- ]- for (const req of rejected) expect(route.match(matchOptions(req))).toBe(false)- expect(boundary.match).not.toHaveBeenCalled()- })-- it("downloads public precache assets anonymously and rejects redirects", async () => {- const { options } = await loadWorker()- const original = request(asset, { credentials: "include", redirect: "follow" })- const plugin = options.precacheOptions!.plugins![0]- const anonymous = await plugin.requestWillFetch!({ request: original, event: event() })- expect(anonymous).not.toBe(original)- expect(anonymous.url).toBe(original.url)- expect(anonymous.method).toBe("GET")- expect(anonymous.credentials).toBe("omit")- expect(anonymous.redirect).toBe("error")- expect(original.credentials).toBe("include")- expect(original.redirect).toBe("follow")- })-- it("writes only explicitly public asset responses through the installed plugin", async () => {- const { options } = await loadWorker()- const plugin = options.precacheOptions!.plugins![0]- const publicResponse = response()- expect(await plugin.cacheWillUpdate!({ request: request(), response: publicResponse, event: event() })).toBe(publicResponse)- const rejected = [- response({ "Cache-Control": "private, max-age=600" }),- response({ "Cache-Control": "public, no-store" }),- response({ "Set-Cookie": "session=test" }),- response({ Vary: "Cookie" }),- response({ "Content-Type": "text/html" }),- response({ "Content-Type": "text/x-component" }),- response({}, 404),- ]- const redirected = response()- Object.defineProperty(redirected, "redirected", { value: true })- rejected.push(redirected)- for (const res of rejected) {- expect(await plugin.cacheWillUpdate!({ request: request(), response: res, event: event() })).toBeNull()- }- expect(await plugin.cacheWillUpdate!({ request: request("/api/community/files/attachment"), response: publicResponse, event: event() })).toBeNull()+ const pending: Promise<unknown>[] = []+ for (const listener of listeners.get("activate") ?? []) listener({ waitUntil: promise => { pending.push(promise) } })+ await Promise.all(pending)+ expect(worker.clients.claim).toHaveBeenCalledOnce()+ expect(names).toEqual(new Set(["alook-public-precache-v1", "unrelated-cache"]))+ expect(storage.delete.mock.calls.map(([name]) => name)).toEqual(["alook-public-precache-v0", "alook-public-v99-runtime"])+ expect(storage.open).toHaveBeenCalledWith("alook-public-precache-v1")+ expect(listeners.has("fetch")).toBe(true)})})diff --git a/src/web/src/app/sw.ts b/src/web/src/app/sw.tsindex b1a91f8c9..dd47c9f92 100644--- a/src/web/src/app/sw.ts+++ b/src/web/src/app/sw.ts@@ -2,6 +2,9 @@import type { PrecacheEntry, SerwistGlobalConfig } from "serwist"import { Serwist } from "serwist"import { isPublicAssetResponse, restrictPublicPrecacheRoutes } from "../lib/service-worker/public-cache"+import { publicWorkerCacheNames } from "../lib/service-worker/cache-identity"++import { clearOutdatedPublicWorkerCaches } from "../lib/service-worker/public-cache-storage"declare global {interface WorkerGlobalScope extends SerwistGlobalConfig {@@ -13,10 +16,10 @@ declare const self: ServiceWorkerGlobalScopeconst serwist = new Serwist({precacheEntries: self.__SW_MANIFEST,- cacheId: "alook-public-v1",+ cacheId: publicWorkerCacheNames().cacheId,clientsClaim: true,precacheOptions: {- cacheName: "alook-public-precache-v1",+ cacheName: publicWorkerCacheNames().precache,cleanURLs: false,directoryIndex: null,ignoreURLParametersMatching: [],@@ -29,3 +32,5 @@ const serwist = new Serwist({restrictPublicPrecacheRoutes(serwist, self.location.origin)serwist.addEventListeners()++self.addEventListener("activate", event => event.waitUntil(clearOutdatedPublicWorkerCaches()))diff --git a/src/web/src/components/community/bots/model-field-select.dom.test.tsx b/src/web/src/components/community/bots/model-field-select.dom.test.tsxindex 38ff8d6d8..a14e39da0 100644--- a/src/web/src/components/community/bots/model-field-select.dom.test.tsx+++ b/src/web/src/components/community/bots/model-field-select.dom.test.tsx@@ -1,6 +1,6 @@import React from "react"import { describe, expect, it, vi } from "vitest"-import { fireEvent, render, screen } from "@/test/react-dom-harness"+import { act, fireEvent, render, screen } from "@/test/react-dom-harness"import { ModelField } from "./model-field"const runtime = {@@ -16,38 +16,38 @@ const runtime = {}describe("ModelField with the real Select", () => {- it("filters an edited model without changing its selection", () => {+ it("filters an edited model without changing its selection", async () => {const onChange = vi.fn()render(<ModelField runtime={runtime} value="gemini-3.1-pro-high" onChange={onChange} />)expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")- fireEvent.click(screen.getByTestId("bot-model-select"))+ await act(async () => { fireEvent.click(screen.getByTestId("bot-model-select")) })const filter = screen.getByTestId("bot-model-filter-input")- fireEvent.change(filter, { target: { value: "gemini-3.1-pro-low" } })+ await act(async () => { fireEvent.change(filter, { target: { value: "gemini-3.1-pro-low" } }) })expect(filter).toHaveValue("gemini-3.1-pro-low")expect(onChange).not.toHaveBeenCalled()expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")expect(screen.getByTestId("bot-model-probe-results").querySelectorAll('[role="option"]')).toHaveLength(1)- fireEvent.click(screen.getByRole("option", { name: "gemini-3.1-pro-low" }))+ await act(async () => { fireEvent.click(screen.getByRole("option", { name: "gemini-3.1-pro-low" })) })expect(onChange).toHaveBeenLastCalledWith("gemini-3.1-pro-low")})- it("keeps explicit Default selectable while the current model is filtered out", () => {+ it("keeps explicit Default selectable while the current model is filtered out", async () => {const onChange = vi.fn()render(<ModelField runtime={runtime} value="gemini-3.1-pro-high" onChange={onChange} />)- fireEvent.click(screen.getByTestId("bot-model-select"))+ await act(async () => { fireEvent.click(screen.getByTestId("bot-model-select")) })const filter = screen.getByTestId("bot-model-filter-input")- fireEvent.change(filter, { target: { value: "no-match" } })+ await act(async () => { fireEvent.change(filter, { target: { value: "no-match" } }) })expect(filter).toHaveValue("no-match")expect(screen.getByRole("status")).toHaveTextContent("No matching models")expect(onChange).not.toHaveBeenCalled()expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")const option = screen.getByRole("option", { name: "Default (antigravity's own default)" })- fireEvent.pointerDown(option, { pointerType: "mouse" })- fireEvent.click(option)+ await act(async () => { fireEvent.pointerDown(option, { pointerType: "mouse" }) })+ await act(async () => { fireEvent.click(option) })expect(onChange).toHaveBeenLastCalledWith(null)})- it("preserves a model chosen after opening a create form with Default", () => {+ it("preserves a model chosen after opening a create form with Default", async () => {const onChange = vi.fn()function CreateModel() {const [value, setValue] = React.useState<string | null>(null)@@ -57,15 +57,15 @@ describe("ModelField with the real Select", () => {}} />}render(<CreateModel />)- fireEvent.click(screen.getByTestId("bot-model-select"))+ await act(async () => { fireEvent.click(screen.getByTestId("bot-model-select")) })const high = screen.getByRole("option", { name: "gemini-3.1-pro-high" })- fireEvent.pointerDown(high, { pointerType: "mouse" })- fireEvent.click(high)+ await act(async () => { fireEvent.pointerDown(high, { pointerType: "mouse" }) })+ await act(async () => { fireEvent.click(high) })expect(onChange).toHaveBeenLastCalledWith("gemini-3.1-pro-high")onChange.mockClear()- fireEvent.click(screen.getByTestId("bot-model-select"))+ await act(async () => { fireEvent.click(screen.getByTestId("bot-model-select")) })const filter = screen.getByTestId("bot-model-filter-input")- fireEvent.change(filter, { target: { value: "gemini-3.1-pro-low" } })+ await act(async () => { fireEvent.change(filter, { target: { value: "gemini-3.1-pro-low" } }) })expect(filter).toHaveValue("gemini-3.1-pro-low")expect(screen.getByTestId("bot-model-select")).toHaveTextContent("gemini-3.1-pro-high")expect(onChange).not.toHaveBeenCalled()diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex 94e31eac5..f0b39e2fd 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -290,9 +290,15 @@ vi.mock("@/hooks/community/mutations", () => ({useKickMember: () => ({ mutateAsync: vi.fn() }),useSetChannelNotif: () => ({ mutate: vi.fn() }),useUploadFile: () => ({ mutateAsync: vi.fn() }),- zipUploadResultsWithDimensions: () => [],+}))+vi.mock("@/hooks/community/mutations/messages", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/hooks/community/mutations/messages")>(),sendNonce: () => "nonce_1",}))+vi.mock("@/hooks/community/mutations/uploads", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/hooks/community/mutations/uploads")>(),+ zipUploadResultsWithDimensions: () => [],+}))vi.mock("@/hooks/community/use-community-ws", () => ({communityWsSendTyping: vi.fn(),communityWsEndTyping: vi.fn(),diff --git a/src/web/src/components/community/channels/dm-route.dom.test.ts b/src/web/src/components/community/channels/dm-route.dom.test.tsindex 222b71303..e9a1aa6b8 100644--- a/src/web/src/components/community/channels/dm-route.dom.test.ts+++ b/src/web/src/components/community/channels/dm-route.dom.test.ts@@ -17,7 +17,7 @@ function render(node: React.ReactNode) {}const mocks = vi.hoisted(() => ({- verification: { status: "pending", retrying: false, retry: vi.fn() },+ verification: { status: "pending", identityKnown: false, retrying: false, retry: vi.fn() },breakpoint: "desktop",last: "dm-a",cold: false,@@ -26,7 +26,7 @@ const mocks = vi.hoisted(() => ({vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }) }))vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "viewer" }) }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))-vi.mock("@/hooks/community/use-dm-route-verification", () => ({ useDmRouteVerification: () => mocks.verification }))+vi.mock("@/hooks/community/use-channel-metadata", () => ({ useChannelMetadata: () => mocks.verification }))vi.mock("@/stores/community", async (importOriginal) => ({ ...await importOriginal<typeof import("@/stores/community")>(), useCommunityStore: { getState: () => ({ uiHandlers: { cancelPendingNavigation: mocks.cancel } }) } }))vi.mock("@/lib/community-db/sync", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/sync")>(), purgeCommunityChannel: mocks.purge }))vi.mock("@/lib/community/last-me-location", () => ({ ME_ROOT: "/c/me", getLastMeLeaf: () => mocks.last, clearLastMeLocation: mocks.clear }))@@ -45,6 +45,7 @@ vi.mock("./dm-route-error-frame", () => ({ DmRouteErrorFrame: ({ onRetry, retryibeforeEach(() => {mocks.verification.status = "pending"+ mocks.verification.identityKnown = falsemocks.verification.retrying = falsemocks.breakpoint = "desktop"mocks.last = "dm-a"@@ -59,14 +60,27 @@ describe("DM target main owns identity, retry and fallback", () => {expect(screen.getByTestId("dm-pending")).toHaveAttribute("data-back", "true")expect(route.container.querySelector("main")).toBeNull()expect(mocks.replace).not.toHaveBeenCalled()- mocks.verification.status = "present"+ mocks.verification.status = "readable"route.rerender(React.createElement(DmRoute, { dmId: "dm-b" }))expect(route.container.querySelector("main")).toHaveAttribute("data-channel-id", "dm-b")expect(route.container.textContent).not.toContain("dm-a")})+ it("keeps a known DM mounted during position wait and terminal denial", () => {+ mocks.verification.identityKnown = true+ const route = render(React.createElement(DmRoute, { dmId: "dm-a" }))+ const frame = route.container.querySelector("main")+ expect(frame).toHaveAttribute("data-channel-id", "dm-a")+ mocks.verification.status = "denied"+ route.rerender(React.createElement(DmRoute, { dmId: "dm-a" }))+ expect(route.container.querySelector("main")).toBe(frame)+ expect(screen.queryByTestId("dm-pending")).toBeNull()+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(mocks.clear).not.toHaveBeenCalled()+ })+it("keeps a transient error at the target and retries its resource without changing memory", async () => {- mocks.verification.status = "error"+ mocks.verification.status = "retryable-error"render(React.createElement(DmRoute, { dmId: "dm-a" }))await setupUser().click(screen.getByRole("button", { name: "Retry" }))expect(mocks.verification.retry).toHaveBeenCalledOnce()@@ -74,11 +88,11 @@ describe("DM target main owns identity, retry and fallback", () => {expect(mocks.clear).not.toHaveBeenCalled()})- it.each([false, true])("purges explicit denial and retires only matching last memory, cold=%s", (cold) => {- mocks.verification.status = "missing"+ it.each([false, true])("exits an unknown denied target and retires only matching last memory, cold=%s", (cold) => {+ mocks.verification.status = "denied"mocks.cold = coldrender(React.createElement(DmRoute, { dmId: "dm-a" }))- expect(mocks.purge).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ accountId: "viewer" }), "dm-a")+ expect(mocks.purge).not.toHaveBeenCalled()expect(mocks.clear).toHaveBeenCalledOnce()expect(mocks.cancel).toHaveBeenCalledOnce()expect(mocks.consume).toHaveBeenCalledExactlyOnceWith("viewer", "/c/me/dm-a")@@ -86,18 +100,18 @@ describe("DM target main owns identity, retry and fallback", () => {})it("does not erase another remembered DM when this target is denied", () => {- mocks.verification.status = "missing"+ mocks.verification.status = "denied"mocks.last = "dm-b"render(React.createElement(DmRoute, { dmId: "dm-a" }))expect(mocks.clear).not.toHaveBeenCalled()})it("keeps a consumed cold fallback through Strict Mode effect replay", () => {- mocks.verification.status = "missing"+ mocks.verification.status = "denied"mocks.cold = truerender(React.createElement(React.StrictMode, null, React.createElement(DmRoute, { dmId: "dm-a" })))expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/me/machines")expect(mocks.consume).toHaveBeenCalledOnce()- expect(mocks.purge).toHaveBeenCalledOnce()+ expect(mocks.purge).not.toHaveBeenCalled()})})diff --git a/src/web/src/components/community/channels/dm-route.tsx b/src/web/src/components/community/channels/dm-route.tsxindex f5e4880a3..85c611330 100644--- a/src/web/src/components/community/channels/dm-route.tsx+++ b/src/web/src/components/community/channels/dm-route.tsx@@ -5,12 +5,12 @@ import { useRouter } from "next/navigation"import { DmView } from "./dm-view"import { DmRouteErrorFrame } from "./dm-route-error-frame"import { DmLoadingFrame } from "./dm-loading-frame"-import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verification"+import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"import { useBreakpoint } from "@/hooks/use-mobile"import { useCurrentUser } from "@/contexts/community/current-user"import { useCommunityRuntime } from "@/stores/community/runtime"-import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"-import { purgeCommunityChannel } from "@/lib/community-db/sync"++import { clearLastMeLocation, getLastMeLeaf, ME_ROOT } from "@/lib/community/last-me-location"import {COMMUNITY_COLD_ENTRY_FALLBACK,@@ -22,11 +22,10 @@ export function DmRoute({ dmId }: { dmId: string }) {const router = useRouter()const currentUser = useCurrentUser()const breakpoint = useBreakpoint()- const registry = useOptionalCommunityDbRegistry()- const verification = useDmRouteVerification(dmId)+ const verification = useChannelMetadata(null, dmId)const exitedTarget = useRef<string | null>(null)useEffect(() => {- if (verification.status !== "missing") return+ if (verification.status !== "denied" || verification.identityKnown) returnconst target = JSON.stringify([currentUser.id, dmId])if (exitedTarget.current === target) returnexitedTarget.current = target@@ -34,17 +33,16 @@ export function DmRoute({ dmId }: { dmId: string }) {const destination = consumeCommunityColdEntryFailure(currentUser.id, href)? COMMUNITY_COLD_ENTRY_FALLBACK: ME_ROOT- if (registry) purgeCommunityChannel(registry, dmId)if (getLastMeLeaf() === dmId) clearLastMeLocation()runtime.ui.get().uiHandlers.cancelPendingNavigation?.()router.replace(destination)- }, [currentUser.id, dmId, registry, router, runtime, verification.status])+ }, [currentUser.id, dmId, router, runtime, verification.status, verification.identityKnown])- if (verification.status === "error") {+ if (verification.status === "retryable-error" && !verification.identityKnown) {return <DmRouteErrorFrame onRetry={verification.retry} retrying={verification.retrying}reserveBackSlot={breakpoint === "mobile"} />}- if (verification.status !== "present") {+ if (!verification.identityKnown && verification.status !== "readable") {return <DmLoadingFrame reserveBackSlot={breakpoint === "mobile"} />}return <DmView dmId={dmId} />diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsxindex a6067b64f..34ba634c3 100644--- a/src/web/src/components/community/channels/dm-view.tsx+++ b/src/web/src/components/community/channels/dm-view.tsx@@ -16,7 +16,7 @@ import {ConversationFooterShell,ConversationFooterSlotProvider,} from "@/components/community/messages/conversation-footer-shell"-import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"+import type { FileAttachment, ImagePreview, ReplyTarget } from "@/lib/community/models/message"import type { OpenProfile } from "@/components/community/social/profile-types"import {useUiHandlers,@@ -58,7 +58,6 @@ import { toastApiError } from "@/lib/api/client"import { displayReplyContent } from "@/lib/community/reply-content"import {useCanonicalProfilesByUserId,- useReadStateProjection,} from "@/lib/community-db/projections"import { useNativeSystemNotificationConversationDismissal } from "@/hooks/community/use-native-system-notifications"import { commitCommunityChannelRoute } from "@/lib/community/last-community-route"@@ -66,7 +65,6 @@ import { useQueryClient } from "@tanstack/react-query"import { useConversationNavigationGate } from "@/lib/community/conversation-navigation-proof"import { useCommunityWsStore } from "@/stores/community/ws"import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"-import { isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"import { ConversationResolutionErrorFrame } from "./conversation-resolution-error-frame"import { isConversationAccessError } from "@/lib/community/conversation-read"import { useDmSeqContext } from "./use-dm-seq-context"@@ -108,8 +106,7 @@ export function DmView({ dmId }: { dmId: string }) {const { friends: rawFriends, blocked } = useFriends()const dm = useMemo(() => dms.find((candidate) => candidate.id === dmId) ?? null, [dms, dmId])const dmBlocked = !!dm && blocked.some((b) => (b.userId ?? b.id) === dm.userId)- const historyAllowed = !dmBlocked && metadata.isVerified && !!metadata.data?.historyVerification- && isChannelMetadataTokenCurrent(metadata.data.historyVerification)+ const historyAllowed = !dmBlocked && metadata.canReadconst profilesByUserId = useCanonicalProfilesByUserId()// Enrich with presence — the Composer @-picker uses `f.status` to render// the avatar presence dot; without this enrichment every avatar shows offline.@@ -137,9 +134,8 @@ export function DmView({ dmId }: { dmId: string }) {// Frozen-once snapshot of the viewer's DM read pointer — the anchor for// the "New" divider AND the initial-page mode. Mirrors the channel-view// wiring so both surfaces open with the same anchor-window UX.- const canonicalReadSnapshot = useReadStateProjection(dmId)const { snapshot: readSnapshot, isFetching: readSnapshotFetching, error: readError, retry: retryRead, retrying: retryingRead } =- useDmReadStateSnapshot(dmId, canonicalReadSnapshot)+ useDmReadStateSnapshot(metadata.denied || dmBlocked ? null : dmId)// Anchor the initial page on the viewer's read pointer. Pass `undefined`// (not `null`) while the snapshot resolves — the hook's initialPageParam@@ -309,7 +305,7 @@ export function DmView({ dmId }: { dmId: string }) {}}, [communityRuntime, dmId])- const [replyTo, setReplyTo] = useAtom(useCreateAtom<{ id: string; authorName: string; text: string } | null>(null))+ const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))useEffect(() => {setReplyTo(null)@@ -433,10 +429,10 @@ export function DmView({ dmId }: { dmId: string }) {channelId: dmId,}, routeReady)- if (navigationGate.failed) {+ if (!metadata.denied && !dmBlocked && navigationGate.failed) {return <ConversationResolutionErrorFrame retrying={false} onRetry={navigationGate.retry} />}- if (navigationBlocked) {+ if (!metadata.denied && !dmBlocked && navigationBlocked) {return <DmLoadingFrame reserveBackSlot={bp === "mobile"} />}@@ -465,7 +461,7 @@ export function DmView({ dmId }: { dmId: string }) {className="flex min-h-0 flex-1 flex-col"><ConversationFooterSlotProvider>- {!historyAllowed && readError ? <ConversationResolutionErrorFrame as="div" onRetry={retryRead} retrying={retryingRead} /> : <MessageList+ {dmBlocked ? null : metadata.denied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : !historyAllowed && readError ? <ConversationResolutionErrorFrame as="div" onRetry={retryRead} retrying={retryingRead} /> : <MessageListkey={dmId}variant="dm"channel={dm.name}@@ -522,7 +518,7 @@ export function DmView({ dmId }: { dmId: string }) {>You have blocked this user. Unblock to send messages.</div>- ) : !historyAllowed ? <ComposerSkeleton /> : (+ ) : metadata.denied ? null : !historyAllowed ? <ComposerSkeleton /> : (<ComposersendContract="accepted"channel={dm.name}diff --git a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.dom.test.tsindex b13da77a8..6bf9c81ba 100644--- a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts+++ b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts@@ -96,10 +96,16 @@ vi.mock("@/hooks/community/mutations", () => ({useEditMessage: () => ({ mutate: mutationMocks.editMessage }),useCreateThread: () => ({ mutateAsync: mutationMocks.createThread }),useUploadFile: () => ({ mutateAsync: mutationMocks.uploadFile }),- zipUploadResultsWithDimensions: () => [],+}))+vi.mock("@/hooks/community/mutations/messages", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/hooks/community/mutations/messages")>(),sendNonce: () => "nonce_1",tempMessageId: () => "temp_1",}))+vi.mock("@/hooks/community/mutations/uploads", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/hooks/community/mutations/uploads")>(),+ zipUploadResultsWithDimensions: () => [],+}))vi.mock("@/hooks/community/use-community-ws", () => ({communityWsSendTyping: vi.fn(),communityWsEndTyping: vi.fn(),diff --git a/src/web/src/components/community/machines/machine-capacity.tsx b/src/web/src/components/community/machines/machine-capacity.tsxindex aa18fcbef..6d991e1a3 100644--- a/src/web/src/components/community/machines/machine-capacity.tsx+++ b/src/web/src/components/community/machines/machine-capacity.tsx@@ -4,9 +4,9 @@ import { ArrowRight } from "lucide-react"import { Button } from "@/components/ui/button"import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from "@/components/ui/popover"-import type { MachineCapacity } from "@/hooks/community/use-machines"+import type { MachineCapacitySummary } from "@alook/shared"-export function MachineCapacityUsage({ summary, onViewPlan }: { summary: MachineCapacity | null; onViewPlan: () => void }) {+export function MachineCapacityUsage({ summary, onViewPlan }: { summary: MachineCapacitySummary | null; onViewPlan: () => void }) {const online = summary?.onlineCount ?? 0const limit = summary?.limit ?? 0const percent = limit > 0 ? Math.min(100, online / limit * 100) : 0diff --git a/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts b/src/web/src/components/community/machines/pair-machine-sheet.dom.test.tsindex c2a102649..d8920e4d9 100644--- a/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts+++ b/src/web/src/components/community/machines/pair-machine-sheet.dom.test.ts@@ -12,7 +12,8 @@ const mocks = vi.hoisted(() => ({toastError: vi.fn(),}))-vi.mock("@alook/shared", () => ({+vi.mock("@alook/shared", async (importOriginal) => ({+ ...await importOriginal<typeof import("@alook/shared")>(),isDesktop: () => true,isTauri: mocks.isTauri,tauriInvoke: mocks.invoke,diff --git a/src/web/src/components/community/members/add-members-dialog.dom.test.tsx b/src/web/src/components/community/members/add-members-dialog.dom.test.tsxindex c696f22ab..7161e9051 100644--- a/src/web/src/components/community/members/add-members-dialog.dom.test.tsx+++ b/src/web/src/components/community/members/add-members-dialog.dom.test.tsx@@ -61,10 +61,10 @@ async function fixture() {if (url.startsWith("/api/community/servers/server/members")) {return Promise.resolve({ members: parentMembers, hasMore: false, limit: 50, total: 3 })}- if (url === "/api/community/channels/parent/members") {+ if (url === "/api/community/channels/parent/members?relation=access") {return Promise.resolve({ members: parentMembers })}- const match = /^\/api\/community\/channels\/(thread|other)\/(members|participants)$/.exec(url)+ const match = /^\/api\/community\/channels\/(thread|other)\/(members|participants)(?:\?relation=(?:access|notify))?$/.exec(url)if (!match) throw new Error(`Unexpected request: ${url}`)const channelId = match[1]if (options?.method === "POST") {diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsxindex 9ccc9be34..d3f748297 100644--- a/src/web/src/components/community/members/channel-member-view-model.tsx+++ b/src/web/src/components/community/members/channel-member-view-model.tsx@@ -4,7 +4,8 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useMemo, type ComponentProps, type ReactNode } from "react"import { toast } from "sonner"-import { isForum, type CommunityRole as Role } from "@alook/shared"+import { isForum, type CommunityRole as Role, type CommunityChannelIdentity } from "@alook/shared"+import type { Category, Channel } from "@/lib/community/models/navigation"import { AddMembersDialog } from "@/components/community/members/add-members-dialog"import type { CommunityPanel } from "@/components/community/shell/community-panel"import type { Member } from "@/lib/community/models/people"@@ -50,21 +51,12 @@ export type ChannelMemberPanelProps = Pick<>type ServerModel = {- categories?: Array<{- private?: number | boolean- channels: Array<{ id: string; type?: string }>- }>+ categories?: Array<Pick<Category, "private"> & { channels: Array<Pick<Channel, "id"> & { type?: string }> }>} | null | undefined-type ChannelModel = {- creatorId?: string | null-} | null+type ChannelModel = Partial<Pick<CommunityChannelIdentity, "creatorId">> | null-type ChannelMeta = {- name: string- parentChannelId: string | null- creatorId?: string | null-} | null+type ChannelMeta = Pick<CommunityChannelIdentity, "parentChannelId"> & Partial<Pick<CommunityChannelIdentity, "creatorId">> & { name: NonNullable<CommunityChannelIdentity["name"]> } | nullexport function useChannelMemberViewModel({serverId,@@ -261,6 +253,7 @@ export function useChannelMemberViewModel({}const roster = isNotifyUnit ? parentChannelMembersHook.members : channelMembersHook.membersreturn roster+ .filter((member): member is typeof member & { role: Role } => member.role !== null).filter((member) => member.userId !== currentUser.id).map((member) => {const profile = readCommunityProfile(diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.tsindex aea8aad34..db9151f80 100644--- a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts+++ b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts@@ -60,8 +60,8 @@ vi.mock("./composer-ordered-list", () => ({serializeComposerDocument: (...args: unknown[]) =>mocks.serializeDocument(...args),}))-vi.mock("@/hooks/community/mutations", async (importOriginal) => ({- ...await importOriginal<typeof import("@/hooks/community/mutations")>(),+vi.mock("@/hooks/community/mutations/messages", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/hooks/community/mutations/messages")>(),sendNonce: () => "nonce_collision",}))diff --git a/src/web/src/components/community/messages/create-forum-thread.tsx b/src/web/src/components/community/messages/create-forum-thread.tsxindex 1313107c0..926536121 100644--- a/src/web/src/components/community/messages/create-forum-thread.tsx+++ b/src/web/src/components/community/messages/create-forum-thread.tsx@@ -27,7 +27,6 @@ import type { Member } from "@/lib/community/models/people"import {useUploadFile,zipUploadResultsWithDimensions,- type UploadedAttachment,} from "@/hooks/community/mutations/uploads"// A forum post's body IS the first message in its thread — content plus any@@ -38,7 +37,7 @@ export type NewForumThread = {nonce: stringname: stringcontent: string- attachments?: UploadedAttachment[]+ attachments?: UploadFileResult[]mentionType?: MentionType}diff --git a/src/web/src/components/community/messages/message-channel-controller-send.test.ts b/src/web/src/components/community/messages/message-channel-controller-send.test.tsindex 93fb01ce3..ab6cc645f 100644--- a/src/web/src/components/community/messages/message-channel-controller-send.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-send.test.ts@@ -16,12 +16,12 @@ const mocks = vi.hoisted(() => ({})),}))-vi.mock("@/hooks/community/mutations", () => ({+vi.mock("@/hooks/community/mutations/messages", () => ({sendNonce: () => "nonce_1",tempMessageId: () => "temp_1",toAttachmentVm: mocks.toVm,- zipUploadResultsWithDimensions: mocks.zip,}))+vi.mock("@/hooks/community/mutations/uploads", () => ({ zipUploadResultsWithDimensions: mocks.zip }))vi.mock("@/hooks/community/use-community-ws", () => ({communityWsEndTyping: mocks.endTyping,}))@@ -359,7 +359,7 @@ describe("message channel send helpers", () => {])})- it("no-ops without a retry payload and retains stream state when send rejects", async () => {+ it("no-ops without a retry payload and leaves native send rejection transitions to the mutation", async () => {const uploadFileAsync = vi.fn()const sendMessageAsync = vi.fn()mocks.getRetryPayload.mockReturnValueOnce(undefined)@@ -388,7 +388,7 @@ describe("message channel send helpers", () => {content: "keep optimistic",nonce: "nonce_failed",}))- expect(mocks.dispatch).toHaveBeenCalledWith(scope, { type: "postFail", nonce: "nonce_failed" })+ expect(mocks.dispatch).not.toHaveBeenCalled()expect(mocks.toastApiError).not.toHaveBeenCalled()})diff --git a/src/web/src/components/community/messages/message-channel-controller-send.ts b/src/web/src/components/community/messages/message-channel-controller-send.tsindex 7b9ee6828..fe3eec6d2 100644--- a/src/web/src/components/community/messages/message-channel-controller-send.ts+++ b/src/web/src/components/community/messages/message-channel-controller-send.ts@@ -1,46 +1,17 @@import type { MentionType } from "@alook/shared"import type { SendAttachment } from "./composer"import type { ReplyTarget, Viewer } from "./message-channel-controller-types"-import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"-import {- sendNonce,- tempMessageId,- toAttachmentVm,- zipUploadResultsWithDimensions,- type UploadedAttachment,-} from "@/hooks/community/mutations"-import { toastApiError } from "@/lib/api/client"+import { acceptMessageIntent, prepareMessageIntent } from "@/lib/community/message-send-intent"+import type { SendMessageArgs } from "@/hooks/community/mutations/messages"+import type { UploadFileArgs, UploadFileResult } from "@/hooks/community/mutations/uploads"import type { CommunityRuntime } from "@/stores/community/runtime"import { communityWsEndTyping } from "@/hooks/community/use-community-ws"-import { canonicalizeReplyContent } from "@/lib/community/reply-content"-type ChannelMessageScope = {- kind: "channel"- id: string- serverId: string-}+type ChannelMessageScope = Extract<import("@/lib/community/message-stream").MessageScope, { kind: "channel" }>-type UploadFile = (input: {- assertActive?: (() => void) & { signal: AbortSignal }- target: { channelId: string }- file: File- thumbnailBlob?: Blob- width?: number- height?: number-}) => Promise<UploadedAttachment>+type UploadFile = (input: Omit<UploadFileArgs, "target"> & { target: { channelId: string } }) => Promise<UploadFileResult>-type SendMessage = (input: {- assertActive?: (() => void) & { signal: AbortSignal }- serverId: string- channelId: string- forumParentChannelId?: string- content: string- replyToId?: string- mentionType?: MentionType- attachments?: UploadedAttachment[]- nonce: string- author: Viewer-}) => Promise<unknown>+type SendMessage = (input: SendMessageArgs & { nonce: string }) => Promise<unknown>export async function runAcceptedMessageIntent({runtime,@@ -71,64 +42,17 @@ export async function runAcceptedMessageIntent({if (!state.active || state.generation !== generation) throw new DOMException("Retired send owner", "AbortError")}const assert = () => { assertOwner(); assertActive?.() }- assert()- const streamStore = runtime.messageStream.actions- const payload = streamStore.getRetryPayload(messageScope, nonce)- if (!payload) return- let uploadedAttachments: UploadedAttachment[] | undefined- if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {- const projected = payload.message.attachments- if (projected?.length === payload.localUploads.length) {- uploadedAttachments = projected.map((attachment, index) => {- const local = payload.localUploads[index]- return {- id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),- filename: local.file.name,- contentType: local.file.type,- size: local.file.size,- ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined- ? { hasThumbnail: true }- : {}),- width: local.width,- height: local.height,- }- })- }- }- if (payload.localUploads.length > 0 && !uploadedAttachments) {- const results = await Promise.all(- payload.localUploads.map((upload) =>- uploadFileAsync({- assertActive,- target: { channelId },- file: upload.file,- thumbnailBlob: upload.thumbnailBlob,- width: upload.width,- height: upload.height,- }).catch((error) => {- toastApiError(error, "Failed to attach file", assert)- return null- }),- ),- )- if (results.some((result) => result === null)) {- try { assertOwner() } catch { return }- streamStore.dispatch(messageScope, { type: "uploadFailed", nonce })- return- }- uploadedAttachments = zipUploadResultsWithDimensions(- results as UploadedAttachment[],- [...payload.localUploads],- )- try { assert() } catch { try { assertOwner(); streamStore.dispatch(messageScope, { type: "uploadFailed", nonce }) } catch {} return }- streamStore.dispatch(messageScope, {- type: "uploadSettled",- nonce,- attachments: uploadedAttachments.map((attachment) => toAttachmentVm(channelId, attachment)),- })- }+ const prepared = await prepareMessageIntent({ runtime, scope: messageScope, nonce, assertOwner, assertActive, uploadFileAsync, target: { channelId } })+ if (!prepared.ok) return+ const { payload, attachments: uploadedAttachments } = prepared+try {assert()+ } catch {+ try { assertOwner(); runtime.messageStream.actions.dispatch(messageScope, { type: "postFail", nonce }) } catch {}+ return+ }+ try {await sendMessageAsync({assertActive,serverId,@@ -142,7 +66,6 @@ export async function runAcceptedMessageIntent({author: viewer,})} catch {- try { assertOwner(); streamStore.dispatch(messageScope, { type: "postFail", nonce }) } catch {}return}}@@ -170,39 +93,8 @@ export function acceptChannelMessage({channelId: stringclearReply: () => void}): boolean {- if (!markdown && !attachments?.length) return false- const content = canonicalizeReplyContent(markdown, replyTo)- const nonce = sendNonce()- const createdPreviewUrls: string[] = []- const accepted = runtime.messageStream.actions.accept(messageScope, {- nonce,- tempId: tempMessageId(),- message: {- type: "chat",- authorId: viewer.id,- authorName: viewer.name,- authorAvatar: viewer.avatar,- content,- createdAt: new Date().toISOString(),- ...(replyTo ? { replyTo: toOptimisticReplyPreview(replyTo) } : {}),- },- localUploads: attachments?.map((attachment) => {- const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)- if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)- return {- file: attachment.file,- thumbnailBlob: attachment.thumbnailBlob,- previewObjectUrl,- width: attachment.width,- height: attachment.height,- }- }) ?? [],- mentionType,- })- if (!accepted) {- for (const url of createdPreviewUrls) URL.revokeObjectURL(url)- return false- }+ const nonce = acceptMessageIntent(runtime, messageScope, { content: markdown, attachments, mentionType, author: viewer, replyTo: replyTo ?? undefined })+ if (nonce === undefined) return falsevoid runAcceptedIntent(nonce)communityWsEndTyping(runtime, { channelId })clearReply()diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.tsindex 13a4aa07f..064588be4 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts@@ -553,6 +553,29 @@ describe("useMessageChannelController", () => {expect(latest.messageActions).toBe(firstActions)})+ it("reads only the clicked current canonical or local failed message with current author profiles", () => {+ act(() => { rtlRender(React.createElement(Probe, { value: props() })) })+ const { getMessage } = mocks.createActions.mock.calls[0][0] as Parameters<typeof import("./message-channel-controller-actions").createMessageActions>[0]+ const runtime = fixtureOwner.registry.runtime+ const scope = { kind: "channel" as const, id: "channel_1", serverId: "server_1" }+ act(() => {+ ingestMessages(fixtureOwner.registry, scope.id, [{ id: "m1", seq: 1, type: "chat", content: "current body", authorId: "u1", authorName: "Current Author", authorAvatar: "current.png", authorAvatarVersion: 7 }])+ ingestMessages(fixtureOwner.registry, "other_channel", [{ id: "other", seq: 2, type: "chat", content: "private other" }])+ runtime.messageStream.actions.accept(scope, { nonce: "clicked_failed", tempId: "temp_clicked_failed", message: { type: "chat", authorId: "u1", content: "local body" }, localUploads: [] })+ runtime.messageStream.actions.dispatch(scope, { type: "postFail", nonce: "clicked_failed" })+ })+ expect(getMessage("m1")).toMatchObject({ id: "m1", content: "current body", authorName: "Current Author", authorAvatar: "current.png", authorAvatarVersion: 7 })+ expect(getMessage("temp_clicked_failed")).toMatchObject({ content: "local body", failed: true, clientNonce: "clicked_failed", authorName: "Current Author", authorAvatarVersion: 7 })+ expect(getMessage("other")).toBeUndefined()+ act(() => {+ const confirmed = { id: "confirmed", seq: 3, type: "chat" as const, content: "confirmed body", authorId: "u1", clientNonce: "clicked_failed" }+ ingestMessages(fixtureOwner.registry, scope.id, [confirmed])+ runtime.messageStream.actions.dispatch(scope, { type: "wsMessage", message: confirmed })+ })+ expect(getMessage("temp_clicked_failed")).toBeUndefined()+ expect(getMessage("confirmed")).toMatchObject({ id: "confirmed", content: "confirmed body", authorName: "Current Author", authorAvatarVersion: 7 })+ })+it("ignores non-finite seq params and projects the exact public value surface", () => {mocks.seq = "not-a-number"mocks.typingIds = ["u1", "u2"]diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.tsindex eb7c3bcba..a5860a7e8 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts@@ -11,10 +11,11 @@ import { useCommunityRuntime } from "@/stores/community/runtime"import { useCallback, useEffect, useLayoutEffect, useMemo } from "react"-import { materializeMessageStream, type CanonicalMessage } from "@/lib/community/message-stream"+import { materializeIntent, type CanonicalMessage } from "@/lib/community/message-stream"+import { messageScopeKey } from "@/stores/community/message-stream-store"import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"import { usePathname, useRouter, useSearchParams } from "next/navigation"-import type { MentionType } from "@alook/shared"+import type { MentionType, CommunityMessageResource, CommunityResourceProfile } from "@alook/shared"import { apiFetchProfiles } from "@/lib/community/profile-seed"import { avatarInitial } from "@/lib/community/avatar"@@ -119,8 +120,8 @@ export function useMessageChannelController({const params = new URLSearchParams({ q: term, channelId })const data = await apiFetchProfiles<{results: Array<{- message: { id: string; content: string; authorId: string; createdAt: string; seq?: number }- author: { id: string; name: string; image: string | null; avatarVersion: number }+ message: Pick<CommunityMessageResource, "id" | "content" | "authorId" | "createdAt"> & Partial<Pick<CommunityMessageResource, "seq">>+ author: Pick<CommunityResourceProfile, "id" | "name" | "avatarVersion"> & { image: CommunityResourceProfile["avatar"] }}>}>("/api/community/messages/search?" + params,@@ -203,12 +204,16 @@ export function useMessageChannelController({const getMessage = useCallback((id: string): Msg | undefined => {const registry = getCommunityDbRegistry(profileQueryClient)const row = registry?.collections.messages.get(id)- const scope = { kind: "channel" as const, id: channelId, serverId }- const message = materializeMessageStream(row?.channelId === channelId ? [row as CanonicalMessage] : [], communityRuntime.messageStream.actions.overlayFor(scope)).find((item) => item.id === id)+ let message: Msg | undefined = row?.channelId === channelId ? row as CanonicalMessage : undefined+ if (!message) {+ const intents = communityRuntime.messageStream.get().entries.get(messageScopeKey({ kind: "channel", id: channelId }))?.state.outboxByNonce.values()+ const intent = [...(intents ?? [])].find((item) => item.tempId === id)+ if (intent) message = materializeIntent(intent)+ }if (!message) return undefinedconst profile = message.authorId ? registry?.collections.profiles.get(message.authorId) : undefinedreturn profile ? { ...message, authorName: profile.name, authorAvatar: profile.avatar, authorAvatarVersion: profile.avatarVersion } : message- }, [profileQueryClient, communityRuntime, channelId, serverId])+ }, [profileQueryClient, communityRuntime, channelId])const jumpToSeq = useCallback((seq: number) => {source.capture()()diff --git a/src/web/src/components/community/messages/message-channel-controller-types.ts b/src/web/src/components/community/messages/message-channel-controller-types.tsindex a6166fca5..1e6092aef 100644--- a/src/web/src/components/community/messages/message-channel-controller-types.ts+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts@@ -1,16 +1,15 @@+import type { CommunityUserCore } from "@/lib/community/models/people"import type { ReactNode } from "react"-import type { MentionType } from "@alook/shared"+import type { MentionType, CommunityResourceProfile } from "@alook/shared"import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"import type { SendAttachment } from "./composer"import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"+import type { ReplyTarget } from "@/lib/community/models/message"+export type { ReplyTarget } from "@/lib/community/models/message"type MessageFeed = ReturnType<typeof useChannelMessageFeed>-export type Viewer = {- id: string- name: string- avatar: string-}+export type Viewer = Pick<CommunityResourceProfile, "id"> & Pick<CommunityUserCore, "name" | "avatar">export type MessageUiHandlers = {navigate?: (serverId: string, channelId: string) => void@@ -18,12 +17,6 @@ export type MessageUiHandlers = {previewAttachment?: (attachment: FileAttachment) => void}-export type ReplyTarget = {- id: string- authorName: string- text: string-}-export type MessageContextTarget = {serverId: stringchannelId: stringdiff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.tsindex 59d5619c8..46b0a3a5b 100644--- a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts@@ -1,7 +1,9 @@import React from "react"-import { beforeEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act } from "@/test/react-dom-harness"import { renderCommunity as render } from "@/test/community-owner-harness"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"const mocks = vi.hoisted(() => ({push: vi.fn(),@@ -17,6 +19,9 @@ const mocks = vi.hoisted(() => ({pinMutate: vi.fn(),unpinMutate: vi.fn(),toastApiError: vi.fn(),+ apiFetch: vi.fn(),+ noData: false,+ canonicalMessages: vi.fn<(_ids?: readonly string[]) => undefined>(() => undefined),}))vi.mock("next/navigation", () => ({@@ -25,7 +30,7 @@ vi.mock("next/navigation", () => ({}))vi.mock("@tanstack/react-query", async (importOriginal) => ({ ...await importOriginal<typeof import("@tanstack/react-query")>(),useQuery: () => ({- data: {+ data: mocks.noData ? undefined : {notFound: false,anchorId: "message_1",messages: [{@@ -105,19 +110,73 @@ vi.mock("@/hooks/community/mutations", () => ({useAddReactionApi: () => mocks.addReactionApi,}))vi.mock("sonner", () => ({ toast: vi.fn() }))-vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: mocks.toastApiError }))+vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.apiFetch, toastApiError: mocks.toastApiError }))vi.mock("@/lib/community-db/projections", async () => {const actual = await vi.importActual<typeof import("@/lib/community-db/projections")>("@/lib/community-db/projections",)- return { ...actual, useCanonicalMessagesById: () => undefined }+ return { ...actual, useCanonicalMessagesById: mocks.canonicalMessages }})import {MessageContextSheet,openMessageContextThread,+ messageContextQueryFn,} from "./message-context-sheet"+describe("MessageContextSheet native query publication", () => {+ beforeEach(() => mocks.apiFetch.mockReset())+ afterEach(() => vi.restoreAllMocks())++ it("publishes author profiles once with the sorted canonical context window and ID-only sheet cache", async () => {+ const owner = await createCommunityQueryOwner("context_viewer")+ const writer = await import("@/lib/community-db/write")+ const write = vi.spyOn(writer, "writeCommunityCollectionRows")+ const signal = new AbortController().signal+ mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockResolvedValueOnce({ messages: [+ { id: "after", seq: 3, type: "chat", content: "after", authorId: "author", authorName: "Author" },+ { id: "anchor", seq: 2, type: "chat", content: "anchor", authorId: "author", authorName: "Author" },+ ], hasMore: false })+ await expect(messageContextQueryFn("channel", "context_channel", 2, owner.client)({ signal })).resolves.toEqual({+ notFound: false, anchorId: "anchor", messages: [{ id: "anchor" }, { id: "after" }],+ })+ expect(mocks.apiFetch.mock.calls.map(([url]) => url)).toEqual([+ "/api/community/channels/context_channel/messages/seq/2",+ "/api/community/channels/context_channel/messages?anchor=anchor&limit=11",+ ])+ expect(mocks.apiFetch.mock.calls.every(([, options]) => options.signal === signal)).toBe(true)+ expect(write.mock.calls.filter(([, collection]) => collection === "profiles")).toHaveLength(1)+ expect(owner.registry.collections.messages.get("anchor")).toMatchObject({ content: "anchor", channelId: "context_channel", authorId: "author" })+ expect(owner.registry.collections.profiles.get("author")).toMatchObject({ name: "Author" })+ write.mockRestore()+ })++ it("keeps seq lookup404 as notFound without fetching or publishing a context page", async () => {+ const owner = await createCommunityQueryOwner("context_viewer")+ const revision = beginCommunityProfileSeed(owner.registry).revision+ const { ApiError } = await import("@/lib/errors")+ mocks.apiFetch.mockRejectedValueOnce(new ApiError("missing", 404))+ await expect(messageContextQueryFn("dm", "context_dm", 8, owner.client)()).resolves.toEqual({ notFound: true })+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1)+ expect(beginCommunityProfileSeed(owner.registry).revision).toBe(revision)+ expect([...owner.registry.collections.messages.values()]).toEqual([])+ })++ it("rejects a late context page when its original channel scope retires", async () => {+ const owner = await createCommunityQueryOwner("context_viewer")+ const { retireCommunityChannelReading } = await import("@/lib/community-db/sync")+ let resolvePage!: (page: unknown) => void+ mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockImplementationOnce(() => new Promise((resolve) => { resolvePage = resolve }))+ const pending = messageContextQueryFn("channel", "context_channel", 2, owner.client)().catch((error) => error)+ while (!resolvePage) await Promise.resolve()+ retireCommunityChannelReading(owner.registry, "context_channel", { reason: "read-denied", serverId: "context_server" })+ resolvePage({ messages: [{ id: "anchor", seq: 2, type: "chat", content: "late", authorId: "author", authorName: "Late Author" }], hasMore: false })+ expect(await pending).toMatchObject({ name: "AbortError" })+ expect(owner.registry.collections.messages.get("anchor")).toBeUndefined()+ expect(owner.registry.collections.profiles.get("author")).toBeUndefined()+ })+})+describe("MessageContextSheet thread navigation", () => {beforeEach(() => {vi.clearAllMocks()@@ -125,6 +184,20 @@ describe("MessageContextSheet thread navigation", () => {mocks.pin = undefinedmocks.toggleReaction = undefinedmocks.addReaction = undefined+ mocks.noData = false+ })++ it("selects only context window IDs and no canonical rows without query data", () => {+ const view = render(React.createElement(MessageContextSheet, {+ open: true, onOpenChange: mocks.close, channelId: "parent_1", targetSeq: 1,+ }))+ expect(mocks.canonicalMessages).toHaveBeenCalledWith(["message_1"])+ mocks.canonicalMessages.mockClear()+ mocks.noData = true+ view.rerender(React.createElement(MessageContextSheet, {+ open: true, onOpenChange: mocks.close, channelId: "parent_1", targetSeq: 2,+ }))+ expect(mocks.canonicalMessages).toHaveBeenCalledWith([])})it("opens a rendered channel thread by its flat child id and closes the sheet", () => {diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsxindex 4cf5437c5..41787d34a 100644--- a/src/web/src/components/community/messages/message-context-sheet.tsx+++ b/src/web/src/components/community/messages/message-context-sheet.tsx@@ -1,5 +1,4 @@"use client"-import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useAtom, useCreateAtom } from "@tanstack/react-store"@@ -15,7 +14,6 @@ import { displayReplyContent } from "@/lib/community/reply-content"import { ChannelIcon } from "../channels/channel-icon"import { Skeleton } from "@/components/ui/skeleton"import { apiFetch, toastApiError } from "@/lib/api/client"-import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { ApiError } from "@/lib/errors"import { formatDateLabel } from "@/lib/community/format-time"import { DateDivider } from "../dividers"@@ -30,8 +28,8 @@ import {useUnpinMessage,type ReactionArgs,} from "@/hooks/community/mutations"-import type { FileAttachment, ImagePreview, MessagesPage, Msg, RenderMsg } from "@/lib/community/models/message"-import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"+import type { FileAttachment, ImagePreview, MessagesPage, Msg, RenderMsg, ReplyTarget } from "@/lib/community/models/message"+import { apiFetchCommunity, communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { isAbortError } from "@/lib/errors"import type { OpenProfile } from "@/components/community/social/profile-types"import { useHoverCapable } from "@/hooks/use-hover-capable"@@ -48,7 +46,7 @@ import {publishCommunityEmbeddedMessages,} from "@/lib/community-db/sync"-export type ReplyTarget = { id: string; authorName: string; text: string }+export type { ReplyTarget } from "@/lib/community/models/message"// Preview window sizing — small on purpose. The sheet is a read-only// excerpt with just enough surrounding context to make the target message@@ -90,8 +88,8 @@ function anchorFetchUrl(_type: ScopeType, id: string, anchor: string, limit: numtype SheetCache = {notFound?: boolean- anchorId?: string- messages?: { id: string }[]+ anchorId?: Msg["id"]+ messages?: Pick<Msg, "id">[]}export function messageContextQueryFn(@@ -101,16 +99,16 @@ export function messageContextQueryFn(queryClient: ReturnType<typeof useQueryClient>,) {return async ({ signal }: { signal?: AbortSignal } = {}): Promise<SheetCache> => {- const publicationToken = captureCommunityLiveSnapshotToken(queryClient)- const registry = getCommunityDbRegistry(queryClient)+ const publicationToken = captureCommunityLiveSnapshotToken(queryClient, channelId)+ const registry = publicationToken.registryconst assert = () => assertCommunityLiveSnapshotTokenCurrent(queryClient, publicationToken, signal)await registry?.readyassert()await registry?.collections.messages.preload()assert()- let lookup: { id: string }+ let lookup: Pick<Msg, "id">try {- lookup = await apiFetch<{ id: string }>(+ lookup = await apiFetch<Pick<Msg, "id">>(seqLookupUrl(type, channelId, targetSeq),communityRequestOptions(queryClient, publicationToken, signal, assert),)@@ -120,10 +118,9 @@ export function messageContextQueryFn(throw error}assert()- const page = await apiFetchProfiles<MessagesPage>(+ const page = await apiFetchCommunity<MessagesPage>(anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),- (response) => messageProfilePatches(response.messages),- { signal, assertActive: assert }, registry,+ { signal, assertActive: assert }, publicationToken,)const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))publishCommunityEmbeddedMessages(queryClient, {@@ -202,7 +199,6 @@ export function MessageContextSheet({const toggleMark = useToggleMark()const toggleReactionApi = useToggleReactionApi()const addReactionApi = useAddReactionApi()- const canonicalMessages = useCanonicalMessagesById()const queryKey = useMemo(() => communityKeys.messageContext(type, channelId, targetSeq),@@ -216,6 +212,8 @@ export function MessageContextSheet({queryFn: messageContextQueryFn(type, channelId, targetSeq!, queryClient),staleTime: 30_000,})+ const selectedIds = useMemo(() => query.data?.messages?.map((message) => message.id) ?? [], [query.data?.messages])+ const canonicalMessages = useCanonicalMessagesById(selectedIds)const renderRows = useMemo<RenderMsg[]>(() => {if (!query.data || query.data.notFound || !query.data.messages) return []diff --git a/src/web/src/components/community/settings/advanced-settings.legacy.dom.test.tsx b/src/web/src/components/community/settings/advanced-settings.legacy.dom.test.tsxindex 147557cce..946080e86 100644--- a/src/web/src/components/community/settings/advanced-settings.legacy.dom.test.tsx+++ b/src/web/src/components/community/settings/advanced-settings.legacy.dom.test.tsx@@ -1,6 +1,7 @@import "fake-indexeddb/auto"import React from "react"import { openDB } from "idb"+import { del, get, set } from "idb-keyval"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { afterEach, describe, expect, it, vi } from "vitest"import { render, screen, setupUser, waitFor } from "@/test/react-dom-harness"@@ -26,6 +27,8 @@ function mount() {}afterEach(async () => {vi.restoreAllMocks()+ vi.unstubAllGlobals()+ for (const key of ["alook:qc:v1:settings:client", "alook:qc:v3:settings:client", "alook:qc:v99:settings:application:client", "settings-unrelated"]) await del(key)for (const db of connections.splice(0)) db.close()for (const name of databases.splice(0)) await new Promise<void>((resolve, reject) => {const request = indexedDB.deleteDatabase(name)@@ -39,7 +42,15 @@ describe("AdvancedSettings legacy device cache", () => {db.close()const unrelated = await seed("unrelated-app-cache")unrelated.close()- expect(await getPersistedCacheSizeBytes()).toBe(["messages", "cache_meta", "last_open", "conv_extras"].reduce((sum, table) => sum + new TextEncoder().encode(JSON.stringify({ text: "旧聊天", marker: table })).byteLength, 0))+ const cacheNames = new Set(["alook-public-precache-v0", "alook-public-precache-v1", "alook-public-v99-runtime", "unrelated-cache"])+ const storage = { keys: vi.fn(async () => [...cacheNames]), delete: vi.fn(async (name: string) => cacheNames.delete(name)),+ open: vi.fn(async () => ({ keys: async () => [new Request("https://example.test/asset")], match: async () => new Response("你好") })) }+ vi.stubGlobal("caches", storage)+ await set("alook:qc:v1:settings:client", "old")+ await set("alook:qc:v3:settings:client", "你好")+ await set("alook:qc:v99:settings:application:client", "future")+ await set("settings-unrelated", "keep")+ expect(await getPersistedCacheSizeBytes()).toBe(33 + ["messages", "cache_meta", "last_open", "conv_extras"].reduce((sum, table) => sum + new TextEncoder().encode(JSON.stringify({ text: "旧聊天", marker: table })).byteLength, 0))mount()await waitFor(() => expect(screen.getByTestId(tid.settingsCacheSize)).not.toHaveTextContent("Calculating"))expect(screen.getByTestId(tid.settingsCacheSize)).not.toHaveTextContent("0 B")@@ -47,6 +58,9 @@ describe("AdvancedSettings legacy device cache", () => {await user.click(screen.getByRole("button", { name: "Clear local cache" }))await user.click(screen.getByRole("button", { name: "Clear cache" }))await waitFor(() => expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("0 B"))+ expect(cacheNames).toEqual(new Set(["unrelated-cache"]))+ for (const key of ["alook:qc:v1:settings:client", "alook:qc:v3:settings:client", "alook:qc:v99:settings:application:client"]) expect(await get(key)).toBeUndefined()+ expect(await get("settings-unrelated")).toBe("keep")expect((await indexedDB.databases()).map((db) => db.name)).not.toContain("alook-chat-cache-legacy-positive")expect((await indexedDB.databases()).map((db) => db.name)).toContain("unrelated-app-cache")})@@ -70,10 +84,28 @@ describe("AdvancedSettings legacy device cache", () => {await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("could not be listed"))expect(screen.getByTestId(tid.settingsCacheSize)).not.toHaveTextContent("0 B")})+ it("reports a public cache deletion failure after completing legacy cleanup", async () => {+ const db = await seed("alook-chat-cache-legacy-public-failure")+ db.close()+ vi.stubGlobal("caches", { keys: vi.fn(async () => ["alook-public-precache-v1"]),+ open: vi.fn(async () => ({ keys: async () => [new Request("https://example.test/asset")], match: async () => new Response("public") })),+ delete: vi.fn(async () => { throw new Error("Public files could not be cleared") }) })+ mount()+ await waitFor(() => expect(screen.getByTestId(tid.settingsCacheSize)).not.toHaveTextContent("Calculating"))+ const user = setupUser()+ await user.click(screen.getByRole("button", { name: "Clear local cache" }))+ await user.click(screen.getByRole("button", { name: "Clear cache" }))+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Public files could not be cleared"))+ expect(screen.getByTestId(tid.settingsCacheSize)).not.toHaveTextContent("0 B")+ expect((await indexedDB.databases()).map(db => db.name)).not.toContain("alook-chat-cache-legacy-public-failure")+ })it("keeps the unqualified legacy workspace database during account-only clear", async () => {const db = await seed("alook-chat-cache-legacy-account-boundary")db.close()+ const deleteCache = vi.fn()+ vi.stubGlobal("caches", { keys: vi.fn(async () => ["alook-public-precache-v99"]), delete: deleteCache })await clearPersistedCache("account-A")+ expect(deleteCache).not.toHaveBeenCalled()expect((await indexedDB.databases()).map((db) => db.name)).toContain("alook-chat-cache-legacy-account-boundary")})})diff --git a/src/web/src/components/community/settings/user-settings.tsx b/src/web/src/components/community/settings/user-settings.tsxindex 5a148dd6f..53018fb49 100644--- a/src/web/src/components/community/settings/user-settings.tsx+++ b/src/web/src/components/community/settings/user-settings.tsx@@ -1,4 +1,5 @@"use client"+import type { CommunityProfile } from "@/lib/community/models/people"import { useObservedRegion } from "@/lib/observability/regions"import { useObservedQueryRegion } from "@/lib/observability/query-regions"@@ -106,7 +107,7 @@ export function AdvancedSettings() {open={confirmOpen}onOpenChange={(o) => { if (!o) setConfirmOpen(false) }}title="Clear local cache?"- description="This removes locally persisted messages for every account used on this device. The next channel or DM you open will refetch from the server. Nothing on the server is deleted."+ description="This removes locally cached messages and public files for every account used on this device. The next channel or DM you open will refetch from the server. Nothing on the server is deleted."confirmLabel="Clear cache"loadingLabel="Clearing..."loading={clearing}@@ -139,7 +140,7 @@ export function AdvancedSettings() {<h2 className="text-base font-medium tracking-tight">Clear local cache</h2>{clearError && <p role="alert" className="text-sm text-destructive">{clearError}</p>}<p className="flex items-baseline justify-between gap-4 text-sm">- <span className="text-muted-foreground">Cached messages</span>+ <span className="text-muted-foreground">Cached messages and public files</span><spandata-testid={tid.settingsCacheSize}className="font-mono tabular-nums text-foreground"@@ -152,8 +153,8 @@ export function AdvancedSettings() {</span></p><p className="max-w-[65ch] text-sm leading-6 text-muted-foreground">- Removes locally persisted messages for every account used on this- device. The next channel or DM you open will refetch from the server.+ Removes locally cached messages and public files for every account used+ on this device. The next channel or DM you open will refetch from the server.Nothing on the server is deleted.</p><Button@@ -187,13 +188,11 @@ export function UserSettings({ initialTab = "profile", billingReturn = null, onCuserEmail: stringaboutMe: stringavatar: string- statusEmoji?: string | null- statusText?: string | null- onSave: (data: { name?: string; aboutMe?: string; statusEmoji?: string | null; statusText?: string | null }) => void+ onSave: (data: Partial<Pick<CommunityProfile, "name" | "aboutMe" | "statusEmoji" | "statusText">>) => voidonLogout?: () => voidonAccountDeleted: () => Promise<void>onUploadAvatar?: () => void-}) {+} & Pick<CommunityProfile, "statusEmoji" | "statusText">) {// Draft + saved baseline are mount-only on purpose — a WS-driven prop change// (e.g. status fan-out echo) must not clobber an in-progress edit. The// baseline advances only on a successful save.diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsxindex 9edae4804..9d9db28f1 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx@@ -48,6 +48,7 @@ vi.mock("@/components/community/channels/channel-sidebar-tree-owner", () => ({ Cvi.mock("@/components/community/settings/server-settings", () => ({ ServerSettings: () => null }))let controller: ReturnType<typeof useShellRailController>, client: QueryClientlet navigation: CommunityNavigationController+let railStyles: HTMLStyleElementfunction Probe({ sidebar = false }: { sidebar?: boolean }) {const currentClient = useQueryClient()const frame = { ...normalizeCommunityHref(route.pathname), revision: route.revision }@@ -81,8 +82,11 @@ beforeEach(async () => {await clearAllPersistedCaches(); api.mockReset(); Object.values(ui).forEach((fn) => fn.mockReset())route.pathname = "/c/channels/s1"; route.revision = 0; window.history.replaceState(null, "", route.pathname)vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("prefers-reduced-motion"), media: query, addEventListener: vi.fn(), removeEventListener: vi.fn() }))+ railStyles = document.createElement("style")+ railStyles.textContent = `[data-testid="${tid.serverRailScroll}"].overflow-y-auto { overflow-y: auto; }`+ document.head.appendChild(railStyles)})-afterEach(() => { api.mockReset(); vi.unstubAllGlobals() })+afterEach(() => { railStyles.remove(); api.mockReset(); vi.unstubAllGlobals() })describe("actual native Rail controller continuation", () => {it("current create continues icon upload and navigation through the original account", async () => {const { resolve } = await mount()diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.tsindex 091dc0ad8..c28053c2f 100644--- a/src/web/src/hooks/community/account-unread-projection.ts+++ b/src/web/src/hooks/community/account-unread-projection.ts@@ -1,8 +1,12 @@"use client"+import type { queries } from "@alook/shared"+import type { ReadCoordinatorSnapshot } from "./read-coordinator-snapshot-projection"import { batch, createStore } from "@tanstack/react-store"import type { QueryClient } from "@tanstack/react-query"+type AccountUnreadPrimarySnapshot = Pick<queries.communityReadState.AccountReadStateSnapshot, "revision"> & ReadCoordinatorSnapshot+export type AccountUnreadFamily =| "servers"| `server-detail:${string}`@@ -680,10 +684,7 @@ export class AccountUnreadProjection {})}- acceptPrimarySnapshot(snapshot: {- revision: number- readStates: Array<{ channelId: string; lastReadSeq: number }>- }) {+ acceptPrimarySnapshot(snapshot: AccountUnreadPrimarySnapshot) {return this.transition(() => {if (this.disposed || snapshot.revision < this.highestRevision) returnthis.highestRevision = snapshot.revision@@ -2018,10 +2019,7 @@ export function disposeAccountUnreadProjection(export function acceptAccountUnreadPrimarySnapshot(queryClient: QueryClient,- snapshot: {- revision: number- readStates: Array<{ channelId: string; lastReadSeq: number }>- },+ snapshot: AccountUnreadPrimarySnapshot,) {const ownerUserId = activeOwners.get(queryClient)if (!ownerUserId) returndiff --git a/src/web/src/hooks/community/channel-metadata.test.ts b/src/web/src/hooks/community/channel-metadata.test.tsindex 700bf0c68..81fbc6cc9 100644--- a/src/web/src/hooks/community/channel-metadata.test.ts+++ b/src/web/src/hooks/community/channel-metadata.test.ts@@ -43,7 +43,7 @@ describe("canonical channel metadata lifecycle", () => {expect(client.getQueryData(options.queryKey)).toBeUndefined()fetchMock.mockResolvedValueOnce(payload)await expect(client.query(options)).resolves.toMatchObject({ id: "child" })- expect(runtime.ws.get().channelAccessScopes.has("child")).toBe(type !== "dm")+ expect(runtime.ws.get().channelAccessScopes.has("child")).toBe(true)expect(fetchMock).toHaveBeenCalledTimes(2)} finally { vi.useRealTimers() }})@@ -69,7 +69,7 @@ describe("canonical channel metadata lifecycle", () => {fetchMock.mockResolvedValue({ ...metadata, serverId, type, name: type === "dm" ? null : metadata.name })const { client, runtime } = await createCommunityQueryOwner()await expect(fetchChannelMetadata(client, serverId, "child")).resolves.toMatchObject({ id: "child", serverId, type, name: type === "dm" ? "" : metadata.name })- expect(runtime.ws.get().channelAccessScopes.has("child")).toBe(type !== "dm")+ expect(runtime.ws.get().channelAccessScopes.has("child")).toBe(true)})it.each(["account", "parent", "server", "membership"] as const)("rejects an old successful HTTP response after %s changes",@@ -111,7 +111,7 @@ describe("canonical channel metadata lifecycle", () => {state.markAccessDisconnected()state.markAccessConnected()release(metadata)- await expect(result).resolves.toMatchObject({ id: "child", verifiedEpoch: epoch })+ await expect(result).resolves.toMatchObject({ id: "child", identityProof: expect.objectContaining({ accessEpoch: epoch }) })})it("restores readable child and parent only from a current authoritative response", async () => {@@ -134,7 +134,7 @@ describe("canonical channel metadata lifecycle", () => {const { client, runtime } = await createCommunityQueryOwner()runtime.ws.actions.revokeChannelAccess("server", "child")fetchMock.mockResolvedValue({ ...metadata, ...overrides })- await expect(client.query({ queryKey: communityKeys.channelMeta("server", "child"), queryFn: ({ signal }) => fetchChannelMetadata(client, "server", "child", signal) })).rejects.toThrow("scope mismatch")+ await expect(client.query({ queryKey: communityKeys.channelMeta("server", "child"), queryFn: ({ signal }) => fetchChannelMetadata(client, "server", "child", signal) })).rejects.toThrow(overrides.type ? "Invalid option" : "scope mismatch")expect(runtime.ws.actions.isChannelAccessRevoked("child")).toBe(true)},)diff --git a/src/web/src/hooks/community/channel-metadata.ts b/src/web/src/hooks/community/channel-metadata.tsindex 77ddf8821..b6e6aef35 100644--- a/src/web/src/hooks/community/channel-metadata.ts+++ b/src/web/src/hooks/community/channel-metadata.ts@@ -2,39 +2,29 @@ import { apiFetch } from "@/lib/api/client"import { queryOptions, type QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import { retryConversationRead, withConversationReadDeadline } from "@/lib/community/conversation-read"-import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent, publishCommunityChannelMetadata } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent, publishCommunityChannelMetadata, retireCommunityChannelReading } from "@/lib/community-db/sync"+import { ApiError } from "@/lib/errors"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"+import { normalizeCommunityChannelIdentity, type CommunityChannelIdentity, type CommunityAccessDecision } from "@alook/shared"-export type ChannelMetadata = {- id: string- serverId: string | null- name: string | null- type: string- parentChannelId: string | null- parentMessageId: string | null- creatorId: string | null- archived: boolean | number- lastMessageAt: string | null- createdAt: string+export type ChannelMetadata = CommunityChannelIdentity & {+ accessDecision?: CommunityAccessDecision}export function captureChannelMetadataToken(queryClient: QueryClient, channelId: string) {- const owner = captureCommunityLiveSnapshotToken(queryClient)- return { ...owner, channelId, generation: owner.registry!.runtime.ws.get().channelAccessScopes.get(channelId)?.generation ?? 0 }+ return captureCommunityLiveSnapshotToken(queryClient, channelId)}export function isChannelMetadataTokenCurrent(token: ReturnType<typeof captureChannelMetadataToken>) {try {assertCommunityLiveSnapshotTokenCurrent(token.queryClient, token, undefined)- return (token.registry!.runtime.ws.get().channelAccessScopes.get(token.channelId)?.generation ?? 0) === token.generation+ return true} catch { return false }}-export type ChannelMetadataResource = {- id: string- verifiedEpoch: number- verification?: ReturnType<typeof captureChannelMetadataToken>- historyVerification?: ReturnType<typeof captureChannelMetadataToken>+export type ChannelMetadataResource = Pick<CommunityChannelIdentity, "id"> & Partial<Pick<CommunityChannelIdentity, "serverId">> & {+ identityProof?: ReturnType<typeof captureChannelMetadataToken>+ readProof?: ReturnType<typeof captureChannelMetadataToken>}export async function fetchChannelMetadata(@@ -45,8 +35,11 @@ export async function fetchChannelMetadata(token = captureChannelMetadataToken(queryClient, channelId),) {return withConversationReadDeadline(signal, async (readSignal) => {+ const queryKey = communityKeys.channelMeta(serverId, channelId)+ const resource = queryClient.getQueryCache().find({ queryKey, exact: true })const assertActive = () => {- if (readSignal.aborted || !isChannelMetadataTokenCurrent(token)) throw new DOMException("Stale channel metadata", "AbortError")+ if (readSignal.aborted || !isChannelMetadataTokenCurrent(token)+ || resource && queryClient.getQueryCache().find({ queryKey, exact: true }) !== resource) throw new DOMException("Stale channel metadata", "AbortError")}assertActive()await token.registry!.ready@@ -55,18 +48,26 @@ export async function fetchChannelMetadata(assertActive()let meta: ChannelMetadatatry {- meta = await apiFetch<ChannelMetadata>(`/api/community/channels/${encodeURIComponent(channelId)}`, communityRequestOptions(queryClient, token, readSignal, assertActive))+ const response = await apiFetch<ChannelMetadata>(`/api/community/channels/${encodeURIComponent(channelId)}`, communityRequestOptions(queryClient, token, readSignal, assertActive))+ meta = { ...response, ...normalizeCommunityChannelIdentity(response) }assertActive()- } catch (error) { assertActive(); throw error }+ } catch (error) {+ assertActive()+ if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {+ retireCommunityChannelReading(token.registry!, channelId, { reason: "read-denied", serverId, preserveQuery: resource })+ }+ throw error+ }if (meta.id !== channelId || meta.serverId !== serverId|| !(serverId === null ? meta.type === "dm" : ["text", "forum", "thread"].includes(meta.type))|| !(typeof meta.name === "string" || (serverId === null && meta.name === null))) throw new Error("Channel metadata scope mismatch")- if (serverId !== null) {- token.registry!.runtime.ws.actions.grantServerAccess(serverId)+ if (meta.parentChannelId && (token.registry!.runtime.ws.get().channelAccessScopes.get(meta.parentChannelId)?.generation ?? 0) !== (token.channelScopes.get(meta.parentChannelId)?.generation ?? 0)) throw new DOMException("Retired parent channel", "AbortError")+ if (!meta.archived && meta.accessDecision?.canRead !== false) {+ if (serverId) token.registry!.runtime.ws.actions.grantServerAccess(serverId)token.registry!.runtime.ws.actions.rememberChannelAccess(serverId, channelId, meta.parentChannelId)}- return { ...meta, name: meta.name ?? "", archived: meta.archived === true || meta.archived === 1,- activityAt: meta.lastMessageAt ?? meta.createdAt, verifiedEpoch: token.accessEpoch, verification: token }+ return { ...meta, name: meta.name ?? "",+ activityAt: meta.lastMessageAt ?? meta.createdAt ?? "", identityProof: token }})}@@ -78,8 +79,10 @@ export function channelMetadataOptions(queryClient: QueryClient, serverId: strinconst token = captureChannelMetadataToken(queryClient, channelId)const metadata = await fetchChannelMetadata(queryClient, serverId, channelId, signal, token)publishCommunityChannelMetadata(queryClient, { metadata, proof: { token, signal } })- const previous = queryClient.getQueryData<ChannelMetadataResource>(queryKey)- return { id: metadata.id, verifiedEpoch: token.accessEpoch, verification: token, historyVerification: previous?.historyVerification }+ const canRead = !metadata.archived && metadata.accessDecision?.canRead !== false+ if (!canRead) retireCommunityChannelReading(token.registry!, channelId, { reason: "read-denied", serverId, preserveQuery: queryClient.getQueryCache().find({ queryKey, exact: true }) })+ const qualified = captureChannelMetadataToken(queryClient, channelId)+ return { id: metadata.id, serverId: metadata.serverId, identityProof: qualified, readProof: canRead ? qualified : undefined }},staleTime: Infinity,gcTime: 5 * 60 * 1000,diff --git a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.tsindex a1fd8f515..12273f950 100644--- a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts@@ -1,3 +1,4 @@+import { act } from "@/test/react-dom-harness"import { getCapturedRuntime, seedCanonicalStream, canonicalMessage } from "./test-harness"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import {@@ -5,6 +6,7 @@ import {COMMUNITY_BROWSER_EVENT_BATCH_TYPE,deriveCommunityDeliveryOperationId,encodeCommunityBrowserEventBatch,+ encodeCommunityBrowserEventBatchForContract,prepareCommunityDeliveryEvents,type CommunityWsEvent,} from "@alook/shared"@@ -30,11 +32,12 @@ import {mountHook,resetCommunityWsHarness,seedCanonicalForumSidebar,+ seedCanonicalThread,} from "./test-harness"import { getCanonicalCommunityChannels, getCanonicalCommunityMessages } from "@/lib/community-db/sync"import * as canonicalSync from "@/lib/community-db/sync"import { useCommunityStore } from "@/stores/community"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import {SEEN_DELIVERY_OPERATION_MAX,SEEN_DELIVERY_OPERATION_TRIM_TO,@@ -111,6 +114,47 @@ function attentionReconcileCount(): number {}describe("useCommunityWs — operation bundles", () => {+ it("admits a v2 batch only after its exact wire digest verifies", async () => {+ await mountHook()+ const prepared = await prepareCommunityDeliveryEvents([message])+ if (!prepared.ok) throw new Error("Invalid test event")+ const frame = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("v2-wire"), prepared: prepared.prepared, contract: 2 })+ if (!frame.ok) throw new Error("Invalid test batch")+ const tampered = JSON.parse(frame.body)+ tampered.events[0].message.content = "changed after encoding"+ await act(async () => { await capturedOnMessage!(tampered) })+ expect(getCapturedRuntime().ws.get().seenMessageIds.size).toBe(0)+ expect(canonicalMessage(message.message.id)).toBeUndefined()+ await act(async () => { await capturedOnMessage!(frame.batch) })+ expect(canonicalMessage(message.message.id)?.content).toBe("hello")+ expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.batch.operationId)).toEqual({ digest: prepared.prepared.digest, completed: true })+ })++ it.each(["socket", "account"] as const)("drops a verified batch after original %s retirement during hashing", async (owner) => {+ await mountHook()+ const prepared = await prepareCommunityDeliveryEvents([message])+ if (!prepared.ok) throw new Error("Invalid test event")+ const frame = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("v2-retired"), prepared: prepared.prepared, contract: 2 })+ if (!frame.ok) throw new Error("Invalid test batch")+ let release!: () => void+ let retired = false+ const gate = new Promise<void>((resolve) => { release = resolve })+ const digest = crypto.subtle.digest.bind(crypto.subtle)+ const hashing = vi.spyOn(crypto.subtle, "digest").mockImplementation(async (algorithm, data) => { await gate; return digest(algorithm, data) })+ try {+ const pending = capturedOnMessage!(frame.batch, () => { if (retired) throw new DOMException("Retired socket", "AbortError") })+ expect(getCapturedRuntime().ws.get().seenMessageIds.size).toBe(0)+ await act(async () => {+ if (owner === "socket") retired = true+ else getCapturedRuntime().ws.actions.activateProfileAccount("other")+ release()+ await pending+ })+ expect(canonicalMessage(message.message.id)).toBeUndefined()+ expect(getCapturedRuntime().ws.get().seenDeliveryOperations.size).toBe(0)+ } finally { hashing.mockRestore() }+ })+it("applies archive and null-tag sidebar semantics inside committed batches", async () => {await mountHook()const baseKey = communityKeys.forumSidebarThreads("s1")@@ -545,7 +589,7 @@ describe("useCommunityWs — operation bundles", () => {capturedOnMessage!(first)const { useCommunityWsStore } = await import("@/stores/community/ws")const seenMessages = getCapturedRuntime().ws.get().seenMessageIds.size- const overlayBeforeConflict = getMessageOverlay(capturedQueryClient, {+ const overlayBeforeConflict = getMessageStreamState(capturedQueryClient, {kind: "channel",id: "ch-1",serverId: "s1",@@ -554,7 +598,7 @@ describe("useCommunityWs — operation bundles", () => {capturedOnMessage!(conflicting)expect(getCapturedRuntime().ws.get().seenMessageIds.size).toBe(seenMessages)- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }))+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" })).toStrictEqual(overlayBeforeConflict)expect(vi.mocked(capturedQueryClient.invalidateQueries)).toHaveBeenCalledTimes(invalidationsBeforeConflict)@@ -607,8 +651,7 @@ describe("useCommunityWs — operation bundles", () => {expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(1)expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId)).toEqual({ digest: frame.operationDigest, completed: false })- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" })- .liveById.has("message-before-second-child-fault")).toBe(true)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }).liveIds.includes("message-before-second-child-fault")).toBe(true)recordArrival.mockRestore()const invalidationsAfterFailure = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length@@ -616,8 +659,8 @@ describe("useCommunityWs — operation bundles", () => {expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(2)expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId)).toEqual({ digest: frame.operationDigest, completed: false })- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" })- .liveById.get("message-before-second-child-fault")?.content).toBe("hello")+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }).liveIds).toContain("message-before-second-child-fault")+ expect(canonicalMessage("message-before-second-child-fault")?.content).toBe("hello")expect(vi.mocked(capturedQueryClient.invalidateQueries)).toHaveBeenCalledTimes(invalidationsAfterFailure)@@ -626,7 +669,7 @@ describe("useCommunityWs — operation bundles", () => {expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId)).toEqual({ digest: frame.operationDigest, completed: true })expect(getCapturedRuntime().ws.get().seenMessageIds.size).toBe(1)- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }).liveById.size)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }).liveIds.length).toBe(1)expect(unreadProjection.projectServerChannelUnread("s1",@@ -669,6 +712,7 @@ describe("useCommunityWs — operation bundles", () => {}],pageParams: [null],})+ seedCanonicalThread("s1", "forum_1", "forum", "ch-1")const parentScope = { kind: "channel" as const, id: "forum_1", serverId: "s1" }seedCanonicalStream(parentScope, {type: "wsMessage",@@ -683,12 +727,16 @@ describe("useCommunityWs — operation bundles", () => {thread: { id: "ch-1", name: "thread", messageCount: 1 },},})+ const { captureChannelMetadataToken } = await import("@/hooks/community/channel-metadata")+ const verification = captureChannelMetadataToken(capturedQueryClient, "ch-1")+ capturedQueryClient.setQueryData(communityKeys.channelMeta("s1", "ch-1"), { id: "ch-1", serverId: "s1", identityProof: verification, readProof: verification })vi.spyOn(capturedQueryClient, "invalidateQueries")const { useCommunityWsStore } = await import("@/stores/community/ws")const originalPublish = canonicalSync.projectCommunityWsEventToDbconst publish = vi.spyOn(canonicalSync, "projectCommunityWsEventToDb").mockImplementation((client, event) => {- originalPublish(client, event)+ const result = originalPublish(client, event)if (event.type === "community:channel.child_update") throw new Error("partial parent projection fault")+ return result})const frame = await batchFor("message-projection-fault", [{@@ -812,7 +860,10 @@ describe("useCommunityWs — operation bundles", () => {const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)const recordArrival = vi.spyOn(unreadProjection, "recordArrival").mockImplementationOnce(() => { throw new Error("later child fault") })- vi.spyOn(capturedQueryClient, "invalidateQueries")+ const { captureChannelMetadataToken } = await import("@/hooks/community/channel-metadata")+ const verification = captureChannelMetadataToken(capturedQueryClient, "ch-1")+ capturedQueryClient.setQueryData(communityKeys.channelMeta("s1", "ch-1"), { id: "ch-1", serverId: "s1", identityProof: verification, readProof: verification })+ vi.spyOn(capturedQueryClient, "invalidateQueries")const messageId = `retry-${retryTiming}`const frame = await batchFor(messageId, [{diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.tsindex 750670406..8856129b3 100644--- a/src/web/src/hooks/community/community-ws/cache.test.ts+++ b/src/web/src/hooks/community/community-ws/cache.test.ts@@ -1,10 +1,10 @@import { describe, expect, it } from "vitest"import type { CommunityReactionAdd, CommunityReactionRemove } from "@alook/shared"-import type { Msg } from "@/lib/community/models/message"+import { applyMessageReaction, type Msg } from "@/lib/community/models/message"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { ingestMessages, projectCommunityWsEventToDb } from "@/lib/community-db/sync"import { findCachedMessage } from "../use-message"-import { applyReactionToMessage, removeThreadFromCache, type PageCache } from "./cache"+import { removeThreadFromCache, type PageCache } from "./cache"function pageCache(...pages: Msg[][]): PageCache {return { pages: pages.map((messages) => ({ messages: messages.map(({ id, seq }) => ({ id, seq })), hasMore: false })), pageParams: pages.map(() => null) }@@ -44,13 +44,13 @@ describe("community WS canonical publication and ID windows", () => {})it("adds, deduplicates and removes reactions without mutating the source", () => {const message: Msg = { id: "m_1", reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["u_1"] }] }- const added = applyReactionToMessage(message, add, "u_me")- const duplicate = applyReactionToMessage(added, add, "u_me")- const removed = applyReactionToMessage(duplicate, remove, "u_me")+ const added = applyMessageReaction(message.reactions, add.emoji, add.userId, true, "u_me")+ const duplicate = applyMessageReaction(added, add.emoji, add.userId, true, "u_me")+ const removed = applyMessageReaction(duplicate, remove.emoji, remove.userId, false, "u_me")expect(message.reactions).toEqual([{ emoji: "👍", count: 1, me: false, userIds: ["u_1"] }])- expect(added.reactions).toEqual([{ emoji: "👍", count: 2, me: true, userIds: ["u_1", "u_me"] }])- expect(duplicate.reactions).toEqual(added.reactions)- expect(removed.reactions).toEqual(message.reactions)+ expect(added).toEqual([{ emoji: "👍", count: 2, me: true, userIds: ["u_1", "u_me"] }])+ expect(duplicate).toEqual(added)+ expect(removed).toEqual(message.reactions)})it("patches canonical reactions and removes the last membership", async () => {const { client, registry } = await createCommunityQueryOwner("u_me")diff --git a/src/web/src/hooks/community/community-ws/cache.ts b/src/web/src/hooks/community/community-ws/cache.tsindex 68a5afd12..ae568df01 100644--- a/src/web/src/hooks/community/community-ws/cache.ts+++ b/src/web/src/hooks/community/community-ws/cache.ts@@ -1,9 +1,5 @@import type { InfiniteData } from "@tanstack/react-query"-import type {- CommunityReactionAdd,- CommunityReactionRemove,-} from "@alook/shared"-import type { MessagesWindowPage, Msg } from "@/lib/community/models/message"+import type { MessagesWindowPage } from "@/lib/community/models/message"export type PageCache = InfiniteData<MessagesWindowPage>@@ -26,40 +22,3 @@ export function removeThreadFromCache(})return touched ? { ...cache, pages } : cache}----export function applyReactionToMessage(- message: Msg,- event: CommunityReactionAdd | CommunityReactionRemove,- viewerUserId: string | null,-): Msg {- const reactions = (message.reactions ?? []).map((reaction) => ({- ...reaction,- userIds: [...(reaction.userIds ?? [])],- }))- if (event.type === "community:reaction.add") {- const existing = reactions.find((reaction) => reaction.emoji === event.emoji)- if (existing) {- if (!existing.userIds.includes(event.userId)) existing.userIds.push(event.userId)- existing.count = existing.userIds.length- if (viewerUserId && event.userId === viewerUserId) existing.me = true- } else {- reactions.push({- emoji: event.emoji,- count: 1,- me: !!viewerUserId && event.userId === viewerUserId,- userIds: [event.userId],- })- }- } else {- const index = reactions.findIndex((reaction) => reaction.emoji === event.emoji)- if (index !== -1) {- reactions[index].userIds = reactions[index].userIds.filter((id) => id !== event.userId)- reactions[index].count = reactions[index].userIds.length- if (viewerUserId && event.userId === viewerUserId) reactions[index].me = false- if (reactions[index].count <= 0) reactions.splice(index, 1)- }- }- return { ...message, reactions }-}diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.tsindex 5ef755297..303ad2f65 100644--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts@@ -1,5 +1,5 @@import { getCapturedRuntime } from "./test-harness"-import { afterEach, beforeEach, describe, expect, it } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { QueryClient } from "@tanstack/react-query"import type { CommunityWsEvent } from "@alook/shared"import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"@@ -8,12 +8,12 @@ import { communityKeys } from "@/lib/query-keys"import { useCommunityWsStore } from "@/stores/community/ws"import {createCommunityDbRegistry,+ getCommunityDbRegistry,registerCommunityDbRegistry,} from "@/lib/community-db/collections"-import { ingestServerDetail, projectCommunityWsEventToDb } from "@/lib/community-db/sync"+import { ingestServerDetail, projectCommunityWsEventToDb, retireCommunityChannelReading } from "@/lib/community-db/sync"import {applyForumPostUnitClientEffects,- projectChannelScopeEviction,} from "./channel-scope-projection"import {capturedOnMessage,@@ -48,9 +48,7 @@ it("purges canonical rows for authoritative channel and forum-post eviction", astype: "community:channel.child_create", parentChannelId: "forum", parentMessageId: "opener",channel: { id: "thread", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },} as CommunityWsEvent)- const projection = { project: (callback: () => void) => callback() } as never-- projectChannelScopeEviction(projection, queryClient, "server", "channel")+ retireCommunityChannelReading(registry, "channel", { reason: "read-denied", serverId: "server" })expect(registry.collections.channels.get("channel")).toBeUndefined()applyForumPostUnitClientEffects(queryClient, {@@ -122,7 +120,7 @@ describe.each(["text", "forum"] as const)("%s canonical thread scope eviction",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)+ const dmKey = communityKeys.messageContext("dm", "other_dm", 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 })@@ -141,6 +139,7 @@ describe.each(["text", "forum"] as const)("%s canonical thread scope eviction",expect(capturedQueryClient.getQueryState(communityKeys.channelMeta("server", "preview_child"))).toBeUndefined()expect(getCapturedRuntime().ws.get().channelAccessScopes.has("preview_child")).toBe(false)const apiCalls = getCommunityApiFetchMock().mock.calls.length+ const retireDisk = vi.spyOn(getCommunityDbRegistry(capturedQueryClient)!, "retireReadingDisk")capturedOnMessage!(event)@@ -156,6 +155,8 @@ describe.each(["text", "forum"] as const)("%s canonical thread scope eviction",expect(capturedQueryClient.getQueryData(foreignKey)).toEqual(preview)expect(capturedQueryClient.getQueryData(dmKey)).toEqual(preview)expect(getCommunityApiFetchMock()).toHaveBeenCalledTimes(apiCalls)+ expect(retireDisk).toHaveBeenCalledTimes(1)+ expect(new Set(retireDisk.mock.calls[0]![0])).toContain("preview_child")release(preview)await pending@@ -198,7 +199,7 @@ it("preserves readable previews when leaving only a thread's notify membership",capturedQueryClient.setQueryData(key, preview)capturedOnMessage!({- type: "community:channel.member_remove", serverId: "server", channelId: "preview_child", userId: "u_me",+ type: "community:channel.membership.change", serverId: "server", channelId: "preview_child", userId: "u_me", relation: "notify", present: false,})expect(capturedQueryClient.getQueryData(key)).toEqual(preview)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 7f3e3735b..4800c2020 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@@ -11,63 +11,9 @@ import { removeThreadFromCache } from "./cache"import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"import { removeForumPostFromFeed } from "@/hooks/community/forum-feed-window"import type { InfiniteData } from "@tanstack/react-query"-import {-isKnownNonForumSidebarChannel,-removeForumSidebarChildrenForParent,-removeForumSidebarThreadExact,-removeForumSidebarUnreadChild,-} from "@/hooks/community/use-forum-sidebar-threads"import type { CommunityWsProjectionTransaction } from "./projection-transaction"-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { getCommunityDbRegistry } from "@/lib/community-db/collections"-import { purgeCommunityChannel,purgeCommunityForumPost } from "@/lib/community-db/sync"-import { collectChannelScopeIds,evictScopeContent } from "./scope-eviction"--export function projectChannelScopeEviction(- projection: CommunityWsProjectionTransaction,- queryClient: QueryClient,- serverId: string,- channelId: string,-) {- const ids = collectChannelScopeIds(queryClient, serverId, channelId)- for (const id of getCommunityRuntime(queryClient).ws.actions.revokeChannelAccess(serverId, channelId)) ids.add(id)- projection.project(() => {- for (const id of ids) {- getCommunityRuntime(queryClient).ws.actions.revokeChannelAccess(serverId, id)- getActiveAccountUnreadProjection(queryClient).retireAccessScope({ kind: "channel", channelId: id })- evictChannelScopeQueryCaches(queryClient, serverId, id)- evictScopeContent(queryClient, serverId, id)- }- const registry = getCommunityDbRegistry(queryClient)- if (registry) purgeCommunityChannel(registry, channelId)- })-}--function evictChannelScopeQueryCaches(- queryClient: QueryClient,- serverId: string,- channelId: string,- queries?: ReadonlySet<Query>,-) {- const allowed = (query: Query) => !queries || queries.has(query)- void queryClient.cancelQueries({ queryKey: ["community", "channel", channelId], predicate: allowed })- const nonForum = isKnownNonForumSidebarChannel(queryClient, serverId, channelId)- const sidebar = queryClient.getQueryCache().find({ queryKey: communityKeys.forumSidebarThreads(serverId), exact: true })- if (!nonForum && (!queries || sidebar && queries.has(sidebar))) {- removeForumSidebarUnreadChild(queryClient, serverId, channelId)- removeForumSidebarChildrenForParent(queryClient, serverId, channelId)- removeForumSidebarThreadExact(queryClient, serverId, channelId)- } else {- queryClient.removeQueries({- queryKey: communityKeys.channelMeta(serverId, channelId),- exact: true,- predicate: allowed,- })- }- queryClient.removeQueries({ queryKey: communityKeys.channelMessages(channelId), predicate: allowed })- queryClient.removeQueries({ queryKey: communityKeys.pins(channelId), predicate: allowed })- queryClient.removeQueries({ queryKey: communityKeys.threads(channelId), predicate: allowed })-}+import { purgeCommunityForumPost, publishCommunityDeletedForumPost, type CommunityFreshQueryProof } from "@/lib/community-db/sync"export type ForumPostUnitIdentity = {serverId: string@@ -83,7 +29,6 @@ function evictForumPostUnitQueryCaches(queries?: ReadonlySet<Query>,) {const allowed = (query: Query) => !queries || queries.has(query)- evictChannelScopeQueryCaches(queryClient, unit.serverId, unit.childChannelId, queries)queryClient.setQueriesData<PageCache>({ queryKey: communityKeys.channelMessages(unit.forumChannelId), predicate: allowed },(cache) => removeThreadFromCache(cache, unit.childChannelId, unit.openerMessageId),@@ -122,23 +67,18 @@ export function projectForumPostUnitEviction(export function applyForumPostUnitClientEffects(queryClient: QueryClient,unit: ForumPostUnitIdentity,- options?: { queries?: ReadonlySet<Query>; assertView?: () => void; canonical?: boolean },+ options?: { queries?: ReadonlySet<Query>; assertView?: () => void; proof?: CommunityFreshQueryProof },) {let viewCurrent = truetry { options?.assertView?.() } catch { viewCurrent = false }const wasCurrent = getCommunityRuntime(queryClient).ui.get().currentChannelId === unit.childChannelId- getCommunityRuntime(queryClient).ws.actions.revokeChannelAccess(unit.serverId, unit.childChannelId)- getActiveAccountUnreadProjection(queryClient).retireAccessScope({- kind: "channel",- channelId: unit.childChannelId,- })+ const registry = getCommunityDbRegistry(queryClient)+ if (registry) {+ if (options?.proof) {+ if (!publishCommunityDeletedForumPost(queryClient, unit, options.proof, options)) return false+ } else purgeCommunityForumPost(registry, unit)+ }evictForumPostUnitQueryCaches(queryClient, unit, options?.queries)- evictScopeContent(queryClient, unit.serverId, unit.childChannelId, options)- getCommunityRuntime(queryClient).messageStream.actions.removeScope({- kind: "channel",- id: unit.childChannelId,- serverId: unit.serverId,- })getCommunityRuntime(queryClient).messageStream.actions.dispatch({kind: "channel",id: unit.forumChannelId,@@ -147,8 +87,6 @@ export function applyForumPostUnitClientEffects(type: "messageRemoved",messageId: unit.openerMessageId,})- const registry = getCommunityDbRegistry(queryClient)- if (registry && options?.canonical !== false) purgeCommunityForumPost(registry, unit)const store = getCommunityRuntime(queryClient).ui.get()if (wasCurrent && viewCurrent) {getCommunityRuntime(queryClient).ui.actions.setCurrentChannelId(unit.forumChannelId)@@ -157,4 +95,5 @@ export function applyForumPostUnitClientEffects(channelHref(unit.serverId, unit.forumChannelId),)}+ return true}diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.tsindex 7c88fb189..34a8cbaaf 100644--- a/src/web/src/hooks/community/community-ws/handler-context.ts+++ b/src/web/src/hooks/community/community-ws/handler-context.ts@@ -54,7 +54,6 @@ export type CommunityWsHandlerContext = CommunityWsDispatchContext & {}>}-export type MessageEventContext = CommunityWsHandlerContextexport type TypingEventContext = Pick<CommunityWsHandlerContext,"queryClient" | "sub" | "viewerUserIdRef" | "matchesFocus"diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.tsindex 6ce7b6b89..ee464d51f 100644--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts@@ -1,3 +1,4 @@+import { canonicalMessage } from "./test-harness"import { readCurrentCommunityChannelMeta } from "@/stores/community/runtime"import { act } from "@/test/react-dom-harness"import { seedCanonicalFocusedChannel } from "./test-harness"@@ -8,7 +9,7 @@ import { ApiError } from "@/lib/errors"import { channelMetadataOptions, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate } from "@alook/shared"import { deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatch, prepareCommunityDeliveryEvents } from "@alook/shared"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import type { PresenceResponse } from "@/hooks/community/use-server-panels"import { communityKeys } from "@/lib/query-keys"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"@@ -18,6 +19,7 @@ import {setCanonicalCommunityChannelMember,} from "@/lib/community-db/sync"import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"+import { useChannelMembers } from "@/hooks/community/use-channel-members"import { useServerMembers } from "@/hooks/community/use-server-members"import {capturedOnMessage,@@ -386,8 +388,9 @@ describe("useCommunityWs — member events", () => {expect(dmCache?.pages[0].messages).toEqual([{ id: "m_3", authorId: "u_renamed", authorName: "OldName", content: "sup" },])+ expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_overlay" }).liveIds).toContain("m_overlay")expect(- getMessageOverlay(capturedQueryClient, { kind: "dm", id: "dm_overlay" }).liveById.get("m_overlay")?.authorName,+ canonicalMessage("m_overlay")?.authorName,).toBe("OldName")})@@ -424,7 +427,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",seedCanonicalThread("srv_1", "private_parent", "forum", "private")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" })+ capturedOnMessage!({ type: "community:channel.membership.change", relation: "notify", present: false, serverId: "srv_1", channelId: "private", userId: "u_me" })expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("private")).toBe(false)projection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 2 })@@ -528,19 +531,19 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",const { useCommunityWsStore } = await import("@/stores/community/ws")await act(async () => { capturedOnMessage!({- type: "community:channel.member_remove",+ type: "community:channel.membership.change", relation: "notify", present: false,serverId: "srv_1",channelId: "post_1",userId: "u_me",}) })expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)- expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)+ expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(true)expect(getCanonicalCommunityChannels(capturedQueryClient)- .find(({ id }) => id === "post_1")?.unread).toBe(false)+ .find(({ id }) => id === "post_1")?.unread).toBe(true)expect(readCurrentCommunityChannelMeta(capturedQueryClient)?.name).toBe("Private forum title")await act(async () => { capturedOnMessage!({- type: "community:channel.member_add",+ type: "community:channel.membership.change", relation: "notify", present: true,serverId: "srv_1",channelId: "post_2",userId: "u_me",@@ -574,7 +577,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",}capturedOnMessage!({- type: "community:channel.member_add",+ type: "community:channel.membership.change", relation: "notify", present: true,serverId: "srv_1",channelId: "text_thread",userId: "u_me",@@ -592,7 +595,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",parentChannelId: "text_parent",})capturedOnMessage!({- type: "community:channel.member_remove",+ type: "community:channel.membership.change", relation: "notify", present: false,serverId: "srv_1",channelId: "text_thread",userId: "u_me",@@ -610,6 +613,153 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",})describe("membership metadata and access lifetime", () => {+ it.each([false, true])("rechecks explicit access present=%s without treating it as a notify change", async present => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("server", "parent", "forum", "child")+ const key = communityKeys.channelMessages("child")+ const content = { pages: [{ messages: [{ id: "private" }] }] }+ capturedQueryClient.setQueryData(key, content)+ const api = getCommunityApiFetchMock()+ api.mockResolvedValue({ id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", name: "Child", archived: false })+ capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present })+ if (!present) expect(capturedQueryClient.getQueryData(key)).toBeUndefined()+ else expect(capturedQueryClient.getQueryData(key)).toEqual(content)+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ id: "child", identityProof: expect.any(Object) }))+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)+ expect(api).toHaveBeenCalledWith("/api/community/channels/child", expect.anything())+ })++ it("retires a DM access denial including only its subscription and content", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const key = communityKeys.dmMessages("dm-private")+ const otherKey = communityKeys.dmMessages("dm-other")+ capturedQueryClient.setQueryData(key, { pages: [{ messages: [{ id: "private" }] }] })+ capturedQueryClient.setQueryData(otherKey, { pages: [{ messages: [{ id: "other" }] }] })+ getCapturedRuntime().ui.actions.setCurrentChannelId("dm-private")+ getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm-private", channelId: "other-channel" })+ const unread = getAccountUnreadProjection(capturedQueryClient, "u_me")+ unread.recordArrival({ channelId: "dm-private", serverId: null, seq: 2 })+ const api = getCommunityApiFetchMock()+ api.mockRejectedValue(new ApiError("DM blocked", 403))+ capturedOnMessage!({ type: "community:channel.membership.change", channelId: "dm-private", serverId: null, userId: "u_me", relation: "access", present: false })+ expect(capturedQueryClient.getQueryData(key)).toBeUndefined()+ expect(capturedQueryClient.getQueryData(otherKey)).toBeDefined()+ expect(getCapturedRuntime().ui.get()).toMatchObject({ currentChannelId: null, subscription: { channelId: "other-channel" } })+ expect(getCapturedRuntime().ui.get().subscription.dmConversationId).toBeUndefined()+ expect(unread.projectUnread("inbox-unreads", "dm-private", true, 2)).toBe(false)+ await vi.waitFor(() => expect(capturedQueryClient.getQueryState(communityKeys.channelMeta(null, "dm-private"))?.status).toBe("error"))+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm-private", null)).toBe(true)+ })++ it.each([403, 404, 500])("lets the real metadata owner resolve access failure %s without a second retirement", async status => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("server", "parent", "forum", "child")+ const key = communityKeys.channelMessages("child")+ const content = { pages: [{ messages: [{ id: "private" }] }] }+ capturedQueryClient.setQueryData(key, content)+ const before = getCapturedRuntime().ws.get().accessEpoch+ const api = getCommunityApiFetchMock()+ const fallback = api.getMockImplementation()!+ const error = new ApiError("metadata lookup failed", status)+ api.mockImplementation((...args) => args[0] === "/api/community/channels/child" ? Promise.reject(error) : fallback(...args))+ const query = vi.spyOn(capturedQueryClient, "query")+ capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true })+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child", expect.anything()))+ await expect(query.mock.results[0]!.value).rejects.toBe(error)+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(status !== 500)+ expect(getCapturedRuntime().ws.get().accessEpoch).toBe(before)+ expect(getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation ?? 0).toBe(status === 500 ? 1 : 2)+ if (status === 500) expect(capturedQueryClient.getQueryData(key)).toEqual(content)+ else { expect(capturedQueryClient.getQueryData(key)).toBeUndefined(); expect(hasCanonicalChannel("child")).toBe(false) }+ })++ it("retires a channel when its explicit access refresh confirms it is archived", async () => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("server", "parent", "forum", "child")+ const api = getCommunityApiFetchMock()+ const fallback = api.getMockImplementation()!+ api.mockImplementation((...args) => args[0] === "/api/community/channels/child"+ ? Promise.resolve({ id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", creatorId: "u_me", name: "Child", archived: true, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z" }) : fallback(...args))+ const key = communityKeys.channelMessages("child")+ capturedQueryClient.setQueryData(key, { pages: [{ messages: [{ id: "private" }] }] })+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)+ const query = vi.spyOn(capturedQueryClient, "query")+ capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true })+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child", expect.anything()))+ await expect(query.mock.results[0]!.value).resolves.toMatchObject({ id: "child", identityProof: expect.any(Object) })+ await vi.waitFor(() => expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(true))+ expect(capturedQueryClient.getQueryData(key)).toBeUndefined()+ expect(hasCanonicalChannel("child")).toBe(false)+ })++ it("publishes the current notify roster and rejects the retired response without replacing the body", async () => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("server", "parent", "forum", "child")+ const payload = { id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",+ creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",+ readContractVersion: 2, accessDecision: { channelId: "child", canRead: true, canSend: true, canCreateDiscussion: false } }+ const member = { id: "member", userId: "u_me", role: "member", name: "Viewer", discriminator: "0001",+ avatar: "", avatarVersion: 0, source: "explicit", isCreator: true }+ const api = getCommunityApiFetchMock()+ api.mockImplementation(async (path: string) => path.endsWith("/members?relation=notify") ? { members: [member] } : payload)+ const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))+ const roster = await mountCanonicalHook(() => useChannelMembers("child", true, "server", "notify"))+ await vi.waitFor(() => {+ expect(metadata.result.current.isVerified).toBe(true)+ expect(roster.result.current.members).toHaveLength(1)+ })+ const proof = metadata.result.current.data!.readProof+ expect(proof).toBeDefined()+ const key = communityKeys.channelMessages("child")+ const content = { pages: [{ messages: [{ id: "message" }] }] }+ act(() => capturedQueryClient.setQueryData(key, content))+ const bodyQuery = capturedQueryClient.getQueryCache().find({ queryKey: key, exact: true })+ const generation = getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation+ const reads: Array<{ signal: AbortSignal; resolve: (value: unknown) => void }> = []+ api.mockImplementation(async (path: string, options: { signal: AbortSignal }) => {+ if (!path.endsWith("/members?relation=notify")) return payload+ return await new Promise((resolve) => reads.push({ signal: options.signal, resolve }))+ })+ let pending!: ReturnType<typeof roster.result.current.refetch>+ act(() => { pending = roster.result.current.refetch() })+ await vi.waitFor(() => expect(reads).toHaveLength(1))+ act(() => capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "notify", present: false }))+ await vi.waitFor(() => expect(reads).toHaveLength(2))+ expect(reads[0]!.signal.aborted).toBe(true)+ await act(async () => reads[1]!.resolve({ members: [] }))+ await vi.waitFor(() => {+ expect(roster.result.current.members).toHaveLength(0)+ expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)+ })+ await act(async () => { reads[0]!.resolve({ members: [member] }); await pending })+ expect(roster.result.current.members).toHaveLength(0)+ expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)+ expect(metadata.result.current.data!.readProof).toBe(proof)+ expect(metadata.result.current.isVerified).toBe(true)+ expect(getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation).toBe(generation)+ expect(capturedQueryClient.getQueryCache().find({ queryKey: key, exact: true })).toBe(bodyQuery)+ expect(capturedQueryClient.getQueryData(key)).toBe(content)+ })+ it.each([true, false])("keeps the verified body and access generation for explicit notify present=%s", async (present) => {+ await mountHook({ viewerUserId: "u_me" })+ seedCanonicalThread("server", "parent", "forum", "child")+ const payload = { id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",+ creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z" }+ getCommunityApiFetchMock().mockResolvedValue(payload)+ const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))+ await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))+ const proof = metadata.result.current.data!.identityProof+ const content = { pages: [{ messages: [{ id: "message" }] }] }+ capturedQueryClient.setQueryData(communityKeys.channelMessages("child"), content)+ const bodyQuery = capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.channelMessages("child"), exact: true })+ const generation = getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation+ act(() => capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "notify", present }))+ expect(metadata.result.current.isVerified).toBe(true)+ expect(metadata.result.current.data!.identityProof).toBe(proof)+ expect(getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation).toBe(generation)+ expect(capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.channelMessages("child"), exact: true })).toBe(bodyQuery)+ expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("child"))).toBe(content)+ })it.each(["text", "forum"] as const)("replaces an in-flight %s child metadata read when participation changes again", async (parentType) => {await mountHook({ viewerUserId: "u_me" })seedCanonicalThread("server", "parent", parentType, "child")@@ -643,10 +793,10 @@ describe("membership metadata and access lifetime", () => {else reads[0]!.reject(new ApiError("Old denial", 403))})expect(metadata.result.current.data?.name).not.toBe("Old archived child")- expect(metadata.result.current.isVerified).toBe(false)+ expect(metadata.result.current.isVerified).toBe(true)await act(async () => reads[1]!.resolve(payload))await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))- expect(isChannelMetadataTokenCurrent(metadata.result.current.data!.verification!)).toBe(true)+ expect(isChannelMetadataTokenCurrent(metadata.result.current.data!.identityProof!)).toBe(true)expect(metadata.result.current.data).toMatchObject({ name: "Current child", archived: false })expect(capturedQueryClient.getQueryData(key)).toEqual(content)expect(hasCanonicalChannelAccess("child", "u_me")).toBe(true)@@ -679,9 +829,9 @@ describe("membership metadata and access lifetime", () => {})if (!encoded.ok) throw new Error("Participant events must encode")act(() => capturedOnMessage!(encoded.batch))+ await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child")).toHaveLength(before + 1))await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))- expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child")).toHaveLength(before + 1)- expect(isChannelMetadataTokenCurrent(metadata.result.current.data!.verification!)).toBe(true)+ expect(isChannelMetadataTokenCurrent(metadata.result.current.data!.identityProof!)).toBe(true)expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)})@@ -701,7 +851,7 @@ describe("membership metadata and access lifetime", () => {const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child").lengthapi.mockRejectedValue(new ApiError("temporary", 503))capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })- await vi.waitFor(() => expect(metadata.result.current).toMatchObject({ isError: true, fetchStatus: "idle", isVerified: false }))+ await vi.waitFor(() => expect(metadata.result.current).toMatchObject({ isError: true, fetchStatus: "idle", isVerified: true }))expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child")).toHaveLength(before + 2)await act(async () => { await new Promise<void>((resolve) => setTimeout(resolve, 20)) })expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child")).toHaveLength(before + 2)@@ -773,12 +923,12 @@ describe("membership metadata and access lifetime", () => {expect(metadata.result.current.data).toMatchObject({ id: "child", type: "thread" })expect(hasCanonicalChannelAccess("child", "u_me")).toBe(true)expect(hasCanonicalChannel("child")).toBe(true)- expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)+ expect(hasCanonicalChannelNotify("child", "u_me")).toBe(true)expect(capturedQueryClient.getQueryData(key)).toEqual(content)expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(false)})- it("resolves a cold notify removal without evicting readable content", async () => {+ it("retires unqualified legacy content before a cold relationship recheck", 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 })@@ -786,14 +936,14 @@ describe("membership metadata and access lifetime", () => {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({ id: "child", verification: expect.any(Object) }))+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ id: "child", identityProof: expect.any(Object) }))expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).not.toHaveProperty("type")const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))- expect(capturedQueryClient.getQueryData(key)).toEqual(content)+ expect(capturedQueryClient.getQueryData(key)).toBeUndefined()})- it.each([403, 404, 500])("distinguishes authoritative %s from a temporary metadata failure", async (status) => {+ it.each([403, 404, 500])("keeps unknown legacy content retired when the access recheck returns %s", async (status) => {await mountHook({ viewerUserId: "u_me" })const { ApiError } = await import("@/lib/errors")const { useCommunityWsStore } = await import("@/stores/community/ws")@@ -803,8 +953,8 @@ describe("membership metadata and access lifetime", () => {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(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(status !== 500)- expect(capturedQueryClient.getQueryData(key) === undefined).toBe(status !== 500)+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(true)+ expect(capturedQueryClient.getQueryData(key) === undefined).toBe(true)})it("discards a slow removal after a newer add and a slow metadata result after server leave", async () => {@@ -822,7 +972,7 @@ describe("membership metadata and access lifetime", () => {}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({ id: "child", verification: expect.any(Object) }))+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ id: "child", identityProof: expect.any(Object) }))release({ ...meta, type: "text", parentChannelId: null })await Promise.resolve()expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(false)@@ -856,6 +1006,6 @@ describe("membership metadata and access lifetime", () => {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(capturedQueryClient, { kind: "channel", id: "child", serverId: "server" }).liveById.size).toBe(0)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "child", serverId: "server" }).liveIds.length).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 f50ede2e6..f0edbf7c7 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -1,8 +1,10 @@+import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { getCommunityRuntime } from "@/stores/community/runtime"import type {+ CommunityChannelMembershipChange,CommunityMemberJoin,CommunityMemberLeave,CommunityMemberUpdate,@@ -12,16 +14,13 @@ import { communityKeys } from "@/lib/query-keys"import { patchMemberWindows } from "@/hooks/community/use-server-members"import {- removeForumSidebarProjectionExact,invalidateForumSidebarBaseExact,isKnownNonForumSidebarChannel,} from "@/hooks/community/use-forum-sidebar-threads"-import { ApiError } from "@/lib/errors"-import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"+import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent, type ChannelMetadataResource } 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 { evictServerChannelScopes } from "./scope-eviction"@@ -40,8 +39,8 @@ import {} from "./reaction-details-invalidation"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import {- setCanonicalCommunityChannelMember,getCanonicalCommunityChannels,+ retireCommunityChannelReading,} from "@/lib/community-db/sync"type ChannelMemberEvent = Extract<@@ -49,93 +48,73 @@ type ChannelMemberEvent = Extract<{ type: "community:channel.member_add" | "community:channel.member_remove" }>-export function handleChannelMemberEvent(- event: ChannelMemberEvent,- context: MembershipEventContext,-) {- const { queryClient, viewerUserIdRef, projection } = context- invalidateServerDetail(projection, event.serverId)- invalidateChannelRefDirectory(projection)- invalidateChannelRoster(projection, event.channelId)- const viewerChange = event.userId === viewerUserIdRef.current- if (viewerChange) {- invalidateInbox(projection)- invalidateServersList(projection)- if (!isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {- void invalidateForumSidebarBaseExact(queryClient, event.serverId).catch(() => undefined)- }- }- if (viewerChange) getCommunityRuntime(context.queryClient).ws.actions.beginChannelMembershipChange(event.serverId, event.channelId)+function retireChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext) {+ const registry = getCommunityDbRegistry(context.queryClient)+ if (registry) retireCommunityChannelReading(registry, event.channelId, { reason: "read-denied", serverId: event.serverId })+}++function refreshChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext) {+ const { queryClient } = contextconst token = captureChannelMetadataToken(queryClient, event.channelId)const key = communityKeys.channelMeta(event.serverId, event.channelId)- const canonicalType = () => getCanonicalCommunityChannels(queryClient)- .find((channel) => channel.id === event.channelId && channel.serverId === event.serverId)?.type- const apply = (type: string, activeProjection = projection) => {- setCanonicalCommunityChannelMember(queryClient, event.channelId, event.userId, type === "thread" ? "notify" : "access", event.type === "community:channel.member_add", { event: true })- if (!viewerChange) return- if (type === "thread") {- if (event.type === "community:channel.member_remove") {- getAccountUnreadProjection(queryClient, event.userId).retireNotificationScope({- kind: "channel", channelId: event.channelId,- })- if (!isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {- removeForumSidebarProjectionExact(queryClient, event.serverId, event.channelId)- }- }- if (!isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {- void invalidateForumSidebarBaseExact(queryClient, event.serverId).catch(() => undefined)- }- invalidateInbox(activeProjection)- invalidateServersList(activeProjection)- return- }- 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 {- getCommunityRuntime(context.queryClient).ws.actions.rememberChannelAccess(event.serverId, event.channelId)- getAccountUnreadProjection(queryClient, event.userId).grantAccessScope({- kind: "channel", channelId: event.channelId,- })- }- }- const knownType = canonicalType()- if (knownType) {- if (viewerChange && knownType === "thread") {- projection.fence("channel-metadata", { queryKey: key, exact: true }, () => (- isChannelMetadataTokenCurrent(token)- && !getCommunityRuntime(queryClient).ws.actions.isChannelAccessRevoked(event.channelId, event.serverId)- ))- }- apply(knownType)- return- }void (async () => {await queryClient.cancelQueries({ queryKey: key, exact: true })if (!isChannelMetadataTokenCurrent(token)) returntry {- await queryClient.query({- ...channelMetadataOptions(queryClient, event.serverId, event.channelId),- staleTime: 0,- retry: false,- select: undefined,- })+ await queryClient.query({ ...channelMetadataOptions(queryClient, event.serverId, event.channelId), staleTime: 0, retry: false, select: undefined })if (!isChannelMetadataTokenCurrent(token)) return- const type = canonicalType()- if (type) runCommunityWsProjectionTransaction(queryClient, (current) => apply(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)- })- }- }+ const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)+ if (channel?.archived) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))+ else if (channel) getAccountUnreadProjection(queryClient, context.viewerUserIdRef.current!).grantAccessScope({ kind: "channel", channelId: event.channelId })+ } catch {}})()}+export function handleChannelMembershipChange(event: CommunityChannelMembershipChange, context: MembershipEventContext) {+ const { queryClient, projection, viewerUserIdRef } = context+ if (event.serverId) invalidateServerDetail(projection, event.serverId)+ invalidateChannelRefDirectory(projection)+ projection.fence("channel-roster", { queryKey: communityKeys.channelMembers(event.channelId, event.relation) })+ projection.invalidate("channel-addable-members", { queryKey: communityKeys.channelAddableMembers(event.channelId) })+ if (event.relation === "notify") projection.invalidate("thread-participants", { queryKey: communityKeys.threadParticipants(event.channelId) })+ if (event.userId !== viewerUserIdRef.current) return+ invalidateInbox(projection)+ invalidateServersList(projection)+ if (event.serverId && !isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {+ void invalidateForumSidebarBaseExact(queryClient, event.serverId).catch(() => undefined)+ }+ if (event.relation === "notify") {+ if (!event.present) getAccountUnreadProjection(queryClient, event.userId).retireNotificationScope({ kind: "channel", channelId: event.channelId })+ return+ }+ if (!event.present) retireChannelAccess(event, context)+ else getCommunityRuntime(queryClient).ws.actions.beginChannelMembershipChange(event.serverId, event.channelId)+ refreshChannelAccess(event, context)+}++export function handleChannelMemberEvent(event: ChannelMemberEvent, context: MembershipEventContext) {+ const { queryClient } = context+ const key = communityKeys.channelMeta(event.serverId, event.channelId)+ const proof = queryClient.getQueryData<ChannelMetadataResource>(key)?.identityProof+ const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)+ const verified = !!proof && isChannelMetadataTokenCurrent(proof) && !channel?.pending && !channel?.archived+ && !getCommunityRuntime(queryClient).ws.actions.isChannelAccessRevoked(event.channelId, event.serverId)+ const relation = verified && channel?.type === "thread" ? "notify"+ : verified && (channel?.type === "text" || channel?.type === "forum") ? "access" : undefined+ if (relation) {+ handleChannelMembershipChange({ ...event, type: "community:channel.membership.change", relation, present: event.type === "community:channel.member_add" }, context)+ if (relation === "notify" && event.userId === context.viewerUserIdRef.current) {+ const token = captureChannelMetadataToken(queryClient, event.channelId)+ context.projection.fence("channel-metadata", { queryKey: key, exact: true }, () => isChannelMetadataTokenCurrent(token))+ }+ return+ }+ if (event.userId === context.viewerUserIdRef.current) {+ retireChannelAccess(event, context)+ refreshChannelAccess(event, context)+ } else invalidateChannelRoster(context.projection, event.channelId)+}+function finishMemberEvent(event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate,{ projection }: MembershipEventContext,@@ -186,23 +165,9 @@ export function handleMemberLeave(// so the layout's eject effect can detect the drop and route// the user away from the now-forbidden URL.if (event.userId === viewerUserIdRef.current) {- const viewerId = viewerUserIdRef.currentevictServerChannelScopes(queryClient, event.serverId)- if (viewerId) {- getAccountUnreadProjection(queryClient, viewerId).retireAccessScope({- kind: "server",- serverId: event.serverId,- })- }removeServerReactionDetails(queryClient, event.serverId)invalidateChannelRefDirectory(projection)- getCommunityRuntime(context.queryClient).messageStream.actions.removeServer(event.serverId)- queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })- const store = getCommunityRuntime(context.queryClient).ui.get()- if (store.currentServerId === event.serverId) {- getCommunityRuntime(context.queryClient).ui.actions.setCurrentChannelId(null)- getCommunityRuntime(context.queryClient).ui.actions.setCurrentServerId(null)- }// Rail LIST only (the layout's eject effect reads it to route the// kicked viewer away). `exact` so a kick doesn't cascade-refetch// every server's nested detail subtree.diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.tsindex e7af2d24c..d67c46a10 100644--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts@@ -8,7 +8,9 @@ import type {CommunityPinAdd,CommunityReactionAdd,} from "@alook/shared"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"+import { getMessageStreamState } from "@/test/community-query-owner"import { communityKeys } from "@/lib/query-keys"import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"import {@@ -58,13 +60,28 @@ function seedParent(serverId: string, parentId: string, type: "forum" | "text")}describe("useCommunityWs — message.create", () => {+ it("publishes confirmed message and author once before the ID view consumes it", async () => {+ getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_once" })+ resetHookMemoization()+ await mountHook()+ const registry = getCommunityDbRegistry(capturedQueryClient)!+ const revision = beginCommunityProfileSeed(registry).revision+ const event = messageCreate("ch_once")+ capturedOnMessage!(event)+ expect(beginCommunityProfileSeed(registry).revision).toBe(revision + 1)+ expect(registry.collections.messages.get(event.message.id)).toMatchObject({ content: event.message.content })+ expect(registry.collections.profiles.get(event.message.authorId)).toMatchObject({ name: event.message.authorName })+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_once", serverId: "s1" }).liveIds).toContain(event.message.id)+ expect(canonicalMessage(event.message.id)).toMatchObject({ content: event.message.content })+ })+it("checks a focused channel gap before projecting the incoming overlay row", async () => {const { useCommunityStore } = await import("@/stores/community")getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_gap" })resetHookMemoization()await mountHook()scheduleGapRepairMock.mockImplementationOnce(() => {- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_gap", serverId: "s1" }).liveById.size).toBe(0)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_gap", serverId: "s1" }).liveIds.length).toBe(0)return null})const event = messageCreate("ch_gap")@@ -284,7 +301,7 @@ describe("useCommunityWs — message.create", () => {communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].messages).toEqual([])- expect([...getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveById]).toHaveLength(1)+ expect([...getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds]).toHaveLength(1)})it("projects a split-view parent into its own live overlay", async () => {@@ -300,11 +317,11 @@ describe("useCommunityWs — message.create", () => {capturedOnMessage!(messageCreate("thread_1", "thread_message"))expect([- ...getMessageOverlay(capturedQueryClient, { kind: "channel", id: "parent_1", serverId: "s1" }).liveById,- ].map(([id]) => id)).toEqual(["parent_message"])+ ...getMessageStreamState(capturedQueryClient, { kind: "channel", id: "parent_1", serverId: "s1" }).liveIds,+ ]).toEqual(["parent_message"])expect([- ...getMessageOverlay(capturedQueryClient, { kind: "channel", id: "thread_1", serverId: "s1" }).liveById,- ].map(([id]) => id)).toEqual(["thread_message"])+ ...getMessageStreamState(capturedQueryClient, { kind: "channel", id: "thread_1", serverId: "s1" }).liveIds,+ ]).toEqual(["thread_message"])})it("stops treating the parent as focused immediately after the split owner releases it", async () => {@@ -320,11 +337,11 @@ describe("useCommunityWs — message.create", () => {capturedOnMessage!(messageCreate("parent_hidden", "hidden_parent_message"))capturedOnMessage!(messageCreate("thread_1", "visible_thread_message"))- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "parent_hidden", serverId: "s1" }).liveById)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "parent_hidden", serverId: "s1" }).liveIds).toHaveLength(0)expect([- ...getMessageOverlay(capturedQueryClient, { kind: "channel", id: "thread_1", serverId: "s1" }).liveById,- ].map(([id]) => id)).toEqual(["visible_thread_message"])+ ...getMessageStreamState(capturedQueryClient, { kind: "channel", id: "thread_1", serverId: "s1" }).liveIds,+ ]).toEqual(["visible_thread_message"])})it("heals a first-seen event replay once the focused serverId becomes available", async () => {@@ -337,11 +354,11 @@ describe("useCommunityWs — message.create", () => {const event = messageCreate("ch_1")capturedOnMessage!(event)- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(0)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds).toHaveLength(0)getCapturedRuntime().ui.actions.setCurrentServerId("s1")capturedOnMessage!(event)- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(1)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds).toHaveLength(1)})it("keeps forum query variants base-only and stages a new opener in the overlay", async () => {@@ -360,7 +377,7 @@ describe("useCommunityWs — message.create", () => {expect(capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "forum_1", serverId: "s1" }).liveById).toHaveLength(1)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "forum_1", serverId: "s1" }).liveIds).toHaveLength(1)})it("does NOT patch a channel we aren't focused on", async () => {@@ -440,7 +457,7 @@ describe("useCommunityWs — message.create", () => {capturedOnMessage!(messageCreate("ch_1"))capturedOnMessage!(messageCreate("ch_1"))capturedOnMessage!(messageCreate("ch_1"))- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveById.size).toBe(1)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds.length).toBe(1)})it("caps the live page at MAX_LIVE_PAGE_MESSAGES, dropping the oldest entry", async () => {@@ -470,7 +487,7 @@ describe("useCommunityWs — message.create", () => {expect(ids).toHaveLength(MAX_LIVE_PAGE_MESSAGES)expect(ids[0]).toBe("seed_0")expect(ids).not.toContain("new_message")- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("new_message")).toBe(true)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds.includes("new_message")).toBe(true)})it("flips hasMore/hasMoreOlder to true when the head-slice discards history (legacy shape)", async () => {@@ -578,7 +595,7 @@ describe("useCommunityWs — message.create", () => {communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["seed_0"])- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("m_new")).toBe(true)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds.includes("m_new")).toBe(true)})it("does not schedule an inbox invalidate for viewer's own messages", async () => {@@ -857,7 +874,7 @@ describe("useCommunityWs — reactions", () => {emoji: "👍",})- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_empty", serverId: "s1" }).liveById.size)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_empty", serverId: "s1" }).liveIds.length).toBe(0)})@@ -922,7 +939,8 @@ describe("useCommunityWs — reactions", () => {emoji: "👍",})- expect(getMessageOverlay(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.reactions).toEqual([+ expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds).toContain("m_dm")+ expect(canonicalMessage("m_dm")?.reactions).toEqual([{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] },])})@@ -953,7 +971,8 @@ describe("useCommunityWs — reactions", () => {emoji: "👍",})- expect(getMessageOverlay(capturedQueryClient, scope).liveById.get("m_channel")?.reactions).toEqual([+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain("m_channel")+ expect(canonicalMessage("m_channel")?.reactions).toEqual([{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] },])})@@ -1001,7 +1020,8 @@ describe("useCommunityWs — message.updated", () => {approval,})- expect(getMessageOverlay(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.approval).toEqual(approval)+ expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds).toContain("m_dm")+ expect(canonicalMessage("m_dm")?.approval).toEqual(approval)const cache = capturedQueryClient.getQueryData<{pages: { messages: Array<{ authorName?: string; approval?: unknown }> }[]}>(communityKeys.dmMessages("dm_1"))@@ -1039,7 +1059,8 @@ describe("useCommunityWs — message.updated", () => {approval,})- expect(getMessageOverlay(capturedQueryClient, scope).liveById.get("m_channel")?.approval).toEqual(approval)+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain("m_channel")+ expect(canonicalMessage("m_channel")?.approval).toEqual(approval)})it("refreshes approval fields on a secondary focused channel", async () => {@@ -1067,7 +1088,8 @@ describe("useCommunityWs — message.updated", () => {approval,})- expect(getMessageOverlay(capturedQueryClient, scope).liveById.get("m_parent")?.approval).toEqual(approval)+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain("m_parent")+ expect(canonicalMessage("m_parent")?.approval).toEqual(approval)})})@@ -1137,9 +1159,9 @@ describe("useCommunityWs — DM message.create", () => {communityKeys.dmMessages("dm_1"),)expect(cache?.pages[0].messages).toEqual([])- const { getMessageOverlay } = await import("@/stores/community/message-stream")+ const { getMessageStreamState } = await import("@/test/community-query-owner")expect(- [...getMessageOverlay(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveById.values()].map((message) => message.id),+ getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds,).toEqual(["dm_m_1"])await vi.advanceTimersByTimeAsync(600)await vi.runAllTicks()@@ -1174,7 +1196,7 @@ describe("useCommunityWs — DM message.create", () => {},})- expect(getMessageOverlay(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveById.has("dm_replay")).toBe(true)+ expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds.includes("dm_replay")).toBe(true)})})@@ -1265,8 +1287,110 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>expect(capturedQueryClient.getQueryData<{pages: { messages: { content: string }[] }[]}>(communityKeys.channelMessages("ch_1"))?.pages[0].messages[0].content).toBe("old")- expect(getMessageOverlay(capturedQueryClient, matchingScope).liveById.get("m_1")?.content).toBe("new")- expect(getMessageOverlay(capturedQueryClient, otherScope).liveById.get("m_2")?.content).toBe("old")+ expect(getMessageStreamState(capturedQueryClient, matchingScope).liveIds).toContain("m_1")+ expect(canonicalMessage("m_1")?.content).toBe("new")+ expect(getMessageStreamState(capturedQueryClient, otherScope).liveIds).toContain("m_2")+ expect(canonicalMessage("m_2")?.content).toBe("old")+ })+})++describe("canonical message refresh and edit ownership", () => {+ it("keeps the newest 500 live rows when dispatch precedes canonical publication", async () => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ getCapturedRuntime().ui.actions.setCurrentServerId(scope.serverId)+ getCapturedRuntime().ui.actions.subscribe({ channelId: scope.id })+ await mountHook()+ await act(async () => {+ for (let seq = 1; seq <= 502; seq++) {+ const event = messageCreate(scope.id, `tail_${seq}`)+ capturedOnMessage!({ ...event, message: { ...event.message, seq } })+ }+ })+ const live = getMessageStreamState(capturedQueryClient, scope).liveIds+ expect(live.length).toBe(500)+ expect(live.includes("tail_1")).toBe(false)+ expect(live.includes("tail_2")).toBe(false)+ expect(live).toContain("tail_502")+ expect(canonicalMessage("tail_502")?.seq).toBe(502)+ })+ it("clears canonical rich fields when a websocket row explicitly sends empty arrays", async () => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ getCapturedRuntime().ui.actions.setCurrentServerId(scope.serverId)+ getCapturedRuntime().ui.actions.subscribe({ channelId: scope.id })+ await mountHook()+ const event = messageCreate(scope.id)+ seedCanonicalMessages(scope.id, [{ ...event.message,+ attachments: [{ kind: "file", name: "settled.txt", url: "/media/settled", size: "1 KB" }],+ embeds: [{ title: "Prior" }],+ }])+ await act(async () => { capturedOnMessage!({ ...event, message: { ...event.message, attachments: [], embeds: [] } }) })+ expect(getCommunityDbRegistry(capturedQueryClient)!.collections.messages.get(event.message.id)).toMatchObject({ attachments: [], embeds: [] })+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain(event.message.id)+ expect(canonicalMessage(event.message.id)).toMatchObject({ attachments: [], embeds: [] })+ })+ it("preserves canonical attachments when a duplicate WS row omits them", async () => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ getCapturedRuntime().ui.actions.setCurrentServerId(scope.serverId)+ getCapturedRuntime().ui.actions.subscribe({ channelId: scope.id })+ await mountHook()+ const attachments = [{ kind: "file" as const, name: "settled.txt", url: "/media/settled", size: "1 KB" }]+ const event = messageCreate(scope.id)+ seedCanonicalMessages(scope.id, [{ ...event.message, attachments }])+ await act(async () => { capturedOnMessage!(event) })+ expect(getCommunityDbRegistry(capturedQueryClient)!.collections.messages.get(event.message.id)?.attachments).toEqual(attachments)+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain(event.message.id)+ expect(canonicalMessage(event.message.id)?.attachments).toEqual(attachments)+ })++ it("refreshes only an existing live fallback and never absorbs outbox", async () => {+ await mountHook()+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ seedCanonicalMessages(scope.id, [{ id: "m1", content: "ignored" }])+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds.length).toBe(0)+ await act(async () => {+ seedCanonicalStream(scope, { type: "wsMessage", message: { id: "m1", seq: 11, type: "chat", content: "original", authorId: "u1", clientNonce: "n1" } })+ getCapturedRuntime().messageStream.actions.accept(scope, { nonce: "n2", tempId: "temp_n2", message: { type: "chat", content: "pending", authorId: "u1" }, localUploads: [] })+ capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m1", content: "refreshed" } satisfies CommunityMessageEdited)+ })+ const overlay = getMessageStreamState(capturedQueryClient, scope)+ expect(overlay.liveIds).toContain("m1")+ expect(canonicalMessage("m1")?.content).toBe("refreshed")+ expect(overlay.outboxByNonce.get("n2")?.message.content).toBe("pending")+ })++ it("does not refresh a live row from a peer row with the same nonce", async () => {+ await mountHook()+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ await act(async () => {+ seedCanonicalStream(scope, { type: "wsMessage", message: { id: "m1", seq: 11, type: "chat", content: "original", authorId: "u1", clientNonce: "same" } })+ seedCanonicalMessages(scope.id, [{ id: "m2", seq: 12, content: "peer", authorId: "u2", clientNonce: "same" }])+ capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m2", content: "edited peer" } satisfies CommunityMessageEdited)+ })+ const overlay = getMessageStreamState(capturedQueryClient, scope)+ expect(overlay.liveIds).toContain("m1")+ expect(canonicalMessage("m1")?.content).toBe("original")+ expect(overlay.liveIds.includes("m2")).toBe(false)+ expect(canonicalMessage("m2")?.content).toBe("edited peer")+ })++ it("patches edited content across live and acknowledged sends in their canonical owner", async () => {+ await mountHook()+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ await act(async () => {+ getCapturedRuntime().messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "pending", authorId: "u1" }, localUploads: [] })+ const sent = { id: "m1", seq: 11, type: "chat" as const, content: "sent", authorId: "u1", clientNonce: "n1" }+ seedCanonicalMessages(scope.id, [sent])+ seedCanonicalStream(scope, { type: "postAck", nonce: "n1", message: sent })+ seedCanonicalStream(scope, { type: "wsMessage", message: { id: "m2", seq: 12, type: "chat", content: "before", authorId: "u1", clientNonce: "n2" } })+ capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m1", content: "outbox edit" } satisfies CommunityMessageEdited)+ capturedOnMessage!({ type: "community:message.edited", channelId: scope.id, messageId: "m2", content: "live edit" } satisfies CommunityMessageEdited)+ })+ const overlay = getMessageStreamState(capturedQueryClient, scope)+ expect(overlay.outboxByNonce.size).toBe(0)+ expect(overlay.liveIds).toContain("m1")+ expect(canonicalMessage("m1")?.content).toBe("outbox edit")+ expect(overlay.liveIds).toContain("m2")+ expect(canonicalMessage("m2")?.content).toBe("live edit")})})diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex d61e1bb81..6b7f52bb9 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -9,7 +9,6 @@ import type {CommunityReactionRemove,CommunityWsEvent,} from "@alook/shared"-import { projectCommunityMessageCreate } from "@/lib/community/message-wire"import {hasForumSidebarOwnershipEvidence,@@ -18,12 +17,11 @@ import {} from "@/hooks/community/use-forum-sidebar-threads"import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/community-ws/typing"-import type { MessageEventContext } from "@/hooks/community/community-ws/handler-context"+import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"import { scheduleFocusedMessageGapRepair } from "@/hooks/community/community-ws/reconnect-messages"import { armInboxReadReservationCandidate } from "@/hooks/community/inbox-read-reservation"import {approvalProfilePatches,- messageProfilePatches,writeCommunityProfilePatches,} from "@/lib/community/profile-seed"@@ -33,8 +31,7 @@ import {invalidatePins,} from "@/hooks/community/community-ws/invalidation-projections"import { channelMetadataOptions } from "@/hooks/community/channel-metadata"-import {-} from "@/lib/community-db/sync"+import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"type CommunityMessageEdited = Extract<CommunityWsEvent,@@ -42,7 +39,7 @@ type CommunityMessageEdited = Extract<>function warmLiveForumChildOwner(- queryClient: MessageEventContext["queryClient"],+ queryClient: CommunityWsHandlerContext["queryClient"],event: CommunityMessageCreate,) {if (@@ -65,15 +62,15 @@ export function handleMessageCreate(viewerUserIdRef,matchesFocus,projection,- }: MessageEventContext,+ }: CommunityWsHandlerContext,) {warmLiveForumChildOwner(queryClient, event)const viewerId = viewerUserIdRef.currentconst hasSeenMessage = wsStore.actions.hasSeenMessage(event.message.id)const isForeignFocused = event.message.authorId !== viewerId&& matchesFocus(event)- const projected = projectCommunityMessageCreate(event.message)- writeCommunityProfilePatches(messageProfilePatches([projected]), getCommunityDbRegistry(queryClient), { event: true })+ const projected = projectCommunityWsEventToDb(queryClient, event)+ if (!projected) returnif (isForeignFocused && !hasSeenMessage) {armInboxReadReservationCandidate(queryClient, {channelId: event.channelId,@@ -158,7 +155,7 @@ export function handleMessageCreate(export function handleReactionEvent(event: CommunityReactionAdd | CommunityReactionRemove,- context: MessageEventContext,+ context: CommunityWsHandlerContext,) {void eventvoid context@@ -166,14 +163,14 @@ export function handleReactionEvent(export function handlePinEvent(event: CommunityPinAdd | CommunityPinRemove,- { projection }: MessageEventContext,+ { projection }: CommunityWsHandlerContext,) {invalidatePins(projection, event.channelId)}export function handleMessageUpdated(event: CommunityMessageUpdated,- context: MessageEventContext,+ context: CommunityWsHandlerContext,) {writeCommunityProfilePatches(approvalProfilePatches(event.approval), getCommunityDbRegistry(context.queryClient), { event: true })// When a card resolves (accepted/denied/superseded), the friend graph@@ -187,7 +184,7 @@ export function handleMessageUpdated(export function handleMessageEdited(event: CommunityMessageEdited,- context: MessageEventContext,+ context: CommunityWsHandlerContext,) {const { queryClient } = contextif (event.parentChannelId) {diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.tsindex 56df24e23..ca6ee5c66 100644--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts@@ -1,3 +1,4 @@+import type { queries, CommunityInboxChanged } from "@alook/shared"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { notifyManager, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"@@ -10,22 +11,9 @@ import { acceptAccountUnreadPrimarySnapshot } from "@/hooks/community/account-unimport { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot, type CommunityLiveSnapshotToken } from "@/lib/community-db/sync"import { isConversationAccessError } from "@/lib/community/conversation-read"-type AccountReadState = {- channelId: string- lastReadMessageId: string | null- lastReadAt: string- lastReadSeq: number-}--export type AccountReadStateSnapshot = {- revision: number- readStates: AccountReadState[]-}+export type AccountReadStateSnapshot = Awaited<ReturnType<typeof queries.communityReadState.getAccountReadStateSnapshot>>-export type ReadStateEnvelope = {- revision: number- inboxChanged: true-}+export type ReadStateEnvelope = Pick<CommunityInboxChanged, "revision" | "inboxChanged">type ServerSurfaceTarget = {queryKey: QueryKeydiff --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 1b30464f2..a25738487 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@@ -289,7 +289,7 @@ describe("focused message reconnect catch-up", () => {expect(queryClient.getQueryCache().find({ queryKey: [...queryKey, "reconcile"], exact: true })?.state.fetchStatus).toBe("fetching")await firstexpect(apiFetchMock).toHaveBeenCalledTimes(2)- expect(captureCommunityLiveSnapshotTokenMock).toHaveBeenCalledWith(queryClient)+ expect(captureCommunityLiveSnapshotTokenMock).toHaveBeenCalledWith(queryClient, "ch_gap")expect(publishCommunityMessagesMock).toHaveBeenCalledWith(queryClient, {channelId: "ch_gap",messages: expect.arrayContaining([diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.tsindex d5e5f72b3..4380948f0 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts@@ -1,11 +1,11 @@import { CancelledError, queryOptions, type InfiniteData, type QueryClient, type QueryKey } from "@tanstack/react-query"-import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"+import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"import { ApiError, isAbortError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { getCommunityRuntime } from "@/stores/community/runtime"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { messageScopeKey } from "@/stores/community/message-stream-store"import { messageWindowPage, type MessagesPage, type MessagesPageParam, type MessagesWindowPage } from "@/lib/community/models/message"type MessageCache = InfiniteData<MessagesWindowPage, MessagesPageParam>@@ -38,7 +38,7 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess}export function messageReconcileOptions(queryClient: QueryClient, scopeId: string, key: QueryKey) {- const token = captureCommunityLiveSnapshotToken(queryClient), registry = getCommunityDbRegistry(queryClient)+ const token = captureCommunityLiveSnapshotToken(queryClient, scopeId), registry = getCommunityDbRegistry(queryClient)const originalQuery = queryClient.getQueryCache().find({ queryKey: key, exact: true })const receipt = { token, window: originalQuery }return queryOptions({@@ -54,7 +54,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scopeId: strinawait queryClient.cancelQueries({ queryKey: key, exact: true }, { revert: true, silent: true })assert()const tag = key[4] === "tag" && typeof key[5] === "string" ? key[5] : null- const load = async (param: MessagesPageParam) => { assert(); const page = await apiFetchProfiles<MessagesPage>(url(scopeId, param, tag), (response) => messageProfilePatches(response.messages), { signal, assertActive: assert }, registry); assert(); return page }+ const load = async (param: MessagesPageParam) => { assert(); const page = await apiFetchCommunity<MessagesPage>(url(scopeId, param, tag), { signal, assertActive: assert }, token); assert(); return page }let highWater = latest(data)let paginationReplayed = falsetry {@@ -122,8 +122,9 @@ function reconcile(queryClient: QueryClient, scope: GapRepairScope, target = 0)export function scheduleFocusedMessageGapRepair(queryClient: QueryClient, scope: GapRepairScope, incomingSeq: number): Promise<void> | null {const queries = queryClient.getQueryCache().findAll({ queryKey: messagesKey(scope), type: "active" }).filter((query) => isWindowKey(query.queryKey))const windowSeq = Math.max(0, ...queries.flatMap((query) => isMessageCache(query.state.data) ? [latest(query.state.data, false)] : []))- const overlay = getMessageOverlay(queryClient, scope.kind === "dm" ? { kind: "dm", id: scope.scopeId } : { kind: "channel", id: scope.scopeId, serverId: scope.serverId ?? "" })- const known = Math.max(windowSeq, ...[...overlay.liveById.values()].map((message) => message.seq), 0)+ const ids = getCommunityRuntime(queryClient).messageStream.get().entries.get(messageScopeKey({ kind: scope.kind, id: scope.scopeId }))?.state.liveIds ?? []+ const messages = getCommunityDbRegistry(queryClient)?.collections.messages+ const known = Math.max(windowSeq, ...ids.map((id) => messages?.get(id)?.seq ?? 0), 0)return incomingSeq > known + 1 ? reconcile(queryClient, scope, incomingSeq).catch(() => undefined) : null}diff --git a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts b/src/web/src/hooks/community/community-ws/reconnect.dom.test.tsindex 1fd1babca..4f06060d7 100644--- a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts@@ -349,7 +349,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {)capturedQueryClient.setQueryData(communityKeys.channelMeta("srv_open", "post-a"),- { id: "post-a", verifiedEpoch: 0 },+ { id: "post-a", serverId: "srv_open", verifiedEpoch: 0 },)capturedQueryClient.setQueryData(communityKeys.forumOpenerHint("srv_open", "opener-a"),@@ -363,7 +363,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {)).toEqual({ id: "post-a" })expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("srv_open", "post-a"),- )).toEqual({ id: "post-a", verifiedEpoch: 0 })+ )).toEqual({ id: "post-a", serverId: "srv_open", verifiedEpoch: 0 })expect(capturedQueryClient.getQueryData(communityKeys.forumOpenerHint("srv_open", "opener-a"),)).toEqual({ id: "opener-a", content: "private title" })@@ -385,6 +385,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const invalidatedKeys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[] | undefined,)+ expect(invalidatedKeys).toContainEqual(communityKeys.channelMembers("dm_focus"))+ expect(invalidatedKeys).not.toContainEqual(communityKeys.dmReadStateSnapshot("dm_focus"))expect(invalidatedKeys.some((k) =>@@ -460,10 +462,13 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {}for (const serverId of ["srv_a", "srv_b"]) {capturedQueryClient.setQueryData(communityKeys.forumSidebarRetained(serverId, "child"), {})- capturedQueryClient.setQueryData(communityKeys.channelMeta(serverId, "child"), {})+ capturedQueryClient.setQueryData(communityKeys.channelMeta(serverId, `${serverId}-child`), { id: `${serverId}-child`, serverId })capturedQueryClient.setQueryData(communityKeys.forumOpenerHint(serverId, "opener"), {})capturedQueryClient.setQueryData(communityKeys.forumSidebarUnreadFallbacks(serverId), {})}+ const scopeOnlyMetadata = ["community", "channel", "scope-only", "metadata"] as const+ capturedQueryClient.setQueryData(scopeOnlyMetadata, { id: "scope-only" })+ getCapturedRuntime().ws.actions.observeChannelScope("srv_a", "scope-only")const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")await capturedOnReconnect!({ reconnectDurationMs: 250 })@@ -487,14 +492,16 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {})for (const queryKey of [communityKeys.forumSidebarRetained(serverId, "child"),- communityKeys.channelMeta(serverId, "child"),+ communityKeys.channelMeta(serverId, `${serverId}-child`),communityKeys.forumOpenerHint(serverId, "opener"),communityKeys.forumSidebarUnreadFallbacks(serverId),]) {- expect(capturedQueryClient.getQueryData(queryKey)).toEqual({})+ expect(capturedQueryClient.getQueryData(queryKey)).toEqual(queryKey[3] === "metadata" ? { id: `${serverId}-child`, serverId } : {})expect(capturedQueryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)}}+ expect(capturedQueryClient.getQueryState(scopeOnlyMetadata)?.isInvalidated).toBe(true)+ expect(capturedQueryClient.getQueryData(scopeOnlyMetadata)).toEqual({ id: "scope-only" })expect(calls.some(({ queryKey }) => queryKey?.includes("__none__"))).toBe(false)expect(calls.some(({ queryKey }) => queryKey?.includes("__pending__"))).toBe(false)expect(calls.some(({ queryKey }) => queryKey?.includes("channel-ref-directory"))).toBe(false)@@ -808,7 +815,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {queryClient.setQueryData(communityKeys.forumSidebarThreads(serverId), { seeded: true })}queryClient.setQueryData(communityKeys.forumSidebarRetained("srv_b", "private-child"), { stale: true })- queryClient.setQueryData(communityKeys.channelMeta("srv_b", "private-child"), { stale: true })+ queryClient.setQueryData(communityKeys.channelMeta("srv_b", "private-child"), { id: "private-child", serverId: "srv_b", stale: true })queryClient.setQueryData(communityKeys.forumOpenerHint("srv_b", "private-opener"), { stale: true })queryClient.setQueryData(communityKeys.forumSidebarUnreadFallbacks("srv_b"), { stale: true })const unsubscribes = keys("srv_a").map((queryKey) => {diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.tsindex b56302b42..28a8c66b2 100644--- a/src/web/src/hooks/community/community-ws/reconnect.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.ts@@ -73,7 +73,14 @@ function isRecognizedServerQueryKey(key: QueryKey): key is ServerQueryKey {&& key[4].length > 0}-function isDerivedServerAccessQueryKey(key: QueryKey, serverId: string) {+function metadataServerId(queryClient: QueryClient, key: QueryKey) {+ if (key.length !== 4 || key[0] !== "community" || key[1] !== "channel" || typeof key[2] !== "string" || key[3] !== "metadata") return undefined+ return queryClient.getQueryData<{ serverId?: string | null }>(key)?.serverId+ ?? getCommunityRuntime(queryClient).ws.get().channelAccessScopes.get(key[2])?.serverId+}++function isDerivedServerAccessQueryKey(queryClient: QueryClient, key: QueryKey, serverId: string) {+ if (metadataServerId(queryClient, key) === serverId) return trueif (!isServerQueryPrefix(key, serverId)) return falseif (key.length === 4) return key[3] === "forum-sidebar-unread-fallbacks"return key.length === 5@@ -83,17 +90,19 @@ function isDerivedServerAccessQueryKey(key: QueryKey, serverId: string) {&& key[4].length > 0}-function cachedServerIds(queryKeys: readonly QueryKey[]) {+function cachedServerIds(queryClient: QueryClient, queryKeys: readonly QueryKey[]) {const serverIds = new Set<string>()for (const key of queryKeys) {if (isRecognizedServerQueryKey(key)) serverIds.add(key[2])+ const metadataServer = metadataServerId(queryClient, key)+ if (metadataServer && isCommunityServerIdSegment(metadataServer)) serverIds.add(metadataServer)}return [...serverIds]}async function reconcileCachedServer(queryClient: QueryClient, serverId: string) {const derivedRevalidation = queryClient.invalidateQueries({- predicate: (query) => isDerivedServerAccessQueryKey(query.queryKey, serverId),+ predicate: (query) => isDerivedServerAccessQueryKey(queryClient, query.queryKey, serverId),refetchType: "active",})@@ -174,8 +183,7 @@ function policyExecutors(})},"focused-channel-roster": async () => {- if (!sub.channelId) return- const channelIds = [sub.channelId, sub.secondaryChannelId]+ const channelIds = [sub.channelId, sub.secondaryChannelId, sub.dmConversationId].filter((channelId): channelId is string => !!channelId)const settled = await Promise.allSettled([...channelIds.map((channelId) => queryClient.invalidateQueries({@@ -221,7 +229,7 @@ function policyExecutors(await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })},"all-cached-servers": async () => {- const serverIds = cachedServerIds(queryKeys)+ const serverIds = cachedServerIds(queryClient, queryKeys)const settled = await Promise.allSettled([queryClient.invalidateQueries({queryKey: communityKeys.servers(),diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.tsindex b376cfa55..d46016836 100644--- a/src/web/src/hooks/community/community-ws/registry.test.ts+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -42,6 +42,7 @@ vi.mock("./structure-tree-events", () => ({handleServerUpdate: handlers.handleServerUpdate,}))vi.mock("./membership-events", () => ({+ handleChannelMembershipChange: handlers.handleChannelMembershipChange,handleChannelMemberEvent: handlers.handleChannelMemberEvent,handleMemberJoin: handlers.handleMemberJoin,handleMemberLeave: handlers.handleMemberLeave,@@ -86,7 +87,7 @@ describe("community WebSocket registry", () => {it("has exactly one entry for each of the 45 runtime event types", () => {const eventTypes = Object.values(WS_EVENTS).sort()const registryTypes = Object.keys(communityWsRegistry).sort()- expect(eventTypes).toHaveLength(45)+ expect(eventTypes).toHaveLength(46)expect(registryTypes).toEqual(eventTypes)})diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex 24d6c55ae..c7625c036 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -30,6 +30,7 @@ import {} from "@/hooks/community/community-ws/structure-tree-events"import {handleChannelMemberEvent,+ handleChannelMembershipChange,handleMemberJoin,handleMemberLeave,handleMemberUpdate,@@ -83,6 +84,7 @@ export const communityWsRegistry = {"community:channel.update": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },"community:channel.delete": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers", "focused-messages"] },"community:channel.reorder": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },+ "community:channel.membership.change": { handler: handleChannelMembershipChange, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },"community:channel.member_add": { handler: handleChannelMemberEvent, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },"community:channel.member_remove": { handler: handleChannelMemberEvent, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },"community:category.create": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },@@ -181,7 +183,7 @@ export function dispatchCommunityWsEvents(const serverId = "serverId" in event ? event.serverId : undefinedconst parentChannelId = "parentChannelId" in event ? event.parentChannelId : undefinedif (channelId- && !["community:channel.member_add", "community:channel.member_remove", "community:channel.delete"].includes(event.type)+ && !["community:channel.membership.change", "community:channel.member_add", "community:channel.member_remove", "community:channel.delete"].includes(event.type)&& getCommunityRuntime(context.queryClient).ws.actions.isChannelAccessRevoked(channelId, serverId, parentChannelId ?? undefined)) continueif (channelId && serverId) getCommunityRuntime(context.queryClient).ws.actions.observeChannelScope(serverId, channelId, parentChannelId)const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>@@ -189,14 +191,14 @@ export function dispatchCommunityWsEvents(receipts.push(receipt)withSource(context.queryClient, "ws", () => {entry.handler(event, handlerContext)- projectCommunityWsEventToDb(context.queryClient, event)+ if (event.type !== "community:message.create") projectCommunityWsEventToDb(context.queryClient, event)}, receipt)if (["community:server.delete","community:channel.delete","community:channel.member_remove","community:member.leave",- ].includes(event.type)) {+ ].includes(event.type) || event.type === "community:channel.membership.change" && !event.present) {scheduleAccountAttentionReconcile(context.queryClient)}}diff --git a/src/web/src/hooks/community/community-ws/scope-eviction.ts b/src/web/src/hooks/community/community-ws/scope-eviction.tsindex 58cf9757f..ced4265a9 100644--- a/src/web/src/hooks/community/community-ws/scope-eviction.ts+++ b/src/web/src/hooks/community/community-ws/scope-eviction.ts@@ -1,10 +1,7 @@-import { getCommunityRuntime, readCurrentCommunityChannelMeta } from "@/stores/community/runtime"-import type { Query, QueryClient } from "@tanstack/react-query"-import { communityKeys } from "@/lib/query-keys"+import type { QueryClient } from "@tanstack/react-query"-import { clearTypingIndicator } from "./typing"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { purgeCommunityServer } from "@/lib/community-db/sync"import {@@ -15,112 +12,8 @@ import {ownerServerDeleteScopeFlushCandidates,} from "@/lib/community/eject-server"-type ThreadPageLike = {- serverId?: string- threads?: Array<{ id?: string }>-}--export function collectChannelScopeIds(- queryClient: QueryClient,- serverId: string,- channelId?: string,-) {- const ids = new Set<string>(channelId ? [channelId] : [])- const store = getCommunityRuntime(queryClient).ui.get()- const current = readCurrentCommunityChannelMeta(queryClient)- if (store.currentServerId === serverId && store.currentChannelId- && (!channelId || current?.parentChannelId === channelId)) ids.add(store.currentChannelId)- for (const [id, scope] of getCommunityRuntime(queryClient).ws.get().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 getCommunityRuntime(queryClient).messageStream.get().entries.values()) {- if (!channelId && scope.kind === "channel" && scope.serverId === serverId) ids.add(scope.id)- }- const registry = getCommunityDbRegistry(queryClient)- for (const row of registry?.collections.channels.values() ?? []) {- if (row.serverId === serverId && (!channelId || row.id === channelId || row.parentChannelId === channelId)) ids.add(row.id)- }- for (const [key, data] of queryClient.getQueriesData<- ThreadPageLike | { pages: ThreadPageLike[] }- >({- 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 ?? []) if (thread.id) 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-}--export function evictScopeContent(- queryClient: QueryClient,- serverId: string,- channelId: string,- options?: { queries?: ReadonlySet<Query>; assertView?: () => void },-) {- const predicate = (query: Query) => scopeQuery(query, serverId, channelId) && (!options?.queries || options.queries.has(query))- void queryClient.cancelQueries({ predicate })- queryClient.removeQueries({ predicate })- getCommunityRuntime(queryClient).messageStream.actions.removeScope({ kind: "channel", id: channelId, serverId })- const store = getCommunityRuntime(queryClient).ui.get()- for (const userId of store.typingByScope.get(`ch:${channelId}`)?.keys() ?? []) {- clearTypingIndicator(queryClient, `ch:${channelId}`, userId)- }- try { options?.assertView?.() } catch { return }- if (store.currentChannelId === channelId) {- getCommunityRuntime(queryClient).ui.actions.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- getCommunityRuntime(queryClient).ui.setState((state) => ({ ...state,- subscription,- ...(store.subscription.secondaryChannelId === channelId ? { secondaryChannelOwner: null } : {}),- }))- }-}function evictServerChannelScopesNow(queryClient: QueryClient, serverId: string) {- getCommunityRuntime(queryClient).ws.actions.revokeServerAccess(serverId)- for (const id of collectChannelScopeIds(queryClient, serverId)) {- evictScopeContent(queryClient, serverId, id)- }- queryClient.setQueryData<string[] | undefined>(- communityKeys.servers(),- (current) => current- ? current.filter((id) => id !== serverId)- : current,- )- getCommunityRuntime(queryClient).messageStream.actions.removeServer(serverId)- const community = getCommunityRuntime(queryClient).ui.get()- if (community.currentServerId === serverId) {- getCommunityRuntime(queryClient).ui.actions.setCurrentChannelId(null)- getCommunityRuntime(queryClient).ui.actions.setCurrentServerId(null)- }const registry = getCommunityDbRegistry(queryClient)if (registry) purgeCommunityServer(registry, serverId)}diff --git a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts b/src/web/src/hooks/community/community-ws/social-events.dom.test.tsindex ee6655da2..57ffa1b8b 100644--- a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts@@ -10,9 +10,13 @@ import {encodeCommunityBrowserEventBatch,prepareCommunityDeliveryEvents,} from "@alook/shared"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import { communityKeys } from "@/lib/query-keys"import { getActiveAccountUnreadProjection } from "../account-unread-projection"+import { act } from "@/test/react-dom-harness"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { captureCommunityLiveSnapshotToken, ingestDms, publishCommunityMessages } from "@/lib/community-db/sync"+import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "../channel-metadata"import {capturedOnMessage,capturedQueryClient,@@ -23,6 +27,8 @@ import {resetCommunityWsHarness,resetHookMemoization,unreadBump,+ seedCanonicalMessages,+ canonicalMessage,} from "./test-harness"const desktopMode = vi.hoisted(() => ({ value: true }))@@ -251,11 +257,11 @@ describe("useCommunityWs — account unread projection", () => {capturedOnMessage!(messageCreate("ch_focused"))await vi.advanceTimersByTimeAsync(500)- expect(getMessageOverlay(capturedQueryClient, {+ expect(getMessageStreamState(capturedQueryClient, {kind: "channel",id: "ch_focused",serverId: "s1",- }).liveById.has("m_1")).toBe(true)+ }).liveIds.includes("m_1")).toBe(true)expect(invalidateSpy.mock.calls.some((call) => ((call[0]?.queryKey as unknown[] | undefined)?.includes("inbox")))).toBe(false)@@ -318,6 +324,67 @@ describe("useCommunityWs — friend + mention → invalidate", () => {expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("server_message"))).toBeDefined()})+ it.each([false, true])("retires a visible DM and late reads with viewer-owned Block=%s, preserving siblings", async (blockedByViewer) => {+ const registry = getCommunityDbRegistry(capturedQueryClient)!+ ingestDms(registry, { conversations: ["u_a", "u_other"].map((userId) => ({+ id: `dm_${userId}`, userId, name: userId, discriminator: "0001", avatar: "A", avatarVersion: 0,+ status: "offline" as const, preview: "old private preview",+ })) })+ seedCanonicalMessages("dm_u_a", [{ id: "private", content: "private body" }])+ seedCanonicalMessages("dm_u_other", [{ id: "other", content: "other body" }])+ const metadata = { id: "dm_u_a", serverId: null, name: null, type: "dm", parentChannelId: null,+ parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null, createdAt: "2026-10-08T00:00:00Z",+ readContractVersion: 2, accessDecision: { channelId: "dm_u_a", canRead: true, canSend: true, canCreateDiscussion: false } }+ const api = getCommunityApiFetchMock()+ const original = api.getMockImplementation()!+ api.mockImplementation((...args: unknown[]) => args[0] === "/api/community/channels/dm_u_a" ? Promise.resolve(metadata) : original(...args))+ await capturedQueryClient.query(channelMetadataOptions(capturedQueryClient, null, "dm_u_a"))+ const proof = captureCommunityLiveSnapshotToken(capturedQueryClient)+ const oldMetadata = captureChannelMetadataToken(capturedQueryClient, "dm_u_a")+ expect(isChannelMetadataTokenCurrent(oldMetadata)).toBe(true)+ expect(canonicalMessage("private")?.content).toBe("private body")+ let release!: (value: typeof metadata) => void+ const held = new Promise<typeof metadata>((resolve) => { release = resolve })+ api.mockImplementation((...args: unknown[]) => args[0] === "/api/community/channels/dm_u_a" ? held : original(...args))+ const pending = capturedQueryClient.query({ ...channelMetadataOptions(capturedQueryClient, null, "dm_u_a"), staleTime: 0 }).catch((error: unknown) => error)+ await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/dm_u_a")).toHaveLength(2))+ act(() => {+ getCapturedRuntime().ui.actions.setCurrentChannelId("dm_u_a")+ getCapturedRuntime().ui.setState((state) => ({ ...state, subscription: { dmConversationId: "dm_u_a" } }))+ })+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!({ type: "community:friend.block", userId: "u_a", ...(blockedByViewer ? { blockedByViewer: true } : {}) })+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_u_a", null)).toBe(true)+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_u_other", null)).toBe(false)+ expect(isChannelMetadataTokenCurrent(oldMetadata)).toBe(false)+ expect(registry.collections.messages.has("private")).toBe(false)+ expect(registry.collections.messages.get("other")?.content).toBe("other body")+ expect(registry.collections.channels.get("dm_u_a")?.preview).toBe("")+ expect(registry.collections.channelMemberships.has("dm_u_a:u_a:access")).toBe(true)+ expect(registry.collections.friendships.has("blocked:u_a")).toBe(blockedByViewer)+ expect(getCapturedRuntime().ui.get().subscription.dmConversationId).toBeUndefined()+ expect(() => publishCommunityMessages(capturedQueryClient, { channelId: "dm_u_a", messages: [{ id: "late", content: "late body", type: "chat", seq: 2 }], proof: { token: proof } })).toThrow("Stale community live snapshot")+ capturedOnMessage!(messageCreate("dm_u_a", "late-ws"))+ expect(registry.collections.messages.has("late-ws")).toBe(false)+ await act(async () => { release(metadata); await pending })+ expect(capturedQueryClient.getQueryData(communityKeys.channelMeta(null, "dm_u_a"))).toBeUndefined()+ expect(registry.collections.messages.has("private")).toBe(false)+ })++ it("does not retire the focused DM for an unrelated block or a retired provider", async () => {+ const registry = getCommunityDbRegistry(capturedQueryClient)!+ ingestDms(registry, { conversations: [{ id: "dm_keep", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "keep" }] })+ seedCanonicalMessages("dm_keep", [{ id: "keep", content: "keep body" }])+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!({ type: "community:friend.block", userId: "unrelated" })+ capturedOnMessage!({ type: "community:friend.block", userId: "u_me" })+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_keep", null)).toBe(false)+ act(() => getCapturedRuntime().lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 })))+ capturedOnMessage!({ type: "community:friend.block", userId: "peer" })+ expect(registry.collections.messages.get("keep")?.content).toBe("keep body")+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_keep", null)).toBe(false)+ })+it("friend.block evicts an unresolved reaction-details request", async () => {await mountHook()const key = communityKeys.reactionDetails("pending_message")diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex 72aff1914..b450e93db 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -28,6 +28,8 @@ import {showDesktopSystemNotification,} from "@/lib/community/desktop-system-notification"import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { applyCommunityDmBlockAccess } from "@/lib/community-db/sync"export function handleReadStateAdvanced(event: CommunityReadStateAdvanced,@@ -131,7 +133,11 @@ export function handleFriendEvent(exact: true,})}- if (event.type === "community:friend.block") removeDmReactionDetails(queryClient)+ if (event.type === "community:friend.block") {+ const registry = getCommunityDbRegistry(queryClient)+ if (registry) applyCommunityDmBlockAccess(registry, event.userId, true)+ removeDmReactionDetails(queryClient)+ }}export function handleMentionCreate(diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.tsindex aa2a89a87..d3fb998f2 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts@@ -4,7 +4,7 @@ import { seedCanonicalFocusedChannel } from "./test-harness"import { getCapturedRuntime, seedCanonicalStream, seedCanonicalMessages, canonicalMessage, seedCanonicalServer, canonicalRegistry, mountCanonicalHook } from "./test-harness"import { useServerRailProjection, useServerTreeProjection } from "@/lib/community-db/projections"import { mapForumFeedPages } from "@/hooks/community/use-forum-feed"-import { forumFeedWindow } from "@/hooks/community/forum-feed-window"+import { normalizeThreadResources, forumFeedWindow } from "@/hooks/community/forum-feed-window"import { publishCommunityForumFeed, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { QueryObserver } from "@tanstack/react-query"@@ -22,7 +22,7 @@ import type {CommunityServerDelete,CommunityServerUpdate,} from "@alook/shared"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import { communityKeys } from "@/lib/query-keys"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import {@@ -96,13 +96,13 @@ function forumFeedIds(filter: string | null) {)?.pages ?? []const messages = new Map([...canonicalRegistry!.collections.messages.values()].map((message) => [message.id, message]))const channels = new Map([...canonicalRegistry!.collections.channels.values()].map((channel) => [channel.id, channel]))- return mapForumFeedPages(pages.map(forumFeedWindow), messages, channels, new Map(), filter).map((thread) => thread.id)+ return mapForumFeedPages(pages.map((page) => forumFeedWindow(normalizeThreadResources("forum_1", page))), messages, channels, new Map(), filter).map((thread) => thread.id)}function seedForumFeed(rows: Parameters<typeof forumFeedFixture>[0]) {seedCanonicalServer({ id: "s1", categories: [{ id: "cat1", name: "Forum", channels: [{ id: "forum_1", name: "Forum", type: "forum", active: false, unread: false }] }] })const page = forumFeedFixture(rows).pages[0]!- act(() => { publishCommunityForumFeed(capturedQueryClient, "forum_1", page, { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined }) })+ act(() => { publishCommunityForumFeed(capturedQueryClient, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined }) })}beforeEach(resetCommunityWsHarness)@@ -437,8 +437,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>?.pages[0].threads.map((thread) => thread.id)).toEqual(["post_keep"])expect(canonicalForumSidebar("srv_1").threads.map((thread) => thread.id)).toEqual(["post_keep"])- expect(getMessageOverlay(capturedQueryClient, { kind: "channel", id: "forum_1", serverId: "srv_1" })- .liveById.has("opener-post_1")).toBe(false)+ expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "forum_1", serverId: "srv_1" }).liveIds.includes("opener-post_1")).toBe(false)expect(readCurrentCommunityChannelMeta(capturedQueryClient)).toMatchObject({ id: "forum_1", type: "forum" })expect(replacePath).toHaveBeenCalledWith("/c/channels/srv_1/forum_1")expect(capturedQueryClient.getQueryState(communityKeys.forumTags("forum_1"))?.isInvalidated)@@ -477,7 +476,8 @@ describe("useCommunityWs — child_create patches parent thread badge with countpages: { messages: { id: string; thread?: { id: string; name: string; messageCount: number } }[] }[]}>(communityKeys.channelMessages("ch_parent"))expect(cache?.pages[0].messages).toEqual([])- const overlay = getMessageOverlay(capturedQueryClient, { kind: "channel", id: "ch_parent", serverId: "s1" })+ const overlay = getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_parent", serverId: "s1" })+ expect(overlay.liveIds).toContain("m_parent")expect(canonicalMessage("m_parent")?.thread).toMatchObject({id: "ch_thread",name: "New thread",@@ -967,6 +967,7 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()await mountHook()// Seed the deleted channel's own message cache so we can assert eviction.act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] }) })+ const query = capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.channelMessages("post_1"), exact: true })!const removeSpy = vi.spyOn(capturedQueryClient, "removeQueries")const event: CommunityChannelDelete = {@@ -976,8 +977,8 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()}expect(() => capturedOnMessage!(event)).not.toThrow()- const removedKeys = removeSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))- expect(removedKeys).toContain(JSON.stringify(communityKeys.channelMessages("post_1")))+ expect(removeSpy.mock.calls.some(([filters]) => filters?.predicate?.(query) || JSON.stringify(filters?.queryKey) === JSON.stringify(query.queryKey))).toBe(true)+ expect(capturedQueryClient.getQueryState(query.queryKey)).toBeUndefined()})})diff --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 88d4e3715..5ca7eb19c 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@@ -16,7 +16,8 @@ import type {} from "@alook/shared"import { FORUM_ARCHIVE_TAG } from "@alook/shared"import { communityKeys } from "@/lib/query-keys"-import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { getCanonicalCommunityChannels, retireCommunityChannelReading } from "@/lib/community-db/sync"import {grantForumSidebarChild,hasForumSidebarOwnershipEvidence,@@ -27,7 +28,6 @@ import {} from "@/hooks/community/use-forum-sidebar-threads"import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"import {- projectChannelScopeEviction,projectForumPostUnitEviction,} from "./channel-scope-projection"import { evictServerChannelScopes } from "./scope-eviction"@@ -124,15 +124,10 @@ export function handleServerDelete({ queryClient, projection }: StructureTreeEventContext,) {evictServerChannelScopes(queryClient, event.serverId)- getActiveAccountUnreadProjection(queryClient).retireAccessScope({- kind: "server",- serverId: event.serverId,- })invalidateChannelRefDirectory(projection)// Refresh the rail LIST only (drop the deleted server). `exact`// so this doesn't cascade-refetch every other server's nested- // detail subtree; the deleted server's own subtree is cleared by- // the removeQueries below.+ // detail subtree.invalidateServersList(projection)}@@ -175,12 +170,8 @@ export function handleChannelEvent(kind: "channel",channelId: event.channelId,})- projectChannelScopeEviction(- projection,- queryClient,- event.serverId,- event.channelId,- )+ const registry = getCommunityDbRegistry(queryClient)+ if (registry) retireCommunityChannelReading(registry, event.channelId, { reason: "resource-deleted", serverId: event.serverId })}// When a child thread is deleted, refresh the// PARENT's list so the deleted card disappears from the feed ondiff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.tsindex 6a5a433d5..892577ea6 100644--- a/src/web/src/hooks/community/community-ws/test-harness.ts+++ b/src/web/src/hooks/community/community-ws/test-harness.ts@@ -55,7 +55,7 @@ const additionalHooks: Array<RenderHookResult<void, Parameters<typeof mountHook>let messageProjectionHook: RenderHookResult<ReturnType<typeof useCanonicalMessagesById>, unknown> | null = nullconst projectionHooks: Array<{ unmount: () => void }> = []-export let capturedOnMessage: ((msg: unknown) => void) | null = null+export let capturedOnMessage: ((msg: unknown, assertCurrent?: () => void) => void | Promise<void>) | null = nullexport let capturedOnReconnect: ((info: { reconnectDurationMs: number }) => void | Promise<void>) | null = nullexport let capturedConnectionStateChange: ((phase: UserWsConnectionPhase) => void | Promise<void>) | null = nullexport let capturedUseUserWsOptions: UseUserWsOptions | undefined@@ -63,9 +63,13 @@ let stableSend: ReturnType<typeof vi.fn> = vi.fn()let stableReconnectNow: ReturnType<typeof vi.fn> = vi.fn()export let useUserWsCallCount = 0vi.mock("@/lib/use-user-ws", () => ({- useUserWs: (onMessage: (msg: unknown) => void, options?: UseUserWsOptions) => {+ useUserWs: (onMessage: (msg: unknown, assertCurrent?: () => void) => void | Promise<void>, options?: UseUserWsOptions) => {useUserWsCallCount += 1- capturedOnMessage = (message) => { act(() => { onMessage(message) }) }+ capturedOnMessage = (message, assertCurrent) => {+ let result: void | Promise<void>+ act(() => { result = onMessage(message, assertCurrent) })+ if ((message as { type?: unknown })?.type === "community:events.batch.v2") return result!+ }capturedOnReconnect = options?.onReconnect ?? nullcapturedConnectionStateChange = options?.onConnectionStateChange ?? nullcapturedUseUserWsOptions = optionsdiff --git a/src/web/src/hooks/community/facade-membership-composition.dom.test.ts b/src/web/src/hooks/community/facade-membership-composition.dom.test.tsindex 8b0e6285d..bca672bc5 100644--- a/src/web/src/hooks/community/facade-membership-composition.dom.test.ts+++ b/src/web/src/hooks/community/facade-membership-composition.dom.test.ts@@ -35,7 +35,7 @@ describe("membership facade composition", () => {apiFetchMock.mockImplementation(async (url: string) => {if (new URL(url, "https://alook.test").searchParams.get("cursor") === "next") return { members: [bob], hasMore: false }if (url.includes("/servers/s1/members?")) return { members: [alice], hasMore: true, cursor: "next" }- if (url === "/api/community/channels/c1/members") return { members: [alice] }+ if (url === "/api/community/channels/c1/members?relation=access") return { members: [alice] }return buckets(url)})const rendered = renderHook(() => useAddableMembers("s1", "c1"), { wrapper: Owner })diff --git a/src/web/src/hooks/community/forum-feed-window.ts b/src/web/src/hooks/community/forum-feed-window.tsindex ad1f86480..ce5f4a5dc 100644--- a/src/web/src/hooks/community/forum-feed-window.ts+++ b/src/web/src/hooks/community/forum-feed-window.ts@@ -1,44 +1,79 @@-import { FORUM_ARCHIVE_TAG } from "@alook/shared"+import { FORUM_ARCHIVE_TAG, normalizeCommunityChannelResource, normalizeCommunityMessageResource, type CommunityChannelResource, type CommunityThreadsRead, type CommunityMessageResource, type CommunityResourceProfile, type CommunityMemberRelation } from "@alook/shared"+import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"import type { InfiniteData } from "@tanstack/react-query"+import { resourceProfile, threadParticipantResources } from "@/lib/community/participant-resources"+import type { Msg, Thread } from "@/lib/community/models/message"+import type { ChannelRow } from "@/lib/community-db/schema"-export type ForumFeedTransportPage = {- serverId: string+export function projectThread(thread: ChannelRow, opener: Msg | undefined, parentType: string): Thread {+ return {+ id: thread.id,+ name: parentType === "forum" ? (opener?.content?.trim() ? opener.content : thread.name || "Post") : thread.name,+ messageCount: thread.messageCount ?? 0,+ lastMessageAt: thread.lastMessageAt ?? "",+ parent: { authorId: opener?.authorId, authorName: opener?.authorName ?? "", text: parentType === "forum" ? thread.preview ?? "" : opener?.content ?? thread.preview ?? "" },+ ...(opener?.seq === undefined ? {} : { parentSeq: opener.seq }),+ }+}++export type ForumFeedTransportPage = Pick<CommunityThreadsRead["page"], "hasMore"> & {+ serverId: NonNullable<CommunityChannelResource["serverId"]>parentType: string- threads: Array<{- id: string- name: string | null- creatorId: string | null- messageCount: number | null- parentMessageId: string | null- lastMessageAt: string | null- createdAt: string+ threads: Array<Pick<CommunityChannelResource, "id" | "name" | "creatorId" | "parentMessageId" | "lastMessageAt" | "createdAt"> & {+ messageCount: CommunityChannelResource["messageCount"] | nullactivityAt: string}>included: {- parentMessages: Array<{ id: string; channelId: string; seq: number; createdAt?: string; content: string; authorId: string; authorName: string; authorImage: string | null; authorAvatarVersion: number }>- firstMessages: Array<{ channelId: string; content: string }>- tags: Array<{ messageId: string; tag: string }>- participants: Array<{ channelId: string; userId: string; userName: string | null; userImage: string | null; userAvatarVersion: number; participantCount?: number }>+ parentMessages: Array<Required<Pick<CommunityMessageResource, "id" | "channelId" | "seq" | "content" | "authorId" | "authorName" | "authorAvatarVersion">> & Partial<Pick<CommunityMessageResource, "createdAt">> & { authorImage: CommunityResourceProfile["avatar"] }>+ firstMessages: Array<Pick<CommunityMessageResource, "channelId" | "content">>+ tags: CommunityThreadsRead["included"]["tags"]+ participants: Array<Pick<CommunityMemberRelation, "channelId" | "userId"> & { userName: CommunityResourceProfile["name"] | null; userImage: CommunityResourceProfile["avatar"]; userAvatarVersion: CommunityResourceProfile["avatarVersion"]; participantCount?: number }>+ }+ nextCursor?: NonNullable<CommunityThreadsRead["page"]["nextCursor"]>+}++export type CommunityThreadResources = {+ channel: Pick<CommunityChannelResource, "id" | "serverId" | "type">+ threads: Array<Pick<CommunityChannelResource, "id" | "name" | "creatorId" | "parentMessageId" | "createdAt" | "lastMessageAt" | "messageCount"> & Partial<Omit<CommunityChannelResource, "id" | "name" | "creatorId" | "parentMessageId" | "createdAt" | "lastMessageAt" | "messageCount">>>+ included: CommunityThreadsRead["included"] & { previews: Array<Pick<CommunityThreadsRead["included"]["messages"][number], "channelId" | "content">> }+ page: CommunityThreadsRead["page"]+}++export function normalizeThreadResources(channelId: string, value: ForumFeedTransportPage | CommunityThreadsRead): CommunityThreadResources {+ if ("contractVersion" in value) return { ...value, included: { ...value.included, previews: value.included.messages.filter((message) => message.channelId !== channelId) } }+ const participants = threadParticipantResources(value.included.participants.map((participant) => ({+ channelId: participant.channelId, userId: participant.userId, participantCount: participant.participantCount,+ isCreator: value.threads.some((thread) => thread.id === participant.channelId && thread.creatorId === participant.userId),+ profile: resourceProfile({ id: participant.userId, name: participant.userName ?? "Deleted user", avatar: canonicalUserImage(participant.userId, participant.userImage, participant.userAvatarVersion), avatarVersion: participant.userAvatarVersion }),+ })))+ return {+ channel: { id: channelId, serverId: value.serverId, type: value.parentType === "forum" ? "forum" : "text" },+ threads: value.threads.map((thread) => {+ const channel = normalizeCommunityChannelResource({ ...thread, type: "thread", serverId: value.serverId, parentChannelId: channelId, topic: "", position: 0, archived: false })+ const { archived: _archived, ...identity } = channel+ return identity+ }),+ included: {+ messages: value.included.parentMessages.map((message) => normalizeCommunityMessageResource({ ...message, type: "chat", createdAt: message.createdAt ?? "", authorAvatar: canonicalUserImage(message.authorId, message.authorImage, message.authorAvatarVersion) ?? avatarInitial(message.authorName) }, channelId)),+ previews: value.included.firstMessages, tags: value.included.tags, ...participants,+ },+ page: { hasMore: value.hasMore, nextCursor: value.nextCursor ?? null },}- hasMore: boolean- nextCursor?: string}-export type ForumFeedPage = {- serverId: string+export type ForumFeedPage = Pick<CommunityThreadsRead["page"], "hasMore"> & {+ serverId: NonNullable<CommunityChannelResource["serverId"]>parentType: string- threads: Array<{ id: string; openerMessageId: string | null; participantIds: string[] }>- hasMore: boolean- nextCursor?: string+ threads: Array<Pick<CommunityChannelResource, "id"> & { openerMessageId: CommunityChannelResource["parentMessageId"]; participantIds: Array<CommunityMemberRelation["userId"]> }>+ nextCursor?: NonNullable<CommunityThreadsRead["page"]["nextCursor"]>}-export function forumFeedWindow(page: ForumFeedTransportPage): ForumFeedPage {+export function forumFeedWindow(page: CommunityThreadResources): ForumFeedPage {return {- serverId: page.serverId,- parentType: page.parentType,- threads: page.threads.map((thread) => ({ id: thread.id, openerMessageId: thread.parentMessageId, participantIds: page.included.participants.filter((participant) => participant.channelId === thread.id).map((participant) => participant.userId) })),- hasMore: page.hasMore,- ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),+ serverId: page.channel.serverId ?? "", parentType: page.channel.type,+ threads: page.threads.map((thread) => ({ id: thread.id, openerMessageId: thread.parentMessageId, participantIds: page.included.members.filter((member) => member.channelId === thread.id).map((member) => member.userId) })),+ hasMore: page.page.hasMore, ...(page.page.nextCursor ? { nextCursor: page.page.nextCursor } : {}),}}diff --git a/src/web/src/hooks/community/message-surface-ownership.test.ts b/src/web/src/hooks/community/message-surface-ownership.test.tsindex aa427bae5..6ac7b898d 100644--- a/src/web/src/hooks/community/message-surface-ownership.test.ts+++ b/src/web/src/hooks/community/message-surface-ownership.test.ts@@ -19,7 +19,7 @@ import {} from "@/lib/community-db/sync"import type { Msg } from "@/lib/community/models/message"import { mapForumFeedPages } from "./use-forum-feed"-import { forumFeedWindow, type ForumFeedTransportPage } from "./forum-feed-window"+import { normalizeThreadResources, forumFeedWindow, type ForumFeedTransportPage } from "./forum-feed-window"import { materializeThreadsResponse, type ThreadsResponse } from "./use-channel-panels"let registry: CommunityDbRegistry | undefined@@ -102,7 +102,7 @@ describe("embedded message surface ownership", () => {surface,materializeCanonicalMessages(messages, canonical()).map((message) => message.content),])),- forum: mapForumFeedPages([forumFeedWindow(forumPage)], canonical(), channels(), new Map()).map((post) => post.name),+ forum: mapForumFeedPages([forumFeedWindow(normalizeThreadResources("c1", forumPage))], canonical(), channels(), new Map()).map((post) => post.name),threads: materializeThreadsResponse(threads, canonical(), channels()).map((thread) => thread.name),})diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 96b3e4c95..0fbc845cd 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -8,7 +8,7 @@ import { nanoid } from "nanoid"import { apiFetch } from "@/lib/api/client"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import {- publishCommunityChannelPatch, publishCommunityChannelFields, publishCommunityCategoryFields,+ retireCommunityChannelReading, publishCommunityChannelPatch, publishCommunityChannelFields, publishCommunityCategoryFields,publishCommunityCreatedChannel, publishCommunityCreatedCategory, publishCommunityDeletedCategory,type CommunityFreshQueryProof,} from "@/lib/community-db/sync"@@ -17,8 +17,6 @@ import { isAbortError } from "@/lib/errors"import type { ChannelRow, CategoryRow } from "@/lib/community-db/schema"import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"-import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"-import { projectChannelScopeEviction } from "@/hooks/community/community-ws/channel-scope-projection"// Prefix marks an optimistic row so every consumer can tell it from a real// `ch_…` id without a separate flag, and guarantees it never collides with one.@@ -176,11 +174,7 @@ export function useRenameChannel() {}return result!},- onSettled: (_data, error, args) => {- if (isAbortError(error) || !origin.registry?.runtime.lifecycle.get().active) return- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true, predicate: (query) => args.resources.includes(query) })- invalidateChannelRefDirectory(queryClient, args)- },+ onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),})}@@ -218,7 +212,7 @@ export function useDeleteChannel() {await apiFetch(`/api/community/channels/${args.channelId}`, { method: "DELETE", ...options })origin.assert(proof.token)getActiveAccountUnreadProjection(queryClient).retireAccessScope({ kind: "channel", channelId: args.channelId })- runCommunityWsProjectionTransaction(queryClient, (projection) => projectChannelScopeEviction(projection, queryClient, args.serverId, args.channelId))+ retireCommunityChannelReading(origin.registry!, args.channelId, { reason: "resource-deleted", serverId: args.serverId })}),onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),})diff --git a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts b/src/web/src/hooks/community/mutations/forum-commands.dom.test.tsindex e20694166..f485ca695 100644--- a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts+++ b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts@@ -5,14 +5,14 @@ import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { communityKeys } from "@/lib/query-keys"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"import { captureCommunityLiveSnapshotToken, projectCommunityWsEventToDb, publishCommunityForumSidebar, publishCommunityForumFeed, publishCommunityForumTags, getCanonicalCommunityChannelMemberships, removeCanonicalCommunityChannelMembership } from "@/lib/community-db/sync"import { mapForumFeedPages } from "../use-forum-feed"import { useForumTags } from "../use-channel-panels"-import { forumFeedWindow, forumFeedMatchesTags, type ForumFeedPage, type ForumFeedTransportPage } from "../forum-feed-window"+import { normalizeThreadResources, forumFeedWindow, forumFeedMatchesTags, type ForumFeedPage, type ForumFeedTransportPage } from "../forum-feed-window"import { getForumSidebarBase } from "../use-forum-sidebar-threads"-import { getActiveAccountUnreadProjection } from "../account-unread-projection"+import { getAccountUnreadProjection } from "../account-unread-projection"import { applyForumPostUnitClientEffects } from "../community-ws/channel-scope-projection"import { useCreateForumThread, useUpdatePostTags, useDeleteForumThread } from "./forum"@@ -60,8 +60,8 @@ async function setup(ids = ["before", "p2", "after"], observeCatalog = false) {function seed(rows: string[], append = false) {const page = wire(rows), token = captureCommunityLiveSnapshotToken(owner.client)publishCommunityForumSidebar(owner.client, { serverId: "server_1", channels: page.threads.map((row) => ({ ...row, name: row.name!, unread: false, parentChannelId: "forum_1", type: "thread", archived: false })), openers: page.included.parentMessages, proof: { token, signal: undefined } })- publishCommunityForumFeed(owner.client, "forum_1", page, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })- for (const filter of [null, "bug", "archived"]) owner.client.setQueryData<InfiniteData<ForumFeedPage>>(communityKeys.forumFeed("forum_1", filter), (current) => ({ pages: append && current ? [{ ...current.pages[0], threads: [...current.pages[0].threads, ...forumFeedWindow(page).threads] }] : [forumFeedWindow(page)], pageParams: [null] }))+ publishCommunityForumFeed(owner.client, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })+ for (const filter of [null, "bug", "archived"]) owner.client.setQueryData<InfiniteData<ForumFeedPage>>(communityKeys.forumFeed("forum_1", filter), (current) => ({ pages: append && current ? [{ ...current.pages[0], threads: [...current.pages[0].threads, ...forumFeedWindow(normalizeThreadResources("forum_1", page)).threads] }] : [forumFeedWindow(normalizeThreadResources("forum_1", page))], pageParams: [null] }))}act(() => {projectCommunityWsEventToDb(owner.client, { type: "community:channel.create", serverId: "server_1", channel: { id: "forum_1", name: "Forum", type: "forum", categoryId: null, position: 0, createdAt: new Date().toISOString() } })@@ -95,6 +95,18 @@ describe("Native forum creation", () => {expect(mocks.api.mock.calls[1][0]).toBe("/api/community/channels/p_new/messages")expect(JSON.parse(mocks.api.mock.calls[1][1].body)).toEqual({ content: "body", nonce: "command_1:reply" })})+ it("publishes the actual returned opener and linked child before the reply settles", async () => {+ const view = await setup(), held = deferred()+ const opener = { id: "created-opener", seq: 40, type: "chat", content: "New post", authorId: "viewer", authorName: "Viewer", createdAt: "2026-10-08T01:00:00Z" }+ mocks.api.mockResolvedValueOnce({ threadId: "p_new", message: opener }).mockReturnValueOnce(held.promise)+ let request!: Promise<unknown>+ act(() => { request = view.view.result.current.create.mutateAsync({ nonce: "create_1", channelId: "forum_1", name: "New post", content: "Body" }) })+ await waitFor(() => expect(mocks.api).toHaveBeenCalledTimes(2))+ expect(view.registry.collections.messages.get(opener.id)).toMatchObject({ channelId: "forum_1", content: "New post", clientNonce: "create_1:opener", seq: 40 })+ expect(view.registry.collections.channels.get("p_new")).toMatchObject({ serverId: "server_1", parentChannelId: "forum_1", parentMessageId: opener.id, name: "New post", type: "thread" })+ await act(async () => { held.resolve({}); await request })+ expect(view.registry.collections.messages.get("opener_p2")).toBeDefined()+ })it("reserves attachment IDs for both messages and broadcasts mentionType on the opener", async () => {const view = await setup(), attachments = [{ id: "att_1", filename: "abc.png", contentType: "image/png", size: 100, width: 10, height: 10 }]mocks.api.mockResolvedValueOnce({ threadId: "p_new" }).mockResolvedValueOnce({})@@ -257,7 +269,8 @@ describe("Native forum tag transactions", () => {describe("Native forum post deletion", () => {it("clears local stream, unread and active route once without requiring a self WS frame", async () => {- const view = await setup(), projection = getActiveAccountUnreadProjection(view.client)+ const view = await setup(), projection = getAccountUnreadProjection(view.client, view.registry.accountId!)+ const disk = vi.spyOn(view.registry, "retireReadingDisk").mockResolvedValue(undefined)act(() => {projection.recordArrival({ channelId: "p2", serverId: "server_1", seq: 1 })view.runtime.ui.actions.setCurrentServerId("server_1"); view.runtime.ui.actions.setCurrentChannelId("p2")@@ -269,7 +282,7 @@ describe("Native forum post deletion", () => {const { held, request } = await begin(view, "remove")await act(async () => { held.resolve(); await request })expect(view.runtime.messageStream.get().entries.has("channel:p2")).toBe(false)- expect(getMessageOverlay(view.client, { kind: "channel", id: "forum_1", serverId: "server_1" }).liveById.has("opener_p2")).toBe(false)+ expect(getMessageStreamState(view.client, { kind: "channel", id: "forum_1", serverId: "server_1" }).liveIds.includes("opener_p2")).toBe(false)expect(view.runtime.ui.get()).toMatchObject({ currentChannelId: "forum_1" })expect(view.registry.collections.channels.has("p2")).toBe(false)expect(mocks.clearLastChannel).toHaveBeenCalledOnce()@@ -279,6 +292,8 @@ describe("Native forum post deletion", () => {expect(projection.projectUnread("inbox-unreads", "p2", true, 1)).toBe(false)act(() => applyForumPostUnitClientEffects(view.client, { serverId: "server_1", forumChannelId: "forum_1", childChannelId: "p2", openerMessageId: "opener_p2" }))expect(mocks.clearLastChannel).toHaveBeenCalledOnce(); expect(view.navigate).toHaveBeenCalledOnce()+ expect(disk).toHaveBeenCalledOnce()+ expect(disk).toHaveBeenCalledWith(new Set(["p2"]), true)})it("optimistically hides both canonical post identities and DELETEs the exact opener", async () => {const view = await setup(), { held, request } = await begin(view, "remove")@@ -291,7 +306,7 @@ describe("Native forum post deletion", () => {expect(view.client.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)})it("restores canonical post/sidebar and exact original ID windows on DELETE failure", async () => {- const view = await setup(), projection = getActiveAccountUnreadProjection(view.client)+ const view = await setup(), projection = getAccountUnreadProjection(view.client, view.registry.accountId!)projection.recordArrival({ channelId: "p2", serverId: "server_1", seq: 1 })view.client.setQueryData(communityKeys.channelMeta("server_1", "p2"), { id: "p2" })const keys = [communityKeys.channelMessages("forum_1"), communityKeys.forumFeed("forum_1", null), communityKeys.forumSidebarThreads("server_1"), communityKeys.channelMeta("server_1", "p2")], before = keys.map((key) => view.client.getQueryData(key)), sidebar = getForumSidebarBase(view.client, "server_1")@@ -309,7 +324,7 @@ describe("Native forum post deletion", () => {describe("Native forum partition and transaction controls", () => {const ids = (view: View, filter: "all" | "bug" | "archived" = "all") => view.view.result.current[filter].map(({ id }) => id)function window(view: View, filter: string | null, pages: string[][], pageParams: (string | null)[] = pages.map((_, index) => index ? `cursor_${index}` : null)) {- act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", filter), { pages: pages.map((rows) => forumFeedWindow(wire(rows))), pageParams }))+ act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", filter), { pages: pages.map((rows) => forumFeedWindow(normalizeThreadResources("forum_1", wire(rows)))), pageParams }))}function wsTags(view: View, tags: string[], id = "p2") {act(() => projectCommunityWsEventToDb(view.client, { type: "community:channel.update", serverId: "server_1", channelId: id, changes: { tags } }))@@ -414,7 +429,7 @@ describe("Native forum partition and transaction controls", () => {})it("projects WS membership only through the canonical opener identity", async () => {const view = await setup(["p2"])- const invalid = forumFeedWindow(wire(["p2"]))+ const invalid = forumFeedWindow(normalizeThreadResources("forum_1", wire(["p2"])))invalid.threads[0].openerMessageId = "retired_opener"act(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", "bug"), { pages: [invalid], pageParams: [null] }))await waitFor(() => expect(ids(view, "bug")).toEqual([]))@@ -423,7 +438,7 @@ describe("Native forum partition and transaction controls", () => {expect(ids(view, "archived")).toEqual(["p2"])})it("does not manufacture opener evidence for a malformed transport window", async () => {- const view = await setup(["p2"]), invalid = forumFeedWindow(wire(["p2"]))+ const view = await setup(["p2"]), invalid = forumFeedWindow(normalizeThreadResources("forum_1", wire(["p2"])))invalid.threads[0].openerMessageId = nullact(() => view.client.setQueryData(communityKeys.forumFeed("forum_1", null), { pages: [invalid], pageParams: ["invalid_cursor"] }))await waitFor(() => expect(ids(view)).toEqual([]))diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex ad8a1e12a..342811488 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -15,16 +15,15 @@ import {} from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"-import { collectChannelScopeIds } from "../community-ws/scope-eviction"import { communityKeys } from "@/lib/query-keys"-import type { UploadedAttachment } from "@/hooks/community/mutations/uploads"+import type { UploadFileResult } from "@/hooks/community/mutations/uploads"import type { MentionType } from "@alook/shared"import { FORUM_ARCHIVE_TAG } from "@alook/shared"import {applyForumPostUnitClientEffects,type ForumPostUnitIdentity,} from "@/hooks/community/community-ws/channel-scope-projection"-import { beginCommunityCommandRevision, publishCommunityDeletedForumPost, publishCommunityCreatedChannel, publishCommunityForumTags, publishCommunityMessages } from "@/lib/community-db/sync"+import { collectChannelScopeIds, beginCommunityCommandRevision, publishCommunityCreatedChannel, publishCommunityForumTags, publishCommunityMessages } from "@/lib/community-db/sync"import { projectPostedMessage, type PostedMessage } from "@/lib/community/message-wire"import { reconcileForumSidebarArchiveTag } from "../use-forum-sidebar-threads"@@ -38,7 +37,7 @@ export type CreateForumThreadArgs = {// (creating pending rows) before firing this mutation and passes the// descriptors here; only their `id`s reach the server (reserve-by-id,// route/disc step 2b), which links them onto the post's first message.- attachments?: UploadedAttachment[]+ attachments?: UploadFileResult[]// Propagated to the first message so `@everyone` audience broadcast// fires end-to-end.mentionType?: MentionType@@ -68,7 +67,7 @@ export function useCreateForumThread() {assert()const parent = origin.registry!.collections.channels.get(channelId)if (parent && structure.message) {- publishCommunityMessages(queryClient, { channelId, messages: [projectPostedMessage(structure.message, `${nonce}:opener`)], proof: { token, signal: assertActive?.signal } })+ publishCommunityMessages(queryClient, { channelId, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })publishCommunityCreatedChannel(queryClient, { id: structure.threadId, serverId: parent.serverId, categoryId: null, name, type: "thread", parentChannelId: channelId, parentMessageId: structure.message.id, creatorId: structure.message.authorId, position: 0, archived: false, muted: false, unread: false, tags: [], pending: false, createdAt: structure.message.createdAt, lastMessageAt: structure.message.createdAt, messageCount: 0 }, { token, signal: assertActive?.signal })}assert()@@ -77,7 +76,7 @@ export function useCreateForumThread() {body: JSON.stringify({ content, attachments: attachmentIds, nonce: `${nonce}:reply` }),})assert()- if (reply.message) publishCommunityMessages(queryClient, { channelId: structure.threadId, messages: [projectPostedMessage(reply.message, `${nonce}:reply`)], proof: { token, signal: assertActive?.signal } })+ if (reply.message) publishCommunityMessages(queryClient, { channelId: structure.threadId, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })for (const query of resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)return structure},@@ -231,7 +230,12 @@ export function useDeleteForumThread() {})assertOwner()try { origin.assert(token) } catch { return }- if (publishCommunityDeletedForumPost(queryClient, unit, { token, signal: controller.signal })) applyForumPostUnitClientEffects(queryClient, unit, { queries: new Set(args.resources), assertView: assert, canonical: false })+ let navigationAllowed = true+ try { assert() } catch { navigationAllowed = false }+ applyForumPostUnitClientEffects(queryClient, unit, { proof: { token, signal: controller.signal }, queries: new Set(args.resources), assertView: () => {+ if (!navigationAllowed) throw new DOMException("Retired post navigation", "AbortError")+ args.view.assertOwner()+ } })for (const query of args.resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query && [communityKeys.channelMessages(args.forumChannelId), communityKeys.threads(args.forumChannelId), communityKeys.forumTags(args.forumChannelId), communityKeys.server(args.serverId)].some((key) => startsWithQueryKey(query.queryKey, key))) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)} catch (error) { assertOwner(); throw error }finally { subscription.unsubscribe() }diff --git a/src/web/src/hooks/community/mutations/friends.dom.test.ts b/src/web/src/hooks/community/mutations/friends.dom.test.tsindex 138cb6c30..57ceb1f56 100644--- a/src/web/src/hooks/community/mutations/friends.dom.test.ts+++ b/src/web/src/hooks/community/mutations/friends.dom.test.ts@@ -4,7 +4,7 @@ import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityDbProvider, useFriendshipRows, useAttentionItems } from "@/lib/community-db/projections"-import { captureCommunityLiveSnapshotToken, publishCommunityFriendships, publishAccountAttentionSnapshot, projectCommunityWsEventToDb } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken, ingestDms, ingestMessages, publishCommunityFriendships, publishAccountAttentionSnapshot, projectCommunityWsEventToDb } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"import * as commands from "./friends"@@ -154,11 +154,41 @@ describe("native friendship commands", () => {expect(client.getQueryData(communityKeys.friends())).toBeUndefined(); exactFriends(invalidate)})it("publishes a canonical block and invalidates Friends", async () => {- seed(); const rendered = mount(commands.useBlockUser), invalidate = vi.spyOn(client, "invalidateQueries")- await act(async () => { await rendered.result.current.command.mutateAsync({ userId: "u_a" }) })+ seed()+ ingestDms(registry, { conversations: [{ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" }] })+ ingestMessages(registry, "dm_a", [{ id: "private", type: "chat", content: "private body", seq: 1 }])+ const rendered = mount(commands.useBlockUser), invalidate = vi.spyOn(client, "invalidateQueries"), success = vi.fn()+ await act(async () => { await rendered.result.current.command.mutateAsync({ userId: "u_a" }, { onSuccess: success }) })expect(registry.collections.friendships.get("blocked:u_a")?.kind).toBe("blocked")+ expect(registry.runtime.ws.actions.isChannelAccessRevoked("dm_a", null)).toBe(true)+ expect(registry.collections.channels.has("dm_a")).toBe(true)+ expect(registry.collections.messages.has("private")).toBe(false)+ expect(success).toHaveBeenCalledOnce()expect(registry.collections.attentionItems.has("friend_request:a")).toBe(false); exactFriends(invalidate)})+ it("keeps visible DM reading intact when the normal block command fails", async () => {+ seed()+ ingestDms(registry, { conversations: [{ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" }] })+ ingestMessages(registry, "dm_a", [{ id: "private", type: "chat", content: "private body", seq: 1 }])+ const held = hold(), rendered = mount(commands.useBlockUser), pending = start(rendered.result.current.command, { userId: "u_a" })+ await waitFor(() => expect(api).toHaveBeenCalledOnce())+ await act(async () => { held.reject(new Error("block failed")); await pending })+ expect(registry.runtime.ws.actions.isChannelAccessRevoked("dm_a", null)).toBe(false)+ expect(registry.collections.messages.get("private")?.content).toBe("private body")+ expect(registry.collections.friendships.has("blocked:u_a")).toBe(false)+ })+ it("starts a new permission generation after a confirmed own unblock", async () => {+ seed([{ id: "blocked:u_a", userId: "u_a", kind: "blocked" }])+ ingestDms(registry, { conversations: [{ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "" }] })+ registry.runtime.ws.actions.revokeChannelAccess(null, "dm_a")+ const generation = registry.runtime.ws.get().channelAccessScopes.get("dm_a")!.generation+ const rendered = mount(commands.useUnblockUser)+ await act(async () => { await rendered.result.current.command.mutateAsync({ userId: "u_a" }) })+ expect(registry.runtime.ws.actions.isChannelAccessRevoked("dm_a", null)).toBe(false)+ expect(registry.runtime.ws.get().channelAccessScopes.get("dm_a")!.generation).toBe(generation + 1)+ expect(registry.collections.friendships.has("blocked:u_a")).toBe(false)+ expect(registry.collections.messages.size).toBe(0)+ })it("restores a blocked row when unblock fails", async () => {seed([{ ...incoming("a"), kind: "blocked" }]); const held = hold(), rendered = mount(commands.useUnblockUser), pending = start(rendered.result.current.command, { userId: "u_a" })await waitFor(() => expect(ids()).toEqual([]))diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.tsindex 5053f8215..3ae997d16 100644--- a/src/web/src/hooks/community/mutations/friends.ts+++ b/src/web/src/hooks/community/mutations/friends.ts@@ -7,7 +7,7 @@ import { beginCommunityCommandRevision, captureCommunityLiveSnapshotToken } fromimport { reconcileAccountAttention } from "../use-account-attention"import { useCommunityMutationOrigin } from "../community-origin"import { communityKeys } from "@/lib/query-keys"-import { publishCommunityFriendBlock, publishCommunityFriendDecision, removeSettledCommunityFriendCommands } from "@/lib/community-db/sync"+import { applyCommunityDmBlockAccess, publishCommunityFriendBlock, publishCommunityFriendDecision, removeSettledCommunityFriendCommands } from "@/lib/community-db/sync"import { isAbortError } from "@/lib/errors"export type SendFriendRequestArgs = { username?: string; userId?: string }@@ -66,8 +66,10 @@ function useFriendCommand<Args extends object>(action: string, build: (args: Argif (!error || isAbortError(error) || (row?.kind !== "incoming" && row?.kind !== "outgoing")) {for (const mutation of queryClient.getMutationCache().findAll({ mutationKey: ["community", "friend-request"], predicate: (entry) => entry.state.variables === args })) queryClient.getMutationCache().remove(mutation)}+ const command = build(args)+ if (!error && command.userId && command.blocked !== undefined) applyCommunityDmBlockAccess(origin.registry!, command.userId, command.blocked)},- })+ }, action === "block" ? (args) => origin.assertOwner(args.original) : undefined)}export function useSendFriendRequest() { return useFriendCommand<SendFriendRequestArgs>("send", ({ username, userId }) => ({ path: "/api/community/friends/request", method: "POST", body: JSON.stringify({ username, userId }) })) }diff --git a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsxindex 2a4481e0d..119ff53ef 100644--- a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx+++ b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx@@ -8,6 +8,7 @@ import { QueryProvider } from "@/app/c/QueryProvider"import { clearAllPersistedCaches } from "@/lib/query-persister"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useCanonicalMessagesById } from "@/lib/community-db/projections"+import * as projections from "@/lib/community-db/projections"import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"import { useMessage } from "../use-message"@@ -21,12 +22,12 @@ vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ dvi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }) }))vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))let client: QueryClient, edit: ReturnType<typeof useEditMessage>-function Probe() {+function Probe({ messageId = "m1" }: { messageId?: string | null }) {const currentClient = useQueryClient(), command = useEditMessage(); useLayoutEffect(() => { client = currentClient; edit = command })- const exact = useMessage("m1"), rows = useCanonicalMessagesById()+ const exact = useMessage(messageId), rows = useCanonicalMessagesById()return <><output data-testid="exact">{exact.message?.content ?? "missing"}</output><output data-testid="canonical">{rows?.get("m1")?.content ?? "missing"}</output></>}-function Root({ id = sdk.id }: { id?: string }) { return <QueryProvider userId={id}><Probe /></QueryProvider> }+function Root({ id = sdk.id, messageId }: { id?: string; messageId?: string | null }) { return <QueryProvider userId={id}><Probe messageId={messageId} /></QueryProvider> }const args = { serverId: "s1", channelId: "c1", messageId: "m1", content: "requested" }async function mount() {let resolve!: (value: unknown) => void, reject!: (error: Error) => void@@ -47,6 +48,20 @@ function command() { return edit.mutateAsync(args).catch((error) => error) }async function pending() { await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "PATCH")).toBe(true)) }beforeEach(async () => { await clearAllPersistedCaches(); api.mockReset(); sdk.id = "A" })describe("actual canonical message field command", () => {+ it("subscribes the exact message to its ID and selects no rows without an ID", async () => {+ const subscription = vi.spyOn(projections, "useCanonicalMessagesById")+ try {+ const { view } = await mount()+ expect(subscription).toHaveBeenCalledWith(["m1"])+ const requests = api.mock.calls.length+ subscription.mockClear()+ act(() => view.rerender(<Root messageId={null} />))+ expect(subscription).toHaveBeenCalledWith([])+ expect(screen.getByTestId("exact").textContent).toBe("missing")+ expect(screen.getByTestId("canonical").textContent).toBe("original")+ expect(api.mock.calls).toHaveLength(requests)+ } finally { subscription.mockRestore() }+ })it.each(["edit", "reaction"] as const)("WS %s updates canonical facts without overwriting the exact-message ID transport", async (kind) => {const { original } = await mount(), runtime = getCommunityRuntime(original)act(() => dispatchCommunityWsEvent(kind === "edit"diff --git a/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts b/src/web/src/hooks/community/mutations/message-reactions.dom.test.tsindex baf416e59..c89cfaa7e 100644--- a/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts+++ b/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts@@ -6,7 +6,7 @@ import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/commuimport { CommunityDbProvider, useCanonicalMessagesById } from "@/lib/community-db/projections"import { captureCommunityLiveSnapshotToken, publishCommunityMessages, projectCommunityWsEventToDb } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import { useAddReactionApi, useToggleReactionApi } from "./message-reactions"import type { Msg } from "@/lib/community/models/message"@@ -116,11 +116,13 @@ describe("native reaction intents — original debounce and rollback guarantees"api.mockRejectedValueOnce(new Error("boom")); vi.useFakeTimers()act(() => rendered.result.current.toggle({ ...args, channelId: kind === "channel" ? id : undefined, dmId: kind === "dm" ? id : undefined }))await advance(0)- expect(getMessageOverlay(client, scope).liveById.get("m_1")?.reactions).toEqual([])+ expect(getMessageStreamState(client, scope).liveIds).toContain("m_1")+ expect(registry.collections.messages.get("m_1")?.reactions).toEqual([])await advance()expect(api).toHaveBeenCalledWith(expect.stringContaining("/api/community/messages/m_1/reactions/"), expect.objectContaining({ method: "DELETE" }))- expect(getMessageOverlay(client, scope).liveById.size).toBe(1)- expect(getMessageOverlay(client, scope).liveById.get("m_1")?.reactions).toEqual(mine)+ expect(getMessageStreamState(client, scope).liveIds.length).toBe(1)+ expect(getMessageStreamState(client, scope).liveIds).toContain("m_1")+ expect(registry.collections.messages.get("m_1")?.reactions).toEqual(mine)expect(client.getQueryData(key)).toEqual(base)expect(registry.collections.messages.size).toBe(1)})@@ -129,8 +131,22 @@ describe("native reaction intents — original debounce and rollback guarantees"api.mockRejectedValueOnce(new Error("boom")); vi.useFakeTimers()act(() => rendered.result.current.toggle({ ...args, channelId: undefined, dmId: "dm_1", messageId: "missing" }))await advance(500)- expect(getMessageOverlay(client, { kind: "dm", id: "dm_1" }).liveById.size).toBe(0)+ expect(getMessageStreamState(client, { kind: "dm", id: "dm_1" }).liveIds.length).toBe(0)expect(registry.collections.messages.size).toBe(0)+ expect(api).toHaveBeenCalledOnce()+ })+ it("cancels a no-row reaction when its original view retires during the delay", async () => {+ const rendered = mounted(), controller = new AbortController(), onError = vi.fn()+ const assertActive = Object.assign(() => controller.signal.throwIfAborted(), { signal: controller.signal })+ vi.useFakeTimers()+ act(() => rendered.result.current.toggle({ ...args, messageId: "missing", assertActive, onError }))+ await advance(100)+ act(() => controller.abort(new DOMException("Retired view", "AbortError")))+ await advance(400)+ expect(api).not.toHaveBeenCalled()+ expect(onError).not.toHaveBeenCalled()+ expect(registry.collections.messages.size).toBe(0)+ expect(client.getMutationCache().findAll({ status: "pending" })).toHaveLength(0)})it.each([3, 5])("%s rapid alternating clicks settle to exactly one API call at the end of the window", async (clicks) => {seed(); api.mockResolvedValue(undefined)diff --git a/src/web/src/hooks/community/mutations/message-reactions.ts b/src/web/src/hooks/community/mutations/message-reactions.tsindex de4486597..8df682118 100644--- a/src/web/src/hooks/community/mutations/message-reactions.ts+++ b/src/web/src/hooks/community/mutations/message-reactions.ts@@ -6,7 +6,7 @@ import { useCallback } from "react"import { useMutation, useQueryClient } from "@tanstack/react-query"import { beginCommunityCommandRevision, publishCommunityMessageReaction, type CommunityLiveSnapshotToken } from "@/lib/community-db/sync"import { isAbortError } from "@/lib/errors"-import type { Msg } from "@/lib/community/models/message"+import { applyMessageReaction, type Msg } from "@/lib/community/models/message"import { useCommunityMutationOrigin } from "../community-origin"import type { ReactionArgs } from "./message-command-inputs"@@ -14,18 +14,30 @@ const key = ["community", "message-reaction"] as consttype ReactionProtocol = { requestStarted: boolean; transaction: Transaction<Record<string, unknown>> | null }type Intent = ReactionArgs & { token: CommunityLiveSnapshotToken; originalMe: boolean; nextMe: boolean; readyAt: number; protocol: ReturnType<typeof createStore<ReactionProtocol>> }function same(a: Intent, b: ReactionArgs) { return a.messageId === b.messageId && a.emoji === b.emoji && a.userId === b.userId }-function reactions(source: Msg["reactions"], args: Intent) {- const rows = (source ?? []).map((row) => ({ ...row, userIds: [...row.userIds] }))- const row = rows.find((candidate) => candidate.emoji === args.emoji)- if (args.nextMe) { if (row && !row.userIds.includes(args.userId)) row.userIds.push(args.userId); else if (!row) rows.push({ emoji: args.emoji, count: 1, me: true, userIds: [args.userId] }) }- else if (row) row.userIds = row.userIds.filter((id) => id !== args.userId)- return rows.filter((row) => row.userIds.length).map((row) => ({ ...row, count: row.userIds.length, me: row.userIds.includes(args.userId) }))-}+function useReactionIntent(intent: "toggle" | "add") {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const assert = (args: Intent) => { origin.assert(args.token); args.assertActive?.() }const pending = useCallback((args: ReactionArgs) => queryClient.getMutationCache().findAll({ mutationKey: key, status: "pending", predicate: (mutation) => same(mutation.state.variables as Intent, args) }).map((mutation) => mutation.state.variables as Intent), [queryClient])+ const persist = async (args: Intent) => {+ const delay = Math.max(0, args.readyAt - Date.now())+ if (delay) await new Promise<void>((resolve, reject) => {+ const cleanup = () => { clearTimeout(timer); args.assertActive?.signal.removeEventListener("abort", abort); subscription.unsubscribe() }+ const abort = () => { cleanup(); reject(new DOMException("Retired reaction", "AbortError")) }+ const timer = setTimeout(() => { cleanup(); resolve() }, delay)+ const subscription = origin.registry!.runtime.lifecycle.subscribe(() => { try { assert(args) } catch { abort() } })+ args.assertActive?.signal.addEventListener("abort", abort, { once: true })+ try { assert(args) } catch { abort() }+ })+ assert(args)+ if (pending(args).at(-1) !== args || args.nextMe === args.originalMe) return+ args.protocol.setState((state) => ({ ...state, requestStarted: true }))+ const proof = beginCommunityCommandRevision(queryClient, args.token)+ await origin.request(args.token, `/api/community/messages/${args.messageId}/reactions/${encodeURIComponent(args.emoji)}`, { method: args.nextMe ? "PUT" : "DELETE", signal: args.assertActive?.signal, assertActive: args.assertActive })+ assert(args)+ publishCommunityMessageReaction(queryClient, args.messageId, args.emoji, args.userId, args.nextMe, { token: proof, signal: args.assertActive?.signal })+ }const mutation = useMutation<void, Error, Intent>({ meta: { observabilityAction: intent === "add" ? "message.reaction.add" : "message.reaction.toggle" },mutationKey: key, scope: { id: "community-reaction-commands" }, gcTime: 0,onMutate: async (args) => {@@ -33,51 +45,16 @@ function useReactionIntent(intent: "toggle" | "add") {assert(args)await origin.registry!.collections.messages.preload()assert(args)- const persist = async () => {- const delay = Math.max(0, args.readyAt - Date.now())- if (delay) await new Promise<void>((resolve, reject) => {- const cleanup = () => { clearTimeout(timer); args.assertActive?.signal.removeEventListener("abort", abort); subscription.unsubscribe() }- const abort = () => { cleanup(); reject(new DOMException("Retired reaction", "AbortError")) }- const timer = setTimeout(() => { cleanup(); resolve() }, delay)- const subscription = origin.registry!.runtime.lifecycle.subscribe(() => { try { assert(args) } catch { abort() } })- args.assertActive?.signal.addEventListener("abort", abort, { once: true })- try { assert(args) } catch { abort() }- })- assert(args)- if (pending(args).at(-1) !== args || args.nextMe === args.originalMe) return- args.protocol.setState((state) => ({ ...state, requestStarted: true }))- const proof = beginCommunityCommandRevision(queryClient, args.token)- await origin.request(args.token, `/api/community/messages/${args.messageId}/reactions/${encodeURIComponent(args.emoji)}`, { method: args.nextMe ? "PUT" : "DELETE", signal: args.assertActive?.signal, assertActive: args.assertActive })- assert(args)- publishCommunityMessageReaction(queryClient, args.messageId, args.emoji, args.userId, args.nextMe, { token: proof, signal: args.assertActive?.signal })- }- const transaction = origin.registry!.dbClient.createTransaction({ autoCommit: false, mutationFn: persist })+ const transaction = origin.registry!.dbClient.createTransaction({ autoCommit: false, mutationFn: () => persist(args) })args.protocol.setState((state) => ({ ...state, transaction }))- transaction.mutate(() => { if (origin.registry!.collections.messages.has(args.messageId)) origin.registry!.collections.messages.update(args.messageId, (row) => { row.reactions = reactions(row.reactions as Msg["reactions"], args) }) })- return { persist }+ transaction.mutate(() => { if (origin.registry!.collections.messages.has(args.messageId)) origin.registry!.collections.messages.update(args.messageId, (row) => { row.reactions = applyMessageReaction(row.reactions as Msg["reactions"], args.emoji, args.userId, args.nextMe, args.userId) }) })+ return { persist: () => persist(args) }},mutationFn: async (args, _context) => {assert(args)const transaction = args.protocol.get().transactionif (transaction?.mutations.length) await transaction.commit()- else {- const delay = Math.max(0, args.readyAt - Date.now())- if (delay) await new Promise<void>((resolve, reject) => {- const cleanup = () => { clearTimeout(timer); args.assertActive?.signal.removeEventListener("abort", abort); subscription.unsubscribe() }- const abort = () => { cleanup(); reject(new DOMException("Retired reaction", "AbortError")) }- const timer = setTimeout(() => { cleanup(); resolve() }, delay)- const subscription = origin.registry!.runtime.lifecycle.subscribe(() => { try { assert(args) } catch { abort() } })- args.assertActive?.signal.addEventListener("abort", abort, { once: true })- try { assert(args) } catch { abort() }- })- assert(args)- if (pending(args).at(-1) !== args || args.nextMe === args.originalMe) return- args.protocol.setState((state) => ({ ...state, requestStarted: true }))- const proof = beginCommunityCommandRevision(queryClient, args.token)- await origin.request(args.token, `/api/community/messages/${args.messageId}/reactions/${encodeURIComponent(args.emoji)}`, { method: args.nextMe ? "PUT" : "DELETE", signal: args.assertActive?.signal, assertActive: args.assertActive })- assert(args)- publishCommunityMessageReaction(queryClient, args.messageId, args.emoji, args.userId, args.nextMe, { token: proof, signal: args.assertActive?.signal })- }+ else await persist(args)assert(args)},onError: (error, args) => { if (isAbortError(error)) return; try { assert(args) } catch { return } args.onError?.(error) },diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.tsindex e0b115dd8..2c603c644 100644--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts@@ -1,3 +1,5 @@+import { canonicalMessageReader } from "@/test/community-query-owner"+import { materializeMessageStream } from "@/lib/community/message-stream"import { createElement, type PropsWithChildren } from "react"import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"@@ -236,12 +238,106 @@ describe("useEditMessage", () => {// ── useSendMessage ────────────────────────────────────────────────────────describe("useSendMessage — happy path", () => {+ it.each([+ ["POST→WS→base", ["post", "ws", "base"]],+ ["WS→POST→base", ["ws", "post", "base"]],+ ["base→POST→WS", ["base", "post", "ws"]],+ ["WS→base→POST", ["ws", "base", "post"]],+ ["POST→matching GET base", ["post", "matchingBase"]],+ ["matching GET base→POST", ["matchingBase", "post"]],+ ] as const)("keeps one rich confirmed row and releases previews once for %s", async (_name, stages) => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ const runtime = canonicalRegistry.runtime+ runtime.ui.actions.setCurrentServerId(scope.serverId)+ runtime.ui.actions.subscribe({ channelId: scope.id })+ const replyTo = { id: "reply_1", authorName: "Reply Author", text: "preview" }+ const attachment = { id: "file_1", filename: "notes.txt", contentType: "text/plain", size: 1024 }+ const remoteAttachment = { kind: "file" as const, name: attachment.filename,+ url: "/api/community/channels/ch_1/attachments/file_1", contentType: attachment.contentType,+ sizeBytes: attachment.size, size: "1.0 KB" }+ const revoke = vi.fn(), originalRevoke = URL.revokeObjectURL+ URL.revokeObjectURL = revoke+ try {+ runtime.messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1",+ message: { type: "chat", content: "optimistic", authorId: "u_me", replyTo },+ localUploads: [{ file: new File(["local"], "notes.txt", { type: "text/plain" }), previewObjectUrl: "blob:owned" }],+ })+ runtime.messageStream.actions.dispatch(scope, { type: "uploadSettled", nonce: "n1", attachments: [remoteAttachment] })+ let release!: (value: { message: ReturnType<typeof postedMessage> }) => void+ apiFetchMock.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))+ const mod = await loadMod()+ mountHook(() => mod.useSendMessage())+ const pending = startMutation({ serverId: scope.serverId, channelId: scope.id,+ content: "hi", nonce: "n1", replyToId: replyTo.id, attachments: [attachment] })+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))+ const { dispatchCommunityWsEvent } = await import("@/hooks/community/community-ws/registry")+ const { getMessageStreamState } = await import("@/test/community-query-owner")+ const { materializeMessageStream } = await import("@/lib/community/message-stream")+ const older = { id: "older", seq: 1, type: "chat" as const, content: "anchor", authorId: "peer", createdAt: "2026-08-07T09:00:00.000Z" }+ let currentBase: import("@/lib/community/message-stream").CanonicalMessage[] = [older]+ for (const stage of stages) {+ if (stage === "post") {+ await act(async () => { release({ message: postedMessage("server_id_1", 9) }); await pending })+ expect(getMessageStreamState(capturedQc, scope).liveIds).toContain("server_id_1")+ expect(materializeMessageStream([], getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc)).find(row => row.id === "server_id_1")).toMatchObject({+ id: "server_id_1", seq: 9, authorName: "Canonical Name", content: "canonical content",+ authorAvatar: "https://avatar.test/me.png", createdAt: "2026-08-07T10:00:00.000Z",+ embeds: [{ title: "Canonical embed" }], replyTo, attachments: [remoteAttachment], clientNonce: "n1", failed: false,+ })+ } else if (stage === "ws") {+ await act(async () => { dispatchCommunityWsEvent({ type: "community:message.create", serverId: scope.serverId,+ channelId: scope.id, message: { id: "server_id_1", seq: 9, type: "chat", authorId: "u_me",+ authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0, content: "canonical content",+ createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyTo,+ embeds: [{ title: "Canonical embed" }],+ attachments: [{ ...attachment, url: remoteAttachment.url }],+ } }, { deliveryMode: "single", queryClient: capturedQc, communityStore: runtime.ui, wsStore: runtime.ws,+ sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" },+ matchesFocus: event => event.channelId === scope.id, scheduleInboxInvalidate: vi.fn() }) })+ } else if (stage === "matchingBase") {+ const { channelMessagesQueryFn } = await import("@/hooks/community/use-messages")+ const { decodeCommunityReadResponse } = await import("@/lib/community/read-response")+ const path = `/api/community/channels/${scope.id}/messages`+ const confirmed = { id: "server_id_1", seq: 9, type: "chat", authorId: "u_me",+ authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0,+ content: "canonical content", createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyTo,+ embeds: [{ title: "Canonical embed" }], attachments: [remoteAttachment] }+ apiFetchMock.mockResolvedValueOnce(decodeCommunityReadResponse(path, "GET", new Response(),+ { messages: [older, confirmed], latestSeq: 9, hasMore: false }))+ await act(async () => { await channelMessagesQueryFn(scope.id, undefined, { queryClient: capturedQc })({ pageParam: { mode: "newest" } })+ const canonical = canonicalRegistry.collections.messages.get(confirmed.id)+ if (typeof canonical?.seq !== "number") throw new Error("Missing confirmed canonical seq")+ currentBase = [older, { ...canonical, seq: canonical.seq }]+ runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: currentBase, latestSeq: 9 }) })+ expect(canonicalRegistry.collections.messages.get(confirmed.id)?.attachments).toEqual([remoteAttachment])+ expect(materializeMessageStream(currentBase, getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc))).toEqual([+ expect.objectContaining({ id: older.id }),+ expect.objectContaining({ id: confirmed.id, replyTo, attachments: [remoteAttachment] }),+ ])+ } else {+ await act(async () => { ingestMessages(canonicalRegistry, scope.id, [older])+ runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: [older], latestSeq: 100 }) })+ }+ }+ const overlay = getMessageStreamState(capturedQc, scope)+ expect(overlay.outboxByNonce.size).toBe(0)+ expect(materializeMessageStream(currentBase, overlay, canonicalMessageReader(capturedQc)).filter(row => row.id === "server_id_1")).toEqual([+ expect.objectContaining({ seq: 9, content: "canonical content", replyTo, attachments: [remoteAttachment],+ ...(!stages.some(stage => stage === "matchingBase") ? { failed: false } : {}) }),+ ])+ expect(materializeMessageStream(currentBase, overlay, canonicalMessageReader(capturedQc)).find(row => row.id === "server_id_1")?.failed).not.toBe(true)+ runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: [older], latestSeq: 100 })+ runtime.messageStream.actions.removeScope(scope)+ expect(revoke).toHaveBeenCalledExactlyOnceWith("blob:owned")+ } finally { URL.revokeObjectURL = originalRevoke }+ })+it("keeps Query base-only and acknowledges the accepted overlay intent", async () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })const mod = await loadMod()- const stream = await import("@/stores/community/message-stream")+ const stream = await import("@/test/community-query-owner")canonicalRegistry.runtime.messageStream.actions.accept({ kind: "channel", id: "ch_1", serverId: "s1" },{ nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi", authorId: "u_me" }, localUploads: [] },@@ -259,10 +355,11 @@ describe("useSendMessage — happy path", () => {communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].ids).toEqual([])- const overlay = stream.getMessageOverlay(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" })+ const overlay = stream.getMessageStreamState(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" })expect(overlay.outboxByNonce.size).toBe(0)- expect(overlay.liveById.size).toBe(1)- expect(overlay.liveById.get("server_id_1")).toMatchObject({ seq: 9, authorId: "u_me", content: "canonical content", clientNonce: "n1" })+ expect(overlay.liveIds.length).toBe(1)+ expect(overlay.liveIds).toContain("server_id_1")+ expect(materializeMessageStream([], overlay, canonicalMessageReader(capturedQc)).find(row => row.id === "server_id_1")).toMatchObject({ seq: 9, authorId: "u_me", content: "canonical content", clientNonce: "n1" })expect(canonicalRegistry.collections.messages.get("server_id_1")).toMatchObject({ authorId: "u_me", content: "canonical content", embeds: [{ title: "Canonical embed" }] })expect(canonicalRegistry.collections.profiles.get("u_me")?.name).toBe("Canonical Name")})@@ -354,7 +451,7 @@ describe("useSendMessage — rollback", () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))apiFetchMock.mockRejectedValueOnce(new Error("boom"))const mod = await loadMod()- const stream = await import("@/stores/community/message-stream")+ const stream = await import("@/test/community-query-owner")canonicalRegistry.runtime.messageStream.actions.accept({ kind: "channel", id: "ch_1", serverId: "s1" },{ nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },@@ -371,7 +468,7 @@ describe("useSendMessage — rollback", () => {communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].ids).toEqual([])- expect(stream.getMessageOverlay(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")+ expect(stream.getMessageStreamState(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")})})@@ -381,7 +478,7 @@ describe("useSendMessage — stamps authorId on optimistic row", () => {it("optimistic row carries the sender's authorId", async () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))const mod = await loadMod()- const stream = await import("@/stores/community/message-stream")+ const stream = await import("@/test/community-query-owner")canonicalRegistry.runtime.messageStream.actions.accept({ kind: "channel", id: "ch_1", serverId: "s1" },{@@ -391,7 +488,7 @@ describe("useSendMessage — stamps authorId on optimistic row", () => {localUploads: [],},)- expect(stream.getMessageOverlay(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.message.authorId).toBe("u_me")+ expect(stream.getMessageStreamState(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.message.authorId).toBe("u_me")expect(mod.useSendMessage).toBeTypeOf("function")})})@@ -399,7 +496,7 @@ describe("useSendMessage — stamps authorId on optimistic row", () => {// ── useSendDmMessage ──────────────────────────────────────────────────────async function acceptDmIntent(nonce = "n1") {- const stream = await import("@/stores/community/message-stream")+ const stream = await import("@/test/community-query-owner")canonicalRegistry.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" },{@@ -440,6 +537,26 @@ describe("useSendDmMessage — overlay terminal emitter", () => {)})+ it("keeps the accepted channel intent failed with one native terminal transition after runner rejection", async () => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ const runtime = canonicalRegistry.runtime+ runtime.messageStream.actions.accept(scope, { nonce: "runner_failure", tempId: "temp_runner_failure",+ message: { type: "chat", content: "keep optimistic", authorId: "u_me" }, localUploads: [] })+ const dispatch = vi.spyOn(runtime.messageStream.actions, "dispatch")+ apiFetchMock.mockRejectedValueOnce(new Error("send failed"))+ const mod = await loadMod()+ const mutation = mountHook(() => mod.useSendMessage())+ const { runAcceptedMessageIntent } = await import("@/components/community/messages/message-channel-controller-send")+ await act(async () => { await expect(runAcceptedMessageIntent({ runtime, messageScope: scope, nonce: "runner_failure",+ uploadFileAsync: vi.fn(), sendMessageAsync: mutation.mutateAsync,+ channelId: scope.id, serverId: scope.serverId, viewer: { id: "u_me", name: "Me", avatar: "M" },+ })).resolves.toBeUndefined() })+ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ expect(runtime.messageStream.actions.getRetryPayload(scope, "runner_failure")?.message).toMatchObject({ content: "keep optimistic", failed: true })+ expect(dispatch.mock.calls).toEqual([[scope, { type: "postFail", nonce: "runner_failure" }]])+ expect(toastMock).toHaveBeenCalledExactlyOnceWith("send failed")+ })+it("emits postFail for a generic network failure and leaves Query untouched", async () => {capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))apiFetchMock.mockRejectedValueOnce(new Error("boom"))@@ -450,13 +567,61 @@ describe("useSendDmMessage — overlay terminal emitter", () => {await runMutation({ dmId: "dm_1", content: "hi", nonce: "n1" }).catch(() => { })expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))- expect(stream.getMessageOverlay(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")+ expect(stream.getMessageStreamState(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(dispatch).toHaveBeenCalledTimes(1)expect(dispatch).toHaveBeenCalledWith({ kind: "dm", id: "dm_1" },{ type: "postFail", nonce: "n1" },)})++ it("fails the upload intent when its view retires after upload succeeds, before native POST", async () => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }, runtime = canonicalRegistry.runtime+ const file = new File(["x"], "x.txt", { type: "text/plain" })+ runtime.messageStream.actions.accept(scope, { nonce: "upload-view", tempId: "temp-upload-view", message: { type: "chat", content: "file", authorId: "u_me" }, localUploads: [{ file, previewObjectUrl: "blob:view" }] })+ const dispatch = vi.spyOn(runtime.messageStream.actions, "dispatch"), mod = await loadMod(), mutation = mountHook(() => mod.useSendMessage())+ let current = true, finish!: (value: { id: string; filename: string; contentType: string; size: number }) => void+ const uploadFileAsync = vi.fn(() => new Promise<{ id: string; filename: string; contentType: string; size: number }>(resolve => { finish = resolve }))+ const assertActive = Object.assign(() => { if (!current) throw new DOMException("Retired view", "AbortError") }, { signal: new AbortController().signal })+ const { runAcceptedMessageIntent } = await import("@/components/community/messages/message-channel-controller-send")+ await act(async () => {+ const pending = runAcceptedMessageIntent({ runtime, messageScope: scope, nonce: "upload-view", assertActive, uploadFileAsync, sendMessageAsync: mutation.mutateAsync,+ channelId: scope.id, serverId: scope.serverId, viewer: { id: "u_me", name: "Me", avatar: "M" } })+ current = false+ finish({ id: "uploaded", filename: "x.txt", contentType: "text/plain", size: 1 })+ await pending+ })+ expect(uploadFileAsync).toHaveBeenCalledOnce()+ expect(apiFetchMock).not.toHaveBeenCalled()+ expect(dispatch.mock.calls).toEqual([[scope, { type: "uploadFailed", nonce: "upload-view" }]])+ expect(runtime.messageStream.actions.getRetryPayload(scope, "upload-view")?.message.failed).toBe(true)+ expect(toastMock).not.toHaveBeenCalled()+ })++ it("fails the accepted channel intent once when its view retires before native POST starts", async () => {+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ const runtime = canonicalRegistry.runtime+ runtime.messageStream.actions.accept(scope, { nonce: "retired_view", tempId: "temp_retired_view",+ message: { type: "chat", content: "keep optimistic", authorId: "u_me" }, localUploads: [] })+ const dispatch = vi.spyOn(runtime.messageStream.actions, "dispatch")+ const mod = await loadMod()+ const mutation = mountHook(() => mod.useSendMessage())+ let current = true+ const assertActive = Object.assign(() => { if (!current) throw new DOMException("Retired view", "AbortError") }, { signal: new AbortController().signal })+ const { runAcceptedMessageIntent } = await import("@/components/community/messages/message-channel-controller-send")+ await act(async () => {+ const pending = runAcceptedMessageIntent({ runtime, messageScope: scope, nonce: "retired_view", assertActive,+ uploadFileAsync: vi.fn(), sendMessageAsync: mutation.mutateAsync,+ channelId: scope.id, serverId: scope.serverId, viewer: { id: "u_me", name: "Me", avatar: "M" },+ })+ current = false+ await expect(pending).resolves.toBeUndefined()+ })+ expect(apiFetchMock).not.toHaveBeenCalled()+ expect(dispatch.mock.calls).toEqual([[scope, { type: "postFail", nonce: "retired_view" }]])+ expect(runtime.messageStream.actions.getRetryPayload(scope, "retired_view")?.message).toMatchObject({ content: "keep optimistic", failed: true })+ expect(toastMock).not.toHaveBeenCalled()+ })})describe("useSendDmMessage — 403 blocked special-case", () => {@@ -475,7 +640,7 @@ describe("useSendDmMessage — 403 blocked special-case", () => {content: "hi",nonce: "n1",}).catch(() => { })- expect(stream.getMessageOverlay(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.size).toBe(0)+ expect(stream.getMessageStreamState(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.size).toBe(0)expect(dispatch).toHaveBeenCalledTimes(1)expect(dispatch).toHaveBeenCalledWith({ kind: "dm", id: "dm_1" },@@ -497,7 +662,7 @@ describe("useSendDmMessage — 403 blocked special-case", () => {content: "hi",nonce: "n1",}).catch(() => { })- expect(stream.getMessageOverlay(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")+ expect(stream.getMessageStreamState(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))// Not the blocked-specific copy — any other error falls through to the// generic send-failed toast (see `useSendDmMessage`'s `onError` fallback).@@ -516,7 +681,7 @@ describe("useSendMessage — 429 rate limit fires a toast + marks failed", () =>const { ApiError } = await import("@/lib/errors")apiFetchMock.mockRejectedValueOnce(new ApiError("rate_limited", 429))mountHook(() => mod.useSendMessage())- const stream = await import("@/stores/community/message-stream")+ const stream = await import("@/test/community-query-owner")canonicalRegistry.runtime.messageStream.actions.accept({ kind: "channel", id: "ch_1", serverId: "s1" },{ nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },@@ -532,7 +697,7 @@ describe("useSendMessage — 429 rate limit fires a toast + marks failed", () =>communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].ids).toEqual([])- expect(stream.getMessageOverlay(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")+ expect(stream.getMessageStreamState(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(toastMock).toHaveBeenCalledWith(expect.stringContaining("Rate limited"))})})@@ -550,7 +715,7 @@ describe("useSendDmMessage — 429 rate limit fires a toast + marks failed", ()content: "hi",nonce: "n1",}).catch(() => { })- expect(stream.getMessageOverlay(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")+ expect(stream.getMessageStreamState(capturedQc, { kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))expect(toastMock).toHaveBeenCalledWith(expect.stringContaining("Rate limited"))})@@ -568,7 +733,7 @@ describe("useSendMessage — no blocked branch on channel path", () => {const { ApiError } = await import("@/lib/errors")apiFetchMock.mockRejectedValueOnce(new ApiError("blocked", 403))mountHook(() => mod.useSendMessage())- const stream = await import("@/stores/community/message-stream")+ const stream = await import("@/test/community-query-owner")canonicalRegistry.runtime.messageStream.actions.accept({ kind: "channel", id: "ch_1", serverId: "s1" },{ nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },@@ -584,7 +749,7 @@ describe("useSendMessage — no blocked branch on channel path", () => {communityKeys.channelMessages("ch_1"),)expect(cache?.pages[0].ids).toEqual([])- expect(stream.getMessageOverlay(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")+ expect(stream.getMessageStreamState(capturedQc, { kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(toastMock).not.toHaveBeenCalledWith("You cannot send messages to this user")expect(toastMock).toHaveBeenCalledWith("blocked")})diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 04a211e7e..3c8dd2123 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -5,7 +5,7 @@ import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"import { useCallback } from "react"import { useCommunityMutationOrigin } from "../community-origin"-import { getCommunityRuntime, useCommunityRuntime } from "@/stores/community/runtime"+import { getCommunityRuntime } from "@/stores/community/runtime"@@ -16,8 +16,7 @@ import { ApiError, isAbortError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { publishCommunityMessageFields, publishCommunityMessages, publishCommunityCreatedChannel } from "@/lib/community-db/sync"-import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"-import { formatAttachmentSize } from "@/lib/community/attachment-presentation"+import { presentMessageAttachment } from "@/lib/community/attachment-presentation"import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"import {projectPostedMessage,@@ -26,7 +25,9 @@ import {+import type { MessageScope } from "@/lib/community/message-stream"import type { Attachment, Msg } from "@/lib/community/models/message"+import type { UploadFileResult } from "./uploads"import {@@ -36,7 +37,7 @@ import {isForumSidebarParent,patchForumSidebarActivityExact,} from "@/hooks/community/use-forum-sidebar-threads"-import { isBlocked, type MentionType } from "@alook/shared"+import { isBlocked, type MentionType, type CommunityResourceProfile } from "@alook/shared"import {getActiveAccountUnreadProjection,type AccountUnreadDomain,@@ -55,8 +56,7 @@ import {restoreAttentionOptimisticDomains,restoreAttentionOptimisticSnapshot,restoreAttentionItemsOptimisticSnapshot,- type AttentionOptimisticSnapshot,- type AttentionItemsOptimisticSnapshot,+ type AttentionIntent,} from "@/lib/community-db/sync"@@ -130,26 +130,11 @@ export function toAttachmentVm(// and derived HERE client-side, matching what the server's read path emits via// `attachmentUrl`. This keeps the optimistic row's image src identical to the// reconciled row that arrives over WS.- const url = attachmentUrl(channelId, a.id)- const isImage = isInlineAttachmentContentType(a.contentType)- if (isImage) return {- kind: "image",- name: a.filename,- url,- contentType: a.contentType,- sizeBytes: a.size,+ return presentMessageAttachment({+ name: a.filename, url: attachmentUrl(channelId, a.id), contentType: a.contentType, sizeBytes: a.size,...(a.hasThumbnail ? { thumbnailUrl: attachmentThumbnailUrl(channelId, a.id) } : {}),- width: a.width,- height: a.height,- }- return {- kind: "file",- name: a.filename,- url,- contentType: a.contentType,- sizeBytes: a.size,- size: formatAttachmentSize(a.size),- }+ width: a.width, height: a.height,+ })}// Random-ish temp id — collision on the same tick is essentially impossible@@ -184,8 +169,8 @@ export type SendMessageArgs = {// sent to the server (in an id array); the rest drive the optimistic VM// (whose url is derived client-side from `id`). No `url` field — the upload// no longer returns one.- attachments?: { id: string; filename: string; contentType: string; size: number; hasThumbnail?: boolean; width?: number; height?: number }[]- author: { id: string; name: string; avatar: string }+ attachments?: UploadFileResult[]+ author: { [Field in "id" | "name" | "avatar"]: NonNullable<CommunityResourceProfile[Field]> }// Idempotency nonce. Omitted on a fresh send (the hook mints one); the// retry-pill caller passes the failed row's nonce back so the resend reuses// it and dedupes server-side instead of double-posting.@@ -203,70 +188,61 @@ export type SendMessageResult = { message: PostedMessage; deduped?: boolean }* channel row's `parentChannelId` (per #14), so the client always POSTs to* `/channels/:id/messages`.*/-export function useSendMessage() {+export type SendDmMessageArgs = Pick<SendMessageArgs, "assertActive" | "content" | "replyToId" | "replyTo" | "attachments"> & {+ dmId: string+ nonce: string+}++function sendMessageScope(input: SendMessageArgs | SendDmMessageArgs): MessageScope {+ return "dmId" in input ? { kind: "dm", id: input.dmId } : { kind: "channel", id: input.channelId, serverId: input.serverId }+}++function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(kind: MessageScope["kind"]) {const origin = useCommunityMutationOrigin()const queryClient = useQueryClient()- type Intent = SendMessageArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<- SendMessageResult,- Error,- Intent- >({ meta: { observabilityAction: "channel.message.send" },- mutationFn: async ({ channelId, content, replyToId, replyTo, mentionType, attachments, nonce, original: token, assertActive }) => {+ type Intent = Args & { original: ReturnType<typeof origin.begin>["token"] }+ const native = useMutation<SendMessageResult, Error, Intent>({+ meta: { observabilityAction: `${kind}.message.send` },+ mutationFn: async (args) => {+ const { content, replyToId, replyTo, attachments, nonce, original: token, assertActive } = argsorigin.assert(token); assertActive?.()- // Server receives only the attachment IDS (reserve-by-id); the rest of the- // descriptor is client-only (optimistic VM). Dimensions already rode the- // upload, so they are NOT re-sent here (single-source guard).- const attachmentIds = attachments?.map((a) => a.id)- const result = await origin.request<SendMessageResult>(token,- `/api/community/channels/${channelId}/messages`,- {- method: "POST",- signal: assertActive?.signal,- assertActive,- body: JSON.stringify({- content,- replyToId: replyTo?.id ?? replyToId,- mentionType,- attachments: attachmentIds,- nonce,- }),- },- )+ const scope = sendMessageScope(args)+ const acceptedReply = replyTo ?? getCommunityRuntime(queryClient).messageStream.actions.getRetryPayload(scope, nonce ?? "")?.message.replyTo+ const result = await origin.request<SendMessageResult>(token, `/api/community/channels/${scope.id}/messages`, {+ method: "POST", signal: assertActive?.signal, assertActive,+ body: JSON.stringify({ content, replyToId: replyTo?.id ?? replyToId,+ mentionType: "serverId" in args ? args.mentionType : undefined,+ attachments: attachments?.map((attachment) => attachment.id), nonce }),+ })await origin.registry!.collections.messages.preload()origin.assert(token); assertActive?.()- const message = projectPostedMessage(result.message, nonce ?? "")- publishCommunityMessages(queryClient, { channelId, messages: [{ ...message, ...(attachments?.length ? { attachments: attachments.map((attachment) => toAttachmentVm(channelId, attachment)) } : {}), ...(replyTo ? { replyTo } : {}) }], proof: { token, signal: assertActive?.signal } })+ const message = projectPostedMessage(result.message, nonce ?? "", scope.id)+ publishCommunityMessages(queryClient, { channelId: scope.id,+ messages: [{ ...message, ...(attachments?.length ? { attachments: attachments.map((attachment) => toAttachmentVm(scope.id, attachment)) } : {}), ...(acceptedReply && !("replyTo" in result.message) && (!("replyToId" in result.message) || result.message.replyToId === acceptedReply.id) ? { replyTo: acceptedReply } : {}) }],+ proof: { token, ...(scope.kind === "channel" ? { signal: assertActive?.signal } : {}) } })return result},- onError: (err, args) => {+ onError: (error, args) => {try { origin.assert(args.original) } catch { return }- if (args.nonce) {- getCommunityRuntime(queryClient).messageStream.actions.dispatch(- { kind: "channel", id: args.channelId, serverId: args.serverId },- { type: "postFail", nonce: args.nonce },- )+ const scope = sendMessageScope(args)+ const stream = getCommunityRuntime(queryClient).messageStream.actions+ const nonce = args.nonce ?? ""+ if (scope.kind === "dm" && error instanceof ApiError && error.status === 403 && isBlocked(error.message)) {+ stream.dispatch(scope, { type: "terminalReject", nonce })+ try { args.assertActive?.() } catch { return }+ toast("You cannot send messages to this user")+ return}+ if (scope.kind === "dm" || args.nonce) stream.dispatch(scope, { type: "postFail", nonce })try { args.assertActive?.() } catch { return }- if (isAbortError(err)) return- // 429: server-side rate limit. Fire an explicit toast so the user- // knows why the send failed — otherwise the only signal is a- // `failed: true` pill, which reads like a generic error. The row- // still gets marked failed so the retry affordance stays available.- if (err instanceof ApiError && err.status === 429) {- toast.error("Rate limited — please wait a moment before trying again")- } else {- // Any other failure (validation error, forbidden, 500, etc.) — the- // `failed: true` pill below is a retry affordance, not a reason.- // Without this the user sees no explanation at all for send- // failures outside the 429 case.- toastApiError(err, "Failed to send message")- }+ if (isAbortError(error)) return+ if (error instanceof ApiError && error.status === 429) toast.error("Rate limited — please wait a moment before trying again")+ else toastApiError(error, "Failed to send message")},onSuccess: (data, args) => {try { origin.assert(args.original) } catch { return }if (- args.forumParentChannelId &&+ "serverId" in args && args.forumParentChannelId &&isForumSidebarParent(queryClient, args.serverId, args.forumParentChannelId)) {const canonical = hasForumSidebarThread(@@ -284,108 +260,24 @@ export function useSendMessage() {void invalidateForumSidebarBaseExact(queryClient, args.serverId)}}- if (!args.nonce) return- getCommunityRuntime(queryClient).messageStream.actions.dispatch(- { kind: "channel", id: args.channelId, serverId: args.serverId },- {- type: "postAck",- nonce: args.nonce,- message: projectPostedMessage(data.message, args.nonce),- },- )+ const scope = sendMessageScope(args)+ const nonce = args.nonce ?? ""+ if (scope.kind === "dm" || args.nonce) getCommunityRuntime(queryClient).messageStream.actions.dispatch(scope, {+ type: "postAck", nonce, message: projectPostedMessage(data.message, nonce, scope.id),+ })},})- const capture = useCallback((input: SendMessageArgs): Intent => { input.assertActive?.(); return { ...input, original: origin.begin().token } }, [origin])+ const capture = useCallback((input: Args): Intent => { input.assertActive?.(); return { ...input, original: origin.begin().token } }, [origin])const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.assertActive?.() }, [origin])return useNativeMutationFacade(native, capture, assertCurrent)}-// ── Send DM message ────────────────────────────────────────────────────────--export type SendDmMessageArgs = {- assertActive?: (() => void) & { signal: AbortSignal }- dmId: string- content: string- replyToId?: string- replyTo?: Msg["replyTo"]- // Reserve-by-id (see SendMessageArgs.attachments): id-bearing descriptors;- // only `id` reaches the server.- attachments?: { id: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]- nonce: string+export function useSendMessage() {+ return useSendScopedMessage<SendMessageArgs>("channel")}export function useSendDmMessage() {- const origin = useCommunityMutationOrigin()- const queryClient = useQueryClient()- const communityRuntime = useCommunityRuntime()- type Intent = SendDmMessageArgs & { original: ReturnType<typeof origin.begin>["token"] }- const native = useMutation<- SendMessageResult,- Error,- Intent- >({ meta: { observabilityAction: "dm.message.send" },- mutationFn: async ({ dmId, content, replyToId, replyTo, attachments, nonce, original: token, assertActive }) => {- origin.assert(token); assertActive?.()- const attachmentIds = attachments?.map((a) => a.id)- const result = await origin.request<SendMessageResult>(token,- `/api/community/channels/${dmId}/messages`,- {- method: "POST",- signal: assertActive?.signal,- assertActive,- body: JSON.stringify({- content,- replyToId: replyTo?.id ?? replyToId,- attachments: attachmentIds,- nonce,- }),- },- )- await origin.registry!.collections.messages.preload()- origin.assert(token)- assertActive?.()- publishCommunityMessages(queryClient, { channelId: dmId, messages: [{ ...projectPostedMessage(result.message, nonce), ...(attachments?.length ? { attachments: attachments.map((attachment) => toAttachmentVm(dmId, attachment)) } : {}), ...(replyTo ? { replyTo } : {}) }], proof: { token } })- return result- },- onError: (err, args) => {- try { origin.assert(args.original) } catch { return }- const scope = { kind: "dm" as const, id: args.dmId }- if (err instanceof ApiError && err.status === 403 && isBlocked(err.message)) {- communityRuntime.messageStream.actions.dispatch(scope, {- type: "terminalReject",- nonce: args.nonce,- })- try { args.assertActive?.() } catch { return }- toast("You cannot send messages to this user")- return- }- communityRuntime.messageStream.actions.dispatch(scope, {- type: "postFail",- nonce: args.nonce,- })- try { args.assertActive?.() } catch { return }- if (isAbortError(err)) return- if (err instanceof ApiError && err.status === 429) {- toast.error("Rate limited — please wait a moment before trying again")- } else {- toastApiError(err, "Failed to send message")- }- },- onSuccess: (data, args) => {- try { origin.assert(args.original) } catch { return }- communityRuntime.messageStream.actions.dispatch(- { kind: "dm", id: args.dmId },- {- type: "postAck",- nonce: args.nonce,- message: projectPostedMessage(data.message, args.nonce),- },- )- },- })- const capture = useCallback((input: SendDmMessageArgs): Intent => { input.assertActive?.(); return { ...input, original: origin.begin().token } }, [origin])- const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.assertActive?.() }, [origin])- return useNativeMutationFacade(native, capture, assertCurrent)+ return useSendScopedMessage<SendDmMessageArgs>("dm")}// ── Reaction intents ──────────────────────────────────────────────────────@@ -445,7 +337,7 @@ export function useMarkAllInboxRead() {}type MarkAllContext = {tokens: Map<AccountUnreadDomain, MarkAllToken>- snapshot?: AttentionOptimisticSnapshot+ snapshot?: AttentionIntent}type Original = ReturnType<typeof origin.begin>["token"]const mutation = useMutation<DomainResult[], Error, Original, MarkAllContext>({ meta: { observabilityAction: "inbox.read_all" },@@ -556,7 +448,7 @@ export function useDeleteMention() {{ input: DeleteMentionArgs; original: Original },{token?: AccountUnreadDismissToken- attentionSnapshot?: AttentionItemsOptimisticSnapshot+ attentionSnapshot?: AttentionIntent}>({ meta: { observabilityAction: "mention.dismiss" },scope: { id: "community-mention-delete" },diff --git a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsxindex 21c4a887f..f2eb80cfa 100644--- a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx+++ b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx@@ -7,7 +7,7 @@ import { act, render, screen, waitFor } from "@/test/react-dom-harness"import { QueryProvider } from "@/app/c/QueryProvider"import { clearAllPersistedCaches } from "@/lib/query-persister"import { getCommunityDbRegistry } from "@/lib/community-db/collections"-import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"+import { projectCommunityWsEventToDb, retireCommunityChannelReading } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"import { useServer, useServers } from "../use-servers"import { useUpdateServer, useLeaveServer, useDeleteServer, useUploadServerIcon } from "./servers"@@ -189,19 +189,59 @@ describe("actual canonical server and tree command owner", () => {})it("rolls back optimistic leave while keeping newer WS facts", async () => {const { reject, original } = await mount()- let result!: Promise<unknown>; act(() => { result = leave.mutateAsync({ serverId: "s1" }).catch((error) => error) })+ const input = { serverId: "s1" }, failure = new Error("denied")+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }+ let result!: Promise<unknown>; act(() => { result = leave.mutateAsync(input, callbacks).catch((error) => error) })await waitFor(() => expect(screen.getByTestId("server-list").textContent).toBe(""))act(() => projectCommunityWsEventToDb(original, { type: "community:server.update", serverId: "s1", changes: { name: "newer-ws" } }))- await act(async () => { reject(new Error("denied")); await result })+ await act(async () => { reject(failure); expect(await result).toBe(failure) })await waitFor(() => expect(screen.getByTestId("server-list").textContent).toBe("newer-ws"))+ expect(callbacks.onError).toHaveBeenCalledOnce()+ expect(callbacks.onError.mock.calls[0]!.slice(0, 2)).toEqual([failure, input])+ expect(callbacks.onSettled).toHaveBeenCalledOnce()+ expect(callbacks.onSettled.mock.calls[0]!.slice(0, 3)).toEqual([undefined, failure, input])+ expect(callbacks.onSuccess).not.toHaveBeenCalled()})it("commits leave through native membership removal and evicts the original server scope", async () => {const { resolve, original } = await mount()- let result!: Promise<unknown>; act(() => { result = leave.mutateAsync({ serverId: "s1" }).catch((error) => error) })+ const input = { serverId: "s1" }+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }+ let result!: Promise<unknown>; act(() => { result = leave.mutateAsync(input, callbacks).catch((error) => error) })await waitFor(() => expect(screen.getByTestId("server-list").textContent).toBe(""))await act(async () => { resolve(undefined); expect(await result).toBeUndefined() })expect(getCommunityDbRegistry(original)!.collections.servers.has("s1")).toBe(false)expect(original.getQueryData(communityKeys.servers())).toEqual([])+ expect(callbacks.onSuccess).toHaveBeenCalledOnce()+ expect(callbacks.onSuccess.mock.calls[0]!.slice(0, 2)).toEqual([undefined, input])+ expect(callbacks.onSettled).toHaveBeenCalledOnce()+ expect(callbacks.onSettled.mock.calls[0]!.slice(0, 3)).toEqual([undefined, null, input])+ expect(callbacks.onError).not.toHaveBeenCalled()+ })+ it("suppresses Leave failure callbacks after scope retirement while the account remains current", async () => {+ const { reject, original } = await mount()+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }+ let result!: Promise<unknown>; act(() => { result = leave.mutateAsync({ serverId: "s1" }, callbacks).catch((error) => error) })+ await waitFor(() => expect(api.mock.calls.some(([path, options]) => path.endsWith("/leave") && options.method === "POST")).toBe(true))+ const registry = getCommunityDbRegistry(original)!+ act(() => retireCommunityChannelReading(registry, "c1", { reason: "read-denied", serverId: "s1" }))+ await act(async () => { reject(new Error("denied after retirement")); expect(await result).toMatchObject({ name: "AbortError" }) })+ expect(getCommunityDbRegistry(original)).toBe(registry)+ expect(registry.runtime.lifecycle.get().active).toBe(true)+ expect(callbacks.onSuccess).not.toHaveBeenCalled()+ expect(callbacks.onError).not.toHaveBeenCalled()+ expect(callbacks.onSettled).not.toHaveBeenCalled()+ })+ it.each(["success", "failure"] as const)("suppresses retired-account Leave %s callbacks", async (outcome) => {+ const { view, resolve, reject, original } = await mount()+ const callbacks = { onSuccess: vi.fn(), onError: vi.fn(), onSettled: vi.fn() }+ let result!: Promise<unknown>; act(() => { result = leave.mutateAsync({ serverId: "s1" }, callbacks).catch((error) => error) })+ await waitFor(() => expect(api.mock.calls.some(([path, options]) => path.endsWith("/leave") && options.method === "POST")).toBe(true))+ act(() => { sdk.id = "B"; view.rerender(<Root id="B" />) })+ await waitFor(() => expect(client).not.toBe(original))+ await act(async () => { if (outcome === "success") resolve(undefined); else reject(new Error("old Leave failure")); expect(await result).toMatchObject({ name: "AbortError" }) })+ expect(callbacks.onSuccess).not.toHaveBeenCalled()+ expect(callbacks.onError).not.toHaveBeenCalled()+ expect(callbacks.onSettled).not.toHaveBeenCalled()})it("retains native detail until one safe route commit after successful owner deletion", async () => {const { resolve, original } = await mount()diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.tsindex 862d96a1d..43b576348 100644--- a/src/web/src/hooks/community/mutations/uploads.ts+++ b/src/web/src/hooks/community/mutations/uploads.ts@@ -50,8 +50,6 @@ export type UploadFileResult = {height?: number}-export type UploadedAttachment = UploadFileResult & { width?: number; height?: number }-export function appendGeneratedThumbnail(formData: FormData,originalContentType: string,@@ -103,11 +101,11 @@ export function buildAttachmentUploadFormData({export function zipUploadResultsWithDimensions(results: (UploadFileResult | null)[],attachments: { file: File; width?: number; height?: number }[],-): UploadedAttachment[] {- const zipped: (UploadedAttachment | null)[] = results.map((r, i) =>+): UploadFileResult[] {+ const zipped: (UploadFileResult | null)[] = results.map((r, i) =>r ? { ...r, width: attachments[i].width, height: attachments[i].height } : null,)- return zipped.filter((x): x is UploadedAttachment => x !== null)+ return zipped.filter((x): x is UploadFileResult => x !== null)}function uploadPath(target: UploadTarget): string | null {diff --git a/src/web/src/hooks/community/read-coordinator-snapshot-projection.ts b/src/web/src/hooks/community/read-coordinator-snapshot-projection.tsindex 766c332fc..cb1fc460b 100644--- a/src/web/src/hooks/community/read-coordinator-snapshot-projection.ts+++ b/src/web/src/hooks/community/read-coordinator-snapshot-projection.ts@@ -1,7 +1,8 @@+import type { queries } from "@alook/shared"import type { QueryClient } from "@tanstack/react-query"export type ReadCoordinatorSnapshot = {- readStates: Array<{ channelId: string; lastReadSeq: number }>+ readStates: Pick<queries.communityReadState.AccountReadState, "channelId" | "lastReadSeq">[]}type SnapshotProjector = (snapshot: ReadCoordinatorSnapshot) => voiddiff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.tsindex 018570be6..d812b26aa 100644--- a/src/web/src/hooks/community/read-coordinator.ts+++ b/src/web/src/hooks/community/read-coordinator.ts@@ -1,5 +1,7 @@"use client"+import type { CommunityReadAdvanceSchema } from "@alook/shared"+import type { z } from "zod"import { createStore } from "@tanstack/react-store"import type { Mutation, QueryClient } from "@tanstack/react-query"import { communityRequestOptions } from "@/lib/community-db/sync"@@ -64,11 +66,7 @@ type PendingReadFlushOptions = {deferInboxDms?: () => boolean}-type ReadMutationResponse = {- changed: boolean- revision: number- targetSeq: number-}+type ReadMutationResponse = Pick<z.infer<typeof CommunityReadAdvanceSchema>, "changed" | "revision" | "targetSeq">type SurfaceLease = {coordinator: ReadCoordinatordiff --git a/src/web/src/hooks/community/use-channel-members.dom.test.ts b/src/web/src/hooks/community/use-channel-members.dom.test.tsindex b2601e38e..e37b36462 100644--- a/src/web/src/hooks/community/use-channel-members.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-members.dom.test.ts@@ -46,13 +46,28 @@ describe("useChannelMembers", () => {await waitFor(() => {expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/channels/private%2Fchannel/members",+ "/api/community/channels/private%2Fchannel/members?relation=access",expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }),)})await waitFor(() => expect(rendered.result.current.members).toHaveLength(1))})+ it("renders a DM access pair without inventing a server membership or role", async () => {+ const { useChannelMembers } = await import("./use-channel-members")+ const { publishCommunityChannelMetadata, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")+ const owner = await createCommunityQueryOwner()+ publishCommunityChannelMetadata(owner.client, { metadata: { id: "dm", serverId: null, name: null, type: "dm", parentChannelId: null, parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null }, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })+ apiFetchMock.mockResolvedValue({ members: ["viewer", "peer"].map((userId) => ({ id: userId, userId, name: userId, discriminator: "0001", avatar: "", avatarVersion: 0, sub: "", role: null, status: "offline", statusEmoji: null, statusText: "", source: "explicit", isCreator: false })) })+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)+ const rendered = renderHook(() => useChannelMembers("dm", true, undefined, "access"), { wrapper })+ await waitFor(() => expect(rendered.result.current.members).toHaveLength(2))+ expect(rendered.result.current.members.map((member) => member.role)).toEqual([null, null])+ expect([...owner.registry.collections.serverMemberships.values()]).toEqual([])+ expect(owner.client.getQueryData(["community", "channel", "dm", "members", "access"])).toMatchObject({ serverId: null, relation: "access" })+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/dm/members?relation=access", expect.anything())+ })+it.each(Object.values(PARTICIPANT_SOURCE))("recovers a failed notify roster with source %s while retaining its resolved parent",async (source) => {@@ -76,13 +91,13 @@ describe("useChannelMembers", () => {let participantGets = 0let parentGets = 0apiFetchMock.mockImplementation((url: string) => {- if (url.endsWith("/thread/members")) {+ if (url.endsWith("/thread/members?relation=notify")) {participantGets += 1return failParticipants? Promise.reject(new Error("controlled first-load failure")): Promise.resolve({ members: participants })}- if (url.endsWith("/parent/members")) {+ if (url.endsWith("/parent/members?relation=access")) {parentGets += 1return Promise.resolve({ members: parentMembers })}diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex 3762a3090..268a6dcb3 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -8,40 +8,46 @@ import { useCallback,useMemo } from "react"import { QueryObserver,useMutation,useQuery,useQueryClient,type QueryClient,type QueryFunctionContext,type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { CommunityRole } from "@alook/shared"-import type { CommunityUserCore } from "@/lib/community/models/people"+import { COMMUNITY_CONTRACT_VERSION, CommunityMembersReadSchema, CommunityResourceProfileSchema, type CommunityMembersRead, type CommunityRole, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"+import type { CommunityUserCore, Presence } from "@/lib/community/models/people"import { fetchAllServerMembers } from "./fetch-all-server-members"import { useCanonicalProfilesByUserId,useServerMemberRows,useChannelRosterRows } from "@/lib/community-db/projections"import { captureCommunityLiveSnapshotToken,assertCommunityLiveSnapshotTokenCurrent,publishCommunityChannelMembersSnapshot,setCanonicalCommunityChannelMember } from "@/lib/community-db/sync"import { channelMembershipKey, type ChannelMembershipRow } from "@/lib/community-db/schema"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"-import { beginCommunityProfileSeed,writeCommunityProfilePatches,communityUserProfilePatch } from "@/lib/community/profile-seed"import { readCommunityProfile } from "@/lib/community/profile-read"import { useCommunityMutationOrigin } from "./community-origin"import { useCommunityViewSource } from "./use-community-view-source"-export type ChannelMember = CommunityUserCore & {+export type ChannelMember = CommunityUserCore & Pick<CommunityMemberRelation, "userId" | "isCreator"> & Pick<CommunityResourceProfile, "statusEmoji" | "statusText"> & {id: string- userId: stringsub: string- role: CommunityRole- status: "online" | "offline"- statusEmoji: string | null- statusText: string+ role: CommunityRole | null+ status: Presencesource: NonNullable<ChannelMembershipRow["source"]>- isCreator: boolean}-export type AddableMember = { userId: string; name: string | null; discriminator: string | null; avatar: string; avatarVersion: number }-type ChannelRosterWindow = { serverId: string; relation: "access" | "notify"; members: Array<{ id: string; userId: string }> }++function normalizeChannelRoster(channelId: string, relation: CommunityMemberRelation["relation"], response: { members: ChannelMember[] } | CommunityMembersRead): CommunityMembersRead {+ if ("contractVersion" in response) return response+ return CommunityMembersReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId, relation,+ members: response.members.map((member) => ({ channelId, userId: member.userId, relation, memberId: member.id, source: member.source, isCreator: member.isCreator, role: member.role })),+ profiles: response.members.map((member) => CommunityResourceProfileSchema.strip().parse({ ...member, id: member.userId, statusEmoji: member.statusEmoji ?? null, statusText: member.statusText ?? "" })),+ })+}+export type AddableMember = Pick<ChannelMember, "userId" | "avatar" | "avatarVersion"> & { [Field in "name" | "discriminator"]: ChannelMember[Field] | null }+type ChannelRosterWindow = {+ serverId: CommunityChannelResource["serverId"]+ relation: CommunityMemberRelation["relation"]+ members: Array<Pick<CommunityMemberRelation, "userId"> & { id: NonNullable<CommunityMemberRelation["memberId"]> }>+}function channelMembersOptions(client: QueryClient, channelId: string, serverId?: string, relation?: "access" | "notify") {- const queryKey = communityKeys.channelMembers(channelId)+ const queryKey = communityKeys.channelMembers(channelId, relation ?? "access")return {queryKey,queryFn: async ({ signal }: { signal: AbortSignal }): Promise<ChannelRosterWindow> => {- const token = captureCommunityLiveSnapshotToken(client), registry = token.registry!- const profileSnapshot = beginCommunityProfileSeed(registry)+ const token = captureCommunityLiveSnapshotToken(client, channelId), registry = token.registry!const resource = client.getQueryCache().find({ queryKey, exact: true })const assert = () => {assertCommunityLiveSnapshotTokenCurrent(client, token, signal)@@ -52,21 +58,21 @@ function channelMembersOptions(client: QueryClient, channelId: string, serverId?await Promise.all([registry.collections.channelMemberships.preload(), registry.collections.serverMemberships.preload()])assert()const channel = registry.collections.channels.get(channelId)- const scopeId = serverId ?? channel?.serverId- if (!scopeId) throw new DOMException("Missing channel roster scope", "AbortError")- const dimension = relation ?? (channel?.type === "thread" ? "notify" : "access")- const response = await apiFetch<{ members: ChannelMember[] }>("/api/community/channels/" + encodeURIComponent(channelId) + "/members", communityRequestOptions(client, token, signal, assert))+ const scopeId = serverId ?? channel?.serverId ?? (channel?.type === "dm" ? null : undefined)+ if (scopeId === undefined) throw new DOMException("Missing channel roster scope", "AbortError")+ const dimension = relation ?? "access"+ const response = await apiFetch<{ members: ChannelMember[] } | CommunityMembersRead>("/api/community/channels/" + encodeURIComponent(channelId) + "/members?relation=" + dimension, communityRequestOptions(client, token, signal, assert))assert()- writeCommunityProfilePatches(response.members.map((member) => communityUserProfilePatch(member.userId, member)), registry, { snapshot: profileSnapshot })- publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, response.members, { token, signal })+ const resources = normalizeChannelRoster(channelId, dimension, response)+ publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles)assert()- return { serverId: scopeId, relation: dimension, members: response.members.map(({ id, userId }) => ({ id, userId })) }+ return { serverId: scopeId, relation: dimension, members: resources.members.map(({ memberId, userId }) => ({ id: memberId ?? userId, userId })) }},}}async function readChannelRoster(client: QueryClient, channelId: string, serverId: string, signal: AbortSignal) {- const original = captureCommunityLiveSnapshotToken(client)+ const original = captureCommunityLiveSnapshotToken(client, channelId)const assert = () => assertCommunityLiveSnapshotTokenCurrent(client, original, signal)assert()const options = channelMembersOptions(client, channelId, serverId)@@ -81,7 +87,7 @@ async function readChannelRoster(client: QueryClient, channelId: string, serverI}async function addableMembersQueryFn(serverId: string, channelId: string, context: QueryFunctionContext) {- const original = captureCommunityLiveSnapshotToken(context.client)+ const original = captureCommunityLiveSnapshotToken(context.client, channelId)assertCommunityLiveSnapshotTokenCurrent(context.client, original, context.signal)const [serverMembers, roster] = await Promise.all([fetchAllServerMembers(context.client, serverId, context.signal),@@ -102,11 +108,11 @@ export function useChannelMembers(channelId: string, enabled = true, serverId?:const byUser = new Map(memberships.map((member) => [member.userId, member]))return roster.flatMap((participant) => {const member = byUser.get(participant.userId)- if (!member?.memberId) return []+ if (query.data?.serverId !== null && !member?.memberId) return []const profile = readCommunityProfile(profiles.get(participant.userId), participant.userId)- return [deriveView({ id: member.memberId, userId: participant.userId, name: member.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member.role as CommunityRole, sub: "", status: member.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source ?? "explicit", isCreator: participant.isCreator ?? false }, [viewEvidence(member), viewEvidence(participant), viewEvidence(profile)])]+ return [deriveView({ id: member?.memberId ?? participant.userId, userId: participant.userId, name: member?.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member ? member.role as CommunityRole : null, sub: "", status: member?.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source ?? "explicit", isCreator: participant.isCreator ?? false }, [viewEvidence(member), viewEvidence(participant), viewEvidence(profile)])]})- }, [profiles, memberships, roster])+ }, [profiles, memberships, roster, query.data?.serverId])deriveView(members, [valueEvidence(client, query.data), ...members.map(viewEvidence)], members.length)const data = useMemo(() => query.data ? { members } : undefined, [query.data, members])return { ...query, data, members } as UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[] }@@ -183,7 +189,7 @@ export function useChannelMemberCommand(channelId: string, kind: "add" | "removevalue.assertActive?.()const view = source.capture()view()- return { ...value, view, original: origin.begin().token, resources: [communityKeys.channelMembers(channelId), communityKeys.channelAddableMembers(channelId)].flatMap((queryKey) => client.getQueryCache().findAll({ queryKey, exact: true })) }+ return { ...value, view, original: origin.begin().token, resources: [communityKeys.channelMembers(channelId), communityKeys.channelAddableMembers(channelId)].flatMap((queryKey) => client.getQueryCache().findAll({ queryKey })) }}, [origin, client, channelId, source])const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.view(); args.assertActive?.() }, [origin])return useNativeMutationFacade(native, capture, assertCurrent)diff --git a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts b/src/web/src/hooks/community/use-channel-message-feed.dom.test.tsindex 45bc56d68..e606ee37b 100644--- a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts@@ -29,11 +29,7 @@ const mocks = vi.hoisted(() => ({},useMessages: vi.fn(),watermark: vi.fn(),- canonicalReadSnapshot: undefined as undefined | {- lastReadMessageId: string | null- lastReadAt: string- lastReadSeq: number- },+}))vi.mock("./use-channel-read-state", () => ({@@ -52,9 +48,7 @@ vi.mock("./use-channel-panels", () => ({useThreads: () => ({ threads: [], isLoading: false }),usePins: () => ({ pins: [], isLoading: false }),}))-vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),- useReadStateProjection: () => mocks.canonicalReadSnapshot,-}))+function Capture({ onResult }: { onResult?: (result: ReturnType<typeof useChannelMessageFeed>) => void }) {const result = useChannelMessageFeed({@@ -91,7 +85,6 @@ describe("useChannelMessageFeed", () => {mocks.messages.anchorReconciled = truemocks.useMessages.mockReset()mocks.watermark.mockReset()- mocks.canonicalReadSnapshot = undefined})it("always revalidates a mount and reconciles the authoritative server anchor", () => {@@ -131,15 +124,13 @@ describe("useChannelMessageFeed", () => {expect(mocks.messages.refetch).not.toHaveBeenCalled()})- it("seeds the frozen mount snapshot from the canonical read projection", () => {- mocks.canonicalReadSnapshot = {- lastReadMessageId: "authoritative-anchor",- lastReadAt: "2026-09-26T00:00:00.000Z",- lastReadSeq: 2,- }+++ it("uses the mount's qualified read snapshot for the initial page", () => {+ mocks.readState.snapshot = { lastReadMessageId: "current-mount-anchor", lastReadSeq: 7 }render(createElement(Capture)).unmount()expect(mocks.useMessages).toHaveBeenLastCalledWith("channel", expect.objectContaining({- lastReadMessageId: "authoritative-anchor",+ lastReadMessageId: "current-mount-anchor",}))})diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.tsindex 6667ab185..2277541a7 100644--- a/src/web/src/hooks/community/use-channel-message-feed.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.ts@@ -8,7 +8,6 @@ import { useChannelWatermark } from "./use-channel-watermark"import { useMessages } from "./use-messages"import { usePins, useThreads } from "./use-channel-panels"import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"-import { useReadStateProjection } from "@/lib/community-db/projections"export function useChannelMessageFeed({channelId,@@ -23,8 +22,7 @@ export function useChannelMessageFeed({isChildChannel: booleananchorMessageId: string | null}) {- const canonicalReadSnapshot = useReadStateProjection(channelId)- const readState = useChannelReadStateSnapshot(channelId, canonicalReadSnapshot)+ const readState = useChannelReadStateSnapshot(channelId)const readSnapshot = readState.snapshotconst messagesQuery = useMessages(channelId, {serverId,diff --git a/src/web/src/hooks/community/use-channel-metadata.dom.test.ts b/src/web/src/hooks/community/use-channel-metadata.dom.test.tsindex ee3ebeff0..b46219508 100644--- a/src/web/src/hooks/community/use-channel-metadata.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-metadata.dom.test.ts@@ -2,13 +2,13 @@ import React from "react"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { getLastChannel, setLastChannel } from "@/lib/community/last-channel"import { communityKeys } from "@/lib/query-keys"import { createCommunityDbRegistry, registerCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityDbProvider, useDmProjection } from "@/lib/community-db/projections"-import { captureCommunityLiveSnapshotToken, ingestDms, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"+import { applyCommunityDmBlockAccess, assertCommunityLiveSnapshotTokenCurrent, publishCommunityMessages, captureCommunityLiveSnapshotToken, ingestDms, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "./channel-metadata"import { useChannelMetadata } from "./use-channel-metadata"-import { useDmRouteVerification } from "./use-dm-route-verification"import { useDmReadStateSnapshot } from "./use-dm-read-state"import { startConversationNavigationWarmup } from "@/lib/community/conversation-navigation-warmup"@@ -42,6 +42,11 @@ function publishDms(registry: CommunityDbRegistry) {publishCommunityLiveSnapshot(registry.queryClient, { snapshot: { kind: "dms", data: dms },proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(registry.queryClient), signal: undefined } })}+async function qualifyMetadata(client: QueryClient, value = metadata) {+ apiFetch.mockResolvedValue(value)+ await client.query({ ...channelMetadataOptions(client, value.serverId, value.id), staleTime: 0 })+ apiFetch.mockReset()+}beforeEach(() => {apiFetch.mockReset()})@@ -53,6 +58,49 @@ afterEach(async () => {})describe("shared Channel resource and canonical DM publication", () => {+ it("retires a verified DM on block and waits for fresh metadata after unblock", async () => {+ const { client, registry, wrapper } = await fixture()+ publishDms(registry)+ await qualifyMetadata(client)+ const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })+ expect(route.result.current.isVerified).toBe(true)+ const original = route.result.current.data!.identityProof!+ act(() => applyCommunityDmBlockAccess(registry, "peer", true))+ expect(route.result.current.isVerified).toBe(false)+ expect(isChannelMetadataTokenCurrent(original)).toBe(false)+ expect(registry.collections.channels.has(metadata.id)).toBe(true)+ const detail = deferred<typeof metadata>()+ apiFetch.mockReturnValue(detail.promise)+ act(() => applyCommunityDmBlockAccess(registry, "peer", false))+ expect(route.result.current.isVerified).toBe(false)+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())+ await act(async () => detail.resolve(metadata))+ await waitFor(() => expect(route.result.current.isVerified).toBe(true))+ expect(isChannelMetadataTokenCurrent(route.result.current.data!.identityProof!)).toBe(true)+ route.unmount()+ })+ it("retires only the blocked DM while a sibling stays readable and rejects old target and bulk writes", async () => {+ const { client, registry, wrapper } = await fixture()+ ingestDms(registry, { conversations: [...dms.conversations, { ...dms.conversations[0], id: "dm-b", userId: "other-peer" }] })+ await qualifyMetadata(client)+ await qualifyMetadata(client, { ...metadata, id: "dm-b" })+ const target = captureChannelMetadataToken(client, metadata.id)+ const sibling = captureChannelMetadataToken(client, "dm-b")+ const bulk = captureCommunityLiveSnapshotToken(client)+ const beforeEpoch = registry.runtime.ws.get().accessEpoch+ const route = renderHook(() => ({ first: useChannelMetadata(null, metadata.id), second: useChannelMetadata(null, "dm-b") }), { wrapper })+ await waitFor(() => expect(route.result.current.second.canRead).toBe(true))+ act(() => applyCommunityDmBlockAccess(registry, "peer", true))+ expect(route.result.current.first).toMatchObject({ identityKnown: true, canRead: false, status: "denied" })+ expect(route.result.current.second).toMatchObject({ identityKnown: true, canRead: true, status: "readable" })+ expect(registry.runtime.ws.get().accessEpoch).toBe(beforeEpoch)+ expect(isChannelMetadataTokenCurrent(sibling)).toBe(true)+ expect(() => publishCommunityMessages(client, { channelId: metadata.id, messages: [], proof: { token: target } })).toThrow(expect.objectContaining({ name: "AbortError" }))+ expect(() => assertCommunityLiveSnapshotTokenCurrent(client, bulk, undefined)).toThrow(expect.objectContaining({ name: "AbortError" }))+ expect(apiFetch).not.toHaveBeenCalled()+ route.unmount()+ })+it("leaves an absent target disabled without starting a metadata request", async () => {const { client, wrapper } = await fixture()const route = renderHook(() => useChannelMetadata(null, undefined), { wrapper })@@ -64,8 +112,9 @@ describe("shared Channel resource and canonical DM publication", () => {})it("invalidates expired qualification and waits for a current metadata receipt", async () => {- const { registry, wrapper } = await fixture()+ const { client, registry, wrapper } = await fixture()publishDms(registry)+ await qualifyMetadata(client)const request = deferred<typeof metadata>()apiFetch.mockReturnValue(request.promise)const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })@@ -76,7 +125,7 @@ describe("shared Channel resource and canonical DM publication", () => {await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())await act(async () => request.resolve(metadata))await waitFor(() => expect(route.result.current.isVerified).toBe(true))- expect(isChannelMetadataTokenCurrent(route.result.current.data!.verification!)).toBe(true)+ expect(isChannelMetadataTokenCurrent(route.result.current.data!.identityProof!)).toBe(true)route.unmount()})@@ -85,23 +134,28 @@ describe("shared Channel resource and canonical DM publication", () => {ingestDms(registry, dms)apiFetch.mockResolvedValue(metadata)await client.query(channelMetadataOptions(client, null, metadata.id))- const route = renderHook(() => ({ route: useDmRouteVerification(metadata.id), peers: useDmProjection() }), { wrapper })- await waitFor(() => expect(route.result.current.route.status).toBe("present"))+ const route = renderHook(() => ({ route: useChannelMetadata(null, metadata.id), peers: useDmProjection() }), { wrapper })+ await waitFor(() => expect(route.result.current.route.status).toBe("readable"))await waitFor(() => expect(route.result.current.peers?.[0]).toMatchObject({ id: metadata.id, name: "Peer", preview: "canonical preview" }))expect(registry.collections.channels.get(metadata.id)).toMatchObject({ name: "", serverId: null, type: "dm" })- expect(registry.runtime.ws.get().channelAccessScopes.size).toBe(0)+ expect(registry.runtime.ws.get().channelAccessScopes.get(metadata.id)).toMatchObject({ serverId: null, generation: 0, revoked: false })expect(registry.runtime.ws.get().revokedServerIds.size).toBe(0)expect(apiFetch).toHaveBeenCalledOnce()route.unmount()})- it("reuses current live canonical qualification through the same Channel Query without another GET", async () => {+ it("uses a list receipt for identity and starts the protected GET for reading", async () => {const { registry, wrapper } = await fixture()publishDms(registry)+ const detail = deferred<typeof metadata>()+ apiFetch.mockReturnValue(detail.promise)const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })- expect(route.result.current.isVerified).toBe(true)- expect(route.result.current.data?.historyVerification).toBeUndefined()- expect(apiFetch).not.toHaveBeenCalled()+ expect(route.result.current.identityKnown).toBe(true)+ expect(route.result.current.canRead).toBe(false)+ expect(route.result.current.data?.readProof).toBeUndefined()+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())+ await act(async () => detail.resolve(metadata))+ await waitFor(() => expect(route.result.current.canRead).toBe(true))route.unmount()})@@ -116,17 +170,34 @@ describe("shared Channel resource and canonical DM publication", () => {const { wrapper } = await fixture(restored)const request = deferred<typeof metadata>()apiFetch.mockReturnValue(request.promise)- const route = renderHook(() => useDmRouteVerification(metadata.id), { wrapper })+ const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })expect(route.result.current.status).toBe("pending")await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())await act(async () => request.resolve(metadata))- await waitFor(() => expect(route.result.current.status).toBe("present"))+ await waitFor(() => expect(route.result.current.status).toBe("readable"))route.unmount()})})describe("DM history permission stays separate from metadata identity", () => {- it("keeps an early warm-read receipt unverified and stale until the mounted metadata request succeeds", async () => {+ it("qualifies V2 reading from metadata while the position snapshot remains pending", async () => {+ const { client, registry, wrapper } = await fixture()+ ingestDms(registry, dms)+ const pending = deferred<typeof readState>()+ apiFetch.mockImplementation((path: string) => path.endsWith("/read-state") ? pending.promise+ : { ...metadata, readContractVersion: 2, accessDecision: { channelId: metadata.id, canRead: true, canSend: true, canCreateDiscussion: false } })+ const route = renderHook(() => ({ metadata: useChannelMetadata(null, metadata.id), read: useDmReadStateSnapshot(metadata.id) }), { wrapper })+ await waitFor(() => expect(route.result.current.metadata.data?.readProof).toBeDefined())+ expect(route.result.current.metadata.isVerified).toBe(true)+ expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.readProof!)).toBe(true)+ expect(route.result.current.read).toMatchObject({ snapshot: null, isFetching: true })+ expect(client.getQueryData(metadataKey)).toHaveProperty("readProof")+ await act(async () => pending.resolve(readState))+ await waitFor(() => expect(route.result.current.read.snapshot).toEqual(readState))+ route.unmount()+ })++ it("keeps an early protected read receipt on the same resource while metadata is pending", async () => {const { client, registry, wrapper } = await fixture()ingestDms(registry, dms)const detail = deferred<typeof metadata>()@@ -136,16 +207,16 @@ describe("DM history permission stays separate from metadata identity", () => {act(() => { startConversationNavigationWarmup(client, {href: `/c/me/${metadata.id}`, viewerId: "viewer", channelId: metadata.id, scopeKind: "dm",}, registry.runtime.ws.get().accessEpoch) })- await waitFor(() => expect(client.getQueryData<{ historyVerification?: unknown }>(metadataKey)?.historyVerification).toBeDefined())- expect(client.getQueryData<{ verification?: unknown }>(metadataKey)?.verification).toBeUndefined()+ await waitFor(() => expect(client.getQueryData<{ readProof?: unknown }>(metadataKey)?.readProof).toBeDefined())+ expect(client.getQueryData<{ identityProof?: unknown }>(metadataKey)?.identityProof).toBeUndefined()expect(client.getQueryState(metadataKey)?.isInvalidated).toBe(true)const originalResource = client.getQueryCache().find({ queryKey: metadataKey, exact: true })const route = renderHook(() => useChannelMetadata(null, metadata.id), { wrapper })- expect(route.result.current.isVerified).toBe(false)+ expect(route.result.current.canRead).toBe(true)await waitFor(() => expect(apiFetch.mock.calls.filter(([path]) => path === `/api/community/channels/${metadata.id}`)).toHaveLength(1))await act(async () => detail.resolve(metadata))await waitFor(() => expect(route.result.current.isVerified).toBe(true))- expect(isChannelMetadataTokenCurrent(route.result.current.data!.historyVerification!)).toBe(true)+ expect(isChannelMetadataTokenCurrent(route.result.current.data!.readProof!)).toBe(true)expect(client.getQueryCache().find({ queryKey: metadataKey, exact: true })).toBe(originalResource)expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1)route.unmount()@@ -171,11 +242,11 @@ describe("DM history permission stays separate from metadata identity", () => {const originalResource = client.getQueryCache().find({ queryKey: metadataKey, exact: true })await act(async () => read.resolve(readState))await waitFor(() => expect(route.result.current.read.snapshot).toEqual(readState))- expect(route.result.current.metadata.isVerified).toBe(false)- expect(client.getQueryData<{ historyVerification?: unknown }>(metadataKey)?.historyVerification).toBeDefined()+ expect(route.result.current.metadata.canRead).toBe(true)+ expect(client.getQueryData<{ readProof?: unknown }>(metadataKey)?.readProof).toBeDefined()await act(async () => detail.resolve(metadata))await waitFor(() => expect(route.result.current.metadata.isVerified).toBe(true))- expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.historyVerification!)).toBe(true)+ expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.readProof!)).toBe(true)expect(client.getQueryCache().find({ queryKey: metadataKey, exact: true })).toBe(originalResource)expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1)expect(apiFetch.mock.calls.filter(([path]) => path === `/api/community/channels/${metadata.id}`)).toHaveLength(1)@@ -188,18 +259,18 @@ describe("DM history permission stays separate from metadata identity", () => {const request = deferred<typeof readState>()apiFetch.mockImplementation((path: string) => path.endsWith("/messages")? Promise.resolve({ messages: [], hasMore: false, surfaceReceipt: { channelId: metadata.id, surfaceKind: "dm" } })- : request.promise)+ : path.endsWith("/read-state") ? request.promise : new Promise(() => {}))act(() => { startConversationNavigationWarmup(client, {href: `/c/me/${metadata.id}`, viewerId: "viewer", channelId: metadata.id, scopeKind: "dm",}, registry.runtime.ws.get().accessEpoch) })await waitFor(() => expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1))const route = renderHook(() => ({ metadata: useChannelMetadata(null, metadata.id), read: useDmReadStateSnapshot(metadata.id) }), { wrapper })- expect(route.result.current.metadata.isVerified).toBe(true)- expect(route.result.current.metadata.data?.historyVerification).toBeUndefined()+ expect(route.result.current.metadata.canRead).toBe(false)+ expect(route.result.current.metadata.data?.readProof).toBeUndefined()await act(async () => request.resolve(readState))await waitFor(() => expect(route.result.current.read.snapshot).toEqual(readState))- expect(route.result.current.metadata.data?.historyVerification).toBeDefined()- expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.historyVerification!)).toBe(true)+ expect(route.result.current.metadata.data?.readProof).toBeDefined()+ expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.readProof!)).toBe(true)expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1)route.unmount()})@@ -215,7 +286,7 @@ describe("DM history permission stays separate from metadata identity", () => {}const request = deferred<typeof readState>()if (order === "published" && race.startsWith("denial")) {- client.setQueryData(metadataKey, (previous: object | undefined) => ({ ...previous, historyVerification: captureChannelMetadataToken(client, metadata.id) }))+ client.setQueryData(metadataKey, (previous: object | undefined) => ({ ...previous, readProof: captureChannelMetadataToken(client, metadata.id) }))}apiFetch.mockImplementation((path: string) => path.endsWith("/messages")? Promise.resolve({ messages: [], hasMore: false, surfaceReceipt: { channelId: metadata.id, surfaceKind: "dm" } })@@ -243,28 +314,28 @@ describe("DM history permission stays separate from metadata identity", () => {if (race === "replacement") await waitFor(() => expect(route.result.current.snapshot).toEqual(readState))else await waitFor(() => expect(route.result.current.error).toMatchObject(race.startsWith("denial")? { status: Number(race.slice(6)) } : { name: "AbortError" }))- expect(client.getQueryData<{ historyVerification?: unknown }>(metadataKey)?.historyVerification).toBeUndefined()+ expect(client.getQueryData<{ readProof?: unknown }>(metadataKey)?.readProof).toBeUndefined()expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1)route.unmount()})- it("keeps a transient read error local and grants history after explicit Retry succeeds", async () => {- const { registry, wrapper } = await fixture(new QueryClient({+ it("keeps a transient position error local and retries that request without losing reading", async () => {+ const { client, registry, wrapper } = await fixture(new QueryClient({defaultOptions: { queries: { retryDelay: 0, gcTime: Infinity } },}))publishDms(registry)+ await qualifyMetadata(client)apiFetch.mockRejectedValue(new Error("offline"))const route = renderHook(() => ({ metadata: useChannelMetadata(null, metadata.id), read: useDmReadStateSnapshot(metadata.id) }), { wrapper })await waitFor(() => expect(route.result.current.read.error?.message).toBe("offline"))- expect(apiFetch).toHaveBeenCalledTimes(2)- expect(route.result.current.metadata.isVerified).toBe(true)- expect(route.result.current.metadata.data?.historyVerification).toBeUndefined()+ expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(2)+ expect(route.result.current.metadata.canRead).toBe(true)apiFetch.mockResolvedValue(readState)act(() => route.result.current.read.retry())await waitFor(() => expect(route.result.current.read.snapshot).toEqual(readState))expect(route.result.current.read.error).toBeNull()- expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.historyVerification!)).toBe(true)- expect(apiFetch).toHaveBeenCalledTimes(3)+ expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.readProof!)).toBe(true)+ expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(3)route.unmount()})@@ -272,14 +343,15 @@ describe("DM history permission stays separate from metadata identity", () => {const { client, registry, wrapper } = await fixture()publishDms(registry)const request = deferred<typeof readState>()- apiFetch.mockReturnValue(request.promise)+ apiFetch.mockImplementation((path: string) => path.endsWith("/read-state") ? request.promise : new Promise(() => {}))const route = renderHook(() => ({ metadata: useChannelMetadata(null, metadata.id), read: useDmReadStateSnapshot(metadata.id) }), { wrapper })- expect(route.result.current.metadata.isVerified).toBe(true)- expect(route.result.current.metadata.data?.historyVerification).toBeUndefined()- await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())+ expect(route.result.current.metadata.identityKnown).toBe(true)+ expect(route.result.current.metadata.canRead).toBe(false)+ expect(route.result.current.metadata.data?.readProof).toBeUndefined()+ await waitFor(() => expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1))await act(async () => request.resolve(readState))- await waitFor(() => expect(route.result.current.metadata.data?.historyVerification).toBeDefined())- expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.historyVerification!)).toBe(true)+ await waitFor(() => expect(route.result.current.metadata.data?.readProof).toBeDefined())+ expect(isChannelMetadataTokenCurrent(route.result.current.metadata.data!.readProof!)).toBe(true)expect(apiFetch).toHaveBeenCalledWith(`/api/community/channels/${metadata.id}/read-state`, expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))expect(client.getQueryData(metadataKey)).toMatchObject({ id: metadata.id })expect(client.getQueryData(metadataKey)).not.toHaveProperty("type")@@ -289,12 +361,13 @@ describe("DM history permission stays separate from metadata identity", () => {it("removes a prior history receipt after an explicit read denial without retrying it", async () => {const { client, registry, wrapper } = await fixture()publishDms(registry)- client.setQueryData(metadataKey, (previous: object | undefined) => ({ ...previous, historyVerification: captureChannelMetadataToken(client, metadata.id) }))+ client.setQueryData(metadataKey, (previous: object | undefined) => ({ ...previous, readProof: captureChannelMetadataToken(client, metadata.id) }))apiFetch.mockRejectedValue(Object.assign(new Error("blocked"), { status: 403 }))const route = renderHook(() => ({ metadata: useChannelMetadata(null, metadata.id), read: useDmReadStateSnapshot(metadata.id) }), { wrapper })await waitFor(() => expect(route.result.current.read.error).toMatchObject({ status: 403 }))- expect(route.result.current.metadata.isVerified).toBe(true)- expect(route.result.current.metadata.data?.historyVerification).toBeUndefined()+ expect(route.result.current.metadata.identityKnown).toBe(true)+ expect(route.result.current.metadata.status).toBe("denied")+ expect(route.result.current.metadata.data?.readProof).toBeUndefined()expect(apiFetch).toHaveBeenCalledOnce()route.unmount()})@@ -315,7 +388,7 @@ describe("DM history permission stays separate from metadata identity", () => {await act(async () => request.resolve(readState))if (race === "account") await waitFor(() => expect(route.result.current.error?.name).toBe("AbortError"))else await waitFor(() => expect(route.result.current.snapshot).toEqual(readState))- expect(client.getQueryData<{ historyVerification?: unknown }>(metadataKey)?.historyVerification).toBeUndefined()+ expect(client.getQueryData<{ readProof?: unknown }>(metadataKey)?.readProof).toBeUndefined()route.unmount()})})@@ -339,3 +412,17 @@ describe("restored forum archive ambiguity", () => {route.unmount()})})++it("retires a protected archived channel and clears its exact flat navigation memory", async () => {+ const { client, registry, wrapper } = await fixture()+ const post = { ...metadata, id: "post-archived", serverId: "server-1", type: "thread", name: "Post", parentChannelId: "forum-1", parentMessageId: "opener-archived", archived: true }+ setLastChannel("server-1", post.id)+ apiFetch.mockResolvedValue(post)+ const route = renderHook(() => useChannelMetadata("server-1", post.id), { wrapper })+ await waitFor(() => expect(route.result.current.denied).toBe(true))+ expect(getLastChannel("server-1")).toBeNull()+ expect(registry.collections.channels.get(post.id)).toBeUndefined()+ expect(registry.runtime.ws.actions.isChannelAccessRevoked(post.id, "server-1")).toBe(true)+ expect(client.getQueryData(communityKeys.channelMeta("server-1", post.id))).toMatchObject({ id: post.id })+ route.unmount()+})diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.tsindex d15f46160..7fdf35d7f 100644--- a/src/web/src/hooks/community/use-channel-metadata.ts+++ b/src/web/src/hooks/community/use-channel-metadata.ts@@ -8,53 +8,46 @@ import { useCommunityWsStore } from "@/stores/community/ws"import { communityKeys } from "@/lib/query-keys"import { useCommunityRuntime } from "@/stores/community/runtime"+import { useConversationReadRetry } from "./use-conversation-read-retry"++type ChannelReadingStatus = "no-target" | "pending" | "readable" | "denied" | "unresolved" | "retryable-error"+export function useChannelMetadata(serverId: string | null, channelId: string | undefined) {const queryClient = useQueryClient()const runtime = useCommunityRuntime()const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)const accountEpoch = useCommunityWsStore((state) => state.profileAccountEpoch)const viewerId = useCommunityWsStore((state) => state.profileViewerId)- const generation = useCommunityWsStore((state) => channelId- ? state.channelAccessScopes.get(channelId)?.generation ?? 0 : 0)- const revoked = useCommunityWsStore(() => channelId- ? runtime.ws.actions.isChannelAccessRevoked(channelId, serverId ?? undefined)- : false)+ const generation = useCommunityWsStore((state) => channelId ? state.channelAccessScopes.get(channelId)?.generation ?? 0 : 0)+ const revoked = useCommunityWsStore(() => !!channelId && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId))const canonical = useRouteChannelProjection(channelId ?? null)const options = channelMetadataOptions(queryClient, serverId, channelId ?? "__none__")- const query = useQuery({- ...options,- enabled: !!channelId && !revoked,- retry: serverId === null ? false : options.retry,- retryOnMount: false,- refetchOnReconnect: false,- refetchOnWindowFocus: false,- })+ const query = useQuery({ ...options, enabled: !!channelId && !revoked,+ retry: serverId === null ? false : options.retry, retryOnMount: false,+ refetchOnReconnect: false, refetchOnWindowFocus: false })useEffect(() => {if (!channelId || revoked || query.data === undefined- || (query.data.verification && isChannelMetadataTokenCurrent(query.data.verification))) return+ || query.data.identityProof && isChannelMetadataTokenCurrent(query.data.identityProof) && query.data.readProof && isChannelMetadataTokenCurrent(query.data.readProof)) returnif (queryClient.getQueryState(communityKeys.channelMeta(serverId, channelId))?.fetchStatus === "fetching") returnvoid queryClient.invalidateQueries({ queryKey: communityKeys.channelMeta(serverId, channelId), exact: true })}, [accessEpoch, accountEpoch, viewerId, generation, channelId, revoked, query.data, queryClient, serverId])- const denied = typeof query.error === "object" && query.error !== null && "status" in query.error+ const retry = useConversationReadRetry(query, queryClient, [serverId, channelId, viewerId, accountEpoch, accessEpoch, generation])+ const identityKnown = !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pending+ const denied = revoked || typeof query.error === "object" && query.error !== null && "status" in query.error&& (query.error.status === 403 || query.error.status === 404)- const hasCurrentVerification = !!query.data && query.data.id === channelId- && canonical?.serverId === serverId && query.data.verifiedEpoch === accessEpoch- && !!query.data.verification && isChannelMetadataTokenCurrent(query.data.verification)- && !revoked && !denied && !canonical?.pending- const isArchived = hasCurrentVerification && !!canonical?.archived- const isVerified = hasCurrentVerification && !canonical?.archived- const data = useMemo(() => canonical && canonical.id === channelId && canonical.serverId === serverId- ? { ...canonical,- serverId,- createdAt: canonical.createdAt ?? "",- name: canonical.name ?? "",- verifiedEpoch: query.data?.verifiedEpoch ?? -1,- verification: query.data?.verification,- historyVerification: query.data?.historyVerification,- parentChannelId: canonical.parentChannelId ?? null,- parentMessageId: canonical.parentMessageId ?? null,- creatorId: canonical.creatorId ?? null,- lastMessageAt: canonical.lastMessageAt ?? null }- : undefined, [canonical, channelId, query.data, serverId])- return { ...query, data, isVerified, isArchived, denied, canonical }+ const isArchived = identityKnown && canonical.archived && !!query.data?.identityProof && isChannelMetadataTokenCurrent(query.data.identityProof)+ const canRead = identityKnown && !denied && !isArchived && query.data?.id === channelId+ && !!query.data.readProof && isChannelMetadataTokenCurrent(query.data.readProof)+ const status: ChannelReadingStatus = !channelId ? "no-target" : denied || isArchived ? "denied"+ : canRead ? "readable" : retry.failed ? "retryable-error"+ : query.fetchStatus === "fetching" ? "pending" : "unresolved"++ const data = useMemo(() => identityKnown ? { ...canonical, serverId,+ createdAt: canonical.createdAt ?? "", name: canonical.name ?? "",+ verifiedEpoch: query.data?.identityProof?.accessEpoch ?? -1,+ identityProof: query.data?.identityProof, readProof: query.data?.readProof,+ parentChannelId: canonical.parentChannelId ?? null, parentMessageId: canonical.parentMessageId ?? null,+ creatorId: canonical.creatorId ?? null, lastMessageAt: canonical.lastMessageAt ?? null }+ : undefined, [canonical, identityKnown, query.data, serverId])+ return { ...query, data, status, identityKnown, canRead, isVerified: canRead, isArchived, denied, canonical, retry: retry.retry, retrying: retry.retrying }}diff --git a/src/web/src/hooks/community/use-channel-panels.dom.test.ts b/src/web/src/hooks/community/use-channel-panels.dom.test.tsindex 0fce99033..a9e76161f 100644--- a/src/web/src/hooks/community/use-channel-panels.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-panels.dom.test.ts@@ -1,11 +1,42 @@import { createElement, type PropsWithChildren } from "react"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"-import { describe, expect, it } from "vitest"-import { renderHook } from "@/test/react-dom-harness"+import { describe, expect, it, vi } from "vitest"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { communityKeys } from "@/lib/query-keys"import { usePins, useThreads } from "./use-channel-panels"+import { usePinMessage } from "./mutations/message-memberships"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { ingestMessages } from "@/lib/community-db/sync"+import * as projections from "@/lib/community-db/projections"++const api = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: vi.fn() }))describe("usePins", () => {+ it("includes the same-channel pending pin in the bounded native message selection", async () => {+ const owner = await createCommunityQueryOwner("viewer")+ ingestMessages(owner.registry, "c1", [{ id: "pending", seq: 1, type: "chat", content: "Pinned body" }])+ ingestMessages(owner.registry, "foreign", [{ id: "foreign", seq: 1, type: "chat", content: "Foreign body" }])+ let resolve!: () => void+ api.mockReset().mockImplementation((_path: string, options: { method?: string }) => options.method === "POST"+ ? new Promise<void>((done) => { resolve = done }) : Promise.resolve({ pins: [] }))+ const subscription = vi.spyOn(projections, "useCanonicalMessagesById")+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider,+ { client: owner.client, registry: owner.registry, userId: "viewer", retainOwner: true }, children)+ const rendered = renderHook(() => ({ pins: usePins("c1"), pin: usePinMessage() }), { wrapper })+ try {+ await waitFor(() => expect(rendered.result.current.pins.isSuccess).toBe(true))+ expect(rendered.result.current.pins.pins).toEqual([])+ let request!: Promise<unknown>+ act(() => { request = rendered.result.current.pin.mutateAsync({ channelId: "c1", messageId: "pending" }) })+ await waitFor(() => expect(rendered.result.current.pins.pins.map((row) => row.id)).toEqual(["pending"]))+ expect(subscription).toHaveBeenCalledWith(["pending"])+ expect(owner.registry.collections.messages.size).toBe(2)+ expect(owner.registry.collections.messages.get("foreign")?.content).toBe("Foreign body")+ await act(async () => { resolve(); await request })+ } finally { rendered.unmount(); subscription.mockRestore() }+ })it("exposes a stable empty list while the query is disabled", async () => {const queryClient = new QueryClient()const wrapper = ({ children }: PropsWithChildren) => createElement(diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.tsindex f1a4f0484..e6a870477 100644--- a/src/web/src/hooks/community/use-channel-panels.test.ts+++ b/src/web/src/hooks/community/use-channel-panels.test.ts@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { type QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import { createCommunityQueryOwner } from "@/test/community-query-owner"-import { getCanonicalCommunityMessages, getCanonicalCommunityChannels } from "@/lib/community-db/sync"+import { getCanonicalCommunityMessages, getCanonicalCommunityChannels, ingestMessages } from "@/lib/community-db/sync"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { channelSchema } from "@/lib/community-db/schema"import { materializeThreadsResponse, type ThreadsResponse } from "./use-channel-panels"@@ -30,7 +31,7 @@ describe("useThreads / threadsQueryFn", () => {.mockResolvedValueOnce({ participants: [] })const { threadsQueryFn } = await import("./use-channel-panels")const data = await threadsQueryFn("ch_1", qc)()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads", expect.objectContaining({ authenticationAccount: "viewer", signal: undefined }))+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads?include=parentMessage,firstMessage,tags,participants", expect.objectContaining({ authenticationAccount: "viewer", signal: undefined }))expect(apiFetchMock).not.toHaveBeenCalledWith("/api/community/channels/ch_1/posts")expect(data.threads).toHaveLength(1)expect(project(data)[0]?.parent.text).toBe("identityless preview")@@ -78,7 +79,7 @@ describe("useThreads / threadsQueryFn", () => {apiFetchMock.mockImplementation((url: string, init: RequestInit = {}) => {const requestSignal = init.signal as AbortSignalsignals.push(requestSignal)- if (url.endsWith("/threads")) return Promise.resolve({ serverId: "s1", parentType: "forum", threads: [] })+ if (new URL(url, "http://localhost").pathname.endsWith("/threads")) return Promise.resolve({ serverId: "s1", parentType: "forum", threads: [] })return new Promise((_resolve, reject) => {requestSignal.addEventListener("abort", () => reject(new Error("aborted")))})@@ -95,6 +96,22 @@ describe("useThreads / threadsQueryFn", () => {})describe("usePins / pinsQueryFn", () => {+ it("keeps known message fields absent from a pin summary", async () => {+ const rich = { id: "m_1", type: "system" as const, systemKind: "thread" as const,+ authorId: "u1", content: "full", clientNonce: "known-nonce",+ replyTo: { id: "reply", authorName: "Peer", text: "Prior" },+ attachments: [{ kind: "file" as const, name: "known.txt", url: "/known", size: "1 KB" }],+ embeds: [{ title: "Known" }], reactions: [{ emoji: "👍", count: 1 }],+ }+ ingestMessages(getCommunityDbRegistry(qc)!, "ch_1", [rich])+ apiFetchMock.mockResolvedValueOnce({ pins: [{ id: rich.id, authorId: rich.authorId,+ authorName: "Peer", content: "summary", seq: 1, createdAt: "now" }] })+ const { pinsQueryFn } = await import("./use-channel-panels")+ await pinsQueryFn("ch_1", qc)()+ expect(getCommunityDbRegistry(qc)!.collections.messages.get(rich.id)).toMatchObject({+ ...rich, content: "summary", replyToId: "reply",+ })+ })it("fetches from /channels/:id/pins and returns { pins }", async () => {apiFetchMock.mockResolvedValueOnce({ pins: [{ id: "m_1", type: "chat", channelId: "ch_1", authorId: "u1", content: "pin" }] })const { pinsQueryFn } = await import("./use-channel-panels")@@ -113,6 +130,25 @@ describe("usePins / pinsQueryFn", () => {})describe("materializeThreadsResponse", () => {+ it("retains panel preview limits, created-time fallback and optional opener fields", () => {+ const preview = "preview".repeat(30), content = "content".repeat(30)+ const base = { type: "thread", position: 0, archived: false, muted: false, unread: false, pending: false, tags: [] }+ const channels = new Map([+ ["post", channelSchema.parse({ ...base, id: "post", name: "Fallback", createdAt: "created", preview, parentMessageId: "opener" })],+ ["empty", channelSchema.parse({ ...base, id: "empty", name: "", preview, createdAt: "created" })],+ ["archived", channelSchema.parse({ ...base, id: "archived", name: "Archived", archived: true })],+ ])+ const data = { parentType: "forum", serverId: "s1", parentChannelId: "forum", threads: [{ id: "post", openerMessageId: "opener" }, { id: "empty" }, { id: "archived" }] }+ const messages = new Map([["opener", { id: "opener", type: "chat" as const, content: " ", authorId: "u1", authorName: "A", seq: 0 }]])+ const forum = materializeThreadsResponse(data, messages, channels)+ expect(forum).toHaveLength(2)+ expect(forum[0]).toEqual({ id: "post", name: "Fallback", messageCount: 0, lastMessageAt: "created", parent: { authorId: "u1", authorName: "A", text: preview.slice(0, 100) }, parentSeq: 0, openerMessageId: "opener" })+ expect(forum[1]).toMatchObject({ name: "Post", lastMessageAt: "created", parent: { authorName: "", text: preview.slice(0, 100) } })+ expect(forum[1]).not.toHaveProperty("parentSeq")+ expect(forum[1]).not.toHaveProperty("openerMessageId")+ messages.set("opener", { ...messages.get("opener")!, content })+ expect(materializeThreadsResponse({ ...data, parentType: "text" }, messages, channels)[0]).toMatchObject({ name: "Fallback", parent: { text: content.slice(0, 100) } })+ })it("filters missing openers and projects forum and text content from canonical rows", async () => {const { materializeThreadsResponse } = await import("./use-channel-panels")const base = {diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.tsindex dcf9717ac..40c44f424 100644--- a/src/web/src/hooks/community/use-channel-panels.ts+++ b/src/web/src/hooks/community/use-channel-panels.ts@@ -1,11 +1,12 @@"use client"+import { useMemo } from "react"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useMutationState, useQuery, useQueryClient, type QueryClient, type UseQueryResult } from "@tanstack/react-query"import { communityRequestOptions } from "@/lib/community-db/sync"import { apiFetch } from "@/lib/api/client"-import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"+import { apiFetchCommunity, communityRequestOptions as qualifiedCommunityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { communityKeys } from "@/lib/query-keys"import type { Thread, Msg } from "@/lib/community/models/message"import {@@ -19,8 +20,9 @@ import {publishCommunityForumFeed,assertCommunityLiveSnapshotTokenCurrent,} from "@/lib/community-db/sync"-import { communityRequestOptions as qualifiedCommunityRequestOptions } from "@/lib/community/account-cache-lifecycle"import type { CommunityFreshQueryProof } from "@/lib/community-db/sync"+import { normalizeThreadResources, projectThread, type ForumFeedTransportPage } from "./forum-feed-window"+import type { CommunityThreadsRead, CommunityChannelResource, CommunityMessageResource } from "@alook/shared"import type { ChannelRow } from "@/lib/community-db/schema"/**@@ -33,85 +35,36 @@ import type { ChannelRow } from "@/lib/community-db/schema"* — without touching messages.*/export type ThreadsResponse = {- threads: Array<{ id: string; openerMessageId?: string }>- serverId: string+ threads: Array<Pick<CommunityChannelResource, "id"> & { openerMessageId?: CommunityMessageResource["id"] }>+ serverId: NonNullable<CommunityChannelResource["serverId"]>parentType: string- parentChannelId: string+ parentChannelId: CommunityChannelResource["id"]}-type RawThread = {- id: string- name: string- type: string- creatorId: string | null- parentMessageId: string | null- messageCount: number | null- lastMessageAt: string | null- createdAt: string-}-type BatchMessage = {- id: string- channelId: string- content: string- seq: number- authorId: string- authorName: string- authorImage: string | null-}-type FirstMessagePreview = { channelId: string; content: string }-type ParticipantRow = { channelId: string; userId: string; userName: string | null; userImage: string | null; addedAt: string; participantCount?: number }--async function loadThreadResources(queryClient: QueryClient, channelId: string, proof: CommunityFreshQueryProof, tag?: string | null) {+async function loadThreadResources(queryClient: QueryClient, channelId: string, proof: CommunityFreshQueryProof) {const options = qualifiedCommunityRequestOptions(queryClient, proof.token, proof.signal)- const query = tag ? `?tag=${encodeURIComponent(tag)}` : ""- const { threads, parentType, serverId } = await apiFetch<{- threads: RawThread[]- parentType: string- serverId: string- }>(- `/api/community/channels/${channelId}/threads${query}`,- options,- )+ const response = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants`, options)assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- const openerIds = threads.map((thread) => thread.parentMessageId).filter((id): id is string => !!id)- const threadIds = threads.map((thread) => thread.id)- const [messageBatch, tagBatch, participantBatch] = await Promise.all([- apiFetch<{ messages: BatchMessage[]; firstMessages: FirstMessagePreview[] }>("/api/community/messages/batch", {- method: "POST",- body: JSON.stringify({ channelId, ids: openerIds, firstInChannelIds: threadIds }),- ...options,- }),- apiFetch<{ tags: { messageId: string; tag: string }[] }>("/api/community/messages/tags/batch", {- method: "POST",- body: JSON.stringify({ channelId, messageIds: openerIds }),- ...options,- }),- apiFetch<{ participants: ParticipantRow[] }>("/api/community/channels/participants/batch", {- method: "POST",- body: JSON.stringify({ parentChannelId: channelId, channelIds: threadIds }),- ...options,- }),+ if ("contractVersion" in response || response.included) return normalizeThreadResources(channelId, response)+ const openerIds = response.threads.flatMap((thread) => thread.parentMessageId ? [thread.parentMessageId] : [])+ const threadIds = response.threads.map((thread) => thread.id)+ const [messages, tags, participants] = await Promise.all([+ apiFetch<Pick<ForumFeedTransportPage["included"], "parentMessages" | "firstMessages"> & { messages: ForumFeedTransportPage["included"]["parentMessages"] }>("/api/community/messages/batch", { method: "POST", body: JSON.stringify({ channelId, ids: openerIds, firstInChannelIds: threadIds }), ...options }),+ apiFetch<Pick<ForumFeedTransportPage["included"], "tags">>("/api/community/messages/tags/batch", { method: "POST", body: JSON.stringify({ channelId, messageIds: openerIds }), ...options }),+ apiFetch<Pick<ForumFeedTransportPage["included"], "participants">>("/api/community/channels/participants/batch", { method: "POST", body: JSON.stringify({ parentChannelId: channelId, channelIds: threadIds }), ...options }),])- return { threads, parentType, serverId, openerIds, ...messageBatch, ...tagBatch, ...participantBatch }+ return normalizeThreadResources(channelId, { ...response, hasMore: false, included: { parentMessages: messages.messages.map((message) => ({ ...message, authorAvatarVersion: message.authorAvatarVersion ?? 0 })), firstMessages: messages.firstMessages, tags: tags.tags, participants: participants.participants.map((participant) => ({ ...participant, userAvatarVersion: participant.userAvatarVersion ?? 0 })) } })}export const threadsQueryFn = (channelId: string, queryClient: QueryClient) => async ({ signal }: { signal?: AbortSignal } = {}) => {- const token = captureCommunityLiveSnapshotToken(queryClient), registry = getCommunityDbRegistry(queryClient)+ const token = captureCommunityLiveSnapshotToken(queryClient, channelId), registry = getCommunityDbRegistry(queryClient)await registry?.readyassertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)await Promise.all([registry!.collections.channels.preload(), registry!.collections.messages.preload(), registry!.collections.channelMemberships.preload()])assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)const data = await loadThreadResources(queryClient, channelId, { token, signal })- publishCommunityForumFeed(queryClient, channelId, {- serverId: data.serverId, parentType: data.parentType, hasMore: false,- threads: data.threads.map((thread) => ({ ...thread, activityAt: thread.lastMessageAt ?? thread.createdAt })),- included: {- parentMessages: data.messages.map((message) => ({ ...message, authorAvatarVersion: 0 })),- firstMessages: data.firstMessages, tags: data.tags,- participants: data.participants.map((participant) => ({ ...participant, userAvatarVersion: 0 })),- },- }, { token, signal })- return { threads: data.threads.map((thread) => ({ id: thread.id, ...(thread.parentMessageId ? { openerMessageId: thread.parentMessageId } : {}) })), parentType: data.parentType, serverId: data.serverId, parentChannelId: channelId }+ publishCommunityForumFeed(queryClient, channelId, data, { token, signal })+ return { threads: data.threads.map((thread) => ({ id: thread.id, ...(thread.parentMessageId ? { openerMessageId: thread.parentMessageId } : {}) })), parentType: data.channel.type, serverId: data.channel.serverId ?? "", parentChannelId: channelId }}export function materializeThreadsResponse(data: ThreadsResponse | undefined, messages: ReadonlyMap<string, Msg> | undefined, channels: ReadonlyMap<string, ChannelRow>): Thread[] {@@ -119,7 +72,8 @@ export function materializeThreadsResponse(data: ThreadsResponse | undefined, mereturn data.threads.flatMap((window) => {const thread = channels.get(window.id), opener = window.openerMessageId ? messages?.get(window.openerMessageId) : undefinedif (!thread || (window.openerMessageId && !opener) || thread.archived) return []- return [{ id: thread.id, name: data.parentType === "forum" ? (opener?.content?.trim() ? opener.content : thread.name || "Post") : thread.name, messageCount: thread.messageCount ?? 0, lastMessageAt: thread.lastMessageAt ?? thread.createdAt ?? "", parent: { authorId: opener?.authorId, authorName: opener?.authorName ?? "", text: (data.parentType === "forum" ? thread.preview ?? "" : opener?.content ?? thread.preview ?? "").slice(0, 100) }, ...(opener?.seq === undefined ? {} : { parentSeq: opener.seq }), ...(window.openerMessageId ? { openerMessageId: window.openerMessageId } : {}) }]+ const core = projectThread(thread, opener, data.parentType)+ return [{ ...core, lastMessageAt: thread.lastMessageAt ?? thread.createdAt ?? "", parent: { ...core.parent, text: core.parent.text.slice(0, 100) }, ...(window.openerMessageId ? { openerMessageId: window.openerMessageId } : {}) }]})}@@ -127,7 +81,6 @@ export function useThreads(channelId: string | null): UseQueryResult<ThreadsRespthreads: Thread[]} {const queryClient = useQueryClient()- const canonicalMessages = useCanonicalMessagesById()const channels = useCanonicalChannelsById()const enabled = !!channelIdconst query = useQuery({@@ -137,6 +90,8 @@ export function useThreads(channelId: string | null): UseQueryResult<ThreadsResp: (() => Promise.reject(new Error("disabled"))),enabled,})+ const messageIds = useMemo(() => query.data?.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : []) ?? [], [query.data?.threads])+ const canonicalMessages = useCanonicalMessagesById(messageIds)const threads = materializeThreadsResponse(query.data, canonicalMessages, channels)return {...query,@@ -156,20 +111,17 @@ export function useForumTags(channelId: string | null, enabled: boolean) {* Fetches the pinned-message list for a channel. Server-side hydrates the* author + content so no follow-up fetch is needed.*/-export type PinsResponse = { pins: Msg[] }-export type PinsWindowResponse = { pins: Array<{ id: string }> }+export type PinsResponse = { pins: Array<Pick<Msg, "id" | "seq" | "authorId" | "authorName" | "authorAvatar" | "authorAvatarVersion" | "content" | "createdAt">> }+export type PinsWindowResponse = { pins: Array<Pick<CommunityMessageResource, "id">> }export const pinsQueryFn = (channelId: string, queryClient: QueryClient) =>async ({ signal }: { signal?: AbortSignal } = {}) => {- const publicationToken = queryClient- ? captureCommunityLiveSnapshotToken(queryClient)- : null- const data = await apiFetchProfiles<PinsResponse>(+ const publicationToken = captureCommunityLiveSnapshotToken(queryClient, channelId)+ const data = await apiFetchCommunity<PinsResponse>(`/api/community/channels/${channelId}/pins`,- (response) => messageProfilePatches(response.pins),- signal ? { signal } : undefined, getCommunityDbRegistry(queryClient),+ signal ? { signal } : undefined, publicationToken,)- if (queryClient && publicationToken) {+ {publishCommunityEmbeddedMessages(queryClient, {entries: data.pins.map((message) => ({ channelId, message })),proof: { token: publicationToken, signal },@@ -182,7 +134,6 @@ export function usePins(channelId: string | null): UseQueryResult<PinsWindowResppins: Msg[]} {const queryClient = useQueryClient()- const canonicalMessages = useCanonicalMessagesById()const enabled = !!channelIdconst query = useQuery({queryKey: enabled ? communityKeys.pins(channelId!) : communityKeys.pins("__none__"),@@ -192,10 +143,14 @@ export function usePins(channelId: string | null): UseQueryResult<PinsWindowRespenabled,})const pending = useMutationState({ filters: { mutationKey: ["community", "pin-command"], status: "pending" }, select: (mutation) => ({ channelId: (mutation.state.variables as { channelId: string }).channelId, messageId: (mutation.state.variables as { messageId: string }).messageId, pinned: mutation.options.mutationKey?.[2] === "pin" }) })- const ids = new Set(query.data?.pins.map((row) => row.id) ?? [])- for (const command of pending) if (command.channelId === channelId) { if (command.pinned) ids.add(command.messageId); else ids.delete(command.messageId) }+ const ids = useMemo(() => {+ const ids = new Set(query.data?.pins.map((row) => row.id) ?? [])+ for (const command of pending) if (command.channelId === channelId) { if (command.pinned) ids.add(command.messageId); else ids.delete(command.messageId) }+ return [...ids]+ }, [query.data?.pins, pending, channelId])+ const canonicalMessages = useCanonicalMessagesById(ids)return {...query,- pins: materializeCanonicalMessages([...ids].map((id) => ({ id })), canonicalMessages),+ pins: materializeCanonicalMessages(ids.map((id) => ({ id })), canonicalMessages),}}diff --git a/src/web/src/hooks/community/use-channel-read-state.dom.test.ts b/src/web/src/hooks/community/use-channel-read-state.dom.test.tsindex aff1095df..2863358d7 100644--- a/src/web/src/hooks/community/use-channel-read-state.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-read-state.dom.test.ts@@ -1,11 +1,12 @@import { createElement, type PropsWithChildren } from "react"-import { QueryClient, QueryClientProvider, onlineManager } from "@tanstack/react-query"+import { QueryClient, QueryClientProvider, onlineManager, IsRestoringProvider } from "@tanstack/react-query"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityDbProvider } from "@/lib/community-db/projections"import { CONVERSATION_READ_TIMEOUT_MS, ConversationReadTimeoutError } from "@/lib/community/conversation-read"import { communityKeys } from "@/lib/query-keys"+import { ingestReadStateSnapshot } from "@/lib/community-db/sync"import { useChannelReadStateSnapshot, type ChannelReadStateSnapshot } from "./use-channel-read-state"const api = vi.fn()@@ -27,8 +28,8 @@ afterEach(async () => {})})function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }-function mount(id = "ch_1", canonical?: ChannelReadStateSnapshot) {- return renderHook(({ id, canonical }) => useChannelReadStateSnapshot(id, canonical), { wrapper: Owner, initialProps: { id, canonical } })+function mount(id = "ch_1") {+ return renderHook(({ id }) => useChannelReadStateSnapshot(id), { wrapper: Owner, initialProps: { id } })}function held() {let resolve!: (value: ChannelReadStateSnapshot) => void@@ -43,6 +44,24 @@ describe("native channel read-state snapshot", () => {expect(rendered.result.current).toMatchObject({ snapshot: null, isFetching: true })await act(async () => { pending.resolve(original) })})+ it.each(["channel", "dm"] as const)("keeps %s restoration unresolved until the current read settles", async (kind) => {+ const key = kind === "dm" ? communityKeys.dmReadStateSnapshot("restored") : communityKeys.channelReadStateSnapshot("restored")+ client.setQueryData(key, original)+ const pending = held()+ const observed: ReturnType<typeof useChannelReadStateSnapshot>[] = []+ function Capture() { observed.push(useChannelReadStateSnapshot("restored", kind)); return null }+ const view = (restoring: boolean) => createElement(Owner, null,+ createElement(IsRestoringProvider, { value: restoring }, createElement(Capture)))+ const rendered = render(view(true))+ expect(observed.at(-1)).toMatchObject({ snapshot: null, isFetching: true })+ expect(api).not.toHaveBeenCalled()+ rendered.rerender(view(false))+ await waitFor(() => expect(api).toHaveBeenCalledOnce())+ expect(observed.at(-1)).toMatchObject({ snapshot: null, isFetching: true })+ await act(async () => { pending.resolve(fresh) })+ await waitFor(() => expect(observed.at(-1)).toMatchObject({ snapshot: fresh, isFetching: false }))+ })+it("returns the resolved value on first success", async () => {api.mockResolvedValueOnce(original)const rendered = mount()@@ -56,12 +75,28 @@ describe("native channel read-state snapshot", () => {await act(async () => { pending.resolve(fresh) })await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))})- it("freezes canonical data immediately while the mount request revalidates", async () => {- const pending = held(), rendered = mount("ch_1", original)- expect(rendered.result.current).toMatchObject({ snapshot: original, isFetching: false })+ it("withholds a stale canonical pointer until the current mount read succeeds", async () => {+ ingestReadStateSnapshot(registry, { revision: 1, readStates: [{ channelId: "ch_1", ...empty }] })+ const pending = held(), rendered = mount("ch_1")+ await waitFor(() => expect(api).toHaveBeenCalledOnce())+ expect(rendered.result.current).toMatchObject({ snapshot: null, isFetching: true })await act(async () => { pending.resolve(fresh) })- rendered.rerender({ id: "ch_1", canonical: undefined })- expect(rendered.result.current.snapshot).toEqual(original)+ await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))+ await act(async () => { ingestReadStateSnapshot(registry, { revision: 2, readStates: [{ channelId: "ch_1", ...original }] }) })+ rendered.rerender({ id: "ch_1" })+ expect(rendered.result.current.snapshot).toEqual(fresh)+ })+ it("does not latch retained query data when the new mount read fails", async () => {+ client.setQueryData(communityKeys.channelReadStateSnapshot("ch_1"), original)+ api.mockRejectedValue(new Error("fresh mount unavailable"))+ const rendered = mount()+ await waitFor(() => expect(api).toHaveBeenCalledTimes(2))+ await waitFor(() => expect(rendered.result.current.isFetching).toBe(false))+ expect(rendered.result.current.error).toBeInstanceOf(Error)+ expect(rendered.result.current.snapshot).toBeNull()+ api.mockResolvedValueOnce(fresh)+ act(() => rendered.result.current.retry())+ await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))})it("keeps the first settled snapshot through a later refetch", async () => {api.mockResolvedValueOnce(original)@@ -77,7 +112,7 @@ describe("native channel read-state snapshot", () => {const rendered = mount()await waitFor(() => expect(rendered.result.current.snapshot).toEqual(original))const pending = held()- rendered.rerender({ id: "ch_2", canonical: undefined })+ rendered.rerender({ id: "ch_2" })expect(rendered.result.current.snapshot).toBeNull()await act(async () => { pending.resolve(fresh) })await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))diff --git a/src/web/src/hooks/community/use-channel-read-state.ts b/src/web/src/hooks/community/use-channel-read-state.tsindex f94bdbdbe..fcf3a2ebe 100644--- a/src/web/src/hooks/community/use-channel-read-state.ts+++ b/src/web/src/hooks/community/use-channel-read-state.ts@@ -2,27 +2,21 @@import { useLayoutEffect, useMemo } from "react"import { createStore, useSelector } from "@tanstack/react-store"-import { useQuery, useQueryClient, type QueryFunctionContext } from "@tanstack/react-query"+import { useQuery, useQueryClient, useIsRestoring, type QueryFunctionContext } from "@tanstack/react-query"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent, type ChannelMetadataResource } from "./channel-metadata"import { retryConversationRead, withConversationReadDeadline } from "@/lib/community/conversation-read"import { apiFetch } from "@/lib/api/client"+import { retireCommunityChannelReading } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"+import type { CommunityReadStateResource } from "@alook/shared"/*** The channel read-state snapshot returned by* `GET /api/community/channels/:id/read-state`. Both fields are `null` when* the viewer has never visited the channel.*/-export type ChannelReadStateSnapshot = {- lastReadMessageId: string | null- lastReadAt: string | null- // Numeric equivalent of `lastReadMessageId` — the seq of the row that- // pointer refers to. Server returns `0` when the viewer has never read- // this channel; consumers subtract from `latestSeq` for the unread-count- // pill without needing to walk loaded rows.- lastReadSeq: number-}+export type ChannelReadStateSnapshot = Omit<CommunityReadStateResource, "channelId">export function channelReadStateSnapshotQueryFn(channelId: string,@@ -40,12 +34,12 @@ export function channelReadStateSnapshotQueryFn(const metadataQuery = kind === "dm"? client.getQueryCache().build(client, client.defaultQueryOptions(channelMetadataOptions(client, null, channelId))): undefined- const updateHistory = (historyVerification?: ChannelMetadataResource["historyVerification"]) => {+ const updateHistory = (readProof?: ChannelMetadataResource["readProof"]) => {if (!metadataQuery || !Object.is(client.getQueryCache().find({ queryKey: metadataKey, exact: true }), metadataQuery)) returnconst metadata = client.setQueryData<ChannelMetadataResource>(metadataKey, (previous) => previous- ? { ...previous, historyVerification }- : historyVerification ? { id: channelId, verifiedEpoch: -1, historyVerification } : undefined)- if (metadata && !metadata.verification) metadataQuery.invalidate()+ ? { ...previous, readProof }+ : readProof ? { id: channelId, serverId: null, readProof } : undefined)+ if (metadata && !metadata.identityProof) metadataQuery.invalidate()}try {const snapshot = await withConversationReadDeadline(signal, async (readSignal) => {@@ -55,11 +49,15 @@ export function channelReadStateSnapshotQueryFn(return apiFetch<ChannelReadStateSnapshot>(`/api/community/channels/${channelId}/read-state`, communityRequestOptions(client, token, readSignal, assert))})assert()- updateHistory(token)+ if (kind === "dm") token.registry!.runtime.ws.actions.rememberChannelAccess(null, channelId)+ updateHistory(captureChannelMetadataToken(client, channelId))return snapshot} catch (error) {assert()- if (typeof error === "object" && error !== null && "status" in error && [403, 404].includes(Number(error.status))) updateHistory()+ if (typeof error === "object" && error !== null && "status" in error && [403, 404].includes(Number(error.status))) {+ updateHistory()+ retireCommunityChannelReading(token.registry!, channelId, { reason: "read-denied", preserveQuery: client.getQueryCache().find({ queryKey: kind === "dm" ? communityKeys.dmReadStateSnapshot(channelId) : communityKeys.channelReadStateSnapshot(channelId), exact: true }) })+ }throw error}}@@ -88,7 +86,6 @@ export function channelReadStateSnapshotQueryFn(*/export function useChannelReadStateSnapshot(channelId: string | null | undefined,- canonicalSnapshot?: ChannelReadStateSnapshot,kind: "channel" | "dm" = "channel",): {snapshot: ChannelReadStateSnapshot | null@@ -98,6 +95,7 @@ export function useChannelReadStateSnapshot(retry: () => void} {const client = useQueryClient()+ const isRestoring = useIsRestoring()const entry = useMemo(() => createStore({ client, channelId, kind, snapshot: null as ChannelReadStateSnapshot | null }), [client, channelId, kind])const frozen = useSelector(entry, (state) => state.snapshot)const query = useQuery<ChannelReadStateSnapshot>({@@ -124,14 +122,14 @@ export function useChannelReadStateSnapshot(networkMode: "always",})+ const available = !isRestoring && query.status === "success" && !query.isFetching ? query.data : undefineduseLayoutEffect(() => {- const available = canonicalSnapshot ?? (!query.isFetching ? query.data : undefined)if (available) entry.setState((state) => state.snapshot ? state : { ...state, snapshot: available })- }, [entry, canonicalSnapshot, query.data, query.isFetching])+ }, [entry, available])return {- snapshot: frozen ?? canonicalSnapshot ?? (!query.isFetching ? (query.data ?? null) : null),- isFetching: frozen === null && !canonicalSnapshot && query.isFetching,+ snapshot: frozen ?? available ?? null,+ isFetching: !!channelId && frozen === null && (isRestoring || query.isPending || query.isFetching),error: query.error,retrying: query.isFetching,retry: () => { void query.refetch({ cancelRefetch: false }) },diff --git a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.tsindex d638ad002..91145c53b 100644--- a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts@@ -11,18 +11,18 @@ import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"import { runAuthoritativeServerEject } from "@/lib/community/eject-server"-const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), replace: vi.fn(), toast: vi.fn(),+const mocks = vi.hoisted(() => ({ pathname: "/c/channels/server-1/post-1", apiFetch: vi.fn(), replace: vi.fn(), toast: vi.fn(),server: { server: { id: "server-1", categories: [{ channels: [{ id: "parent-1", name: "parent", type: "text" }] }] } as { id: string; categories: { channels: { id: string; name: string; type: string }[] }[] } | null,isError: false, isFetching: false, refetch: vi.fn(() => Promise.resolve()) },}))vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.apiFetch, toastApiError: mocks.toast }))-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }) }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }), usePathname: () => mocks.pathname }))vi.mock("./use-servers", () => ({useServer: () => mocks.server,}))vi.mock("./use-community-ws", () => ({ communityWsSubscribe: vi.fn(), communityWsUnsubscribe: vi.fn() }))vi.mock("./use-forum-sidebar-threads", () => ({- removeForumSidebarUnreadChild: vi.fn(), removeForumSidebarThreadExact: vi.fn(),+ removeForumSidebarUnreadChild: vi.fn(),invalidateForumSidebarBaseExact: vi.fn().mockResolvedValue(undefined),}))vi.mock("@/lib/community/last-channel", () => ({ getLastChannel: () => null, clearLastChannel: vi.fn() }))@@ -69,9 +69,11 @@ function payload(id = "post-1") {}beforeEach(async () => {+ window.history.replaceState(null, "", "/c/channels/server-1/post-1")mocks.apiFetch.mockReset()Object.assign(mocks.server, { server: { id: "server-1", categories: [{ channels: [{ id: "parent-1", name: "parent", type: "text" }] }] }, isError: false, isFetching: false })mocks.server.refetch.mockReset().mockResolvedValue(undefined)+ mocks.pathname = "/c/channels/server-1/post-1"mocks.replace.mockClear()mocks.toast.mockClear()client = (await createCommunityQueryOwner("viewer-1", { defaultOptions: { queries: { retry: 1, retryDelay: 0, gcTime: Infinity } } })).client@@ -174,6 +176,7 @@ describe("unresolved metadata terminal error and retry", () => {await mount()await until(() => mocks.apiFetch.mock.calls.length === 1)+ mocks.pathname = "/c/channels/server-1/next-1"act(() => getCommunityDbRegistry(client)!.runtime.ui.actions.setCurrentChannelId(null))await act(async () => request.reject(new ApiError("missing", 404)))await until(() => current.routeLifecycle === "terminal-error")@@ -181,6 +184,17 @@ describe("unresolved metadata terminal error and retry", () => {expect(mocks.replace).not.toHaveBeenCalled()})+ it("does not exit a new browser URL before the previous pathname hook catches up", async () => {+ const request = deferred()+ mocks.apiFetch.mockReturnValueOnce(request.promise)+ await mount()+ await until(() => mocks.apiFetch.mock.calls.length === 1)+ window.history.pushState(null, "", "/c/channels/server-1/next-1")+ await act(async () => request.reject(new ApiError("missing", 404)))+ await until(() => current.routeLifecycle === "terminal-error")+ expect(mocks.replace).not.toHaveBeenCalled()+ })+it("does not overwrite a server eject with the denied channel's server root", async () => {const owner = getCommunityDbRegistry(client)!owner.runtime.ws.actions.revokeServerAccess("server-1")@@ -231,7 +245,21 @@ describe("unresolved metadata terminal error and retry", () => {await act(async () => { await reconcileCommunityWsReconnect(client, 60_000) })await until(() => current.routeLifecycle === "terminal-error")expect(current.metadataError).toBe(false)- if (status !== 401) expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")+ if (status !== 401) {+ expect(getCommunityDbRegistry(client)!.runtime.ui.get().currentChannelId).toBeNull()+ expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")+ }+ })++ it("does not redirect a new URL after the old target is authoritatively revoked", async () => {+ mocks.apiFetch.mockResolvedValue(payload())+ await mount()+ await until(() => current.routeHydrated)+ mocks.pathname = "/c/channels/server-1/parent-1"+ mocks.apiFetch.mockRejectedValue(new ApiError("denied", 403))+ await act(async () => { await reconcileCommunityWsReconnect(client, 60_000) })+ await until(() => current.routeLifecycle === "terminal-error")+ expect(mocks.replace).not.toHaveBeenCalled()})it("keeps a legacy tag-derived archive bit pending without purging or revoking access", async () => {@@ -335,7 +363,7 @@ describe("unresolved metadata terminal error and retry", () => {await act(async () => { request = current.retryMetadata() })expect(current.retryingMetadata).toBe(true)await act(async () => {- if (change === "account") renderer!.rerender(tree({ accountId: "viewer-2" }))+ if (change === "account") { getCommunityDbRegistry(client)!.runtime.ws.actions.activateProfileAccount("viewer-2"); renderer!.rerender(tree({ accountId: "viewer-2" })) }else {getCommunityDbRegistry(client)!.runtime.ws.setState((state) => ({ ...state, accessEpoch: state.accessEpoch + 1 }))}diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.tsindex be5419607..e6b5b1459 100644--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({metaQuery: {data: undefined as undefined | Record<string, unknown>,error: null as unknown,- isVerified: false, isArchived: false,+ canRead: false, isArchived: false,isError: false,},dbChannel: undefined as undefined | Record<string, unknown>,@@ -31,12 +31,13 @@ function render(node: React.ReactNode) { return renderDom(node, { wrapper: Nativvi.mock("next/navigation", () => ({useRouter: () => ({ replace: mocks.replace }),+ usePathname: () => "/c/channels/server-1/post-1",}))vi.mock("./use-servers", () => ({useServer: () => ({ server: mocks.server }),}))vi.mock("./use-channel-metadata", () => ({- useChannelMetadata: () => mocks.metaQuery,+ useChannelMetadata: () => ({ ...mocks.metaQuery, canonical: mocks.dbChannel, denied: mocks.metaQuery.isArchived, status: mocks.metaQuery.isError ? "retryable-error" : mocks.metaQuery.canRead ? "readable" : "pending", retrying: false, retry: async () => {} }),}))vi.mock("./use-community-ws", () => ({communityWsSubscribe: (...args: unknown[]) => mocks.subscribe(...args),@@ -63,7 +64,7 @@ vi.mock("@/lib/community-db/sync", async (importOriginal) => ({ ...await importOimport { buildChannelRouteModel, useChannelRouteModel } from "./use-channel-route-model"function Harness({ channelId = "post-1" }: { channelId?: string }) {- const result = useChannelRouteModel("server-1", "server-1", channelId, "viewer-1")+ const result = useChannelRouteModel("server-1", "server-1", channelId, "viewer")return React.createElement("span", {"data-lifecycle": result.routeLifecycle,"data-skeleton-subtype": result.skeletonSubtype,@@ -78,6 +79,7 @@ function lifecycle(renderer: ReturnType<typeof render>) {}beforeEach(async () => {+ window.history.replaceState(null, "", "/c/channels/server-1/post-1")const owner = await createCommunityQueryOwner()queryClient = owner.clientmocks.subscribe.mockClear()@@ -96,7 +98,7 @@ beforeEach(async () => {channels: [{ id: "forum-1", name: "Forum", type: "forum" }],}],}- mocks.metaQuery = { data: undefined, error: null, isVerified: false, isArchived: false, isError: false }+ mocks.metaQuery = { data: undefined, error: null, canRead: false, isArchived: false, isError: false }mocks.dbChannel = undefined})@@ -122,7 +124,7 @@ describe("useChannelRouteModel subscription ownership", () => {})expect(lifecycle(renderer!)).toBe("pending")- mocks.metaQuery.isVerified = true+ mocks.metaQuery.canRead = trueact(() => renderer!.rerender(React.createElement(Harness, { channelId: "forum-1" })))expect(lifecycle(renderer!)).toBe("ready")act(() => renderer!.unmount())@@ -137,7 +139,7 @@ describe("useChannelRouteModel subscription ownership", () => {}],}- mocks.metaQuery.isVerified = true+ mocks.metaQuery.canRead = trueconst renderer = render(React.createElement(Harness, { channelId: "text-1" }))const node = renderer.container.querySelector("span")@@ -178,7 +180,7 @@ describe("useChannelRouteModel subscription ownership", () => {expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "pending")expect(renderer.container.querySelector("span")).toHaveAttribute("data-parent-channel", "")mocks.metaQuery = { data: { ...mocks.dbChannel, creatorId: null, lastMessageAt: null, createdAt: "", archived: false },- error: null, isVerified: true, isArchived: false, isError: false }+ error: null, canRead: true, isArchived: false, isError: false }act(() => renderer.rerender(React.createElement(Harness)))expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "ready")expect(renderer.container.querySelector("span")).toHaveAttribute("data-creator-id", "")@@ -231,7 +233,7 @@ describe("useChannelRouteModel subscription ownership", () => {verifiedEpoch: 0,},error: null,- isVerified: true, isArchived: false,+ canRead: true, isArchived: false,isError: false,}act(() => {@@ -260,7 +262,7 @@ describe("useChannelRouteModel subscription ownership", () => {activityAt: "2026-08-09T00:00:00.000Z",verifiedEpoch: 0,}- mocks.metaQuery = { data: meta, error: null, isVerified: true, isArchived: false, isError: false }+ mocks.metaQuery = { data: meta, error: null, canRead: true, isArchived: false, isError: false }const storeListener = vi.fn()const subscription = getCommunityRuntime(queryClient).ui.subscribe(storeListener)const renderer = render(React.createElement(Harness))@@ -269,7 +271,7 @@ describe("useChannelRouteModel subscription ownership", () => {mocks.metaQuery = {data: { ...meta },error: null,- isVerified: true, isArchived: false,+ canRead: true, isArchived: false,isError: false,}act(() => renderer.rerender(React.createElement(Harness)))@@ -283,7 +285,7 @@ describe("useChannelRouteModel subscription ownership", () => {mocks.metaQuery = {data: undefined,error: new Error("metadata unavailable"),- isVerified: false, isArchived: false,+ canRead: false, isArchived: false,isError: true,}let renderer: ReturnType<typeof render>@@ -294,7 +296,7 @@ describe("useChannelRouteModel subscription ownership", () => {act(() => renderer!.unmount())})- it("clears an exact flat last-channel value when verified metadata is archived", () => {+ it("falls back after the common read owner archives a child without retiring it a second time", () => {mocks.lastChannel = "post-1"mocks.metaQuery = {data: {@@ -310,7 +312,7 @@ describe("useChannelRouteModel subscription ownership", () => {verifiedEpoch: 0,},error: null,- isVerified: false, isArchived: true,+ canRead: false, isArchived: true,isError: false,}let renderer: ReturnType<typeof render>@@ -319,9 +321,9 @@ describe("useChannelRouteModel subscription ownership", () => {renderer = render(React.createElement(Harness))})- expect(mocks.clearLastChannel).toHaveBeenCalledWith("server-1")+ expect(mocks.clearLastChannel).not.toHaveBeenCalled()expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")- expect(mocks.purgeCommunityChannel).toHaveBeenCalledWith(mocks.communityDb.current, "post-1")+ expect(mocks.purgeCommunityChannel).not.toHaveBeenCalled()expect(mocks.subscribe).toHaveBeenCalledTimes(1)expect(mocks.unsubscribe).not.toHaveBeenCalled()@@ -345,7 +347,7 @@ describe("useChannelRouteModel subscription ownership", () => {verifiedEpoch: 0,},error: null,- isVerified: false, isArchived: true,+ canRead: false, isArchived: true,isError: false,}@@ -355,7 +357,7 @@ describe("useChannelRouteModel subscription ownership", () => {})expect(mocks.consumeColdEntryFailure).toHaveBeenCalledWith(- "viewer-1",+ "viewer","/c/channels/server-1/post-1",)expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex 858f1bf9a..51f3b44a3 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -1,34 +1,26 @@"use client"-import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCommunityRuntime } from "@/stores/community/runtime"-import { useCallback, useEffect, useMemo, useRef } from "react"-import { useRouter } from "next/navigation"+import { useEffect, useMemo, useRef } from "react"+import { usePathname, useRouter } from "next/navigation"import { useQueryClient } from "@tanstack/react-query"import { isForum as isForumType } from "@alook/shared"import { useServer } from "./use-servers"import { toastApiError } from "@/lib/api/client"import { ApiError } from "@/lib/errors"-import { useCommunityWsStore } from "@/stores/community/ws"-import { isDefinitiveChildMetaFailure } from "@/lib/community/eject-server"-import { clearLastChannel, getLastChannel } from "@/lib/community/last-channel"import {COMMUNITY_COLD_ENTRY_FALLBACK,consumeCommunityColdEntryFailure,} from "@/lib/community/last-community-route"import { communityWsSubscribe, communityWsUnsubscribe } from "./use-community-ws"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useChannelMetadata } from "./use-channel-metadata"import type { ChildChannelMeta } from "./use-forum-sidebar-threads"-import {- removeForumSidebarThreadExact,- removeForumSidebarUnreadChild,-} from "./use-forum-sidebar-threads"-import { useRouteChannelProjection } from "@/lib/community-db/projections"-import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"-import { purgeCommunityChannel } from "@/lib/community-db/sync"++import { useConversationReadRetry } from "./use-conversation-read-retry"type Server = ReturnType<typeof useServer>["server"]type ChannelMeta = ChildChannelMeta | null@@ -73,92 +65,52 @@ export function useChannelRouteModel(accountId: string,) {const router = useRouter()+ const pathname = usePathname()const queryClient = useQueryClient()const runtime = useCommunityRuntime()- const communityDb = useOptionalCommunityDbRegistry()const serverQuery = useServer(serverId)- const { server, isFetching: fetchingServer, refetch: refetchServer } = serverQuery- const dbChannel = useRouteChannelProjection(channelId)- const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)+ const { server } = serverQueryconst topLevelChannel = server?.categories?.flatMap((category) => category.channels).some((candidate) => candidate.id === channelId)const isChild = !!server?.categories && !topLevelChannelconst metaQuery = useChannelMetadata(serverId, channelId)- const renderableChannelMeta: ChannelMeta = useMemo(() => isChild && metaQuery.isVerified+ const renderableChannelMeta: ChannelMeta = useMemo(() => isChild && metaQuery.canRead&& metaQuery.data?.serverId === serverId && metaQuery.data.parentChannelId && metaQuery.data.parentMessageId? { ...metaQuery.data, serverId,parentChannelId: metaQuery.data.parentChannelId,parentMessageId: metaQuery.data.parentMessageId,activityAt: metaQuery.data.lastMessageAt ?? metaQuery.data.createdAt }- : null, [isChild, metaQuery.data, metaQuery.isVerified, serverId])- const retryScope = JSON.stringify([accountId, serverId, channelId, accessEpoch])- const [serverRetryAttempt, setServerRetryAttempt] = useAtom(useCreateAtom<{ scope: string } | null>(null))- const serverRetryRef = useRef<{ scope: string } | null>(null)- const retryingServer = serverRetryAttempt?.scope === retryScope- const serverError = !server?.categories && (serverQuery.isError || retryingServer)- const retryServer = useCallback(async () => {- if (!serverError || fetchingServer || serverRetryRef.current?.scope === retryScope) return- const attempt = { scope: retryScope }- serverRetryRef.current = attempt- setServerRetryAttempt(attempt)- try { await refetchServer({ cancelRefetch: false }) }- finally {- if (serverRetryRef.current === attempt) serverRetryRef.current = null- setServerRetryAttempt((current) => current === attempt ? null : current)- }- }, [retryScope, serverError, fetchingServer, refetchServer, setServerRetryAttempt])+ : null, [isChild, metaQuery.data, metaQuery.canRead, serverId])+ const serverRetry = useConversationReadRetry(serverQuery, queryClient, [accountId, serverId])+ const serverError = !server?.categories && serverRetry.failed+ const retryingServer = serverRetry.retrying+ const retryServer = serverRetry.retry+ const metadataExit = metaQuery.denied || metaQuery.isArchived+ || metaQuery.error instanceof ApiError && metaQuery.error.status === 401+ const metadataError = !metadataExit && metaQuery.status === "retryable-error"+ const retryingMetadata = metaQuery.retrying+ const retryMetadata = () => metadataError ? metaQuery.retry() : Promise.resolve()const exitScope = JSON.stringify([accountId, serverId, channelId])- const [exitedMetadata, setExitedMetadata] = useAtom(useCreateAtom<{ owner: typeof communityDb; scope: string } | null>(null))- const freshMetadata = metaQuery.isVerified && !metaQuery.data?.archived- && !isDefinitiveChildMetaFailure(metaQuery.error)- && !(metaQuery.error instanceof ApiError && metaQuery.error.status === 401)- const metadataExited = exitedMetadata?.owner === communityDb && exitedMetadata?.scope === exitScope- && !freshMetadata- useEffect(() => {- if (freshMetadata && exitedMetadata?.owner === communityDb && exitedMetadata.scope === exitScope) {- setExitedMetadata(null)- }- }, [communityDb, exitScope, exitedMetadata, freshMetadata, setExitedMetadata])- const retryAttemptRef = useRef<{ scope: string } | null>(null)- const [retryAttempt, setRetryAttempt] = useAtom(useCreateAtom<{ scope: string } | null>(null))- const retryingMetadata = retryAttempt?.scope === retryScope- const metadataExit = metadataExited || isDefinitiveChildMetaFailure(metaQuery.error)- || (metaQuery.error instanceof ApiError && metaQuery.error.status === 401)- || metaQuery.isArchived- const metadataError = !metaQuery.isVerified && !metadataExit- && (metaQuery.isError || retryingMetadata)- const { refetch: refetchMetadata, isFetching: fetchingMetadata } = metaQuery- const retryMetadata = useCallback(async () => {- if (!metadataError || fetchingMetadata || retryAttemptRef.current?.scope === retryScope) return- const attempt = { scope: retryScope }- retryAttemptRef.current = attempt- setRetryAttempt(attempt)- try {- await refetchMetadata({ cancelRefetch: false })- } finally {- if (retryAttemptRef.current === attempt) retryAttemptRef.current = null- setRetryAttempt((current) => current === attempt ? null : current)- }- }, [metadataError, fetchingMetadata, refetchMetadata, retryScope, setRetryAttempt])+ const exited = useRef<{ client: typeof queryClient; scope: string } | null>(null)const model = useMemo(() => buildChannelRouteModel(server,renderableChannelMeta,channelId,isChild- ? { channelId, settled: metaQuery.isVerified }+ ? { channelId, settled: metaQuery.canRead }: { channelId, settled: true },),- [channelId, isChild, metaQuery.isVerified, renderableChannelMeta, server],+ [channelId, isChild, metaQuery.canRead, renderableChannelMeta, server],)const routeLifecycle = !server?.categories? serverError ? "terminal-error" as const : "pending" as const- : !isChild && metaQuery.isVerified+ : !isChild && metaQuery.canRead && !metadataExit? "ready" as const- : metadataExit || (metaQuery.isError && !metaQuery.isVerified)+ : metadataExit || (metaQuery.isError && !metaQuery.canRead)? "terminal-error" as const- : model.routeHydrated && metaQuery.isVerified+ : model.routeHydrated && metaQuery.canRead && !metadataExit? "ready" as const: "pending" as constconst skeletonSubtype = routeLifecycle === "ready"@@ -167,11 +119,11 @@ export function useChannelRouteModel(: model.isForum? "forum" as const: "text" as const- : dbChannel?.type === "forum"+ : metaQuery.canonical?.type === "forum"? "forum" as const- : dbChannel?.type === "text"+ : metaQuery.canonical?.type === "text"? "text" as const- : dbChannel?.type === "thread"+ : metaQuery.canonical?.type === "thread"? "thread" as const: "unknown" as constuseEffect(() => {@@ -183,41 +135,22 @@ export function useChannelRouteModel(return () => communityWsUnsubscribe(runtime)}, [channelId, runtime])useEffect(() => {- const denied = isDefinitiveChildMetaFailure(metaQuery.error)- if (!isChild && !denied && !metaQuery.isArchived) {- return- }- if (denied || metaQuery.isArchived) {- if (metadataExited) return- setExitedMetadata({ owner: communityDb, scope: exitScope })- const store = runtime.ui.get()- const routeStillCurrent = store.currentChannelId === channelId- if (communityDb) purgeCommunityChannel(communityDb, channelId)- if (!runtime.ws.actions.isChannelAccessRevoked(channelId, serverId)) runtime.ws.actions.revokeChannelAccess(serverId, channelId)- removeForumSidebarUnreadChild(queryClient, serverId, channelId)- removeForumSidebarThreadExact(queryClient, serverId, channelId)- const lastChannel = getLastChannel(serverId)- if (lastChannel === channelId) {- clearLastChannel(serverId)- }- // A top-level delete clears the live pointer and starts its survivor- // navigation before this fallback metadata request can settle. Do not- // let the late 403/404 supersede that newer navigation with the root.- if (!routeStillCurrent || runtime.ws.get().revokedServerIds.has(serverId)) return- const destination = consumeCommunityColdEntryFailure(- accountId,- `/c/channels/${serverParam}/${channelId}`,- )- ? COMMUNITY_COLD_ENTRY_FALLBACK- : `/c/channels/${serverParam}`- router.replace(destination)- } else if (metaQuery.error) {- toastApiError(metaQuery.error, "Failed to load channel")- }- }, [accountId, channelId, communityDb, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, metaQuery.isArchived, queryClient, renderableChannelMeta, router, runtime.ui, runtime.ws, runtime.ws.actions, serverId, serverParam, metadataExited, exitScope, setExitedMetadata])+ if (metaQuery.canRead) exited.current = null+ if (metaQuery.denied || metaQuery.isArchived) {+ if (exited.current?.client === queryClient && exited.current.scope === exitScope) return+ const registry = getCommunityDbRegistry(queryClient)+ if (pathname !== `/c/channels/${serverParam}/${channelId}` || window.location.pathname !== pathname || registry?.accountId !== accountId+ || registry.runtime !== runtime || !runtime.lifecycle.get().active || runtime.ws.get().revokedServerIds.has(serverId)) return+ exited.current = { client: queryClient, scope: exitScope }+ runtime.ui.actions.setCurrentChannelId(null)+ router.replace(consumeCommunityColdEntryFailure(accountId, `/c/channels/${serverParam}/${channelId}`)+ ? COMMUNITY_COLD_ENTRY_FALLBACK : `/c/channels/${serverParam}`)+ } else if (metadataError && metaQuery.error) toastApiError(metaQuery.error, "Failed to load channel")+ }, [accountId, channelId, exitScope, metaQuery.canRead, metaQuery.denied, metaQuery.error, metaQuery.isArchived, metadataError, pathname, queryClient, router, runtime, serverId, serverParam])+return {...model,- routeHydrated: model.routeHydrated && metaQuery.isVerified,+ routeHydrated: model.routeHydrated && metaQuery.canRead && !metadataExit,routeLifecycle,skeletonSubtype,metadataError,diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.tsindex 13c2f98da..e62f16276 100644--- a/src/web/src/hooks/community/use-channel-watermark.ts+++ b/src/web/src/hooks/community/use-channel-watermark.ts@@ -3,34 +3,6 @@import type { Msg } from "@/lib/community/models/message"import { useTimelineReadObserver } from "./use-read-observer"-/* istanbul ignore next -- retained Chromium covers this React hook adapter */-export function useChannelWatermark({- channelId,- messages,- scrollRootEl,- snapshotStatus,- feedStatus,- tailAttached,- confirmedSeq,- catchUp,-}: {- channelId: string | null | undefined- messages: Msg[]- scrollRootEl: HTMLElement | null- snapshotStatus: "pending" | "ready" | "error"- feedStatus: "pending" | "ready" | "error"- tailAttached: boolean- confirmedSeq: number- catchUp: () => Promise<unknown>-}) {- useTimelineReadObserver({- channelId,- messages,- scrollRootEl,- snapshotStatus,- feedStatus,- tailAttached,- confirmedSeq,- catchUp,- })+export function useChannelWatermark(options: Omit<Parameters<typeof useTimelineReadObserver>[0], "messages"> & { messages: Msg[] }) {+ useTimelineReadObserver(options)}diff --git a/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts b/src/web/src/hooks/community/use-child-channel-meta.dom.test.tsindex 975b87483..0e3507ce5 100644--- a/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts+++ b/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts@@ -4,8 +4,7 @@ import { createCommunityDbRegistry } from "@/lib/community-db/collections"import { channelSchema } from "@/lib/community-db/schema"import { createElement, type PropsWithChildren } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"-import { renderHook, waitFor } from "@/test/react-dom-harness"-import type { ChildChannelMeta } from "./use-forum-sidebar-threads"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { communityKeys } from "@/lib/query-keys"import { ApiError } from "@/lib/errors"@@ -14,27 +13,23 @@ vi.mock("@/lib/api/client", () => ({apiFetch: (...args: unknown[]) => apiFetchMock(...args),}))-import {- pickRenderableChildMeta,- sameChildChannelMeta,- updateTrustedChildMeta,- useChildChannelMeta,-} from "./use-child-channel-meta"--const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({- id: "post-1",- serverId: "server-1",- name: "post",- type: "thread",- parentChannelId: "forum-1",- parentMessageId: "opener-1",- creatorId: "user-1",- archived: false,- activityAt: "2026-08-09T00:00:00.000Z",- verifiedEpoch: 2,- ...overrides,+import { useChannelMetadata } from "./use-channel-metadata"++const meta = (overrides: Partial<ReturnType<typeof channelSchema.parse>> = {}) => channelSchema.parse({+ id: "post-1", serverId: "server-1", name: "post", type: "thread",+ parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: "user-1",+ archived: false, lastMessageAt: "2026-08-09T00:00:00.000Z",+ position: 0, muted: false, unread: false, tags: [], pending: false, ...overrides,})+async function fixture() {+ const { client } = await createCommunityQueryOwner()+ const registry = createCommunityDbRegistry(client, "viewer")+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client }, children)+ const rendered = renderHook(() => useChannelMetadata("server-1", "post-1"), { wrapper })+ return { client, registry, rendered }+}+beforeEach(() => {apiFetchMock.mockReset()apiFetchMock.mockResolvedValue({@@ -53,30 +48,56 @@ beforeEach(() => {})describe("child channel metadata stale rendering", () => {- it("compares every durable child metadata field", () => {- const left = meta()- expect(sameChildChannelMeta(left, { ...left })).toBe(true)- expect(sameChildChannelMeta(left, { ...left, verifiedEpoch: 3 })).toBe(false)- const trusted = { channelId: left.id, meta: left }- expect(updateTrustedChildMeta(trusted, left.id, { ...left })).toBe(trusted)+ it("publishes every changed durable child metadata field through the common owner", async () => {+ const { client, rendered } = await fixture()+ await waitFor(() => expect(rendered.result.current.canRead).toBe(true))+ const changed = { name: "updated", parentChannelId: "forum-2", parentMessageId: "opener-2",+ creatorId: "user-2", lastMessageAt: "2026-08-10T00:00:00.000Z" }+ const response = await apiFetchMock.mock.results[0].value+ apiFetchMock.mockResolvedValue({ ...response, ...changed })+ await act(async () => client.refetchQueries({ queryKey: communityKeys.channelMeta("server-1", "post-1"), exact: true }))+ await waitFor(() => expect(rendered.result.current.data).toMatchObject(changed))+ expect(rendered.result.current.canRead).toBe(true)+ expect(rendered.result.current.data).toMatchObject({ id: "post-1", serverId: "server-1", type: "thread", archived: false })+ rendered.unmount()})- it("keeps a previously authorized snapshot renderable across a WS epoch", () => {- const trusted = meta({ verifiedEpoch: 2 })- expect(pickRenderableChildMeta(trusted, trusted, 3)).toBe(trusted)+ it("keeps previously authorized child metadata readable across transport reconnect", async () => {+ const { registry, rendered } = await fixture()+ await waitFor(() => expect(rendered.result.current.canRead).toBe(true))+ const trusted = rendered.result.current.data+ act(() => registry.runtime.ws.actions.markAccessDisconnected())+ expect(rendered.result.current.canRead).toBe(true)+ expect(rendered.result.current.data).toBe(trusted)+ expect(apiFetchMock).toHaveBeenCalledOnce()+ rendered.unmount()})- it("does not render an old first response that was never trusted", () => {- expect(pickRenderableChildMeta(meta({ verifiedEpoch: 2 }), undefined, 3)).toBeUndefined()+ it("does not publish an old first response that was never qualified", async () => {+ let resolve!: (value: unknown) => void+ apiFetchMock.mockReturnValue(new Promise((done) => { resolve = done }))+ const { client, registry, rendered } = await fixture()+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())+ act(() => registry.runtime.ws.setState((state) => ({ ...state, accessEpoch: state.accessEpoch + 1 })))+ await act(async () => resolve(meta()))+ await waitFor(() => expect(rendered.result.current.error).toMatchObject({ name: "AbortError" }))+ expect(rendered.result.current.data).toBeUndefined()+ expect(rendered.result.current.canRead).toBe(false)+ expect(registry.collections.channels.get("post-1")).toBeUndefined()+ expect(client.getQueryData(communityKeys.channelMeta("server-1", "post-1"))).toBeUndefined()+ rendered.unmount()})- it("authoritative current-epoch archive removes a previously trusted snapshot", () => {- const trusted = meta({ verifiedEpoch: 2 })- expect(pickRenderableChildMeta(- meta({ verifiedEpoch: 3, archived: true }),- trusted,- 3,- )).toBeUndefined()+ it("authoritative archive retires a previously qualified child snapshot", async () => {+ const { client, registry, rendered } = await fixture()+ await waitFor(() => expect(rendered.result.current.canRead).toBe(true))+ apiFetchMock.mockResolvedValue({ ...meta(), archived: true })+ await act(async () => client.refetchQueries({ queryKey: communityKeys.channelMeta("server-1", "post-1"), exact: true }))+ await waitFor(() => expect(rendered.result.current.denied).toBe(true))+ expect(rendered.result.current.data).toBeUndefined()+ expect(rendered.result.current.canRead).toBe(false)+ expect(registry.collections.channels.get("post-1")).toBeUndefined()+ rendered.unmount()})it("starts exact metadata loading without waiting for the forum sidebar", async () => {@@ -86,7 +107,7 @@ describe("child channel metadata stale rendering", () => {{ client: queryClient },children,)- renderHook(() => useChildChannelMeta("server-1", "post-1", true), { wrapper })+ renderHook(() => useChannelMetadata("server-1", "post-1"), { wrapper })await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())expect(apiFetchMock).toHaveBeenCalledWith(@@ -108,13 +129,13 @@ describe("child channel metadata stale rendering", () => {{ client: queryClient },children,)- const cached = meta({ verifiedEpoch: createCommunityDbRegistry(queryClient, "viewer").runtime.ws.get().accessEpoch })+ const cached = meta()createCommunityDbRegistry(queryClient, "viewer").collections.channels.utils.writeUpsert(channelSchema.parse({...cached, position: 0, muted: false, unread: false, tags: [], pending: false,- lastMessageAt: cached.activityAt,+ lastMessageAt: cached.lastMessageAt,}))const rendered = renderHook(- () => useChildChannelMeta("server-1", "post-1", true, cached),+ () => useChannelMetadata("server-1", "post-1"),{ wrapper },)@@ -149,12 +170,12 @@ describe("child channel metadata stale rendering", () => {)const rendered = renderHook(- () => useChildChannelMeta("server-1", "post-1", true),+ () => useChannelMetadata("server-1", "post-1"),{ wrapper },)expect(rendered.result.current).toMatchObject({- data: { creatorId: null, activityAt: "" },+ data: { creatorId: null, lastMessageAt: null },isVerified: false,isPlaceholderData: false,})@@ -172,7 +193,7 @@ describe("child channel metadata stale rendering", () => {children,)const rendered = renderHook(- () => useChildChannelMeta("server-1", "post-1", true),+ () => useChannelMetadata("server-1", "post-1"),{ wrapper },)@@ -190,7 +211,7 @@ describe("child channel metadata stale rendering", () => {children,)const rendered = renderHook(- () => useChildChannelMeta("server-1", "post-1", true),+ () => useChannelMetadata("server-1", "post-1"),{ wrapper },)@@ -198,7 +219,7 @@ describe("child channel metadata stale rendering", () => {expect(apiFetchMock).toHaveBeenCalledTimes(2)})- it("preserves the trusted object when an exact refetch returns identical metadata", async () => {+ it("preserves the trusted fields and native Query when an exact refetch returns identical metadata", async () => {const { client: queryClient } = await createCommunityQueryOwner()queryClient.setDefaultOptions({ queries: { retry: false, structuralSharing: false } })const wrapper = ({ children }: PropsWithChildren) => createElement(@@ -207,17 +228,21 @@ describe("child channel metadata stale rendering", () => {children,)const rendered = renderHook(- () => useChildChannelMeta("server-1", "post-1", true),+ () => useChannelMetadata("server-1", "post-1"),{ wrapper },)await waitFor(() => expect(rendered.result.current.isVerified).toBe(true))const trusted = rendered.result.current.data+ const resource = queryClient.getQueryCache().find({ queryKey: communityKeys.channelMeta("server-1", "post-1"), exact: true })await queryClient.refetchQueries({queryKey: communityKeys.channelMeta("server-1", "post-1"),exact: true,})await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))- expect(rendered.result.current.data).toStrictEqual(trusted)+ expect({ ...rendered.result.current.data, identityProof: undefined, readProof: undefined })+ .toStrictEqual({ ...trusted, identityProof: undefined, readProof: undefined })+ expect(rendered.result.current.canRead).toBe(true)+ expect(queryClient.getQueryCache().find({ queryKey: communityKeys.channelMeta("server-1", "post-1"), exact: true })).toBe(resource)})})diff --git a/src/web/src/hooks/community/use-child-channel-meta.ts b/src/web/src/hooks/community/use-child-channel-meta.tsdeleted file mode 100644index 988b2ff85..000000000--- a/src/web/src/hooks/community/use-child-channel-meta.ts+++ /dev/null@@ -1,68 +0,0 @@-"use client"--import type { ChannelMetadata } from "./channel-metadata"-import { useChannelMetadata } from "./use-channel-metadata"-import type { ChildChannelMeta } from "./use-forum-sidebar-threads"--function projectChildMeta(payload: ChannelMetadata, verifiedEpoch: number): ChildChannelMeta {- if (!payload.serverId || !payload.parentChannelId || !payload.parentMessageId) {- throw new Error("invalid child channel metadata")- }- return {- id: payload.id,- serverId: payload.serverId,- name: payload.name ?? "",- type: payload.type,- parentChannelId: payload.parentChannelId,- parentMessageId: payload.parentMessageId,- creatorId: payload.creatorId,- archived: payload.archived === true || payload.archived === 1,- activityAt: payload.lastMessageAt ?? payload.createdAt,- verifiedEpoch,- }-}--export function sameChildChannelMeta(left: ChildChannelMeta, right: ChildChannelMeta): boolean {- return left.id === right.id &&- left.serverId === right.serverId &&- left.name === right.name &&- left.type === right.type &&- left.parentChannelId === right.parentChannelId &&- left.parentMessageId === right.parentMessageId &&- (left.creatorId ?? null) === (right.creatorId ?? null) &&- left.archived === right.archived &&- left.activityAt === right.activityAt &&- left.verifiedEpoch === right.verifiedEpoch-}--type TrustedChildMeta = { channelId: string; meta: ChildChannelMeta } | null--export function updateTrustedChildMeta(- current: TrustedChildMeta,- channelId: string,- data: ChildChannelMeta,-): TrustedChildMeta {- if (data.archived) return current === null ? current : null- if (- current?.channelId === channelId- && sameChildChannelMeta(current.meta, data)- ) return current- return { channelId, meta: data }-}--export function pickRenderableChildMeta(- meta: ChildChannelMeta | undefined,- trusted: ChildChannelMeta | undefined,- accessEpoch: number,-): ChildChannelMeta | undefined {- if (meta?.verifiedEpoch === accessEpoch) return meta.archived ? undefined : meta- if (trusted?.id === meta?.id || !meta) return trusted?.archived ? undefined : trusted- return undefined-}--export function useChildChannelMeta(serverId: string, channelId: string, enabled: boolean, _placeholderData?: ChildChannelMeta) {- const query = useChannelMetadata(serverId, enabled ? channelId : undefined)- const data = query.data?.type === "thread" && query.data.parentChannelId && query.data.parentMessageId && !query.data.archived- ? projectChildMeta(query.data, query.data.verifiedEpoch) : undefined- return { ...query, data, isVerified: query.isVerified && !!data }-}diff --git a/src/web/src/hooks/community/use-community-command-mutation.ts b/src/web/src/hooks/community/use-community-command-mutation.tsindex f80958806..eb3ba10ae 100644--- a/src/web/src/hooks/community/use-community-command-mutation.ts+++ b/src/web/src/hooks/community/use-community-command-mutation.ts@@ -1,7 +1,8 @@"use client"-import { useMutation, type Query, type UseMutationOptions, type MutateOptions } from "@tanstack/react-query"+import { useMutation, type Query, type UseMutationOptions } from "@tanstack/react-query"import { useCallback } from "react"+import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"import type { useCommunityMutationOrigin } from "./community-origin"type Origin = ReturnType<typeof useCommunityMutationOrigin>@@ -22,13 +23,6 @@ export function useCommunityCommandMutation<Data = unknown, Error = globalThis.Eorigin.assert(original)return { ...input, original, resources: origin.registry!.queryClient.getQueryCache().findAll() }}, [origin])- const qualify = useCallback((callbacks?: MutateOptions<Data, Error, Input, Result>): MutateOptions<Data, Error, CommunityCommandArgs<Input>, Result> | undefined => callbacks && ({- onSuccess: (data, args, result, context) => { try { if (assertSuccess) assertSuccess(args); else origin.assert(args.original) } catch { return } callbacks.onSuccess?.(data, communityCommandInput(args), result, context) },- onError: (error, args, result, context) => { try { origin.assert(args.original) } catch { return } callbacks.onError?.(error, communityCommandInput(args), result, context) },- onSettled: (data, error, args, result, context) => { try { if (error === null && assertSuccess) assertSuccess(args); else origin.assert(args.original) } catch { return } callbacks.onSettled?.(data, error, communityCommandInput(args), result, context) },- }), [origin, assertSuccess])- const nativeMutate = native.mutate, nativeMutateAsync = native.mutateAsync- const mutate = useCallback((input: Input, callbacks?: MutateOptions<Data, Error, Input, Result>) => nativeMutate(capture(input), qualify(callbacks)), [nativeMutate, capture, qualify])- const mutateAsync = useCallback((input: Input, callbacks?: MutateOptions<Data, Error, Input, Result>) => nativeMutateAsync(capture(input), qualify(callbacks)), [nativeMutateAsync, capture, qualify])- return { ...native, mutate, mutateAsync }+ const assertCurrent = useCallback((args: CommunityCommandArgs<Input>) => origin.assert(args.original), [origin])+ return useNativeMutationFacade(native, capture, assertCurrent, { projectInput: communityCommandInput<Input>, assertSuccess })}diff --git a/src/web/src/hooks/community/use-community-view-source.ts b/src/web/src/hooks/community/use-community-view-source.tsindex 6edf183eb..09605ee19 100644--- a/src/web/src/hooks/community/use-community-view-source.ts+++ b/src/web/src/hooks/community/use-community-view-source.ts@@ -17,12 +17,13 @@ export function useCommunityViewSource(identity: string, enabled = true) {const capture = () => {const token = origin.begin().tokenconst generation = view.get().generation- const assert = () => {- origin.assert(token)+ const assertOwner = () => {+ origin.assertOwner(token)const state = view.get()if (!state.active || state.generation !== generation) throw new DOMException("Retired community view", "AbortError")}- return Object.assign(assert, { signal: view.get().controller.signal })+ const assert = () => { origin.assert(token); assertOwner() }+ return Object.assign(assert, { signal: view.get().controller.signal, assertOwner })}const retire = () => {const controller = view.get().controllerdiff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 0a071c8e7..9805df202 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -1,4 +1,5 @@"use client"+import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"import { useCommunityRuntime, type CommunityRuntime } from "@/stores/community/runtime"@@ -35,7 +36,7 @@ import type {import { flushPendingReadIntents } from "@/hooks/community/read-coordinator"import {decodeCommunityBrowserEvent,- decodeCommunityBrowserEventBatch,+ admitCommunityBrowserEventBatch,isCommunityBrowserEventBatchCandidate,isCommunityEventType,TYPING_INDICATOR_THROTTLE_MS,@@ -348,7 +349,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {}, [runInboxGeneration])const handleMessage = useCallback(- (msg: { type: string;[key: string]: unknown }) => {+ async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void) => {if (!msg.type.startsWith("community:")) returnif (!runtime.lifecycle.get().active) returnconst communityStore = runtime.ui@@ -396,7 +397,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {}if (isCommunityBrowserEventBatchCandidate(msg)) {- const decoded = decodeCommunityBrowserEventBatch(msg)+ const token = captureCommunityLiveSnapshotToken(queryClient)+ const admission = admitCommunityBrowserEventBatch(msg)+ const decoded = admission instanceof Promise ? await admission : admission+ try { assertAdmissionCurrent?.(); assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined) } catch { return }+ if (!runtime.lifecycle.get().active) returnif (!decoded.ok) {const reason = decoded.reason === "oversized" ? "oversized" : "invalid-payload"const metadata = {diff --git a/src/web/src/hooks/community/use-conversation-read-retry.ts b/src/web/src/hooks/community/use-conversation-read-retry.tsnew file mode 100644index 000000000..ac5f5c2aa--- /dev/null+++ b/src/web/src/hooks/community/use-conversation-read-retry.ts@@ -0,0 +1,27 @@+"use client"++import { useCallback } from "react"+import { useCreateAtom, useAtom } from "@tanstack/react-store"+import { hashKey, type QueryKey, type UseQueryResult } from "@tanstack/react-query"+import { isConversationAccessError } from "@/lib/community/conversation-read"++export function useConversationReadRetry<T>(+ query: Pick<UseQueryResult<T>, "isError" | "isFetching" | "refetch"> & Partial<Pick<UseQueryResult<T>, "error">>,+ owner: object,+ scope: QueryKey,+) {+ const identity = hashKey(scope)+ const state = useCreateAtom<{ owner: object; identity: string; pending: Promise<void> } | null>(null)+ const [operation] = useAtom(state)+ const retrying = operation?.owner === owner && operation.identity === identity+ const { isError, isFetching, error, refetch } = query+ const retry = useCallback(() => {+ const active = state.get()+ if (active?.owner === owner && active.identity === identity) return Promise.resolve()+ if (!isError || isFetching || isConversationAccessError(error)) return Promise.resolve()+ const pending = refetch({ cancelRefetch: false }).then(() => {}).finally(() => state.set((current) => current?.pending === pending ? null : current))+ state.set({ owner, identity, pending })+ return pending+ }, [isError, isFetching, error, refetch, state, owner, identity])+ return { retry, retrying, failed: isError || retrying }+}diff --git a/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts b/src/web/src/hooks/community/use-dm-message-sender.dom.test.tsindex 55d854090..ac75a0f65 100644--- a/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts@@ -1,9 +1,10 @@+import { canonicalMessageReader } from "@/test/community-query-owner"import { createElement, type PropsWithChildren } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityTestProvider } from "@/test/community-owner-fixture"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"import { materializeMessageStream } from "@/lib/community/message-stream"import { MESSAGE_PREVIEW_LENGTH } from "@alook/shared"import { useDmMessageSender, type AcceptDmMessageArgs, type DmSendReceipt } from "./use-dm-message-sender"@@ -44,7 +45,7 @@ async function setup() {await act(async () => { result = await receipt.committed })return result}- const overlay = () => getMessageOverlay(owner.client, scope)+ const overlay = () => getMessageStreamState(owner.client, scope)return { ...owner, view, accept, retry, settle, overlay }}@@ -117,7 +118,7 @@ describe("Native DM sender", () => {const owner = await setup(), file = new File(["x"], "x.txt", { type: "text/plain" })const receipt = owner.accept({ content: "", replyTo: { id: "prior", authorName: "Peer Name", text: "quoted" }, attachments: [{ file, previewObjectUrl: "blob:x" }] })expect(await owner.settle(receipt)).toMatchObject({ ok: true, message: { id: "server_file", seq: 9 } })- expect(materializeMessageStream([], owner.overlay()).find(({ id }) => id === "server_file")?.content).toBe("@Peer Name\n")+ expect(materializeMessageStream([], owner.overlay(), canonicalMessageReader(owner.client)).find(({ id }) => id === "server_file")?.content).toBe("@Peer Name\n")expect(mocks.post).toHaveBeenCalledExactlyOnceWith({ content: "@Peer Name\n", replyToId: "prior", attachments: ["att_x"], nonce: "fresh_nonce" })})@@ -139,9 +140,9 @@ describe("Native DM sender", () => {act(() => owner.runtime.ui.actions.setCurrentChannelId("other_dm"))const receipt = owner.accept({ content: "out of view" })expect(await owner.settle(receipt)).toMatchObject({ ok: true, message: { id: "server_1", seq: 11 } })- expect(materializeMessageStream([], owner.overlay()).map(({ id }) => id)).toEqual(["server_1"])+ expect(materializeMessageStream([], owner.overlay(), canonicalMessageReader(owner.client)).map(({ id }) => id)).toEqual(["server_1"])const base = [{ id: "server_1", seq: 11, clientNonce: "fresh_nonce", type: "chat" as const, authorId: "u_me", authorName: "Me", content: "out of view" }]act(() => owner.runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: base }))- expect(materializeMessageStream(base, owner.overlay()).map(({ id }) => id)).toEqual(["server_1"])+ expect(materializeMessageStream(base, owner.overlay(), canonicalMessageReader(owner.client)).map(({ id }) => id)).toEqual(["server_1"])})})diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.tsindex 1f3d265bf..874514bf2 100644--- a/src/web/src/hooks/community/use-dm-message-sender.ts+++ b/src/web/src/hooks/community/use-dm-message-sender.ts@@ -5,41 +5,25 @@ import { useCommunityRuntime } from "@/stores/community/runtime"import { useCallback } from "react"import { useCommunityViewSource } from "./use-community-view-source"import { useCommunityMutationOrigin } from "./community-origin"-import type { Msg } from "@/lib/community/models/message"+import type { SendMessageArgs, SendMessageResult } from "./mutations/messages"import type { SendAttachment } from "@/lib/community/models/message"-import { toastApiError } from "@/lib/api/client"-import { toOptimisticReplyPreview } from "@/lib/community/reply-preview"-import { canonicalizeReplyContent } from "@/lib/community/reply-content"+import { acceptMessageIntent, prepareMessageIntent, messageSendError } from "@/lib/community/message-send-intent"import {- sendNonce,- tempMessageId,- toAttachmentVm,useSendDmMessage,useUploadFile,- zipUploadResultsWithDimensions,- type UploadedAttachment,} from "@/hooks/community/mutations"export type DmSendCommit =- | { ok: true; message: { id: string; seq: number } }+ | { ok: true; message: Pick<SendMessageResult["message"], "id" | "seq"> }| { ok: false; error: Error }export type DmSendReceipt =| { accepted: false }| { accepted: true; nonce: string; committed: Promise<DmSendCommit> }-export type AcceptDmMessageArgs = {- assertActive?: (() => void) & { signal: AbortSignal }+export type AcceptDmMessageArgs = Pick<SendMessageArgs, "assertActive" | "content" | "replyTo" | "author" | "nonce"> & {dmId: string- content: string- replyTo?: Msg["replyTo"]attachments?: SendAttachment[]- author: { id: string; name: string; avatar: string }- nonce?: string-}--function asError(error: unknown): Error {- return error instanceof Error ? error : new Error("Failed to send message")}export function useDmMessageSender() {@@ -56,69 +40,12 @@ export function useDmMessageSender() {): Promise<DmSendCommit> => {const original = origin.begin().tokenconst assert = () => { origin.assert(original); assertActive?.() }- try { assert() } catch (error) { return { ok: false, error: asError(error) } }const scope = { kind: "dm" as const, id: dmId }- const payload = communityRuntime.messageStream.actions.getRetryPayload(scope, nonce)- if (!payload) {- return { ok: false, error: new Error("Message intent is no longer available") }- }-- let uploadedAttachments: UploadedAttachment[] | undefined- if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {- const projected = payload.message.attachments- if (projected?.length === payload.localUploads.length) {- uploadedAttachments = projected.map((attachment, index) => {- const local = payload.localUploads[index]- return {- id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),- filename: local.file.name,- contentType: local.file.type,- size: local.file.size,- ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined- ? { hasThumbnail: true }- : {}),- width: local.width,- height: local.height,- }- })- }- }-- if (payload.localUploads.length > 0 && !uploadedAttachments) {- const results = await Promise.all(- payload.localUploads.map((upload) =>- uploadFileAsync({- assertActive,- target: { dmId },- file: upload.file,- thumbnailBlob: upload.thumbnailBlob,- width: upload.width,- height: upload.height,- }).catch((error) => {- toastApiError(error, "Failed to attach file", assert)- return null- }),- ),- )- if (results.some((result) => result === null)) {- try { origin.assert(original) } catch (error) { return { ok: false, error: asError(error) } }- communityRuntime.messageStream.actions.dispatch(scope, { type: "uploadFailed", nonce })- return { ok: false, error: new Error("Failed to attach file") }- }- uploadedAttachments = zipUploadResultsWithDimensions(results, [...payload.localUploads])- try { assert() } catch (error) {- try { origin.assert(original); communityRuntime.messageStream.actions.dispatch(scope, { type: "uploadFailed", nonce }) } catch {}- return { ok: false, error: asError(error) }- }- communityRuntime.messageStream.actions.dispatch(scope, {- type: "uploadSettled",- nonce,- attachments: uploadedAttachments.map((attachment) =>- toAttachmentVm(dmId, attachment)),- })- }-try {+ const prepared = await prepareMessageIntent({ runtime: communityRuntime, scope, nonce,+ assertOwner: () => origin.assert(original), assertActive, uploadFileAsync, target: { dmId } })+ if (!prepared.ok) return prepared+ const { payload, attachments: uploadedAttachments } = preparedassert()const result = await sendDmMessageAsync({dmId,@@ -130,54 +57,21 @@ export function useDmMessageSender() {})return { ok: true, message: result.message }} catch (error) {- return { ok: false, error: asError(error) }+ return { ok: false, error: messageSendError(error) }}}, [communityRuntime, origin, sendDmMessageAsync, uploadFileAsync])const accept = useCallback((args: AcceptDmMessageArgs): DmSendReceipt => {const assertActive = args.assertActive ?? source.capture()assertActive()- if (!args.content && !args.attachments?.length) return { accepted: false }- const content = canonicalizeReplyContent(args.content, args.replyTo)- const nonce = args.nonce ?? sendNonce()- const createdPreviewUrls: string[] = []- const accepted = communityRuntime.messageStream.actions.accept(- { kind: "dm", id: args.dmId },- {- nonce,- tempId: tempMessageId(),- message: {- type: "chat",- authorId: args.author.id,- authorName: args.author.name,- authorAvatar: args.author.avatar,- content,- createdAt: new Date().toISOString(),- ...(args.replyTo ? { replyTo: toOptimisticReplyPreview(args.replyTo) } : {}),- },- localUploads: args.attachments?.map((attachment) => {- const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)- if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)- return {- file: attachment.file,- thumbnailBlob: attachment.thumbnailBlob,- previewObjectUrl,- width: attachment.width,- height: attachment.height,- }- }) ?? [],- },- )- if (!accepted) {- for (const url of createdPreviewUrls) URL.revokeObjectURL(url)- return { accepted: false }- }+ const nonce = acceptMessageIntent(communityRuntime, { kind: "dm", id: args.dmId }, args)+ if (nonce === undefined) return { accepted: false }return {accepted: true,nonce,committed: runAcceptedIntent(args.dmId, nonce, assertActive),}- }, [communityRuntime.messageStream.actions, runAcceptedIntent, source])+ }, [communityRuntime, runAcceptedIntent, source])const retry = useCallback((dmId: string, nonce: string): Promise<DmSendCommit> => {const assertActive = source.capture()@@ -187,7 +81,7 @@ export function useDmMessageSender() {{ type: "retry", nonce },)return runAcceptedIntent(dmId, nonce, assertActive)- }, [communityRuntime.messageStream.actions, runAcceptedIntent, source])+ }, [communityRuntime, runAcceptedIntent, source])return { accept, retry }}diff --git a/src/web/src/hooks/community/use-dm-read-state.dom.test.ts b/src/web/src/hooks/community/use-dm-read-state.dom.test.tsindex 5fea8d647..e56b5ce7f 100644--- a/src/web/src/hooks/community/use-dm-read-state.dom.test.ts+++ b/src/web/src/hooks/community/use-dm-read-state.dom.test.ts@@ -5,7 +5,9 @@ import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityDbProvider } from "@/lib/community-db/projections"import { communityKeys } from "@/lib/query-keys"-import { useDmReadStateSnapshot, type DmReadStateSnapshot } from "./use-dm-read-state"+import { ingestReadStateSnapshot } from "@/lib/community-db/sync"+import { useDmReadStateSnapshot } from "./use-dm-read-state"+import type { ChannelReadStateSnapshot } from "./use-channel-read-state"const api = vi.fn()vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => api(...args) }))@@ -25,12 +27,12 @@ afterEach(async () => {})})function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }-function mount(id = "dm_1", canonical?: DmReadStateSnapshot) {- return renderHook(({ id, canonical }) => useDmReadStateSnapshot(id, canonical), { wrapper: Owner, initialProps: { id, canonical } })+function mount(id = "dm_1") {+ return renderHook(({ id }) => useDmReadStateSnapshot(id), { wrapper: Owner, initialProps: { id } })}function held() {- let resolve!: (value: DmReadStateSnapshot) => void- api.mockReturnValueOnce(new Promise<DmReadStateSnapshot>((done) => { resolve = done }))+ let resolve!: (value: ChannelReadStateSnapshot) => void+ api.mockReturnValueOnce(new Promise<ChannelReadStateSnapshot>((done) => { resolve = done }))return { resolve }}@@ -54,12 +56,28 @@ describe("native DM read-state snapshot", () => {await act(async () => { pending.resolve(fresh) })await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))})- it("freezes canonical data immediately while the mount request revalidates", async () => {- const pending = held(), rendered = mount("dm_1", original)- expect(rendered.result.current).toMatchObject({ snapshot: original, isFetching: false })+ it("withholds a stale canonical pointer until the current mount read succeeds", async () => {+ ingestReadStateSnapshot(registry, { revision: 1, readStates: [{ channelId: "dm_1", ...empty }] })+ const pending = held(), rendered = mount("dm_1")+ await waitFor(() => expect(api).toHaveBeenCalledOnce())+ expect(rendered.result.current).toMatchObject({ snapshot: null, isFetching: true })await act(async () => { pending.resolve(fresh) })- rendered.rerender({ id: "dm_1", canonical: undefined })- expect(rendered.result.current.snapshot).toEqual(original)+ await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))+ await act(async () => { ingestReadStateSnapshot(registry, { revision: 2, readStates: [{ channelId: "dm_1", ...original }] }) })+ rendered.rerender({ id: "dm_1" })+ expect(rendered.result.current.snapshot).toEqual(fresh)+ })+ it("does not latch retained query data when the new mount read fails", async () => {+ client.setQueryData(communityKeys.dmReadStateSnapshot("dm_1"), original)+ api.mockRejectedValue(new Error("fresh mount unavailable"))+ const rendered = mount()+ await waitFor(() => expect(api).toHaveBeenCalledTimes(2))+ await waitFor(() => expect(rendered.result.current.isFetching).toBe(false))+ expect(rendered.result.current.error).toBeInstanceOf(Error)+ expect(rendered.result.current.snapshot).toBeNull()+ api.mockResolvedValueOnce(fresh)+ act(() => rendered.result.current.retry())+ await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))})it("keeps the first settled snapshot through a later refetch", async () => {api.mockResolvedValueOnce(original)@@ -75,7 +93,7 @@ describe("native DM read-state snapshot", () => {const rendered = mount()await waitFor(() => expect(rendered.result.current.snapshot).toEqual(original))const pending = held()- rendered.rerender({ id: "dm_2", canonical: undefined })+ rendered.rerender({ id: "dm_2" })expect(rendered.result.current.snapshot).toBeNull()await act(async () => { pending.resolve(fresh) })await waitFor(() => expect(rendered.result.current.snapshot).toEqual(fresh))diff --git a/src/web/src/hooks/community/use-dm-read-state.ts b/src/web/src/hooks/community/use-dm-read-state.tsindex e3a8be217..b16be812c 100644--- a/src/web/src/hooks/community/use-dm-read-state.ts+++ b/src/web/src/hooks/community/use-dm-read-state.ts@@ -2,37 +2,8 @@import { useChannelReadStateSnapshot } from "./use-channel-read-state"-/**- * The DM read-state snapshot returned by- * `GET /api/community/channels/:id/read-state` (a DM is a channel row; the- * whole DM surface reads through the one canonical door). Fields default to- * `null` / `0`- * when the viewer has never opened this DM.- */-export type DmReadStateSnapshot = {- lastReadMessageId: string | null- lastReadAt: string | null- // Numeric equivalent of `lastReadMessageId` — the seq of the row that- // pointer refers to. Server returns `0` when the viewer has never read- // this DM; consumers subtract from `latestSeq` for the unread-count pill- // without walking loaded rows.- lastReadSeq: number-}--/**- * Once-per-mount snapshot of the viewer's read pointer for a DM. The- * channel-side sibling is `useChannelReadStateSnapshot` — this hook mirrors- * it exactly, because the invariants are shared: fix a bug on one side and- * the same fix must reach the other, or the divider anchors diverge across- * channels vs DMs and users lose their place.- *- * See `use-channel-read-state.ts` for the full doc — same freeze rule,- * same `staleTime: Infinity` + `gcTime: 0` combo, same channelId → dmId- * substitution.- */export function useDmReadStateSnapshot(dmId: string | null | undefined,- canonicalSnapshot?: DmReadStateSnapshot,): ReturnType<typeof useChannelReadStateSnapshot> {- return useChannelReadStateSnapshot(dmId, canonicalSnapshot, "dm")+ return useChannelReadStateSnapshot(dmId, "dm")}diff --git a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts b/src/web/src/hooks/community/use-dm-route-verification.dom.test.tsindex 4c42de77f..325ddcb76 100644--- a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts+++ b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts@@ -7,7 +7,8 @@ import { QueryClientProvider } from "@tanstack/react-query"import { CommunityDbProvider } from "@/lib/community-db/projections"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { channelMetadataOptions } from "./channel-metadata"-import { startDmRouteVerification, useDmRouteVerification } from "./use-dm-route-verification"+import { startDmRouteVerification } from "./use-dm-route-verification"+import { useChannelMetadata } from "./use-channel-metadata"const apiFetch = vi.hoisted(() => vi.fn())vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))@@ -42,17 +43,17 @@ describe("DM route uses the shared Channel metadata owner", () => {apiFetch.mockReturnValue(request.promise)const first = startDmRouteVerification(client, dm.id)const second = startDmRouteVerification(client, dm.id)- const route = renderHook(() => useDmRouteVerification(dm.id), { wrapper })+ const route = renderHook(() => useChannelMetadata(null, dm.id), { wrapper })await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())expect(route.result.current.status).toBe("pending")await act(async () => request.resolve(metadata))await expect(first).resolves.toBe("present")await expect(second).resolves.toBe("present")- await waitFor(() => expect(route.result.current.status).toBe("present"))+ await waitFor(() => expect(route.result.current.status).toBe("readable"))expect(apiFetch).toHaveBeenCalledWith(`/api/community/channels/${dm.id}`, expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))expect(client.getQueryData(communityKeys.channelMeta(null, dm.id))).toMatchObject({ id: metadata.id })expect(client.getQueryData(communityKeys.dms())).toEqual({ conversations: [] })- expect(registry.runtime.ws.get().channelAccessScopes.size).toBe(0)+ expect(registry.runtime.ws.get().channelAccessScopes.get(dm.id)).toMatchObject({ serverId: null, generation: 0, revoked: false })route.unmount()client.clear()})@@ -61,8 +62,8 @@ describe("DM route uses the shared Channel metadata owner", () => {const { client, registry, wrapper } = await fixture()apiFetch.mockResolvedValue(metadata)await client.query(channelMetadataOptions(client, null, dm.id))- const route = renderHook(() => useDmRouteVerification(dm.id), { wrapper })- expect(route.result.current.status).toBe("present")+ const route = renderHook(() => useChannelMetadata(null, dm.id), { wrapper })+ expect(route.result.current.status).toBe("readable")await expect(startDmRouteVerification(client, dm.id)).resolves.toBe("present")expect(apiFetch).toHaveBeenCalledOnce()route.unmount()@@ -74,11 +75,11 @@ describe("DM route uses the shared Channel metadata owner", () => {client.setQueryData(communityKeys.dms(), { conversations: [dm] })const request = deferred<typeof metadata>()apiFetch.mockReturnValue(request.promise)- const route = renderHook(() => useDmRouteVerification(dm.id), { wrapper })+ const route = renderHook(() => useChannelMetadata(null, dm.id), { wrapper })expect(route.result.current.status).toBe("pending")await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())await act(async () => request.resolve(metadata))- await waitFor(() => expect(route.result.current.status).toBe("present"))+ await waitFor(() => expect(route.result.current.status).toBe("readable"))route.unmount()client.clear()})@@ -97,18 +98,18 @@ describe("DM route uses the shared Channel metadata owner", () => {const { client, registry, wrapper } = await fixture()apiFetch.mockRejectedValueOnce(new Error("offline"))const hook = ({ key }: { key: string }) => React.createElement(Capture, { key })- let latest!: ReturnType<typeof useDmRouteVerification>- function Capture() { latest = useDmRouteVerification(dm.id); return null }+ let latest!: ReturnType<typeof useChannelMetadata>+ function Capture() { latest = useChannelMetadata(null, dm.id); return null }const { render } = await import("@/test/react-dom-harness")const route = render(hook({ key: "first" }), { wrapper })- await waitFor(() => expect(latest.status).toBe("error"))+ await waitFor(() => expect(latest.status).toBe("retryable-error"))route.rerender(hook({ key: "second" }))await act(async () => { onlineManager.setOnline(false); onlineManager.setOnline(true) })- expect(latest.status).toBe("error")+ expect(latest.status).toBe("retryable-error")expect(apiFetch).toHaveBeenCalledOnce()apiFetch.mockResolvedValueOnce(metadata)await act(async () => latest.retry())- await waitFor(() => expect(latest.status).toBe("present"))+ await waitFor(() => expect(latest.status).toBe("readable"))expect(apiFetch).toHaveBeenCalledTimes(2)route.unmount()client.clear()@@ -135,7 +136,7 @@ describe("DM route uses the shared Channel metadata owner", () => {const { client, registry, wrapper } = await fixture()const request = deferred<typeof metadata>()apiFetch.mockReturnValue(request.promise)- const route = renderHook(() => useDmRouteVerification(dm.id), { wrapper })+ const route = renderHook(() => useChannelMetadata(null, dm.id), { wrapper })await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())const signal = apiFetch.mock.calls[0][1].signal as AbortSignalroute.unmount()diff --git a/src/web/src/hooks/community/use-dm-route-verification.ts b/src/web/src/hooks/community/use-dm-route-verification.tsindex 6b0e1d73c..435438e42 100644--- a/src/web/src/hooks/community/use-dm-route-verification.ts+++ b/src/web/src/hooks/community/use-dm-route-verification.ts@@ -1,21 +1,13 @@"use client"import { QueryObserver, type QueryClient } from "@tanstack/react-query"-import { useCallback } from "react"import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "./channel-metadata"-import { useChannelMetadata } from "./use-channel-metadata"import {assertCommunityLiveSnapshotTokenCurrent,captureCommunityLiveSnapshotToken,} from "@/lib/community-db/sync"export type DmRouteVerification = "present" | "missing" | "denied"-type DmRouteVerificationStatus = "idle" | "pending" | "present" | "missing" | "error"-export type DmRouteVerificationResult = {- status: DmRouteVerificationStatus- retry: () => void- retrying: boolean-}function classifyDmRouteAuthorityError(error: unknown): "denied" | "error" {const status = typeof error === "object" && error !== null && "status" in error@@ -41,34 +33,22 @@ export async function startDmRouteVerification(const options = verificationOptions(queryClient, dmId)const owner = new QueryObserver(queryClient, { ...options, enabled: false })const release = owner.subscribe(() => {})- const token = captureCommunityLiveSnapshotToken(queryClient)+ const token = captureCommunityLiveSnapshotToken(queryClient, dmId)try {- const cached = queryClient.getQueryData<{ verification?: ReturnType<typeof captureChannelMetadataToken> }>(options.queryKey)- await queryClient.query({ ...options,- staleTime: cached?.verification && isChannelMetadataTokenCurrent(cached.verification) ? Infinity : 0, select: undefined })- return "present"+ const cached = queryClient.getQueryData<{ readProof?: ReturnType<typeof captureChannelMetadataToken> }>(options.queryKey)+ const resource = await queryClient.query({ ...options,+ staleTime: cached?.readProof && isChannelMetadataTokenCurrent(cached.readProof) ? Infinity : 0, select: undefined })+ return resource.readProof && isChannelMetadataTokenCurrent(resource.readProof) ? "present" : "denied"} catch (error) {+ if (classifyDmRouteAuthorityError(error) === "denied") {+ assertCommunityLiveSnapshotTokenCurrent(queryClient, {+ ...token, accessEpoch: captureCommunityLiveSnapshotToken(queryClient).accessEpoch, channelScopes: captureCommunityLiveSnapshotToken(queryClient).channelScopes,+ }, undefined)+ return "denied"+ }assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)- if (classifyDmRouteAuthorityError(error) === "denied") return "denied"throw error} finally {release()}}--export function useDmRouteVerification(- dmId: string | undefined,-): DmRouteVerificationResult {- const verification = useChannelMetadata(null, dmId)- const retry = useCallback(() => {- if (!dmId || verification.fetchStatus === "fetching") return- void verification.refetch({ cancelRefetch: false })- }, [dmId, verification])- let status: DmRouteVerificationStatus = "pending"- if (!dmId) status = "idle"- else if (classifyDmRouteAuthorityError(verification.error) === "denied" || verification.data?.archived || verification.canonical?.archived) status = "missing"- else if (verification.isVerified && verification.data?.type === "dm") status = "present"- else if (verification.isError) status = "error"-- return { status, retry, retrying: verification.fetchStatus === "fetching" }-}diff --git a/src/web/src/hooks/community/use-dm-watermark.ts b/src/web/src/hooks/community/use-dm-watermark.tsindex 67742d789..0c64a9956 100644--- a/src/web/src/hooks/community/use-dm-watermark.ts+++ b/src/web/src/hooks/community/use-dm-watermark.ts@@ -1,36 +1,10 @@"use client"-import type { Msg } from "@/lib/community/models/message"+import type { useChannelWatermark } from "./use-channel-watermark"import { useTimelineReadObserver } from "./use-read-observer"-/* istanbul ignore next -- retained Chromium covers this React hook adapter */-export function useDmWatermark({- dmId,- messages,- scrollRootEl,- snapshotStatus,- feedStatus,- tailAttached,- confirmedSeq,- catchUp,-}: {- dmId: string | null | undefined- messages: Msg[]- scrollRootEl: HTMLElement | null- snapshotStatus: "pending" | "ready" | "error"- feedStatus: "pending" | "ready" | "error"- tailAttached: boolean- confirmedSeq: number- catchUp: () => Promise<unknown>-}) {- useTimelineReadObserver({- channelId: dmId,- messages,- scrollRootEl,- snapshotStatus,- feedStatus,- tailAttached,- confirmedSeq,- catchUp,- })+type ChannelReadOptions = Parameters<typeof useChannelWatermark>[0]++export function useDmWatermark({ dmId, ...options }: Omit<ChannelReadOptions, "channelId"> & { dmId: ChannelReadOptions["channelId"] }) {+ useTimelineReadObserver({ ...options, channelId: dmId })}diff --git a/src/web/src/hooks/community/use-forum-feed.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.dom.test.tsindex 3adc3d662..c02840279 100644--- a/src/web/src/hooks/community/use-forum-feed.dom.test.ts+++ b/src/web/src/hooks/community/use-forum-feed.dom.test.ts@@ -6,8 +6,8 @@ import { renderHook, waitFor } from "@/test/react-dom-harness"import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { getCommunityDbRegistry } from "@/lib/community-db/collections"-import { getCanonicalCommunityMessages, getCanonicalCommunityChannels } from "@/lib/community-db/sync"-import { forumFeedWindow, type ForumFeedTransportPage } from "./forum-feed-window"+import { getCanonicalCommunityMessages, getCanonicalCommunityChannels, patchCanonicalCommunityChannel } from "@/lib/community-db/sync"+import { forumFeedWindow, normalizeThreadResources, type ForumFeedTransportPage } from "./forum-feed-window"import { CONVERSATION_READ_TIMEOUT_MS } from "@/lib/community/conversation-read"import { communityKeys } from "@/lib/query-keys"@@ -133,7 +133,7 @@ describe("forumFeedPageQueryFn", () => {it("seeds opener and participant profiles while returning only the ID window", async () => {const page = {serverId: "server_1", parentType: "forum",- threads: [],+ threads: [{ id: "thread_1", name: "post", creatorId: "author_1", messageCount: 1, parentMessageId: "m1", lastMessageAt: null, createdAt: "", activityAt: "" }],included: {parentMessages: [{id: "m1",@@ -158,7 +158,7 @@ describe("forumFeedPageQueryFn", () => {const result = await forumFeedPageQueryFn("forum_one", null, client)({ pageParam: null })- expect(result).toEqual(forumFeedWindow(page))+ expect(result).toEqual(forumFeedWindow(normalizeThreadResources("forum_one", page)))const profiles = getCommunityDbRegistry(client)!.collections.profilesexpect(profiles.get("author_1")).toMatchObject({ name: "Alice", avatarVersion: 2 })expect(profiles.get("participant_1")).toMatchObject({ name: "Bob", avatar: "bob.png", avatarVersion: 3 })@@ -167,6 +167,20 @@ describe("forumFeedPageQueryFn", () => {})describe("mapForumFeedPages", () => {+ it("retains full forum preview, empty activity and zero opener sequence", async () => {+ const preview = "preview".repeat(30)+ const result = await projectPages([{+ serverId: "server_1", parentType: "forum", hasMore: false,+ threads: [{ id: "post", name: "Fallback", creatorId: "u1", messageCount: null, parentMessageId: "opener", lastMessageAt: null, createdAt: "created", activityAt: "created" }],+ included: { ...emptyIncluded, parentMessages: [{ id: "opener", channelId: "forum_1", seq: 0, content: " ", authorId: "u1", authorName: "A", authorImage: null, authorAvatarVersion: 0 }], firstMessages: [{ channelId: "post", content: preview }] },+ }])+ expect(result).toHaveLength(1)+ expect(result[0]).toMatchObject({ name: "Fallback", messageCount: 0, lastMessageAt: "created", parent: { authorId: "u1", authorName: "A", text: preview.slice(0, 100) }, parentSeq: 0, openerMessageId: "opener", preview: preview.slice(0, 100) })+ patchCanonicalCommunityChannel(client, "post", (row) => ({ ...row, preview, lastMessageAt: null }))+ const registry = getCommunityDbRegistry(client)!+ const projected = mapForumFeedPages([{ serverId: "server_1", parentType: "forum", threads: [{ id: "post", openerMessageId: "opener", participantIds: [] }], hasMore: false }], new Map(getCanonicalCommunityMessages(client).map((row) => [row.id, row])), new Map(getCanonicalCommunityChannels(client).map((row) => [row.id, row])), new Map([...registry.collections.profiles.values()].map((row) => [row.userId, row])))+ expect(projected[0]).toMatchObject({ lastMessageAt: "", parent: { text: preview }, preview, parentSeq: 0 })+ })it("keeps one operation baseline across pages and excludes duplicate profile publications", async () => {const registry = getCommunityDbRegistry(client)!const page = (id: string, name: string, more: boolean): ForumFeedTransportPage => ({@@ -205,8 +219,8 @@ describe("mapForumFeedPages", () => {threads: [thread("delete", "m_delete"), thread("keep", "m_keep")],included: {parentMessages: [- { id: "m_delete", channelId: "forum", seq: 1, content: "delete", authorId: "u", authorName: "U", authorImage: null, authorAvatarVersion: 0 },- { id: "m_keep", channelId: "forum", seq: 2, content: "keep", authorId: "u", authorName: "U", authorImage: null, authorAvatarVersion: 0 },+ { id: "m_delete", channelId: "forum_1", seq: 1, content: "delete", authorId: "u", authorName: "U", authorImage: null, authorAvatarVersion: 0 },+ { id: "m_keep", channelId: "forum_1", seq: 2, content: "keep", authorId: "u", authorName: "U", authorImage: null, authorAvatarVersion: 0 },],firstMessages: [{ channelId: "delete", content: "delete" }, { channelId: "keep", content: "keep" }],tags: [{ messageId: "m_delete", tag: "delete" }, { messageId: "m_keep", tag: "keep" }],@@ -220,7 +234,7 @@ describe("mapForumFeedPages", () => {pageParams: [null],}- const windows = { ...data, pages: data.pages.map((page) => forumFeedWindow(page)) }+ const windows = { ...data, pages: data.pages.map((page) => forumFeedWindow(normalizeThreadResources("forum_1", page))) }const projected = removeForumPostFromFeed(windows, "delete", "m_delete")!expect(projected.pages[0].threads.map((row) => row.id)).toEqual(["keep"])@@ -337,7 +351,7 @@ describe("mapForumFeedPages", () => {included: {parentMessages: [{id: "opener-1",- channelId: "forum-1",+ channelId: "forum_1",seq: 7,content: "transport content",authorId: "transport-author",diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex c59541ac7..b5ee1a878 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -4,13 +4,11 @@ import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/datimport { useCallback, useEffect, useMemo } from "react"import { createStore, useAtom, useCreateAtom } from "@tanstack/react-store"import { useInfiniteQuery, useIsMutating, useQueryClient, type Query } from "@tanstack/react-query"-import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE } from "@alook/shared"+import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityThreadsRead } from "@alook/shared"import { apiFetch } from "@/lib/api/client"-import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"import { communityKeys } from "@/lib/query-keys"-import { canonicalUserImage } from "@/lib/community/storage"import { avatarInitial } from "@/lib/community/avatar"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"@@ -20,7 +18,7 @@ import type { ForumThread, Msg } from "@/lib/community/models/message"import type { ChannelRow } from "@/lib/community-db/schema"import { readCommunityProfile } from "@/lib/community/profile-read"import { useForumTags } from "./use-channel-panels"-import { forumFeedMatchesTags, forumFeedWindow, type ForumFeedPage, type ForumFeedTransportPage } from "./forum-feed-window"+import { forumFeedMatchesTags, forumFeedWindow, normalizeThreadResources, projectThread, type ForumFeedPage, type ForumFeedTransportPage } from "./forum-feed-window"export { removeForumPostFromFeed } from "./forum-feed-window"export type { ForumFeedPage } from "./forum-feed-window"@@ -37,7 +35,7 @@ function beginForumRead(queryClient: ReturnType<typeof useQueryClient>, channelIconst existing = resource ? forumReads.get(resource) : undefinedif (existing && existing.get().operation === resource!.promise) return existingconst cached = resource?.state.data as { pages: ForumFeedPage[] } | undefined- const protocol = createStore<ForumReadProtocol>({ operation: resource?.promise, token: captureCommunityLiveSnapshotToken(queryClient), publishedIds: new Set(resource?.state.fetchMeta?.fetchMore ? cached?.pages.flatMap((page) => page.threads.map((thread) => thread.id)) : []) })+ const protocol = createStore<ForumReadProtocol>({ operation: resource?.promise, token: captureCommunityLiveSnapshotToken(queryClient, channelId), publishedIds: new Set(resource?.state.fetchMeta?.fetchMore ? cached?.pages.flatMap((page) => page.threads.map((thread) => thread.id)) : []) })if (resource) forumReads.set(resource, protocol)return protocol}@@ -55,20 +53,19 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null, querconst params = new URLSearchParams({ order: "createdAt", limit: String(DEFAULT_MESSAGE_PAGE_SIZE), include: "parentMessage,firstMessage,tags,participants" })if (tag) params.set("tag", tag)if (pageParam) params.set("cursor", pageParam)- const page = await apiFetch<ForumFeedTransportPage>(`/api/community/channels/${channelId}/threads?${params}`, communityRequestOptions(queryClient, token, readSignal))+ const transport = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead>(`/api/community/channels/${channelId}/threads?${params}`, communityRequestOptions(queryClient, token, readSignal))assertCommunityLiveSnapshotTokenCurrent(queryClient, token, readSignal)+ const page = normalizeThreadResources(channelId, transport)const freshThreads = page.threads.filter((thread) => !protocol.get().publishedIds.has(thread.id))const ids = new Set(freshThreads.map((thread) => thread.id)), openerIds = new Set(freshThreads.map((thread) => thread.parentMessageId))- const duplicateOpeners = new Set(page.threads.filter((thread) => protocol.get().publishedIds.has(thread.id)).map((thread) => thread.parentMessageId))- writeCommunityProfilePatches([- ...page.included.parentMessages.filter((message) => !duplicateOpeners.has(message.id)).map((message) => ({ id: message.authorId, identityAbout: { name: message.authorName }, avatar: { avatar: canonicalUserImage(message.authorId, message.authorImage, message.authorAvatarVersion) ?? avatarInitial(message.authorName), avatarVersion: message.authorAvatarVersion } })),- ...page.included.participants.filter((participant) => !protocol.get().publishedIds.has(participant.channelId)).map((participant) => ({ id: participant.userId, ...(participant.userName !== null ? { identityAbout: { name: participant.userName } } : {}), avatar: { avatar: canonicalUserImage(participant.userId, participant.userImage, participant.userAvatarVersion) ?? avatarInitial(participant.userName ?? "Deleted user"), avatarVersion: participant.userAvatarVersion } })),- ], registry, { snapshot: token.profileSnapshot })+ const users = new Set(page.included.members.filter((member) => ids.has(member.channelId)).map((member) => member.userId))publishCommunityForumFeed(queryClient, channelId, { ...page, threads: freshThreads, included: {- parentMessages: page.included.parentMessages.filter((message) => openerIds.has(message.id)),- firstMessages: page.included.firstMessages.filter((message) => ids.has(message.channelId)),+ messages: page.included.messages.filter((message) => openerIds.has(message.id) || ids.has(message.channelId)),+ previews: page.included.previews.filter((message) => ids.has(message.channelId)),tags: page.included.tags.filter((row) => openerIds.has(row.messageId)),- participants: page.included.participants.filter((row) => ids.has(row.channelId)),+ members: page.included.members.filter((row) => ids.has(row.channelId)),+ profiles: page.included.profiles.filter((profile) => users.has(profile.id)),+ participantCounts: page.included.participantCounts.filter((row) => ids.has(row.channelId)),} }, { token, signal: readSignal })protocol.setState((state) => ({ ...state, publishedIds: new Set([...state.publishedIds, ...ids]) }))return forumFeedWindow(page)@@ -82,10 +79,9 @@ export function mapForumFeedPages(pages: ForumFeedPage[], messages: ReadonlyMap<const thread = channels.get(window.id), opener = window.openerMessageId ? messages.get(window.openerMessageId) : undefinedif (!thread || !opener || thread.parentMessageId !== opener.id || !forumFeedMatchesTags(filter, thread.tags)) continuebyId.set(thread.id, deriveView({- id: thread.id, name: opener.content?.trim() ? opener.content : thread.name || "Post", messageCount: thread.messageCount ?? 0, lastMessageAt: thread.lastMessageAt ?? "",- parent: { authorId: opener.authorId, authorName: opener.authorName ?? "", text: thread.preview ?? "" }, authorId: opener.authorId ?? thread.creatorId ?? "",+ ...projectThread(thread, opener, "forum"), authorId: opener.authorId ?? thread.creatorId ?? "",authorAvatar: opener.authorAvatar ?? avatarInitial(opener.authorName ?? ""), authorAvatarVersion: opener.authorAvatarVersion ?? 0,- openerMessageId: opener.id, ...(opener.createdAt === undefined ? {} : { openerCreatedAt: opener.createdAt }), ...(opener.seq === undefined ? {} : { parentSeq: opener.seq }), tags: thread.tags, preview: thread.preview ?? "",+ openerMessageId: opener.id, ...(opener.createdAt === undefined ? {} : { openerCreatedAt: opener.createdAt }), tags: thread.tags, preview: thread.preview ?? "",participants: window.participantIds.map((id) => { const profile = readCommunityProfile(profiles.get(id), id); return { id, name: profile.name, avatar: profile.avatar, avatarVersion: profile.avatarVersion } }), participantCount: thread.participantCount ?? 0,}, [viewEvidence(thread), viewEvidence(opener), ...window.participantIds.map(id => viewEvidence(profiles.get(id)))]))}@@ -93,7 +89,7 @@ export function mapForumFeedPages(pages: ForumFeedPage[], messages: ReadonlyMap<}export function useForumFeed(serverId: string, channelId: string) {- const queryClient = useQueryClient(), messages = useCanonicalMessagesById(), channels = useCanonicalChannelsById(), profiles = useCanonicalProfilesByUserId()+ const queryClient = useQueryClient(), channels = useCanonicalChannelsById(), profiles = useCanonicalProfilesByUserId()const readTag = () => { try { return readForumTagSelection(window.localStorage, channelId) } catch { return "All" } }const [selection, setSelection] = useAtom(useCreateAtom({ channelId, tag: readTag() }))const tag = selection.channelId === channelId ? selection.tag : readTag()@@ -108,6 +104,8 @@ export function useForumFeed(serverId: string, channelId: string) {const queryKey = communityKeys.forumFeed(channelId, selectedTag)const query = useInfiniteQuery({ queryKey, queryFn: forumFeedPageQueryFn(channelId, selectedTag, queryClient), initialPageParam: null as string | null, getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry), networkMode: "always" })+ const messageIds = useMemo(() => [...new Set(query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : [])) ?? [])], [query.data?.pages])+ const messages = useCanonicalMessagesById(messageIds)const posts = useMemo(() => mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag), [query.data?.pages, messages, channels, profiles, selectedTag])deriveView(posts, [valueEvidence(queryClient, query.data), ...posts.map(viewEvidence)], posts.length)return { ...query, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder: () => { void query.fetchNextPage() } }diff --git a/src/web/src/hooks/community/use-forum-opener-hint.ts b/src/web/src/hooks/community/use-forum-opener-hint.tsindex 6d0c9133b..27bc1b594 100644--- a/src/web/src/hooks/community/use-forum-opener-hint.ts+++ b/src/web/src/hooks/community/use-forum-opener-hint.ts@@ -1,4 +1,6 @@"use client"+import type { CommunityMessageResource } from "@alook/shared"+import { useMemo } from "react"import { useQuery, useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"@@ -22,22 +24,17 @@ export function useForumOpenerHint() {const active = enabled && !!messageIdconst registry = useOptionalCommunityDbRegistry()- const canonicalMessages = useCanonicalMessagesById()+ const messageIds = useMemo(() => messageId ? [messageId] : [], [messageId])+ const canonicalMessages = useCanonicalMessagesById(messageIds)const queryClient = useQueryClient()const queryKey = communityKeys.message(messageId ?? "__none__")- const query = useQuery<{ id: string }>({+ const query = useQuery<Pick<CommunityMessageResource, "id">>({queryKey,queryFn: ({ signal }) => withConversationReadDeadline(signal, async (readSignal) => {const token = captureCommunityLiveSnapshotToken(queryClient)await token.registry!.readyassertCommunityLiveSnapshotTokenCurrent(queryClient, token, readSignal)- const message = await apiFetch<{- id: string- content: string- seq: number- channelId: string- type: "chat" | "system"- }>(+ const message = await apiFetch<Pick<CommunityMessageResource, "id" | "content" | "seq" | "channelId" | "type">>(`/api/community/messages/${messageId}`,communityRequestOptions(queryClient, token, readSignal),)diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.tsindex 84a961b2d..7748fa32f 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts@@ -12,20 +12,22 @@ import {ingestServerDetail,ingestServers,getCanonicalCommunityChannels,+ getCanonicalCommunityChannelMemberships,getCanonicalCommunityMessages,projectCommunityWsEventToDb,publishCommunityLiveSnapshot,+ purgeCommunityChannel,publishCommunityForumSidebar,removeCanonicalCommunityChannelMembership,setCanonicalCommunityChannelMembership,} from "@/lib/community-db/sync"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useChannelMetadata } from "./use-channel-metadata"+import { projectForumSidebar } from "@/lib/community/forum-sidebar"import { useForumOpenerHint } from "./use-forum-opener-hint"import { isChannelMetadataTokenCurrent } from "./channel-metadata"import { communityKeys } from "@/lib/query-keys"import {- deriveForumSidebarProjection,getForumSidebarBase,grantForumSidebarChild,invalidateForumSidebarBaseExact,@@ -34,9 +36,7 @@ import {patchForumSidebarTitleExact,reconcileForumSidebarNotifyMemberships,reconcileForumSidebarArchiveTag,- removeForumSidebarChildrenForParent,removeForumSidebarProjectionExact,- removeForumSidebarThreadExact,resolveForumSidebarRouteCandidate,useForumSidebarThreads,type SidebarThreadEnvelope,@@ -360,7 +360,7 @@ describe("forum sidebar canonical projection", () => {expect(registry.collections.channelMemberships.get("text-child:viewer:notify")).toBeDefined()rendered.unmount()})- it("hands a fresh sidebar child and opener to the shared qualified route without another GET", async () => {+ it("uses sidebar identity and opener while one protected metadata GET qualifies reading", async () => {const { queryClient, wrapper } = await setup()apiFetchMock.mockResolvedValueOnce(envelope())let retainId: string | null = null@@ -368,7 +368,7 @@ describe("forum sidebar canonical projection", () => {await waitFor(() => expect(sidebar.result.current.threads[0]?.title).toBe("Canonical title"))let releaseRetained!: (value: SidebarThreadEnvelope) => voidconst retained = new Promise<SidebarThreadEnvelope>((resolve) => { releaseRetained = resolve })- apiFetchMock.mockReturnValue(retained)+ apiFetchMock.mockImplementation((url) => url === "/api/community/channels/post-1" ? Promise.resolve({ ...envelope().channels[0], id: "post-1", serverId: "server-1", type: "thread", name: "Canonical title", archived: false, createdAt: new Date().toISOString() }) : retained)retainId = "post-1"sidebar.rerender()const route = renderHook(() => {@@ -377,11 +377,13 @@ describe("forum sidebar canonical projection", () => {return { metadata, opener }}, { wrapper })try {- expect(route.result.current.metadata.isVerified).toBe(true)+ expect(route.result.current.metadata.identityKnown).toBe(true)+ expect(route.result.current.metadata.canRead).toBe(false)+ await waitFor(() => expect(route.result.current.metadata.canRead).toBe(true))expect(route.result.current.opener.data?.content).toBe("Canonical title")await waitFor(() => expect(apiFetchMock.mock.calls.some(([url]) => new URL(url, "http://localhost").searchParams.get("retainId") === "post-1")).toBe(true))- expect(apiFetchMock.mock.calls.some(([url]) => url === "/api/community/channels/post-1")).toBe(false)- expect(isChannelMetadataTokenCurrent(queryClient.getQueryData<{ verification: Parameters<typeof isChannelMetadataTokenCurrent>[0] }>(communityKeys.channelMeta("server-1", "post-1"))!.verification)).toBe(true)+ expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/channels/post-1")).toHaveLength(1)+ expect(isChannelMetadataTokenCurrent(queryClient.getQueryData<{ identityProof: Parameters<typeof isChannelMetadataTokenCurrent>[0] }>(communityKeys.channelMeta("server-1", "post-1"))!.identityProof)).toBe(true)} finally {route.unmount()sidebar.unmount()@@ -412,29 +414,62 @@ describe("forum sidebar canonical projection", () => {expect(queryClient.getQueryData(communityKeys.channelMeta("server-1", "post-1"))).toBeUndefined()})- it("classifies retained route candidates and bounded active extras", () => {+ it("classifies retained route candidates and bounds an expired active extra in the canonical view", async () => {expect(resolveForumSidebarRouteCandidate(null, ["forum-1"], true)).toBeNull()expect(resolveForumSidebarRouteCandidate("forum-1", ["forum-1"], true)).toBeNull()- expect(resolveForumSidebarRouteCandidate("post-3", ["forum-1"], true)).toBe("post-3")-- const base = normalizeForumSidebarEnvelope(envelopeFor(["post-1", "post-2"]), null, 0).base- const extra = normalizeForumSidebarEnvelope(envelopeFor(["post-3"]), null, 0).base.threads[0]!- expect(deriveForumSidebarProjection(- base,- extra,- { "forum-1": { baseUnread: false, childIds: ["post-3"] } },- Date.parse(base.serverNow),- 2,- )).toMatchObject({- threads: expect.arrayContaining([expect.objectContaining({ id: "post-3", unread: true })]),+ expect(resolveForumSidebarRouteCandidate("post-6", ["forum-1"], true)).toBe("post-6")+ const { queryClient, wrapper } = await setup()+ const response = envelopeFor(["post-1", "post-2", "post-3", "post-4", "post-5", "post-6"])+ const expired = new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString()+ Object.assign(response.channels[5]!, { activityAt: expired, lastMessageAt: expired, expiresAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(), unread: true })+ publish(queryClient, response)+ const rendered = renderHook(() => useForumSidebarProjection("server-1", "post-6", Date.now()), { wrapper })+ await waitFor(() => expect(rendered.result.current?.threads).toHaveLength(5))+ expect(rendered.result.current).toMatchObject({+ threads: expect.arrayContaining([expect.objectContaining({ id: "post-6", unread: true })]),parentUnread: { "forum-1": false },})+ rendered.rerender()+ rendered.unmount()})it("ignores incomplete child metadata while normalizing", () => {const response = envelope()response.channels[0] = { ...response.channels[0]!, serverId: undefined }- expect(normalizeForumSidebarEnvelope(response, null, 0).channelMetas).toEqual({})+ expect(normalizeForumSidebarEnvelope(response, null, 0).channels).toEqual([])+ })++ it("ignores another user's notify row in both Sidebar views and bounded negative reconciliation", async () => {+ const { queryClient, registry, wrapper } = await setup()+ publish(queryClient)+ removeCanonicalCommunityChannelMembership(queryClient, "post-1", "notify")+ registry.collections.channelMemberships.utils.writeUpsert({ id: "post-1:other:notify",+ channelId: "post-1", userId: "other", relation: "notify", source: "explicit" })+ expect(getForumSidebarBase(queryClient, "server-1").threads).toEqual([])+ const rendered = renderHook(() => useForumSidebarProjection("server-1", null, Date.now()), { wrapper })+ await waitFor(() => expect(rendered.result.current?.threads).toEqual([]))+ apiFetchMock.mockResolvedValue(envelopeFor([]))+ const result = await reconcileForumSidebarNotifyMemberships(queryClient, "server-1")+ expect(result.removedIds).toEqual([])+ expect(registry.collections.channelMemberships.get("post-1:other:notify")).toBeDefined()+ expect(registry.collections.channels.get("post-1")?.unread).toBe(true)+ rendered.unmount()+ })++ it.each([null, "0", "expired"] as const)("shares ASCII candidates and one expiry/top-five/retain=$0 view selector", async (retainId) => {+ const { queryClient, registry, wrapper } = await setup()+ const data = envelopeFor(["0", "9", "A", "Z", "a", "z", "expired"])+ const expired = data.channels.find((row) => row.id === "expired")!+ expired.lastMessageAt = expired.activityAt = new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString()+ publish(queryClient, data)+ const rendered = renderHook(() => useForumSidebarProjection("server-1", retainId, Date.now()), { wrapper })+ const expected = retainId === null ? ["z", "a", "Z", "A", "9"] : ["z", "a", "Z", "A", retainId]+ await waitFor(() => expect(rendered.result.current?.threads.map((row) => row.id)).toEqual(expected))+ expect(getForumSidebarBase(queryClient, "server-1").threads.map((row) => row.id)).toEqual(["z", "a", "Z", "A", "9", "0", "expired"])+ expect(projectForumSidebar(getCanonicalCommunityChannels(queryClient), getCanonicalCommunityChannelMemberships(queryClient),+ getCanonicalCommunityMessages(queryClient), registry.accountId, "server-1", retainId, Date.now()).threads)+ .toStrictEqual(rendered.result.current?.threads)+ rendered.unmount()})it("removes only bounded-base misses that could displace the authoritative top five", async () => {@@ -690,24 +725,22 @@ describe("forum sidebar canonical projection", () => {rendered.unmount()})- it("keeps providerless normalization explicit for pure tests", () => {- const normalized = normalizeForumSidebarEnvelope(envelope(), null, 0)- expect(deriveForumSidebarProjection(- normalized.base,- null,- { "forum-1": { baseUnread: false, childIds: ["post-1"] } },- Date.parse(normalized.base.serverNow),- )).toEqual({+ it("keeps normalized child unread and parent ownership in the canonical view", async () => {+ const { queryClient, wrapper } = await setup()+ publish(queryClient, envelope())+ const rendered = renderHook(() => useForumSidebarProjection("server-1", null, Date.now()), { wrapper })+ await waitFor(() => expect(rendered.result.current).toEqual({threads: [expect.objectContaining({ id: "post-1", unread: true })],parentUnread: { "forum-1": false },- })+ }))+ rendered.unmount()})it("preserves system opener types at the canonical ingress boundary", () => {const response = envelope()response.included.parentMessages[0]!.type = "system"- expect(normalizeForumSidebarEnvelope(response, null, 0).openerHints["opener-1"])+ expect(normalizeForumSidebarEnvelope(response, null, 0).openers.find((message) => message.id === "opener-1")).toEqual(expect.objectContaining({ type: "system" }))})@@ -804,7 +837,7 @@ describe("forum sidebar canonical projection", () => {act(() => { patchForumSidebarActivityExact(queryClient, "server-1", "missing", "forum-1", activityAt,) });- act(() => { removeForumSidebarThreadExact(queryClient, "server-1", "post-2") });+ act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "post-2") });await act(async () => resolveRequest(envelopeFor(["post-1", "post-2"])))await waitFor(() => expect(rendered.result.current.threads).toEqual([expect.objectContaining({@@ -892,7 +925,7 @@ describe("forum sidebar canonical projection", () => {act(() => { patchForumSidebarActivityExact(queryClient, "server-1", "post-1", "forum-1", "invalid") });expect(getForumSidebarBase(queryClient, "server-1").threads[0]?.expiresAt).toBe("invalid")act(() => { removeForumSidebarProjectionExact(queryClient, "server-1", "post-1") });- act(() => { removeForumSidebarChildrenForParent(queryClient, "server-1", "forum-1") });+ act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "forum-1") });expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1")).toBe(false)})@@ -958,7 +991,7 @@ describe("forum sidebar canonical projection", () => {apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveGrant = resolve }))const grant = grantForumSidebarChild(queryClient, "server-1", "post-1").catch((error) => error)await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())- act(() => { removeForumSidebarThreadExact(queryClient, "server-1", "post-1") });+ act(() => { purgeCommunityChannel(getCommunityDbRegistry(queryClient)!, "post-1") });await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)const retained = envelopeFor(["post-1"])resolveGrant({diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex 7f5f44255..42ac3df38 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -1,5 +1,5 @@"use client"-import { deriveView, valueEvidence, viewEvidence } from "@/lib/observability/data-source"+import { deriveView, viewEvidence } from "@/lib/observability/data-source"import { useAtom,useCreateAtom } from "@tanstack/react-store"import { useTrustedRestoredForumProjection } from "@/lib/community-db/projections"import { getCommunityRuntime } from "@/stores/community/runtime"@@ -7,8 +7,7 @@ import { getCommunityRuntime } from "@/stores/community/runtime"import { useEffect,useMemo,useRef } from "react"import { QueryObserver,useQuery,useQueryClient,type QueryClient } from "@tanstack/react-query"-import { compareAsciiSqliteBinary } from "@alook/shared"-import { FORUM_ARCHIVE_TAG } from "@alook/shared/constants/community"+import { type CommunityChannelIdentity, normalizeCommunityChannelIdentity } from "@alook/shared"import { apiFetch } from "@/lib/api/client"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { communityKeys } from "@/lib/query-keys"@@ -16,7 +15,6 @@ import { useCommunityWsStore } from "@/stores/community/ws"import {useAttentionScopes,useForumSidebarProjection,-useOptionalCommunityDbRegistry,} from "@/lib/community-db/projections"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import {@@ -29,22 +27,15 @@ patchCanonicalCommunityChannel,patchCanonicalCommunityMessage,publishCommunityForumSidebar,removeCanonicalCommunityChannelMembership,-purgeCommunityChannel,setCanonicalCommunityChannelMembership,type CommunityFreshQueryProof,+type CommunityForumSidebarChannel,+type CommunityForumSidebarOpener,} from "@/lib/community-db/sync"import { getActiveAccountUnreadProjection } from "./account-unread-projection"--export type ForumSidebarThread = {- id: string- parentChannelId: string- parentMessageId: string- title: string- activityAt: string- expiresAt: string- unread: boolean-}-+import { forumSidebarCandidates, viewerNotifyChannelIds, compareForumSidebarThreads as compareThreads,+ FORUM_SIDEBAR_ACTIVITY_WINDOW_MS as SIDEBAR_ACTIVITY_WINDOW_MS, type ForumSidebarThread } from "@/lib/community/forum-sidebar"+export type { ForumSidebarThread } from "@/lib/community/forum-sidebar"type ForumSidebarRetainedDisposition =| "eligible"@@ -52,33 +43,11 @@ type ForumSidebarRetainedDisposition =| "genuine-negative"export type SidebarThreadEnvelope = {- channels: Array<{- id: string- name: string- parentChannelId: string | null- parentMessageId: string | null- activityAt: string- expiresAt: string- unread: boolean- serverId?: string- type?: string- creatorId?: string | null- archived?: boolean | number- lastMessageAt?: string | null- createdAt?: string- }>+ channels: Array<CommunityForumSidebarChannel & { expiresAt: string; createdAt?: string }>canonicalChannels?: SidebarThreadEnvelope["channels"]retainedChannel?: SidebarThreadEnvelope["channels"][number] | nullretainedDisposition?: ForumSidebarRetainedDisposition | null- included: {- parentMessages: Array<{- id: string- content: string- seq?: number- channelId?: string- type?: string- }>- }+ included: { parentMessages: Array<Omit<CommunityForumSidebarOpener, "type"> & { type?: string }> }serverNow: string}@@ -90,43 +59,19 @@ export type ForumSidebarQueryData = {serverClockOffsetMs: number}-export type ChildChannelMeta = {- id: string- serverId: string- name: string- type: string- parentChannelId: string- parentMessageId: string- creatorId: string | null- archived: boolean+export type ChildChannelMeta = Omit<CommunityChannelIdentity, "serverId" | "name" | "parentChannelId" | "parentMessageId" | "createdAt" | "lastMessageAt"> & { [Field in "serverId" | "name" | "parentChannelId" | "parentMessageId"]: NonNullable<CommunityChannelIdentity[Field]> } & {activityAt: stringverifiedEpoch: number}-type ForumOpenerHint = {- id: string- content: string- seq?: number- channelId?: string- type?: "chat" | "system"-}-export type NormalizedForumSidebarEnvelope = {base: ForumSidebarQueryDataretained: ForumSidebarThread | nullretainedDisposition: ForumSidebarRetainedDisposition | null- channelMetas: Record<string, ChildChannelMeta>- openerHints: Record<string, ForumOpenerHint>+ channels: CommunityForumSidebarChannel[]+ openers: CommunityForumSidebarOpener[]}-/** Source-compatible shape only; no unread fallback cache is stored. */-export type ForumSidebarUnreadFallbackState = Record<string, {- baseUnread: boolean- childIds: string[]-}>--const SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000-export function resolveForumSidebarRouteCandidate(channelId: string | null,topLevelChannelIds: Iterable<string> | null,@@ -143,12 +88,6 @@ export function hasForumSidebarThread(return !!data?.threads.some((thread) => thread.id === threadId)}-function compareThreads(left: ForumSidebarThread, right: ForumSidebarThread) {- return compareAsciiSqliteBinary(left.parentChannelId, right.parentChannelId)- || compareAsciiSqliteBinary(right.activityAt, left.activityAt)- || compareAsciiSqliteBinary(right.id, left.id)-}-function projectForumSidebarThreads(data: SidebarThreadEnvelope) {const openerById = new Map(data.included.parentMessages.map((message) => [message.id, message]))return data.channels.flatMap((channel): ForumSidebarThread[] => {@@ -165,23 +104,21 @@ function projectForumSidebarThreads(data: SidebarThreadEnvelope) {})}-function childMeta(+function sidebarChannelResource(channel: SidebarThreadEnvelope["channels"][number],-): ChildChannelMeta | null {+): CommunityForumSidebarChannel | null {if (!channel.serverId || !channel.type || !channel.parentChannelId || !channel.parentMessageId) {return null}return {- id: channel.id,+ ...normalizeCommunityChannelIdentity({ ...channel, archived: channel.archived ?? false, creatorId: channel.creatorId ?? null, lastMessageAt: channel.activityAt }),serverId: channel.serverId,name: channel.name,- type: channel.type,parentChannelId: channel.parentChannelId,parentMessageId: channel.parentMessageId,- creatorId: channel.creatorId ?? null,- archived: channel.archived === true || channel.archived === 1,activityAt: channel.activityAt,- verifiedEpoch: -1,+ unread: channel.unread,+ participating: true,}}@@ -209,58 +146,14 @@ export function normalizeForumSidebarEnvelope(const retainedDisposition = retainId? envelope.retainedDisposition ?? (retained ? "eligible" : "genuine-negative"): null- const channelMetas: Record<string, ChildChannelMeta> = {}- for (const channel of retainedChannel- ? [...canonicalChannels, retainedChannel]- : canonicalChannels) {- const meta = childMeta(channel)- if (meta) channelMetas[meta.id] = meta- }- const openerHints = Object.fromEntries(- envelope.included.parentMessages.map((message) => [message.id, {- ...message,- type: message.type === "system" ? "system" : "chat",- } satisfies ForumOpenerHint]),- )- return { base, retained, retainedDisposition, channelMetas, openerHints }-}--export function deriveForumSidebarProjection(- base: ForumSidebarQueryData | undefined,- activeExtra: ForumSidebarThread | null | undefined,- ownership: ForumSidebarUnreadFallbackState | undefined,- nowMs = Date.now(),- limitPerParent = 5,-) {- if (!base) {- return { threads: [] as ForumSidebarThread[], parentUnread: {} as Record<string, boolean> }- }- const serverNowMs = nowMs + base.serverClockOffsetMs- let threads = base.threads.filter((thread) => {- const expiry = Date.parse(thread.expiresAt)- return !Number.isFinite(expiry) || expiry > serverNowMs- })- if (activeExtra && !threads.some((thread) => thread.id === activeExtra.id)) {- threads = [- ...threads.filter((thread) => thread.parentChannelId !== activeExtra.parentChannelId),- ...threads- .filter((thread) => thread.parentChannelId === activeExtra.parentChannelId)- .slice(0, Math.max(0, limitPerParent - 1)),- activeExtra,- ].sort(compareThreads)- }- const rendered = new Set(threads.map((thread) => thread.id))- threads = threads.map((thread) => ({- ...thread,- unread: ownership?.[thread.parentChannelId]?.childIds.includes(thread.id)- ?? thread.unread,+ const channels = [...new Map([+ ...canonicalChannels,+ ...(retainedDisposition === "eligible" && retainedChannel ? [retainedChannel] : []),+ ].map((channel) => [channel.id, sidebarChannelResource(channel)])).values()].filter((channel) => channel !== null)+ const openers = envelope.included.parentMessages.map((message) => ({+ ...message, type: message.type === "system" ? "system" as const : "chat" as const,}))- const parentUnread: Record<string, boolean> = {}- for (const [parentId, state] of Object.entries(ownership ?? {})) {- parentUnread[parentId] = state.baseUnread- || state.childIds.some((childId) => !rendered.has(childId))- }- return { threads, parentUnread }+ return { base, retained, retainedDisposition, channels, openers }}function sidebarUrl(serverId: string, retainId: string | null) {@@ -305,37 +198,8 @@ function publishNormalizedForumSidebar(signal: AbortSignal | undefined,token: ReturnType<typeof captureCommunityLiveSnapshotToken>,) {- const threads = [- ...normalized.base.threads,- ...(normalized.retainedDisposition === "eligible" && normalized.retained- ? [normalized.retained]- : []),- ]- const byId = new Map(threads.map((thread) => [thread.id, thread]))- const participatingIds = new Set(normalized.base.threads.map((thread) => thread.id))- if (normalized.retainedDisposition === "eligible" && normalized.retained) {- participatingIds.add(normalized.retained.id)- }publishCommunityForumSidebar(queryClient, {- serverId,- channels: Object.values(normalized.channelMetas).flatMap((meta) => {- const thread = byId.get(meta.id)- return thread ? [{- id: meta.id,- name: meta.name,- parentChannelId: meta.parentChannelId,- parentMessageId: meta.parentMessageId,- activityAt: thread.activityAt,- unread: thread.unread,- serverId: meta.serverId,- type: meta.type,- creatorId: meta.creatorId,- archived: meta.archived,- lastMessageAt: thread.activityAt,- participating: participatingIds.has(meta.id),- }] : []- }),- openers: Object.values(normalized.openerHints),+ serverId, channels: normalized.channels, openers: normalized.openers,negativeRetain: retainId && normalized.retainedDisposition !== "eligible"? {id: retainId,@@ -347,53 +211,13 @@ function publishNormalizedForumSidebar(}function canonicalSidebarBase(queryClient: QueryClient, serverId: string) {- const channels = getCanonicalCommunityChannels(queryClient)- const forumParentIds = new Set(channels- .filter((channel) => channel.serverId === serverId && channel.type === "forum")- .map((channel) => channel.id))- const participating = new Set(- getCanonicalCommunityChannelMemberships(queryClient)- .filter((membership) => membership.relation === "notify")- .map((membership) => membership.channelId),- )- const messages = new Map(- getCanonicalCommunityMessages(queryClient).map((message) => [message.id, message]),- )- const transport = queryClient.getQueryData<ForumSidebarQueryData>(- communityKeys.forumSidebarThreads(serverId),- )- return {- threads: channels- .filter((channel) => (- channel.serverId === serverId- && channel.type === "thread"- && !channel.archived- && !channel.tags.includes(FORUM_ARCHIVE_TAG)- && participating.has(channel.id)- && channel.parentChannelId- && forumParentIds.has(channel.parentChannelId)- && channel.parentMessageId- ))- .map((channel) => {- const activityAt = channel.lastMessageAt ?? ""- const activityMs = Date.parse(activityAt)- return {- id: channel.id,- parentChannelId: channel.parentChannelId!,- parentMessageId: channel.parentMessageId!,- title: messages.get(channel.parentMessageId!)?.content ?? channel.name,- activityAt,- expiresAt: Number.isFinite(activityMs)- ? new Date(activityMs + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()- : activityAt,- unread: channel.unread,- }- })- .sort(compareThreads),- verifiedEpoch: getCommunityRuntime(queryClient).ws.get().accessEpoch,- serverNow: transport?.serverNow ?? new Date().toISOString(),- serverClockOffsetMs: transport?.serverClockOffsetMs ?? 0,- } satisfies ForumSidebarQueryData+ const transport = queryClient.getQueryData<ForumSidebarQueryData>(communityKeys.forumSidebarThreads(serverId))+ const serverClockOffsetMs = transport?.serverClockOffsetMs ?? 0+ const threads = forumSidebarCandidates(getCanonicalCommunityChannels(queryClient),+ getCanonicalCommunityChannelMemberships(queryClient), getCanonicalCommunityMessages(queryClient),+ getCommunityDbRegistry(queryClient)?.accountId ?? null, serverId)+ return { threads, verifiedEpoch: getCommunityRuntime(queryClient).ws.get().accessEpoch,+ serverNow: transport?.serverNow ?? new Date().toISOString(), serverClockOffsetMs } satisfies ForumSidebarQueryData}export function getForumSidebarBase(queryClient: QueryClient, serverId: string) {@@ -475,20 +299,6 @@ export function patchForumSidebarTitleExact(}}-export function removeForumSidebarThreadExact(- queryClient: QueryClient,- serverId: string,- childId: string,-) {- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return- const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === childId)- if (channel && channel.serverId !== serverId) return- if (!channel && registry.runtime.ws.actions.isChannelAccessRevoked(childId, serverId)) return- purgeCommunityChannel(registry, childId)- if (!registry.runtime.ws.actions.isChannelAccessRevoked(childId, serverId)) registry.runtime.ws.actions.revokeChannelAccess(serverId, childId)-}-export function removeForumSidebarProjectionExact(queryClient: QueryClient,serverId: string,@@ -498,20 +308,6 @@ export function removeForumSidebarProjectionExact(removeForumSidebarUnreadChild(queryClient, serverId, childId)}-export function removeForumSidebarChildrenForParent(- queryClient: QueryClient,- serverId: string,- parentChannelId: string,-) {- for (const child of getCanonicalCommunityChannels(queryClient)) {- if (- child.serverId === serverId- && child.type === "thread"- && child.parentChannelId === parentChannelId- ) removeForumSidebarThreadExact(queryClient, serverId, child.id)- }-}-export async function invalidateForumSidebarBaseExact(queryClient: QueryClient,serverId: string,@@ -529,7 +325,6 @@ async function fetchForumSidebarBaseExact(await queryClient.cancelQueries({ queryKey, exact: true })await queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "none" })- const registry = getCommunityDbRegistry(queryClient)const unreadProjection = getActiveAccountUnreadProjection(queryClient)const confirmation = unreadProjection.beginAccessConfirmation()const token = captureCommunityLiveSnapshotToken(queryClient)@@ -560,7 +355,7 @@ async function fetchForumSidebarBaseExact()return {...normalized.base,- threads: registry ? [] : normalized.base.threads,+ threads: [],verifiedEpoch: requestEpoch,}},@@ -604,11 +399,8 @@ function reconcileForumSidebarNotifyMembershipsFromBase() {const channels = getCanonicalCommunityChannels(queryClient)const channelById = new Map(channels.map((channel) => [channel.id, channel]))- const notifyIds = new Set(- getCanonicalCommunityChannelMemberships(queryClient)- .filter((membership) => membership.relation === "notify")- .map((membership) => membership.channelId),- )+ const notifyIds = viewerNotifyChannelIds(getCanonicalCommunityChannelMemberships(queryClient),+ getCommunityDbRegistry(queryClient)?.accountId ?? null)const candidates = channels.filter((channel) => (channel.serverId === serverId&& channel.type === "thread"@@ -713,7 +505,6 @@ export function useForumSidebarThreads(retainId: string | null,enabled = true,) {- const registry = useOptionalCommunityDbRegistry()const restoredForumProjection = useTrustedRestoredForumProjection()const queryClient = useQueryClient()const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)@@ -731,8 +522,7 @@ export function useForumSidebarThreads(const requestEpoch = getCommunityRuntime(queryClient).ws.get().accessEpochconst normalized = await fetchForumSidebar(queryClient, serverId, retainId, signal, token)if (signal.aborted) throw new DOMException("Aborted", "AbortError")- if (registry) {- publishNormalizedForumSidebar(+ publishNormalizedForumSidebar(queryClient,serverId,normalized,@@ -749,7 +539,6 @@ export function useForumSidebarThreads(? normalized.retained?.id ?? null: null,)- }unreadProjection.confirmAccessScopes([...normalized.base.threads,@@ -761,7 +550,7 @@ export function useForumSidebarThreads()return {...normalized.base,- threads: registry ? [] : normalized.base.threads,+ threads: [],verifiedEpoch: requestEpoch,}},@@ -783,15 +572,8 @@ export function useForumSidebarThreads(: clockNowMs + (query.data?.serverClockOffsetMs ?? 0)const canonical = useForumSidebarProjection(serverId, retainId, serverNowMs)const attentionScopes = useAttentionScopes()- const providerless = useMemo(- () => clockNowMs === null- ? { threads: [], parentUnread: {} }- : deriveForumSidebarProjection(query.data, null, undefined, clockNowMs),- [clockNowMs, query.data],- )const projection = useMemo(() => {- const structuralProjection = registry ? canonical ?? { threads: [], parentUnread: {} } : providerless- if (!registry) return structuralProjection+ const structuralProjection = canonical ?? { threads: [], parentUnread: {} }const relevant = attentionScopes.filter((scope) => scope.serverId === serverId)const unreadByScope = new Map(relevant.map((scope) => [scope.scopeId,@@ -812,7 +594,7 @@ export function useForumSidebarThreads(})),parentUnread,}- }, [attentionScopes, registry, serverId, canonical, providerless])+ }, [attentionScopes, serverId, canonical])useEffect(() => {if (serverNowMs === null) return@@ -829,18 +611,14 @@ export function useForumSidebarThreads(return () => globalThis.clearTimeout(timeout)}, [projection.threads, retainId, serverNowMs, setClockNowMs])- deriveView(projection.threads, [registry ? viewEvidence(canonical?.threads) : valueEvidence(queryClient, query.data), viewEvidence(attentionScopes)])+ deriveView(projection.threads, [viewEvidence(canonical?.threads), viewEvidence(attentionScopes)])return {...query,threads: projection.threads,parentUnread: projection.parentUnread,projectionReady: query.isError || (clockNowMs !== null- && (registry- ? query.data !== undefined- || restoredForumProjection- || (canonical?.threads.length ?? 0) > 0- : query.data !== undefined)+ && (query.data !== undefined || restoredForumProjection || (canonical?.threads.length ?? 0) > 0)),verifiedEpoch: accessEpoch,}diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.dom.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.dom.test.tsindex a90f14588..671c9f97b 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.dom.test.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.dom.test.ts@@ -148,6 +148,16 @@ describe("useInboxAutoCollapse", () => {expect(mocks.cancel).not.toHaveBeenCalled()})+ it("keeps a reopened Inbox visible when the consumed opener handoff leaves the same route", async () => {+ const href = "/c/channels/s1/c1"+ const hook = renderInboxHook({ publishedHref: `${href}?inboxThreadOpener=first&keep=1` })+ await hook.call(() => hook.current.onOpenChange(true))+ await hook.rerender({ publishedHref: `${href}?keep=1` })+ expect(hook.current.open).toBe(true)+ await hook.rerender({ publishedHref: `${href}?keep=2` })+ expect(hook.current.open).toBe(false)+ })+it("preserves the latest lease across a shell controller remount", async () => {const queryClient = {} as Options["queryClient"]const href = "/c/channels/s1/c1"diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.tsindex 74db0eee5..7765f5d2c 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts@@ -198,7 +198,7 @@ export function useInboxAutoCollapse({useEffect(() => {const previousHref = previousPublishedHref.get()previousPublishedHref.set(publishedHref)- if (previousHref === publishedHref || !openAtom.get()) return+ if (destinationMatches(previousHref, publishedHref) || !openAtom.get()) returnsetOpen(false)}, [publishedHref, previousPublishedHref, openAtom, setOpen])diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex ae4933d34..8f56df8e0 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -1,6 +1,5 @@"use client"import { useSelector } from "@tanstack/react-store"-import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { deriveView, viewEvidence, valueEvidence } from "@/lib/observability/data-source"@@ -16,7 +15,7 @@ type UseQueryResult,} from "@tanstack/react-query"import { communityRequestOptions } from "@/lib/community-db/sync"import { apiFetch } from "@/lib/api/client"-import { apiFetchProfiles,messageProfilePatches } from "@/lib/community/profile-seed"+import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"import { communityKeys } from "@/lib/query-keys"import type {InboxFriendRequest,@@ -64,7 +63,8 @@ type ProjectedUnreadChannel = UnreadServer["channels"][number]export function useInboxAttention() {const query = useAccountAttentionProjection()const channelsById = useCanonicalChannelsById()- const messagesById = useCanonicalMessagesById()+ const messageIds = useMemo(() => [...new Set(query.items.flatMap((item) => item.messageId ? [item.messageId] : []))], [query.items])+ const messagesById = useCanonicalMessagesById(messageIds)const profilesById = useCanonicalProfilesByUserId()const serversById = useCanonicalServersById()const dmProjection = useDmProjection()@@ -282,20 +282,16 @@ export function useInboxUnreads() {}type MarkedResponse = { marked: Marked[] }-type MarkedWindowResponse = { marked: Array<Omit<Marked, "m"> & { m: { id: string } }> }+type MarkedWindowResponse = { marked: Array<Omit<Marked, "m"> & { m: Pick<Marked["m"], "id"> }> }const inboxMarkedQueryFn = (queryClient: QueryClient) =>async ({ signal }: { signal?: AbortSignal } = {}) => {const publicationToken = captureCommunityLiveSnapshotToken(queryClient)- const data = await apiFetchProfiles<MarkedResponse & { stale?: boolean }>(+ const data = throwIfStale(await apiFetchCommunity<MarkedResponse & { stale?: boolean }>("/api/community/users/me/marks",- (response) => {- throwIfStale(response)- return messageProfilePatches(response.marked.map((marked) => marked.m))- },- signal ? { signal } : undefined, getCommunityDbRegistry(queryClient),- )- if (publicationToken) {+ signal ? { signal } : undefined, publicationToken,+ ))+ {publishCommunityEmbeddedMessages(queryClient, {entries: data.marked.map((marked) => ({channelId: marked.channelId,@@ -304,13 +300,12 @@ const inboxMarkedQueryFn = (queryClient: QueryClient) =>proof: { token: publicationToken, signal },})}- return { marked: throwIfStale(data).marked.map((row) => ({ ...row, m: { id: row.m.id } })) }+ return { marked: data.marked.map((row) => ({ ...row, m: { id: row.m.id } })) }}export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowResponse> & {marked: Marked[]} {- const canonicalMessages = useCanonicalMessagesById()const queryClient = useQueryClient()const unreadProjection = useMemo(() => getActiveAccountUnreadProjection(queryClient),@@ -322,6 +317,8 @@ export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowResplaceholderData: keepPreviousData,enabled,})+ const messageIds = useMemo(() => query.data?.marked.map((row) => row.m.id) ?? [], [query.data?.marked])+ const canonicalMessages = useCanonicalMessagesById(messageIds)const pendingMarks = useMutationState({ filters: { mutationKey: ["community", "mark-command"], status: "pending" }, select: (mutation) => ({ messageId: (mutation.state.variables as { messageId: string }).messageId, marked: mutation.options.mutationKey?.[2] === true }) })const markedAccess = useSelector(unreadProjection.state, (state) => (query.data?.marked ?? []).map((row) => accountUnreadAllowsAccess(state, row)), { compare: (left, right) => left.length === right.length && left.every((value, index) => value === right[index]) })const marked = useMemo(() => {diff --git a/src/web/src/hooks/community/use-machines.ts b/src/web/src/hooks/community/use-machines.tsindex 603578c64..f18d2d59a 100644--- a/src/web/src/hooks/community/use-machines.ts+++ b/src/web/src/hooks/community/use-machines.ts@@ -51,8 +51,7 @@ export type MachineSummary = CommunityMachineSummary & {* live-patch `communityKeys.machines()` via `queryClient.setQueryData` on* `community:machine.*` WS events, so this list stays fresh without a refetch.*/-export type MachineCapacity = MachineCapacitySummary-export type MachinesResponse = { machines: MachineSummary[]; machineCapacity?: MachineCapacity }+export type MachinesResponse = { machines: MachineSummary[]; machineCapacity?: MachineCapacitySummary }export function replaceMachines(data: MachinesResponse, machines: MachineSummary[]): MachinesResponse {return {diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.tsindex 62dea4ad2..7643e8eef 100644--- a/src/web/src/hooks/community/use-message.test.ts+++ b/src/web/src/hooks/community/use-message.test.ts@@ -15,6 +15,18 @@ const payload = {}describe("useMessage / messageQueryFn", () => {+ it("clears absent rich fields from a fresh complete exact response", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ ingestMessages(registry, payload.channelId, [{ ...payload,+ attachments: [{ kind: "file", name: "old.txt", url: "/old", size: "1 KB" }],+ embeds: [{ title: "Old" }], reactions: [{ emoji: "👍", count: 1 }],+ replyTo: { id: "reply", authorName: "Peer", text: "Old reply" },+ }])+ apiFetchMock.mockResolvedValueOnce(payload)+ await client.query({ queryKey: communityKeys.message(payload.id), queryFn: messageQueryFn(payload.id, client) })+ expect(registry.collections.messages.get(payload.id)).toMatchObject({ attachments: [], embeds: [], reactions: [], replyToId: null })+ expect(registry.collections.messages.get(payload.id)?.replyTo).toBeUndefined()+ })it("fetches from /messages/:id and publishes the hydrated payload into canonical DB", async () => {const { client, registry } = await createCommunityQueryOwner()apiFetchMock.mockResolvedValueOnce(payload)diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.tsindex 548f9b5bb..2a8e614d2 100644--- a/src/web/src/hooks/community/use-message.ts+++ b/src/web/src/hooks/community/use-message.ts@@ -1,6 +1,5 @@"use client"import { useSelector } from "@tanstack/react-store"-import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useEffect, useMemo } from "react"@@ -11,7 +10,7 @@ import {type QueryFunctionContext,type UseQueryResult,} from "@tanstack/react-query"-import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"+import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"import { communityKeys } from "@/lib/query-keys"import type { Msg } from "@/lib/community/models/message"import {@@ -42,26 +41,8 @@ import {** Pass a falsy id when there's nothing to load — the query stays disabled.*/-export type OpenerPayload = {- id: string- // Exact-message responses carry their owning surface so a hard-refresh can- // publish an archived opener even when the route model has no parent hint.- // Persisted list-window placeholders predate that response field.- channelId?: string- authorId: string- authorName: string- authorAvatar: string- authorAvatarVersion: number- content: string- // Required, exhaustive (#12) — matches `mapMessageForApi`'s new output- // shape (this payload is fed by that same endpoint, `GET /api/community/messages/:id`).- type: "chat" | "system"- createdAt: string- replyTo?: Msg["replyTo"]- attachments?: Msg["attachments"]- embeds?: Msg["embeds"]- reactions?: Msg["reactions"]-}+export type OpenerPayload = Required<Pick<Msg, "id" | "authorId" | "authorName" | "authorAvatar" | "authorAvatarVersion" | "content" | "type" | "createdAt">>+ & Pick<Msg, "replyTo" | "attachments" | "embeds" | "reactions"> & { channelId?: string }export const messageQueryFn = (messageId: string,@@ -69,17 +50,17 @@ export const messageQueryFn = (channelId?: string,) => async (context: QueryFunctionContext) => {if (context.client !== queryClient) throw new DOMException("Mismatched message query owner", "AbortError")- const token = captureCommunityLiveSnapshotToken(queryClient)- const message = await apiFetchProfiles<OpenerPayload>(+ const token = captureCommunityLiveSnapshotToken(queryClient, channelId)+ const message = await apiFetchCommunity<OpenerPayload>(`/api/community/messages/${messageId}`,- (message) => messageProfilePatches([message]),- context.signal ? { signal: context.signal } : undefined, getCommunityDbRegistry(context.client),+ context.signal ? { signal: context.signal } : undefined, token,)const publishChannelId = message.channelId ?? channelIdif (publishChannelId) {publishCommunityMessages(queryClient, {channelId: publishChannelId,- messages: [message],+ messages: [{ ...message, attachments: message.attachments ?? [], embeds: message.embeds ?? [],+ reactions: message.reactions ?? [], replyTo: message.replyTo }],proof: { token, signal: context.signal },})}@@ -109,7 +90,8 @@ export function useMessage(accessScope?: MessageAccessScope,): UseQueryResult<string> & { message: OpenerPayload | null } {const registry = useOptionalCommunityDbRegistry()- const canonicalMessages = useCanonicalMessagesById()+ const selectedIds = useMemo(() => messageId ? [messageId] : [], [messageId])+ const canonicalMessages = useCanonicalMessagesById(selectedIds)const queryClient = useQueryClient()const accessProjection = useMemo(() => getActiveAccountUnreadProjection(queryClient),diff --git a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsindex 1ca7f75b0..85db8d686 100644--- a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts@@ -930,6 +930,48 @@ describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {renderer.unmount()})+ it("holds an empty messages window through native restore and current read, then sends fresh anchor first", async () => {+ const { client: restoredClient } = await createCommunityQueryOwner("viewer")+ restoredClient.setQueryData(communityKeys.dmReadStateSnapshot("dm_activation"), {+ lastReadMessageId: "m_old", lastReadAt: "2026-08-08T00:00:00.000Z", lastReadSeq: 1,+ })+ const { client: queryClient } = await createCommunityQueryOwner("viewer", {+ defaultOptions: { queries: { refetchOnMount: false, retry: false } },+ })+ const restore = deferred<{ buster: string; clientState: ReturnType<typeof dehydrate>; timestamp: number }>()+ const read = deferred<{ lastReadMessageId: string; lastReadAt: string; lastReadSeq: number }>()+ const messages = deferred<MessagesPage>()+ const persister = {+ persistClient: vi.fn(() => Promise.resolve()), removeClient: vi.fn(() => Promise.resolve()),+ restoreClient: vi.fn(() => restore.promise),+ }+ apiFetchMock.mockImplementation((url: string) => url.endsWith("/read-state") ? read.promise : messages.promise)+ const snapshots: Array<Snapshot & { readStateFetching: boolean }> = []+ const renderer = render(React.createElement(PersistQueryClientProvider, {+ client: queryClient, persistOptions: { buster: "activation", persister },+ }, React.createElement(DmRouteCapture, { onRender: snapshot => snapshots.push(snapshot) })))++ await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)) })+ expect(persister.restoreClient).toHaveBeenCalledTimes(1)+ expect(apiFetchMock).not.toHaveBeenCalled()+ expect(snapshots.at(-1)).toMatchObject({ ids: [], readStateFetching: true })+ await act(async () => { restore.resolve({ buster: "activation", clientState: dehydrate(restoredClient), timestamp: Date.now() }) })+ await waitFor(() => apiFetchMock.mock.calls.some(([url]) => url.endsWith("/read-state")))+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 20)) })+ expect(snapshots.at(-1)).toMatchObject({ ids: [], readStateFetching: true })+ expect(apiFetchMock.mock.calls.filter(([url]) => url.includes("/messages"))).toHaveLength(0)++ await act(async () => { read.resolve({ lastReadMessageId: "m_fresh", lastReadAt: "2026-08-09T00:00:00.000Z", lastReadSeq: 2 }) })+ await waitFor(() => apiFetchMock.mock.calls.some(([url]) => url.includes("/messages")))+ expect(apiFetchMock.mock.calls.filter(([url]) => url.includes("/messages"))).toEqual([+ ["/api/community/channels/dm_activation/messages?anchor=m_fresh", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" })],+ ])+ await act(async () => { messages.resolve({ messages: [{ id: "m_fresh", seq: 2, createdAt: "2026-08-09T00:00:00.000Z" }], hasMoreOlder: false, hasMoreNewer: false, latestSeq: 2 }) })+ await waitFor(() => snapshots.at(-1)?.ids[0] === "m_fresh")+ expect(snapshots.at(-1)?.readStateFetching).toBe(false)+ renderer.unmount()+ })+it("revalidates a warm DM again after an unmount and same-client remount", async () => {const { client: queryClient } = await createCommunityQueryOwner("viewer", {defaultOptions: { queries: { refetchOnMount: false, retry: false } },diff --git a/src/web/src/hooks/community/use-messages.dom.test.ts b/src/web/src/hooks/community/use-messages.dom.test.tsindex b5f07d408..a19d21a55 100644--- a/src/web/src/hooks/community/use-messages.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.dom.test.ts@@ -2,7 +2,7 @@ import { CommunityTestProvider as QueryClientProvider } from "@/test/community-oimport { createCommunityQueryOwner } from "@/test/community-query-owner"import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"import { createElement, type PropsWithChildren } from "react"-import { type InfiniteData } from "@tanstack/react-query"+import { CancelledError, type InfiniteData } from "@tanstack/react-query"import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { CONVERSATION_READ_TIMEOUT_MS, ConversationReadTimeoutError } from "@/lib/community/conversation-read"@@ -398,6 +398,50 @@ describe("mergeMessagesPages", () => {describe("bounded messages publication", () => {+ it.each(["cold", "known", "late-lineage"] as const)("rejects a %s child response after parent retirement without publishing body, window or navigation", async (lineage) => {+ const { channelMessagesQueryFn } = await loadHook()+ const { retireCommunityChannelReading, assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")+ const { client, registry, runtime } = await createCommunityQueryOwner()+ runtime.ws.actions.rememberChannelAccess(null, "sibling-dm")+ const sibling = captureCommunityLiveSnapshotToken(client, "sibling-dm")+ if (lineage === "known") runtime.ws.actions.rememberChannelAccess("server", "child", "parent")+ let resolve!: (value: unknown) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((done) => { resolve = done }))+ const receipt = vi.fn(), key = communityKeys.channelMessages("child")+ const request = client.infiniteQuery({ queryKey: key, queryFn: channelMessagesQueryFn("child", null, { onSurfaceReceipt: receipt }), initialPageParam: { mode: "newest" }, getNextPageParam: () => undefined, retry: false })+ const rejected = lineage === "known" ? expect(request).rejects.toBeInstanceOf(CancelledError) : expect(request).rejects.toMatchObject({ name: "AbortError" })+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())+ retireCommunityChannelReading(registry, "parent", { reason: "read-denied", serverId: "server" })+ if (lineage === "late-lineage") runtime.ws.actions.observeChannelScope("server", "child", "parent")+ resolve({ messages: [{ id: "late-child-message", type: "chat", seq: 1, authorId: "late-author", authorName: "Late", content: "private" }], hasMore: false, latestSeq: 1, surfaceReceipt: { channelId: "child", surfaceKind: "thread" } })+ await rejected+ expect(registry.collections.messages.has("late-child-message")).toBe(false)+ expect(registry.collections.profiles.has("late-author")).toBe(false)+ expect(client.getQueryData(key)).toBeUndefined()+ expect(receipt).not.toHaveBeenCalled()+ expect(() => assertCommunityLiveSnapshotTokenCurrent(client, sibling, undefined)).not.toThrow()+ apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "fresh-child-message", type: "chat", seq: 2, authorId: "fresh-author", authorName: "Fresh", content: "fresh" }], hasMore: false, latestSeq: 2 })+ await client.infiniteQuery({ queryKey: key, queryFn: channelMessagesQueryFn("child"), initialPageParam: { mode: "newest" }, getNextPageParam: () => undefined, retry: false })+ expect(registry.collections.messages.has("fresh-child-message")).toBe(true)+ expect(client.getQueryData(key)).toBeDefined()+ })++ it("publishes an already-qualified sibling DM response across an unrelated parent retirement", async () => {+ const { channelMessagesQueryFn } = await loadHook()+ const { retireCommunityChannelReading } = await import("@/lib/community-db/sync")+ const { client, registry, runtime } = await createCommunityQueryOwner()+ runtime.ws.actions.rememberChannelAccess(null, "sibling-dm")+ let resolve!: (value: unknown) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((done) => { resolve = done }))+ const request = channelMessagesQueryFn("sibling-dm")({ client, pageParam: { mode: "newest" } })+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())+ retireCommunityChannelReading(registry, "parent", { reason: "read-denied", serverId: "server" })+ resolve({ messages: [{ id: "dm-message", type: "chat", seq: 1, authorId: "peer", authorName: "Peer", content: "current" }], hasMore: false, latestSeq: 1 })+ await expect(request).resolves.toMatchObject({ messages: [{ id: "dm-message" }] })+ expect(registry.collections.messages.has("dm-message")).toBe(true)+ expect(registry.collections.profiles.has("peer")).toBe(true)+ })+it("does not publish a late message, profile or navigation receipt after deadline failure", async () => {const { channelMessagesQueryFn } = await loadHook()const { client } = await createCommunityQueryOwner()diff --git a/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts b/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.tsindex c89a90cff..fbdc42cb7 100644--- a/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts@@ -348,11 +348,17 @@ describe("useMessages jumpToPresent", () => {},)- it("resets once, fetches newest once, and keeps the old last-read anchor suppressed", async () => {+ it.each(["legacy", "v2"] as const)("resets once, fetches newest once, and keeps the old last-read anchor suppressed (%s)", async (contract) => {const queryClient = await createClient()const queryKey = communityKeys.channelMessages("channel_1")seedAnchor(queryClient, queryKey, "anchor_1")- apiFetchMock.mockResolvedValue(newestPage("latest_1"))+ const page = newestPage("latest_1")+ if (contract === "v2") {+ delete page.hasMore+ page.hasMoreOlder = false+ page.hasMoreNewer = false+ }+ apiFetchMock.mockResolvedValue(page)const resetSpy = vi.spyOn(queryClient, "resetQueries")let latest!: Snapshotconst onRender = (snapshot: Snapshot) => { latest = snapshot }diff --git a/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts b/src/web/src/hooks/community/use-messages.loading-state.dom.test.tsindex 4fe523b75..37d1b3dc4 100644--- a/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts@@ -10,7 +10,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"import { act, renderHook } from "@/test/react-dom-harness"import { communityKeys } from "@/lib/query-keys"import { useDmMessages, useMessages } from "./use-messages"-import { getMessageOverlay } from "@/stores/community/message-stream"+import { getMessageStreamState } from "@/test/community-query-owner"function dispatchLive(client: QueryClient, scope: MessageScope, event: { type: "wsMessage"; message: CanonicalMessage }) {const registry = getCommunityDbRegistry(client)@@ -95,6 +95,23 @@ describe("useMessages — isLoading while the anchor snapshot is unresolved", ()})describe("useMessages — instant channel switch", () => {+ it.each(["channel", "dm"] as const)("reads one canonical rich body for the %s window and live IDs", async (kind) => {+ const { client, registry } = await createCommunityQueryOwner()+ const scope: MessageScope = kind === "channel" ? { kind, id: "ch_new", serverId: "s1" } : { kind, id: "dm_new" }+ const attachments = [{ kind: "file" as const, name: "notes.txt", url: "/notes.txt", size: "1 KB" }]+ const embeds = [{ title: "Existing embed" }], replyTo = { id: "reply", authorName: "Peer", text: "reply" }+ const message: CanonicalMessage = { id: "rich", seq: 3, type: "chat", authorId: "peer", authorName: "Peer", content: "before", clientNonce: "rich-nonce", createdAt: "2026-08-07T10:00:00.000Z" }+ ingestMessages(registry, scope.id, [{ ...message, attachments, embeds, replyTo }])+ const rendered = kind === "channel" ? await renderChannelMessages(undefined, [{ id: message.id, seq: message.seq }], client) : await renderDmMessages([{ id: message.id, seq: message.seq }], client)+ expect(rendered.result.current.messages).toEqual([expect.objectContaining({ id: message.id, attachments, embeds, replyTo })])+ await act(async () => { dispatchLive(client, scope, { type: "wsMessage", message: { ...message, content: "sparse live" } }) })+ expect(registry.collections.messages.get(message.id)).toMatchObject({ content: "sparse live", attachments, embeds, replyTo })+ expect(rendered.result.current.messages).toEqual([expect.objectContaining({ id: message.id, content: "sparse live", attachments, embeds, replyTo })])+ await act(async () => { dispatchLive(client, scope, { type: "wsMessage", message: { ...message, content: "cleared", attachments: [], embeds: [] } }) })+ expect(registry.collections.messages.get(message.id)).toMatchObject({ attachments: [], embeds: [] })+ expect(rendered.result.current.messages).toEqual([expect.objectContaining({ id: message.id, content: "cleared", attachments: [], embeds: [], replyTo })])+ expect(apiFetchMock).not.toHaveBeenCalled()+ })it("paints a warm cache without waiting on the anchor", async () => {const rendered = await renderChannelMessages(undefined, [{ id: "m_1", seq: 1 },@@ -157,7 +174,7 @@ describe("useMessages — instant channel switch", () => {act(() => getCommunityRuntime(queryClient).messageStream.actions.removeServer("s1"))expect(getCommunityRuntime(queryClient).messageStream.get().entries.size).toBe(0)- expect(getMessageOverlay(queryClient, messageScope).liveById.size).toBe(0)+ expect(getMessageStreamState(queryClient, messageScope).liveIds.length).toBe(0)})})diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex fed61c28e..ba3abece2 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -1,7 +1,6 @@"use client"import { deriveView, mergeEvidence, valueEvidence, viewEvidence } from "@/lib/observability/data-source"import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { getCommunityRuntime } from "@/stores/community/runtime"@@ -19,7 +18,7 @@ import {type QueryClient,} from "@tanstack/react-query"import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"-import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"+import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"import { captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"import { communityKeys } from "@/lib/query-keys"import type {@@ -34,15 +33,15 @@ import {type CanonicalMessage,type MessageScope,} from "@/lib/community/message-stream"-import { useMessageOverlay } from "@/stores/community/message-stream"+import { useMessageOverlayIds } from "@/stores/community/message-stream"import { useCommunityWsStore } from "@/stores/community/ws"import {commitConversationNavigationProof,recordConversationNavigationReceipt,useConversationNavigationGate,} from "@/lib/community/conversation-navigation-proof"-import type { MessageSurfaceReceipt } from "@/lib/community/conversation-navigation-proof"-import { useMessageProjection, useMessageWindowProjection, useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"+import type { CommunityMessageSurfaceReceipt } from "@alook/shared"+import { useMessageWindowProjection } from "@/lib/community-db/projections"import {captureCommunityLiveSnapshotToken,publishCommunityMessages,@@ -70,7 +69,6 @@ import { messageReconcileOptions } from "./community-ws/reconnect-messages"*/export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/message"-export type { MessageSurfaceReceipt } from "@/lib/community/conversation-navigation-proof"type CommittedTransportWindow = {key: string@@ -107,17 +105,17 @@ function useCommittedTransportWindow(}type MessagesTransportPage = WireMessagesPage & {- surfaceReceipt?: MessageSurfaceReceipt+ surfaceReceipt?: CommunityMessageSurfaceReceipt}type MessagesTransportOptions = {- onSurfaceReceipt?: (receipt: MessageSurfaceReceipt) => void+ onSurfaceReceipt?: (receipt: CommunityMessageSurfaceReceipt) => voidqueryClient?: QueryClient}-function isMessageSurfaceReceipt(value: unknown): value is MessageSurfaceReceipt {+function isMessageSurfaceReceipt(value: unknown): value is CommunityMessageSurfaceReceipt {if (!value || typeof value !== "object") return false- const receipt = value as Partial<MessageSurfaceReceipt>+ const receipt = value as Partial<CommunityMessageSurfaceReceipt>return typeof receipt.channelId === "string" && (receipt.surfaceKind === "channel" ||receipt.surfaceKind === "thread" ||@@ -154,11 +152,11 @@ async function fetchMessagesTransport(url: string,signal: AbortSignal | undefined,options: MessagesTransportOptions | undefined,+ token: ReturnType<typeof captureCommunityLiveSnapshotToken>,): Promise<WireMessagesPage> {- const transport = await withConversationReadDeadline(signal, (readSignal) => apiFetchProfiles<MessagesTransportPage>(+ const transport = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesTransportPage>(url,- (page) => messageProfilePatches(page.messages),- { signal: readSignal }, getCommunityDbRegistry(queryClient),+ { signal: readSignal }, token,))const { surfaceReceipt, ...page } = transportif (isMessageSurfaceReceipt(surfaceReceipt)) {@@ -180,13 +178,13 @@ export const channelMessagesQueryFn =}): Promise<MessagesPage> => {const originalClient = options?.queryClient ?? clientif (!originalClient) throw new DOMException("Missing message query owner", "AbortError")- const publicationToken = captureCommunityLiveSnapshotToken(originalClient)+ const publicationToken = captureCommunityLiveSnapshotToken(originalClient, channelId)const url = buildMessagesUrl(`/api/community/channels/${channelId}/messages`,pageParam,tag,)- const page = await fetchMessagesTransport(originalClient, url, signal, options)+ const page = await fetchMessagesTransport(originalClient, url, signal, options, publicationToken){publishCommunityMessages(originalClient, {channelId,@@ -199,32 +197,7 @@ export const channelMessagesQueryFn =export const dmMessagesQueryFn =(dmId: string, options?: MessagesTransportOptions) =>- async ({- pageParam,- signal,- client,- }: {- pageParam: MessagesPageParam- signal?: AbortSignal- client?: QueryClient- }): Promise<MessagesPage> => {- const originalClient = options?.queryClient ?? client- if (!originalClient) throw new DOMException("Missing message query owner", "AbortError")- const publicationToken = captureCommunityLiveSnapshotToken(originalClient)- const url = buildMessagesUrl(- `/api/community/channels/${dmId}/messages`,- pageParam,- )- const page = await fetchMessagesTransport(originalClient, url, signal, options)- {- publishCommunityMessages(originalClient, {- channelId: dmId,- messages: page.messages,- proof: { token: publicationToken, signal },- })- }- return messageWindowPage(page)- }+ channelMessagesQueryFn(dmId, undefined, options)export function messageMatchesTag(message: Msg, tag?: string | null): boolean {return !tag || message.thread?.tags?.includes(tag) === true@@ -427,7 +400,8 @@ function useMessagesInner(signal?: AbortSignal}) => Promise<MessagesPage>,opts: MessagesOpts | undefined,-): MessagesReturn {+ liveIds: readonly string[],+) {const queryClient = useQueryClient()const isRestoring = useIsRestoring()useQuery({ ...messageReconcileOptions(queryClient, scopeId ?? "__none__", queryKey), enabled: false })@@ -689,8 +663,7 @@ function useMessagesInner(if (!jumpPending || !presentOverride) returnconst first = query.data?.pages[0]if (!first) return- const isNewestShape = first.hasMore !== undefined && first.hasMoreOlder === undefined- if (!isNewestShape) return+ if (query.data?.pageParams[0]?.mode !== "newest") returnsnapshotRef.current = nullsetPresentOverride((current) =>current?.attemptId === presentOverride.attemptId@@ -762,7 +735,7 @@ function useMessagesInner(let active = trueconst isCurrent = () => active && isChannelMetadataTokenCurrent(accessToken)&& queryClient.getQueryCache().find({ queryKey, exact: true }) === currentQuery- const accessIdentity = [accessToken.viewerId, accessToken.accountEpoch, accessToken.accessEpoch, accessToken.ownerGeneration, accessToken.generation]+ const accessIdentity = [accessToken.viewerId, accessToken.accountEpoch, accessToken.accessEpoch, accessToken.ownerGeneration, accessToken.channelScopes.get(scopeId!)?.generation ?? 0]const anchorRequestKey = JSON.stringify([queryKey, anchorPageParam, accessIdentity])if (settledAnchorRepairRef.current?.key === anchorRequestKey&& settledAnchorRepairRef.current.query === currentQuery) return@@ -808,10 +781,6 @@ function useMessagesInner(// into a single page — `hasMoreOlder`/`hasMoreNewer` come from the// new anchor page since it alone knows the true state of both// edges relative to the (possibly wider) merged window.- const currentMessages = mergeMessagesPages(current.pages)- const anchorAlreadyPainted = opts?.waitForAnchor === false- && currentMessages.some((message) => message.id === anchorId)- if (anchorAlreadyPainted) return { ...current, pages: [page, ...current.pages], pageParams: [anchorPageParam, ...current.pageParams] }return { ...current, pages: [page, ...current.pages], pageParams: [anchorPageParam, ...current.pageParams] }})})@@ -843,16 +812,20 @@ function useMessagesInner(reconcileLateAnchor,])- const windowIds = useMemo(() => query.data?.pages.flatMap((page) => page.messages.map((message) => message.id)) ?? [], [query.data])- const canonicalRows = useMessageProjection(scopeId, windowIds)+ const transportWindowObserved = useCommittedTransportWindow(queryKey, query.data !== undefined)+ const transportMessages = useMemo(() => query.data ? mergeMessagesPages(query.data.pages) : [], [query.data])+ const windowIds = useMemo(() => transportMessages.map((message) => message.id), [transportMessages])+ const projection = useMessageWindowProjection(scopeId, transportWindowObserved ? windowIds : undefined, liveIds)+ const canonicalById = useMemo(() => new Map((projection.messages ?? []).flatMap((message) =>+ typeof message.seq === "number" ? [[message.id, message as CanonicalMessage] as const] : [])), [projection.messages])const messages = useMemo<Msg[]>(() => {- if (!query.data) return []- const byId = new Map((canonicalRows ?? []).map((message) => [message.id, message]))- const selected = mergeMessagesPages(query.data.pages).flatMap((window) => { const message = byId.get(window.id); return message ? [message] : [] })+ const selected = projection.windowIds.flatMap((id) => { const message = canonicalById.get(id); return message ? [message] : [] }).sort((a, b) => a.seq - b.seq)const root = valueEvidence(queryClient, query.data)- const window = root.source === "unknown" ? mergeEvidence(query.data.pages.map(viewEvidence)) : root+ const window = transportWindowObserved+ ? root.source === "unknown" ? mergeEvidence(query.data?.pages.map(viewEvidence) ?? []) : root+ : mergeEvidence(selected.map(viewEvidence))return deriveView(selected, [window, ...selected.map(viewEvidence)])- }, [query.data, canonicalRows, queryClient])+ }, [query.data, projection.windowIds, canonicalById, queryClient, transportWindowObserved])const latestSeq = useMemo<number>(() => {if (!query.data) return 0@@ -928,6 +901,7 @@ function useMessagesInner(// cache) still shows the skeleton.isLoading: query.isLoading || (!anchorResolved && messages.length === 0),navigationBlocked: false,+ canonicalById,messages,latestSeq,hasMoreOlder,@@ -953,65 +927,34 @@ function useMessagesInner(* Pass `null` for "no active channel" — the query stays disabled. DM views* should call `useDmMessages` instead of this hook.*/-export function useMessages(- channelId: string | null,- opts: ChannelMessagesOpts,-): MessagesReturn {- const registry = useOptionalCommunityDbRegistry()+export function useMessages(channelId: string | null, opts: ChannelMessagesOpts): MessagesReturn {+ return useMessageSurface(channelId, opts, opts.serverId)+}++export function useDmMessages(dmId: string | null, opts?: MessagesOpts): MessagesReturn {+ return useMessageSurface(dmId, opts, null)+}++function useMessageSurface(channelId: string | null, opts: MessagesOpts | ChannelMessagesOpts | undefined, serverId: string | null): MessagesReturn {const queryClient = useQueryClient()const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)+ const tag = opts && "tag" in opts ? opts.tag : undefined+ const kind = serverId === null ? "dm" : "channel"const queryKey = useMemo(() => {+ if (kind === "dm") return communityKeys.dmMessages(channelId ?? "__none__")const baseKey = communityKeys.channelMessages(channelId ?? "__none__")- return opts.tag ? [...baseKey, "tag", opts.tag] as const : baseKey- }, [channelId, opts.tag])- const queryFn = useMemo(- () => channelMessagesQueryFn(channelId ?? "__none__", opts.tag, {- queryClient,- onSurfaceReceipt: (receipt) => {- recordConversationNavigationReceipt(- queryClient,- receipt,- accessEpoch,- )- },- }),- [accessEpoch, channelId, opts.tag, queryClient],- )- const base = useMessagesInner(- channelId,- queryKey,- queryFn,- opts,- )- const transportWindowObserved = useCommittedTransportWindow(- queryKey,- base.data !== undefined,- )- const windowIds = useMemo(() => base.messages.map((message) => message.id), [base.messages])- const dbMessages = useMessageWindowProjection(channelId, transportWindowObserved ? windowIds : undefined)- const canonicalMessagesById = useMemo(() => new Map((dbMessages ?? []).map((message) => [message.id, message])), [dbMessages])- const scope = useMemo<MessageScope>(() => ({- kind: "channel",- id: channelId ?? "__none__",- serverId: opts.serverId,- }), [channelId, opts.serverId])- const overlay = useMessageOverlay(scope)- const canonicalBase = useMemo(- () => {- const messages = !registry- ? base.messages- : !transportWindowObserved- ? dbMessages ?? []- : base.messages.flatMap((message) => {- const canonical = canonicalMessagesById?.get(message.id)- return canonical ? [canonical] : []- })- return messages.filter(- (message): message is CanonicalMessage => typeof message.seq === "number",- )- },- [base.messages, canonicalMessagesById, dbMessages, registry, transportWindowObserved],- )+ return tag ? [...baseKey, "tag", tag] as const : baseKey+ }, [channelId, kind, tag])+ const queryFn = useMemo(() => {+ const options = { queryClient, onSurfaceReceipt: (receipt: CommunityMessageSurfaceReceipt) => recordConversationNavigationReceipt(queryClient, receipt, accessEpoch) }+ return kind === "dm" ? dmMessagesQueryFn(channelId ?? "__none__", options) : channelMessagesQueryFn(channelId ?? "__none__", tag, options)+ }, [accessEpoch, channelId, kind, queryClient, tag])+ const scope = useMemo<MessageScope>(() => serverId === null ? { kind: "dm", id: channelId ?? "__none__" } : { kind: "channel", id: channelId ?? "__none__", serverId }, [channelId, serverId])+ const state = useMessageOverlayIds(scope)+ const base = useMessagesInner(channelId, queryKey, queryFn, opts, state.liveIds)+ const canonicalBase = useMemo(() => base.messages.filter(+ (message): message is CanonicalMessage => typeof message.seq === "number",+ ), [base.messages])useEffect(() => {if (!channelId) returngetCommunityRuntime(queryClient).messageStream.actions.dispatch(scope, {@@ -1020,111 +963,19 @@ export function useMessages(})}, [canonicalBase, channelId, queryClient, scope])const messages = useMemo(- () => materializeMessageStream(canonicalBase, overlay).filter((message) =>- messageMatchesTag(message, opts.tag)),- [canonicalBase, opts.tag, overlay],+ () => materializeMessageStream(canonicalBase, state, base.canonicalById).filter((message) =>+ messageMatchesTag(message, tag)),+ [canonicalBase, tag, state, base.canonicalById],)- deriveView(messages, messages.length ? [viewEvidence(dbMessages), viewEvidence(base.messages), ...messages.map(viewEvidence)] : [viewEvidence(base.data === undefined ? dbMessages : base.messages)])+ deriveView(messages, [viewEvidence(base.messages), ...messages.map(viewEvidence)])useEffect(() => {if (!channelId || base.data === undefined) returncommitConversationNavigationProof(queryClient, channelId, accessEpoch)}, [accessEpoch, base.data, base.dataUpdatedAt, channelId, queryClient])- const navigationGate = useConversationNavigationGate(- queryClient,- opts.viewerUserId ?? "__none__",- channelId ?? "__none__",- accessEpoch,- )- const gated = navigationGate.required && !navigationGate.allowed- return {- ...base,- messages: gated ? [] : messages,- isLoading: (base.isLoading && canonicalBase.length === 0) || gated,- navigationBlocked: gated,- }-}--/**- * DM-scoped sibling of `useMessages`. Same pagination shape, different route.- */-export function useDmMessages(- dmId: string | null,- opts?: MessagesOpts,-): MessagesReturn {- const registry = useOptionalCommunityDbRegistry()- const queryClient = useQueryClient()- const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)- const queryKey = useMemo(- () => communityKeys.dmMessages(dmId ?? "__none__"),- [dmId],- )- const queryFn = useMemo(- () => dmMessagesQueryFn(dmId ?? "__none__", {- queryClient,- onSurfaceReceipt: (receipt) => {- recordConversationNavigationReceipt(- queryClient,- receipt,- accessEpoch,- )- },- }),- [accessEpoch, dmId, queryClient],- )- const base = useMessagesInner(- dmId,- queryKey,- queryFn,- opts,- )- const transportWindowObserved = useCommittedTransportWindow(- queryKey,- base.data !== undefined,- )- const windowIds = useMemo(() => base.messages.map((message) => message.id), [base.messages])- const dbMessages = useMessageWindowProjection(dmId, transportWindowObserved ? windowIds : undefined)- const canonicalMessagesById = useMemo(() => new Map((dbMessages ?? []).map((message) => [message.id, message])), [dbMessages])- const scope = useMemo<MessageScope>(() => ({- kind: "dm",- id: dmId ?? "__none__",- }), [dmId])- const overlay = useMessageOverlay(scope)- const canonicalBase = useMemo(- () => {- const messages = !registry- ? base.messages- : !transportWindowObserved- ? dbMessages ?? []- : base.messages.flatMap((message) => {- const canonical = canonicalMessagesById?.get(message.id)- return canonical ? [canonical] : []- })- return messages.filter(- (message): message is CanonicalMessage => typeof message.seq === "number",- )- },- [base.messages, canonicalMessagesById, dbMessages, registry, transportWindowObserved],- )- useEffect(() => {- if (!dmId) return- getCommunityRuntime(queryClient).messageStream.actions.dispatch(scope, {- type: "baseChanged",- messages: canonicalBase,- })- }, [canonicalBase, dmId, queryClient, scope])- const messages = useMemo(- () => materializeMessageStream(canonicalBase, overlay),- [canonicalBase, overlay],- )- deriveView(messages, messages.length ? [viewEvidence(dbMessages), viewEvidence(base.messages), ...messages.map(viewEvidence)] : [viewEvidence(base.data === undefined ? dbMessages : base.messages)])- useEffect(() => {- if (!dmId || base.data === undefined) return- commitConversationNavigationProof(queryClient, dmId, accessEpoch)- }, [accessEpoch, base.data, base.dataUpdatedAt, dmId, queryClient])const navigationGate = useConversationNavigationGate(queryClient,opts?.viewerUserId ?? "__none__",- dmId ?? "__none__",+ channelId ?? "__none__",accessEpoch,)const gated = navigationGate.required && !navigationGate.alloweddiff --git a/src/web/src/hooks/community/use-read-observer.dom.test.ts b/src/web/src/hooks/community/use-read-observer.dom.test.tsindex 46858a710..4c69f94dc 100644--- a/src/web/src/hooks/community/use-read-observer.dom.test.ts+++ b/src/web/src/hooks/community/use-read-observer.dom.test.ts@@ -63,6 +63,8 @@ vi.mock("./account-unread-projection", async () => ({}))import { useTimelineReadObserver } from "./use-read-observer"+import { useChannelWatermark } from "./use-channel-watermark"+import { useDmWatermark } from "./use-dm-watermark"type ObserverRecord = {callback: IntersectionObserverCallback@@ -260,6 +262,37 @@ describe("useTimelineReadObserver", () => {vi.restoreAllMocks()})+ it.each(["channel", "dm"] as const)("keeps the %s adapter on the common observer intent and lifetime", (kind) => {+ const channelId = `${kind}-1`+ const row = makeRow("message-4")+ const props: Parameters<typeof useChannelWatermark>[0] = {+ channelId,+ messages: [{ id: "message-4", type: "chat", seq: 4, authorId: "other-1", createdAt: "t4" }],+ scrollRootEl: makeRoot([row]),+ snapshotStatus: "ready",+ feedStatus: "ready",+ tailAttached: true,+ confirmedSeq: 2,+ catchUp: () => Promise.resolve(),+ }+ act(() => ingestMessages(owner.registry, channelId, props.messages))+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer-1", retainOwner: true }, children)+ const view = kind === "channel"+ ? renderHook(useChannelWatermark, { wrapper, initialProps: props })+ : renderHook(useDmWatermark, { wrapper, initialProps: { ...props, dmId: channelId, channelId: "other-channel" } })++ expect(coordinator.register).toHaveBeenCalledExactlyOnceWith(queryClient, "viewer-1", { kind: "timeline", channelId })+ expect(coordinator.confirm).toHaveBeenCalledWith({ lease: "timeline" }, 2)+ expect(observers).toHaveLength(1)+ trigger(observers[0]!, row)+ expect(coordinator.submit).toHaveBeenCalledExactlyOnceWith({ lease: "timeline" }, {+ kind: "timeline", channelId, messageId: "message-4", seq: 4,+ })+ view.unmount()+ expect(coordinator.release).toHaveBeenCalledExactlyOnceWith({ lease: "timeline" })+ expect(observers[0]!.disconnected).toBe(true)+ })+it("accepts only after the snapshot-ready observer sees a visible foreign row", () => {useTestRender({ snapshotStatus: "pending" })takeUnmounts()diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.tsindex 9e8ecafd7..40be46da3 100644--- a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts@@ -6,6 +6,42 @@ beforeEach(installMessageScrollFixture)afterEach(restoreMessageScrollFixture)describe("locked native adapter and existing message scroll owner", () => {+ it.each([2, 26])("keeps a present landing after %i frames through consecutive responsive widths", frames => {+ scrollFixture.width = 905+ scrollFixture.height = 783+ scrollFixture.firstPrefix = 193+ const h = mount({ items: Array.from({ length: 28 }, (_, i) => message(`m${i}`)), tailPaddingEnd: 48 })+ h.move(0)+ act(() => scrollFixture.latest.scrollToBottom())+ runFrames(frames)+ scrollFixture.width = 639+ resize(0)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ scrollFixture.width = 265+ scrollFixture.height = 727+ scrollFixture.firstPrefix = 233+ for (const item of h.input.items) scrollFixture.bodyHeights.set(item.m.id, 190)+ h.stage({ tailPaddingEnd: 48 })+ resize()+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ expect(scrollFixture.latest.belowCount).toBe(0)+ })+ it("keeps a landed present intent unreadable until its native row geometry can be confirmed", () => {+ const h = mount()+ h.move(0)+ act(() => scrollFixture.latest.scrollToBottom())+ const pending = Array.from(h.root.querySelectorAll<HTMLElement>("[data-index]"))+ for (const row of pending) Object.defineProperty(row, "getBoundingClientRect", {+ configurable: true, value: () => DOMRect.fromRect(),+ })+ runFrames(3)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ for (const row of pending) Reflect.deleteProperty(row, "getBoundingClientRect")+ resize()+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ })it("keeps an explicit tail scroll when wrapped offscreen rows receive their later native measurements", () => {scrollFixture.width = 639scrollFixture.height = 736@@ -119,6 +155,36 @@ describe("locked native adapter and existing message scroll owner", () => {expect(h.root.scrollTop).toBeLessThan(100)expect(bodyTop(h.root, id)).toBeGreaterThanOrEqual(0)})+ it.each(["target", "unread"])("keeps a newly landed %s origin through consecutive widths and overflow", intent => {+ scrollFixture.width = 905+ scrollFixture.height = 783+ scrollFixture.firstPrefix = 193+ const items = [message("m0"), message("m1"), message("m2")]+ if (intent === "unread") items[0].newDivider = true+ const positioned = vi.fn()+ const h = mount({+ items, hasMoreOlder: false, hasMoreNewer: intent === "unread",+ initialScrollReady: intent !== "unread",+ newDividerBefore: intent === "unread" ? "m0" : undefined,+ onScrollTargetPositioned: positioned,+ })+ h.stage(intent === "target" ? { scrollToMessageId: "m0" } : { initialScrollReady: true })+ runFrames(2)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ if (intent === "target") expect(positioned).toHaveBeenCalledWith("m0")+ expect(h.root.scrollTop).toBe(0)+ scrollFixture.width = 639+ resize(0)+ expect(h.root.scrollTop).toBe(0)+ scrollFixture.width = 265+ scrollFixture.height = 727+ scrollFixture.bodyHeights.set("m2", 900)+ resize()+ expect(h.root.scrollHeight).toBeGreaterThan(h.root.clientHeight)+ expect(h.root.scrollTop).toBe(0)+ expect(bodyTop(h.root, "m0")).toBeGreaterThanOrEqual(0)+ expect(bodyTop(h.root, "m0")).toBeLessThan(h.root.clientHeight)+ })it("unifies native total and DOM max while keeping 40/48px rail clearance", () => {const h = mount()expect(scrollFixture.latest.readPositionReady).toBe(true)diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex fd11dc67c..35e4f77f1 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -401,6 +401,46 @@ export function useScrollAnchor({})virtualizerRef.current = virtualizer+ const readGeometry = useCallback((viewportTransition = false): Geometry | null => {+ const root = scrollRef.current+ const native = virtualizerRef.current+ const owner = positionOwnerRef.current+ const previous = acceptedGeometryRef.current+ const pendingViewportRect = viewportTransition && previous?.epoch === owner.epoch+ && (previous.clientHeight !== root?.clientHeight || previous.clientWidth !== root?.clientWidth)+ && Math.abs((native?.scrollRect?.height ?? 0) - previous.outerHeight) <= 1+ && Math.abs((native?.scrollRect?.width ?? 0) - previous.outerWidth) <= 1+ if (!owner.active || !root || !native || root.clientHeight <= 0+ || Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1+ || (!pendingViewportRect && (Math.abs((native.scrollRect?.height ?? 0) - root.offsetHeight) > 1+ || Math.abs((native.scrollRect?.width ?? 0) - root.offsetWidth) > 1))) return null+ const total = native.getTotalSize()+ const max = Math.max(0, root.scrollHeight - root.clientHeight)+ if (root.scrollTop < 0 || root.scrollTop > max + 1) return null+ const virtualItems = native.getVirtualItems()+ const fold = [...virtualItems].reverse().find((item) => item.start <= root.scrollTop + 1) ?? virtualItems[0]+ if (!fold) return null+ const item = currentItemsRef.current[fold.index]+ const wrapper = root.querySelector<HTMLElement>(`[data-index="${fold.index}"]`)+ const body = wrapper?.querySelector<HTMLElement>("[data-msg-id]")+ if (!item || !wrapper || body?.dataset.msgId !== item.m.id || fold.key !== item.key) return null+ const wrapperRect = wrapper.getBoundingClientRect()+ const bodyRect = body.getBoundingClientRect()+ const viewport = root.getBoundingClientRect()+ if (wrapperRect.height <= 0 || bodyRect.height <= 0+ || Math.abs(wrapperRect.height - fold.size) > 1+ || Math.abs(wrapperRect.top - viewport.top + root.scrollTop - fold.start) > 1) return null+ return {+ epoch: owner.epoch, key: fold.key, prefix: bodyRect.top - wrapperRect.top,+ itemStart: fold.start, clientHeight: root.clientHeight, clientWidth: root.clientWidth,+ outerHeight: root.offsetHeight, outerWidth: root.offsetWidth,+ scrollHeight: root.scrollHeight, scrollTop: root.scrollTop,+ total, paddingEnd: native.options.paddingEnd ?? 0,+ pinEligible: max - root.scrollTop <= 1 && !userScrolledAwayRef.current+ && nativeOriginKeyRef.current !== currentItemsRef.current[0]?.key,+ isScrolling: native.isScrolling,+ }+ }, [])const scheduleInitialPositionSettled = useCallback(() => {if (initialSettleFrameRef.current !== null) returnconst epoch = positionOwnerRef.current.epoch@@ -461,12 +501,14 @@ export function useScrollAnchor({}}intent.stableFrames = landed ? intent.stableFrames + 1 : 0- if (intent.stableFrames >= 2) {+ if (intent.stableFrames >= 2 && intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)+ const geometry = intent.stableFrames >= 2 ? readGeometry() : null+ if (geometry) {settlePresentation()if (owner.kind === "initial" && !initialScrollReadyRef.current) return+ acceptedGeometryRef.current = geometrysemanticIntentRef.current = nullowner.nativeIndex = false- if (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)owner.kind = "idle"setOwnerKind("idle")readReadyRef.current = true@@ -482,7 +524,7 @@ export function useScrollAnchor({initialSettleFrameRef.current = window.requestAnimationFrame(settle)}initialSettleFrameRef.current = window.requestAnimationFrame(settle)- }, [clearBudget, holdNativeOrigin, setOwnerKind, setReadPositionReady, settlePresentation])+ }, [clearBudget, holdNativeOrigin, readGeometry, setOwnerKind, setReadPositionReady, settlePresentation])const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false) => {const owner = positionOwnerRef.current@@ -548,46 +590,6 @@ export function useScrollAnchor({} else if (owner.kind === "initial") armBudget()}, [armBudget, items, scheduleInitialPositionSettled, startIntent])- const readGeometry = useCallback((viewportTransition = false): Geometry | null => {- const root = scrollRef.current- const native = virtualizerRef.current- const owner = positionOwnerRef.current- const previous = acceptedGeometryRef.current- const pendingViewportRect = viewportTransition && previous?.epoch === owner.epoch- && (previous.clientHeight !== root?.clientHeight || previous.clientWidth !== root?.clientWidth)- && Math.abs((native?.scrollRect?.height ?? 0) - previous.outerHeight) <= 1- && Math.abs((native?.scrollRect?.width ?? 0) - previous.outerWidth) <= 1- if (!owner.active || !root || !native || root.clientHeight <= 0- || Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1- || (!pendingViewportRect && (Math.abs((native.scrollRect?.height ?? 0) - root.offsetHeight) > 1- || Math.abs((native.scrollRect?.width ?? 0) - root.offsetWidth) > 1))) return null- const total = native.getTotalSize()- const max = Math.max(0, root.scrollHeight - root.clientHeight)- if (root.scrollTop < 0 || root.scrollTop > max + 1) return null- const virtualItems = native.getVirtualItems()- const fold = [...virtualItems].reverse().find((item) => item.start <= root.scrollTop + 1) ?? virtualItems[0]- if (!fold) return null- const item = currentItemsRef.current[fold.index]- const wrapper = root.querySelector<HTMLElement>(`[data-index="${fold.index}"]`)- const body = wrapper?.querySelector<HTMLElement>("[data-msg-id]")- if (!item || !wrapper || body?.dataset.msgId !== item.m.id || fold.key !== item.key) return null- const wrapperRect = wrapper.getBoundingClientRect()- const bodyRect = body.getBoundingClientRect()- const viewport = root.getBoundingClientRect()- if (wrapperRect.height <= 0 || bodyRect.height <= 0- || Math.abs(wrapperRect.height - fold.size) > 1- || Math.abs(wrapperRect.top - viewport.top + root.scrollTop - fold.start) > 1) return null- return {- epoch: owner.epoch, key: fold.key, prefix: bodyRect.top - wrapperRect.top,- itemStart: fold.start, clientHeight: root.clientHeight, clientWidth: root.clientWidth,- outerHeight: root.offsetHeight, outerWidth: root.offsetWidth,- scrollHeight: root.scrollHeight, scrollTop: root.scrollTop,- total, paddingEnd: native.options.paddingEnd ?? 0,- pinEligible: max - root.scrollTop <= 1 && !userScrolledAwayRef.current- && nativeOriginKeyRef.current !== currentItemsRef.current[0]?.key,- isScrolling: native.isScrolling,- }- }, [])const observeGeometry = useCallback((next: Geometry, scrollEvent = false) => {const previous = acceptedGeometryRef.currentconst previousFold = previous && virtualizerRef.current?.getVirtualItems().find((item) => item.key === previous.key)@@ -712,6 +714,7 @@ export function useScrollAnchor({useLayoutEffect(() => {const root = scrollRef.currentif (!root) return+ const inputOwner = userInputRef.currentconst onScroll = () => {const input = userInputRef.currentconst previous = acceptedGeometryRef.current@@ -808,8 +811,8 @@ export function useScrollAnchor({root.ownerDocument.defaultView?.removeEventListener("blur", onBlur)ro.disconnect()mo?.disconnect()- userInputRef.current.touch = false- userInputRef.current.pointers.clear()+ inputOwner.touch = false+ inputOwner.pointers.clear()}}, [holdNativeOrigin, observeGeometry, readGeometry, reconcileGeometry, releasePosition, scheduleGeometry])diff --git a/src/web/src/hooks/community/use-server-cold.dom.test.tsx b/src/web/src/hooks/community/use-server-cold.dom.test.tsxindex ecd97dcf4..a144aaa39 100644--- a/src/web/src/hooks/community/use-server-cold.dom.test.tsx+++ b/src/web/src/hooks/community/use-server-cold.dom.test.tsx@@ -28,7 +28,7 @@ describe("actual cold server native read", () => {let view!: ReturnType<typeof renderHook<{ server: ReturnType<typeof useServer>; rail: ReturnType<typeof useServers> }, unknown>>try {view = renderHook(() => ({ server: useServer("srv"), rail: useServers() }), { wrapper })- await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/servers")).toHaveLength(1))+ await act(async () => { await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/servers")).toHaveLength(1)) })await act(async () => { await vi.advanceTimersByTimeAsync(CONVERSATION_READ_TIMEOUT_MS) })expect(qc.getQueryState(communityKeys.server("srv"))?.error).toMatchObject({ name: "ConversationReadTimeoutError" })expect(identitySignal.aborted).toBe(false)@@ -56,7 +56,7 @@ describe("actual cold server native read", () => {const wrapper = ({ children }: { children: React.ReactNode }) => <CommunityTestProvider client={qc}>{children}</CommunityTestProvider>const view = renderHook(() => { const server = useServer("srv"); const rail = useServers(); return { server, rail } }, { wrapper })await waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/servers")).toHaveLength(1))- resolve(list)+ await act(async () => { resolve(list) })await waitFor(() => { expect(view.result.current.server.server?.name).toBe("Cold"); expect(view.result.current.rail.servers[0]?.name).toBe("Cold") })})})diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.tsindex f2e94bcd0..f8c19faea 100644--- a/src/web/src/hooks/community/use-servers.dom.test.ts+++ b/src/web/src/hooks/community/use-servers.dom.test.ts@@ -147,7 +147,7 @@ describe("useServers / serversQueryFn", () => {apiFetchMock.mockResolvedValueOnce({ servers: [] })const rendered = renderHook(() => useServers(), { wrapper: Owner })await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))- act(() => registry.runtime.ws.actions.revokeChannelAccess("s1", "c1"))+ act(() => registry.runtime.ws.actions.revokeServerAccess("s1"))await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(false))})diff --git a/src/web/src/hooks/use-native-mutation-facade.ts b/src/web/src/hooks/use-native-mutation-facade.tsindex 238a2533c..56019b43d 100644--- a/src/web/src/hooks/use-native-mutation-facade.ts+++ b/src/web/src/hooks/use-native-mutation-facade.ts@@ -7,12 +7,18 @@ export function useNativeMutationFacade<Data, Error, Input, Intent, Context>(native: UseMutationResult<Data, Error, Intent, Context>,capture: (input: Input) => Intent,assertCurrent: (intent: Intent) => void,+ policy?: {+ projectInput?: (intent: Intent) => Input+ assertSuccess?: (intent: Intent) => void+ },) {+ const projectInput = policy?.projectInput+ const assertSuccess = policy?.assertSuccessconst qualify = useCallback((input: Input, callbacks?: MutateOptions<Data, Error, Input, Context>): MutateOptions<Data, Error, Intent, Context> | undefined => callbacks && ({- onSuccess: (data, intent, result, context) => { try { assertCurrent(intent) } catch { return } callbacks.onSuccess?.(data, input, result, context) },- onError: (error, intent, result, context) => { try { assertCurrent(intent) } catch { return } callbacks.onError?.(error, input, result, context) },- onSettled: (data, error, intent, result, context) => { try { assertCurrent(intent) } catch { return } callbacks.onSettled?.(data, error, input, result, context) },- }), [assertCurrent])+ onSuccess: (data, intent, result, context) => { try { (assertSuccess ?? assertCurrent)(intent) } catch { return } callbacks.onSuccess?.(data, projectInput ? projectInput(intent) : input, result, context) },+ onError: (error, intent, result, context) => { try { assertCurrent(intent) } catch { return } callbacks.onError?.(error, projectInput ? projectInput(intent) : input, result, context) },+ onSettled: (data, error, intent, result, context) => { try { (error === null && assertSuccess ? assertSuccess : assertCurrent)(intent) } catch { return } callbacks.onSettled?.(data, error, projectInput ? projectInput(intent) : input, result, context) },+ }), [assertCurrent, assertSuccess, projectInput])const nativeMutate = native.mutate, nativeMutateAsync = native.mutateAsyncconst mutate = useCallback((input: Input, callbacks?: MutateOptions<Data, Error, Input, Context>) => nativeMutate(capture(input), qualify(input, callbacks)), [nativeMutate, capture, qualify])const mutateAsync = useCallback((input: Input, callbacks?: MutateOptions<Data, Error, Input, Context>) => nativeMutateAsync(capture(input), qualify(input, callbacks)), [nativeMutateAsync, capture, qualify])diff --git a/src/web/src/lib/account-cache-lifecycle.dom.test.tsx b/src/web/src/lib/account-cache-lifecycle.dom.test.tsxindex c96cbf07b..fa3862bc3 100644--- a/src/web/src/lib/account-cache-lifecycle.dom.test.tsx+++ b/src/web/src/lib/account-cache-lifecycle.dom.test.tsx@@ -7,7 +7,7 @@ import { useMutation } from "@tanstack/react-query"import { act, render, waitFor } from "@/test/react-dom-harness"import { PublicQueryProvider, useApplicationOwner, runApplicationRequest, type ApplicationOwner } from "./application-owner"import { apiFetch } from "./api/client"-import { clearAllPersistedCaches, clearPersistedCache, createIdbPersister, CACHE_INVALIDATION_STORAGE_KEY } from "./query-persister"+import { PERSIST_BUSTER, clearAllPersistedCaches, clearPersistedCache, createIdbPersister, CACHE_INVALIDATION_STORAGE_KEY } from "./query-persister"const identity = vi.hoisted(() => ({ id: "A" }))vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: identity.id } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))@@ -23,7 +23,7 @@ function Probe({ name }: { name: string }) {return <output>{name}</output>}function App({ user = identity.id, name = user }: { user?: string; name?: string }) { return <PublicQueryProvider><Probe name={name} /></PublicQueryProvider> }-const persisted = { timestamp: Date.now(), buster: "v3", clientState: { queries: [], mutations: [] } }+const persisted = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { queries: [], mutations: [] } }beforeEach(async () => {await act(async () => { await clearAllPersistedCaches(); }) ; identity.id = "A"; for (const key of Object.keys(owners)) delete owners[key]; for (const key of Object.keys(commands)) delete commands[key]assign = vi.fn(); reload = vi.fn(); const real = windowdiff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.tsindex 14672fb3e..1ccc00900 100644--- a/src/web/src/lib/api/client.ts+++ b/src/web/src/lib/api/client.ts@@ -1,3 +1,5 @@+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } from "@alook/shared"+import { communityReadTarget, decodeCommunityReadResponse } from "@/lib/community/read-response"import { createStore } from "@tanstack/store";import { ApiError, UnauthorizedError, isAbortError } from "@/lib/errors";import { startRequest, requestHeaders, requestRejected, finishRequest, readObservedResponse, runObservedFetch, type RequestObservation } from "@/lib/observability/requests";@@ -104,9 +106,11 @@ async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions,try {assertEligible();const headers = new Headers(request.headers);+ if (communityReadTarget(path, request.method) && !headers.has(COMMUNITY_CONTRACT_HEADER)) headers.set(COMMUNITY_CONTRACT_HEADER, String(COMMUNITY_CONTRACT_VERSION));if (!headers.has("Content-Type") && !(typeof FormData !== "undefined" && request.body instanceof FormData)) headers.set("Content-Type", "application/json");res = await runObservedFetch(observation, () => fetch(API_BASE + path, {...request,+ ...(path.startsWith("/api/community/") ? { cache: "no-store" as const } : {}),credentials: "include",headers,}));@@ -132,8 +136,8 @@ async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions,let serverError: string | undefined;let details: string[] | undefined;try {- const body = (await res.json()) as { error?: string; details?: string[] };- serverError = body.error;+ const body = (await res.json()) as { error?: string | { message?: string }; details?: string[] };+ serverError = typeof body.error === "string" ? body.error : body.error?.message;details = body.details;} catch {// non-JSON body (HTML from proxy, empty body, etc.)@@ -167,7 +171,7 @@ async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions,export async function apiFetch<T>(path: string, options?: ApiRequestOptions): Promise<T> {const res = await apiFetchResponse(path, options, true);if (res.status === 204) return readObservedResponse(res, async () => undefined as T);- const data = await readObservedResponse(res, () => res.json() as Promise<T>, () => {+ const data = await readObservedResponse(res, async () => decodeCommunityReadResponse(path, options?.method, res, await res.json()) as T, () => {options?.assertActive?.();if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");});diff --git a/src/web/src/lib/broadcast.test.ts b/src/web/src/lib/broadcast.test.tsindex de7631945..ac2ba702b 100644--- a/src/web/src/lib/broadcast.test.ts+++ b/src/web/src/lib/broadcast.test.ts@@ -271,6 +271,17 @@ describe("broadcastToUser", () => {},)+ it.each([undefined, "1", "2"])("projects committed membership for producer contract %s before transport", async contract => {+ const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))+ mockGetCloudflareContext.mockReturnValue({ env: { ...makeEnv(bindingFetch), COMMUNITY_EVENT_CONTRACT: contract }, ctx: { waitUntil: mockCtxWaitUntil } })+ const event = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "viewer", relation: "notify", present: true } as const+ await broadcastToUser("viewer", event)+ expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual(contract === "2" ? event+ : { type: "community:channel.member_add", channelId: "thread", serverId: "server", userId: "viewer" })+ expect(bindingFetch).toHaveBeenCalledTimes(1)+ expect(mockFetch).not.toHaveBeenCalled()+ })+it("rejects invalid community targets and payloads before transport", async () => {const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))mockGetCloudflareContext.mockReturnValue({diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.tsindex 748be39ce..98df7a8bc 100644--- a/src/web/src/lib/broadcast.ts+++ b/src/web/src/lib/broadcast.ts@@ -9,11 +9,19 @@ import {isValidCommunityUserTarget,} from "@alook/shared"import { fetchViaBindingOrDevFallback } from "./dev-binding-fetch"+import { projectCommunityProducerEvent } from "./community/producer-contract"const log = createLogger({ service: "broadcast" })const bulkBroadcastMaxUserIds = 1000const bulkBroadcastMaxActive = 3+function encodeCommunityProducerEvent(message: unknown) {+ const encoded = encodeCommunityBrowserEvent(message)+ if (!encoded.ok || encoded.event.type !== "community:channel.membership.change") return encoded+ const { env } = getCloudflareContext()+ return encodeCommunityBrowserEvent(projectCommunityProducerEvent(encoded.event, env as Env))+}+/*** Fetch against the WS DO worker.*@@ -136,7 +144,7 @@ async function runBroadcastToUsers()) {throw new Error("invalid community broadcast target")}- const encoded = community ? encodeCommunityBrowserEvent(message) : null+ const encoded = community ? encodeCommunityProducerEvent(message) : nullif (encoded && !encoded.ok) throw new Error(`invalid community event: ${encoded.reason}`)const wireMessage = encoded?.event ?? messageconst chunks: string[][] = []@@ -220,7 +228,7 @@ export function broadcastToUser(userId: string, message: WsMessage): Promise<voiif (!isValidCommunityUserTarget(userId)) {return Promise.reject(new Error("invalid community broadcast target"))}- const encoded = encodeCommunityBrowserEvent(message)+ const encoded = encodeCommunityProducerEvent(message)if (!encoded.ok) return Promise.reject(new Error(`invalid community event: ${encoded.reason}`))return sendBroadcast(`/broadcast/community/user/${encodeCommunityUserTargetPathSegment(userId)}`,diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.tsindex d421e2308..e8028d9a8 100644--- a/src/web/src/lib/community-db/collections.ts+++ b/src/web/src/lib/community-db/collections.ts@@ -1,9 +1,11 @@-import { clearPersistedCache } from "@/lib/query-persister"+import type { z } from "zod"+import { clearPersistedCache, type QualifiedPersister } from "@/lib/query-persister"import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"import {DbClient,BasicIndex,collectionOptions,+ type InferSchemaOutput,} from "@tanstack/react-db"import { queryCollectionOptions } from "@tanstack/query-db-collection"import type { QueryClient, QueryFunctionContext } from "@tanstack/react-query"@@ -31,20 +33,6 @@ import {readStateSchema,serverMembershipSchema,serverSchema,- type CategoryRow,- type AttentionItemRow,- type AttentionScopeRow,- type ChannelMembershipRow,- type ChannelRow,- type FolderItemRow,- type FolderRow,- type MessageRow,- type FriendshipRow,- type NotificationSettingRow,- type ProfileRow,- type ReadStateClockRow,- type ReadStateRow,- type ServerMembershipRow,type ServerRow,} from "./schema"@@ -89,206 +77,32 @@ function buildCommunityDbRegistry(return restoredRows<T>(queryClient, scopeId, name)}- const servers = dbClient.collection(collectionOptions("community-db-servers", () => ({- ...queryCollectionOptions({- id: "community-db-servers",- queryClient,- queryKey: collectionQueryKey(scopeId, "servers"),- queryFn: queryFnFor<ServerRow>("servers"),- schema: serverSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const categories = dbClient.collection(collectionOptions("community-db-categories", () => ({- ...queryCollectionOptions({- id: "community-db-categories",- queryClient,- queryKey: collectionQueryKey(scopeId, "categories"),- queryFn: queryFnFor<CategoryRow>("categories"),- schema: categorySchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const channels = dbClient.collection(collectionOptions("community-db-channels", () => ({- ...queryCollectionOptions({- id: "community-db-channels",- queryClient,- queryKey: collectionQueryKey(scopeId, "channels"),- queryFn: queryFnFor<ChannelRow>("channels"),- schema: channelSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const serverMemberships = dbClient.collection(collectionOptions("community-db-server-memberships", () => ({- ...queryCollectionOptions({- id: "community-db-server-memberships",- queryClient,- queryKey: collectionQueryKey(scopeId, "serverMemberships"),- queryFn: queryFnFor<ServerMembershipRow>("serverMemberships"),- schema: serverMembershipSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const channelMemberships = dbClient.collection(collectionOptions("community-db-channel-memberships", () => ({- ...queryCollectionOptions({- id: "community-db-channel-memberships",- queryClient,- queryKey: collectionQueryKey(scopeId, "channelMemberships"),- queryFn: queryFnFor<ChannelMembershipRow>("channelMemberships"),- schema: channelMembershipSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const profiles = dbClient.collection(collectionOptions("community-db-profiles", () => ({- ...queryCollectionOptions({- id: "community-db-profiles",- queryClient,- queryKey: collectionQueryKey(scopeId, "profiles"),- queryFn: queryFnFor<ProfileRow>("profiles"),- schema: profileSchema,- getKey: (row) => row.userId,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const messages = dbClient.collection(collectionOptions("community-db-messages", () => ({- ...queryCollectionOptions({- id: "community-db-messages",- queryClient,- queryKey: collectionQueryKey(scopeId, "messages"),- queryFn: queryFnFor<MessageRow>("messages"),- schema: messageSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const readStates = dbClient.collection(collectionOptions("community-db-read-states", () => ({- ...queryCollectionOptions({- id: "community-db-read-states",- queryClient,- queryKey: collectionQueryKey(scopeId, "readStates"),- queryFn: queryFnFor<ReadStateRow>("readStates"),- schema: readStateSchema,- getKey: (row) => row.channelId,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const readStateClock = dbClient.collection(collectionOptions("community-db-read-state-clock", () => ({- ...queryCollectionOptions({- id: "community-db-read-state-clock",- queryClient,- queryKey: collectionQueryKey(scopeId, "readStateClock"),- queryFn: queryFnFor<ReadStateClockRow>("readStateClock"),- schema: readStateClockSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const attentionScopes = dbClient.collection(collectionOptions("community-db-attention-scopes", () => ({- ...queryCollectionOptions({- id: "community-db-attention-scopes",- queryClient,- queryKey: collectionQueryKey(scopeId, "attentionScopes"),- queryFn: queryFnFor<AttentionScopeRow>("attentionScopes"),- schema: attentionScopeSchema,- getKey: (row) => row.scopeId,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const attentionItems = dbClient.collection(collectionOptions("community-db-attention-items", () => ({- ...queryCollectionOptions({- id: "community-db-attention-items",- queryClient,- queryKey: collectionQueryKey(scopeId, "attentionItems"),- queryFn: queryFnFor<AttentionItemRow>("attentionItems"),- schema: attentionItemSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const folders = dbClient.collection(collectionOptions("community-db-folders", () => ({- ...queryCollectionOptions({- id: "community-db-folders",- queryClient,- queryKey: collectionQueryKey(scopeId, "folders"),- queryFn: queryFnFor<FolderRow>("folders"),- schema: folderSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const folderItems = dbClient.collection(collectionOptions("community-db-folder-items", () => ({- ...queryCollectionOptions({- id: "community-db-folder-items",- queryClient,- queryKey: collectionQueryKey(scopeId, "folderItems"),- queryFn: queryFnFor<FolderItemRow>("folderItems"),- schema: folderItemSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))- const notificationSettings = dbClient.collection(collectionOptions("community-db-notification-settings", () => ({- ...queryCollectionOptions({- id: "community-db-notification-settings",- queryClient,- queryKey: collectionQueryKey(scopeId, "notificationSettings"),- queryFn: queryFnFor<NotificationSettingRow>("notificationSettings"),- schema: notificationSettingSchema,- getKey: (row) => row.id,- staleTime: Infinity,- gcTime: QUERY_CACHE_GC_TIME,- persistedGcTime: QUERY_CACHE_GC_TIME,- }),- gcTime: 0,- })))-- const friendships = dbClient.collection(collectionOptions("community-db-friendships", () => ({- ...queryCollectionOptions({ id: "community-db-friendships", queryClient, queryKey: collectionQueryKey(scopeId, "friendships"), queryFn: queryFnFor<FriendshipRow>("friendships"), schema: friendshipSchema, getKey: (row) => row.id, staleTime: Infinity, gcTime: QUERY_CACHE_GC_TIME, persistedGcTime: QUERY_CACHE_GC_TIME }), gcTime: 0,- })))+ const collectionFor = <S extends z.ZodType<Record<string, unknown>, Record<string, unknown>>>(name: string, schema: S, getKey: (row: InferSchemaOutput<S>) => string) => {+ const id = `community-db-${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`+ return dbClient.collection(collectionOptions({+ ...queryCollectionOptions<S, unknown, ReturnType<typeof collectionQueryKey>, string>({+ id, queryClient, schema, getKey,+ queryKey: collectionQueryKey(scopeId, name), queryFn: queryFnFor<InferSchemaOutput<S>>(name),+ staleTime: Infinity, gcTime: QUERY_CACHE_GC_TIME, persistedGcTime: QUERY_CACHE_GC_TIME,+ }),+ gcTime: 0,+ }))+ }+ const servers = collectionFor("servers", serverSchema, (row) => row.id)+ const categories = collectionFor("categories", categorySchema, (row) => row.id)+ const channels = collectionFor("channels", channelSchema, (row) => row.id)+ const serverMemberships = collectionFor("serverMemberships", serverMembershipSchema, (row) => row.id)+ const channelMemberships = collectionFor("channelMemberships", channelMembershipSchema, (row) => row.id)+ const profiles = collectionFor("profiles", profileSchema, (row) => row.userId)+ const messages = collectionFor("messages", messageSchema, (row) => row.id)+ const readStates = collectionFor("readStates", readStateSchema, (row) => row.channelId)+ const readStateClock = collectionFor("readStateClock", readStateClockSchema, (row) => row.id)+ const attentionScopes = collectionFor("attentionScopes", attentionScopeSchema, (row) => row.scopeId)+ const attentionItems = collectionFor("attentionItems", attentionItemSchema, (row) => row.id)+ const folders = collectionFor("folders", folderSchema, (row) => row.id)+ const folderItems = collectionFor("folderItems", folderItemSchema, (row) => row.id)+ const notificationSettings = collectionFor("notificationSettings", notificationSettingSchema, (row) => row.id)+ const friendships = collectionFor("friendships", friendshipSchema, (row) => row.id)const collections = {servers,@@ -312,18 +126,19 @@ function buildCommunityDbRegistry(type CollectionName = keyof typeof collectionsconst restoration = createStore({ captured: false, names: new Set<string>(), hasData: false })const runtime = {- ui: createCommunityStore(), ws: createCommunityWsStore(accountId), messageStream: createMessageStreamStore(() => new Map(Array.from(messages.values()).flatMap((message) => typeof message.seq === "number" ? [[message.id, message as CanonicalMessage] as const] : [])), queryClient),+ ui: createCommunityStore(), ws: createCommunityWsStore(accountId), messageStream: createMessageStreamStore(() => ({ get: (id) => { const message = messages.get(id); return typeof message?.seq === "number" ? message as CanonicalMessage : undefined } }), queryClient),serverEject: createOwnerServerDeleteStore(),lifecycle: createStore({ active: true, generation: 0 }), transport: { send: null as ((message: object) => void) | null },}- const authenticationBindings = createStore({ retireDisk: () => clearPersistedCache(accountId), sessionViewer: () => accountId as string | null | undefined })+ const authenticationBindings = createStore({ retireDisk: () => clearPersistedCache(accountId), retireReadingDisk: (() => Promise.resolve()) as QualifiedPersister["retireChannels"], sessionViewer: () => accountId as string | null | undefined })const registry = {accountId,authenticationView: createStore({ active: false, generation: 0 }),retireDisk: () => authenticationBindings.get().retireDisk(),+ retireReadingDisk: (ids: Iterable<string>, deleted = false) => authenticationBindings.get().retireReadingDisk(ids, deleted),sessionViewer: () => authenticationBindings.get().sessionViewer(),- bindAuthentication: (sessionViewer: () => string | null | undefined, retireDisk: () => Promise<void>) => authenticationBindings.setState(() => ({ sessionViewer, retireDisk })),+ bindAuthentication: (sessionViewer: () => string | null | undefined, retireDisk: () => Promise<void>, retireReadingDisk: QualifiedPersister["retireChannels"] = () => Promise.resolve()) => authenticationBindings.setState(() => ({ sessionViewer, retireDisk, retireReadingDisk })),scopeId,queryClient,dbClient,diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.tsindex d0459157b..fb2c12113 100644--- a/src/web/src/lib/community-db/projections.dom.test.ts+++ b/src/web/src/lib/community-db/projections.dom.test.ts@@ -15,7 +15,6 @@ import {useDmProjection,useMessageProjection,useNotificationSettingsProjection,- useReadStateProjection,useRouteChannelProjection,useServerRailProjection,useServerTreeProjection,@@ -24,6 +23,50 @@ import {import { ingestMessages, ingestServerDetail, ingestServers } from "./sync"describe("community DB projections", () => {+ it("keeps disabled channel arrays unresolved and active empty selections empty while restore is pending", async () => {+ const client = new QueryClient()+ let release!: () => void+ const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>((resolve) => { release = resolve }) })+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(+ QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children),+ )+ const observations: Array<{ array: ReturnType<typeof useMessageProjection>; map: ReturnType<typeof useCanonicalMessagesById> }> = []+ const rendered = renderHook(() => {+ const array = useMessageProjection("c1", ["selected"]), map = useCanonicalMessagesById(["selected"])+ observations.push({ array, map })+ return { array, map, nullScope: useMessageProjection(null), emptyScope: useMessageProjection("") }+ }, { wrapper })+ try {+ expect(observations[0]?.array).toEqual([])+ expect(observations[0]?.map?.size).toBe(0)+ await act(async () => { release(); await registry.preload() })+ await waitFor(() => expect(rendered.result.current.array).toEqual([]))+ expect(rendered.result.current.map?.size).toBe(0)+ expect(rendered.result.current.nullScope).toBeUndefined()+ expect(rendered.result.current.emptyScope).toBeUndefined()+ } finally { release(); rendered.unmount(); await registry.cleanup(); client.clear() }+ })+ it("projects only selected message IDs, observes their updates and selects none for an empty window", async () => {+ const client = new QueryClient()+ const registry = createCommunityDbRegistry(client, "viewer")+ await registry.preload()+ ingestMessages(registry, "c1", [{ id: "selected", type: "chat", content: "Before" }])+ ingestMessages(registry, "other", [{ id: "unrelated", type: "chat", content: "Foreign" }])+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(+ QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children),+ )+ const rendered = renderHook(({ ids }: { ids: readonly string[] }) => useCanonicalMessagesById(ids), {+ wrapper, initialProps: { ids: ["selected"] },+ })+ try {+ await waitFor(() => expect([...rendered.result.current?.keys() ?? []]).toEqual(["selected"]))+ act(() => ingestMessages(registry, "c1", [{ id: "selected", type: "chat", content: "After" }]))+ await waitFor(() => expect(rendered.result.current?.get("selected")?.content).toBe("After"))+ expect(registry.collections.messages.get("unrelated")?.content).toBe("Foreign")+ rendered.rerender({ ids: [] })+ await waitFor(() => expect(rendered.result.current?.size).toBe(0))+ } finally { rendered.unmount(); await registry.cleanup(); client.clear() }+ })it("keeps a surviving StrictMode consumer live and cleans derived queries before their owner facts", async () => {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })const registry = createCommunityDbRegistry(client, "viewer")@@ -101,7 +144,6 @@ describe("community DB projections", () => {messages: useMessageProjection("c1"),messagesById: useCanonicalMessagesById(),notifications: useNotificationSettingsProjection(),- readState: useReadStateProjection("c1"),directory: useChannelRefDirectoryProjection(),}))@@ -114,7 +156,6 @@ describe("community DB projections", () => {messages: undefined,messagesById: undefined,notifications: undefined,- readState: undefined,directory: undefined,})rendered.unmount()@@ -366,7 +407,6 @@ describe("community DB projections", () => {messages: useMessageProjection("c1"),messagesById: useCanonicalMessagesById(),notifications: useNotificationSettingsProjection(),- readState: useReadStateProjection("c1"),profiles: useCanonicalProfilesByUserId(),profile: useCanonicalCommunityProfile("peer"),directory: useChannelRefDirectoryProjection(),@@ -405,7 +445,7 @@ describe("community DB projections", () => {server: { s1: "All Messages" },channel: { c1: "Only @mentions" },})- expect(rendered.result.current.readState).toEqual({+ expect(registry.collections.readStates.get("c1")).toMatchObject({lastReadMessageId: "m1",lastReadAt: "2026-09-25T00:00:01.000Z",lastReadSeq: 1,diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.tsindex cdc7d01d0..822f4c49a 100644--- a/src/web/src/lib/community-db/projections.ts+++ b/src/web/src/lib/community-db/projections.ts@@ -2,11 +2,11 @@import { createContext, createElement, useContext, useMemo, type Context, type ReactNode } from "react"import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/application-owner"-import { DbProvider, collectionOptions, getLiveQueryHash, liveQueryCollectionOptions, prepareLiveQueryValue, eq, inArray, useLiveQuery as useNativeLiveQuery, type Context as QueryContext, type LiveQueryCollectionConfig } from "@tanstack/react-db"+import { DbProvider, collectionOptions, getLiveQueryHash, liveQueryCollectionOptions, prepareLiveQueryValue, and, eq, inArray, useLiveQuery as useNativeLiveQuery, type Context as QueryContext, type LiveQueryCollectionConfig, type WhereCallback, type ContextFromSource } from "@tanstack/react-db"import { createStore, useSelector } from "@tanstack/react-store"import { CommunityRuntimeProvider } from "@/stores/community/runtime"import { notifLevelDisplay } from "@alook/shared"-import { FORUM_ARCHIVE_TAG } from "@alook/shared/constants/community"+import { projectForumSidebar } from "@/lib/community/forum-sidebar"import { avatarInitial } from "@/lib/community/avatar"import type { DM } from "@/lib/community/models/people"import { sortDmsByActivity } from "@/lib/community/dm-order"@@ -20,19 +20,13 @@ import { MAX_PERSISTED_MESSAGES_PER_SCOPE } from "@/lib/query-persister"import { collectionEvidence, deriveView, sourceEvidence, tagView, viewEvidence } from "@/lib/observability/data-source"import type {+ CommunityCollectionName,+ CommunityCollectionRows,AttentionItemRow,AttentionScopeRow,- CategoryRow,- ChannelMembershipRow,ChannelRow,FolderItemRow,- FolderRow,MessageRow,- FriendshipRow,- NotificationSettingRow,- ProfileRow,- ReadStateRow,- ServerMembershipRow,ServerRow,} from "./schema"@@ -115,99 +109,46 @@ export function CommunityDbProvider({)}-function useServerRows(serverId?: string) {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ server: registry.collections.servers }).where(({ server }) => serverId === undefined ? eq(1, 1) : eq(server.id, serverId))- : undefined,- }).data as ServerRow[] | undefined- return annotateRows(registry, "servers", data)-}+type CollectionWhere<N extends CommunityCollectionName> = WhereCallback<ContextFromSource<{ row: CommunityDbRegistry["collections"][N] }>>-function useCategoryRows(serverId?: string) {+function useCollectionQuery<N extends CommunityCollectionName>(name: N, where?: CollectionWhere<N>, enabled = true) {const registry = useOptionalCommunityDbRegistry()const data = useLiveQuery({- query: (q) => registry- ? q.from({ category: registry.collections.categories }).where(({ category }) => serverId === undefined ? eq(1, 1) : eq(category.serverId, serverId))- : undefined,- }).data as CategoryRow[] | undefined- return annotateRows(registry, "categories", data)+ query: (q) => {+ if (!registry || !enabled) return undefined+ const query = q.from({ row: registry.collections[name] })+ return where ? query.where(where) : query+ },+ }).data as CommunityCollectionRows[N][] | undefined+ return { registry, data }}-function useServerMembershipRows() {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ membership: registry.collections.serverMemberships })- : undefined,- }).data as ServerMembershipRow[] | undefined- return annotateRows(registry, "serverMemberships", data)+function useCollectionRows<N extends CommunityCollectionName>(name: N, where?: CollectionWhere<N>) {+ const { registry, data } = useCollectionQuery(name, where)+ return annotateRows(registry, name, data)}-function useFolderRows() {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ folder: registry.collections.folders })- : undefined,- }).data as FolderRow[] | undefined- return annotateRows(registry, "folders", data)-}--function useFolderItemRows() {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ item: registry.collections.folderItems })- : undefined,- }).data as FolderItemRow[] | undefined- return annotateRows(registry, "folderItems", data)+function useServerRows(serverId?: string) {+ return useCollectionRows("servers", ({ row }) => serverId === undefined ? eq(1, 1) : eq(row.id, serverId))}--function useNotificationSettingRows() {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ setting: registry.collections.notificationSettings })- : undefined,- }).data as NotificationSettingRow[] | undefined- return annotateRows(registry, "notificationSettings", data)+function useCategoryRows(serverId?: string) {+ return useCollectionRows("categories", ({ row }) => serverId === undefined ? eq(1, 1) : eq(row.serverId, serverId))}-+function useServerMembershipRows() { return useCollectionRows("serverMemberships") }+function useFolderRows() { return useCollectionRows("folders") }+function useFolderItemRows() { return useCollectionRows("folderItems") }+function useNotificationSettingRows() { return useCollectionRows("notificationSettings") }function useChannelRows(serverId?: string, type?: ChannelRow["type"]) {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => {- if (!registry) return undefined- let query = q.from({ channel: registry.collections.channels })- if (serverId !== undefined) query = query.where(({ channel }) => eq(channel.serverId, serverId))- if (type !== undefined) query = query.where(({ channel }) => eq(channel.type, type))- return query- },- }).data as ChannelRow[] | undefined- return annotateRows(registry, "channels", data)+ return useCollectionRows("channels", ({ row }) => and(+ serverId === undefined ? eq(1, 1) : eq(row.serverId, serverId),+ type === undefined ? eq(1, 1) : eq(row.type, type),+ ))}-function useChannelMembershipRows(channelIds?: string[]) {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ membership: registry.collections.channelMemberships })- .where(({ membership }) => channelIds === undefined ? eq(1, 1) : inArray(membership.channelId, channelIds))- : undefined,- }).data as ChannelMembershipRow[] | undefined- return annotateRows(registry, "channelMemberships", data)+ return useCollectionRows("channelMemberships", ({ row }) => channelIds === undefined ? eq(1, 1) : inArray(row.channelId, channelIds))}-function useMessageRowsById(messageIds: string[]) {- const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({- query: (q) => registry- ? q.from({ message: registry.collections.messages }).where(({ message }) => inArray(message.id, messageIds))- : undefined,- }).data as MessageRow[] | undefined- return annotateRows(registry, "messages", data)+ return useCollectionRows("messages", ({ row }) => inArray(row.id, messageIds))}export function useServerRailProjection() {@@ -301,6 +242,17 @@ export function useServerTreeProjection(serverId: string | null) {const channels = rows.channels.filter((channel) => (channel.serverId === serverId && channel.type !== "thread"))+ const channelView = (channel: ChannelRow): Category["channels"][number] => ({+ id: channel.id,+ name: channel.name,+ active: false,+ unread: channel.unread,+ muted: channel.muted,+ type: channel.type === "forum" ? "forum" : "text",+ tags: channel.tags,+ creatorId: channel.creatorId,+ pending: channel.pending,+ })const categories: Category[] = rows.categories.filter((category) => category.serverId === serverId).sort((a, b) => a.position - b.position)@@ -313,32 +265,12 @@ export function useServerTreeProjection(serverId: string | null) {channels: channels.filter((channel) => channel.categoryId === category.id).sort((a, b) => a.position - b.position)- .map((channel) => ({- id: channel.id,- name: channel.name,- active: false,- unread: channel.unread,- muted: channel.muted,- type: channel.type === "forum" ? "forum" : "text",- tags: channel.tags,- creatorId: channel.creatorId,- pending: channel.pending,- })),+ .map(channelView),}))const uncategorized = channels.filter((channel) => !channel.categoryId).sort((a, b) => a.position - b.position)- .map((channel) => ({- id: channel.id,- name: channel.name,- active: false,- unread: channel.unread,- muted: channel.muted,- type: channel.type === "forum" ? "forum" as const : "text" as const,- tags: channel.tags,- creatorId: channel.creatorId,- pending: channel.pending,- }))+ .map(channelView)if (uncategorized.length > 0) {categories.push({ id: "__uncategorized__", name: "", private: false, channels: uncategorized })}@@ -364,16 +296,8 @@ export function useDmProjection() {const userIds = useMemo(() => (channelMemberships ?? []).filter((membership) => (membership.relation === "access" && membership.userId !== registry?.accountId)).map((membership) => membership.userId), [channelMemberships, registry?.accountId])- const profiles = useLiveQuery({- query: (q) => registry- ? q.from({ profile: registry.collections.profiles }).where(({ profile }) => inArray(profile.userId, userIds))- : undefined,- }).data as ProfileRow[] | undefined- const readStates = useLiveQuery({- query: (q) => registry- ? q.from({ readState: registry.collections.readStates }).where(({ readState }) => inArray(readState.channelId, channelIds))- : undefined,- }).data as ReadStateRow[] | undefined+ const profiles = useCollectionQuery("profiles", ({ row }) => inArray(row.userId, userIds)).data+ const readStates = useCollectionQuery("readStates", ({ row }) => inArray(row.channelId, channelIds)).dataconst rows = { registry, channels, channelMemberships, profiles, readStates }return useMemo(() => {const viewerId = rows.registry?.accountId@@ -414,77 +338,49 @@ export function useDmProjection() {}export function useRouteChannelProjection(channelId: string | null) {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ channel: registry.collections.channels }).where(({ channel }) => eq(channel.id, channelId ?? ""))- : undefined,- })- return useMemo(() => {- if (!channelId || !result.data) return undefined- return (result.data as ChannelRow[]).find((row) => row.id === channelId)- }, [channelId, result.data])-}--export function useReadStateProjection(channelId: string | null | undefined) {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ readState: registry.collections.readStates }).where(({ readState }) => eq(readState.channelId, channelId ?? ""))- : undefined,- })+ const result = useCollectionQuery("channels", ({ row }) => eq(row.id, channelId ?? ""))return useMemo(() => {if (!channelId || !result.data) return undefined- const row = (result.data as ReadStateRow[])- .find((candidate) => candidate.channelId === channelId)- if (!row) return undefined- return {- lastReadMessageId: row.lastReadMessageId,- lastReadAt: row.lastReadAt,- lastReadSeq: row.lastReadSeq,- }+ return result.data.find((row) => row.id === channelId)}, [channelId, result.data])}-export function useMessageProjection(channelId: string | null, ids?: readonly string[]) {+function useJoinedMessageQuery(channelId: string | null | undefined, ids?: readonly string[]) {const registry = useOptionalCommunityDbRegistry()const result = useLiveQuery({- query: (q) => registry && channelId- ? q.from({ message: registry.collections.messages }).where(({ message }) => eq(message.channelId, channelId))+ query: (q) => registry && (channelId === undefined || !!channelId)+ ? q.from({ message: registry.collections.messages }).where(({ message }) => channelId === undefined ? eq(1, 1) : eq(message.channelId, channelId)).where(({ message }) => ids === undefined ? eq(1, 1) : inArray(message.id, [...ids])).leftJoin({ child: registry.collections.channels }, ({ message, child }) => eq(message.id, child.parentMessageId)).select(({ message, child }) => ({ message, child })): undefined,})+ return { registry, data: result.data as Array<{ message: MessageRow; child?: ChannelRow }> | undefined }+}++export function useMessageProjection(channelId: string | null, ids?: readonly string[]) {+ const { registry, data } = useJoinedMessageQuery(channelId, ids)return useMemo(() => {- if (!channelId || !result.data) return undefined- const messages = (result.data as Array<{ message: MessageRow; child?: ChannelRow }>)+ if (!channelId || !data) return undefined+ const messages = data.sort((a, b) => (a.message.seq ?? 0) - (b.message.seq ?? 0)).map(({ message, child }) => {return projectedMessage(registry, message, child)})return deriveView(messages, messages.map(viewEvidence))- }, [channelId, result.data, registry])+ }, [channelId, data, registry])}export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<string, Msg> | undefined {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ message: registry.collections.messages })- .where(({ message }) => ids === undefined ? eq(1, 1) : inArray(message.id, [...ids]))- .leftJoin({ child: registry.collections.channels }, ({ message, child }) => eq(message.id, child.parentMessageId))- .select(({ message, child }) => ({ message, child }))- : undefined,- })+ const { registry, data } = useJoinedMessageQuery(undefined, ids)return useMemo(() => !registry ? undefined : new Map(- ((result.data ?? []) as Array<{ message: MessageRow; child?: ChannelRow }>).map(({ message, child }) => {+ (data ?? []).map(({ message, child }) => {return [message.id, projectedMessage(registry, message, child)]}),- ), [registry, result.data])+ ), [registry, data])}-export function useMessageWindowProjection(channelId: string | null, ids?: readonly string[]) {+export function useMessageWindowProjection(channelId: string | null, ids: readonly string[] | undefined, liveIds: readonly string[]) {const registry = useOptionalCommunityDbRegistry()const warm = useLiveQuery({ query: (q) => registry && channelId && ids === undefined? q.from({ message: registry.collections.messages }).where(({ message }) => eq(message.channelId, channelId))@@ -492,37 +388,23 @@ export function useMessageWindowProjection(channelId: string | null, ids?: reado.limit(MAX_PERSISTED_MESSAGES_PER_SCOPE).select(({ message }) => ({ id: message.id })): undefined }).data as Array<{ id: string }> | undefinedconst selected = useMemo(() => ids ?? warm?.map((message) => message.id) ?? [], [ids, warm])- return useMessageProjection(channelId, selected)+ const allIds = useMemo(() => [...new Set([...selected, ...liveIds])], [selected, liveIds])+ const messages = useMessageProjection(channelId, allIds)+ return { messages, windowIds: selected }}-export function useCanonicalChannelsById(): ReadonlyMap<string, ChannelRow> {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ channel: registry.collections.channels })- : undefined,- })- return useMemo(() => new Map(- (annotateRows(registry, "channels", (result.data ?? []) as ChannelRow[])!).map((channel) => [channel.id, channel]),- ), [result.data, registry])+function useCollectionById<N extends "channels" | "servers">(name: N) {+ const rows = useCollectionRows(name)+ return useMemo(() => new Map((rows ?? []).map((row) => [row.id, row])), [rows])}+export function useCanonicalChannelsById(): ReadonlyMap<string, ChannelRow> { return useCollectionById("channels") }+export function useFriendshipRows(ids?: readonly string[]) {- const registry = useOptionalCommunityDbRegistry()- return (useLiveQuery({ query: (q) => registry ? q.from({ friendship: registry.collections.friendships }).where(({ friendship }) => ids === undefined ? eq(1, 1) : inArray(friendship.id, [...ids])) : undefined }).data ?? []) as FriendshipRow[]+ return useCollectionQuery("friendships", ({ row }) => ids === undefined ? eq(1, 1) : inArray(row.id, [...ids])).data ?? []}-export function useCanonicalServersById(): ReadonlyMap<string, ServerRow> {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ server: registry.collections.servers })- : undefined,- })- return useMemo(() => new Map(- (annotateRows(registry, "servers", (result.data ?? []) as ServerRow[])!).map((server) => [server.id, server]),- ), [result.data, registry])-}+export function useCanonicalServersById(): ReadonlyMap<string, ServerRow> { return useCollectionById("servers") }export function useCanonicalCommunityServer(serverId: string | null | undefined) {return useServerRows(serverId ?? "__inactive__")?.[0]@@ -571,14 +453,9 @@ export function useNotificationSettingsProjection() {}function useProfileProjectionMap(userIds?: readonly string[]) {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ profile: registry.collections.profiles }).where(({ profile }) => userIds === undefined ? eq(1, 1) : inArray(profile.userId, [...userIds]))- : undefined,- })+ const result = useCollectionQuery("profiles", ({ row }) => userIds === undefined ? eq(1, 1) : inArray(row.userId, [...userIds]))return useMemo(() => new Map(- ((result.data ?? []) as ProfileRow[]).map((profile) => [profile.userId, profile]),+ (result.data ?? []).map((profile) => [profile.userId, profile]),), [result.data])}@@ -605,21 +482,19 @@ export function useCanonicalProfilesByUserId(userIds?: readonly string[]): Reado}export function useServerMemberRows(serverId: string | null, userIds: readonly string[]) {- const registry = useOptionalCommunityDbRegistry()- const data = (useLiveQuery({ query: (q) => registry && serverId ? q.from({ membership: registry.collections.serverMemberships }).where(({ membership }) => eq(membership.serverId, serverId)).where(({ membership }) => inArray(membership.userId, [...userIds])) : undefined }).data ?? []) as ServerMembershipRow[]- return annotateRows(registry, "serverMemberships", data)!+ const { registry, data } = useCollectionQuery("serverMemberships", ({ row }) => and(eq(row.serverId, serverId), inArray(row.userId, [...userIds])), !!serverId)+ return annotateRows(registry, "serverMemberships", data ?? [])!}export function useChannelRosterRows(channelId: string, relation: "access" | "notify") {- const registry = useOptionalCommunityDbRegistry()- const data = (useLiveQuery({ query: (q) => registry && channelId ? q.from({ membership: registry.collections.channelMemberships }).where(({ membership }) => eq(membership.channelId, channelId)).where(({ membership }) => eq(membership.relation, relation)) : undefined }).data ?? []) as ChannelMembershipRow[]- return annotateRows(registry, "channelMemberships", data)!+ const { registry, data } = useCollectionQuery("channelMemberships", ({ row }) => and(eq(row.channelId, channelId), eq(row.relation, relation)), !!channelId)+ return annotateRows(registry, "channelMemberships", data ?? [])!}export function useCanonicalCommunityProfile(userId: string | null | undefined) {- const registry = useOptionalCommunityDbRegistry()const preview = useCommunityPreviewProfiles()- const profile = useLiveQuery({ query: (q) => registry && userId ? q.from({ profile: registry.collections.profiles }).where(({ profile }) => eq(profile.userId, userId)) : undefined }).data?.[0] as ProfileRow | undefined+ const { registry, data } = useCollectionQuery("profiles", ({ row }) => eq(row.userId, userId), !!userId)+ const profile = data?.[0]const presence = useSelector(registry?.runtime.ws ?? absentPresence, (state) => userId ? state.presenceByUserId.get(userId) : undefined)return useMemo(() => {if (!userId) return undefined@@ -633,23 +508,13 @@ export function useCanonicalCommunityProfile(userId: string | null | undefined)}export function useAttentionScopes(): readonly AttentionScopeRow[] {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ scope: registry.collections.attentionScopes })- : undefined,- })- return annotateRows(registry, "attentionScopes", (result.data ?? []) as AttentionScopeRow[])!+ const { registry, data } = useCollectionQuery("attentionScopes")+ return annotateRows(registry, "attentionScopes", data ?? [])!}export function useAttentionItems(): readonly AttentionItemRow[] {- const registry = useOptionalCommunityDbRegistry()- const result = useLiveQuery({- query: (q) => registry- ? q.from({ item: registry.collections.attentionItems })- : undefined,- })- return annotateRows(registry, "attentionItems", (result.data ?? []) as AttentionItemRow[])!+ const { registry, data } = useCollectionQuery("attentionItems")+ return annotateRows(registry, "attentionItems", data ?? [])!}export function useChannelRefDirectoryProjection(): ChannelRefDirectory | undefined {@@ -672,18 +537,6 @@ export function useChannelRefDirectoryProjection(): ChannelRefDirectory | undefi}, [rows.channels, rows.servers])}-export type CanonicalForumSidebarThread = {- id: string- parentChannelId: string- parentMessageId: string- title: string- activityAt: string- expiresAt: string- unread: boolean-}--const FORUM_SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000-export function useForumSidebarProjection(serverId: string,retainId: string | null,@@ -706,92 +559,8 @@ export function useForumSidebarProjection(|| !rows.channelMemberships|| !rows.messages) return undefined- const viewerId = rows.registry.accountId- const participating = new Set(rows.channelMemberships- .filter((membership) => (- membership.relation === "notify"- && membership.userId === viewerId- ))- .map((membership) => membership.channelId))- const messageById = new Map(rows.messages.map((message) => [message.id, message]))- const forumParentIds = new Set(rows.channels- .filter((channel) => channel.serverId === serverId && channel.type === "forum")- .map((channel) => channel.id))- const candidates: CanonicalForumSidebarThread[] = rows.channels- .filter((channel) => (- channel.serverId === serverId- && channel.type === "thread"- && !channel.archived- && !channel.tags.includes(FORUM_ARCHIVE_TAG)- && participating.has(channel.id)- && channel.parentChannelId- && forumParentIds.has(channel.parentChannelId)- && channel.parentMessageId- ))- .map((channel) => {- const activityAt = channel.lastMessageAt ?? ""- const activityMs = Date.parse(activityAt)- return {- id: channel.id,- parentChannelId: channel.parentChannelId!,- parentMessageId: channel.parentMessageId!,- title: messageById.get(channel.parentMessageId!)?.content ?? channel.name,- activityAt,- expiresAt: Number.isFinite(activityMs)- ? new Date(activityMs + FORUM_SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()- : activityAt,- unread: channel.unread,- }- })- .filter((thread) => (- thread.id === retainId- || !Number.isFinite(Date.parse(thread.expiresAt))- || Date.parse(thread.expiresAt) > serverNowMs- ))- .sort((left, right) => (- left.parentChannelId.localeCompare(right.parentChannelId)- || right.activityAt.localeCompare(left.activityAt)- || right.id.localeCompare(left.id)- ))- const byParent = new Map<string, CanonicalForumSidebarThread[]>()- for (const thread of candidates) {- const siblings = byParent.get(thread.parentChannelId) ?? []- siblings.push(thread)- byParent.set(thread.parentChannelId, siblings)- }- const threads = [...byParent.values()].flatMap((siblings) => {- const retained = retainId- ? siblings.find((thread) => thread.id === retainId)- : undefined- if (!retained) return siblings.slice(0, 5)- if (siblings.slice(0, 5).some((thread) => thread.id === retained.id)) {- return siblings.slice(0, 5)- }- return [...siblings.filter((thread) => thread.id !== retained.id).slice(0, 4), retained]- .sort((left, right) => (- right.activityAt.localeCompare(left.activityAt)- || right.id.localeCompare(left.id)- ))- })- const renderedIds = new Set(threads.map((thread) => thread.id))- const parentUnread: Record<string, boolean> = {}- for (const parent of rows.channels.filter((channel) => (- channel.serverId === serverId && channel.type === "forum"- ))) {- parentUnread[parent.id] = parent.baseUnread ?? parent.unread- }- for (const child of rows.channels) {- if (- child.serverId === serverId- && child.type === "thread"- && child.unread- && child.parentChannelId- && forumParentIds.has(child.parentChannelId)- && !renderedIds.has(child.id)- ) {- parentUnread[child.parentChannelId] = true- }- }+ const { threads, parentUnread } = projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages,+ rows.registry.accountId, serverId, retainId, serverNowMs)deriveView(threads, [viewEvidence(rows.channels), viewEvidence(rows.channelMemberships), viewEvidence(rows.messages)])return deriveView({ threads, parentUnread }, [viewEvidence(threads)], threads.length)}, [serverNowMs, rows.registry, rows.channels, rows.channelMemberships, rows.messages, serverId, retainId])diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.tsindex 3cd1a2b9e..7edc77574 100644--- a/src/web/src/lib/community-db/schema.ts+++ b/src/web/src/lib/community-db/schema.ts@@ -1,4 +1,5 @@import { z } from "zod"+import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityReadStateResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "@alook/shared"import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"const nullableString = z.string().nullable()@@ -31,30 +32,25 @@ export const categorySchema = z.object({pending: z.boolean(),})-export const channelSchema = z.object({- id: z.string().min(1),- serverId: optionalNullableString,- categoryId: optionalNullableString,- name: z.string(),- type: z.enum(["text", "forum", "thread", "dm"]),- parentChannelId: optionalNullableString,- parentMessageId: optionalNullableString,- creatorId: optionalNullableString,- position: z.number(),- archived: z.boolean(),+export const channelSchema = CommunityChannelResourceSchema.pick({+ id: true, serverId: true, categoryId: true, type: true, parentChannelId: true,+ parentMessageId: true, creatorId: true, position: true, archived: true,+ lastMessageAt: true, createdAt: true, messageCount: true,+}).strip().partial({+ serverId: true, categoryId: true, parentChannelId: true, parentMessageId: true,+ creatorId: true, lastMessageAt: true, createdAt: true, messageCount: true,+}).extend({+ name: CommunityChannelResourceSchema.shape.name.unwrap(),muted: z.boolean(),unread: z.boolean(),/** Forum channel's own unread bit, excluding participating child rows. */baseUnread: z.boolean().optional(),tags: z.array(z.string()),pending: z.boolean(),- lastMessageAt: optionalNullableString,openerSeq: z.number().int().nonnegative().optional(),openerUnread: z.boolean().optional(),preview: z.string().optional(),lastUnreadSeq: z.number().int().nonnegative().optional(),- createdAt: z.string().optional(),- messageCount: z.number().int().nonnegative().optional(),participantCount: z.number().int().nonnegative().optional(),})@@ -69,11 +65,10 @@ export const serverMembershipSchema = z.object({viewer: z.boolean(),})-export const channelMembershipSchema = z.object({+export const channelMembershipSchema = CommunityMemberRelationSchema.pick({+ channelId: true, userId: true, relation: true, isCreator: true,+}).strip().partial({ isCreator: true }).extend({id: z.string().min(1),- channelId: z.string().min(1),- userId: z.string().min(1),- relation: z.enum(["access", "notify"]),memberId: z.string().optional(),source: z.enum(["explicit",@@ -83,15 +78,12 @@ export const channelMembershipSchema = z.object({PARTICIPANT_SOURCE.SPOKE,PARTICIPANT_SOURCE.ADDED,]).optional(),- isCreator: z.boolean().optional(),})-export const profileSchema = z.object({- userId: z.string().min(1),- name: z.string(),- discriminator: z.string(),- avatar: z.string(),- avatarVersion: z.number().int().nonnegative(),+export const profileSchema = CommunityResourceProfileSchema.omit({ id: true }).strip().extend({+ userId: CommunityResourceProfileSchema.shape.id,+ discriminator: CommunityResourceProfileSchema.shape.discriminator.unwrap(),+ avatar: CommunityResourceProfileSchema.shape.avatar.unwrap(),aboutMe: z.string().optional(),bannerColor: optionalNullableString,kind: z.enum(["human", "bot"]).optional(),@@ -99,33 +91,20 @@ export const profileSchema = z.object({ownerHandle: optionalNullableString,mutualServers: z.number().int().nonnegative().optional(),ownedByViewer: z.boolean().optional(),- statusEmoji: optionalNullableString,- statusText: optionalNullableString,+ statusEmoji: CommunityResourceProfileSchema.shape.statusEmoji.optional(),+ statusText: CommunityResourceProfileSchema.shape.statusText.nullable().optional(),})-export const messageSchema = z.object({- id: z.string().min(1),- channelId: z.string().min(1),- type: z.enum(["chat", "system"]),- systemKind: z.literal("thread").optional(),- authorId: z.string().optional(),- authorName: z.string().optional(),- authorAvatar: z.string().optional(),- authorAvatarVersion: z.number().int().nonnegative().optional(),- seq: z.number().int().nonnegative().optional(),- createdAt: z.string().optional(),+export const messageSchema = CommunityMessageResourceSchema.pick({+ id: true, channelId: true, type: true, systemKind: true, authorId: true, authorName: true,+ authorAvatar: true, authorAvatarVersion: true, seq: true, createdAt: true, content: true,+}).partial({ authorId: true, seq: true, createdAt: true, content: true }).extend({clientNonce: z.string().optional(),- content: z.string().optional(),failed: z.boolean().optional(),- replyToId: z.string().optional(),+ replyToId: z.string().nullable().optional(),}).loose()-export const readStateSchema = z.object({- channelId: z.string().min(1),- lastReadMessageId: nullableString,- lastReadAt: z.string(),- lastReadSeq: z.number().int().nonnegative(),-})+export const readStateSchema = CommunityReadStateResourceSchema.strip()export const friendshipSchema = z.object({id: z.string().min(1),@@ -213,6 +192,7 @@ export const communityCollectionSchemas = {} as constexport type CommunityCollectionName = keyof typeof communityCollectionSchemas+export type CommunityCollectionRows = { [N in CommunityCollectionName]: z.output<typeof communityCollectionSchemas[N]> }export type ServerRow = z.infer<typeof serverSchema>export type CategoryRow = z.infer<typeof categorySchema>export type ChannelRow = z.infer<typeof channelSchema>@@ -229,6 +209,29 @@ export type FolderRow = z.infer<typeof folderSchema>export type FolderItemRow = z.infer<typeof folderItemSchema>export type NotificationSettingRow = z.infer<typeof notificationSettingSchema>+export function canonicalChannelRow(+ input: Pick<ChannelRow, "id" | "type"> & Partial<Omit<ChannelRow, "id" | "type" | "name">> & { name?: string | null },+ previous?: ChannelRow,+): ChannelRow {+ return channelSchema.parse({+ serverId: null,+ categoryId: null,+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ position: 0,+ archived: false,+ muted: false,+ unread: false,+ tags: [],+ pending: false,+ lastMessageAt: null,+ ...previous,+ ...input,+ name: input.name === undefined ? previous?.name ?? "" : input.name ?? "",+ })+}+export function serverMembershipKey(serverId: string, userId: string) {return `${serverId}:${userId}`}@@ -241,6 +244,15 @@ export function channelMembershipKey(return `${channelId}:${userId}:${relation}`}+export function canonicalChannelMembershipRow(+ channelId: string,+ userId: string,+ relation: ChannelMembershipRow["relation"],+ fields?: Omit<ChannelMembershipRow, "id" | "channelId" | "userId" | "relation">,+): ChannelMembershipRow {+ return { ...fields, id: channelMembershipKey(channelId, userId, relation), channelId, userId, relation }+}+export function folderItemKey(folderId: string, serverId: string) {return `${folderId}:${serverId}`}diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.tsindex fe9e9f034..b3893c5c6 100644--- a/src/web/src/lib/community-db/sync.test.ts+++ b/src/web/src/lib/community-db/sync.test.ts@@ -1,3 +1,4 @@+import { projectPostedMessage } from "@/lib/community/message-wire"import { QueryClient } from "@tanstack/react-query"import { afterEach, describe, expect, it, vi } from "vitest"import type { CommunityWsEvent } from "@alook/shared"@@ -39,6 +40,7 @@ import {projectCommunityWsEventToDb,purgeCommunityChannel,purgeCommunityServer,+ retireCommunityChannelReading,removeAttentionItemsOptimistically,restoreAttentionScopeOptimisticSnapshot,type CommunityLiveSnapshot,@@ -101,6 +103,38 @@ describe("community DB sync", () => {expect(db.collections.servers.get("s1")).toMatchObject({ name, description: "confirmed" })})+ it("keeps confirmed reply identity on incomplete same-message input and accepts explicit deletion", async () => {+ const db = await registry()+ const replyTo = { id: "reply", authorId: "peer", authorName: "Peer", text: "confirmed" }+ const row = { id: "posted", channelId: "c1", type: "chat" as const, authorId: "viewer", clientNonce: "nonce", seq: 1, replyTo, replyToId: replyTo.id }+ ingestMessages(db, "c1", [row])+ ingestMessages(db, "c1", [{ ...row, replyTo: undefined }])+ expect(db.collections.messages.get(row.id)?.replyTo).toBeUndefined()+ ingestMessages(db, "c1", [row])+ const { replyTo: _reply, ...incomplete } = row+ ingestMessages(db, "c1", [incomplete])+ expect(db.collections.messages.get(row.id)?.replyTo).toEqual(replyTo)+ const posted = projectPostedMessage({ id: row.id, seq: row.seq, authorId: row.authorId, authorName: "Viewer",+ authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-08T00:00:00Z", content: "posted", type: "default", embeds: null }, row.clientNonce, "c1")+ ingestMessages(db, "c1", [posted])+ expect(db.collections.messages.get(row.id)?.replyTo).toEqual(replyTo)+ ingestMessages(db, "c1", [{ ...row, replyTo: { id: replyTo.id, authorName: "Deleted user", text: "", deleted: true } }])+ expect(db.collections.messages.get(row.id)?.replyTo).toMatchObject({ deleted: true, text: "" })+ ingestMessages(db, "c1", [{ ...incomplete, replyToId: null }])+ expect(db.collections.messages.get(row.id)?.replyTo).toBeUndefined()+ expect(db.collections.messages.get(row.id)?.replyToId).toBeNull()+ })++ it.each(["author", "nonce", "channel"])("does not retain a confirmed quote for a different %s owner", async (field) => {+ const db = await registry()+ const identity = { id: "owned-reply", channelId: "c1", type: "chat" as const, authorId: "viewer", clientNonce: "nonce", seq: 1 }+ ingestMessages(db, "c1", [{ ...identity, replyTo: { id: "target", authorName: "Peer", text: "private" }, replyToId: "target" }])+ ingestMessages(db, field === "channel" ? "c2" : "c1", [{ ...identity,+ ...(field === "author" ? { authorId: "other" } : field === "nonce" ? { clientNonce: "other" } : {}) }])+ expect(db.collections.messages.get(identity.id)?.replyTo).toBeUndefined()+ expect(db.collections.messages.get(identity.id)?.replyToId).toBeNull()+ })+it("cannot resurrect a deleted channel through a confirmed field patch or the older snapshot", async () => {const db = await registry()const original = { id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "General", channels: [{ id: "c1", name: "old", active: false, unread: false }] }] }@@ -168,6 +202,32 @@ describe("community DB sync", () => {})})+ it.each(["directory", "attention"] as const)("preserves rich server rows and existing viewer roles when seeding $0 summaries", async (source) => {+ const db = await registry()+ ingestServers(db, { servers: [{ id: "s1", name: "Server", discriminator: "0001",+ initial: "S", active: false, unread: true, mentions: 3, ownerId: "viewer",+ isOwner: true, role: "admin", memberId: "member-1" }] })+ ingestServerDetail(db, { id: "s1", name: "Server", discriminator: "0001",+ description: "rich description", icon: "server.png", ownerId: "viewer", official: true, categories: [] })+ const original = db.collections.servers.get("s1")!+ const membership = [...db.collections.serverMemberships.values()].find((row) => row.serverId === "s1")!+ const summaries = [{ id: "s1", name: "Updated", discriminator: "0002" },+ { id: "s2", name: "New", discriminator: "0003" }]+ if (source === "directory") publishCommunityChannelDirectory(db.queryClient, {+ directory: summaries.map((server) => ({ ...server, channels: [] })),+ proof: { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined },+ })+ else ingestAttentionSnapshot(db, { scopes: [], items: [], limit: 100, truncated: false,+ included: { servers: summaries } })+ expect(db.collections.servers.get("s1")).toStrictEqual({ ...original, name: "Updated", discriminator: "0002" })+ expect(db.collections.serverMemberships.get(membership.id)).toStrictEqual(membership)+ expect(db.collections.servers.get("s2")).toMatchObject({ id: "s2", position: 1,+ name: "New", discriminator: "0003", description: "", ownerId: "", icon: null,+ official: false, isOwner: false, unread: false, mentions: 0, detailComplete: false })+ expect([...db.collections.serverMemberships.values()].find((row) => row.serverId === "s2"))+ .toMatchObject({ serverId: "s2", userId: "viewer", role: "member", viewer: true })+ })+it("keeps anonymous canonical ingestion free of viewer access rows", async () => {const db = createCommunityDbRegistry(new QueryClient(), null)registries.push(db)@@ -550,10 +610,10 @@ describe("community DB sync", () => {serverId: "s1",channelId: "c1",} as CommunityWsEvent)- expect(publishCommunityLiveSnapshotWithProof(db.queryClient, {+ expect(() => publishCommunityLiveSnapshotWithProof(db.queryClient, {snapshot: { kind: "server-detail", data: detail },proof: { kind: "structural", token, signal: undefined },- })).toBe("published")+ })).toThrow(expect.objectContaining({ name: "AbortError" }))expect(db.collections.channels.get("c1")).toBeUndefined()})@@ -982,10 +1042,7 @@ describe("community DB sync", () => {expect(db.collections.readStates.get("live-c2")).toBeUndefined()expect(db.collections.notificationSettings.get("channel:live-c2")).toBeUndefined()- projectCommunityWsEventToDb(db.queryClient, {- type: "community:server.delete",- serverId: "live-s1",- } as CommunityWsEvent)+ purgeCommunityServer(db, "live-s1")expect(db.collections.servers.get("live-s1")).toBeUndefined()expect(db.runtime.ws.get().revokedServerIds.has("live-s1")).toBe(true)db.runtime.ws.actions.grantServerAccess("live-s1")@@ -1779,7 +1836,7 @@ describe("community DB sync", () => {authorId: "u2",authorName: "Alice",content: "rich",- attachments: [{ id: "a1", name: "proof.png" }],+ attachments: [{ kind: "image", name: "proof.png", url: "/proof.png" }],replyTo: { id: "m0", authorId: "u3", authorName: "Bob", content: "earlier" },}])@@ -1815,7 +1872,7 @@ describe("community DB sync", () => {})expect(db.collections.messages.get("m1")).toMatchObject({content: "new preview",- attachments: [{ id: "a1", name: "proof.png" }],+ attachments: [{ kind: "image", name: "proof.png", url: "/proof.png" }],replyTo: { id: "m0", authorId: "u3" },})})@@ -2061,11 +2118,32 @@ describe("community DB sync", () => {preview: "",}],})+ ingestAttentionSnapshot(db, { scopes: [], items: [+ { id: "scope-item", kind: "mention", sourceId: "source-1", scopeId: "c1", createdAt: "now" },+ { id: "child-item", kind: "forum_post", sourceId: "source-2", childChannelId: "c1", createdAt: "now" },+ { id: "target-item", kind: "reply", sourceId: "source-3", readTarget: { channelId: "c1", seq: 1 }, createdAt: "now" },+ { id: "dm-item", kind: "mention", sourceId: "source-4", scopeId: "dm1", createdAt: "now" },+ ], limit: 100, truncated: false })purgeCommunityServer(db, "s1")expect(db.collections.servers.get("s1")).toBeUndefined()expect(db.collections.categories.get("cat1")).toBeUndefined()expect(db.collections.channels.get("c1")).toBeUndefined()expect(db.collections.channels.get("dm1")).toBeDefined()+ expect([...db.collections.attentionItems.keys()]).toEqual(["dm-item"])+ })++ it("keeps channel retirement fail-closed when native disk retirement rejects", async () => {+ const db = await registry(), error = new Error("IDB unavailable")+ ingestMessages(db, "dm-A", [{ id: "retire-message", type: "chat", content: "old" }])+ ingestMessages(db, "dm-B", [{ id: "sibling-message", type: "chat", content: "keep" }])+ db.bindAuthentication(() => "viewer", () => Promise.resolve(), () => Promise.reject(error))+ const report = vi.spyOn(console, "error").mockImplementation(() => {})+ retireCommunityChannelReading(db, "dm-A", { reason: "read-denied", serverId: null })+ await vi.waitFor(() => expect(report).toHaveBeenCalledWith("Channel cache retirement failed", error))+ expect(db.collections.messages.has("retire-message")).toBe(false)+ expect(db.collections.messages.get("sibling-message")?.content).toBe("keep")+ expect(db.runtime.ws.actions.isChannelAccessRevoked("dm-A", null)).toBe(true)+ report.mockRestore()})it("purges a scoped raw single-message query before it materializes canonically", async () => {@@ -2368,7 +2446,7 @@ describe("community DB sync", () => {channelId: "c1",serverId: "s1",message: {- id: "m1",+ id: "m1", seq: 1,type: "chat",authorId: "peer",authorName: "Peer",@@ -2554,13 +2632,13 @@ describe("community DB sync", () => {expect(db.collections.channels.get("thread1")).toMatchObject({ archived: true })event({ type: "community:channel.delete", serverId: "s1", channelId: "c2" })expect(db.collections.channels.get("c2")).toBeUndefined()- event({ type: "community:server.delete", serverId: "s1" })+ purgeCommunityServer(db, "s1")expect(db.collections.servers.get("s1")).toBeUndefined()ingestServers(db, { servers: [{id: "leave", name: "Leave", initial: "L", active: false, unread: false,mentions: 0, ownerId: "viewer",}] })- event({ type: "community:member.leave", serverId: "leave", userId: "viewer" })+ purgeCommunityServer(db, "leave")expect(db.collections.servers.get("leave")).toBeUndefined()event({ type: "community:unknown" })})diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex 18b7392bc..f0d22b460 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -4,13 +4,18 @@ import { communityRequestOptions as qualifiedCommunityRequestOptions } from "@/limport { isAbortError } from "@/lib/errors"import { isOwnerServerDeleteScopeEvictionBlocked } from "@/lib/community/eject-server"-import { getCommunityRuntime } from "@/stores/community/runtime"+import { getCommunityRuntime, readCurrentCommunityChannelMeta } from "@/stores/community/runtime"import { notifyManager,type QueryClient } from "@tanstack/react-query"import { createStore } from "@tanstack/store"import type { Query } from "@tanstack/react-query"import {UNCATEGORIZED_CATEGORY_ID,FORUM_ARCHIVE_TAG,+normalizeCommunityChannelIdentity,+type CommunityChannelIdentity,+type CommunityMemberRelation,+type CommunityResourceProfile,+type CommunityMessageResource,type AccountAttentionSnapshot,type CommunityWsEvent,type ServerRailProjection,@@ -21,7 +26,7 @@ import type {AccountReadStateSnapshot,} from "@/hooks/community/community-ws/read-state-reconciliation"import type { ServerDetail,ServersResponse } from "@/hooks/community/use-servers"-import type { Msg } from "@/lib/community/models/message"+import { applyMessageReaction, messageProfileIds, type Msg, type MessageInput } from "@/lib/community/models/message"import type { NotificationSettings } from "@/hooks/community/use-notification-settings"import { communityKeys } from "@/lib/query-keys"import {@@ -35,8 +40,8 @@ import type { CommunityProfilePatch } from "@/lib/community/models/people"import type { ChannelRefDirectory } from "@/lib/community/channel-ref"-import { canonicalUserImage } from "@/lib/community/storage"-import { projectCommunityMessageCreate } from "@/lib/community/message-wire"+import { avatarInitial } from "@/lib/community/avatar"+import { projectCommunityMessageCreate, projectMessageRichContent } from "@/lib/community/message-wire"import { clearTypingIndicator } from "@/hooks/community/community-ws/typing"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { takeMessageIdsForAccessScope } from "./message-access-scope"@@ -47,25 +52,19 @@ getCommunityDbRegistry,type CommunityDbRegistry,} from "./collections"import {-categorySchema,-attentionItemSchema,-attentionScopeSchema,channelMembershipKey,+canonicalChannelMembershipRow,channelMembershipSchema,channelSchema,+canonicalChannelRow,folderItemKey,-folderItemSchema,-folderSchema,messageSchema,-friendshipSchema,notificationSettingKey,-notificationSettingSchema,profileSchema,-readStateClockSchema,-readStateSchema,serverMembershipKey,-serverMembershipSchema,serverSchema,+communityCollectionSchemas,+type CommunityCollectionRows,type CategoryRow,type AttentionItemRow,type AttentionScopeRow,@@ -83,7 +82,7 @@ type ServerRow,} from "./schema"import type { z } from "zod"import { writeCommunityCollectionRows } from "./write"-import type { ForumFeedTransportPage } from "@/hooks/community/forum-feed-window"+import type { CommunityThreadResources } from "@/hooks/community/forum-feed-window"type CollectionName = keyof CommunityDbRegistry["collections"]type SnapshotIngestMode = "authoritative" | "merge"@@ -269,37 +268,35 @@ function withCanonicalWriteContext<T>(}}-function collectionRows<T extends object>(- registry: CommunityDbRegistry,- name: CollectionName,- schema: z.ZodType<T>,-) {- const cached = registry.queryClient.getQueryData<T[]>(- communityKeys.communityDbCollection(registry.scopeId, name),- )- if (cached) return cached.flatMap((row) => {- const parsed = schema.safeParse(row)- return parsed.success ? [parsed.data] : []- })- const collection = registry.collections[name] as unknown as {- values: () => IterableIterator<unknown>- }- return Array.from(collection.values()).flatMap((row) => {+function collectionSchema<N extends CollectionName>(name: N) {+ return communityCollectionSchemas[name] as unknown as z.ZodType<CommunityCollectionRows[N]>+}++function collectionRows<N extends CollectionName>(registry: CommunityDbRegistry, name: N): CommunityCollectionRows[N][] {+ const schema = collectionSchema(name)+ const values = registry.queryClient.getQueryData<unknown[]>(communityKeys.communityDbCollection(registry.scopeId, name))+ ?? Array.from<unknown>(registry.collections[name].values())+ return values.flatMap((row) => {const parsed = schema.safeParse(row)return parsed.success ? [parsed.data] : []})}-function replaceRows<T extends object>(+function collectionKey<N extends CollectionName>(registry: CommunityDbRegistry, name: N) {+ const collection = registry.collections[name] as { getKeyFromItem: (row: CommunityCollectionRows[N]) => string }+ return (row: CommunityCollectionRows[N]) => collection.getKeyFromItem(row)+}++function replaceRows<N extends CollectionName>(registry: CommunityDbRegistry,- name: CollectionName,- schema: z.ZodType<T>,- getKey: (row: T) => string,- incoming: T[],- owns: (row: T) => boolean,+ name: N,+ incoming: CommunityCollectionRows[N][],+ owns: (row: CommunityCollectionRows[N]) => boolean,) {+ const schema = collectionSchema(name)+ const getKey = collectionKey(registry, name)const parsedIncoming = incoming.map((row) => schema.parse(row))- const current = collectionRows(registry, name, schema)+ const current = collectionRows(registry, name)const nextByKey = new Map(current.flatMap((row) => {const key = getKey(row)return !owns(row) || isProtectedFromQueryWrite(registry, name, key)@@ -329,44 +326,19 @@ function replaceRows<T extends object>(])}-function upsertRows<T extends object>(+function upsertRows<N extends CollectionName>(registry: CommunityDbRegistry,- name: CollectionName,- schema: z.ZodType<T>,- getKey: (row: T) => string,- incoming: T[],+ name: N,+ incoming: CommunityCollectionRows[N][],) {- const parsedIncoming = incoming.map((row) => schema.parse(row))- const nextByKey = new Map(- collectionRows(registry, name, schema).map((row) => [getKey(row), row]),- )- const acceptedKeys: string[] = []- for (const row of parsedIncoming) {- const key = getKey(row)- if (!isProtectedFromQueryWrite(registry, name, key)) {- nextByKey.set(key, row)- acceptedKeys.push(key)- clearPendingOperations(registry, name, [key])- continue- }- if (nextByKey.has(key)) {- clearPendingOperations(registry, name, [key])- continue- }- const merged = mergePendingOperationsIntoQueryRow(registry, name, key, schema, row)- if (merged) nextByKey.set(key, merged)- }- const next = [...nextByKey.values()]- writeCommunityCollectionRows(registry, name, next, getKey)- if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)- recordEventWrites(registry, name, acceptedKeys)+ replaceRows(registry, name, incoming, () => false)}function promoteServerDetailComplete(registry: CommunityDbRegistry,serverId: string,) {- const current = collectionRows(registry, "servers", serverSchema)+ const current = collectionRows(registry, "servers")let changed = falseconst next = current.map((row) => {if (row.id !== serverId || row.detailComplete) return row@@ -377,17 +349,17 @@ function promoteServerDetailComplete(writeCommunityCollectionRows(registry, "servers", next, (row) => row.id)}-function patchRows<T extends object>(+function patchRows<N extends CollectionName>(registry: CommunityDbRegistry,- name: CollectionName,- schema: z.ZodType<T>,- getKey: (row: T) => string,- patch: (row: T) => T,- matches: (row: T) => boolean,+ name: N,+ patch: (row: CommunityCollectionRows[N]) => CommunityCollectionRows[N],+ matches: (row: CommunityCollectionRows[N]) => boolean,eventKeys?: Iterable<string>,eventFields?: readonly string[],) {- const current = collectionRows(registry, name, schema)+ const schema = collectionSchema(name)+ const getKey = collectionKey(registry, name)+ const current = collectionRows(registry, name)let changed = falseconst changedKeys: string[] = []const next = current.map((row) => {@@ -409,28 +381,23 @@ function patchRows<T extends object>(return changed}-function deleteRows<T extends object>(+function deleteRows<N extends CollectionName>(registry: CommunityDbRegistry,- name: CollectionName,- schema: z.ZodType<T>,- remove: (row: T) => boolean,+ name: N,+ remove: (row: CommunityCollectionRows[N]) => boolean,eventKeys?: Iterable<string>,) {- const current = collectionRows(registry, name, schema)+ const getKey = collectionKey(registry, name)+ const current = collectionRows(registry, name)const removedKeys: string[] = []const next = current.filter((row) => {if (!remove(row)) return true- const key = (registry.collections[name] as unknown as {- getKeyFromItem: (value: T) => string- }).getKeyFromItem(row)+ const key = getKey(row)if (isProtectedFromQueryWrite(registry, name, key)) return trueremovedKeys.push(key)return false})- const keyByValue = new Map(current.map((row) => [row, (- registry.collections[name] as unknown as { getKeyFromItem: (value: T) => string }- ).getKeyFromItem(row)]))- writeCommunityCollectionRows(registry, name, next, (row) => keyByValue.get(row)!)+ writeCommunityCollectionRows(registry, name, next, getKey)if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)if (eventKeys) recordEventDeletes(registry, name, eventKeys)else recordEventWrites(registry, name, removedKeys)@@ -438,28 +405,18 @@ function deleteRows<T extends object>(function referencedProfileIds(registry: CommunityDbRegistry) {const ids = new Set<string>(registry.accountId ? [registry.accountId] : [])- for (const row of collectionRows(registry, "servers", serverSchema)) {+ for (const row of collectionRows(registry, "servers")) {if (row.ownerId) ids.add(row.ownerId)}- for (const row of collectionRows(registry, "serverMemberships", serverMembershipSchema)) {+ for (const row of collectionRows(registry, "serverMemberships")) {ids.add(row.userId)}- for (const row of collectionRows(registry, "channelMemberships", channelMembershipSchema)) {+ for (const row of collectionRows(registry, "channelMemberships")) {ids.add(row.userId)}- for (const row of collectionRows(registry, "friendships", friendshipSchema)) ids.add(row.userId)- for (const row of collectionRows(registry, "messages", messageSchema)) {- const message = row as MessageRow & Msg- if (message.authorId) ids.add(message.authorId)- if (message.replyTo?.authorId) ids.add(message.replyTo.authorId)- for (const participant of message.thread?.participants ?? []) ids.add(participant.id)- for (const profile of [- message.approval?.otherProfile,- message.approval?.botProfile,- message.approval?.waitingOnProfile,- ]) {- if (profile?.id) ids.add(profile.id)- }+ for (const row of collectionRows(registry, "friendships")) ids.add(row.userId)+ for (const row of collectionRows(registry, "messages")) {+ for (const id of messageProfileIds(row as MessageRow & Msg)) ids.add(id)}return ids}@@ -469,7 +426,6 @@ function garbageCollectCommunityProfiles(registry: CommunityDbRegistry) {deleteRows(registry,"profiles",- profileSchema,(row) => !referenced.has(row.userId),)}@@ -529,10 +485,12 @@ function clearChannelTransientState(registry: CommunityDbRegistry,channelIds: ReadonlySet<string>,serverId: string | null,+ preserveQuery?: Query,+ options?: { queries?: ReadonlySet<Query>; assertView?: () => void },) {const messageIds = new Set([...takeMessageIdsForAccessScope(registry.queryClient, channelIds, serverId),- ...collectionRows(registry, "messages", messageSchema)+ ...collectionRows(registry, "messages").filter((row) => channelIds.has(row.channelId)).map((row) => row.id),])@@ -562,7 +520,6 @@ function clearChannelTransientState(clearTypingIndicator(registry.queryClient, scope, userId)}}- if (serverId) registry.runtime.ws.actions.revokeChannelAccess(serverId, channelId)}pruneInboxCaches(registry.queryClient, channelIds, null)if (serverId) {@@ -572,7 +529,9 @@ function clearChannelTransientState(const remembered = getLastMeLeaf()if (remembered && channelIds.has(remembered)) clearLastMeLocation()}- if (community.currentChannelId && channelIds.has(community.currentChannelId)) {+ let viewCurrent = true+ try { options?.assertView?.() } catch { viewCurrent = false }+ if (viewCurrent && !preserveQuery && community.currentChannelId && channelIds.has(community.currentChannelId)) {registry.runtime.ui.actions.setCurrentChannelId(null)}const subscription = { ...community.subscription }@@ -589,6 +548,7 @@ function clearChannelTransientState(registry.runtime.ui.actions.setPendingReply(null)}const predicate = (query: Query) => {+ if (query === preserveQuery || options?.queries && !options.queries.has(query)) return falseconst key = query.queryKeyif (key[0] !== "community" || key[1] === "db") return falseif ((key[1] === "channel" || key[1] === "dm") && channelIds.has(String(key[2]))) return true@@ -605,9 +565,8 @@ function clearChannelTransientState(export function ingestServers(registry: CommunityDbRegistry,response: ServersResponse,- mode: SnapshotIngestMode = "authoritative",) {- const currentServers = collectionRows(registry, "servers", serverSchema)+ const currentServers = collectionRows(registry, "servers")const existingById = new Map(currentServers.map((server) => [server.id, server]))const incomingServerIds = new Set(response.servers.map((server) => server.id))const removedServerIds = currentServers@@ -639,31 +598,15 @@ export function ingestServers(})): []notifyManager.batch(() => {- if (mode === "authoritative") {- for (const serverId of removedServerIds) if (!isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, serverId)) purgeCommunityServer(registry, serverId)- replaceRows(registry, "servers", serverSchema, (row) => row.id, servers, (row) => !isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, row.id))- } else {- upsertRows(registry, "servers", serverSchema, (row) => row.id, servers)- }+ for (const serverId of removedServerIds) if (!isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, serverId)) purgeCommunityServer(registry, serverId)+ replaceRows(registry, "servers", servers, (row) => !isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, row.id))if (viewerId) {- if (mode === "authoritative") {- replaceRows(- registry,- "serverMemberships",- serverMembershipSchema,- (row) => row.id,- memberships,- (row) => row.viewer,- )- } else {- upsertRows(- registry,- "serverMemberships",- serverMembershipSchema,- (row) => row.id,- memberships,- )- }+ replaceRows(+ registry,+ "serverMemberships",+ memberships,+ (row) => row.viewer,+ )}})}@@ -671,9 +614,8 @@ export function ingestServers(export function ingestServerDetail(registry: CommunityDbRegistry,detail: ServerDetail,- mode: SnapshotIngestMode = "authoritative",) {- const existing = collectionRows(registry, "servers", serverSchema)+ const existing = collectionRows(registry, "servers").find((row) => row.id === detail.id)const server: ServerRow = {id: detail.id,@@ -705,7 +647,7 @@ export function ingestServerDetail(})}category.channels.forEach((channel, channelIndex) => {- channels.push({+ channels.push(canonicalChannelRow({id: channel.id,serverId: detail.id,categoryId: uncategorized ? null : category.id,@@ -724,11 +666,11 @@ export function ingestServerDetail(tags: channel.tags ?? [],pending: channel.pending === true,lastMessageAt: null,- })+ }))})})const currentTopLevelIds = new Set(- collectionRows(registry, "channels", channelSchema)+ collectionRows(registry, "channels").filter((row) => row.serverId === detail.id && row.type !== "thread").map((row) => row.id),)@@ -737,16 +679,10 @@ export function ingestServerDetail(.filter((channelId) => !incomingTopLevelIds.has(channelId))const viewerId = registry.accountIdconst accessMemberships: ChannelMembershipRow[] = viewerId- ? channels.map((channel) => ({- id: channelMembershipKey(channel.id, viewerId, "access"),- channelId: channel.id,- userId: viewerId,- relation: "access",- source: "inherited",- }))+ ? channels.map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" }))): []const existingChannels = new Map(- collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),+ collectionRows(registry, "channels").map((row) => [row.id, row]),)const unreadChildOwnership = Object.entries(detail.forumUnreadState ?? {}).flatMap(([parentChannelId, state]) => state.childIds.map((childId) => ({@@ -755,111 +691,62 @@ export function ingestServerDetail(})))const unreadChildStubs: ChannelRow[] = unreadChildOwnership.flatMap((ownership) => {if (existingChannels.has(ownership.childId)) return []- return [{+ return [canonicalChannelRow({id: ownership.childId,serverId: detail.id,- categoryId: null,- name: "",type: "thread" as const,parentChannelId: ownership.parentChannelId,- parentMessageId: null,- creatorId: null,- position: 0,- archived: false,- muted: false,unread: true,- tags: [],- pending: false,- lastMessageAt: null,- }]+ })]})const unreadChildMemberships: ChannelMembershipRow[] = viewerId? unreadChildOwnership.flatMap(({ childId }) => ([- {- id: channelMembershipKey(childId, viewerId, "access"),- channelId: childId,- userId: viewerId,- relation: "access" as const,- source: "explicit" as const,- },- {- id: channelMembershipKey(childId, viewerId, "notify"),- channelId: childId,- userId: viewerId,- relation: "notify" as const,- source: "explicit" as const,- },+ canonicalChannelMembershipRow(childId, viewerId, "access", { source: "explicit" as const }),+ canonicalChannelMembershipRow(childId, viewerId, "notify", { source: "explicit" as const }),])): []const authoritativeTopLevelIds = new Set([...currentTopLevelIds, ...incomingTopLevelIds])notifyManager.batch(() => {- if (mode === "authoritative") {- for (const channelId of removedTopLevelIds) purgeCommunityChannel(registry, channelId)- }- upsertRows(registry, "servers", serverSchema, (row) => row.id, [server])+ for (const channelId of removedTopLevelIds) purgeCommunityChannel(registry, channelId)+ upsertRows(registry, "servers", [server])// Completeness is monotonic query state, not mutable server identity. A// newer WS event may protect the row's fields without blocking this proof// that its canonical tree has arrived.promoteServerDetailComplete(registry, detail.id)- if (mode === "authoritative") {- replaceRows(- registry,- "categories",- categorySchema,- (row) => row.id,- categories,- (row) => row.serverId === detail.id,- )+ replaceRows(+ registry,+ "categories",+ categories,+ (row) => row.serverId === detail.id,+ )+ replaceRows(+ registry,+ "channels",+ channels,+ (row) => row.serverId === detail.id && row.type !== "thread",+ )+ if (viewerId) {replaceRows(registry,- "channels",- channelSchema,- (row) => row.id,- channels,- (row) => row.serverId === detail.id && row.type !== "thread",+ "channelMemberships",+ accessMemberships,+ (row) => row.userId === viewerId+ && row.relation === "access"+ && authoritativeTopLevelIds.has(row.channelId),)- } else {- upsertRows(registry, "categories", categorySchema, (row) => row.id, categories)- upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)- }- if (viewerId) {- if (mode === "authoritative") {- replaceRows(- registry,- "channelMemberships",- channelMembershipSchema,- (row) => row.id,- accessMemberships,- (row) => row.userId === viewerId- && row.relation === "access"- && authoritativeTopLevelIds.has(row.channelId),- )- } else {- upsertRows(- registry,- "channelMemberships",- channelMembershipSchema,- (row) => row.id,- accessMemberships,- )- }upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,unreadChildMemberships,)}- upsertRows(registry, "channels", channelSchema, (row) => row.id, unreadChildStubs)+ upsertRows(registry, "channels", unreadChildStubs)const unreadChildren = new Set(Object.values(detail.forumUnreadState ?? {}).flatMap((state) => state.childIds),)patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({ ...row, unread: unreadChildren.has(row.id) }),(row) => row.serverId === detail.id && row.type === "thread",)@@ -868,44 +755,18 @@ export function ingestServerDetail(function ingestChannelMetadata(registry: CommunityDbRegistry,- metadata: {- id: string- serverId: string | null- name: string | null- type: string- parentChannelId: string | null- parentMessageId: string | null- creatorId: string | null- archived: boolean | number- lastMessageAt: string | null- openerSeq?: number- openerUnread?: boolean- },+ input: unknown,+ proof?: CommunityFreshQueryProof,) {- if (!["dm", "text", "forum", "thread"].includes(metadata.type)) return- const existing = collectionRows(registry, "channels", channelSchema)- .find((row) => row.id === metadata.id)- upsertRows(registry, "channels", channelSchema, (row) => row.id, [{- ...existing,- id: metadata.id,- serverId: metadata.serverId,- categoryId: existing?.categoryId ?? null,- name: metadata.name ?? "",- type: metadata.type as ChannelRow["type"],- parentChannelId: metadata.parentChannelId,- parentMessageId: metadata.parentMessageId,- creatorId: metadata.creatorId,- position: existing?.position ?? 0,- archived: metadata.archived === true || metadata.archived === 1,- muted: existing?.muted ?? false,- unread: existing?.unread ?? false,- ...(existing?.baseUnread === undefined ? {} : { baseUnread: existing.baseUnread }),- tags: existing?.tags ?? [],- pending: false,- lastMessageAt: metadata.lastMessageAt,- ...(metadata.openerSeq === undefined ? {} : { openerSeq: metadata.openerSeq }),- ...(metadata.openerUnread === undefined ? {} : { openerUnread: metadata.openerUnread }),- }])+ const metadata = normalizeCommunityChannelIdentity(input)+ const hints = channelSchema.pick({ openerSeq: true, openerUnread: true }).parse(input)+ const changes = { ...metadata, ...hints, name: metadata.name ?? "", pending: false }+ const existing = registry.collections.channels.get(metadata.id)+ if (proof && existing) {+ publishConfirmedFields(registry.queryClient, "channels", metadata.id, changes, proof)+ } else {+ upsertRows(registry, "channels", [canonicalChannelRow(changes, existing)])+ }}export function ingestDms(@@ -916,7 +777,7 @@ export function ingestDms(const viewerId = registry.accountIdif (!viewerId) returnconst currentDmIds = new Set(- collectionRows(registry, "channels", channelSchema)+ collectionRows(registry, "channels").filter((row) => row.type === "dm").map((row) => row.id),)@@ -924,38 +785,14 @@ export function ingestDms(const memberships: ChannelMembershipRow[] = []const profilePatches: CommunityProfilePatch[] = []for (const [position, dm] of response.conversations.entries()) {- channels.push({- id: dm.id,- serverId: null,- categoryId: null,- name: "",- type: "dm",- parentChannelId: null,- parentMessageId: null,- creatorId: null,- position,- archived: false,- muted: false,- unread: dm.unread === true,- tags: [],- pending: false,- lastMessageAt: dm.activityAt ?? null,- preview: dm.preview,+ channels.push(canonicalChannelRow({+ id: dm.id, type: "dm", position,+ unread: dm.unread === true, lastMessageAt: dm.activityAt ?? null, preview: dm.preview,...(dm.lastUnreadSeq === undefined ? {} : { lastUnreadSeq: dm.lastUnreadSeq }),- })+ }))memberships.push(- {- id: channelMembershipKey(dm.id, viewerId, "access"),- channelId: dm.id,- userId: viewerId,- relation: "access",- },- {- id: channelMembershipKey(dm.id, dm.userId, "access"),- channelId: dm.id,- userId: dm.userId,- relation: "access",- },+ canonicalChannelMembershipRow(dm.id, viewerId, "access"),+ canonicalChannelMembershipRow(dm.id, dm.userId, "access"),)profilePatches.push(communityUserProfilePatch(dm.userId, dm))}@@ -965,22 +802,18 @@ export function ingestDms(notifyManager.batch(() => {if (mode === "authoritative") {for (const channelId of removedDmIds) purgeCommunityChannel(registry, channelId)- replaceRows(registry, "channels", channelSchema, (row) => row.id, channels, (row) => row.type === "dm")+ replaceRows(registry, "channels", channels, (row) => row.type === "dm")replaceRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,memberships,(row) => row.relation === "access" && authoritativeDmIds.has(row.channelId),)} else {- upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)+ upsertRows(registry, "channels", channels)upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,memberships,)}@@ -1009,7 +842,6 @@ export function publishCommunityDmSummary(function ingestFolders(registry: CommunityDbRegistry,response: FoldersResponse,- mode: SnapshotIngestMode = "authoritative",) {const folders: FolderRow[] = response.folders.map((folder) => ({id: folder.id,@@ -1025,35 +857,27 @@ function ingestFolders(}))))notifyManager.batch(() => {- if (mode === "authoritative") {- replaceRows(registry, "folders", folderSchema, (row) => row.id, folders, () => true)- replaceRows(registry, "folderItems", folderItemSchema, (row) => row.id, items, () => true)- } else {- upsertRows(registry, "folders", folderSchema, (row) => row.id, folders)- upsertRows(registry, "folderItems", folderItemSchema, (row) => row.id, items)- }+ replaceRows(registry, "folders", folders, () => true)+ replaceRows(registry, "folderItems", items, () => true)})}export function publishCommunityServerRailCommit(queryClient: QueryClient, projection: ServerRailProjection, proof: CommunityFreshQueryProof) {- assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => {+ return withCommunityQueryProof(queryClient, proof, (registry) => {if (projection.reorderServers) {const positions = new Map(projection.after.serverOrder.map((id, position) => [id, position]))withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- patchRows(registry, "servers", serverSchema, (row) => row.id, (row) => ({ ...row, position: positions.get(row.id)! }), (row) => positions.has(row.id), undefined, ["position"])+ patchRows(registry, "servers", (row) => ({ ...row, position: positions.get(row.id)! }), (row) => positions.has(row.id), undefined, ["position"])})}const affected = new Set([...projection.affectedFolderIds, ...projection.createdFolders.map((row) => row.id), ...(projection.reorderFolders ? projection.after.folderOrder : [])])const folders = projection.after.folderOrder.filter((id) => affected.has(id)).map((id) => ({ id, name: projection.after.folders[id]!.name, position: projection.after.folderOrder.indexOf(id) }))- const knownServers = new Set(collectionRows(registry, "servers", serverSchema).map((row) => row.id))- const allowed = new Set(collectionRows(registry, "serverMemberships", serverMembershipSchema).filter((row) => row.viewer && row.userId === registry.accountId && knownServers.has(row.serverId)).map((row) => row.serverId))+ const knownServers = new Set(collectionRows(registry, "servers").map((row) => row.id))+ const allowed = new Set(collectionRows(registry, "serverMemberships").filter((row) => row.viewer && row.userId === registry.accountId && knownServers.has(row.serverId)).map((row) => row.serverId))const items = folders.flatMap((folder) => projection.after.folders[folder.id]!.serverIds.filter((serverId) => allowed.has(serverId)).map((serverId, position) => ({ id: folderItemKey(folder.id, serverId), folderId: folder.id, serverId, position })))notifyManager.batch(() => {- replaceRows(registry, "folders", folderSchema, (row) => row.id, folders, (row) => affected.has(row.id))- replaceRows(registry, "folderItems", folderItemSchema, (row) => row.id, items, (row) => affected.has(row.folderId))+ replaceRows(registry, "folders", folders, (row) => affected.has(row.id))+ replaceRows(registry, "folderItems", items, (row) => affected.has(row.folderId))})return "published" as const})@@ -1062,137 +886,111 @@ export function publishCommunityServerRailCommit(queryClient: QueryClient, projeexport function ingestMessages(registry: CommunityDbRegistry,channelId: string,- messages: Msg[],+ messages: readonly (MessageInput | CommunityMessageResource)[],) {+ const previous = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))const rows: MessageRow[] = messages- .filter((message) => !message.id.startsWith("temp_") && message.failed !== true)+ .filter((message) => !message.id.startsWith("temp_") && !("failed" in message && message.failed === true)).map((message) => {- const { thread, ...fields } = message+ const { thread, clientNonce, ...fields } = message+ const existingMessage = previous.get(message.id)+ const retainReply = existingMessage?.channelId === channelId+ && (!message.authorId || message.authorId === existingMessage.authorId)+ && (clientNonce === undefined || clientNonce === existingMessage.clientNonce)+ && !("replyTo" in message)+ && (!("replyToId" in message) || message.replyToId === existingMessage.replyToId)if (thread) {- const existing = collectionRows(registry, "channels", channelSchema).find((row) => row.id === thread.id)- const parent = collectionRows(registry, "channels", channelSchema).find((row) => row.id === channelId)- upsertRows(registry, "channels", channelSchema, (row) => row.id, [{ ...existing, id: thread.id, serverId: existing?.serverId ?? parent?.serverId, categoryId: null, name: thread.name, type: "thread", parentChannelId: channelId, parentMessageId: message.id, creatorId: existing?.creatorId ?? null, position: existing?.position ?? 0, archived: existing?.archived ?? false, tags: thread.tags ?? existing?.tags ?? [], muted: existing?.muted ?? false, unread: existing?.unread ?? false, pending: false, messageCount: thread.messageCount, ...(thread.lastReplyAt ? { lastMessageAt: thread.lastReplyAt } : {}), ...(thread.preview !== undefined ? { preview: thread.preview } : {}), ...(thread.participantCount !== undefined ? { participantCount: thread.participantCount } : {}) }])+ const existing = collectionRows(registry, "channels").find((row) => row.id === thread.id)+ const parent = collectionRows(registry, "channels").find((row) => row.id === channelId)+ upsertRows(registry, "channels", [canonicalChannelRow({+ id: thread.id, serverId: existing?.serverId ?? parent?.serverId, categoryId: null,+ name: thread.name, type: "thread", parentChannelId: channelId, parentMessageId: message.id,+ tags: thread.tags ?? existing?.tags ?? [], pending: false, messageCount: thread.messageCount,+ ...(thread.lastReplyAt ? { lastMessageAt: thread.lastReplyAt } : {}),+ ...(thread.preview !== undefined ? { preview: thread.preview } : {}),+ ...(thread.participantCount !== undefined ? { participantCount: thread.participantCount } : {}),+ }, existing)])+ }+ return { ...fields, replyTo: retainReply ? existingMessage!.replyTo : message.replyTo, replyToId: retainReply ? existingMessage!.replyToId : message.replyTo?.id ?? message.replyToId ?? null, ...projectMessageRichContent(fields), type: message.type ?? existingMessage?.type ?? "chat", channelId,+ ...("clientNonce" in message ? { clientNonce: clientNonce ?? undefined } : {}),}- return { ...fields, type: message.type ?? "chat", channelId, replyToId: message.replyTo?.id }})- upsertRows(registry, "messages", messageSchema, (row) => row.id, rows)+ upsertRows(registry, "messages", rows)writeCanonicalProfilePatches(registry, messageProfilePatches(messages))}export function ingestReadStateSnapshot(registry: CommunityDbRegistry,snapshot: AccountReadStateSnapshot,- mode: SnapshotIngestMode = "authoritative",) {- const currentRevision = collectionRows(registry, "readStateClock", readStateClockSchema)+ const currentRevision = collectionRows(registry, "readStateClock").find((row) => row.id === "account")?.revision ?? -1if (snapshot.revision <= currentRevision) returnconst readStates: ReadStateRow[] = snapshot.readStates.map((row) => ({ ...row }))const clock: ReadStateClockRow = { id: "account", revision: snapshot.revision }notifyManager.batch(() => {- if (mode === "authoritative") {- replaceRows(registry, "readStates", readStateSchema, (row) => row.channelId, readStates, () => true)- replaceRows(registry, "readStateClock", readStateClockSchema, (row) => row.id, [clock], () => true)- } else {- upsertRows(registry, "readStates", readStateSchema, (row) => row.channelId, readStates)- upsertRows(registry, "readStateClock", readStateClockSchema, (row) => row.id, [clock])+ replaceRows(registry, "readStates", readStates, () => true)+ replaceRows(registry, "readStateClock", [clock], () => true)+ })+}++function serverSummaryRows(registry: CommunityDbRegistry, summaries: readonly Pick<ServerRow, "id" | "name" | "discriminator">[]): ServerRow[] {+ const existingById = new Map(collectionRows(registry, "servers").map((row) => [row.id, row]))+ return summaries.map((server, position) => {+ const existing = existingById.get(server.id)+ return {+ description: "", ownerId: "", icon: null, official: false, isOwner: false,+ unread: false, mentions: 0, detailComplete: false, ...existing,+ id: server.id, position: existing?.position ?? position,+ name: server.name, discriminator: server.discriminator,}})}+function seedViewerServerMemberships(registry: CommunityDbRegistry, servers: readonly Pick<ServerRow, "id" | "isOwner">[]) {+ const viewerId = registry.accountId+ if (!viewerId) return+ const existingById = new Map(collectionRows(registry, "serverMemberships").map((row) => [row.id, row]))+ upsertRows(registry, "serverMemberships", servers.map((server) => {+ const id = serverMembershipKey(server.id, viewerId), existing = existingById.get(id)+ return { ...existing, id, serverId: server.id, userId: viewerId,+ role: existing?.role ?? (server.isOwner ? "owner" : "member"), viewer: true }+ }))+}+function ingestAttentionIncluded(registry: CommunityDbRegistry,included: Partial<AccountAttentionSnapshot["included"]> | undefined,) {- const existingServers = new Map(- collectionRows(registry, "servers", serverSchema).map((row) => [row.id, row]),- )const existingChannels = new Map(- collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),+ collectionRows(registry, "channels").map((row) => [row.id, row]),)const viewerId = registry.accountId- const existingMemberships = new Map(collectionRows(registry, "serverMemberships", serverMembershipSchema).map((row) => [row.id, row]))- const servers: ServerRow[] = (included?.servers ?? []).map((owner, position) => {- const existing = existingServers.get(owner.id)- return {- id: owner.id,- position: existing?.position ?? position,- name: owner.name,- discriminator: owner.discriminator,- description: existing?.description ?? "",- ownerId: existing?.ownerId ?? "",- icon: existing?.icon ?? null,- official: existing?.official ?? false,- isOwner: existing?.isOwner ?? false,- unread: existing?.unread ?? false,- mentions: existing?.mentions ?? 0,- detailComplete: existing?.detailComplete ?? false,- }- })- upsertRows(registry, "servers", serverSchema, (row) => row.id, servers)+ const servers = serverSummaryRows(registry, included?.servers ?? [])+ upsertRows(registry, "servers", servers)for (const channel of included?.channels ?? []) ingestChannelMetadata(registry, channel)const dmChannels: ChannelRow[] = (included?.dms ?? []).map((dm, position) => {const existing = existingChannels.get(dm.id)- return {+ return canonicalChannelRow({id: dm.id,- serverId: null,- categoryId: null,- name: "",type: "dm",- parentChannelId: null,- parentMessageId: null,- creatorId: null,position: existing?.position ?? position,- archived: false,muted: existing?.muted ?? false,unread: true,- tags: [],- pending: false,lastMessageAt: dm.lastMessageAt,preview: existing?.preview ?? "",lastUnreadSeq: dm.lastUnreadSeq,- }+ })})- upsertRows(registry, "channels", channelSchema, (row) => row.id, dmChannels)+ upsertRows(registry, "channels", dmChannels)if (viewerId) {- upsertRows(- registry,- "serverMemberships",- serverMembershipSchema,- (row) => row.id,- servers.map((server) => ({- ...existingMemberships.get(serverMembershipKey(server.id, viewerId)),- id: serverMembershipKey(server.id, viewerId),- serverId: server.id,- userId: viewerId,- role: existingMemberships.get(serverMembershipKey(server.id, viewerId))?.role ?? (server.isOwner ? "owner" : "member"),- viewer: true,- })),- )+ seedViewerServerMemberships(registry, servers)upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,[- ...(included?.channels ?? []).map((channel) => ({- id: channelMembershipKey(channel.id, viewerId, "access"),- channelId: channel.id,- userId: viewerId,- relation: "access" as const,- source: "inherited" as const,- })),- ...(included?.dms ?? []).flatMap((dm) => [{- id: channelMembershipKey(dm.id, viewerId, "access"),- channelId: dm.id,- userId: viewerId,- relation: "access" as const,- }, {- id: channelMembershipKey(dm.id, dm.userId, "access"),- channelId: dm.id,- userId: dm.userId,- relation: "access" as const,- }]),+ ...(included?.channels ?? []).map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" as const }))),+ ...(included?.dms ?? []).flatMap((dm) => [canonicalChannelMembershipRow(dm.id, viewerId, "access"), canonicalChannelMembershipRow(dm.id, dm.userId, "access")]),],)}@@ -1205,13 +1003,13 @@ function ingestAttentionIncluded(const messages = messageSchema.array().safeParse(included?.messages ?? [])if (messages.success) {const current = new Map(- collectionRows(registry, "messages", messageSchema).map((row) => [row.id, row]),+ collectionRows(registry, "messages").map((row) => [row.id, row]),)const merged = messages.data.map((message) => ({...current.get(message.id),...Object.fromEntries(Object.entries(message).filter(([, value]) => value !== undefined)),})) as MessageRow[]- upsertRows(registry, "messages", messageSchema, (row) => row.id, merged)+ upsertRows(registry, "messages", merged)}}@@ -1223,7 +1021,7 @@ type AttentionFloor = {ordinary: booleanmentions: boolean}-type AttentionIntent = {+export type AttentionIntent = {token: symbolgeneration: numberscopesQuery: Query | undefined@@ -1302,7 +1100,7 @@ function attentionProjection(})}}- const messages = new Map(collectionRows(registry, "messages", messageSchema).map((message) => [message.id, message]))+ const messages = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))const seqOf = (item: AttentionItemRow) => item.readTarget?.seq ?? item.openerSeq ?? (item.messageId ? messages.get(item.messageId)?.seq : undefined)const removedByScope = new Map<string, number>()const survivingByScope = new Map<string, number>()@@ -1365,8 +1163,8 @@ function rebaseAttentionTransactions(registry: CommunityDbRegistry) {}return}- const scopes = collectionRows(registry, "attentionScopes", attentionScopeSchema)- const items = collectionRows(registry, "attentionItems", attentionItemSchema)+ const scopes = collectionRows(registry, "attentionScopes")+ const items = collectionRows(registry, "attentionItems")const prefix: AttentionIntent[] = []for (const intent of intents.values()) {prefix.push(intent)@@ -1439,8 +1237,8 @@ function publishAttentionConfirmation(registry: CommunityDbRegistry, current: Atmentions: floor.mentions && committed.has(floor.domain === "dms" ? "dms" : "mentions"),}]))const confirmed = { ...current, floors, itemIds: new Set([...current.itemIds].filter((id) => committed.has(current.itemDomains.get(id) ?? "mentions"))) }- const scopes = collectionRows(registry, "attentionScopes", attentionScopeSchema)- const items = collectionRows(registry, "attentionItems", attentionItemSchema)+ const scopes = collectionRows(registry, "attentionScopes")+ const items = collectionRows(registry, "attentionItems")const projected = attentionProjection(registry, scopes, items, [confirmed])const nextScopes = new Map(projected.scopes.map((scope) => [scope.scopeId, scope]))const previousScopes = new Map(scopes.map((scope) => [scope.scopeId, scope]))@@ -1448,9 +1246,9 @@ function publishAttentionConfirmation(registry: CommunityDbRegistry, current: Atconst removedScopes = new Set(scopes.filter((scope) => !nextScopes.has(scope.scopeId)).map((scope) => scope.scopeId))const removedItems = new Set(items.filter((item) => !nextItems.has(item.id)).map((item) => item.id))withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {- if (removedScopes.size) deleteRows(registry, "attentionScopes", attentionScopeSchema, (row) => removedScopes.has(row.scopeId))- upsertRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, projected.scopes.filter((scope) => JSON.stringify(scope) !== JSON.stringify(previousScopes.get(scope.scopeId))))- if (removedItems.size) deleteRows(registry, "attentionItems", attentionItemSchema, (row) => removedItems.has(row.id))+ if (removedScopes.size) deleteRows(registry, "attentionScopes", (row) => removedScopes.has(row.scopeId))+ upsertRows(registry, "attentionScopes", projected.scopes.filter((scope) => JSON.stringify(scope) !== JSON.stringify(previousScopes.get(scope.scopeId))))+ if (removedItems.size) deleteRows(registry, "attentionItems", (row) => removedItems.has(row.id))})const store = attentionTransactionStores.get(registry)store?.setState((state) => ({ ...state, intents: new Map([...state.intents].map(([token, intent]) => {@@ -1521,49 +1319,46 @@ export function hasAttentionScopeOptimisticFence(queryClient: QueryClient, scopeexport function ingestAttentionSnapshot(registry: CommunityDbRegistry, snapshot: AccountAttentionSnapshot) {notifyManager.batch(() => {- const pending = collectionRows(registry, "friendships", friendshipSchema).filter((row) => row.kind === "incoming" && row.needsOwnerApproval == null)- const blocked = new Set(collectionRows(registry, "friendships", friendshipSchema).filter((row) => row.kind === "blocked").map((row) => row.userId))+ const pending = collectionRows(registry, "friendships").filter((row) => row.kind === "incoming" && row.needsOwnerApproval == null)+ const blocked = new Set(collectionRows(registry, "friendships").filter((row) => row.kind === "blocked").map((row) => row.userId))ingestAttentionIncluded(registry, snapshot.included)- replaceRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, snapshot.scopes, () => true)- replaceRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, snapshot.items.filter((row) => row.kind !== "friend_request" || !row.actorUserId || (!blocked.has(row.actorUserId) && !isProtectedFromQueryWrite(registry, "friendships", `user:${row.actorUserId}`))), () => true)- const requests = collectionRows(registry, "attentionItems", attentionItemSchema).filter((row) => row.kind === "friend_request" && row.actorUserId)- upsertRows(registry, "friendships", friendshipSchema, (row) => row.id, requests.filter((row) => !blocked.has(row.actorUserId!)).map((row) => ({ id: row.sourceId, userId: row.actorUserId!, kind: "incoming" as const })))+ replaceRows(registry, "attentionScopes", snapshot.scopes, () => true)+ replaceRows(registry, "attentionItems", snapshot.items.filter((row) => row.kind !== "friend_request" || !row.actorUserId || (!blocked.has(row.actorUserId) && !isProtectedFromQueryWrite(registry, "friendships", `user:${row.actorUserId}`))), () => true)+ const requests = collectionRows(registry, "attentionItems").filter((row) => row.kind === "friend_request" && row.actorUserId)+ upsertRows(registry, "friendships", requests.filter((row) => !blocked.has(row.actorUserId!)).map((row) => ({ id: row.sourceId, userId: row.actorUserId!, kind: "incoming" as const })))if (!snapshot.truncated) retireCanonicalFriendRequests(registry, pending.filter((row) => !requests.some((item) => item.sourceId === row.id)).map((row) => row.id))rebaseAttentionTransactions(registry)})return "applied" as const}-export type AttentionOptimisticSnapshot = AttentionIntentexport type AttentionScopeOptimisticSnapshot = AttentionIntent & { scopeId: string; targetSeq: number }-export type AttentionItemsOptimisticSnapshot = AttentionIntent--export function clearAttentionOptimistically(registry: CommunityDbRegistry): AttentionOptimisticSnapshot {- const floors = new Map(collectionRows(registry, "attentionScopes", attentionScopeSchema).map((scope) => [scope.scopeId, {+export function clearAttentionOptimistically(registry: CommunityDbRegistry): AttentionIntent {+ const floors = new Map(collectionRows(registry, "attentionScopes").map((scope) => [scope.scopeId, {throughSeq: Math.max(scope.lastUnreadSeq, scope.lastAttentionSeq ?? 0),clearedCount: scope.attentionCount, domain: scope.serverId == null ? "dms" as const : "channels" as const,ordinary: true, mentions: true,}]))- const items = collectionRows(registry, "attentionItems", attentionItemSchema).filter((item) => item.kind !== "friend_request")+ const items = collectionRows(registry, "attentionItems").filter((item) => item.kind !== "friend_request")return beginAttentionIntent(registry, { floors, itemIds: new Set(items.map((item) => item.id)), itemDomains: new Map(items.map((item) => [item.id, "mentions" as const])), clearedAttentionCount: 0 })}-export function commitAttentionOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionOptimisticSnapshot) {+export function commitAttentionOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionIntent) {settleAttentionIntent(registry, snapshot, new Set(["channels", "dms", "mentions"]))return snapshot.settled}-export function restoreAttentionOptimisticDomains(registry: CommunityDbRegistry, snapshot: AttentionOptimisticSnapshot, failedDomains: ReadonlySet<AttentionDomain>) {+export function restoreAttentionOptimisticDomains(registry: CommunityDbRegistry, snapshot: AttentionIntent, failedDomains: ReadonlySet<AttentionDomain>) {settleAttentionIntent(registry, snapshot, new Set((["channels", "dms", "mentions"] as const).filter((domain) => !failedDomains.has(domain))))return snapshot.settled}-export function restoreAttentionOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionOptimisticSnapshot) {+export function restoreAttentionOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionIntent) {return settleAttentionIntent(registry, snapshot)}export function clearAttentionScopeOptimistically(registry: CommunityDbRegistry, scopeId: string, targetSeq: number): AttentionScopeOptimisticSnapshot {- const scope = collectionRows(registry, "attentionScopes", attentionScopeSchema).find((row) => row.scopeId === scopeId)- const messages = new Map(collectionRows(registry, "messages", messageSchema).map((message) => [message.id, message]))- const items = collectionRows(registry, "attentionItems", attentionItemSchema).filter((item) => item.scopeId === scopeId)+ const scope = collectionRows(registry, "attentionScopes").find((row) => row.scopeId === scopeId)+ const messages = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))+ const items = collectionRows(registry, "attentionItems").filter((item) => item.scopeId === scopeId)const seqOf = (item: AttentionItemRow) => item.readTarget?.seq ?? item.openerSeq ?? (item.messageId ? messages.get(item.messageId)?.seq : undefined)const removed = items.filter((item) => (seqOf(item) ?? scope?.lastUnreadSeq ?? 0) <= targetSeq)const surviving = items.filter((item) => (item.kind === "mention" || item.kind === "reply") && (seqOf(item) ?? -1) > targetSeq).length@@ -1582,15 +1377,15 @@ export function restoreAttentionScopeOptimisticSnapshot(registry: CommunityDbRegreturn settleAttentionIntent(registry, snapshot)}-export function removeAttentionItemsOptimistically(registry: CommunityDbRegistry, remove: (item: AttentionItemRow) => boolean): AttentionItemsOptimisticSnapshot {- const items = collectionRows(registry, "attentionItems", attentionItemSchema).filter(remove)+export function removeAttentionItemsOptimistically(registry: CommunityDbRegistry, remove: (item: AttentionItemRow) => boolean): AttentionIntent {+ const items = collectionRows(registry, "attentionItems").filter(remove)return beginAttentionIntent(registry, { floors: new Map(), itemIds: new Set(items.map((item) => item.id)), itemDomains: new Map(items.map((item) => [item.id, "mentions" as const])), clearedAttentionCount: 0 })}-export function commitAttentionItemsOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionItemsOptimisticSnapshot) {+export function commitAttentionItemsOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionIntent) {settleAttentionIntent(registry, snapshot, new Set(["channels", "dms", "mentions"]))return snapshot.settled}-export function restoreAttentionItemsOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionItemsOptimisticSnapshot) {+export function restoreAttentionItemsOptimisticSnapshot(registry: CommunityDbRegistry, snapshot: AttentionIntent) {return settleAttentionIntent(registry, snapshot)}@@ -1608,8 +1403,6 @@ function ingestNotificationSettings(replaceRows(registry,"notificationSettings",- notificationSettingSchema,- (row) => row.id,rows,() => true,)@@ -1617,8 +1410,6 @@ function ingestNotificationSettings(upsertRows(registry,"notificationSettings",- notificationSettingSchema,- (row) => row.id,rows,)}@@ -1638,6 +1429,9 @@ export type CommunityLiveSnapshotToken = {readonly viewerId: string | nullreadonly accountEpoch: numberreadonly accessEpoch: number+ readonly channelId?: string+ readonly channelLineage?: Pick<ChannelRow, "parentChannelId">+ readonly channelScopes: ReturnType<ReturnType<typeof getCommunityRuntime>["ws"]["get"]>["channelAccessScopes"]readonly profileSnapshot: CommunityProfileSeedSnapshotreadonly canonicalRevision: numberreadonly queryClient: QueryClient@@ -1675,51 +1469,66 @@ export type CommunityFreshQueryProof = {}export function publishCommunityMembersSnapshot(queryClient: QueryClient, serverId: string, members: readonly { id: string; userId: string; role: string }[], proof: CommunityFreshQueryProof) {- assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- const registry = proof.token.registry!- return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => {- const previous = new Map(collectionRows(registry, "serverMemberships", serverMembershipSchema).map((row) => [row.id, row]))- upsertRows(registry, "serverMemberships", serverMembershipSchema, (row) => row.id, members.map((member) => {+ return withCommunityQueryProof(queryClient, proof, (registry) => {+ const previous = new Map(collectionRows(registry, "serverMemberships").map((row) => [row.id, row]))+ upsertRows(registry, "serverMemberships", members.map((member) => {const id = serverMembershipKey(serverId, member.userId)return { ...previous.get(id), id, serverId, userId: member.userId, memberId: member.id, role: member.role, viewer: member.userId === registry.accountId }}))})}-export function publishCommunityChannelMembersSnapshot(queryClient: QueryClient, serverId: string, channelId: string, relation: "access" | "notify", members: readonly { id: string; userId: string; role: string; source: NonNullable<ChannelMembershipRow["source"]>; isCreator: boolean }[], proof: CommunityFreshQueryProof) {+function withCommunityQueryProof<T>(queryClient: QueryClient, proof: CommunityFreshQueryProof, publish: (registry: CommunityDbRegistry) => T): T {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- publishCommunityMembersSnapshot(queryClient, serverId, members, proof)- const registry = proof.token.registry!- return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => {- replaceRows(registry, "channelMemberships", channelMembershipSchema, (row) => row.id, members.map((member) => ({ id: channelMembershipKey(channelId, member.userId, relation), channelId, userId: member.userId, relation, memberId: member.id, source: member.source, isCreator: member.isCreator })), (row) => row.channelId === channelId && row.relation === relation)+ return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => publish(proof.token.registry!))+}++function ingestResourceProfiles(registry: CommunityDbRegistry, profiles: readonly CommunityResourceProfile[], proof: CommunityFreshQueryProof) {+ writeCommunityProfilePatches(profiles.map((profile) => communityUserProfilePatch(profile.id, { ...profile, discriminator: profile.discriminator ?? "", avatar: profile.avatar ?? avatarInitial(profile.name) })), registry, { snapshot: proof.token.profileSnapshot })+}++export function publishCommunityChannelMembersSnapshot(queryClient: QueryClient, serverId: string | null, channelId: string, relation: CommunityMemberRelation["relation"], members: readonly CommunityMemberRelation[], proof: CommunityFreshQueryProof, profiles: readonly CommunityResourceProfile[] = []) {+ if (serverId) publishCommunityMembersSnapshot(queryClient, serverId, members.flatMap((member) => member.role === null || member.memberId === null ? [] : [{ ...member, id: member.memberId, role: member.role }]), proof)+ return withCommunityQueryProof(queryClient, proof, (registry) => {+ ingestResourceProfiles(registry, profiles, proof)+ replaceRows(registry, "channelMemberships", members.map((member) => channelMembershipSchema.parse({ ...member, id: channelMembershipKey(channelId, member.userId, relation), memberId: member.memberId ?? undefined })), (row) => row.channelId === channelId && row.relation === relation)})}export function publishCommunityMemberRole(queryClient: QueryClient, memberKey: string, memberId: string, role: string, proof: CommunityFreshQueryProof) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- const row = collectionRows(proof.token.registry!, "serverMemberships", serverMembershipSchema).find((row) => row.id === memberKey)+ const row = collectionRows(proof.token.registry!, "serverMemberships").find((row) => row.id === memberKey)if (!row || row.memberId !== memberId) return false- return publishConfirmedFields(queryClient, "serverMemberships", serverMembershipSchema, memberKey, { role }, proof)+ return publishConfirmedFields(queryClient, "serverMemberships", memberKey, { role }, proof)}export function publishCommunityMemberRemoval(queryClient: QueryClient, memberKey: string, memberId: string, proof: CommunityFreshQueryProof) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!- if (!collectionRows(registry, "serverMemberships", serverMembershipSchema).some((row) => row.id === memberKey && row.memberId === memberId)) return false+ if (!collectionRows(registry, "serverMemberships").some((row) => row.id === memberKey && row.memberId === memberId)) return falsereturn withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- deleteRows(registry, "serverMemberships", serverMembershipSchema, (row) => row.id === memberKey && row.memberId === memberId, [memberKey])+ deleteRows(registry, "serverMemberships", (row) => row.id === memberKey && row.memberId === memberId, [memberKey])return true})}export function captureCommunityLiveSnapshotToken(queryClient: QueryClient,+ channelId?: string,): CommunityLiveSnapshotToken {const state = getCommunityRuntime(queryClient).ws.get()+ const registry = getCommunityDbRegistry(queryClient)+ const row = channelId ? registry?.collections.channels.get(channelId) : undefined+ const scope = channelId ? state.channelAccessScopes.get(channelId) : undefined+ const parentChannelId = row?.parentChannelId ?? scope?.parentChannelId+ const lineageKnown = !!row && (row.type !== "thread" || !!parentChannelId) || scope?.serverId === null || !!parentChannelIdreturn {+ channelLineage: lineageKnown ? { parentChannelId } : undefined,viewerId: state.profileViewerId,accountEpoch: state.profileAccountEpoch,accessEpoch: state.accessEpoch,+ channelId,+ channelScopes: state.channelAccessScopes,canonicalRevision: canonicalRevisionState(queryClient).revision,profileSnapshot: beginCommunityProfileSeed(getCommunityDbRegistry(queryClient)),queryClient,@@ -1741,6 +1550,9 @@ export function assertCommunityLiveSnapshotTokenCurrent(|| state.profileViewerId !== token.viewerId|| state.profileAccountEpoch !== token.accountEpoch|| state.accessEpoch !== token.accessEpoch+ || (token.channelId && token.channelLineage+ ? [token.channelId, token.channelLineage.parentChannelId].some((id) => id && (state.channelAccessScopes.get(id)?.generation ?? 0) !== (token.channelScopes.get(id)?.generation ?? 0))+ : [...state.channelAccessScopes].some(([id, scope]) => scope.generation !== (token.channelScopes.get(id)?.generation ?? 0)))|| queryClient !== token.queryClient|| getCommunityDbRegistry(queryClient) !== token.registry) throw new DOMException("Stale community live snapshot", "AbortError")@@ -1763,23 +1575,17 @@ export function publishCommunityLiveSnapshot(publication: CommunityLiveSnapshotPublication,) {const { proof, snapshot } = publication- assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- if (proof.kind === "read-state") {- if (- proof.requestGeneration !== proof.currentRequestGeneration- || (- proof.targetRevision !== null- && (snapshot as Extract<CommunityLiveSnapshot, { kind: "read-state" }>).data.revision- < proof.targetRevision- )- ) return "superseded" as const- }- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot,- }, () => {+ return withCommunityQueryProof(queryClient, proof, (registry) => {+ if (proof.kind === "read-state") {+ if (+ proof.requestGeneration !== proof.currentRequestGeneration+ || (+ proof.targetRevision !== null+ && (snapshot as Extract<CommunityLiveSnapshot, { kind: "read-state" }>).data.revision+ < proof.targetRevision+ )+ ) return "superseded" as const+ }switch (snapshot.kind) {case "servers":ingestServers(registry, snapshot.data)@@ -1814,17 +1620,7 @@ export function publishAccountAttentionSnapshot(proof: CommunityFreshQueryProof},) {- assertCommunityLiveSnapshotTokenCurrent(- queryClient,- publication.proof.token,- publication.proof.signal,- )- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: publication.proof.token.canonicalRevision, profileSnapshot: publication.proof.token.profileSnapshot,- }, () => {+ return withCommunityQueryProof(queryClient, publication.proof, (registry) => {ingestAttentionSnapshot(registry, publication.snapshot)return "published" as const})@@ -1839,17 +1635,7 @@ export function publishCommunityMessages(proof: CommunityFreshQueryProof},) {- assertCommunityLiveSnapshotTokenCurrent(- queryClient,- publication.proof.token,- publication.proof.signal,- )- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: publication.proof.token.canonicalRevision, profileSnapshot: publication.proof.token.profileSnapshot,- }, () => {+ return withCommunityQueryProof(queryClient, publication.proof, (registry) => {ingestMessages(registry, publication.channelId, publication.messages)return "published" as const})@@ -1859,22 +1645,12 @@ export function publishCommunityMessages(export function publishCommunityEmbeddedMessages(queryClient: QueryClient,publication: {- entries: Array<{ channelId: string; message: Msg }>+ entries: Array<{ channelId: string; message: MessageInput | CommunityMessageResource }>proof: CommunityFreshQueryProof},) {- assertCommunityLiveSnapshotTokenCurrent(- queryClient,- publication.proof.token,- publication.proof.signal,- )- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: publication.proof.token.canonicalRevision, profileSnapshot: publication.proof.token.profileSnapshot,- }, () => {- const byChannel = new Map<string, Msg[]>()+ return withCommunityQueryProof(queryClient, publication.proof, (registry) => {+ const byChannel = new Map<string, Array<MessageInput | CommunityMessageResource>>()for (const { channelId, message } of publication.entries) {byChannel.set(channelId, [...(byChannel.get(channelId) ?? []), message])}@@ -1887,29 +1663,17 @@ export function publishCommunityEmbeddedMessages(})}-export type CommunityChannelMetadata = {- id: string- serverId: string | null- name: string | null- type: string- parentChannelId: string | null- parentMessageId: string | null- creatorId: string | null- archived: boolean | number- lastMessageAt: string | null-}-function qualifyCanonicalChannelMetadata(registry: CommunityDbRegistry, channelIds: readonly string[], token: CommunityLiveSnapshotToken) {if (!registry.accountId) returnfor (const channelId of channelIds) {const channel = registry.collections.channels.get(channelId)const membership = registry.collections.channelMemberships.get(channelMembershipKey(channelId, registry.accountId, "access"))if (!channel || channel.pending || channel.archived || !membership) continue- registry.queryClient.setQueryData(communityKeys.channelMeta(channel.serverId ?? null, channelId), (previous: { historyVerification?: unknown } | undefined) => ({+ registry.queryClient.setQueryData(communityKeys.channelMeta(channel.serverId ?? null, channelId), (previous: { readProof?: unknown } | undefined) => ({id: channel.id,- verifiedEpoch: token.accessEpoch,- verification: { ...token, channelId, generation: registry.runtime.ws.get().channelAccessScopes.get(channelId)?.generation ?? 0 },- historyVerification: previous?.historyVerification,+ serverId: channel.serverId ?? null,+ identityProof: { ...token, channelId },+ readProof: previous?.readProof,}))}}@@ -1918,53 +1682,18 @@ function qualifyCanonicalChannelMetadata(registry: CommunityDbRegistry, channelIexport function publishCommunityChannelMetadata(queryClient: QueryClient,publication: {- metadata: CommunityChannelMetadata+ metadata: CommunityChannelIdentityproof: CommunityFreshQueryProof},) {- assertCommunityLiveSnapshotTokenCurrent(- queryClient,- publication.proof.token,- publication.proof.signal,- )- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: publication.proof.token.canonicalRevision, profileSnapshot: publication.proof.token.profileSnapshot,- }, () => {- const metadata = publication.metadata- const existing = collectionRows(registry, "channels", channelSchema)- .find((row) => row.id === metadata.id)- if (existing) {- publishConfirmedFields<ChannelRow>(queryClient, "channels", channelSchema, metadata.id, {- serverId: metadata.serverId,- name: metadata.name ?? "",- type: metadata.type as ChannelRow["type"],- parentChannelId: metadata.parentChannelId,- parentMessageId: metadata.parentMessageId,- creatorId: metadata.creatorId,- archived: metadata.archived === true || metadata.archived === 1,- lastMessageAt: metadata.lastMessageAt,- pending: false,- }, publication.proof)- } else {- ingestChannelMetadata(registry, metadata)- }+ return withCommunityQueryProof(queryClient, publication.proof, (registry) => {+ ingestChannelMetadata(registry, publication.metadata, publication.proof)const viewerId = registry.accountIdif (viewerId) {upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,- [{- id: channelMembershipKey(publication.metadata.id, viewerId, "access"),- channelId: publication.metadata.id,- userId: viewerId,- relation: "access",- source: "explicit",- }],+ [canonicalChannelMembershipRow(publication.metadata.id, viewerId, "access", { source: "explicit" })],)}return "published" as const@@ -1979,95 +1708,33 @@ export function publishCommunityChannelDirectory(proof: CommunityFreshQueryProof},) {- assertCommunityLiveSnapshotTokenCurrent(- queryClient,- publication.proof.token,- publication.proof.signal,- )- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: publication.proof.token.canonicalRevision, profileSnapshot: publication.proof.token.profileSnapshot,- }, () => {- const existingServers = new Map(- collectionRows(registry, "servers", serverSchema).map((row) => [row.id, row]),- )+ return withCommunityQueryProof(queryClient, publication.proof, (registry) => {const existingChannels = new Map(- collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),+ collectionRows(registry, "channels").map((row) => [row.id, row]),)const viewerId = registry.accountId- const existingMemberships = new Map(collectionRows(registry, "serverMemberships", serverMembershipSchema).map((row) => [row.id, row]))- const servers: ServerRow[] = publication.directory.map((server, position) => ({- id: server.id,- position: existingServers.get(server.id)?.position ?? position,- name: server.name,- discriminator: server.discriminator,- description: existingServers.get(server.id)?.description ?? "",- ownerId: existingServers.get(server.id)?.ownerId ?? "",- icon: existingServers.get(server.id)?.icon ?? null,- official: existingServers.get(server.id)?.official ?? false,- isOwner: existingServers.get(server.id)?.isOwner ?? false,- unread: existingServers.get(server.id)?.unread ?? false,- mentions: existingServers.get(server.id)?.mentions ?? 0,- detailComplete: existingServers.get(server.id)?.detailComplete ?? false,- }))+ const servers = serverSummaryRows(registry, publication.directory)const channels: ChannelRow[] = publication.directory.flatMap((server) => (server.channels.flatMap((channel, position) => {const existing = existingChannels.get(channel.id)// Older directory payloads predate the subtype field and therefore only// describe text channels. Preserve any richer canonical subtype first.const type = channel.type ?? existing?.type ?? "text"- return [{- id: channel.id,- serverId: server.id,- categoryId: existing?.categoryId ?? null,- name: channel.name,- type,- parentChannelId: null,- parentMessageId: null,- creatorId: existing?.creatorId ?? null,- position: existing?.position ?? position,- archived: existing?.archived ?? false,- muted: existing?.muted ?? false,- unread: existing?.unread ?? false,- ...(existing?.baseUnread === undefined ? {} : { baseUnread: existing.baseUnread }),- tags: existing?.tags ?? [],- pending: existing?.pending ?? false,- lastMessageAt: existing?.lastMessageAt ?? null,- }]+ return [canonicalChannelRow({+ id: channel.id, serverId: server.id, name: channel.name, type,+ parentChannelId: null, parentMessageId: null, position: existing?.position ?? position,+ }, existing)]})))notifyManager.batch(() => {- upsertRows(registry, "servers", serverSchema, (row) => row.id, servers)- upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)+ upsertRows(registry, "servers", servers)+ upsertRows(registry, "channels", channels)if (viewerId) {- upsertRows(- registry,- "serverMemberships",- serverMembershipSchema,- (row) => row.id,- servers.map((server) => ({- ...existingMemberships.get(serverMembershipKey(server.id, viewerId)),- id: serverMembershipKey(server.id, viewerId),- serverId: server.id,- userId: viewerId,- role: existingMemberships.get(serverMembershipKey(server.id, viewerId))?.role ?? (server.isOwner ? "owner" : "member"),- viewer: true,- })),- )+ seedViewerServerMemberships(registry, servers)upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,- channels.map((channel) => ({- id: channelMembershipKey(channel.id, viewerId, "access"),- channelId: channel.id,- userId: viewerId,- relation: "access" as const,- source: "inherited" as const,- })),+ channels.map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" as const }))),)}})@@ -2075,28 +1742,17 @@ export function publishCommunityChannelDirectory(})}-export type CommunityForumSidebarChannel = {- id: string- name: string- parentChannelId: string | null- parentMessageId: string | null+export type CommunityForumSidebarChannel = Pick<CommunityChannelIdentity, "id" | "parentChannelId" | "parentMessageId"> & Partial<Pick<CommunityChannelIdentity, "creatorId" | "lastMessageAt">> & {+ name: NonNullable<CommunityChannelIdentity["name"]>+ serverId?: NonNullable<CommunityChannelIdentity["serverId"]>+ type?: string+ archived?: CommunityChannelIdentity["archived"] | numberactivityAt: stringunread: boolean- serverId?: string- type?: string- creatorId?: string | null- archived?: boolean | number- lastMessageAt?: string | nullparticipating?: boolean}-export type CommunityForumSidebarOpener = {- id: string- content: string- seq?: number- channelId?: string- type?: "chat" | "system"-}+export type CommunityForumSidebarOpener = Pick<CommunityMessageResource, "id" | "content"> & Partial<Pick<CommunityMessageResource, "seq" | "channelId" | "type">>/** Publish the service facts carried by one forum-sidebar response. */export function publishCommunityForumSidebar(@@ -2112,50 +1768,35 @@ export function publishCommunityForumSidebar(proof: CommunityFreshQueryProof},) {- assertCommunityLiveSnapshotTokenCurrent(- queryClient,- publication.proof.token,- publication.proof.signal,- )- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return "no-registry" as const- return withCanonicalWriteContext(queryClient, {- kind: "query",- requestRevision: publication.proof.token.canonicalRevision, profileSnapshot: publication.proof.token.profileSnapshot,- }, () => {+ return withCommunityQueryProof(queryClient, publication.proof, (registry) => {const existingById = new Map(- collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),+ collectionRows(registry, "channels").map((row) => [row.id, row]),)const channels: ChannelRow[] = publication.channels.flatMap((channel) => {if (!channel.parentChannelId || !channel.parentMessageId) return []const existing = existingById.get(channel.id)- return [{+ return [canonicalChannelRow({id: channel.id,serverId: channel.serverId ?? publication.serverId,- categoryId: null,name: channel.name,type: "thread" as const,parentChannelId: channel.parentChannelId,parentMessageId: channel.parentMessageId,creatorId: channel.creatorId ?? existing?.creatorId ?? null,- position: existing?.position ?? 0,archived: channel.archived === true || channel.archived === 1,- muted: existing?.muted ?? false,unread: channel.unread,- tags: existing?.tags ?? [],- pending: false,lastMessageAt: channel.lastMessageAt ?? channel.activityAt,- }]+ }, existing)]})const viewerId = registry.accountIdnotifyManager.batch(() => {- upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)+ upsertRows(registry, "channels", channels)for (const channel of publication.channels) {if (channel.participating === false || channel.archived === true || channel.archived === 1) continue- const current = collectionRows(registry, "channels", channelSchema)+ const current = collectionRows(registry, "channels").find((row) => row.id === channel.id && row.serverId === publication.serverId && row.type === "thread")if (current?.tags.includes(FORUM_ARCHIVE_TAG)) {- publishConfirmedFields<ChannelRow>(queryClient, "channels", channelSchema, channel.id, {+ publishConfirmedFields(queryClient, "channels", channel.id, {tags: current.tags.filter((tag) => tag !== FORUM_ARCHIVE_TAG),}, publication.proof)}@@ -2164,15 +1805,7 @@ export function publishCommunityForumSidebar(upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,- channels.map((channel) => ({- id: channelMembershipKey(channel.id, viewerId, "access"),- channelId: channel.id,- userId: viewerId,- relation: "access" as const,- source: "explicit" as const,- })),+ channels.map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "explicit" as const }))),)const participating = publication.channels.filter((channel) => channel.participating !== false)@@ -2180,15 +1813,7 @@ export function publishCommunityForumSidebar(upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,- participating.map((channelId) => ({- id: channelMembershipKey(channelId, viewerId, "notify"),- channelId,- userId: viewerId,- relation: "notify" as const,- source: "explicit" as const,- })),+ participating.map((channelId) => (canonicalChannelMembershipRow(channelId, viewerId, "notify", { source: "explicit" as const }))),)}for (const opener of publication.openers) {@@ -2203,31 +1828,15 @@ export function publishCommunityForumSidebar(if (publication.negativeRetain) {const { id, disposition } = publication.negativeRetainif (disposition === "opener-archived") {- const current = collectionRows(registry, "channels", channelSchema)+ const current = collectionRows(registry, "channels").find((row) => row.id === id)if (!current) {- upsertRows(registry, "channels", channelSchema, (row) => row.id, [{- id,- serverId: publication.serverId,- categoryId: null,- name: "",- type: "thread",- parentChannelId: null,- parentMessageId: null,- creatorId: null,- position: 0,- archived: false,- muted: false,- unread: false,- tags: [],- pending: true,- lastMessageAt: null,- }])+ upsertRows(registry, "channels", [canonicalChannelRow({ id, serverId: publication.serverId, type: "thread", pending: true })])}- const target = collectionRows(registry, "channels", channelSchema)+ const target = collectionRows(registry, "channels").find((row) => row.id === id && row.serverId === publication.serverId && row.type === "thread")if (target && !target.tags.includes(FORUM_ARCHIVE_TAG)) {- publishConfirmedFields<ChannelRow>(queryClient, "channels", channelSchema, id, {+ publishConfirmedFields(queryClient, "channels", id, {tags: [...target.tags, FORUM_ARCHIVE_TAG],}, publication.proof)}@@ -2235,7 +1844,6 @@ export function publishCommunityForumSidebar(deleteRows(registry,"channelMemberships",- channelMembershipSchema,(row) => row.channelId === id&& row.userId === viewerId&& row.relation === "notify",@@ -2244,8 +1852,6 @@ export function publishCommunityForumSidebar(patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({ ...row, unread: false }),(row) => row.id === id,)@@ -2267,8 +1873,6 @@ export function patchCanonicalCommunityChannel(return withCanonicalWriteContext(queryClient, { kind: "event" }, () => patchRows(registry,"channels",- channelSchema,- (row) => row.id,patch,(row) => row.id === channelId,))@@ -2282,34 +1886,34 @@ export function publishCommunityChannelPatch() {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!- const row = collectionRows(registry, "channels", channelSchema).find((row) => row.id === channelId)+ const row = collectionRows(registry, "channels").find((row) => row.id === channelId)if (!row) return falseconst next = patch(row)const changes = Object.fromEntries(Object.entries(next).filter(([key, value]) => !Object.is(value, row[key as keyof ChannelRow])))- return publishConfirmedFields(queryClient, "channels", channelSchema, channelId, changes, proof)+ return publishConfirmedFields(queryClient, "channels", channelId, changes, proof)}-function publishConfirmedFields<T extends { id: string }>(+function publishConfirmedFields<N extends CollectionName>(queryClient: QueryClient,- name: CollectionName,- schema: z.ZodType<T>,+ name: N,id: string,- changes: Partial<T>,+ changes: Partial<CommunityCollectionRows[N]>,proof: CommunityFreshQueryProof,) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!- if (!collectionRows(registry, name, schema).some((row) => row.id === id)) return false+ const getKey = collectionKey(registry, name)+ if (!collectionRows(registry, name).some((row) => getKey(row) === id)) return falseconst revisions = canonicalRevisionState(queryClient).fieldRevisions.get(canonicalEntityKey(name, id))const fields = Object.keys(changes).filter((field) => (- changes[field as keyof T] !== undefined+ changes[field as keyof CommunityCollectionRows[N]] !== undefined&& (revisions?.get("*") ?? 0) <= proof.token.canonicalRevision&& (revisions?.get(field) ?? 0) <= proof.token.canonicalRevision))if (!fields.length) return false- const accepted = Object.fromEntries(fields.map((field) => [field, changes[field as keyof T]]))+ const accepted = Object.fromEntries(fields.map((field) => [field, changes[field as keyof CommunityCollectionRows[N]]]))return withCanonicalWriteContext(queryClient, { kind: "event" }, () => (- patchRows(registry, name, schema, (row) => row.id, (row) => ({ ...row, ...accepted }), (row) => row.id === id, [id], fields)+ patchRows(registry, name, (row) => ({ ...row, ...accepted }), (row) => getKey(row) === id, [id], fields)))}@@ -2319,7 +1923,7 @@ export function publishCommunityServerFields(changes: Partial<Pick<ServerRow, "name" | "description" | "icon">>,proof: CommunityFreshQueryProof,) {- return publishConfirmedFields<ServerRow>(queryClient, "servers", serverSchema, serverId, changes, proof)+ return publishConfirmedFields(queryClient, "servers", serverId, changes, proof)}export function publishCommunityChannelFields(@@ -2328,7 +1932,7 @@ export function publishCommunityChannelFields(changes: Partial<Pick<ChannelRow, "name" | "categoryId" | "position">>,proof: CommunityFreshQueryProof,) {- return publishConfirmedFields<ChannelRow>(queryClient, "channels", channelSchema, channelId, changes, proof)+ return publishConfirmedFields(queryClient, "channels", channelId, changes, proof)}export function publishCommunityCategoryFields(@@ -2337,7 +1941,7 @@ export function publishCommunityCategoryFields(changes: Partial<Pick<CategoryRow, "name" | "position">>,proof: CommunityFreshQueryProof,) {- return publishConfirmedFields<CategoryRow>(queryClient, "categories", categorySchema, categoryId, changes, proof)+ return publishConfirmedFields(queryClient, "categories", categoryId, changes, proof)}export function publishCommunityMessageFields(@@ -2346,7 +1950,7 @@ export function publishCommunityMessageFields(changes: Partial<MessageRow>,proof: CommunityFreshQueryProof,) {- return publishConfirmedFields<MessageRow>(queryClient, "messages", messageSchema, messageId, changes, proof)+ return publishConfirmedFields(queryClient, "messages", messageId, changes, proof)}export function publishCommunityMessageReaction(queryClient: QueryClient, messageId: string, emoji: string, userId: string, add: boolean, proof: CommunityFreshQueryProof) {@@ -2354,37 +1958,30 @@ export function publishCommunityMessageReaction(queryClient: QueryClient, messagconst state = canonicalRevisionState(queryClient), registry = proof.token.registry!, field = `reaction:${emoji}:${userId}`const revisions = state.fieldRevisions.get(canonicalEntityKey("messages", messageId))if ((revisions?.get("*") ?? 0) > proof.token.canonicalRevision || (revisions?.get(field) ?? 0) > proof.token.canonicalRevision) return false- return withCanonicalWriteContext(queryClient, { kind: "event" }, () => patchRows(registry, "messages", messageSchema, (row) => row.id, (row) => {- const reactions = ((row as MessageRow & Msg).reactions ?? []).map((reaction) => ({ ...reaction, userIds: [...reaction.userIds] }))- const reaction = reactions.find((candidate) => candidate.emoji === emoji)- if (add) { if (reaction && !reaction.userIds.includes(userId)) reaction.userIds.push(userId); else if (!reaction) reactions.push({ emoji, count: 1, me: userId === registry.accountId, userIds: [userId] }) }- else if (reaction) reaction.userIds = reaction.userIds.filter((id) => id !== userId)- return { ...row, reactions: reactions.filter((reaction) => reaction.userIds.length).map((reaction) => ({ ...reaction, count: reaction.userIds.length, me: !!registry.accountId && reaction.userIds.includes(registry.accountId) })) }- }, (row) => row.id === messageId, [messageId], ["reactions", field]))+ return withCanonicalWriteContext(queryClient, { kind: "event" }, () => patchRows(registry, "messages", (row) => ({+ ...row, reactions: applyMessageReaction((row as MessageRow & Msg).reactions, emoji, userId, add, registry.accountId || null),+ }), (row) => row.id === messageId, [messageId], ["reactions", field]))}-export function publishCommunityForumFeed(queryClient: QueryClient, forumChannelId: string, page: ForumFeedTransportPage, proof: CommunityFreshQueryProof) {- assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- const registry = proof.token.registry!- return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => notifyManager.batch(() => {- const existing = new Map(collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]))- const rows: ChannelRow[] = page.threads.map((thread) => ({- ...existing.get(thread.id), id: thread.id, serverId: page.serverId, categoryId: null, type: "thread", name: thread.name ?? "Post", creatorId: thread.creatorId,- parentChannelId: forumChannelId, parentMessageId: thread.parentMessageId, position: existing.get(thread.id)?.position ?? 0,+export function publishCommunityForumFeed(queryClient: QueryClient, forumChannelId: string, page: CommunityThreadResources, proof: CommunityFreshQueryProof) {+ return withCommunityQueryProof(queryClient, proof, (registry) => notifyManager.batch(() => {+ const rows = page.threads.map((thread) => canonicalChannelRow({+ ...thread, type: "thread", serverId: page.channel.serverId, parentChannelId: forumChannelId,+ name: thread.name ?? "Post", pending: false,tags: page.included.tags.filter((tag) => tag.messageId === thread.parentMessageId).map((tag) => tag.tag),- archived: existing.get(thread.id)?.archived ?? false, muted: existing.get(thread.id)?.muted ?? false, unread: existing.get(thread.id)?.unread ?? false, pending: false,- createdAt: thread.createdAt, messageCount: thread.messageCount ?? 0, lastMessageAt: thread.activityAt,- preview: page.included.firstMessages.find((message) => message.channelId === thread.id)?.content.slice(0, 100) ?? "",- participantCount: page.included.participants.find((participant) => participant.channelId === thread.id)?.participantCount ?? 0,- }))- upsertRows(registry, "channels", channelSchema, (row) => row.id, rows)- ingestMessages(registry, forumChannelId, page.included.parentMessages.map((message) => ({ ...message, type: "chat", authorAvatar: canonicalUserImage(message.authorId, message.authorImage, message.authorAvatarVersion) ?? undefined })))- upsertRows(registry, "channelMemberships", channelMembershipSchema, (row) => row.id, page.included.participants.map((participant) => ({ id: channelMembershipKey(participant.channelId, participant.userId, "notify"), channelId: participant.channelId, userId: participant.userId, relation: "notify", source: "explicit" })))+ lastMessageAt: thread.lastMessageAt ?? thread.createdAt,+ preview: page.included.previews.find((message) => message.channelId === thread.id)?.content.slice(0, 100) ?? "",+ participantCount: page.included.participantCounts.find((row) => row.channelId === thread.id)?.count ?? 0,+ }, registry.collections.channels.get(thread.id)))+ upsertRows(registry, "channels", rows)+ ingestResourceProfiles(registry, page.included.profiles, proof)+ publishCommunityEmbeddedMessages(queryClient, { entries: page.included.messages.map((message) => ({ channelId: message.channelId, message })), proof })+ upsertRows(registry, "channelMemberships", page.included.members.map((member) => channelMembershipSchema.parse({ ...member, id: channelMembershipKey(member.channelId, member.userId, member.relation), memberId: member.memberId ?? undefined })))}))}export function publishCommunityForumTags(queryClient: QueryClient, threadId: string, tags: string[], proof: CommunityFreshQueryProof) {- return publishConfirmedFields<ChannelRow>(queryClient, "channels", channelSchema, threadId, { tags }, proof)+ return publishConfirmedFields(queryClient, "channels", threadId, { tags }, proof)}export function publishCommunityNotificationSetting(queryClient: QueryClient, target: Pick<NotificationSettingRow, "serverId" | "channelId">, level: string | null, proof: CommunityFreshQueryProof) {@@ -2392,19 +1989,18 @@ export function publishCommunityNotificationSetting(queryClient: QueryClient, taconst registry = proof.token.registry!, id = notificationSettingKey(target)if ((canonicalRevisionState(queryClient).entityRevisions.get(canonicalEntityKey("notificationSettings", id)) ?? 0) > proof.token.canonicalRevision) return falsereturn withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- if (level === null) deleteRows(registry, "notificationSettings", notificationSettingSchema, (row) => row.id === id, [id])- else upsertRows(registry, "notificationSettings", notificationSettingSchema, (row) => row.id, [{ id, ...target, level }])+ if (level === null) deleteRows(registry, "notificationSettings", (row) => row.id === id, [id])+ else upsertRows(registry, "notificationSettings", [{ id, ...target, level }])return true})}export function publishCommunityFriendships(queryClient: QueryClient, rows: FriendshipRow[], proof: CommunityFreshQueryProof) {- assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- const state = canonicalRevisionState(queryClient), registry = proof.token.registry!- return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => notifyManager.batch(() => {- const previous = collectionRows(registry, "friendships", friendshipSchema).filter((row) => row.kind === "incoming" || row.kind === "outgoing")- replaceRows(registry, "friendships", friendshipSchema, (row) => row.id, rows.filter((row) => (state.entityRevisions.get(canonicalEntityKey("friendships", `user:${row.userId}`)) ?? 0) <= proof.token.canonicalRevision), () => true)- const pending = new Set(collectionRows(registry, "friendships", friendshipSchema).filter((row) => row.kind === "incoming" || row.kind === "outgoing").map((row) => row.id))+ return withCommunityQueryProof(queryClient, proof, (registry) => notifyManager.batch(() => {+ const state = canonicalRevisionState(queryClient)+ const previous = collectionRows(registry, "friendships").filter((row) => row.kind === "incoming" || row.kind === "outgoing")+ replaceRows(registry, "friendships", rows.filter((row) => (state.entityRevisions.get(canonicalEntityKey("friendships", `user:${row.userId}`)) ?? 0) <= proof.token.canonicalRevision), () => true)+ const pending = new Set(collectionRows(registry, "friendships").filter((row) => row.kind === "incoming" || row.kind === "outgoing").map((row) => row.id))retireCanonicalFriendRequests(registry, previous.filter((row) => !pending.has(row.id)).map((row) => row.id))}))}@@ -2417,13 +2013,13 @@ export function removeSettledCommunityFriendCommands(queryClient: QueryClient, ifunction retireCanonicalFriendRequests(registry: CommunityDbRegistry, ids: readonly string[]) {const eligible = new Set(ids.filter((id) => !isProtectedFromQueryWrite(registry, "friendships", id)))if (!eligible.size) return- const items = collectionRows(registry, "attentionItems", attentionItemSchema).filter((row) => row.kind === "friend_request" && eligible.has(row.sourceId) && !isProtectedFromQueryWrite(registry, "attentionItems", row.id))- const present = new Set(collectionRows(registry, "friendships", friendshipSchema).filter((row) => eligible.has(row.id) && row.kind === "accepted").map((row) => row.id))+ const items = collectionRows(registry, "attentionItems").filter((row) => row.kind === "friend_request" && eligible.has(row.sourceId) && !isProtectedFromQueryWrite(registry, "attentionItems", row.id))+ const present = new Set(collectionRows(registry, "friendships").filter((row) => eligible.has(row.id) && row.kind === "accepted").map((row) => row.id))withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {- deleteRows(registry, "friendships", friendshipSchema, (row) => eligible.has(row.id) && (row.kind === "incoming" || row.kind === "outgoing"), [...eligible].filter((id) => !present.has(id)))+ deleteRows(registry, "friendships", (row) => eligible.has(row.id) && (row.kind === "incoming" || row.kind === "outgoing"), [...eligible].filter((id) => !present.has(id)))recordEventPatches<FriendshipRow>(registry, "friendships", present, (row) => ({ ...row, kind: "accepted" }), present, ["kind"])const attentionIds = new Set([...items.map((row) => row.id), ...[...eligible].map((id) => `friend_request:${id}`)])- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => attentionIds.has(row.id), attentionIds)+ deleteRows(registry, "attentionItems", (row) => attentionIds.has(row.id), attentionIds)})removeSettledCommunityFriendCommands(registry.queryClient, [...eligible])}@@ -2431,71 +2027,82 @@ function retireCanonicalFriendRequests(registry: CommunityDbRegistry, ids: readoexport function publishCommunityFriendDecision(queryClient: QueryClient, friendshipId: string, action: "accept" | "reject" | "remove", proof: CommunityFreshQueryProof) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!- if (action === "accept") publishConfirmedFields<FriendshipRow>(queryClient, "friendships", friendshipSchema, friendshipId, { kind: "accepted" as const, needsOwnerApproval: null }, proof)- else if ((canonicalRevisionState(queryClient).entityRevisions.get(canonicalEntityKey("friendships", friendshipId)) ?? 0) <= proof.token.canonicalRevision) withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "friendships", friendshipSchema, (row) => row.id === friendshipId, [friendshipId]))- withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "attentionItems", attentionItemSchema, (row) => row.kind === "friend_request" && row.sourceId === friendshipId))+ if (action === "accept") publishConfirmedFields(queryClient, "friendships", friendshipId, { kind: "accepted" as const, needsOwnerApproval: null }, proof)+ else if ((canonicalRevisionState(queryClient).entityRevisions.get(canonicalEntityKey("friendships", friendshipId)) ?? 0) <= proof.token.canonicalRevision) withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "friendships", (row) => row.id === friendshipId, [friendshipId]))+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(registry, "attentionItems", (row) => row.kind === "friend_request" && row.sourceId === friendshipId))removeSettledCommunityFriendCommands(queryClient, [friendshipId])}+export function applyCommunityDmBlockAccess(registry: CommunityDbRegistry, peerUserId: string, blocked: boolean) {+ if (peerUserId === registry.accountId) return+ const memberships = collectionRows(registry, "channelMemberships")+ const peerChannels = new Set(memberships.filter((row) => row.userId === peerUserId && row.relation === "access").map((row) => row.channelId))+ const viewerChannels = new Set(memberships.filter((row) => row.userId === registry.accountId && row.relation === "access").map((row) => row.channelId))+ const ids = new Set(collectionRows(registry, "channels")+ .filter((row) => row.type === "dm" && row.serverId === null && peerChannels.has(row.id) && viewerChannels.has(row.id))+ .map((row) => row.id))+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => notifyManager.batch(() => {+ for (const id of ids) {+ if (blocked) retireCommunityChannelReading(registry, id, { reason: "read-denied", serverId: null })+ else registry.runtime.ws.actions.beginChannelMembershipChange(null, id)+ }+ }))+}+export function publishCommunityFriendBlock(queryClient: QueryClient, userId: string, blocked: boolean, proof: CommunityFreshQueryProof) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!, state = canonicalRevisionState(queryClient)if ((state.entityRevisions.get(canonicalEntityKey("friendships", `user:${userId}`)) ?? 0) > proof.token.canonicalRevision) return- const retired = blocked ? collectionRows(registry, "friendships", friendshipSchema).filter((row) => row.userId === userId).map((row) => row.id) : []+ const retired = blocked ? collectionRows(registry, "friendships").filter((row) => row.userId === userId).map((row) => row.id) : []withCanonicalWriteContext(queryClient, { kind: "event" }, () => notifyManager.batch(() => {recordEventWrites(registry, "friendships", [`user:${userId}`])- deleteRows(registry, "friendships", friendshipSchema, (row) => row.userId === userId && (blocked || row.kind === "blocked"))+ deleteRows(registry, "friendships", (row) => row.userId === userId && (blocked || row.kind === "blocked"))if (blocked) {- upsertRows(registry, "friendships", friendshipSchema, (row) => row.id, [{ id: `blocked:${userId}`, userId, kind: "blocked" }])- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => row.kind === "friend_request" && row.actorUserId === userId)+ upsertRows(registry, "friendships", [{ id: `blocked:${userId}`, userId, kind: "blocked" }])+ deleteRows(registry, "attentionItems", (row) => row.kind === "friend_request" && row.actorUserId === userId)}}))removeSettledCommunityFriendCommands(queryClient, retired)}-function publishCreatedTreeRow<T extends { id: string }>(+function publishCreatedTreeRow<N extends "channels" | "categories">(queryClient: QueryClient,- name: "channels" | "categories",- schema: z.ZodType<T>,- row: T,+ name: N,+ row: CommunityCollectionRows[N],proof: CommunityFreshQueryProof,) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!- const existing = collectionRows(registry, name, schema).find((current) => current.id === row.id)- if (!existing) withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => {- upsertRows(registry, name, schema, (value) => value.id, [row])- })- if (collectionRows(registry, name, schema).some((current) => current.id === row.id)) {+ const existing = collectionRows(registry, name).find((current) => current.id === row.id)+ if (!existing) withCommunityQueryProof(queryClient, proof, (owner) => upsertRows(owner, name, [row]))+ if (collectionRows(registry, name).some((current) => current.id === row.id)) {withCanonicalWriteContext(queryClient, { kind: "event" }, () => recordEventWrites(registry, name, [row.id]))}}export function publishCommunityCreatedChannel(queryClient: QueryClient, row: ChannelRow, proof: CommunityFreshQueryProof) {- publishCreatedTreeRow(queryClient, "channels", channelSchema, row, proof)+ publishCreatedTreeRow(queryClient, "channels", row, proof)const registry = proof.token.registry!- if (!registry.accountId || !collectionRows(registry, "channels", channelSchema).some((current) => current.id === row.id)) return+ if (!registry.accountId || !collectionRows(registry, "channels").some((current) => current.id === row.id)) returnwithCanonicalWriteContext(queryClient, { kind: "event" }, () => upsertRows(- registry, "channelMemberships", channelMembershipSchema, (value) => value.id,- [{ id: channelMembershipKey(row.id, registry.accountId!, "access"), channelId: row.id, userId: registry.accountId!, relation: "access", source: "inherited" }],+ registry, "channelMemberships", [canonicalChannelMembershipRow(row.id, registry.accountId!, "access", { source: "inherited" })],))}export function publishCommunityCreatedCategory(queryClient: QueryClient, row: CategoryRow, proof: CommunityFreshQueryProof) {- publishCreatedTreeRow(queryClient, "categories", categorySchema, row, proof)+ publishCreatedTreeRow(queryClient, "categories", row, proof)}export function publishCommunityDeletedCategory(queryClient: QueryClient, categoryId: string, proof: CommunityFreshQueryProof) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)- withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(proof.token.registry!, "categories", categorySchema, (row) => row.id === categoryId, [categoryId]))+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(proof.token.registry!, "categories", (row) => row.id === categoryId, [categoryId]))}export function publishCommunityServerMembershipRemoval(queryClient: QueryClient, serverId: string, proof: CommunityFreshQueryProof) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const registry = proof.token.registry!withCanonicalWriteContext(queryClient, { kind: "event" }, () => deleteRows(- registry, "serverMemberships", serverMembershipSchema,- (row) => row.serverId === serverId && row.viewer && row.userId === registry.accountId,+ registry, "serverMemberships", (row) => row.serverId === serverId && row.viewer && row.userId === registry.accountId,))}@@ -2510,8 +2117,6 @@ export function patchCanonicalCommunityMessage(patchRows(registry,"messages",- messageSchema,- (row) => row.id,patch,(row) => row.id === messageId,)@@ -2528,7 +2133,6 @@ export function removeCanonicalCommunityChannelMembership(deleteRows(registry,"channelMemberships",- channelMembershipSchema,(row) => row.channelId === channelId&& row.userId === registry.accountId&& row.relation === relation,@@ -2555,23 +2159,14 @@ export function setCanonicalCommunityChannelMember(queryClient: QueryClient, chaconst id = channelMembershipKey(channelId, userId, relation)const write = () => {if (!present) {- deleteRows(registry, "channelMemberships", channelMembershipSchema, (row) => row.id === id, [id])+ deleteRows(registry, "channelMemberships", (row) => row.id === id, [id])return true}- const previous = collectionRows(registry, "channelMemberships", channelMembershipSchema).find((row) => row.id === id)+ const previous = collectionRows(registry, "channelMemberships").find((row) => row.id === id)upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,- [{- ...previous,- id,- channelId,- userId,- relation,- source: "explicit",- }],+ [canonicalChannelMembershipRow(channelId, userId, relation, { ...previous, source: "explicit" })],)return true}@@ -2583,38 +2178,35 @@ export function setCanonicalCommunityChannelMember(queryClient: QueryClient, chaexport function getCanonicalCommunityChannels(queryClient: QueryClient) {const registry = getCommunityDbRegistry(queryClient)- return registry ? collectionRows(registry, "channels", channelSchema) : []+ return registry ? collectionRows(registry, "channels") : []}export function getCanonicalCommunityAttentionScopes(queryClient: QueryClient) {const registry = getCommunityDbRegistry(queryClient)- return registry ? collectionRows(registry, "attentionScopes", attentionScopeSchema) : []+ return registry ? collectionRows(registry, "attentionScopes") : []}export function getCanonicalCommunityAttentionItems(queryClient: QueryClient) {const registry = getCommunityDbRegistry(queryClient)- return registry ? collectionRows(registry, "attentionItems", attentionItemSchema) : []+ return registry ? collectionRows(registry, "attentionItems") : []}export function getCanonicalCommunityChannelMemberships(queryClient: QueryClient) {const registry = getCommunityDbRegistry(queryClient)return registry- ? collectionRows(registry, "channelMemberships", channelMembershipSchema)+ ? collectionRows(registry, "channelMemberships"): []}export function getCanonicalCommunityMessages(queryClient: QueryClient) {const registry = getCommunityDbRegistry(queryClient)- return registry ? collectionRows(registry, "messages", messageSchema) : []+ return registry ? collectionRows(registry, "messages") : []}export function purgeCommunityServer(registry: CommunityDbRegistry, serverId: string) {if (isProtectedFromQueryWrite(registry, "servers", serverId)) return- const removedChannelIds = new Set(- collectionRows(registry, "channels", channelSchema)- .filter((row) => row.serverId === serverId)- .map((row) => row.id),- )+ const removedChannelIds = collectChannelScopeIds(registry.queryClient, serverId)+ for (const id of removedChannelIds) registry.runtime.ws.actions.revokeChannelAccess(serverId, id)clearChannelTransientState(registry, removedChannelIds, serverId)pruneInboxCaches(registry.queryClient, removedChannelIds, serverId)getAccountUnreadProjection(@@ -2626,7 +2218,9 @@ export function purgeCommunityServer(registry: CommunityDbRegistry, serverId: st})clearLastChannel(serverId)registry.runtime.ws.actions.revokeServerAccess(serverId)+ void registry.retireReadingDisk(removedChannelIds).catch((error: unknown) => console.error("Server cache retirement failed", error))registry.runtime.messageStream.actions.removeServer(serverId)+ registry.queryClient.setQueryData<string[]>(communityKeys.servers(), (current) => current?.filter((id) => id !== serverId))void registry.queryClient.cancelQueries({ queryKey: communityKeys.server(serverId) }, { revert: false })registry.queryClient.removeQueries({ queryKey: communityKeys.server(serverId) })const community = registry.runtime.ui.get()@@ -2635,67 +2229,124 @@ export function purgeCommunityServer(registry: CommunityDbRegistry, serverId: stregistry.runtime.ui.actions.setCurrentServerId(null)}notifyManager.batch(() => {- deleteRows(registry, "servers", serverSchema, (row) => row.id === serverId, [serverId])- deleteRows(registry, "categories", categorySchema, (row) => row.serverId === serverId)- deleteRows(registry, "channels", channelSchema, (row) => removedChannelIds.has(row.id))- deleteRows(registry, "serverMemberships", serverMembershipSchema, (row) => row.serverId === serverId)- deleteRows(registry, "channelMemberships", channelMembershipSchema, (row) => removedChannelIds.has(row.channelId))- deleteRows(registry, "messages", messageSchema, (row) => removedChannelIds.has(row.channelId))- deleteRows(registry, "readStates", readStateSchema, (row) => removedChannelIds.has(row.channelId))- deleteRows(registry, "attentionScopes", attentionScopeSchema, (row) => (+ deleteRows(registry, "servers", (row) => row.id === serverId, [serverId])+ deleteRows(registry, "categories", (row) => row.serverId === serverId)+ deleteRows(registry, "channels", (row) => removedChannelIds.has(row.id), removedChannelIds)+ deleteRows(registry, "serverMemberships", (row) => row.serverId === serverId)+ deleteRows(registry, "channelMemberships", (row) => removedChannelIds.has(row.channelId))+ deleteRows(registry, "messages", (row) => removedChannelIds.has(row.channelId))+ deleteRows(registry, "readStates", (row) => removedChannelIds.has(row.channelId))+ deleteRows(registry, "attentionScopes", (row) => (row.serverId === serverId || removedChannelIds.has(row.channelId)))- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => (- Boolean(row.scopeId && removedChannelIds.has(row.scopeId))+ deleteRows(registry, "attentionItems", (row) => (+ Boolean(row.scopeId && removedChannelIds.has(row.scopeId) || row.childChannelId && removedChannelIds.has(row.childChannelId) || row.readTarget && removedChannelIds.has(row.readTarget.channelId))))- deleteRows(registry, "folderItems", folderItemSchema, (row) => row.serverId === serverId)- deleteRows(registry, "notificationSettings", notificationSettingSchema, (row) => (+ deleteRows(registry, "folderItems", (row) => row.serverId === serverId)+ deleteRows(registry, "notificationSettings", (row) => (row.serverId === serverId || Boolean(row.channelId && removedChannelIds.has(row.channelId))))garbageCollectCommunityProfiles(registry)})}-export function purgeCommunityChannel(registry: CommunityDbRegistry, channelId: string, clearTransient = true) {- if (isProtectedFromQueryWrite(registry, "channels", channelId)) return- const channels = collectionRows(registry, "channels", channelSchema)- const root = channels.find((row) => row.id === channelId)- const removed = new Set([- channelId,- ...channels- .filter((row) => row.id === channelId || row.parentChannelId === channelId)- .map((row) => row.id),- ])- if (clearTransient) clearChannelTransientState(registry, removed, root?.serverId ?? null)- notifyManager.batch(() => {- deleteRows(registry, "channels", channelSchema, (row) => removed.has(row.id), [channelId])- deleteRows(registry, "channelMemberships", channelMembershipSchema, (row) => removed.has(row.channelId))- deleteRows(registry, "messages", messageSchema, (row) => removed.has(row.channelId))- deleteRows(registry, "readStates", readStateSchema, (row) => removed.has(row.channelId))- deleteRows(registry, "attentionScopes", attentionScopeSchema, (row) => removed.has(row.channelId))- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => (- Boolean(row.scopeId && removed.has(row.scopeId))- ))- deleteRows(registry, "notificationSettings", notificationSettingSchema, (row) => (- Boolean(row.channelId && removed.has(row.channelId))- ))- garbageCollectCommunityProfiles(registry)- })+type ThreadPageLike = {+ serverId?: string+ threads?: Array<{ id?: string }>}-export function purgeCommunityForumPost(registry: CommunityDbRegistry, unit: { childChannelId: string; openerMessageId: string }, clearTransient = true) {+export function collectChannelScopeIds(+ queryClient: QueryClient,+ serverId: string | null,+ channelId?: string,+) {+ const ids = new Set<string>(channelId ? [channelId] : [])+ const store = getCommunityRuntime(queryClient).ui.get()+ const current = readCurrentCommunityChannelMeta(queryClient)+ if (store.currentServerId === serverId && store.currentChannelId+ && (!channelId || current?.parentChannelId === channelId)) ids.add(store.currentChannelId)+ for (const [id, scope] of getCommunityRuntime(queryClient).ws.get().channelAccessScopes) {+ if (scope.serverId === serverId && (!channelId || scope.parentChannelId === channelId)) ids.add(id)+ }+ for (const [, meta] of queryClient.getQueriesData<{ id: string; parentChannelId?: string }>(+ { queryKey: ["community", "channel"], predicate: (query) => query.queryKey[3] === "metadata" },+ )) {+ if (meta && ("serverId" in meta ? meta.serverId : getCommunityDbRegistry(queryClient)?.collections.channels.get(meta.id)?.serverId) === serverId+ && (!channelId || meta.parentChannelId === channelId)) ids.add(meta.id)+ }+ for (const { scope } of getCommunityRuntime(queryClient).messageStream.get().entries.values()) {+ if (!channelId && scope.kind === "channel" && scope.serverId === serverId) ids.add(scope.id)+ }+ const registry = getCommunityDbRegistry(queryClient)+ for (const row of registry?.collections.channels.values() ?? []) {+ if (row.serverId === serverId && (!channelId || row.id === channelId || row.parentChannelId === channelId)) ids.add(row.id)+ }+ for (const [key, data] of queryClient.getQueriesData<+ ThreadPageLike | { pages: ThreadPageLike[] }+ >({+ 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 ?? []) if (thread.id) ids.add(thread.id)+ }+ }+ return ids+}+++export function retireCommunityChannelReading(+ registry: CommunityDbRegistry,+ channelId: string,+ options: { reason: "read-denied" | "resource-deleted"; serverId?: string | null; preserveQuery?: Query; queries?: ReadonlySet<Query>; assertView?: () => void; clearTransient?: boolean },+) {+ const root = registry.collections.channels.get(channelId)+ const serverId = options.serverId === undefined ? root?.serverId ?? null : options.serverId+ const removed = collectChannelScopeIds(registry.queryClient, serverId, channelId)+ for (const id of registry.runtime.ws.actions.revokeChannelAccess(serverId, channelId)) removed.add(id)+ for (const id of removed) if (!registry.runtime.ws.actions.isChannelAccessRevoked(id, serverId)) registry.runtime.ws.actions.revokeChannelAccess(serverId, id)+ void registry.retireReadingDisk(removed, options.reason === "resource-deleted")+ .catch((error: unknown) => console.error("Channel cache retirement failed", error))+ if (options.clearTransient !== false) clearChannelTransientState(registry, removed, serverId, options.preserveQuery, options)withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => notifyManager.batch(() => {- purgeCommunityChannel(registry, unit.childChannelId, clearTransient)- deleteRows(registry, "messages", messageSchema, (row) => row.id === unit.openerMessageId, [unit.openerMessageId])- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => row.childChannelId === unit.childChannelId || row.messageId === unit.openerMessageId)+ patchRows(registry, "channels", (row) => ({ ...row, preview: "", unread: false, baseUnread: false, lastUnreadSeq: undefined }),+ (row) => removed.has(row.id), removed, ["preview", "unread", "baseUnread", "lastUnreadSeq"])+ deleteRows(registry, "messages", (row) => removed.has(row.channelId))+ deleteRows(registry, "readStates", (row) => removed.has(row.channelId))+ deleteRows(registry, "attentionScopes", (row) => removed.has(row.channelId))+ deleteRows(registry, "attentionItems", (row) => Boolean(row.scopeId && removed.has(row.scopeId) || row.childChannelId && removed.has(row.childChannelId) || row.readTarget && removed.has(row.readTarget.channelId)))+ if (options.reason === "resource-deleted" || root?.type !== "dm") {+ deleteRows(registry, "channels", (row) => removed.has(row.id), removed)+ deleteRows(registry, "channelMemberships", (row) => removed.has(row.channelId))+ deleteRows(registry, "notificationSettings", (row) => Boolean(row.channelId && removed.has(row.channelId)))+ garbageCollectCommunityProfiles(registry)+ }}))+ return removed+}++export function purgeCommunityChannel(registry: CommunityDbRegistry, channelId: string, clearTransient = true, preserveQuery?: Query) {+ if (isProtectedFromQueryWrite(registry, "channels", channelId) || !registry.collections.channels.has(channelId) && registry.runtime.ws.actions.isChannelAccessRevoked(channelId)) return+ retireCommunityChannelReading(registry, channelId, { reason: "resource-deleted", clearTransient, preserveQuery })}-export function publishCommunityDeletedForumPost(queryClient: QueryClient, unit: { childChannelId: string; openerMessageId: string }, proof: CommunityFreshQueryProof) {+export function purgeCommunityForumPost(registry: CommunityDbRegistry, unit: { childChannelId: string; openerMessageId: string; serverId?: string }, options?: { queries?: ReadonlySet<Query>; assertView?: () => void }) {+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => notifyManager.batch(() => {+ if (registry.collections.channels.has(unit.childChannelId) || !registry.runtime.ws.actions.isChannelAccessRevoked(unit.childChannelId, unit.serverId)) retireCommunityChannelReading(registry, unit.childChannelId, { reason: "resource-deleted", serverId: unit.serverId, ...options })+ deleteRows(registry, "messages", (row) => row.id === unit.openerMessageId, [unit.openerMessageId])+ deleteRows(registry, "attentionItems", (row) => row.childChannelId === unit.childChannelId || row.messageId === unit.openerMessageId)+ }))+}++export function publishCommunityDeletedForumPost(queryClient: QueryClient, unit: { childChannelId: string; openerMessageId: string; serverId?: string }, proof: CommunityFreshQueryProof, options?: { queries?: ReadonlySet<Query>; assertView?: () => void }) {assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)const state = canonicalRevisionState(queryClient)if ((state.entityRevisions.get(canonicalEntityKey("channels", unit.childChannelId)) ?? 0) > proof.token.canonicalRevision || (state.entityRevisions.get(canonicalEntityKey("messages", unit.openerMessageId)) ?? 0) > proof.token.canonicalRevision) return false- purgeCommunityForumPost(proof.token.registry!, unit, false)+ purgeCommunityForumPost(proof.token.registry!, unit, options)return true}@@ -2724,51 +2375,49 @@ export function projectCommunityWsEventToDb(case "community:friend.request": {const row = event.friendshipconst otherId = row.requesterId === registry.accountId ? row.addresseeId : row.requesterId- if (collectionRows(registry, "friendships", friendshipSchema).some((friendship) => friendship.kind === "blocked" && friendship.userId === otherId)) break+ if (collectionRows(registry, "friendships").some((friendship) => friendship.kind === "blocked" && friendship.userId === otherId)) breakconst outgoing = row.requesterId === registry.accountId- upsertRows(registry, "friendships", friendshipSchema, (friendship) => friendship.id, [{ id: row.id, userId: outgoing ? row.addresseeId : row.requesterId, kind: outgoing ? "outgoing" : "incoming" }])+ upsertRows(registry, "friendships", [{ id: row.id, userId: outgoing ? row.addresseeId : row.requesterId, kind: outgoing ? "outgoing" : "incoming" }])return}case "community:friend.accept":- patchRows(registry, "friendships", friendshipSchema, (row) => row.id, (row) => ({ ...row, kind: "accepted" as const, needsOwnerApproval: null }), (row) => row.id === event.friendshipId, [event.friendshipId], ["kind", "needsOwnerApproval"])- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => row.kind === "friend_request" && row.sourceId === event.friendshipId)+ patchRows(registry, "friendships", (row) => ({ ...row, kind: "accepted" as const, needsOwnerApproval: null }), (row) => row.id === event.friendshipId, [event.friendshipId], ["kind", "needsOwnerApproval"])+ deleteRows(registry, "attentionItems", (row) => row.kind === "friend_request" && row.sourceId === event.friendshipId)removeSettledCommunityFriendCommands(queryClient, [event.friendshipId])returncase "community:friend.reject":case "community:friend.remove":- deleteRows(registry, "friendships", friendshipSchema, (row) => row.id === event.friendshipId, [event.friendshipId])- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => row.kind === "friend_request" && row.sourceId === event.friendshipId)+ deleteRows(registry, "friendships", (row) => row.id === event.friendshipId, [event.friendshipId])+ deleteRows(registry, "attentionItems", (row) => row.kind === "friend_request" && row.sourceId === event.friendshipId)removeSettledCommunityFriendCommands(queryClient, [event.friendshipId])returncase "community:friend.block": {- const retired = collectionRows(registry, "friendships", friendshipSchema).filter((row) => row.userId === event.userId).map((row) => row.id)+ const retired = collectionRows(registry, "friendships").filter((row) => row.userId === event.userId).map((row) => row.id)recordEventWrites(registry, "friendships", [`user:${event.userId}`])- deleteRows(registry, "friendships", friendshipSchema, (row) => row.userId === event.userId)- upsertRows(registry, "friendships", friendshipSchema, (row) => row.id, [{ id: `blocked:${event.userId}`, userId: event.userId, kind: "blocked" }])- deleteRows(registry, "attentionItems", attentionItemSchema, (row) => row.kind === "friend_request" && row.actorUserId === event.userId)+ deleteRows(registry, "friendships", (row) => row.userId === event.userId && (event.blockedByViewer === true || row.kind !== "blocked"))+ if (event.blockedByViewer) upsertRows(registry, "friendships", [{ id: `blocked:${event.userId}`, userId: event.userId, kind: "blocked" }])+ deleteRows(registry, "attentionItems", (row) => row.kind === "friend_request" && row.actorUserId === event.userId)removeSettledCommunityFriendCommands(queryClient, retired)return}- case "community:message.create":- ingestMessages(registry, event.channelId, [projectCommunityMessageCreate(event.message)])+ case "community:message.create": {+ const projected = projectCommunityMessageCreate(event.message, event.channelId)+ ingestMessages(registry, event.channelId, [projected])if (event.message.createdAt) {patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({ ...row, lastMessageAt: event.message.createdAt }),(row) => row.id === event.channelId,[event.channelId],)}- return+ return projected+ }case "community:message.edited":patchRows(registry,"messages",- messageSchema,- (row) => row.id,(row) => ({ ...row, content: event.content }),(row) => row.id === event.messageId,[event.messageId],@@ -2779,8 +2428,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"messages",- messageSchema,- (row) => row.id,(row) => ({ ...row, approval: event.approval }),(row) => row.id === event.messageId,[event.messageId],@@ -2792,35 +2439,7 @@ export function projectCommunityWsEventToDb(patchRows(registry,"messages",- messageSchema,- (row) => row.id,- (row) => {- const message = row as MessageRow & Msg- const reactions = (message.reactions ?? []).map((reaction) => ({- ...reaction,- userIds: [...reaction.userIds],- }))- const reaction = reactions.find((candidate) => candidate.emoji === event.emoji)- if (event.type === "community:reaction.add") {- if (reaction && !reaction.userIds.includes(event.userId)) reaction.userIds.push(event.userId)- else if (!reaction) reactions.push({- emoji: event.emoji,- count: 1,- me: event.userId === registry.accountId,- userIds: [event.userId],- })- } else if (reaction) {- reaction.userIds = reaction.userIds.filter((userId) => userId !== event.userId)- }- const normalized = reactions- .filter((candidate) => candidate.userIds.length > 0)- .map((candidate) => ({- ...candidate,- count: candidate.userIds.length,- me: Boolean(registry.accountId && candidate.userIds.includes(registry.accountId)),- }))- return { ...row, reactions: normalized }- },+ (row) => ({ ...row, reactions: applyMessageReaction((row as MessageRow & Msg).reactions, event.emoji, event.userId, event.type === "community:reaction.add", registry.accountId || null) }),(row) => row.id === event.messageId,[event.messageId],["reactions", `reaction:${event.emoji}:${event.userId}`],@@ -2828,39 +2447,24 @@ export function projectCommunityWsEventToDb(returncase "community:channel.child_create": {if (!event.parentMessageId) return- const parent = collectionRows(registry, "channels", channelSchema)+ const parent = collectionRows(registry, "channels").find((row) => row.id === event.parentChannelId)if (!parent?.serverId) return- upsertRows(registry, "channels", channelSchema, (row) => row.id, [{+ upsertRows(registry, "channels", [canonicalChannelRow({id: event.channel.id,serverId: parent.serverId,- categoryId: null,name: event.channel.name,type: "thread",parentChannelId: event.parentChannelId,parentMessageId: event.parentMessageId,creatorId: event.channel.creatorId ?? null,- position: 0,- archived: false,- muted: false,- unread: false,- tags: [],- pending: false,lastMessageAt: event.channel.createdAt,- }])+ })])if (registry.accountId) {upsertRows(registry,"channelMemberships",- channelMembershipSchema,- (row) => row.id,- [{- id: channelMembershipKey(event.channel.id, registry.accountId, "access"),- channelId: event.channel.id,- userId: registry.accountId,- relation: "access",- source: "explicit",- }],+ [canonicalChannelMembershipRow(event.channel.id, registry.accountId, "access", { source: "explicit" })],)}return@@ -2869,8 +2473,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({...row,...(event.changes.name === undefined ? {} : { name: event.changes.name }),@@ -2888,43 +2490,27 @@ export function projectCommunityWsEventToDb(patchRows(registry,"servers",- serverSchema,- (row) => row.id,(row) => ({ ...row, ...event.changes }),(row) => row.id === event.serverId,[event.serverId],Object.keys(event.changes),)return- case "community:server.delete":- if (isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, event.serverId)) return- purgeCommunityServer(registry, event.serverId)- returncase "community:channel.create":- upsertRows(registry, "channels", channelSchema, (row) => row.id, [{+ upsertRows(registry, "channels", [canonicalChannelRow({id: event.channel.id,serverId: event.serverId,categoryId: event.channel.categoryId ?? null,name: event.channel.name,type: event.channel.type,- parentChannelId: null,- parentMessageId: null,- creatorId: null,position: event.channel.position,- archived: false,- muted: false,- unread: false,- tags: [],- pending: false,lastMessageAt: event.channel.createdAt,- }])+ })])returncase "community:channel.update":patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({ ...row, ...event.changes }),(row) => row.id === event.channelId,[event.channelId],@@ -2941,8 +2527,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({ ...row, position: positionById.get(row.id) ?? row.position }),(row) => row.serverId === event.serverId && positionById.has(row.id),positionById.keys(),@@ -2950,6 +2534,7 @@ export function projectCommunityWsEventToDb()return}+ case "community:channel.membership.change":case "community:channel.member_add":case "community:channel.member_remove":// Relation ownership depends on resolved channel type. The membership@@ -2957,7 +2542,7 @@ export function projectCommunityWsEventToDb(// the event changes thread notify or top-level access.returncase "community:category.create":- upsertRows(registry, "categories", categorySchema, (row) => row.id, [{+ upsertRows(registry, "categories", [{id: event.category.id,serverId: event.serverId,name: event.category.name,@@ -2970,8 +2555,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"categories",- categorySchema,- (row) => row.id,(row) => ({ ...row, ...event.changes }),(row) => row.id === event.categoryId,[event.categoryId],@@ -2982,7 +2565,6 @@ export function projectCommunityWsEventToDb(deleteRows(registry,"categories",- categorySchema,(row) => row.id === event.categoryId,[event.categoryId],)@@ -2992,8 +2574,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"categories",- categorySchema,- (row) => row.id,(row) => ({ ...row, position: positionById.get(row.id) ?? row.position }),(row) => row.serverId === event.serverId && positionById.has(row.id),positionById.keys(),@@ -3002,7 +2582,7 @@ export function projectCommunityWsEventToDb(return}case "community:member.join":- upsertRows(registry, "serverMemberships", serverMembershipSchema, (row) => row.id, [{+ upsertRows(registry, "serverMemberships", [{id: serverMembershipKey(event.serverId, event.member.userId),serverId: event.serverId,userId: event.member.userId,@@ -3019,13 +2599,10 @@ export function projectCommunityWsEventToDb(})], registry, { event: true })returncase "community:member.leave":- if (event.userId === registry.accountId) {- purgeCommunityServer(registry, event.serverId)- } else {+ if (event.userId !== registry.accountId) {deleteRows(registry,"serverMemberships",- serverMembershipSchema,(row) => row.serverId === event.serverId && row.userId === event.userId,[serverMembershipKey(event.serverId, event.userId)],)@@ -3035,8 +2612,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"serverMemberships",- serverMembershipSchema,- (row) => row.id,(row) => ({ ...row, ...event.changes }),(row) => row.serverId === event.serverId&& (row.memberId === event.memberId || Boolean(event.userId && row.userId === event.userId)),@@ -3049,8 +2624,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"channels",- channelSchema,- (row) => row.id,(row) => ({ ...row, unread: true }),(row) => row.id === event.channelId || row.id === event.railChannelId,[event.channelId, event.railChannelId]@@ -3060,8 +2633,6 @@ export function projectCommunityWsEventToDb(patchRows(registry,"servers",- serverSchema,- (row) => row.id,(row) => ({...row,unread: true,diff --git a/src/web/src/lib/community-db/write.test.ts b/src/web/src/lib/community-db/write.test.tsindex 1478e90b0..4b7b3ff7d 100644--- a/src/web/src/lib/community-db/write.test.ts+++ b/src/web/src/lib/community-db/write.test.ts@@ -7,6 +7,7 @@ import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"import { createCommunityDbRegistry, type CommunityDbRegistry } from "./collections"import { profileSchema } from "./schema"import { writeCommunityCollectionRows } from "./write"+import { ingestMessages, projectCommunityWsEventToDb } from "./sync"const owners: CommunityDbRegistry[] = []@@ -22,6 +23,32 @@ function owner() {}describe("canonical collection publication", () => {+ it.each([false, true])("preserves sparse same-identity WS fields before ready=%s and honors explicit empty", async (ready) => {+ const registry = owner()+ if (ready) await registry.preload()+ const message = { id: "m-rich", seq: 3, type: "chat" as const, authorId: "peer", authorName: "Peer",+ authorAvatar: "P", authorAvatarVersion: 0, content: "before", createdAt: "2026-08-07T10:00:00.000Z" }+ const attachments = [{ kind: "file" as const, name: "notes.txt", url: "/notes.txt", size: "1 KB" }]+ const embeds = [{ title: "Reference" }]+ ingestMessages(registry, "channel", [{ ...message, attachments, embeds }])+ const summaryFacts = { type: "system" as const, clientNonce: "known-nonce", replyToId: "reply" }+ ingestMessages(registry, "channel", [{ ...message, ...summaryFacts, attachments, embeds }])+ ingestMessages(registry, "channel", [{ id: message.id, content: "summary" }])+ expect(registry.queryClient.getQueryData(communityKeys.communityDbCollection(registry.scopeId, "messages"))).toMatchObject([+ { ...summaryFacts, content: "summary", attachments, embeds },+ ])+ expect(registry.collections.messages.status === "ready").toBe(ready)+ projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.create",+ serverId: "server", channelId: "channel", message: { ...message, content: "after" } })+ const key = communityKeys.communityDbCollection(registry.scopeId, "messages")+ expect(registry.queryClient.getQueryData(key)).toMatchObject([{ ...message, content: "after", attachments, embeds }])+ await registry.preload()+ expect(registry.collections.messages.get(message.id)).toMatchObject({ content: "after", attachments, embeds })+ projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.create",+ serverId: "server", channelId: "channel", message: { ...message, attachments: [], embeds: [] } })+ expect(registry.collections.messages.get(message.id)).toMatchObject({ attachments: [], embeds: [] })+ })+it("reproduces snapshot loss with the library default collection GC", async () => {vi.useFakeTimers()const queryClient = new QueryClient()diff --git a/src/web/src/lib/community-db/write.ts b/src/web/src/lib/community-db/write.tsindex eebe76dc2..34938da9d 100644--- a/src/web/src/lib/community-db/write.ts+++ b/src/web/src/lib/community-db/write.ts@@ -27,15 +27,17 @@ export function writeCommunityCollectionRows<T extends object>(writeUpsert: (rows: T[]) => void}}+ const committed = registry.queryClient.getQueryData<T[]>(communityKeys.communityDbCollection(registry.scopeId, name))if (collection.status !== "ready") {+ const previousByKey = new Map((committed ?? []).map((row) => [getKey(row), businessRow(row)]))+ const next = rows.map((row) => ({ ...previousByKey.get(getKey(row)), ...businessRow(row) }))registry.queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, name),- rows,+ next,)recordRows(registry.queryClient, name, registry.queryClient.getQueryData<T[]>(communityKeys.communityDbCollection(registry.scopeId, name)) ?? rows, getKey)return}- const committed = registry.queryClient.getQueryData<T[]>(communityKeys.communityDbCollection(registry.scopeId, name))const previousByKey = committed === undefined ? undefined : new Map(committed.map((row) => [collection.getKeyFromItem(row), row]))const nextKeys = new Set(rows.map(getKey))const removed = Array.from(previousByKey?.keys() ?? collection.keys()).filter((key) => !nextKeys.has(key))diff --git a/src/web/src/lib/community/account-cache-lifecycle.ts b/src/web/src/lib/community/account-cache-lifecycle.tsindex 1c5342caa..6a2605f65 100644--- a/src/web/src/lib/community/account-cache-lifecycle.ts+++ b/src/web/src/lib/community/account-cache-lifecycle.ts@@ -1,6 +1,6 @@import { commandObservation } from "@/lib/observability/context"import { clearComposerAttachmentSessionsForAccount } from "./composer-attachment-session"-import type { ApiRequestOptions } from "@/lib/api/client"+import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"import { getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { assertCommunityLiveSnapshotTokenCurrent, type CommunityLiveSnapshotToken } from "@/lib/community-db/sync"import type { QueryClient } from "@tanstack/react-query"@@ -24,3 +24,36 @@ export function communityRequestOptions(queryClient: QueryClient, token: Communireturn registry.authenticationView.get().active && registry.authenticationView.get().generation === generation && (viewer === undefined || viewer === null || viewer === registry.accountId)} }}++export async function loadCommunityRequest<T>(+ load: (options: ApiRequestOptions) => Promise<T>,+ token: CommunityLiveSnapshotToken,+ signal?: AbortSignal,+): Promise<T> {+ const registry = token.registry+ if (!registry) throw new DOMException("Missing community profile owner", "AbortError")+ const assertActive = () => assertCommunityLiveSnapshotTokenCurrent(registry.queryClient, token, signal)+ await registry.ready+ assertActive()+ await registry.collections.profiles.preload()+ assertActive()+ try {+ const data = await load(communityRequestOptions(registry.queryClient, token, signal, assertActive))+ assertActive()+ return data+ } catch (error) {+ assertActive()+ throw error+ }+}++export function apiFetchCommunity<T>(+ path: string,+ options: ApiRequestOptions | undefined,+ token: CommunityLiveSnapshotToken,+): Promise<T> {+ return loadCommunityRequest((origin) => apiFetch<T>(path, {+ ...options, ...origin, signal: options?.signal,+ assertActive: () => { origin.assertActive?.(); options?.assertActive?.() },+ }), token, options?.signal ?? undefined)+}diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.tsindex bf9f9488b..1bcf7eed6 100644--- a/src/web/src/lib/community/attachment-presentation.ts+++ b/src/web/src/lib/community/attachment-presentation.ts@@ -1,3 +1,7 @@+import type { CommunityMessageAttachment } from "@alook/shared"+import type { Attachment } from "./models/message"+import { isInlineAttachmentContentType } from "./attachment-content-type"+export const MAX_TEXT_ATTACHMENT_PREVIEW_BYTES = 1024 * 1024export const MAX_PDF_ATTACHMENT_PREVIEW_BYTES = 10 * 1024 * 1024@@ -274,3 +278,13 @@ export function formatAttachmentSize(bytes?: number): string {if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`return `${(bytes / (1024 * 1024)).toFixed(1)} MB`}++export function presentMessageAttachment(+ attachment: Omit<CommunityMessageAttachment, "kind"> & Partial<Pick<CommunityMessageAttachment, "kind">>,+): Attachment {+ const kind = attachment.kind ?? (isInlineAttachmentContentType(attachment.contentType) ? "image" : "file")+ if (kind === "image") return { ...attachment, kind }+ const { width: _width, height: _height, thumbnailUrl: _thumbnailUrl, ...file } = attachment+ return { ...(attachment.kind ? attachment : file), kind,+ size: attachment.size ?? formatAttachmentSize(attachment.kind ? attachment.sizeBytes ?? 0 : attachment.sizeBytes) }+}diff --git a/src/web/src/lib/community/conversation-navigation-proof.dom.test.ts b/src/web/src/lib/community/conversation-navigation-proof.dom.test.tsindex 60fdb124e..3dd163b54 100644--- a/src/web/src/lib/community/conversation-navigation-proof.dom.test.ts+++ b/src/web/src/lib/community/conversation-navigation-proof.dom.test.ts@@ -312,10 +312,10 @@ describe("conversation navigation proof", () => {expect(gate).toMatchObject({ required: true, allowed: false, failed: true })await act(async () => { vi.advanceTimersByTime(60_000) })expect(restart).not.toHaveBeenCalled()- act(() => gate.retry())+ await act(async () => gate.retry())expect(restart).toHaveBeenCalledExactlyOnceWith(1, 1)- cancelActiveConversationNavigationProof(queryClient)- act(() => gate.retry())+ await act(async () => cancelActiveConversationNavigationProof(queryClient))+ await act(async () => gate.retry())expect(restart).toHaveBeenCalledOnce()view.unmount()})diff --git a/src/web/src/lib/community/conversation-navigation-proof.ts b/src/web/src/lib/community/conversation-navigation-proof.tsindex 6cd2f8080..35541a6eb 100644--- a/src/web/src/lib/community/conversation-navigation-proof.ts+++ b/src/web/src/lib/community/conversation-navigation-proof.ts@@ -6,11 +6,7 @@ import type { QueryClient } from "@tanstack/react-query"import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent, type CommunityLiveSnapshotToken } from "@/lib/community-db/sync"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { communityKeys } from "@/lib/query-keys"--export type MessageSurfaceReceipt = {- channelId: string- surfaceKind: "channel" | "thread" | "forum" | "dm"-}+import type { CommunityMessageSurfaceReceipt } from "@alook/shared"export type ConversationNavigationTarget = {href: string@@ -18,7 +14,7 @@ export type ConversationNavigationTarget = {channelId: stringserverId?: stringscopeKind: "channel" | "dm"- expectedSurfaceKind?: MessageSurfaceReceipt["surfaceKind"]+ expectedSurfaceKind?: CommunityMessageSurfaceReceipt["surfaceKind"]anchorMessageId?: string}@@ -81,7 +77,7 @@ export function beginConversationNavigationProof(): { epoch: number; signal: AbortSignal } {const store = getStore(queryClient)const current = store.get()- const ownerToken = captureCommunityLiveSnapshotToken(queryClient)+ const ownerToken = captureCommunityLiveSnapshotToken(queryClient, target.channelId)if (ownerToken.viewerId !== target.viewerId) throw new DOMException("Conversation viewer does not match owner", "AbortError")if (current.activeTarget) {const previousKey = current.activeTarget.scopeKind === "dm"@@ -160,7 +156,7 @@ export function isCurrentConversationNavigation(export function recordConversationNavigationReceipt(queryClient: QueryClient,- receipt: MessageSurfaceReceipt,+ receipt: CommunityMessageSurfaceReceipt,accessEpoch: number,epoch?: number,): boolean {diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.tsindex e13bc9385..5b09deca1 100644--- a/src/web/src/lib/community/enrich-messages.test.ts+++ b/src/web/src/lib/community/enrich-messages.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", async () => {...actual.queries.communityMessage,getMessagesByIdsInScope: (...args: unknown[]) => mocks.getReplies(...args),getLatestMessageSeq: (...args: unknown[]) => mocks.getLatestSeq(...args),- getFirstMessageByChannelIds: (...args: unknown[]) => mocks.getFirstMessages(...args),+ getFirstMessageResourcesByChannelIds: (...args: unknown[]) => mocks.getFirstMessages(...args),},communityChannel: {...actual.queries.communityChannel,@@ -70,6 +70,17 @@ describe("enrichMessages attachment projection", () => {mocks.getLatestSeq.mockResolvedValue(9)})+ it("skips empty DM attachment, reaction, reply and approval hydration while reading latest sequence", async () => {+ const db = {} as never+ expect(await enrichMessages(db, "u1", { channelId: "dm1", isDm: true }, [])).toEqual({ messages: [], latestSeq: 9 })+ expect(mocks.listAttachments).not.toHaveBeenCalled()+ expect(mocks.listReactions).not.toHaveBeenCalled()+ expect(mocks.getReplies).not.toHaveBeenCalled()+ expect(mocks.hydrateApprovals).not.toHaveBeenCalled()+ expect(mocks.listChildren).not.toHaveBeenCalled()+ expect(mocks.getLatestSeq).toHaveBeenCalledWith(db, { channelId: "dm1" })+ })+it("projects a canonical thumbnail beside reply enrichment", async () => {mocks.listAttachments.mockResolvedValue([{id: "att_1",diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.tsindex a6528753e..5a2e6726e 100644--- a/src/web/src/lib/community/enrich-messages.ts+++ b/src/web/src/lib/community/enrich-messages.ts@@ -1,7 +1,6 @@-import { queries, withD1Retry } from "@alook/shared"+import { queries, withD1Retry, type CommunityMessageResource } from "@alook/shared"import type { getDb } from "@/lib/db"-import { groupAttachments, groupReactions } from "@/lib/community/messages"-import { mapMessageForApi } from "@/lib/community/message-payload"+import { loadApiMessageContext, mapMessageForApi } from "@/lib/community/message-payload"import { avatarInitial } from "@/lib/community/avatar"import { canonicalUserImage } from "@/lib/community/storage"@@ -23,25 +22,19 @@ export async function enrichMessages(db: Db,userId: string,scope: MessageScope,- items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,+ items: Array<Parameters<typeof mapMessageForApi>[0] & { channelId: string }>,): Promise<{ messages: unknown[]; latestSeq: number }> {const isDm = scope.isDm === trueconst messageIds = items.map((m) => m.id)- const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]+ const replyToIds = items.flatMap((row) => row.replyToId ? [row.replyToId] : [])- const [allAttachments, allReactions, replyMessages, childChannels, latestSeq, approvalByMessageId] = await Promise.all([- messageIds.length > 0- ? queries.communityAttachment.listByMessageIds(db, messageIds)- : Promise.resolve([]),- messageIds.length > 0- ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId)- : Promise.resolve([]),- replyToIds.length > 0+ const [contextForChannel, childChannels, latestSeq, approvalByMessageId] = await Promise.all([+ loadApiMessageContext(db, userId, messageIds, () => replyToIds.length > 0? withD1Retry(() => queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId: scope.channelId }),{ route: "community/messages:reply-enrichment" },)- : Promise.resolve([]),+ : Promise.resolve([]), true),// Thread indicators only exist for non-DM channel-scoped messages.!isDm? scope.isForum@@ -56,15 +49,13 @@ export async function enrichMessages(: Promise.resolve(new Map()),])- const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, userId)- const replyMap = new Map(replyMessages.map((m) => [m.id, m]))+ const context = contextForChannel(scope.channelId)const threadIds = childChannels.map((channel) => channel.id)const [forumTags, forumFirstMessages, forumParticipants] = scope.isForum && messageIds.length > 0? await Promise.all([queries.communityMessageTag.listTagsForMessages(db, messageIds),- queries.communityMessage.getFirstMessageByChannelIds(db, threadIds),+ queries.communityMessage.getFirstMessageResourcesByChannelIds(db, threadIds),queries.communityThread.listParticipantsForChannels(db, threadIds, 5),]): [[], [], []]@@ -73,12 +64,7 @@ export async function enrichMessages(tagsByMessage.set(row.messageId, [...(tagsByMessage.get(row.messageId) ?? []), row.tag])}const firstByChannel = new Map(forumFirstMessages.map((message) => [message.channelId, message]))- const participantsByChannel = new Map<string, Array<{- id: string- name: string- avatar: string- avatarVersion: number- }>>()+ const participantsByChannel = new Map<string, NonNullable<NonNullable<CommunityMessageResource["thread"]>["participants"]>>()const participantCountByChannel = new Map<string, number>()for (const row of forumParticipants) {participantCountByChannel.set(@@ -118,10 +104,8 @@ export async function enrichMessages()const messages = items.map((r) =>- mapMessageForApi(r as never, {- replyMap,- attachmentsByMessage,- reactionsByMessage,+ mapMessageForApi(r, {+ ...context,threadByMessageId,approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,}),diff --git a/src/web/src/lib/community/forum-sidebar.ts b/src/web/src/lib/community/forum-sidebar.tsnew file mode 100644index 000000000..b70f88e1c--- /dev/null+++ b/src/web/src/lib/community/forum-sidebar.ts@@ -0,0 +1,70 @@+import { compareAsciiSqliteBinary, FORUM_ARCHIVE_TAG } from "@alook/shared"+import type { ChannelMembershipRow, ChannelRow, MessageRow } from "@/lib/community-db/schema"++export type ForumSidebarThread = Pick<ChannelRow, "id" | "unread"> & {+ parentChannelId: string+ parentMessageId: string+ title: string+ activityAt: string+ expiresAt: string+}++export const FORUM_SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000++export function viewerNotifyChannelIds(memberships: readonly ChannelMembershipRow[], viewerId: string | null) {+ return new Set(memberships.filter((row) => row.relation === "notify" && row.userId === viewerId).map((row) => row.channelId))+}++export function compareForumSidebarThreads(left: ForumSidebarThread, right: ForumSidebarThread) {+ return compareAsciiSqliteBinary(left.parentChannelId, right.parentChannelId)+ || compareAsciiSqliteBinary(right.activityAt, left.activityAt)+ || compareAsciiSqliteBinary(right.id, left.id)+}++export function forumSidebarCandidates(+ channels: readonly ChannelRow[], memberships: readonly ChannelMembershipRow[], messages: readonly MessageRow[],+ viewerId: string | null, serverId: string,+) {+ const participating = viewerNotifyChannelIds(memberships, viewerId)+ const messageById = new Map(messages.map((message) => [message.id, message]))+ const parents = channels.filter((channel) => channel.serverId === serverId && channel.type === "forum")+ const parentIds = new Set(parents.map((channel) => channel.id))+ return channels.flatMap((channel) => {+ if (channel.serverId !== serverId || channel.type !== "thread" || channel.archived+ || channel.tags.includes(FORUM_ARCHIVE_TAG) || !participating.has(channel.id)+ || !channel.parentChannelId || !parentIds.has(channel.parentChannelId) || !channel.parentMessageId) return []+ const activityAt = channel.lastMessageAt ?? "", activityMs = Date.parse(activityAt)+ const expiresAt = Number.isFinite(activityMs) ? new Date(activityMs + FORUM_SIDEBAR_ACTIVITY_WINDOW_MS).toISOString() : activityAt+ return [{ id: channel.id, parentChannelId: channel.parentChannelId, parentMessageId: channel.parentMessageId,+ title: messageById.get(channel.parentMessageId)?.content ?? channel.name, activityAt, expiresAt, unread: channel.unread }]+ }).sort(compareForumSidebarThreads)+}++export function projectForumSidebar(+ channels: readonly ChannelRow[], memberships: readonly ChannelMembershipRow[], messages: readonly MessageRow[],+ viewerId: string | null, serverId: string, retainId: string | null, serverNowMs: number,+) {+ const parents = channels.filter((channel) => channel.serverId === serverId && channel.type === "forum")+ const parentIds = new Set(parents.map((channel) => channel.id))+ const candidates = forumSidebarCandidates(channels, memberships, messages, viewerId, serverId)+ .filter((thread) => thread.id === retainId || !Number.isFinite(Date.parse(thread.expiresAt)) || Date.parse(thread.expiresAt) > serverNowMs)+ const byParent = new Map<string, ForumSidebarThread[]>()+ for (const thread of candidates) {+ const siblings = byParent.get(thread.parentChannelId) ?? []+ siblings.push(thread)+ byParent.set(thread.parentChannelId, siblings)+ }+ const threads = [...byParent.values()].flatMap((siblings) => {+ const retained = retainId ? siblings.find((thread) => thread.id === retainId) : undefined+ if (!retained || siblings.slice(0, 5).some((thread) => thread.id === retainId)) return siblings.slice(0, 5)+ return [...siblings.filter((thread) => thread.id !== retainId).slice(0, 4), retained].sort(compareForumSidebarThreads)+ })+ const renderedIds = new Set(threads.map((thread) => thread.id))+ const parentUnread: Record<string, boolean> = {}+ for (const parent of parents) parentUnread[parent.id] = parent.baseUnread ?? parent.unread+ for (const child of channels) {+ if (child.serverId === serverId && child.type === "thread" && child.unread && child.parentChannelId+ && parentIds.has(child.parentChannelId) && !renderedIds.has(child.id)) parentUnread[child.parentChannelId] = true+ }+ return { threads, parentUnread }+}diff --git a/src/web/src/lib/community/member-read.test.ts b/src/web/src/lib/community/member-read.test.tsnew file mode 100644index 000000000..b944f4be5--- /dev/null+++ b/src/web/src/lib/community/member-read.test.ts@@ -0,0 +1,67 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+const mocks = vi.hoisted(() => ({ access: vi.fn(), channel: vi.fn(), participants: vi.fn(), audience: vi.fn(), users: vi.fn(), serverMembers: vi.fn(), resolve: vi.fn() }))+vi.mock("./permissions", () => ({ requireMessageSurfaceAccess: mocks.access }))+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: {+ communityChannel: { getChannelForMember: mocks.channel, listChannelMemberUserIds: mocks.audience },+ communityThread: { listThreadParticipants: mocks.participants }, user: { getUsersByIds: mocks.users },+ communityMember: { getMembersByUserIds: mocks.serverMembers }, communityMembersResolver: { resolveScopeMembers: mocks.resolve },+} }))+import { readCommunityMembers } from "./member-read"+beforeEach(() => {+ vi.clearAllMocks()+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "dm", dm: { otherUserId: "peer" } } })+ mocks.channel.mockResolvedValue({ id: "dm", type: "dm", serverId: null, creatorId: null })+ mocks.audience.mockResolvedValue(["viewer", "peer"])+ mocks.participants.mockResolvedValue([])+ mocks.users.mockResolvedValue(["viewer", "peer"].map((id) => ({ id, name: id, discriminator: "1234", image: null, avatarVersion: 0, email: "[email protected]" })))+})+describe("common member relations", () => {+ it("keeps the current notify roster distinct from readable users", async () => {+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "channel", channel: { id: "thread", type: "thread", serverId: "server", creatorId: "viewer" } } })+ mocks.participants.mockResolvedValue([{ userId: "viewer", source: "spoke" }, { userId: "deleted", source: "added" }])+ mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", discriminator: "1234", image: null, avatarVersion: 0, email: "[email protected]" }])+ mocks.serverMembers.mockResolvedValue([{ id: "member", userId: "viewer", role: "admin", statusEmoji: "👍", statusText: "here" }])+ const response = await readCommunityMembers({} as never, "thread", "viewer", "notify")+ expect(await response.json()).toMatchObject({ channelId: "thread", relation: "notify", members: [{ userId: "viewer", source: "spoke", isCreator: true, role: "admin", memberId: "member" }], profiles: [{ id: "viewer", statusEmoji: "👍", statusText: "here" }] })+ expect(mocks.participants).toHaveBeenCalledWith({}, "thread")+ expect(mocks.audience).not.toHaveBeenCalled()+ expect(mocks.resolve).not.toHaveBeenCalled()+ })+ it.each(["text", "forum"])("resolves the %s access audience rather than notify participants", async (type) => {+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "channel", channel: { id: "parent", type, serverId: "server", creatorId: "viewer" } } })+ mocks.resolve.mockResolvedValue([{ userId: "viewer", source: "admin" }])+ mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", image: null, avatarVersion: 0 }])+ mocks.serverMembers.mockResolvedValue([])+ const response = await readCommunityMembers({} as never, "parent", "viewer", "access")+ expect(await response.json()).toMatchObject({ members: [{ channelId: "parent", userId: "viewer", relation: "access", source: "admin" }] })+ expect(mocks.resolve).toHaveBeenCalledWith({}, { scope: type === "forum" ? "forum" : "channel", scopeId: "parent" })+ expect(mocks.participants).not.toHaveBeenCalled()+ })+ it("does not hydrate members when the readable DM no longer has metadata", async () => {+ mocks.channel.mockResolvedValue(null)+ expect((await readCommunityMembers({} as never, "dm", "viewer", "access")).status).toBe(404)+ expect(mocks.users).not.toHaveBeenCalled()+ })+ it("retains both DM participants without server membership or email fields", async () => {+ const response = await readCommunityMembers({} as never, "dm", "viewer", "access")+ const body = await response.json()+ expect(body).toMatchObject({ contractVersion: 2, channelId: "dm", relation: "access" })+ expect(body.members).toHaveLength(2)+ expect(body.members.every((member: { role: unknown; memberId: unknown }) => member.role === null && member.memberId === null)).toBe(true)+ expect(JSON.stringify(body)).not.toContain("[email protected]")+ expect(mocks.serverMembers).not.toHaveBeenCalled()+ expect(mocks.resolve).not.toHaveBeenCalled()+ })+ it("returns the actual empty notify set rather than deriving it from access", async () => {+ mocks.users.mockResolvedValue([])+ const response = await readCommunityMembers({} as never, "dm", "viewer", "notify")+ expect(await response.json()).toMatchObject({ relation: "notify", members: [], profiles: [] })+ expect(mocks.audience).not.toHaveBeenCalled()+ })+ it("requires a relation and preserves the full reading rejection", async () => {+ expect((await readCommunityMembers({} as never, "dm", "viewer", null)).status).toBe(400)+ mocks.access.mockResolvedValue({ ok: false, status: 403, error: "blocked" })+ expect((await readCommunityMembers({} as never, "dm", "viewer", "access")).status).toBe(403)+ expect(mocks.audience).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/lib/community/member-read.ts b/src/web/src/lib/community/member-read.tsnew file mode 100644index 000000000..83c6fdb0b--- /dev/null+++ b/src/web/src/lib/community/member-read.ts@@ -0,0 +1,34 @@+import { COMMUNITY_CONTRACT_VERSION, CommunityMembersReadSchema, queries, type Database } from "@alook/shared"+import { requireMessageSurfaceAccess } from "./permissions"+import { writeError } from "@/lib/middleware/helpers"+import { writeCommunityContractJSON } from "./read-contract"+import { canonicalUserImage } from "./storage"+import { resourceProfile } from "./participant-resources"++export async function readCommunityMembers(db: Database, channelId: string, userId: string, relation: string | null) {+ const access = await requireMessageSurfaceAccess(db, channelId, userId)+ if (!access.ok) return writeError(access.error, access.status)+ if (relation !== "access" && relation !== "notify") return writeError("relation must be access or notify", 400)+ const channel = access.value.surface === "channel" ? access.value.channel+ : await queries.communityChannel.getChannelForMember(db, channelId, userId)+ if (!channel) return writeError("not found", 404)+ const relations = relation === "notify"+ ? (await queries.communityThread.listThreadParticipants(db, channelId)).map((row) => ({ userId: row.userId, source: row.source }))+ : access.value.surface === "dm"+ ? (await queries.communityChannel.listChannelMemberUserIds(db, channelId)).map((id) => ({ userId: id, source: "explicit" }))+ : await queries.communityMembersResolver.resolveScopeMembers(db, { scope: channel.type === "forum" ? "forum" : "channel", scopeId: channelId })+ const ids = relations.map((row) => row.userId)+ const [users, serverMembers] = await Promise.all([+ queries.user.getUsersByIds(db, ids), channel.serverId+ ? queries.communityMember.getMembersByUserIds(db, channel.serverId, ids) : Promise.resolve([]),+ ])+ const memberByUser = new Map(serverMembers.map((row) => [row.userId, row]))+ const profiles = users.map((row) => resourceProfile({ id: row.id, name: row.name ?? "", discriminator: row.discriminator ?? null,+ avatar: canonicalUserImage(row.id, row.image, row.avatarVersion), avatarVersion: row.avatarVersion,+ statusEmoji: memberByUser.get(row.id)?.statusEmoji ?? null, statusText: memberByUser.get(row.id)?.statusText ?? "" }))+ const available = new Set(profiles.map((profile) => profile.id))+ return writeCommunityContractJSON(CommunityMembersReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId, relation,+ members: relations.filter((row) => available.has(row.userId)).map((row) => ({ channelId, userId: row.userId,+ relation, source: row.source ?? "explicit", isCreator: row.userId === channel.creatorId,+ role: memberByUser.get(row.userId)?.role ?? null, memberId: memberByUser.get(row.userId)?.id ?? null })), profiles }))+}diff --git a/src/web/src/lib/community/message-delivery-transport.test.ts b/src/web/src/lib/community/message-delivery-transport.test.tsindex 529032387..26eef079f 100644--- a/src/web/src/lib/community/message-delivery-transport.test.ts+++ b/src/web/src/lib/community/message-delivery-transport.test.ts@@ -19,6 +19,7 @@ const {vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: () => ({env: {+ COMMUNITY_EVENT_CONTRACT: "2",WS_DO_WORKER: { fetch: bindingFetch },DEV_WS_DO_URL: "http://dev-ws:8789",},@@ -102,6 +103,14 @@ afterAll(() => {})describe("sendMessageDeliveryBatch", () => {+ it("retains the original roster refresh identity after a partial retry subset", async () => {+ bindingFetch.mockResolvedValueOnce(Response.json({ failedUserIds: ["u2"] }, { status: 207 }))+ .mockResolvedValueOnce(Response.json({ failedUserIds: [] }))+ await sendMessageDeliveryBatch(batch({ joinedParticipantUserIds: ["u1", "u2"], rosterRefreshUserId: "u1", memberAdded: undefined }))+ expect(requestBatch(0)).toMatchObject({ joinedParticipantUserIds: ["u1", "u2"], rosterRefreshUserId: "u1" })+ expect(requestBatch(1)).toMatchObject({ joinedParticipantUserIds: ["u2"], rosterRefreshUserId: "u1" })+ expect(requestOperationId(1)).toBe(requestOperationId(0))+ })it("sends one valid batch when target and byte limits both fit", async () => {await sendMessageDeliveryBatch(batch())diff --git a/src/web/src/lib/community/message-delivery-transport.ts b/src/web/src/lib/community/message-delivery-transport.tsindex 942ec911f..19cb153cc 100644--- a/src/web/src/lib/community/message-delivery-transport.ts+++ b/src/web/src/lib/community/message-delivery-transport.ts@@ -12,6 +12,7 @@ import {type CommunityDeliveryOperationId,} from "@alook/shared"import { fetchViaBindingOrDevFallback } from "../dev-binding-fetch"+import { projectCommunityProducerDelivery } from "./producer-contract"const log = createLogger({ service: "message-delivery-transport" })const maxAttempts = 3@@ -40,6 +41,7 @@ function selectTargets(batch: MessageDeliveryBatch, selected: ReadonlySet<stringunreadPlainUserIds: keep(batch.unreadPlainUserIds),unreadMentionUserIds: keep(batch.unreadMentionUserIds),mentionUserIds: keep(batch.mentionUserIds),+ ...(batch.joinedParticipantUserIds ? { joinedParticipantUserIds: keep(batch.joinedParticipantUserIds), rosterRefreshUserId: batch.rosterRefreshUserId } : {}),...(batch.memberAdded && selected.has(batch.memberAdded.userId)? { memberAdded: batch.memberAdded }: {}),@@ -176,15 +178,16 @@ async function settleChunks(}export async function sendMessageDeliveryBatch(- batch: MessageDeliveryBatch,+ original: MessageDeliveryBatch,plannedOperationId?: CommunityDeliveryOperationId,): Promise<void> {- const derivedOperationId = await deriveCommunityDeliveryOperationId(batch.messageId)+ const derivedOperationId = await deriveCommunityDeliveryOperationId(original.messageId)if (plannedOperationId !== undefined && plannedOperationId !== derivedOperationId) {throw new Error("message delivery: operation ID does not match message")}const operationId = plannedOperationId ?? derivedOperationIdconst { env } = getCloudflareContext()+ const batch = projectCommunityProducerDelivery(original, env as Env)const targets = allTargetUserIds(batch)const chunks: MessageDeliveryBatch[] = []let index = 0diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.tsindex 6d4557932..d1bf1a673 100644--- a/src/web/src/lib/community/message-dispatcher.test.ts+++ b/src/web/src/lib/community/message-dispatcher.test.ts@@ -571,6 +571,10 @@ describe("dispatchCommittedMessage", () => {expect.objectContaining({ messageId: "msg_1" }),await deriveCommunityDeliveryOperationId("msg_1"),)+ expect(Object.keys(mockSendMessageDeliveryBatch.mock.calls[0]![0]).sort()).toEqual([+ "contentUserIds", "mentionUserIds", "messageEvent", "messageId",+ "unreadMentionUserIds", "unreadPlainUserIds",+ ])expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([])})@@ -587,7 +591,9 @@ describe("dispatchCommittedMessage", () => {channelId === "forum_1" ? ["parent_viewer"] : ["author_1"],)- await dispatchCommittedMessage({} as never, "msg_1")+ await dispatchCommittedMessage({} as never, "msg_1", {+ memberAddedUserId: "author_1", joinedParticipantUserIds: ["author_1"],+ })expect(mockSendMessageDeliveryBatch).toHaveBeenCalledWith(expect.objectContaining({@@ -596,9 +602,17 @@ describe("dispatchCommittedMessage", () => {channelId: "t1",}),parentProjectionUserIds: ["parent_viewer"],+ memberAdded: { userId: "author_1", serverId: "s1", channelId: "t1" },+ joinedParticipantUserIds: ["author_1"],+ rosterRefreshUserId: "author_1",}),await deriveCommunityDeliveryOperationId("msg_1"),)+ expect(Object.keys(mockSendMessageDeliveryBatch.mock.calls[0]![0]).sort()).toEqual([+ "contentUserIds", "joinedParticipantUserIds", "memberAdded", "mentionUserIds",+ "messageEvent", "messageId", "parentProjection", "parentProjectionUserIds",+ "rosterRefreshUserId", "unreadMentionUserIds", "unreadPlainUserIds",+ ])})it("enqueues the exact mobile-push union separately from gated bot wakes", async () => {diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.tsindex f8c568e32..901e221e4 100644--- a/src/web/src/lib/community/message-dispatcher.ts+++ b/src/web/src/lib/community/message-dispatcher.ts@@ -12,7 +12,7 @@ import {type MessageDeliveryBatch,type AlookQueueTask,} from "@alook/shared"-import { mapMessageForWs } from "./message-payload"+import { mapMessageForWs, type MessageRow } from "./message-payload"import { sendMessageDeliveryBatch } from "./message-delivery-transport"import { enqueueQueueTasks } from "./queue-producer"import { attachmentThumbnailUrl, attachmentUrl } from "./storage"@@ -22,6 +22,7 @@ const log = createLogger({ service: "committed-message-dispatcher" })export type CommittedMessageStructuralOutcome = {/** A participant row inserted by this exact message write. */memberAddedUserId?: string+ joinedParticipantUserIds?: string[]/** Existing thread-open collision suppression; no audience/policy input. */suppressParentProjection?: boolean}@@ -52,7 +53,7 @@ function unique(values: readonly string[]): string[] {return [...new Set(values)]}-async function planCommittedMessageBase(+export async function planCommittedMessage(db: Database,messageId: string,structural: CommittedMessageStructuralOutcome = {},@@ -168,12 +169,7 @@ async function planCommittedMessageBase(...mentionUserIds,])- const replyMap = new Map<string, {- id: string- authorId: string- authorName: string- content: string | null- }>()+ const replyMap = new Map<string, Pick<MessageRow, "id" | "authorId" | "authorName" | "content">>()if (replyTarget) {replyMap.set(replyTarget.id, {id: replyTarget.id,@@ -221,6 +217,8 @@ async function planCommittedMessageBase(} as const: undefined+ const joinedParticipantUserIds = [...new Set(structural.joinedParticipantUserIds ?? [])]+ if (joinedParticipantUserIds.some((id) => !channel.serverId || !contentUserIds.includes(id))) throw new Error("committed participant outcome is outside message scope")if (structural.memberAddedUserId&& (!channel.serverId || !contentUserIds.includes(structural.memberAddedUserId))@@ -238,6 +236,7 @@ async function planCommittedMessageBase(mentionUserIds,wakeBotUserIds,pushUserIds,+ ...(joinedParticipantUserIds.length ? { joinedParticipantUserIds, rosterRefreshUserId: joinedParticipantUserIds[0]! } : {}),...(structural.memberAddedUserId && channel.serverId? {memberAdded: {@@ -253,54 +252,32 @@ async function planCommittedMessageBase(}}-export async function planCommittedMessage(- db: Database,- messageId: string,- structural: CommittedMessageStructuralOutcome = {},-): Promise<MessageDeliveryPlan> {- return planCommittedMessageBase(db, messageId, structural)-}-async function runCommittedMessageDispatch(db: Database,messageId: string,structural: CommittedMessageStructuralOutcome,): Promise<void> {const startedAt = Date.now()- const plan = await planCommittedMessageBase(+ const plan = await planCommittedMessage(db,messageId,structural,)- const browserBatch: MessageDeliveryBatch = {- messageId: plan.messageId,- messageEvent: plan.messageEvent,- contentUserIds: plan.contentUserIds,- unreadPlainUserIds: plan.unreadPlainUserIds,- unreadMentionUserIds: plan.unreadMentionUserIds,- mentionUserIds: plan.mentionUserIds,- ...(plan.memberAdded ? { memberAdded: plan.memberAdded } : {}),- ...(plan.parentProjection- ? {- parentProjection: plan.parentProjection,- parentProjectionUserIds: plan.parentProjectionUserIds,- }- : {}),- }- const pushTasks: AlookQueueTask[] = plan.pushUserIds.map((userId) => ({+ const { operationId, wakeBotUserIds, pushUserIds, ...browserBatch } = plan+ const pushTasks: AlookQueueTask[] = pushUserIds.map((userId) => ({version: 1 as const,kind: "mobile-push" as const,messageId: plan.messageId,userId,}))- const browserDelivery = sendMessageDeliveryBatch(browserBatch, plan.operationId)+ const browserDelivery = sendMessageDeliveryBatch(browserBatch, operationId)const pushDelivery = enqueueQueueTasks(pushTasks)- const botWake = enqueueQueueTasks(plan.wakeBotUserIds.map((botUserId) => ({+ const botWake = enqueueQueueTasks(wakeBotUserIds.map((botUserId) => ({version: 1 as const,kind: "bot-wake" as const,messageId: plan.messageId,botUserId,- }))).then(() => plan.wakeBotUserIds.length)+ }))).then(() => wakeBotUserIds.length)const [browser, push, wake] = await Promise.allSettled([browserDelivery,pushDelivery,@@ -330,7 +307,7 @@ async function runCommittedMessageDispatch(unreadCount: plan.unreadPlainUserIds.length + plan.unreadMentionUserIds.length,mentionCount: plan.mentionUserIds.length,wakeCount: wake.status === "fulfilled" ? wake.value : 0,- pushCount: plan.pushUserIds.length,+ pushCount: pushUserIds.length,parentCount: plan.parentProjectionUserIds?.length ?? 0,durationMs: Date.now() - startedAt,})diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 0cb71d9fc..7cb3944e0 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -563,7 +563,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-adexpect(mockCreateChannelMember).not.toHaveBeenCalled()expect(mockCreateMentions).not.toHaveBeenCalled()expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {- memberAddedUserId: "author_1",+ joinedParticipantUserIds: ["author_1"],})})@@ -697,7 +697,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad{ userId: "cara_1", source: "mention" },])expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {- memberAddedUserId: "author_1",+ joinedParticipantUserIds: ["author_1", "cara_1"],suppressParentProjection: true,})})diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex ed892d30e..9b5226945 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -560,9 +560,7 @@ export async function createCommunityMessage(params: {}).readStateRevisionconst doBroadcast = async (): Promise<void> => {const deliveries: Promise<void>[] = [dispatchCommittedMessage(db, created.id, {- ...(joinedParticipantUserIds.includes(authorId)- ? { memberAddedUserId: authorId }- : {}),+ ...(joinedParticipantUserIds.length ? { joinedParticipantUserIds } : {}),...(skipChildChannelUpdate ? { suppressParentProjection: true } : {}),})]if (readStateRevision !== undefined) {diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.tsindex 1a4a6028d..4d50fe68c 100644--- a/src/web/src/lib/community/message-payload.ts+++ b/src/web/src/lib/community/message-payload.ts@@ -14,70 +14,30 @@* embeds pass-through, and mentionType projection so adding/removing a* field on the wire is one edit, not four.*/-import { truncateMessagePreview, type MentionType } from "@alook/shared"+import { queries, truncateMessagePreview, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment, type CommunityMessageCreate } from "@alook/shared"import type { FriendApprovalPayload } from "@alook/shared"import { avatarInitial } from "@/lib/community/avatar"import { canonicalUserImage } from "@/lib/community/storage"import { projectMessageWireType } from "@/lib/community/message-wire-type"+import { groupAttachments, groupReactions } from "./messages"-// The subset of fields on rows returned by-// queries.communityMessage.{listMessages, getMessage, getMessagesByIds} that-// this mapper actually consumes. Structural-typed so the module doesn't-// reach into the shared query package — a row with additional columns-// (channelId, authorEmail, …) is still accepted. Those columns are-// scope-filtered / used by the route BEFORE the row reaches this mapper; the-// mapper deliberately doesn't see them.-export type MessageRow = {- id: string- authorId: string- authorName: string- authorImage: string | null- authorAvatarVersion: number- content: string | null- type: string | null- mentionType: string | null- replyToId: string | null- embeds: unknown- seq: number- createdAt: string- clientNonce?: string | null- /** Friend-approval card back-ref — set only on approval card messages. */- friendshipId?: string | null-}--type ReplyTargetRow = {- id: string- authorId: string- authorName: string- content: string | null-}--type UiAttachment = { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }-type WsAttachment = { id: string; filename: string; url: string; thumbnailUrl?: string; contentType?: string; size?: number; width?: number; height?: number }-type UiReaction = { emoji: string; count: number; me: boolean; userIds: string[] }+export type MessageRow = Pick<Awaited<ReturnType<typeof queries.communityMessage.getMessagesByIdsInScope>>[number],+ "id" | "authorId" | "authorName" | "authorImage" | "authorAvatarVersion" | "mentionType" | "replyToId" | "seq" | "createdAt"> & { content: string | null; type: string | null; embeds: unknown; clientNonce?: string | null; friendshipId?: string | null }-type ReplyPreview = {- id: string- authorId?: string- authorName: string- text: string- deleted?: boolean-}+type ReplyTargetRow = Pick<MessageRow, "id" | "authorId" | "authorName" | "content">-type ThreadPreview = {- id: string- name: string- messageCount: number- lastReplyAt?: string- tags?: string[]- preview?: string- participants?: { id: string; name: string; avatar: string; avatarVersion: number }[]- participantCount?: number-}+type WsAttachment = NonNullable<CommunityMessageCreate["message"]["attachments"]>[number]+type UiReaction = NonNullable<CommunityMessageResource["reactions"]>[number]+type ReplyPreview = NonNullable<CommunityMessageResource["replyTo"]>+type ThreadPreview = NonNullable<CommunityMessageResource["thread"]>/** Common fields shared by both API and WS variants — derived exactly once. */-function coreFields(row: MessageRow) {+function coreFields(row: MessageRow, replyMap: Map<string, ReplyTargetRow>, nonce = row.clientNonce) {+ const clientNonce = nonce && !nonce.startsWith("srv:") ? nonce : undefinedreturn {+ ...projectMessageWireType(row.type),+ ...(clientNonce ? { clientNonce } : {}),+ replyTo: resolveReply(row, replyMap),id: row.id,authorId: row.authorId,authorName: row.authorName,@@ -94,6 +54,7 @@ function coreFields(row: MessageRow) {seq: row.seq,createdAt: row.createdAt,mentionType: (row.mentionType ?? null) as MentionType | null,+ replyToId: row.replyToId,}}@@ -117,7 +78,7 @@ function resolveReply(row: MessageRow, replyMap: Map<string, ReplyTargetRow>): Rexport type ApiMessageContext = {replyMap: Map<string, ReplyTargetRow>- attachmentsByMessage: Record<string, UiAttachment[] | undefined>+ attachmentsByMessage: Record<string, CommunityMessageAttachment[] | undefined>reactionsByMessage: Record<string, UiReaction[] | undefined>/** Optional: only channel GET surfaces a thread child; DM/thread don't. */threadByMessageId?: Map<string, ThreadPreview>@@ -125,6 +86,18 @@ export type ApiMessageContext = {approvalByMessageId?: Map<string, FriendApprovalPayload>}+export async function loadApiMessageContext(db: Database, userId: string, ids: string[], readReplies: () => ReturnType<typeof queries.communityMessage.getMessagesByIdsInChannels>, skipEmpty = false) {+ const [attachments, reactions, replies] = await Promise.all([+ skipEmpty && !ids.length ? Promise.resolve([]) : queries.communityAttachment.listByMessageIds(db, ids),+ skipEmpty && !ids.length ? Promise.resolve([]) : queries.communityReaction.listReactionsByMessageIds(db, ids, userId),+ readReplies(),+ ])+ const attachmentsByMessage = groupAttachments(attachments), reactionsByMessage = groupReactions(reactions, userId)+ return (channelId: string): ApiMessageContext => ({ attachmentsByMessage, reactionsByMessage,+ replyMap: new Map(replies.filter((reply) => reply.channelId === channelId).map((reply) => [reply.id, reply])),+ })+}+// Splits the DB's `type` column value into the wire's `{ type, systemKind }`// pair. `"thread_created"` was already documented above (and in the shared// WS type, `CommunityMessageCreate.message.type`) as a possible column@@ -140,24 +113,21 @@ export type ApiMessageContext = {// same DB-to-wire normalization as channel message responses.export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {- const core = coreFields(row)- const thread = ctx.threadByMessageId?.get(row.id)- const approval = ctx.approvalByMessageId?.get(row.id)- const clientNonce =- row.clientNonce && !row.clientNonce.startsWith("srv:") ? row.clientNonce : undefinedreturn {- ...core,- ...projectMessageWireType(row.type),- ...(clientNonce ? { clientNonce } : {}),- replyTo: resolveReply(row, ctx.replyMap),+ ...coreFields(row, ctx.replyMap),embeds: row.embeds,attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id] : undefined,reactions: ctx.reactionsByMessage[row.id]?.length ? ctx.reactionsByMessage[row.id] : undefined,- thread,- approval,+ thread: ctx.threadByMessageId?.get(row.id),+ approval: ctx.approvalByMessageId?.get(row.id),}}+export async function mapPostedMessageForApi(db: Database, channelId: string, row: MessageRow) {+ const replies = row.replyToId ? await queries.communityMessage.getMessagesByIdsInScope(db, [row.replyToId], { channelId }) : []+ return { ...row, replyTo: resolveReply(row, new Map(replies.filter((reply) => reply.channelId === channelId).map((reply) => [reply.id, reply]))) }+}+export type WsMessageContext = {replyMap: Map<string, ReplyTargetRow>attachments: WsAttachment[]@@ -172,19 +142,13 @@ export type WsMessageContext = {}export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext) {- const core = coreFields(row)// Echo ONLY a client-provided nonce, and never the `srv:`-prefixed server// fallback (a content fingerprint — a content-correlation leak on the// broadcast wire, and a fallback send has no client optimistic row to match// anyway). The prefix guard is defense-in-depth: callers pass the raw client// nonce, but if a `srv:` value ever reaches here it is dropped, not fanned.- const clientNonce =- ctx.clientNonce && !ctx.clientNonce.startsWith("srv:") ? ctx.clientNonce : undefinedreturn {- ...core,- ...projectMessageWireType(row.type),- ...(clientNonce ? { clientNonce } : {}),- replyTo: resolveReply(row, ctx.replyMap),+ ...coreFields(row, ctx.replyMap, ctx.clientNonce ?? null),// The shared CommunityMessageCreate.embeds is `unknown[]` — narrow here// rather than widening the wire type.embeds: Array.isArray(row.embeds) ? row.embeds : undefined,diff --git a/src/web/src/lib/community/message-send-intent.ts b/src/web/src/lib/community/message-send-intent.tsnew file mode 100644index 000000000..3b3375367--- /dev/null+++ b/src/web/src/lib/community/message-send-intent.ts@@ -0,0 +1,125 @@+import { sendNonce, tempMessageId, toAttachmentVm, type SendMessageArgs } from "@/hooks/community/mutations/messages"+import { zipUploadResultsWithDimensions, type UploadFileArgs, type UploadFileResult } from "@/hooks/community/mutations/uploads"+import { toastApiError } from "@/lib/api/client"+import type { CommunityRuntime } from "@/stores/community/runtime"+import type { MessageScope } from "./message-stream"+import type { SendAttachment } from "./models/message"+import { canonicalizeReplyContent } from "./reply-content"+import { toOptimisticReplyPreview } from "./reply-preview"++export function messageSendError(error: unknown): Error {+ return error instanceof Error ? error : new Error("Failed to send message")+}++export function acceptMessageIntent(runtime: CommunityRuntime, scope: MessageScope,+ input: Pick<SendMessageArgs, "content" | "author" | "replyTo" | "nonce" | "mentionType"> & { attachments?: SendAttachment[] },+): string | undefined {+ if (!input.content && !input.attachments?.length) return undefined+ const content = canonicalizeReplyContent(input.content, input.replyTo)+ const nonce = input.nonce ?? sendNonce()+ const createdPreviewUrls: string[] = []+ const accepted = runtime.messageStream.actions.accept(scope, {+ nonce,+ tempId: tempMessageId(),+ message: {+ type: "chat",+ authorId: input.author.id,+ authorName: input.author.name,+ authorAvatar: input.author.avatar,+ content,+ createdAt: new Date().toISOString(),+ ...(input.replyTo ? { replyTo: toOptimisticReplyPreview(input.replyTo) } : {}),+ },+ localUploads: input.attachments?.map((attachment) => {+ const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)+ if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)+ return {+ file: attachment.file,+ thumbnailBlob: attachment.thumbnailBlob,+ previewObjectUrl,+ width: attachment.width,+ height: attachment.height,+ }+ }) ?? [],+ mentionType: input.mentionType,+ })+ if (!accepted) {+ for (const url of createdPreviewUrls) URL.revokeObjectURL(url)+ return undefined+ }+ return nonce+}++export async function prepareMessageIntent<Target extends UploadFileArgs["target"]>({+ runtime, scope, nonce, assertOwner, assertActive, uploadFileAsync, target,+}: {+ runtime: CommunityRuntime+ scope: MessageScope+ nonce: string+ assertOwner: () => void+ assertActive?: UploadFileArgs["assertActive"]+ target: Target+ uploadFileAsync: (input: Omit<UploadFileArgs, "target"> & { target: Target }) => Promise<UploadFileResult>+}) {+ const assert = () => { assertOwner(); assertActive?.() }+ assert()+ const streamStore = runtime.messageStream.actions+ const payload = streamStore.getRetryPayload(scope, nonce)+ if (!payload) return { ok: false as const, error: new Error("Message intent is no longer available") }+ let uploadedAttachments: UploadFileResult[] | undefined+ if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {+ const projected = payload.message.attachments+ if (projected?.length === payload.localUploads.length) {+ uploadedAttachments = projected.map((attachment, index) => {+ const local = payload.localUploads[index]+ return {+ id: attachment.url.slice(attachment.url.lastIndexOf("/") + 1),+ filename: local.file.name,+ contentType: local.file.type,+ size: local.file.size,+ ...(attachment.kind === "image" && attachment.thumbnailUrl !== undefined+ ? { hasThumbnail: true }+ : {}),+ width: local.width,+ height: local.height,+ }+ })+ }+ }+ if (payload.localUploads.length > 0 && !uploadedAttachments) {+ const results = await Promise.all(+ payload.localUploads.map((upload) =>+ uploadFileAsync({+ assertActive,+ target,+ file: upload.file,+ thumbnailBlob: upload.thumbnailBlob,+ width: upload.width,+ height: upload.height,+ }).catch((error) => {+ toastApiError(error, "Failed to attach file", assert)+ return null+ }),+ ),+ )+ if (results.some((result) => result === null)) {+ try { assertOwner() } catch (error) { return { ok: false as const, error: messageSendError(error) } }+ streamStore.dispatch(scope, { type: "uploadFailed", nonce })+ return { ok: false as const, error: new Error("Failed to attach file") }+ }+ uploadedAttachments = zipUploadResultsWithDimensions(+ results as UploadFileResult[],+ [...payload.localUploads],+ )+ try { assert() } catch (error) {+ try { assertOwner(); streamStore.dispatch(scope, { type: "uploadFailed", nonce }) } catch {}+ return { ok: false as const, error: messageSendError(error) }+ }+ streamStore.dispatch(scope, {+ type: "uploadSettled",+ nonce,+ attachments: uploadedAttachments.map((attachment) => toAttachmentVm(scope.id, attachment)),+ })+ }+ return { ok: true as const, payload, attachments: uploadedAttachments }+}diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsindex a786b73b1..93eb65868 100644--- a/src/web/src/lib/community/message-stream.test.ts+++ b/src/web/src/lib/community/message-stream.test.ts@@ -1,16 +1,18 @@-import { describe, expect, it } from "vitest"+import { beforeEach, describe, expect, it } from "vitest"import type { Msg } from "@/lib/community/models/message"import {MAX_LIVE_MESSAGE_DELTAS,emptyMessageOverlay,getOutboxRetryPayload,- materializeMessageStream,+ materializeMessageStream as materialize,reduceMessageOverlay,type CanonicalMessage,type MessageOverlayEvent,- type MessageOverlayState,+ type MessageOverlayIds,type NewOutboxIntent,} from "./message-stream"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { ingestMessages } from "@/lib/community-db/sync"function message(id: string, seq: number, extra: Partial<Msg> = {}): CanonicalMessage {return {@@ -51,15 +53,25 @@ function intent(}}-function apply(state: MessageOverlayState, event: MessageOverlayEvent) {- return reduceMessageOverlay(state, event)+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>+beforeEach(async () => { owner = await createCommunityQueryOwner("u1") })+const canonicalRows = () => new Map([...owner.registry.collections.messages.values()].flatMap((row) =>+ typeof row.seq === "number" ? [[row.id, row as CanonicalMessage] as const] : []))+function materializeMessageStream(base: CanonicalMessage[], state: MessageOverlayIds) {+ return materialize(base, state, canonicalRows())+}+function apply(state: MessageOverlayIds, event: MessageOverlayEvent) {+ if (event.type === "wsMessage") ingestMessages(owner.registry, "channel", [event.message])+ if (event.type === "baseChanged") ingestMessages(owner.registry, "channel", event.messages)+ if (event.type === "postAck") throw new Error("POST confirmation belongs to the native mutation suite")+ return reduceMessageOverlay(state, event, canonicalRows())}-function ids(base: CanonicalMessage[], state: MessageOverlayState): string[] {+function ids(base: CanonicalMessage[], state: MessageOverlayIds): string[] {return materializeMessageStream(base, state).map((row) => row.id)}-function submit(state: MessageOverlayState, value = intent("n1", 1)) {+function submit(state: MessageOverlayIds, value = intent("n1", 1)) {return apply(state, { type: "submit", intent: value }).state}@@ -72,11 +84,18 @@ function canonical(return message(id, seq, { clientNonce: nonce, authorName: "Canonical", ...extra })}-function ack(nonce = "n1", id = "m1", seq = 11, extra: Partial<Msg> = {}): MessageOverlayEvent {- return { type: "postAck", nonce, message: canonical(id, seq, nonce, extra) }+function confirmation(nonce = "n1", id = "m1", seq = 11, extra: Partial<Msg> = {}): MessageOverlayEvent {+ return { type: "wsMessage", message: canonical(id, seq, nonce, extra) }}describe("message stream monotonic visibility", () => {+ it("gives the original window priority over a live ID with the same author and nonce", () => {+ const state = apply(emptyMessageOverlay(), confirmation("same", "live", 20)).state+ expect(state.liveIds).toEqual(["live"])+ expect(materializeMessageStream([canonical("window", 5, "same")], state)).toEqual([+ expect.objectContaining({ id: "window", seq: 5, clientNonce: "same" }),+ ])+ })it("removes a canonical live row after a post-unit delete", () => {let state = apply(emptyMessageOverlay(), {type: "wsMessage",@@ -85,25 +104,18 @@ describe("message stream monotonic visibility", () => {state = apply(state, { type: "messageRemoved", messageId: "m_delete" }).state- expect(state.liveById.has("m_delete")).toBe(false)+ expect(state.liveIds.includes("m_delete")).toBe(false)expect(ids([], state)).toEqual([])})- it("revokes preview URLs when a removed server message still has an outbox intent", () => {- let state = submit(emptyMessageOverlay(), intent("delete", 1, {+ it("revokes preview URLs when a pending message is removed", () => {+ const state = submit(emptyMessageOverlay(), intent("delete", 1, {localUploads: [{file: {} as File,previewObjectUrl: "blob:delete-preview",}],}))- const outboxByNonce = new Map(state.outboxByNonce)- outboxByNonce.set("delete", {- ...outboxByNonce.get("delete")!,- serverMessageId: "m_delete",- })- state = { ...state, outboxByNonce }-- const transition = apply(state, { type: "messageRemoved", messageId: "m_delete" })+ const transition = apply(state, { type: "messageRemoved", messageId: "temp_delete" })expect(transition.state.outboxByNonce.has("delete")).toBe(false)expect(transition.effects).toEqual([{@@ -124,25 +136,25 @@ describe("message stream monotonic visibility", () => {})it.each([- ["ack → WS → stale snapshot", [- ack(),+ ["confirmed → WS → stale snapshot", [+ confirmation(),{ type: "wsMessage", message: canonical() },{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },]],- ["WS → ack → stale snapshot", [+ ["WS → confirmed → stale snapshot", [{ type: "wsMessage", message: canonical() },- ack(),+ confirmation(),{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },]],- ["stale snapshot → ack → delayed WS", [+ ["stale snapshot → confirmed → delayed WS", [{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },- ack(),+ confirmation(),{ type: "wsMessage", message: canonical() },]],- ["WS → stale snapshot → ack", [+ ["WS → stale snapshot → confirmed", [{ type: "wsMessage", message: canonical() },{ type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },- ack(),+ confirmation(),]],] satisfies Array<[string, MessageOverlayEvent[]]>) ("%s always materializes exactly one canonical row",@@ -161,7 +173,7 @@ describe("message stream monotonic visibility", () => {state = apply(state, { type: "wsMessage", message: row }).stateexpect(ids([], state)).toEqual(["m1"])- expect(state.liveById.size).toBe(1)+ expect(state.liveIds.length).toBe(1)})it("retains WS canonical rows when different authors reuse the same nonce", () => {@@ -236,7 +248,7 @@ describe("message stream monotonic visibility", () => {it("retains server-id WS settlement when the canonical row omits the nonce", () => {let state = submit(emptyMessageOverlay())- state = apply(state, ack()).state+ state = apply(state, confirmation()).statestate = apply(state, {type: "wsMessage",message: message("m1", 11, { authorId: "u1", authorName: "Canonical" }),@@ -248,7 +260,7 @@ describe("message stream monotonic visibility", () => {it("retains server-id base settlement when the canonical row omits the nonce", () => {let state = submit(emptyMessageOverlay())- state = apply(state, ack()).state+ state = apply(state, confirmation()).stateconst base = [message("m1", 11, { authorId: "u1", authorName: "Canonical" })]state = apply(state, { type: "baseChanged", messages: base }).state@@ -277,8 +289,8 @@ describe("message stream monotonic visibility", () => {status: "pending",uploadStatus: "none",}))- expect(stored?.serverMessageId).toBeUndefined()- expect(stored?.serverSeq).toBeUndefined()+ expect(stored).not.toHaveProperty("serverMessageId")+ expect(stored).not.toHaveProperty("serverSeq")const materialized = materializeMessageStream([], state)[0]expect(materialized).toEqual(expect.objectContaining({id: "temp_n1",@@ -304,47 +316,17 @@ describe("message stream monotonic visibility", () => {expect(state.outboxByNonce.size).toBe(1)expect(state.outboxByNonce.get("n1")?.status).toBe("pending")- state = apply(state, ack()).state+ state = apply(state, confirmation()).statestate = apply(state, { type: "wsMessage", message: canonical() }).stateexpect(ids([], state)).toEqual(["m1"])expect(state.outboxByNonce.size).toBe(0)})- it("merges the full POST canonical row into the intent while retaining optimistic reply and attachments", () => {- const replyTo = { id: "reply_1", authorName: "Reply Author", text: "preview" }- const attachments: Msg["attachments"] = [{ kind: "image", name: "image.png", url: "/local/image" }]- let state = submit(emptyMessageOverlay(), intent("n1", 1, {- message: { ...localMessage("optimistic"), replyTo, attachments },- }))- state = apply(state, ack("n1", "m1", 11, {- authorName: "Canonical Author",- authorAvatar: "canonical-avatar",- content: "canonical content",- createdAt: "2026-08-07T10:00:00.000Z",- embeds: [{ title: "Canonical embed" }],- })).state-- expect(materializeMessageStream([], state)).toEqual([- expect.objectContaining({- id: "m1",- seq: 11,- authorName: "Canonical Author",- authorAvatar: "canonical-avatar",- content: "canonical content",- createdAt: "2026-08-07T10:00:00.000Z",- embeds: [{ title: "Canonical embed" }],- replyTo,- attachments,- clientNonce: "n1",- failed: false,- }),- ])- })it("does not treat latestSeq as proof that an anchor window contains the row", () => {let state = submit(emptyMessageOverlay())- state = apply(state, ack()).state+ state = apply(state, confirmation()).statestate = apply(state, {type: "baseChanged",messages: [message("anchor", 50)],@@ -352,19 +334,20 @@ describe("message stream monotonic visibility", () => {}).stateexpect(ids([message("anchor", 50)], state)).toEqual(["m1", "anchor"])- expect(state.outboxByNonce.has("n1")).toBe(true)+ expect(state.outboxByNonce.has("n1")).toBe(false)})it("settles an exact base hit into a bounded fallback that survives later window omission", () => {let state = submit(emptyMessageOverlay())- state = apply(state, ack()).state+ state = apply(state, confirmation()).statestate = apply(state, {type: "baseChanged",messages: [canonical("m1", 11, "n1", { content: "from base" })],}).stateexpect(state.outboxByNonce.size).toBe(0)- expect(state.liveById.get("m1")?.content).toBe("from base")+ expect(state.liveIds).toContain("m1")+ expect(canonicalRows().get("m1")?.content).toBe("from base")expect(ids([canonical()], state)).toEqual(["m1"])state = apply(state, {@@ -412,72 +395,22 @@ describe("message stream monotonic visibility", () => {"m10", "m20", "temp_n1", "temp_n2",])- state = apply(state, ack("n2", "m15", 15)).state+ state = apply(state, confirmation("n2", "m15", 15)).stateexpect(ids([message("m20", 20), message("m10", 10)], state)).toEqual(["m10", "m15", "m20", "temp_n1",])})- it("refreshes only an existing live fallback and never absorbs outbox", () => {- const initial = emptyMessageOverlay()- const absent = apply(initial, {- type: "liveRefreshed",- message: canonical("m1", 11, "n1", { content: "ignored" }),- })- expect(absent.state).toBe(initial)- expect(absent.state.liveById.size).toBe(0)-- let state = submit(emptyMessageOverlay())- state = apply(state, { type: "wsMessage", message: canonical() }).state- state = submit(state, intent("n2", 2))- state = apply(state, {- type: "liveRefreshed",- message: canonical("m1", 11, "n1", { content: "refreshed" }),- }).state- expect(state.liveById.get("m1")?.content).toBe("refreshed")- expect(state.outboxByNonce.has("n2")).toBe(true)- })-- it("does not refresh a live row from a peer row with the same nonce", () => {- const state = apply(emptyMessageOverlay(), {- type: "wsMessage",- message: canonical("m1", 11, "same", { authorId: "u1", content: "original" }),- }).state- const transition = apply(state, {- type: "liveRefreshed",- message: canonical("m2", 12, "same", { authorId: "u2", content: "peer" }),- })-- expect(transition.state).toBe(state)- expect(transition.state.liveById.get("m1")?.content).toBe("original")- expect(transition.state.liveById.has("m2")).toBe(false)- })-- it("patches edited content across live and acknowledged outbox rows", () => {- let state = submit(emptyMessageOverlay(), intent("n1", 1))- state = apply(state, ack()).state- state = apply(state, {- type: "wsMessage",- message: canonical("m2", 12, "n2", { content: "before" }),- }).state-- state = apply(state, { type: "messageEdited", messageId: "m1", content: "outbox edit" }).state- state = apply(state, { type: "messageEdited", messageId: "m2", content: "live edit" }).state-- expect(state.outboxByNonce.get("n1")?.message.content).toBe("outbox edit")- expect(state.liveById.get("m2")?.content).toBe("live edit")- })-it("bounds canonical live deltas to the existing 500-row live-tail scale", () => {let state = emptyMessageOverlay()for (let seq = 1; seq <= MAX_LIVE_MESSAGE_DELTAS + 2; seq++) {state = apply(state, { type: "wsMessage", message: message(`m${seq}`, seq) }).state}- expect(state.liveById.size).toBe(MAX_LIVE_MESSAGE_DELTAS)- expect(state.liveById.has("m1")).toBe(false)- expect(state.liveById.has("m2")).toBe(false)- expect(state.liveById.has(`m${MAX_LIVE_MESSAGE_DELTAS + 2}`)).toBe(true)+ expect(state.liveIds.length).toBe(MAX_LIVE_MESSAGE_DELTAS)+ expect(state.liveIds.includes("m1")).toBe(false)+ expect(state.liveIds.includes("m2")).toBe(false)+ expect(state.liveIds.includes(`m${MAX_LIVE_MESSAGE_DELTAS + 2}`)).toBe(true)})})@@ -500,6 +433,13 @@ describe("attachment ownership effects", () => {],})+ it("keeps upload intent without inventing an attachment URL when preview is absent", () => {+ const local = { file: retryFile, thumbnailBlob: retryThumbnail }+ const state = submit(emptyMessageOverlay(), intent("no-preview", 1, { localUploads: [local] }))+ expect(materializeMessageStream([], state)[0].attachments).toBeUndefined()+ expect(getOutboxRetryPayload(state, "no-preview")?.localUploads[0].file).toBe(retryFile)+ expect(getOutboxRetryPayload(state, "no-preview")?.localUploads[0].thumbnailBlob).toBe(retryThumbnail)+ })it("initializes lifecycle and retains immutable upload inputs through retry", () => {let state = submit(emptyMessageOverlay(), attachedIntent())expect(state.outboxByNonce.get("files")).toEqual(expect.objectContaining({@@ -525,22 +465,19 @@ describe("attachment ownership effects", () => {])})- it("transfers attachment preview ownership on ack and never revokes twice on WS/base/clear", () => {+ it("releases attachment previews on confirmation and never revokes twice on WS/base/clear", () => {let state = submit(emptyMessageOverlay(), attachedIntent())state = apply(state, {type: "uploadSettled",nonce: "files",attachments: [{ kind: "file", name: "notes.txt", url: "/media/notes", size: "1 KB" }],}).state- const acked = apply(state, ack("files", "mf", 20))+ const acked = apply(state, confirmation("files", "mf", 20))expect(acked.effects).toEqual([{ type: "revokeObjectUrl", url: "blob:a" },{ type: "revokeObjectUrl", url: "blob:b" },])- expect(acked.state.outboxByNonce.get("files")?.localUploads).toEqual([])- expect(acked.state.outboxByNonce.get("files")?.message.attachments).toEqual([- { kind: "file", name: "notes.txt", url: "/media/notes", size: "1 KB" },- ])+ expect(acked.state.outboxByNonce.has("files")).toBe(false)const ws = apply(acked.state, { type: "wsMessage", message: canonical("mf", 20, "files") })expect(ws.effects).toEqual([])@@ -556,14 +493,7 @@ describe("attachment ownership effects", () => {})it.each([- ["POST ack then base", (state: MessageOverlayState) => {- const acked = apply(state, ack("files", "mf", 20))- return apply(acked.state, {- type: "baseChanged",- messages: [canonical("mf", 20, "files")],- }).state- }],- ["WS then base", (state: MessageOverlayState) => {+ ["WS then base", (state: MessageOverlayIds) => {const ws = apply(state, {type: "wsMessage",message: canonical("mf", 20, "files", { attachments: settledAttachments }),@@ -573,13 +503,6 @@ describe("attachment ownership effects", () => {messages: [canonical("mf", 20, "files")],}).state}],- ["base before POST ack", (state: MessageOverlayState) => {- const based = apply(state, {- type: "baseChanged",- messages: [canonical("mf", 20, "files")],- })- return apply(based.state, ack("files", "mf", 20)).state- }],])("preserves settled attachments through a lagging canonical %s", (_label, arrange) => {let state = submit(emptyMessageOverlay(), attachedIntent())state = apply(state, {@@ -589,11 +512,12 @@ describe("attachment ownership effects", () => {}).stateconst converged = arrange(state)- const laggingBase = canonical("mf", 20, "files")+ const currentBase = canonicalRows().get("mf")!expect(converged.outboxByNonce.size).toBe(0)- expect(converged.liveById.get("mf")?.attachments).toEqual(settledAttachments)- expect(materializeMessageStream([laggingBase], converged)[0]?.attachments).toEqual(+ expect(converged.liveIds).toContain("mf")+ expect(canonicalRows().get("mf")?.attachments).toEqual(settledAttachments)+ expect(materializeMessageStream([currentBase], converged)[0]?.attachments).toEqual(settledAttachments,)})@@ -610,7 +534,8 @@ describe("attachment ownership effects", () => {messages: [emptyCanonical],}).state- expect(state.liveById.get("mf")?.attachments).toEqual([])+ expect(state.liveIds).toContain("mf")+ expect(canonicalRows().get("mf")?.attachments).toEqual([])expect(materializeMessageStream([emptyCanonical], state)[0]?.attachments).toEqual([])})@@ -634,20 +559,22 @@ describe("attachment ownership effects", () => {messages: [replacementCanonical],}).state- expect(state.liveById.get("mf")?.attachments).toEqual(replacement)+ expect(state.liveIds).toContain("mf")+ expect(canonicalRows().get("mf")?.attachments).toEqual(replacement)expect(materializeMessageStream([replacementCanonical], state)[0]?.attachments).toEqual(replacement,)})- it("preserves attachments when materialization reconciles a matching nonce under a new id", () => {- const state = apply(emptyMessageOverlay(), {+ it("preserves complete canonical attachments when reconciling a matching nonce under a new id", () => {+ let state = apply(emptyMessageOverlay(), {type: "wsMessage",message: canonical("ws-id", 20, "files", { attachments: settledAttachments }),}).state- const laggingBase = canonical("base-id", 20, "files")+ const completeBase = canonical("base-id", 20, "files", { attachments: settledAttachments })+ state = apply(state, { type: "baseChanged", messages: [completeBase] }).state- expect(materializeMessageStream([laggingBase], state)).toEqual([+ expect(materializeMessageStream([completeBase], state)).toEqual([expect.objectContaining({ id: "base-id", attachments: settledAttachments }),])})@@ -663,7 +590,7 @@ describe("attachment ownership effects", () => {{ type: "revokeObjectUrl", url: "blob:a" },{ type: "revokeObjectUrl", url: "blob:b" },])- const lateAck = apply(ws.state, ack("files", "mf", 20))+ const lateAck = apply(ws.state, confirmation("files", "mf", 20))expect(lateAck.effects).toEqual([])})@@ -701,7 +628,7 @@ describe("attachment ownership effects", () => {it("emits cleanup exactly once for canonical base absorption and clear", () => {const state = submit(emptyMessageOverlay(), attachedIntent())- const acked = apply(state, ack("files", "mf", 20))+ const acked = apply(state, confirmation("files", "mf", 20))expect(acked.effects).toHaveLength(2)const absorbed = apply(acked.state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })expect(absorbed.effects).toEqual([])diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.tsindex 754861da6..929120521 100644--- a/src/web/src/lib/community/message-stream.ts+++ b/src/web/src/lib/community/message-stream.ts@@ -1,24 +1,17 @@import { deriveView, sourceEvidence, viewEvidence } from "@/lib/observability/data-source"-import type { Msg } from "@/lib/community/models/message"-import type { MentionType } from "@alook/shared"-import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"-import { formatAttachmentSize } from "@/lib/community/attachment-presentation"+import type { Msg, SendAttachment } from "@/lib/community/models/message"+import type { MentionType, CommunityMessageResource } from "@alook/shared"+import { presentMessageAttachment } from "@/lib/community/attachment-presentation"export const MAX_LIVE_MESSAGE_DELTAS = 500-export type CanonicalMessage = Msg & { seq: number }+export type CanonicalMessage = Msg & Pick<CommunityMessageResource, "seq"> & Partial<Pick<CommunityMessageResource, "replyToId">>export type MessageScope =| { kind: "channel"; id: string; serverId: string }| { kind: "dm"; id: string }-type LocalUploadInput = Readonly<{- file: File- thumbnailBlob?: Blob- previewObjectUrl?: string- width?: number- height?: number-}>+type LocalUploadInput = Readonly<SendAttachment>type LocalOutboxMessage = Omit<Msg, "id" | "seq" | "clientNonce" | "failed">@@ -41,15 +34,8 @@ export type OutboxRetryPayload = Readonly<{type OutboxIntent = Omit<NewOutboxIntent, "message"> & {message: Msg- status: "pending" | "failed" | "acked"+ status: "pending" | "failed"uploadStatus: "none" | "pending" | "settled" | "failed"- serverMessageId?: string- serverSeq?: number-}--export type MessageOverlayState = {- liveById: ReadonlyMap<string, CanonicalMessage>- outboxByNonce: ReadonlyMap<string, OutboxIntent>}type MessageOverlayEffect = {@@ -57,8 +43,13 @@ type MessageOverlayEffect = {url: string}+export type MessageOverlayIds = {+ liveIds: readonly string[]+ outboxByNonce: ReadonlyMap<string, OutboxIntent>+}+export type MessageOverlayTransition = {- state: MessageOverlayState+ state: MessageOverlayIdseffects: MessageOverlayEffect[]}@@ -71,8 +62,6 @@ export type MessageOverlayEvent =| { type: "terminalReject"; nonce: string }| { type: "retry"; nonce: string }| { type: "wsMessage"; message: CanonicalMessage }- | { type: "liveRefreshed"; message: CanonicalMessage }- | { type: "messageEdited"; messageId: string; content: string }| { type: "messageRemoved"; messageId: string }| { type: "baseChanged"; messages: CanonicalMessage[]; latestSeq?: number }| { type: "dismissFailed"; nonce: string }@@ -83,14 +72,14 @@ type MaterializedEntry = {localOrdinal?: number}-export function emptyMessageOverlay(): MessageOverlayState {+export function emptyMessageOverlay(): MessageOverlayIds {return {- liveById: new Map(),+ liveIds: [],outboxByNonce: new Map(),}}-function unchanged(state: MessageOverlayState): MessageOverlayTransition {+function unchanged(state: MessageOverlayIds): MessageOverlayTransition {return { state, effects: [] }}@@ -104,7 +93,7 @@ function revokeEffects(intent: OutboxIntent): MessageOverlayEffect[] {}function updateIntent(- state: MessageOverlayState,+ state: MessageOverlayIds,nonce: string,update: (intent: OutboxIntent) => OutboxIntent,): MessageOverlayTransition {@@ -115,86 +104,43 @@ function updateIntent(return { state: { ...state, outboxByNonce }, effects: [] }}-function canonicalDeltaOrder(a: CanonicalMessage, b: CanonicalMessage): number {- return a.seq - b.seq+function compoundIdentity(message: Pick<Msg, "authorId" | "clientNonce">): string | undefined {+ return message.authorId && message.clientNonce && !message.clientNonce.startsWith("srv:")+ ? JSON.stringify([message.authorId, message.clientNonce]) : undefined}-function compoundIdentity(- message: Pick<Msg, "authorId" | "clientNonce">,-): string | undefined {- if (!message.authorId || !message.clientNonce || message.clientNonce.startsWith("srv:")) {- return undefined- }- return JSON.stringify([message.authorId, message.clientNonce])-}--function trimLiveDeltas(liveById: Map<string, CanonicalMessage>): void {- const overflow = liveById.size - MAX_LIVE_MESSAGE_DELTAS+function trimLiveDeltas(liveIds: Set<string>, read: (id: string) => CanonicalMessage | undefined): void {+ const overflow = liveIds.size - MAX_LIVE_MESSAGE_DELTASif (overflow <= 0) return- const oldest = [...liveById.values()].sort(canonicalDeltaOrder).slice(0, overflow)- for (const message of oldest) liveById.delete(message.id)+ const oldest = [...liveIds].sort((a, b) => (read(a)?.seq ?? 0) - (read(b)?.seq ?? 0)).slice(0, overflow)+ for (const id of oldest) liveIds.delete(id)}-function upsertLiveCanonical(- liveById: Map<string, CanonicalMessage>,- message: CanonicalMessage,-): void {+function upsertLiveCanonical(liveIds: Set<string>, message: CanonicalMessage, read: (id: string) => CanonicalMessage | undefined): void {const identity = compoundIdentity(message)- if (identity) {- for (const [id, current] of liveById) {- if (id !== message.id && compoundIdentity(current) === identity) liveById.delete(id)- }+ if (identity) for (const id of liveIds) {+ const current = read(id)+ if (id !== message.id && current && compoundIdentity(current) === identity) liveIds.delete(id)}- liveById.set(message.id, deriveView({ ...message, failed: false }, [viewEvidence(message)]))+ liveIds.add(message.id)}-function mergeCanonicalAttachments(- current: Pick<Msg, "attachments">,- canonical: CanonicalMessage,-): CanonicalMessage {- if (canonical.attachments !== undefined || !current.attachments?.length) {- return canonical- }- return deriveView({ ...canonical, attachments: current.attachments }, [viewEvidence(canonical), viewEvidence(current)])-}--function materializeIntent(intent: OutboxIntent): Msg {+export function materializeIntent(intent: OutboxIntent): Msg {return deriveView({...intent.message,- id: intent.serverMessageId ?? intent.tempId,- ...(intent.serverSeq !== undefined ? { seq: intent.serverSeq } : {}),+ id: intent.tempId,clientNonce: intent.nonce,failed: intent.status === "failed" || intent.uploadStatus === "failed",- }, [sourceEvidence(intent, "local_mutation"), ...(intent.status === "acked" ? [viewEvidence(intent.message)] : [])])+ }, [sourceEvidence(intent, "local_mutation")])}function localUploadAttachments(uploads: readonly LocalUploadInput[],): Msg["attachments"] {- const attachments: NonNullable<Msg["attachments"]> = []- for (const upload of uploads) {- if (!upload.previewObjectUrl) continue- if (isInlineAttachmentContentType(upload.file.type)) {- attachments.push({- kind: "image",- name: upload.file.name,- url: upload.previewObjectUrl,- contentType: upload.file.type,- sizeBytes: upload.file.size,- width: upload.width,- height: upload.height,- })- continue- }- attachments.push({- kind: "file",- name: upload.file.name,- url: upload.previewObjectUrl,- contentType: upload.file.type,- sizeBytes: upload.file.size,- size: formatAttachmentSize(upload.file.size),- })- }+ const attachments = uploads.flatMap((upload) => upload.previewObjectUrl ? [presentMessageAttachment({+ name: upload.file.name, url: upload.previewObjectUrl, contentType: upload.file.type, sizeBytes: upload.file.size,+ width: upload.width, height: upload.height,+ })] : [])return attachments.length > 0 ? attachments : undefined}@@ -213,18 +159,6 @@ function upsertMaterialized(byId.set(message.id, entry)}-function findMaterializedMatch(- byId: ReadonlyMap<string, MaterializedEntry>,- idByIdentity: ReadonlyMap<string, string>,- message: Msg,-): MaterializedEntry | undefined {- const exact = byId.get(message.id)- if (exact) return exact- const identity = compoundIdentity(message)- const matchedId = identity ? idByIdentity.get(identity) : undefined- return matchedId ? byId.get(matchedId) : undefined-}-function materializedOrder(a: MaterializedEntry, b: MaterializedEntry): number {const aSeq = a.message.seqconst bSeq = b.message.seq@@ -245,36 +179,33 @@ function materializedOrder(a: MaterializedEntry, b: MaterializedEntry): number {export function materializeMessageStream(baseMessages: CanonicalMessage[],- overlay: MessageOverlayState,+ overlay: MessageOverlayIds,+ canonical: Pick<ReadonlyMap<string, CanonicalMessage>, "get">,): Msg[] {const byId = new Map<string, MaterializedEntry>()const idByIdentity = new Map<string, string>()- // Later sources replace earlier presentation for the same id/nonce. An- // omitted attachment projection cannot erase richer presentation state.for (const intent of overlay.outboxByNonce.values()) {upsertMaterialized(byId, idByIdentity, {message: materializeIntent(intent),- localOrdinal: intent.status === "acked" ? undefined : intent.localOrdinal,+ localOrdinal: intent.localOrdinal,})}- for (const message of overlay.liveById.values()) {- upsertMaterialized(byId, idByIdentity, { message })+ for (const id of overlay.liveIds) {+ const message = canonical.get(id)+ if (message) upsertMaterialized(byId, idByIdentity, {+ message: deriveView({ ...message, failed: false }, [viewEvidence(message)]),+ })}for (const message of baseMessages) {- const current = findMaterializedMatch(byId, idByIdentity, message)- upsertMaterialized(byId, idByIdentity, {- message: current- ? mergeCanonicalAttachments(current.message, message)- : message,- })+ upsertMaterialized(byId, idByIdentity, { message })}return [...byId.values()].sort(materializedOrder).map((entry) => entry.message)}export function getOutboxRetryPayload(- state: MessageOverlayState,+ state: MessageOverlayIds,nonce: string,): OutboxRetryPayload | undefined {const intent = state.outboxByNonce.get(nonce)@@ -289,8 +220,9 @@ export function getOutboxRetryPayload(}export function reduceMessageOverlay(- state: MessageOverlayState,- event: MessageOverlayEvent,+ state: MessageOverlayIds,+ event: Exclude<MessageOverlayEvent, { type: "postAck" }>,+ canonical: Pick<ReadonlyMap<string, CanonicalMessage>, "get"> = new Map(),): MessageOverlayTransition {switch (event.type) {case "submit": {@@ -335,32 +267,6 @@ export function reduceMessageOverlay(message: { ...intent.message, failed: true },}))- case "postAck": {- const intent = state.outboxByNonce.get(event.nonce)- if (!intent) return unchanged(state)- const outboxByNonce = new Map(state.outboxByNonce)- const canonical = event.message- outboxByNonce.set(event.nonce, {- ...intent,- status: "acked",- serverMessageId: canonical.id,- serverSeq: canonical.seq,- localUploads: [],- message: {- ...intent.message,- ...canonical,- clientNonce: event.nonce,- replyTo: canonical.replyTo ?? intent.message.replyTo,- attachments: canonical.attachments ?? intent.message.attachments,- failed: false,- },- })- return {- state: { ...state, outboxByNonce },- effects: revokeEffects(intent),- }- }-case "postFail":return updateIntent(state, event.nonce, (intent) => ({...intent,@@ -388,7 +294,7 @@ export function reduceMessageOverlay(}))case "wsMessage": {- const liveById = new Map(state.liveById)+ const liveIds = new Set(state.liveIds.filter((id) => canonical.get(id) !== undefined))const outboxByNonce = new Map(state.outboxByNonce)const effects: MessageOverlayEffect[] = []const eventIdentity = compoundIdentity(event.message)@@ -399,81 +305,36 @@ export function reduceMessageOverlay(authorId: intent.message.authorId,clientNonce: intentNonce,})- const matchesIdentity = eventIdentity !== undefined && eventIdentity === intentIdentity- const matchesServerId = intent.serverMessageId === event.message.id- if (!matchesIdentity && !matchesServerId) continue+ if (eventIdentity === undefined || eventIdentity !== intentIdentity) continueoutboxByNonce.delete(intentNonce)effects.push(...revokeEffects(intent))}- // The complete enriched WS row is canonical presentation.- upsertLiveCanonical(liveById, event.message)- trimLiveDeltas(liveById)- return { state: { liveById, outboxByNonce }, effects }- }-- case "liveRefreshed": {- let existingId: string | undefined- if (state.liveById.has(event.message.id)) {- existingId = event.message.id- } else {- const identity = compoundIdentity(event.message)- for (const [id, message] of state.liveById) {- if (identity && compoundIdentity(message) === identity) {- existingId = id- break- }- }- }- if (!existingId) return unchanged(state)- const liveById = new Map(state.liveById)- if (existingId !== event.message.id) liveById.delete(existingId)- upsertLiveCanonical(liveById, event.message)- trimLiveDeltas(liveById)- return { state: { ...state, liveById }, effects: [] }- }-- case "messageEdited": {- let changed = false- const liveById = new Map(state.liveById)- const live = liveById.get(event.messageId)- if (live) {- const edited = { ...live, content: event.content }- liveById.set(event.messageId, deriveView(edited, [viewEvidence(live), sourceEvidence(edited, "local_mutation")]))- changed = true- }- const outboxByNonce = new Map(state.outboxByNonce)- for (const [nonce, intent] of outboxByNonce) {- if ((intent.serverMessageId ?? intent.tempId) !== event.messageId) continue- outboxByNonce.set(nonce, {- ...intent,- message: { ...intent.message, content: event.content },- })- changed = true- }- return changed- ? { state: { ...state, liveById, outboxByNonce }, effects: [] }- : unchanged(state)+ const read = (id: string) => id === event.message.id ? event.message : canonical.get(id)+ upsertLiveCanonical(liveIds, event.message, read)+ trimLiveDeltas(liveIds, read)+ return { state: { liveIds: [...liveIds], outboxByNonce }, effects }}case "messageRemoved": {- let changed = false- const liveById = new Map(state.liveById)- if (liveById.delete(event.messageId)) changed = true+ const liveIds = new Set(state.liveIds.filter((id) => canonical.get(id) !== undefined))+ let changed = liveIds.size !== state.liveIds.length+ if (liveIds.delete(event.messageId)) changed = trueconst outboxByNonce = new Map(state.outboxByNonce)const effects: MessageOverlayEffect[] = []for (const [nonce, intent] of outboxByNonce) {- if ((intent.serverMessageId ?? intent.tempId) !== event.messageId) continue+ if (intent.tempId !== event.messageId) continueoutboxByNonce.delete(nonce)effects.push(...revokeEffects(intent))changed = true}return changed- ? { state: { liveById, outboxByNonce }, effects }+ ? { state: { liveIds: [...liveIds], outboxByNonce }, effects }: unchanged(state)}case "baseChanged": {+ if (!state.liveIds.length && !state.outboxByNonce.size) return unchanged(state)const baseById = new Map(event.messages.map((message) => [message.id, message]))const baseByIdentity = new Map(event.messages.flatMap((message) => {@@ -481,46 +342,35 @@ export function reduceMessageOverlay(return identity ? [[identity, message] as const] : []}),)- const liveById = new Map(state.liveById)+ const liveIds = new Set(state.liveIds.filter((id) => canonical.get(id) !== undefined))const outboxByNonce = new Map(state.outboxByNonce)const effects: MessageOverlayEffect[] = []- for (const message of state.liveById.values()) {- const identity = compoundIdentity(message)- const canonical = baseById.get(message.id)- ?? (identity ? baseByIdentity.get(identity) : undefined)- if (canonical) {- upsertLiveCanonical(liveById, mergeCanonicalAttachments(message, canonical))- }+ const read = (id: string) => baseById.get(id) ?? canonical.get(id)+ for (const id of state.liveIds) {+ const message = canonical.get(id)+ const identity = message && compoundIdentity(message)+ const replacement = baseById.get(id) ?? (identity ? baseByIdentity.get(identity) : undefined)+ if (replacement) upsertLiveCanonical(liveIds, replacement, read)}for (const [nonce, intent] of outboxByNonce) {- const canonicalById = intent.serverMessageId- ? baseById.get(intent.serverMessageId)- : undefinedconst identity = compoundIdentity({authorId: intent.message.authorId,clientNonce: nonce,})- const canonical = canonicalById?.authorId === intent.message.authorId- ? canonicalById- : identity- ? baseByIdentity.get(identity)- : undefined+ const canonical = identity ? baseByIdentity.get(identity) : undefinedif (!canonical) continueoutboxByNonce.delete(nonce)- upsertLiveCanonical(- liveById,- mergeCanonicalAttachments(intent.message, canonical),- )+ upsertLiveCanonical(liveIds, canonical, read)effects.push(...revokeEffects(intent))}- trimLiveDeltas(liveById)+ trimLiveDeltas(liveIds, read)// `latestSeq` is deliberately not a deletion predicate: an anchor page// can report a high stream seq while omitting this visible tail row. A// base hit refreshes the bounded fallback but does not delete it, because// a later window may omit the row again.- return { state: { liveById, outboxByNonce }, effects }+ return { state: { liveIds: [...liveIds], outboxByNonce }, effects }}case "dismissFailed": {diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.tsindex 9a8a352e0..57c5e0ffc 100644--- a/src/web/src/lib/community/message-wire.test.ts+++ b/src/web/src/lib/community/message-wire.test.ts@@ -18,14 +18,21 @@ function wire(}describe("projectCommunityMessageCreate", () => {+ it("keeps explicit empty rich fields distinct from omission", () => {+ expect(projectCommunityMessageCreate(wire({ attachments: [], embeds: [] }), "channel-1"))+ .toMatchObject({ attachments: [], embeds: [] })+ const sparse = projectCommunityMessageCreate(wire(), "channel-1")+ expect(sparse).not.toHaveProperty("attachments")+ expect(sparse).not.toHaveProperty("embeds")+ })it("preserves canonical identity and presentation fields", () => {const replyTo = { id: "m0", authorName: "A", text: "prior" }const approval = {friendshipId: "f1",status: "pending" as const,waitingOn: "you" as const,- otherProfile: { id: "u2", name: "Other", discriminator: "0002", image: null },- botProfile: { id: "b1", name: "Bot", discriminator: "0003", image: null },+ otherProfile: { id: "u2", name: "Other", discriminator: "0002", image: null, avatarVersion: 0 },+ botProfile: { id: "b1", name: "Bot", discriminator: "0003", image: null, avatarVersion: 0 },}const projected = projectCommunityMessageCreate(wire({clientNonce: "nonce",@@ -34,7 +41,7 @@ describe("projectCommunityMessageCreate", () => {authorAvatar: "avatar",replyTo,approval,- }))+ }), "channel-1")expect(projected).toEqual(expect.objectContaining({id: "m1",seq: 42,@@ -51,6 +58,16 @@ describe("projectCommunityMessageCreate", () => {}))})+ it("keeps valid embed fields and omits an entirely malformed field list", () => {+ const result = projectCommunityMessageCreate(wire({ embeds: [+ { title: "Mixed", fields: [null, { name: "Key", value: "Value", inline: true }, { name: "Missing value" }] },+ { title: "Invalid", fields: [null, { name: "Missing value" }] },+ ] }), "channel-1")+ expect(result.embeds).toEqual([+ { title: "Mixed", fields: [{ name: "Key", value: "Value", inline: true }] },+ { title: "Invalid", fields: undefined },+ ])+ })it("narrows embeds and maps safe image/file attachments", () => {const projected = projectCommunityMessageCreate(wire({embeds: [{ title: "Card", url: "https://example.com" }, { url: "missing-title" }, null],@@ -59,7 +76,7 @@ describe("projectCommunityMessageCreate", () => {{ id: "a2", filename: "doc.pdf", url: "/doc", contentType: "application/pdf", size: 2048 },{ id: "a3", filename: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", size: 1024 },],- }))+ }), "channel-1")expect(projected.embeds).toEqual([{ title: "Card", url: "https://example.com" }])expect(projected.attachments).toEqual([{ kind: "image", name: "photo.png", url: "/photo", contentType: "image/png", sizeBytes: 2048, width: 640, height: 480 },@@ -82,7 +99,7 @@ describe("projectPostedMessage", () => {type: "default",embeds: null,createdAt: "2026-08-06T00:00:00.000Z",- } as never, "nonce-2")+ }, "nonce-2", "dm-1")expect(projected).toMatchObject({authorAvatar: "G",@@ -90,4 +107,26 @@ describe("projectPostedMessage", () => {clientNonce: "nonce-2",})})++ it("rejects an absent or mismatched actual POST channel scope", () => {+ const row = { id: "m3", seq: 44, authorId: "u3", authorName: "Peer", authorImage: null,+ authorAvatarVersion: 0, content: null, type: "default", embeds: null, createdAt: "2026-08-06T00:00:00.000Z" }+ expect(() => projectPostedMessage(row, "nonce-3", "")).toThrow()+ expect(() => projectPostedMessage(Object.assign({}, row, { channelId: "other" }), "nonce-3", "dm-1"))+ .toThrow("Message resource scope mismatch")+ expect(projectPostedMessage(row, "nonce-3", "dm-1")).toMatchObject({ id: "m3", content: "", type: "chat" })+ })++ it("keeps absent POST and WS rich content sparse", () => {+ const posted = projectPostedMessage({ id: "m4", seq: 45, authorId: "u4", authorName: "Peer", authorImage: null,+ authorAvatarVersion: 0, content: "plain", type: "default", embeds: null, createdAt: "2026-08-06T00:00:00.000Z" }, "nonce-4", "dm-1")+ for (const message of [posted, projectCommunityMessageCreate(wire(), "channel-1")]) {+ expect(message).not.toHaveProperty("attachments")+ expect(message).not.toHaveProperty("embeds")+ expect(message).not.toHaveProperty("channelId")+ expect(message).not.toHaveProperty("replyToId")+ expect(message).not.toHaveProperty("replyTo")+ }+ })+})diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.tsindex 16fc36fd4..2b7835409 100644--- a/src/web/src/lib/community/message-wire.ts+++ b/src/web/src/lib/community/message-wire.ts@@ -1,170 +1,79 @@-import type { CommunityMessageCreate } from "@alook/shared"-import type { Msg } from "@/lib/community/models/message"+import { normalizeCommunityMessageResource, CommunityMessageResourceSchema, type CommunityMessageCreate, type CommunityMessageResource } from "@alook/shared"+import { MessageEmbedSchema, type Msg } from "@/lib/community/models/message"+import type { MessageRow } from "./message-payload"import { avatarInitial } from "@/lib/community/avatar"-import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"-import { formatAttachmentSize } from "@/lib/community/attachment-presentation"+import { presentMessageAttachment } from "@/lib/community/attachment-presentation"import type { CanonicalMessage } from "@/lib/community/message-stream"import { canonicalUserImage } from "@/lib/community/storage"import { projectMessageWireType } from "@/lib/community/message-wire-type"type UiEmbed = NonNullable<Msg["embeds"]>[number]+const richContentSchema = CommunityMessageResourceSchema.pick({ attachments: true, embeds: true }).partial().strip()-export type PostedMessage = {- id: string- seq: number- createdAt: string- content: string | null- authorId: string- authorName: string- authorImage: string | null- authorAvatarVersion: number- type: string | null- embeds: unknown-}--function stringValue(value: unknown): string | undefined {- return typeof value === "string" ? value : undefined-}+export type PostedMessage = Pick<MessageRow, "id" | "seq" | "createdAt" | "content" | "authorId" | "authorName" | "authorImage" | "authorAvatarVersion" | "type" | "embeds"> & Partial<Pick<CommunityMessageResource, "replyToId" | "replyTo" | "attachments">>-function numberValue(value: unknown): number | undefined {- return typeof value === "number" && Number.isFinite(value) ? value : undefined+function omitUndefined<T>(value: T): T {+ if (Array.isArray(value)) return value.map(omitUndefined) as T+ if (!value || typeof value !== "object") return value+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined)+ .map(([key, field]) => [key, omitUndefined(field)])) as T}-function objectValue(value: unknown): Record<string, unknown> | undefined {- return typeof value === "object" && value !== null && !Array.isArray(value)- ? value as Record<string, unknown>- : undefined+function projectEmbed(value: unknown): UiEmbed | undefined {+ const parsed = MessageEmbedSchema.safeParse(value)+ return parsed.success ? omitUndefined(parsed.data) : undefined}-function projectEmbed(value: unknown): UiEmbed | undefined {- const input = objectValue(value)- const title = stringValue(input?.title)- if (!input || title === undefined) return undefined- const imageInput = objectValue(input.image)- const imageUrl = stringValue(imageInput?.url)- const thumbnailInput = objectValue(input.thumbnail)- const thumbnailUrl = stringValue(thumbnailInput?.url)- const footerInput = objectValue(input.footer)- const footerText = stringValue(footerInput?.text)- const authorInput = objectValue(input.author)- const authorName = stringValue(authorInput?.name)- const fields = Array.isArray(input.fields)- ? input.fields.flatMap((field) => {- const row = objectValue(field)- const name = stringValue(row?.name)- const fieldValue = stringValue(row?.value)- if (name === undefined || fieldValue === undefined) return []- return [{- name,- value: fieldValue,- ...(typeof row?.inline === "boolean" ? { inline: row.inline } : {}),- }]- })- : undefined+export function projectMessageRichContent(value: unknown): Pick<Msg, "attachments" | "embeds"> {+ const { attachments, embeds } = richContentSchema.parse(value)return {- title,- ...(stringValue(input.provider) !== undefined ? { provider: stringValue(input.provider) } : {}),- ...(stringValue(input.url) !== undefined ? { url: stringValue(input.url) } : {}),- ...(stringValue(input.desc) !== undefined ? { desc: stringValue(input.desc) } : {}),- ...(stringValue(input.color) !== undefined ? { color: stringValue(input.color) } : {}),- ...(imageUrl !== undefined ? {- image: {- url: imageUrl,- ...(numberValue(imageInput?.width) !== undefined ? { width: numberValue(imageInput?.width) } : {}),- ...(numberValue(imageInput?.height) !== undefined ? { height: numberValue(imageInput?.height) } : {}),- },- } : {}),- ...(thumbnailUrl !== undefined ? { thumbnail: { url: thumbnailUrl } } : {}),- ...(fields?.length ? { fields } : {}),- ...(footerText !== undefined ? {- footer: {- text: footerText,- ...(stringValue(footerInput?.iconUrl) !== undefined ? { iconUrl: stringValue(footerInput?.iconUrl) } : {}),- },- } : {}),- ...(authorName !== undefined ? {- author: {- name: authorName,- ...(stringValue(authorInput?.url) !== undefined ? { url: stringValue(authorInput?.url) } : {}),- ...(stringValue(authorInput?.iconUrl) !== undefined ? { iconUrl: stringValue(authorInput?.iconUrl) } : {}),- },- } : {}),+ ...(attachments ? { attachments: attachments.map(presentMessageAttachment) } : {}),+ ...(embeds ? { embeds: embeds.flatMap((value) => { const embed = projectEmbed(value); return embed ? [embed] : [] }) } : {}),}}export function projectCommunityMessageCreate(message: CommunityMessageCreate["message"],+ channelId: string,): CanonicalMessage {- const attachments = message.attachments?.map((attachment) => {- if (isInlineAttachmentContentType(attachment.contentType)) {- return {- kind: "image" as const,- name: attachment.filename,- url: attachment.url,- contentType: attachment.contentType,- sizeBytes: attachment.size,- ...(attachment.thumbnailUrl ? { thumbnailUrl: attachment.thumbnailUrl } : {}),- width: attachment.width ?? undefined,- height: attachment.height ?? undefined,- }- }- return {- kind: "file" as const,- name: attachment.filename,- url: attachment.url,- contentType: attachment.contentType,- sizeBytes: attachment.size,- size: formatAttachmentSize(attachment.size),- }- })- const embeds = message.embeds?.flatMap((embed) => {- const projected = projectEmbed(embed)- return projected ? [projected] : []- })- return {- id: message.id,- seq: message.seq,- type: message.type,- ...(message.systemKind ? { systemKind: message.systemKind } : {}),- authorId: message.authorId,- authorName: message.authorName,+ const attachments = message.attachments?.map((attachment) => presentMessageAttachment({+ name: attachment.filename, url: attachment.url, contentType: attachment.contentType,+ sizeBytes: attachment.size,+ ...(attachment.thumbnailUrl ? { thumbnailUrl: attachment.thumbnailUrl } : {}),+ width: attachment.width ?? undefined, height: attachment.height ?? undefined,+ }))+ return projectCanonicalMessage({+ ...message,authorAvatar: message.authorAvatar || avatarInitial(message.authorName),- authorAvatarVersion: message.authorAvatarVersion,- content: message.content,- createdAt: message.createdAt,- ...(message.clientNonce ? { clientNonce: message.clientNonce } : {}),- ...(message.replyTo ? { replyTo: message.replyTo } : {}),- ...(message.approval ? { approval: message.approval } : {}),- ...(embeds?.length ? { embeds } : {}),- ...(attachments?.length ? { attachments } : {}),+ attachments,+ }, channelId)+}++function projectCanonicalMessage(value: Record<string, unknown>, channelId: string): CanonicalMessage {+ const { channelId: _channelId, replyToId, replyTo, clientNonce, attachments: _attachments, embeds: _embeds, ...message } = normalizeCommunityMessageResource(value, channelId)+ const { attachments, embeds } = projectMessageRichContent({ attachments: _attachments, embeds: _embeds })+ return {+ ...message,+ ...("replyTo" in value ? { replyTo } : {}),+ ...("replyToId" in value || "replyTo" in value ? { replyToId } : {}),+ ...(clientNonce !== null ? { clientNonce } : {}),+ ...(value.attachments !== undefined ? { attachments } : {}),+ ...(value.embeds != null ? { embeds } : {}),}}export function projectPostedMessage(message: PostedMessage,clientNonce: string,+ channelId: string,): CanonicalMessage {- const embeds = Array.isArray(message.embeds)- ? message.embeds.flatMap((embed) => {- const projected = projectEmbed(embed)- return projected ? [projected] : []- })- : undefined- return {- id: message.id,- seq: message.seq,- ...projectMessageWireType(message.type),- authorId: message.authorId,- authorName: message.authorName,- authorAvatar: canonicalUserImage(- message.authorId,- message.authorImage,- message.authorAvatarVersion,- ) || avatarInitial(message.authorName),- authorAvatarVersion: message.authorAvatarVersion,- content: message.content ?? "",- createdAt: message.createdAt,+ const { authorImage, type, content, embeds, ...fields } = message+ return projectCanonicalMessage({+ ...fields,+ ...projectMessageWireType(type),+ authorAvatar: canonicalUserImage(message.authorId, authorImage, message.authorAvatarVersion) || avatarInitial(message.authorName),+ content: content ?? "",+ embeds: Array.isArray(embeds) ? embeds : undefined,clientNonce,- ...(embeds?.length ? { embeds } : {}),- }+ }, channelId)}diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.tsindex 81a3e5d99..ab04c35de 100644--- a/src/web/src/lib/community/messages.ts+++ b/src/web/src/lib/community/messages.ts@@ -1,8 +1,28 @@-import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE } from "@alook/shared"+import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE, type CommunityMessageAttachment, type CommunityMessageResource } from "@alook/shared"import { isInlineAttachmentContentType } from "./attachment-content-type"import { formatAttachmentSize } from "./attachment-presentation"import { attachmentThumbnailUrl, attachmentUrl } from "./storage"+export function parseCommunityMessageWindow(params: URLSearchParams) {+ const supplied = ["cursor", "since", "anchor"].filter((key) => params.has(key))+ const window = params.get("window") ?? (params.has("anchor") ? "around" : params.has("since") ? "after" : params.has("cursor") ? "before" : "tail")+ if (!["tail", "before", "after", "around"].includes(window) || supplied.length > 1+ || params.has("since") && window !== "after") throw new Error("invalid message window")+ const rawCursor = window === "after" ? params.get("cursor") ?? params.get("since") : params.get("cursor")+ const anchor = params.get("anchorMessageId") ?? params.get("anchor")+ if ((window === "tail" && (rawCursor !== null || anchor !== null))+ || (window === "around" && (rawCursor !== null || !anchor?.trim()))+ || ((window === "before" || window === "after") && (!rawCursor || anchor !== null))) throw new Error("invalid message window inputs")+ if (["before", "after", "around"].some((key) => params.has(key))) throw new Error("seq windows require community contract v1")+ const cursor = rawCursor ? parseCursor(rawCursor) : undefined+ if (rawCursor && (!cursor || rawCursor.split("|").length !== 2 || !Number.isFinite(Date.parse(cursor.createdAt)))) throw new Error("invalid message cursor")+ const rawLimit = params.get("limit")+ const limit = rawLimit === null ? DEFAULT_MESSAGE_PAGE_SIZE : Number(rawLimit)+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_MESSAGE_PAGE_SIZE) throw new Error("invalid message limit")+ return { anchorId: window === "around" ? anchor!.trim() : undefined,+ since: window === "after" ? cursor : undefined, cursor: window === "before" ? cursor : undefined, pageSize: limit }+}+// Parse cursor from query params (format: "createdAt|id")export function parseCursor(cursorParam: string | null): { createdAt: string; id: string } | undefined {if (!cursorParam) return undefined@@ -148,12 +168,12 @@ export function buildMemberPaginatedResponse<T extends { joinedAt: string; id: s// the read paths never surface them.export function groupAttachments(attachments: Array<{ id: string; messageId: string | null; targetId: string; filename: string; r2Key: string; thumbnailR2Key?: string | null; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>-): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }>> {- const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }>> = {}+): Record<string, CommunityMessageAttachment[]> {+ const map: Record<string, CommunityMessageAttachment[]> = {}for (const a of attachments) {if (!a.messageId) continueconst kind = isInlineAttachmentContentType(a.contentType) ? "image" : "file"- const entry = {+ const entry: CommunityMessageAttachment = {kind,name: a.filename,url: attachmentUrl(a.targetId, a.id),@@ -164,7 +184,7 @@ export function groupAttachments(: {}),...(kind === "file" && a.size !== null ? { size: formatAttachmentSize(a.size) } : {}),...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),- } as { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }+ };(map[a.messageId] ??= []).push(entry)}return map@@ -174,8 +194,8 @@ export function groupAttachments(export function groupReactions(reactions: Array<{ messageId: string; emoji: string; userId: string }>,currentUserId: string-): Record<string, Array<{ emoji: string; count: number; me: boolean; userIds: string[] }>> {- const map: Record<string, Array<{ emoji: string; count: number; me: boolean; userIds: string[] }>> = {}+): Record<string, NonNullable<CommunityMessageResource["reactions"]>> {+ const map: Record<string, NonNullable<CommunityMessageResource["reactions"]>> = {}for (const r of reactions) {const list = (map[r.messageId] ??= [])const existing = list.find((x) => x.emoji === r.emoji)diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsindex 799717f91..4cdb2d2a1 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -1,13 +1,9 @@-import type { FriendApprovalPayload } from "@alook/shared"+import { z } from "zod"+import type { CommunityChannelResource, CommunityMessageResource, CommunityMessageAttachment, CommunityMessagesRead } from "@alook/shared"import { deriveView, viewEvidence } from "@/lib/observability/data-source"// ── Messages ───────────────────────────────────────────────────────────────-type AttachmentMetadata = {- name: string- url: string- contentType?: string- sizeBytes?: number-}+type AttachmentMetadata = Pick<CommunityMessageAttachment, "name" | "url" | "contentType" | "sizeBytes">export type FileAttachment = AttachmentMetadata & { kind: "file"; size: string }@@ -23,75 +19,56 @@ export type ImagePreview = {height?: number}-type Embed = {- provider?: string- url?: string- title: string- desc?: string- color?: string- image?: { url: string; width?: number; height?: number }- thumbnail?: { url: string }- fields?: { name: string; value: string; inline?: boolean }[]- footer?: { text: string; iconUrl?: string }- author?: { name: string; url?: string; iconUrl?: string }-}+const optionalString = z.string().optional().catch(undefined)+const optionalNumber = z.number().optional().catch(undefined)+const optionalObject = <Shape extends z.ZodRawShape>(shape: Shape) => z.object(shape).optional().catch(undefined)-export type Reaction = { emoji: string; count: number; me: boolean; userIds: string[] }--export type Msg = {- id: string // nanoid- // Exhaustive discriminator (#12 — was `type?: "system"`, an incomplete- // partial discriminator that let `!m.type` silently misclassify a future- // third kind as an ordinary chat message). `mapMessageForApi`/`mapMessageForWs`- // always emit one of these two values now — never `undefined`.- type: "chat" | "system"- // Only ever set alongside `type: "system"` for a thread-creation system- // message (see `message-payload.ts`'s `splitType`). The `"join"` value- // that used to be part of this type is removed — no code path has ever- // produced it (join notifications are pure WS events with no persisted- // message row, and stay that way — see the debt-record's Out of scope).- systemKind?: "thread"- // Author's user id — populated by `mapMessageForApi` / WS message-create,- // consumed by `useChannelWatermark` to skip self-authored messages when- // advancing the read pointer. Optional to keep optimistic rows valid- // before the server response reconciles.- authorId?: string- authorName?: string+export const MessageEmbedSchema = z.object({+ title: z.string(),+ provider: optionalString, url: optionalString, desc: optionalString, color: optionalString,+ image: optionalObject({ url: z.string(), width: optionalNumber, height: optionalNumber }),+ thumbnail: optionalObject({ url: z.string() }),+ fields: z.array(z.object({ name: z.string(), value: z.string(), inline: z.boolean().optional().catch(undefined) }).optional().catch(undefined))+ .transform((rows) => { const valid = rows.filter((row) => row !== undefined); return valid.length ? valid : undefined }).optional().catch(undefined),+ footer: optionalObject({ text: z.string(), iconUrl: optionalString }),+ author: optionalObject({ name: z.string(), url: optionalString, iconUrl: optionalString }),+})++type Embed = z.infer<typeof MessageEmbedSchema>++export type Reaction = NonNullable<CommunityMessageResource["reactions"]>[number]+export type ReplyTarget = Pick<NonNullable<CommunityMessageResource["replyTo"]>, "id" | "authorName" | "text">++export type Msg = Pick<CommunityMessageResource, "id" | "type"> & Partial<Omit<CommunityMessageResource,+ "id" | "type" | "channelId" | "replyToId" | "clientNonce" | "attachments" | "embeds"+>> & {color?: string- seq?: number // Per-scope (channel/DM) monotonic sequence number- createdAt?: string // ISO 8601 timestamp — the UI formats for display- authorAvatar?: string- authorAvatarVersion?: numberfailed?: boolean- // Idempotency nonce (mutation-idempotency plan). Stamped on optimistic rows- // this client created and echoed back on the WS message-create, so a- // 500-after-commit send that the user never retried self-heals: the WS row- // reconciles the failed optimistic row by nonce instead of appearing twice.clientNonce?: string- content?: string- embeds?: Embed[]attachments?: Attachment[]- reactions?: Reaction[]- replyTo?: {- id: string- authorId?: string- authorName: string- text: string- deleted?: boolean- }- thread?: {- id: string- name: string- messageCount: number- lastReplyAt?: string- tags?: string[]- preview?: string- participants?: { id: string; name: string; avatar: string; avatarVersion: number }[]- participantCount?: number- }- // Present only on a friend-approval DM card. Its presence (not the message- // `type`) is the discriminator for rendering <BotApprovalCard>.- approval?: FriendApprovalPayload+ embeds?: Embed[]+}++export type MessageInput = Pick<Msg, "id"> & Partial<Msg> & Partial<Pick<CommunityMessageResource, "replyToId">>++export function applyMessageReaction(source: Msg["reactions"], emoji: string, userId: string, add: boolean, viewerId: string | null): Reaction[] {+ const rows = (source ?? []).map((row) => ({ ...row, userIds: [...row.userIds] }))+ const row = rows.find((candidate) => candidate.emoji === emoji)+ if (add) {+ if (row && !row.userIds.includes(userId)) row.userIds.push(userId)+ else if (!row) rows.push({ emoji, count: 1, me: userId === viewerId, userIds: [userId] })+ } else if (row) row.userIds = row.userIds.filter((id) => id !== userId)+ return rows.filter((row) => row.userIds.length).map((row) => ({ ...row, count: row.userIds.length, me: viewerId !== null && row.userIds.includes(viewerId) }))+}++export function messageProfileIds(message: Pick<Msg, "authorId" | "replyTo" | "thread" | "approval">): string[] {+ return [+ ...(message.authorId ? [message.authorId] : []),+ ...(message.replyTo?.authorId ? [message.replyTo.authorId] : []),+ ...(message.thread?.participants ?? []).map((participant) => participant.id),+ ...[message.approval?.otherProfile, message.approval?.botProfile, message.approval?.waitingOnProfile]+ .flatMap((profile) => profile?.id ? [profile.id] : []),+ ]}// `grouped` is a RENDER-TIME decision (computed by `message-list.tsx`'s@@ -105,36 +82,23 @@ export type RenderMsg = Msg & { grouped: boolean }// Child-thread summaries shown in side panels and forum lists. Actual// message content for a thread or post is loaded into `ctx.messages` once the// user navigates into the child channel — these summaries don't carry messages.-export type Thread = {- id: string // nanoid- name: string- messageCount: number- lastMessageAt: string- parent: { authorId?: string; authorName: string; text: string }- // The root message's per-channel seq, when the thread was created from a- // parent message (omitted only for legacy rootless threads).- // Used by `channel-ref-pill.tsx` to match a `/server/channel/#N` ref.- parentSeq?: number- // Stable opener identity used to reconcile forum-title edits without- // accidentally patching a same-named or re-rooted child.- openerMessageId?: string+export type Thread = Pick<CommunityChannelResource, "id" | "messageCount"> & {+ name: NonNullable<CommunityChannelResource["name"]>+ lastMessageAt: NonNullable<CommunityChannelResource["lastMessageAt"]>+ parent: Omit<NonNullable<CommunityMessageResource["replyTo"]>, "id" | "deleted">+ parentSeq?: CommunityMessageResource["seq"]+ openerMessageId?: CommunityMessageResource["id"]}-export type ForumThread = Thread & {- authorId: string- authorAvatar: string- authorAvatarVersion: number- openerMessageId: string- openerCreatedAt?: string- tags: string[]- preview: string- // The post's participant (notify) set — creator first, then whoever- // spoke/was mentioned/was added. Drives the card's AvatarGroup. Always- // present (empty for a post with no participant rows yet, e.g. one created- // before the notify-scope change shipped).- participants: { id: string; name: string; avatar: string; avatarVersion: number }[]- // Total participant rows before the card-preview cap is applied.- participantCount: number+export type ForumThread = Thread & Required<Pick<CommunityMessageResource,+ "authorId" | "authorAvatar" | "authorAvatarVersion"+>> & {+ openerMessageId: CommunityMessageResource["id"]+ openerCreatedAt?: CommunityMessageResource["createdAt"]+ tags: NonNullable<NonNullable<CommunityMessageResource["thread"]>["tags"]>+ preview: NonNullable<NonNullable<CommunityMessageResource["thread"]>["preview"]>+ participants: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participants"]>+ participantCount: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participantCount"]>}export type SendAttachment = {@@ -145,20 +109,13 @@ export type SendAttachment = {height?: number}-export type MessagesPage = {+export type MessagesPage = Partial<{ [Field in keyof CommunityMessagesRead["page"]]: NonNullable<CommunityMessagesRead["page"][Field]> }> & {messages: Msg[]- latestSeq?: number- // Anchor / since mode- hasMoreOlder?: boolean- hasMoreNewer?: boolean- olderCursor?: string- newerCursor?: string- // Legacy (newest + older continuation) mode- hasMore?: boolean- cursor?: string+ hasMore?: CommunityMessagesRead["page"]["hasMoreOlder"]+ cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>}-export type MessagesWindowPage = Omit<MessagesPage, "messages"> & { messages: Array<{ id: string; seq?: number }>; newestCursor?: string }+export type MessagesWindowPage = Omit<MessagesPage, "messages"> & { messages: Array<Pick<CommunityMessageResource, "id"> & Partial<Pick<CommunityMessageResource, "seq">>>; newestCursor?: string }export function messageWindowPage(page: MessagesPage): MessagesWindowPage {const newest = [...page.messages].filter((message) => message.createdAt).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id.localeCompare(b.id)).at(-1)diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.tsindex a8c808125..94adbecae 100644--- a/src/web/src/lib/community/models/people.ts+++ b/src/web/src/lib/community/models/people.ts@@ -1,11 +1,8 @@+import type { CommunityResourceProfile, CommunityMemberRelation, CommunityChannelIdentity } from "@alook/shared"+export type Presence = "online" | "offline"-export type CommunityProfile = {- id: string- name?: string- discriminator?: string- avatar?: string- avatarVersion?: number+export type CommunityProfile = Pick<CommunityResourceProfile, "id"> & Partial<CommunityUserCore> & {aboutMe?: stringbannerColor?: string | nullkind?: "human" | "bot"@@ -13,101 +10,64 @@ export type CommunityProfile = {ownerHandle?: string | nullmutualServers?: numberownedByViewer?: boolean- statusEmoji?: string | null- statusText?: string | null+ statusEmoji?: CommunityResourceProfile["statusEmoji"]+ statusText?: CommunityResourceProfile["statusText"] | nullpresence?: Presence}-export type CommunityProfilePatch = {- id: string+export type CommunityProfilePatch = Pick<CommunityProfile, "id"> & {identityAbout?: Partial<Pick<CommunityProfile,"name" | "discriminator" | "aboutMe" | "bannerColor" | "kind" | "ownerUserId">>- avatar?: { avatar: string; avatarVersion: number }+ avatar?: Pick<CommunityUserCore, "avatar" | "avatarVersion">status?: Pick<CommunityProfile, "statusEmoji" | "statusText">card?: Pick<CommunityProfile, "ownerHandle" | "mutualServers" | "ownedByViewer">presence?: Presence}-// ── Members / friends / DMs ──────────────────────────────────────────────────-// Identity fields shared by every community user view-model (member / friend /-// DM). All three are required `string`: `user.name`/`user.discriminator` are-// NOT NULL columns always projected on live payloads. Requiring `discriminator`-// here (in one place) moves the "a mention target always has a tag" guarantee-// to compile time. `userId` is-// NOT part of the core: it's required on Member/DM but optional on Friend, so-// each type declares it. Only types whose identity fields are identically-// shaped extend this — AddableMember/ThreadParticipant (nullable projections),-// Profile/UserProfile (renamed/merged shapes) intentionally stay standalone.export type CommunityUserCore = {- name: string- discriminator: string- avatar: string- avatarVersion: number+ [Field in "name" | "discriminator" | "avatar" | "avatarVersion"]: NonNullable<CommunityResourceProfile[Field]>}-export type Member = CommunityUserCore & {+export type Member = CommunityUserCore & Pick<CommunityProfile, "statusEmoji" | "statusText"> & Pick<CommunityMemberRelation, "userId"> & Partial<Pick<CommunityMemberRelation, "isCreator">> & {id: string- userId: stringstatus: Presencesub: stringrole: import("@alook/shared").CommunityRole- // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.- statusEmoji?: string | null- statusText?: string | null- // Populated only when the drawer shows a private channel/post roster or a- // thread participant set — drives the row's Leave/Remove right-click menu.- // - isCreator: this user owns the unit (row locked — never removable/leaveable).- // - source: for a channel/post, only "explicit" rows are removable (an- // admin-by-role or inherited public member isn't an explicit roster row).- // Thread participants are always "explicit"-equivalent (a real row).- isCreator?: booleansource?: "explicit" | "inherited" | "admin" | import("@alook/shared").ParticipantSource}-export type Friend = CommunityUserCore & {+export type Friend = CommunityUserCore & Pick<CommunityProfile, "statusEmoji" | "statusText"> & Partial<Pick<CommunityMemberRelation, "userId">> & {id: string- // Optional here (unlike Member/DM) — some friend rows predate a resolved- // userId; that's the one field that keeps Friend from a plain intersection.- userId?: stringstatus: Presencesub: string- // Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.- statusEmoji?: string | null- statusText?: string | null}-export type PendingRequest = {+export type PendingRequest = Pick<CommunityUserCore, "name" | "avatar" | "avatarVersion"> & {id: string- userId: string- name: string- avatar: string- avatarVersion: number+ userId: CommunityProfile["id"]kind: "incoming" | "outgoing"// The gating owner id while a bot-touched row is pending; null once// unlocked. Drives whether Approve/Reject buttons render.needsOwnerApproval?: string | null}-export type BlockedUser = {+export type BlockedUser = Pick<CommunityUserCore, "name" | "avatar" | "avatarVersion"> & {id: string- userId?: string- name: string- avatar: string- avatarVersion: number+ userId?: CommunityProfile["id"]}// DM summary shown in the DM sidebar. Actual conversation history is loaded// into `ctx.messages` once the user opens the DM — DM summaries don't carry// inline messages.export type DM = CommunityUserCore & {- id: string // DM conversation nanoid — NOT the peer's user id (that's `userId`)- userId: string+ id: CommunityChannelIdentity["id"] // DM conversation nanoid — NOT the peer's user id (that's `userId`)+ userId: CommunityProfile["id"]status: Presencepreview: string/** Server-authoritative `lastMessageAt ?? createdAt`, used only for list order. */- activityAt?: string+ activityAt?: NonNullable<CommunityChannelIdentity["lastMessageAt"]>unread?: booleanlastUnreadSeq?: number}diff --git a/src/web/src/lib/community/participant-resources.ts b/src/web/src/lib/community/participant-resources.tsnew file mode 100644index 000000000..a618f660d--- /dev/null+++ b/src/web/src/lib/community/participant-resources.ts@@ -0,0 +1,26 @@+import type { CommunityMemberRelation, CommunityResourceProfile, CommunityThreadsRead } from "@alook/shared"++export function resourceProfile(+ fields: Pick<CommunityResourceProfile, "id" | "name" | "avatar" | "avatarVersion"> & Partial<CommunityResourceProfile>,+): CommunityResourceProfile {+ return { discriminator: null, statusEmoji: null, statusText: "", ...fields }+}++type Participant = Pick<CommunityMemberRelation, "channelId" | "userId" | "isCreator"> & {+ profile: CommunityResourceProfile+ participantCount?: number+}++export function threadParticipantResources(rows: readonly Participant[]): Pick<CommunityThreadsRead["included"], "members" | "profiles" | "participantCounts"> {+ const profiles = new Map<string, CommunityResourceProfile>()+ const counts = new Map<string, number>()+ const authoritativeCounts = new Map<string, number>()+ const members = rows.map((row): CommunityMemberRelation => {+ profiles.set(row.userId, row.profile)+ counts.set(row.channelId, (counts.get(row.channelId) ?? 0) + 1)+ if (row.participantCount !== undefined) authoritativeCounts.set(row.channelId, row.participantCount)+ else authoritativeCounts.delete(row.channelId)+ return { channelId: row.channelId, userId: row.userId, isCreator: row.isCreator, relation: "notify", source: "explicit", role: null, memberId: null }+ })+ return { members, profiles: [...profiles.values()], participantCounts: [...counts].map(([channelId, count]) => ({ channelId, count: authoritativeCounts.get(channelId) ?? count })) }+}diff --git a/src/web/src/lib/community/producer-contract.test.ts b/src/web/src/lib/community/producer-contract.test.tsnew file mode 100644index 000000000..4d3efd8c1--- /dev/null+++ b/src/web/src/lib/community/producer-contract.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest"+import { serializeMessageDeliveryBatch, type CommunityChannelMembershipChange, type MessageDeliveryBatch } from "@alook/shared"+import { projectCommunityProducerDelivery, projectCommunityProducerEvent } from "./producer-contract"++const event: CommunityChannelMembershipChange = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "peer", relation: "notify", present: true }+const batch: MessageDeliveryBatch = { messageId: "message", messageEvent: { type: "community:message.create", channelId: "thread", serverId: "server", message: { id: "message", seq: 1, authorId: "author", authorName: "Author", authorAvatarVersion: 0, type: "chat", content: "hello", createdAt: "2026-10-07T12:00:00Z" } }, contentUserIds: ["author", "peer"], unreadPlainUserIds: [], unreadMentionUserIds: [], mentionUserIds: [], joinedParticipantUserIds: ["peer"], rosterRefreshUserId: "peer" }++describe("staged community event production", () => {+ it("defaults to the exact old control shape until v2 production is enabled", () => {+ expect(projectCommunityProducerEvent(event, {})).toEqual({ type: "community:channel.member_add", channelId: "thread", serverId: "server", userId: "peer" })+ expect(projectCommunityProducerEvent(event, { COMMUNITY_EVENT_CONTRACT: "2" })).toBe(event)+ expect(() => projectCommunityProducerEvent({ ...event, serverId: null }, {})).toThrow("requires producer contract v2")+ })+ it("selects the old committed-delivery shape without mutating its source", () => {+ const legacy = projectCommunityProducerDelivery(batch, {})+ expect(legacy).not.toHaveProperty("joinedParticipantUserIds")+ expect(legacy).not.toHaveProperty("rosterRefreshUserId")+ expect(legacy.memberAdded).toEqual({ channelId: "thread", serverId: "server", userId: "peer" })+ expect(() => serializeMessageDeliveryBatch(legacy)).not.toThrow()+ expect(projectCommunityProducerDelivery(batch, { COMMUNITY_EVENT_CONTRACT: "2" })).toBe(batch)+ expect(batch.joinedParticipantUserIds).toEqual(["peer"])+ })+})diff --git a/src/web/src/lib/community/producer-contract.ts b/src/web/src/lib/community/producer-contract.tsnew file mode 100644index 000000000..2f2bcc3ee--- /dev/null+++ b/src/web/src/lib/community/producer-contract.ts@@ -0,0 +1,16 @@+import { projectCommunityEventForContract, type CommunityWsEvent, type MessageDeliveryBatch } from "@alook/shared"++type ProducerEnvironment = { COMMUNITY_EVENT_CONTRACT?: string }++export function projectCommunityProducerEvent(event: CommunityWsEvent, env: ProducerEnvironment) {+ const selected = projectCommunityEventForContract(event, env.COMMUNITY_EVENT_CONTRACT === "2" ? 2 : 1)+ if (!selected) throw new Error("Community event requires producer contract v2")+ return selected+}++export function projectCommunityProducerDelivery(batch: MessageDeliveryBatch, env: ProducerEnvironment): MessageDeliveryBatch {+ if (env.COMMUNITY_EVENT_CONTRACT === "2" || !batch.joinedParticipantUserIds) return batch+ const { joinedParticipantUserIds: _joined, rosterRefreshUserId, ...legacy } = batch+ if (!rosterRefreshUserId || !batch.messageEvent.serverId) throw new Error("Missing committed participant scope")+ return { ...legacy, memberAdded: { userId: rosterRefreshUserId, channelId: batch.messageEvent.channelId, serverId: batch.messageEvent.serverId } }+}diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.tsindex 8dc4b7e56..33e7184ff 100644--- a/src/web/src/lib/community/profile-seed.ts+++ b/src/web/src/lib/community/profile-seed.ts@@ -1,7 +1,7 @@-import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"+import { loadCommunityRequest } from "@/lib/community/account-cache-lifecycle"import { createStore } from "@tanstack/react-store"import type {- CommunityProfilePatch,+ CommunityProfile, CommunityProfilePatch,CommunityUserCore,} from "@/lib/community/models/people"import type { Msg } from "@/lib/community/models/message"@@ -15,7 +15,7 @@ import {import { profileSchema, type ProfileRow } from "@/lib/community-db/schema"import { writeCommunityCollectionRows } from "@/lib/community-db/write"import { currentSource, withSource } from "@/lib/observability/data-source"-import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"type ProfileFieldRevisions = {identityAbout: number@@ -52,10 +52,7 @@ export function beginCommunityProfileSeed(return { registry, revision: registry ? revisionState(registry).get().revision : 0 }}-type CommunityUserProfileSeed = CommunityUserCore & {- statusEmoji?: string | null- statusText?: string | null-}+type CommunityUserProfileSeed = CommunityUserCore & Pick<CommunityProfile, "statusEmoji" | "statusText">export function communityUserProfilePatch(userId: string,@@ -77,7 +74,7 @@ export function communityUserProfilePatch(}}-export function messageProfilePatches(messages: readonly Msg[]): CommunityProfilePatch[] {+export function messageProfilePatches(messages: readonly Partial<Pick<Msg, "authorId" | "authorName" | "authorAvatar" | "authorAvatarVersion" | "replyTo" | "thread" | "approval">>[]): CommunityProfilePatch[] {const patches: CommunityProfilePatch[] = []for (const message of messages) {if (message.authorId) {@@ -221,25 +218,15 @@ export async function loadAndSeedProfiles<T>(patches: (data: T) => readonly CommunityProfilePatch[],registry: CommunityDbRegistry | null,signal?: AbortSignal,+ requestToken?: ReturnType<typeof captureCommunityLiveSnapshotToken>,): Promise<T> {if (!registry) throw new DOMException("Missing community profile owner", "AbortError")- const token = captureCommunityLiveSnapshotToken(registry.queryClient)- const assertActive = () => assertCommunityLiveSnapshotTokenCurrent(registry.queryClient, token, signal)+ const token = requestToken ?? captureCommunityLiveSnapshotToken(registry.queryClient)const overlay = registry.runtime.ws.actionsconst overlaySnapshot = overlay.beginPresenceSnapshot()- const profileSnapshot = beginCommunityProfileSeed(registry)- await registry.ready- assertActive()- await registry.collections.profiles.preload()- assertActive()- let data: T- try {- data = await load(communityRequestOptions(registry.queryClient, token, signal, assertActive))- assertActive()- } catch (error) {- assertActive()- throw error- }+ const profileSnapshot = token.profileSnapshot+ if (token.registry !== registry) throw new DOMException("Mismatched community profile owner", "AbortError")+ const data = await loadCommunityRequest(load, token, signal)const projected = patches(data)writeCommunityProfilePatches(projected, profileSnapshot.registry, {snapshot: profileSnapshot,@@ -263,6 +250,7 @@ export function apiFetchProfiles<T>(patches: (data: T) => readonly CommunityProfilePatch[],options: ApiRequestOptions | undefined,registry: CommunityDbRegistry | null,+ requestToken?: ReturnType<typeof captureCommunityLiveSnapshotToken>,): Promise<T> {return loadAndSeedProfiles((origin) => apiFetch<T>(path, {@@ -274,5 +262,6 @@ export function apiFetchProfiles<T>(patches,registry,options?.signal ?? undefined,+ requestToken,)}diff --git a/src/web/src/lib/community/read-contract.test.ts b/src/web/src/lib/community/read-contract.test.tsnew file mode 100644index 000000000..f3ef20e9c--- /dev/null+++ b/src/web/src/lib/community/read-contract.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest"+import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"+import { writeCommunityChannelRead, writeCommunityMessagesRead, writeCommunityReadState } from "./read-contract"+import { decodeCommunityReadResponse } from "./read-response"+import { parseCommunityMessageWindow } from "./messages"+import { communityKeys } from "@/lib/query-keys"++const request = (version?: string) => new Request("https://alook.test/api/community/channels/channel", { headers: version ? { [COMMUNITY_CONTRACT_HEADER]: version } : {} })+const channel = { id: "channel", type: "dm", serverId: null, name: null, archived: 0, createdAt: "2026-10-07T12:00:00Z" }++describe("common reading negotiation", () => {+ it("keeps legacy metadata and confirms the complete v2 read", async () => {+ const access = { canRead: true, canSend: false, canCreateDiscussion: false }+ const old = writeCommunityChannelRead(request(), "channel", channel, access)+ expect(await old.json()).toEqual(channel)+ const current = writeCommunityChannelRead(request("2"), "channel", channel, access)+ expect(current.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")+ const body = await current.json()+ const decoded = decodeCommunityReadResponse("/api/community/channels/channel", "GET", current, body)+ expect(decoded).toMatchObject({ id: "channel", accessDecision: { canRead: true, canSend: false } })+ expect(decoded).not.toHaveProperty("readContractVersion")+ expect(() => decodeCommunityReadResponse("/api/community/channels/other", "GET", current, body)).toThrow("scope mismatch")+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel", "GET", new Response(), body)).toThrow("confirmation mismatch")+ expect(decodeCommunityReadResponse("/api/community/channels/channel", "GET", new Response(), { ...channel, readContractVersion: 2, accessDecision: access })).not.toHaveProperty("readContractVersion")+ })+ it.each(["channel", "forum", "thread", "dm"] as const)("uses the same message and read-state resource for %s", async (surfaceKind) => {+ const message = { id: "m1", seq: 1, authorId: "user", createdAt: "2026-10-07T12:00:00Z", content: "hello", type: "chat" }+ const response = writeCommunityMessagesRead(request("2"), "channel", { messages: [message], latestSeq: 1, hasMore: true, cursor: "cursor", surfaceReceipt: { channelId: "channel", surfaceKind } })+ const body = await response.json()+ expect(body.messages[0]).toMatchObject({ channelId: "channel", clientNonce: null, replyToId: null, attachments: [] })+ expect(decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body)).toMatchObject({ olderCursor: "cursor", hasMoreOlder: true, surfaceReceipt: { surfaceKind } })+ const state = writeCommunityReadState(request("2"), "channel", { lastReadAt: null, lastReadMessageId: null, lastReadSeq: 0 })+ expect(decodeCommunityReadResponse("/api/community/channels/channel/read-state", "GET", state, await state.json())).toEqual({ channelId: "channel", lastReadAt: null, lastReadMessageId: null, lastReadSeq: 0 })+ })+ it("gives DM and channel transports a single target identity", () => {+ expect(communityKeys.dmMessages("channel")).toEqual(communityKeys.channelMessages("channel"))+ expect(communityKeys.dmReadStateSnapshot("channel")).toEqual(communityKeys.channelReadStateSnapshot("channel"))+ expect(communityKeys.channelMeta(null, "channel")).toEqual(communityKeys.channelMeta("server", "channel"))+ expect(communityKeys.channelMembers("channel", "access")).not.toEqual(communityKeys.channelMembers("channel", "notify"))+ })+ it("normalizes legacy message bytes with the same core resource validator", () => {+ const message = { id: "message", authorId: "author", seq: 1, createdAt: "2026-10-07T12:00:00Z", type: "chat", content: "hello" }+ const decoded = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", new Response(), { messages: [message], latestSeq: 1 })+ expect(decoded).toMatchObject({ latestSeq: 1, messages: [{ ...message, channelId: "channel", replyToId: null, attachments: [] }] })+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", new Response(), { messages: [{ ...message, seq: undefined }] })).toThrow()+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", new Response(), { messages: [{ ...message, channelId: "foreign" }] })).toThrow("scope mismatch")+ })+ it("validates window exclusivity, cursors and limits", () => {+ expect(parseCommunityMessageWindow(new URLSearchParams("window=after&cursor=2026-10-07T12%3A00%3A00Z%7Cm1&limit=10"))).toMatchObject({ since: { id: "m1" }, pageSize: 10 })+ for (const input of ["window=before", "window=around&cursor=x&anchorMessageId=m1", "cursor=x", "cursor=a%7Cb%7Cc", "limit=1.5", "window=tail&since=x", "anchor=m1&cursor=x"]) expect(() => parseCommunityMessageWindow(new URLSearchParams(input))).toThrow()+ })+})diff --git a/src/web/src/lib/community/read-contract.ts b/src/web/src/lib/community/read-contract.tsnew file mode 100644index 000000000..dffa32236--- /dev/null+++ b/src/web/src/lib/community/read-contract.ts@@ -0,0 +1,43 @@+import { NextResponse } from "next/server"+import {+ COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestsCommunityContract,+ CommunityChannelReadSchema, CommunityMessagesReadSchema, CommunityReadStateReadSchema,+ normalizeCommunityChannelResource, normalizeCommunityMessageResource,+ type CommunityAccessDecision, type CommunityReadStateResource, type CommunityMessageSurfaceReceipt, type CommunityMessagesRead,+} from "@alook/shared"+import { writeJSON } from "@/lib/middleware/helpers"++function versionedJSON(data: unknown): NextResponse {+ return NextResponse.json(data, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION) } })+}++export function writeCommunityChannelRead(request: Request, channelId: string, channel: unknown,+ access: Omit<CommunityAccessDecision, "channelId">) {+ if (!requestsCommunityContract(request.headers)) return writeJSON(channel)+ return versionedJSON(CommunityChannelReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId,+ channel: normalizeCommunityChannelResource(channel), access: { channelId, ...access } }))+}++type MessagePage = Pick<CommunityMessagesRead["page"], "latestSeq"> & Partial<{ [Field in Exclude<keyof CommunityMessagesRead["page"], "latestSeq">]: NonNullable<CommunityMessagesRead["page"][Field]> }> & {+ messages: unknown[]+ cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>+ hasMore?: CommunityMessagesRead["page"]["hasMoreOlder"]+ surfaceReceipt: CommunityMessageSurfaceReceipt+}++export function writeCommunityMessagesRead(request: Request, channelId: string, page: MessagePage) {+ if (!requestsCommunityContract(request.headers)) return writeJSON(page)+ return versionedJSON(CommunityMessagesReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId,+ messages: page.messages.map((message) => normalizeCommunityMessageResource(message, channelId)),+ page: { olderCursor: page.olderCursor ?? page.cursor ?? null, newerCursor: page.newerCursor ?? null,+ hasMoreOlder: page.hasMoreOlder ?? page.hasMore ?? false, hasMoreNewer: page.hasMoreNewer ?? false,+ latestSeq: page.latestSeq }, surfaceReceipt: page.surfaceReceipt }))+}++export function writeCommunityReadState(request: Request, channelId: string,+ state: Omit<CommunityReadStateResource, "channelId">) {+ if (!requestsCommunityContract(request.headers)) return writeJSON(state)+ return versionedJSON(CommunityReadStateReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId, readState: { channelId, ...state } }))+}++export { versionedJSON as writeCommunityContractJSON }diff --git a/src/web/src/lib/community/read-response.test.ts b/src/web/src/lib/community/read-response.test.tsnew file mode 100644index 000000000..bdaad15a6--- /dev/null+++ b/src/web/src/lib/community/read-response.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest"+import { COMMUNITY_CONTRACT_HEADER, normalizeCommunityChannelResource, normalizeCommunityMessageResource } from "@alook/shared"+import { communityReadTarget, decodeCommunityReadResponse } from "./read-response"++const parent = normalizeCommunityChannelResource({ id: "forum", type: "forum", serverId: "server", name: "Forum", archived: 0, createdAt: "2026-10-07T12:00:00Z" })+const child = normalizeCommunityChannelResource({ ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer", lastMessageAt: "2026-10-07T13:00:00Z" })+const profile = { id: "viewer", name: "Viewer", discriminator: null, avatar: null, avatarVersion: 0, statusEmoji: null, statusText: "" }+const member = { channelId: "thread", userId: "viewer", relation: "notify" as const, source: "spoke", isCreator: true, role: null, memberId: null }+const message = (id: string, channelId: string) => normalizeCommunityMessageResource({ id, channelId, seq: 1, authorId: "viewer", authorAvatar: "avatar", createdAt: "2026-10-07T12:00:00Z", type: "chat", content: id }, channelId)+const confirmed = () => new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: "2" } })+const threads = () => ({ contractVersion: 2, channelId: "forum", channel: { ...parent }, threads: [{ ...child }],+ included: { messages: [message("opener", "forum"), message("reply", "thread")], members: [{ ...member }], profiles: [{ ...profile }], tags: [{ messageId: "opener", tag: "bug" }], participantCounts: [{ channelId: "thread", count: 7 }] },+ page: { hasMore: true, nextCursor: "next" as string | null } })+const decodeThreads = (body: unknown) => decodeCommunityReadResponse("/api/community/channels/forum/threads", "GET", confirmed(), body)+const members = () => ({ contractVersion: 2, channelId: "thread", relation: "notify" as const, members: [{ ...member }], profiles: [{ ...profile }] })+const decodeMembers = (body: unknown, path = "/api/community/channels/thread/members?relation=notify") => decodeCommunityReadResponse(path, "GET", confirmed(), body)++describe("common read response publication", () => {+ it("recognizes only complete read routes and decodes their encoded channel identity", () => {+ expect(communityReadTarget("/api/community/channels/a%2Fb/read?lastReadSeq=4", "put")).toEqual({ channelId: "a/b", resource: "read" })+ expect(communityReadTarget("/api/community/channels/thread/members?relation=notify")).toEqual({ channelId: "thread", resource: "members" })+ for (const [path, method] of [["/api/community/channels/thread/read", "GET"], ["/api/community/channels/thread/messages/extra", "GET"], ["/api/community/channels/thread", "PUT"], ["/api/community/channels/thread/messages", "POST"]]) {+ expect(communityReadTarget(path!, method)).toBeNull()+ const body = { contractVersion: 2, private: "unrelated endpoint" }+ expect(decodeCommunityReadResponse(path!, method, confirmed(), body)).toBe(body)+ }+ })++ it("keeps metadata authority in the admitted decision and strips legacy forged authority", () => {+ const channel = threads().channel+ const access = { channelId: channel.id, canRead: false, canSend: false, canCreateDiscussion: false }+ const path = `/api/community/channels/${channel.id}`+ const current = decodeCommunityReadResponse(path, "GET", confirmed(), { contractVersion: 2, channelId: channel.id, channel, access })+ expect(current).toEqual({ ...channel, accessDecision: access })+ expect(current).not.toHaveProperty("readContractVersion")+ expect(decodeCommunityReadResponse(path, "GET", new Response(), { ...channel, readContractVersion: 2, accessDecision: access })).toEqual(channel)+ })++ it("publishes only a confirmed scoped read-waterline advancement", () => {+ const body = { contractVersion: 2, channelId: "thread", changed: false, targetSeq: 8, revision: 12 }+ expect(decodeCommunityReadResponse("/api/community/channels/thread/read", "PUT", confirmed(), body)).toEqual({ changed: false, targetSeq: 8, revision: 12 })+ expect(() => decodeCommunityReadResponse("/api/community/channels/other/read", "PUT", confirmed(), body)).toThrow("scope mismatch")+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/read", "PUT", confirmed(), { ...body, targetSeq: -1 })).toThrow()+ })++ it("retains parent/child resources, included profiles and exact pagination without legacy reconstruction", () => {+ const body = threads()+ expect(decodeThreads(body)).toEqual(body)+ body.threads[0]!.lastMessageAt = null+ body.included.participantCounts = []+ body.page.nextCursor = null+ delete body.included.messages[0]!.authorAvatar+ expect(decodeThreads(body)).toEqual(body)+ })++ it.each([+ ["envelope", (body: ReturnType<typeof threads>) => { body.channelId = "other" }],+ ["parent", (body: ReturnType<typeof threads>) => { body.channel.id = "other" }],+ ["child parent", (body: ReturnType<typeof threads>) => { body.threads[0]!.parentChannelId = "other" }],+ ["child server", (body: ReturnType<typeof threads>) => { body.threads[0]!.serverId = "other" }],+ ["message", (body: ReturnType<typeof threads>) => { body.included.messages[0]!.channelId = "other" }],+ ["count", (body: ReturnType<typeof threads>) => { body.included.participantCounts[0]!.channelId = "other" }],+ ["tag", (body: ReturnType<typeof threads>) => { body.included.tags[0]!.messageId = "other" }],+ ["member", (body: ReturnType<typeof threads>) => { body.included.members[0]!.channelId = "other" }],+ ] as const)("rejects an included %s from another resource scope", (_label, mutate) => {+ const body = threads()+ mutate(body)+ expect(() => decodeThreads(body)).toThrow("scope mismatch")+ })++ it("rejects access members and absent profiles in the thread notify projection", () => {+ const body = threads()+ expect(() => decodeThreads({ ...body, included: { ...body.included, members: [{ ...member, relation: "access" }] } })).toThrow("member scope mismatch")+ body.included.profiles = []+ expect(() => decodeThreads(body)).toThrow("profile missing")+ })++ it("retains relation facts and profile resources separately without a UI roster DTO", () => {+ const body = members()+ expect(decodeMembers(body)).toEqual(body)+ const changed = { ...body, members: [{ ...member, memberId: "server-member", role: "admin" }], profiles: [{ ...profile, discriminator: "1234", avatar: "image" }] }+ expect(decodeMembers(changed)).toEqual(changed)+ })++ it("rejects mismatched roster scopes, relations and unhydrated members", () => {+ const body = members()+ expect(() => decodeMembers(body, "/api/community/channels/thread/members?relation=access")).toThrow("relation mismatch")+ expect(() => decodeMembers(body, "/api/community/channels/thread/members")).toThrow("relation mismatch")+ expect(() => decodeMembers({ ...body, channelId: "other" })).toThrow("scope mismatch")+ expect(() => decodeMembers({ ...body, members: [{ ...member, channelId: "other" }] })).toThrow("scope mismatch")+ expect(() => decodeMembers({ ...body, members: [{ ...member, relation: "access" }] })).toThrow("resource relation mismatch")+ expect(() => decodeMembers({ ...body, profiles: [] })).toThrow("profile missing")+ })++ it("keeps legacy nonmessage resources but rejects unconfirmed version claims", () => {+ const legacy = { relation: "notify", members: [] }+ expect(decodeCommunityReadResponse("/api/community/channels/thread/members", "GET", new Response(), legacy)).toBe(legacy)+ expect(() => decodeMembers({ ...members(), contractVersion: 1 })).toThrow("confirmation mismatch")+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "GET", new Response(), {})).toThrow("resource missing")+ })+})diff --git a/src/web/src/lib/community/read-response.ts b/src/web/src/lib/community/read-response.tsnew file mode 100644index 000000000..5bc57f717--- /dev/null+++ b/src/web/src/lib/community/read-response.ts@@ -0,0 +1,94 @@+import {+ COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, CommunityChannelReadSchema, CommunityMessagesReadSchema,+ CommunityReadStateReadSchema, CommunityMembersReadSchema, CommunityThreadsReadSchema, CommunityReadAdvanceSchema,+ normalizeCommunityMessageResource,+} from "@alook/shared"++export function communityReadTarget(path: string, method = "GET") {+ if (method.toUpperCase() === "PUT") {+ const matched = /^\/api\/community\/channels\/([^/?]+)\/read(?:\?|$)/.exec(path)+ return matched ? { channelId: decodeURIComponent(matched[1]), resource: "read" } : null+ }+ if (method.toUpperCase() !== "GET") return null+ const matched = /^\/api\/community\/channels\/([^/?]+)(?:\/(messages|read-state|members|threads))?(?:\?|$)/.exec(path)+ return matched ? { channelId: decodeURIComponent(matched[1]), resource: matched[2] ?? "metadata" } : null+}++export function decodeCommunityReadResponse(path: string, method: string | undefined, response: Response, value: unknown): unknown {+ const target = communityReadTarget(path, method)+ if (!target) return value+ const bodyVersion = typeof value === "object" && value !== null && "contractVersion" in value ? value.contractVersion : undefined+ const headerVersion = response.headers.get(COMMUNITY_CONTRACT_HEADER)+ if (headerVersion !== String(COMMUNITY_CONTRACT_VERSION) && bodyVersion !== COMMUNITY_CONTRACT_VERSION) {+ if (target.resource === "messages") {+ const legacy = value as { messages?: unknown[] }+ if (!Array.isArray(legacy.messages)) throw new Error("Community message resource missing")+ return { ...legacy, messages: legacy.messages.map((message) => {+ const normalized = normalizeCommunityMessageResource(message, target.channelId)+ return { ...normalized, clientNonce: normalized.clientNonce ?? undefined }+ }) }+ }+ if (target.resource === "metadata" && typeof value === "object" && value !== null) {+ const { readContractVersion: _version, accessDecision: _access, ...legacy } = value as Record<string, unknown>+ return legacy+ }+ return value+ }+ if (headerVersion !== String(COMMUNITY_CONTRACT_VERSION) || bodyVersion !== COMMUNITY_CONTRACT_VERSION) throw new Error("Community read protocol confirmation mismatch")+ const assertScope = (channelId: string) => {+ if (channelId !== target.channelId) throw new Error("Community read resource scope mismatch")+ }+ if (target.resource === "metadata") {+ const data = CommunityChannelReadSchema.parse(value)+ assertScope(data.channelId); assertScope(data.channel.id); assertScope(data.access.channelId)+ return { ...data.channel, accessDecision: data.access }+ }+ if (target.resource === "messages") {+ const data = CommunityMessagesReadSchema.parse(value)+ assertScope(data.channelId); assertScope(data.surfaceReceipt.channelId)+ for (const message of data.messages) assertScope(message.channelId)+ return { messages: data.messages.map((message) => ({ ...message, clientNonce: message.clientNonce ?? undefined })),+ olderCursor: data.page.olderCursor ?? undefined, newerCursor: data.page.newerCursor ?? undefined,+ hasMoreOlder: data.page.hasMoreOlder, hasMoreNewer: data.page.hasMoreNewer, latestSeq: data.page.latestSeq,+ surfaceReceipt: data.surfaceReceipt }+ }+ if (target.resource === "read-state") {+ const data = CommunityReadStateReadSchema.parse(value)+ assertScope(data.channelId); assertScope(data.readState.channelId)+ return data.readState+ }+ if (target.resource === "read") {+ const data = CommunityReadAdvanceSchema.parse(value)+ assertScope(data.channelId)+ return { changed: data.changed, targetSeq: data.targetSeq, revision: data.revision }+ }+ if (target.resource === "threads") {+ const data = CommunityThreadsReadSchema.parse(value)+ assertScope(data.channelId); assertScope(data.channel.id)+ const children = new Set(data.threads.map((thread) => thread.id))+ for (const thread of data.threads) if (thread.parentChannelId !== target.channelId || thread.serverId !== data.channel.serverId) throw new Error("Thread resource scope mismatch")+ for (const message of data.included.messages) if (message.channelId !== target.channelId && !children.has(message.channelId)) throw new Error("Included message scope mismatch")+ const profiles = new Set(data.included.profiles.map((profile) => profile.id))+ const openerIds = new Set(data.threads.flatMap((thread) => thread.parentMessageId ? [thread.parentMessageId] : []))+ if (data.included.tags.some((row) => !openerIds.has(row.messageId))) throw new Error("Included tag scope mismatch")+ if (data.included.participantCounts.some((row) => !children.has(row.channelId))) throw new Error("Participant count scope mismatch")+ for (const member of data.included.members) {+ if (!children.has(member.channelId) || member.relation !== "notify") throw new Error("Included member scope mismatch")+ if (!profiles.has(member.userId)) throw new Error("Included member profile missing")+ }+ return data+ }+ if (target.resource === "members") {+ const data = CommunityMembersReadSchema.parse(value)+ assertScope(data.channelId)+ const requested = new URL(path, "https://alook.invalid").searchParams.get("relation")+ if (requested !== data.relation) throw new Error("Community member relation mismatch")+ const profiles = new Set(data.profiles.map((profile) => profile.id))+ for (const member of data.members) {+ assertScope(member.channelId)+ if (member.relation !== data.relation) throw new Error("Community member resource relation mismatch")+ if (!profiles.has(member.userId)) throw new Error("Community member profile missing")+ }+ return data+ }+}diff --git a/src/web/src/lib/community/reading.routes.test.ts b/src/web/src/lib/community/reading.routes.test.tsnew file mode 100644index 000000000..bcd36a5e2--- /dev/null+++ b/src/web/src/lib/community/reading.routes.test.ts@@ -0,0 +1,109 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"++const mocks = vi.hoisted(() => ({ db: {}, access: vi.fn(), channel: vi.fn(), friends: vi.fn(), resolve: vi.fn(), participants: vi.fn(), users: vi.fn(), members: vi.fn(),+ children: vi.fn(), threads: vi.fn(), openers: vi.fn(), first: vi.fn(), tags: vi.fn(), threadParticipants: vi.fn(), attachments: vi.fn(), reactions: vi.fn(), replies: vi.fn() }))+vi.mock("@/lib/db", () => ({ getDb: () => mocks.db, getPrimaryDb: () => mocks.db }))+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: mocks.access, requireChannelAccess: mocks.access }))+vi.mock("@/lib/community/message-door", () => ({ resolveMessageTarget: mocks.resolve }))+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: (request: NextRequest, context: unknown) => Promise<Response>) =>+ async (request: NextRequest, context: { params?: Promise<Record<string, string>> }) => handler(request, { params: await context.params, env: { DB: mocks.db }, userId: "viewer" }) }))+vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (request: NextRequest, context: unknown) => Promise<Response>) =>+ async (request: NextRequest, context: { params?: Promise<Record<string, string>> }) => handler(request, { params: await context.params, env: { DB: mocks.db },+ actor: request.headers.has("Authorization") ? { kind: "bot", userId: "bot" } : { kind: "human", userId: "viewer" } }) }))+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: {+ communityChannel: { getChannelForMember: mocks.channel, listChildChannels: mocks.children }, communityFriendship: { areFriends: mocks.friends },+ communityThread: { listThreadParticipants: mocks.participants, listForumThreadsByCreatedAt: mocks.threads, listParticipantsForChannels: mocks.threadParticipants },+ communityMessage: { getMessagesByIdsInScope: mocks.openers, getFirstMessageResourcesByChannelIds: mocks.first, getMessagesByIdsInChannels: mocks.replies },+ communityMessageTag: { listTagsForMessages: mocks.tags }, communityAttachment: { listByMessageIds: mocks.attachments }, communityReaction: { listReactionsByMessageIds: mocks.reactions },+ user: { getUsersByIds: mocks.users }, communityMember: { getMembersByUserIds: mocks.members },+} }))+import { GET as metadata } from "@/app/api/community/channels/[id]/route"+import { GET as roster } from "@/app/api/community/channels/[id]/members/route"+import { GET as threadList } from "@/app/api/community/channels/[id]/threads/route"++const parent = { id: "forum", type: "forum", serverId: "server", name: "Forum", archived: 0, createdAt: "2026-10-07T12:00:00Z" }+const child = { ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer" }+const ctx = (id: string) => ({ params: Promise.resolve({ id }) })+const req = (path: string, bot = false) => new NextRequest(`https://alook.test/api/community/channels/${path}`, { headers: { [COMMUNITY_CONTRACT_HEADER]: "2", ...(bot ? { Authorization: "Bearer crk_unit_fixture" } : {}) } })+const row = (id: string, channelId: string) => ({ id, channelId, seq: 1, authorId: "viewer", authorName: "Viewer", authorImage: null, authorAvatarVersion: 0, content: id,+ type: "default", mentionType: null, replyToId: null, embeds: [], clientNonce: null, createdAt: "2026-10-07T12:00:00Z" })++beforeEach(() => {+ vi.resetAllMocks()+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "channel", channel: parent } })+ mocks.resolve.mockResolvedValue({ ok: true, value: { target: { channelId: "thread" } } })+ mocks.channel.mockResolvedValue(parent)+ for (const query of [mocks.participants, mocks.users, mocks.members, mocks.children, mocks.threads, mocks.openers, mocks.first, mocks.tags, mocks.threadParticipants, mocks.attachments, mocks.reactions, mocks.replies]) query.mockResolvedValue([])+})++describe("negotiated complete read route boundaries", () => {+ it.each([false, true])("keeps DM reading separate from friendship-dependent sending: friends=%s", async (friends) => {+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "dm", dm: { otherUserId: "peer" } } })+ mocks.channel.mockResolvedValue({ ...parent, id: "dm", type: "dm", serverId: null, name: null })+ mocks.friends.mockResolvedValue(friends)+ const response = await metadata(req("dm"), ctx("dm"))+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")+ expect(await response.json()).toMatchObject({ channelId: "dm", channel: { id: "dm", type: "dm" }, access: { channelId: "dm", canRead: true, canSend: friends, canCreateDiscussion: false } })+ expect(mocks.channel).toHaveBeenCalledWith(mocks.db, "dm", "viewer")+ expect(mocks.friends).toHaveBeenCalledWith(mocks.db, "viewer", "peer")+ })++ it("returns not-found for a vanished DM without checking friendship", async () => {+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "dm", dm: { otherUserId: "peer" } } })+ mocks.channel.mockResolvedValue(null)+ expect((await metadata(req("dm"), ctx("dm"))).status).toBe(404)+ expect(mocks.friends).not.toHaveBeenCalled()+ })++ it.each([false, true])("resolves a current human/bot roster through the complete reader: bot=%s", async (bot) => {+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "channel", channel: child } })+ mocks.participants.mockResolvedValue([{ userId: "viewer", source: "spoke" }])+ mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", image: null, avatarVersion: 0 }])+ const response = await roster(req(`thread/members?relation=notify${bot ? "&ref=%2Fserver%2Fthread" : ""}`, bot), ctx("thread"))+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")+ expect(await response.json()).toMatchObject({ channelId: "thread", relation: "notify", members: [{ userId: "viewer", source: "spoke" }] })+ expect(mocks.resolve).toHaveBeenCalledWith(mocks.db, bot ? "bot" : "viewer", bot ? { ref: "/server/thread" } : { id: "thread" }, bot ? "bot" : "human")+ })++ it("returns the scoped target rejection before reading any roster", async () => {+ mocks.resolve.mockResolvedValue({ ok: false, status: 404, error: "not found" })+ expect((await roster(req("thread/members?relation=notify"), ctx("thread"))).status).toBe(404)+ expect(mocks.access).not.toHaveBeenCalled()+ expect(mocks.participants).not.toHaveBeenCalled()+ })++ it("returns a complete empty DM child collection", async () => {+ mocks.access.mockResolvedValue({ ok: true, value: { surface: "dm", dm: { otherUserId: "peer" } } })+ mocks.channel.mockResolvedValue({ ...parent, id: "dm", type: "dm", serverId: null, name: null })+ const response = await threadList(req("dm/threads"), ctx("dm"))+ expect(await response.json()).toMatchObject({ contractVersion: 2, channelId: "dm", threads: [], included: { messages: [] } })+ expect(mocks.children).not.toHaveBeenCalled()+ })++ it("rejects child enumeration at the full reading gate", async () => {+ mocks.access.mockResolvedValue({ ok: false, status: 403, error: "forbidden" })+ expect((await threadList(req("forum/threads"), ctx("forum"))).status).toBe(403)+ expect(mocks.children).not.toHaveBeenCalled()+ expect(mocks.threads).not.toHaveBeenCalled()+ expect(mocks.openers).not.toHaveBeenCalled()+ })++ it("assembles only the selected page's parent and first committed messages", async () => {+ mocks.threads.mockResolvedValue([child, { ...child, id: "next-thread" }])+ mocks.openers.mockResolvedValue([row("opener", "forum")])+ mocks.first.mockResolvedValue([row("first", "thread")])+ mocks.tags.mockResolvedValue([{ messageId: "opener", tag: "bug" }])+ mocks.threadParticipants.mockResolvedValue([{ channelId: "thread", userId: "viewer", userName: "Viewer", userImage: null, userAvatarVersion: 0, participantCount: 1 }])+ const response = await threadList(req("forum/threads?order=createdAt&include=parentMessage,firstMessage,tags,participants&limit=1"), ctx("forum"))+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")+ const body = await response.json()+ expect(body).toMatchObject({ channelId: "forum", threads: [{ id: "thread" }], included: { messages: [{ id: "opener", channelId: "forum", seq: 1 }, { id: "first", channelId: "thread", seq: 1 }],+ members: [{ userId: "viewer", relation: "notify" }], tags: [{ messageId: "opener", tag: "bug" }] }, page: { hasMore: true, nextCursor: expect.any(String) } })+ expect(body.threads).toHaveLength(1)+ expect(mocks.first).toHaveBeenCalledWith(mocks.db, ["thread"])+ expect(mocks.openers).toHaveBeenCalledWith(mocks.db, ["opener"], { channelId: "forum" })+ expect(mocks.threadParticipants).toHaveBeenCalledWith(mocks.db, ["thread"], 5)+ })+})diff --git a/src/web/src/lib/community/thread-read.test.ts b/src/web/src/lib/community/thread-read.test.tsnew file mode 100644index 000000000..28b35bd3c--- /dev/null+++ b/src/web/src/lib/community/thread-read.test.ts@@ -0,0 +1,95 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { COMMUNITY_CONTRACT_HEADER, CommunityThreadsReadSchema } from "@alook/shared"++const mocks = vi.hoisted(() => ({ attachments: vi.fn(), reactions: vi.fn(), replies: vi.fn() }))+vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: {+ communityAttachment: { listByMessageIds: mocks.attachments },+ communityReaction: { listReactionsByMessageIds: mocks.reactions },+ communityMessage: { getMessagesByIdsInChannels: mocks.replies },+} }))+import { writeCommunityThreadsRead } from "./thread-read"++const db = {} as never+const parent = { id: "forum", type: "forum", serverId: "server", name: "Forum", archived: 0, createdAt: "2026-10-07T12:00:00Z" }+const child = { ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer" }+const row = (id: string, channelId: string) => ({ id, channelId, seq: 4, authorId: "viewer", authorName: "Viewer", authorImage: null, authorAvatarVersion: 0,+ content: id, type: "default", mentionType: null, replyToId: null as string | null, embeds: [], createdAt: "2026-10-07T12:00:00Z", clientNonce: "client-nonce" })+type Included = NonNullable<Parameters<typeof writeCommunityThreadsRead>[4]>+const included = (): Included => ({ messages: [row("opener", "forum"), { ...row("reply", "thread"), replyToId: "previous" }], tags: [{ messageId: "opener", tag: "bug" }],+ participants: [{ channelId: "thread", userId: "viewer", userName: "Viewer", userImage: null, userAvatarVersion: 0, participantCount: 8 }] })++beforeEach(() => {+ vi.clearAllMocks()+ mocks.attachments.mockResolvedValue([])+ mocks.reactions.mockResolvedValue([])+ mocks.replies.mockResolvedValue([])+})++describe("complete thread read resource", () => {+ it("writes the scoped message, attachment, reaction, reply and participant identities", async () => {+ mocks.attachments.mockResolvedValue([{ id: "attachment", messageId: "reply", targetId: "thread", filename: "note.txt", r2Key: "owned-key", contentType: "text/plain", size: 42 }])+ mocks.reactions.mockResolvedValue([{ messageId: "reply", emoji: "👍", userId: "viewer" }])+ mocks.replies.mockResolvedValue([{ ...row("previous", "thread"), content: "same-channel reply" }, { ...row("previous", "foreign"), content: "foreign private body" }])+ const response = await writeCommunityThreadsRead(db, "viewer", parent, [child], included(), { hasMore: true, nextCursor: "next" })+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")+ const body = CommunityThreadsReadSchema.parse(await response.json())+ expect(body).toMatchObject({ contractVersion: 2, channelId: "forum", channel: { id: "forum" }, threads: [{ id: "thread", parentChannelId: "forum" }],+ included: { tags: [{ messageId: "opener", tag: "bug" }], members: [{ channelId: "thread", userId: "viewer", relation: "notify", isCreator: true }],+ profiles: [{ id: "viewer", name: "Viewer", avatarVersion: 0 }], participantCounts: [{ channelId: "thread", count: 8 }] }, page: { hasMore: true, nextCursor: "next" } })+ expect(body.included.messages.find((message) => message.id === "reply")).toMatchObject({ channelId: "thread", seq: 4, clientNonce: "client-nonce", replyToId: "previous", type: "chat",+ replyTo: { id: "previous", text: "same-channel reply", authorId: "viewer" }, attachments: [{ kind: "file", name: "note.txt", sizeBytes: 42 }], reactions: [{ emoji: "👍", me: true, count: 1, userIds: ["viewer"] }] })+ expect(JSON.stringify(body)).not.toContain("foreign private body")+ expect(mocks.attachments).toHaveBeenCalledWith(db, ["opener", "reply"])+ expect(mocks.reactions).toHaveBeenCalledWith(db, ["opener", "reply"], "viewer")+ expect(mocks.replies).toHaveBeenCalledWith(db, ["previous"], ["forum", "thread"])+ })++ it("marks a foreign-only reply as deleted instead of disclosing its text", async () => {+ mocks.replies.mockResolvedValue([{ ...row("previous", "foreign"), content: "private" }])+ const response = await writeCommunityThreadsRead(db, "viewer", parent, [child], included())+ const body = CommunityThreadsReadSchema.parse(await response.json())+ expect(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", text: "", deleted: true })+ })++ it("does not disclose a reply from a legitimate sibling in the same included query", async () => {+ const sibling = { ...child, id: "sibling", parentMessageId: "sibling-opener" }+ mocks.replies.mockResolvedValue([{ ...row("previous", "sibling"), content: "sibling private reply" }])+ const response = await writeCommunityThreadsRead(db, "viewer", parent, [child, sibling], included())+ const body = CommunityThreadsReadSchema.parse(await response.json())+ expect(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", text: "", deleted: true })+ expect(JSON.stringify(body)).not.toContain("sibling private reply")+ expect(mocks.replies).toHaveBeenCalledWith(db, ["previous"], ["forum", "thread", "sibling"])+ })++ it("writes empty reads with default pagination and no fabricated included resource", async () => {+ const response = await writeCommunityThreadsRead(db, "viewer", parent, [])+ expect(CommunityThreadsReadSchema.parse(await response.json())).toMatchObject({ threads: [], included: { messages: [], tags: [], members: [], profiles: [], participantCounts: [] }, page: { nextCursor: null, hasMore: false } })+ expect(mocks.replies).toHaveBeenCalledWith(db, [], ["forum"])+ expect(mocks.attachments).toHaveBeenCalledWith(db, [])+ expect(mocks.reactions).toHaveBeenCalledWith(db, [], "viewer")+ })++ it("deduplicates profiles while preserving the scoped participant counts", async () => {+ const participant = { channelId: "thread", userId: "viewer", userName: null, userImage: null, userAvatarVersion: 0, participantCount: 2 }+ const otherChild = { ...child, id: "other-thread", creatorId: "other" }+ const participants = [participant, { ...participant, userId: "other" }, { ...participant, channelId: "other-thread", participantCount: 1 }]+ const response = await writeCommunityThreadsRead(db, "viewer", parent, [child, otherChild], { messages: [], tags: [], participants })+ const body = CommunityThreadsReadSchema.parse(await response.json())+ expect(body.included.profiles.map((profile) => profile.id)).toEqual(["viewer", "other"])+ expect(body.included.profiles[0]?.name).toBe("")+ expect(body.included.participantCounts).toEqual([{ channelId: "thread", count: 2 }, { channelId: "other-thread", count: 1 }])+ expect(body.included.members.map((member) => member.isCreator)).toEqual([true, false, false])+ })++ it.each([{ ...child, parentChannelId: "other" }, { ...child, serverId: "other" }])("rejects an unrelated child before any included query", async (invalidChild) => {+ await expect(writeCommunityThreadsRead(db, "viewer", parent, [invalidChild], included())).rejects.toThrow("Thread resource scope mismatch")+ expect(mocks.attachments).not.toHaveBeenCalled()+ expect(mocks.replies).not.toHaveBeenCalled()+ })++ it("rejects an unrelated included message before querying its private attachments", async () => {+ await expect(writeCommunityThreadsRead(db, "viewer", parent, [child], { ...included(), messages: [row("foreign", "other")] })).rejects.toThrow("Included message scope mismatch")+ expect(mocks.attachments).not.toHaveBeenCalled()+ expect(mocks.replies).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/lib/community/thread-read.ts b/src/web/src/lib/community/thread-read.tsnew file mode 100644index 000000000..36fe3674d--- /dev/null+++ b/src/web/src/lib/community/thread-read.ts@@ -0,0 +1,31 @@+import { COMMUNITY_CONTRACT_VERSION, CommunityThreadsReadSchema, normalizeCommunityChannelResource, normalizeCommunityMessageResource, queries, type Database } from "@alook/shared"+import { writeCommunityContractJSON } from "./read-contract"+import { loadApiMessageContext, mapMessageForApi } from "./message-payload"+import { canonicalUserImage } from "./storage"+import { resourceProfile, threadParticipantResources } from "./participant-resources"++type Included = { messages: Array<Parameters<typeof mapMessageForApi>[0] & { channelId: string; replyToId: string | null }>;+ tags: Array<{ messageId: string; tag: string }>;+ participants: Awaited<ReturnType<typeof queries.communityThread.listParticipantsForChannels>> }++export async function writeCommunityThreadsRead(db: Database, userId: string, channel: unknown, threads: unknown[], included?: Included,+ page = { nextCursor: null as string | null, hasMore: false }) {+ const parent = normalizeCommunityChannelResource(channel)+ const children = threads.map(normalizeCommunityChannelResource)+ if (children.some((child) => child.parentChannelId !== parent.id || child.serverId !== parent.serverId)) throw new Error("Thread resource scope mismatch")+ const items = included?.messages ?? []+ if (items.some((item) => item.channelId !== parent.id && !children.some((child) => child.id === item.channelId))) throw new Error("Included message scope mismatch")+ const ids = items.map((item) => item.id)+ const scopeIds = [parent.id, ...children.map((child) => child.id)]+ const contextForChannel = await loadApiMessageContext(db, userId, ids, () =>+ queries.communityMessage.getMessagesByIdsInChannels(db, items.flatMap((item) => item.replyToId ? [item.replyToId] : []), scopeIds),+ )+ const messages = items.map((item) => normalizeCommunityMessageResource(mapMessageForApi(item, contextForChannel(item.channelId)), item.channelId))+ const participants = threadParticipantResources((included?.participants ?? []).map((row) => ({+ channelId: row.channelId, userId: row.userId, isCreator: children.find((child) => child.id === row.channelId)?.creatorId === row.userId,+ participantCount: "participantCount" in row ? Number(row.participantCount) : undefined,+ profile: resourceProfile({ id: row.userId, name: row.userName ?? "", avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion), avatarVersion: row.userAvatarVersion }),+ })))+ return writeCommunityContractJSON(CommunityThreadsReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId: parent.id, channel: parent, threads: children,+ included: { messages, ...participants, tags: included?.tags ?? [] }, page }))+}diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.tsindex e9e942ebc..73779b178 100644--- a/src/web/src/lib/middleware/auth.test.ts+++ b/src/web/src/lib/middleware/auth.test.ts@@ -11,7 +11,8 @@ vi.mock("@/lib/db", () => ({getPrimaryDb: vi.fn(() => ({ primary: true })),}));-vi.mock("@alook/shared", () => ({+vi.mock("@alook/shared", async (importOriginal) => ({+ ...await importOriginal<typeof import("@alook/shared")>(),createDb: vi.fn(() => ({})),queries: {machineToken: {diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex e8d518b41..b8dbb8058 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -4,7 +4,7 @@ import { queries } from "@alook/shared"import { getDb, getPrimaryDb } from "@/lib/db"import { getAuth } from "@/lib/auth"import { getKV, cacheKeys, bindCacheKV } from "@/lib/cache"-import { varyPrivateResponseByCredentials } from "./response-cache"+import { protectCommunityJsonResponse, rejectUnknownCommunityContract, varyPrivateResponseByCredentials } from "./response-cache"export interface AuthContext {env: Env@@ -317,6 +317,11 @@ export function withCookieHumanAuth(handler: CookieHumanAuthHandler) {}export function withAuth(handler: AuthenticatedHandler) {+ const authenticate = createAuthenticatedHandler(handler)+ return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], rejectUnknownCommunityContract(args[0]) ?? await authenticate(...args))+}++function createAuthenticatedHandler(handler: AuthenticatedHandler) {return async (req: NextRequest,context?: { params?: Promise<Record<string, string>> | Record<string, string> }diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.tsindex c55b40185..a0dc15f4f 100644--- a/src/web/src/lib/middleware/community-actor.ts+++ b/src/web/src/lib/middleware/community-actor.ts@@ -3,7 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"import { getDb } from "@/lib/db"import { withAuth, type AuthContext } from "./auth"import { resolveBotActor } from "./community-agent-runner-auth"-import { varyPrivateResponseByCredentials } from "./response-cache"+import { protectCommunityJsonResponse, rejectUnknownCommunityContract, varyPrivateResponseByCredentials } from "./response-cache"/*** The unified community actor — the single identity a `/api/community/*` route@@ -79,6 +79,14 @@ export type CommunityActorHandler = (export function withCommunityActor(handler: CommunityActorHandler,options: { allowInactiveBot?: boolean } = {},+) {+ const authenticate = createCommunityActorHandler(handler, options)+ return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], rejectUnknownCommunityContract(args[0]) ?? await authenticate(...args))+}++function createCommunityActorHandler(+ handler: CommunityActorHandler,+ options: { allowInactiveBot?: boolean },) {return async (req: NextRequest,diff --git a/src/web/src/lib/middleware/response-cache.test.ts b/src/web/src/lib/middleware/response-cache.test.tsnew file mode 100644index 000000000..656f64782--- /dev/null+++ b/src/web/src/lib/middleware/response-cache.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest"+import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"+import { protectCommunityJsonResponse, rejectUnknownCommunityContract } from "./response-cache"++describe("protected community JSON policy", () => {+ it.each([200, 400, 401, 403, 404, 409, 429, 500, 503])("protects status %s and preserves cookies and vary", async (status) => {+ const request = new Request("https://alook.test/api/community/channels/c/messages", { headers: { [COMMUNITY_CONTRACT_HEADER]: "2" } })+ const response = await protectCommunityJsonResponse(request, Response.json(status === 200 ? { value: 1 } : { error: "blocked" }, { status,+ headers: { "Vary": "Origin, cookie", "Cache-Control": "public, max-age=600", "ETag": "old", "Last-Modified": "old", "Set-Cookie": "session=refreshed; HttpOnly" } }))+ expect(response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")+ expect(response.headers.get("Vary")).toBe("Origin, cookie, X-Alook-Community-Contract, Authorization")+ expect(response.headers.get("ETag")).toBeNull()+ expect(response.headers.get("Last-Modified")).toBeNull()+ expect(response.headers.get("Set-Cookie")).toBe("session=refreshed; HttpOnly")+ if (status !== 200) expect(await response.json()).toMatchObject({ contractVersion: 2, error: { message: "blocked", retryable: status >= 500 || status === 429 } })+ })+ it("preserves the independent media policy and rejects unknown versions", async () => {+ const request = new Request("https://alook.test/api/community/channels/c/icon", { headers: { [COMMUNITY_CONTRACT_HEADER]: "3" } })+ const image = new Response("image", { headers: { "Content-Type": "image/png", "Cache-Control": "private, max-age=86400", "ETag": "asset" } })+ expect(await protectCommunityJsonResponse(request, image)).toBe(image)+ expect(rejectUnknownCommunityContract(request)?.status).toBe(400)+ expect(rejectUnknownCommunityContract(new Request("https://alook.test/api/calendar", { headers: { [COMMUNITY_CONTRACT_HEADER]: "3" } }))).toBeNull()+ })+})diff --git a/src/web/src/lib/middleware/response-cache.ts b/src/web/src/lib/middleware/response-cache.tsindex 7273dce58..18f952365 100644--- a/src/web/src/lib/middleware/response-cache.ts+++ b/src/web/src/lib/middleware/response-cache.ts@@ -1,3 +1,44 @@+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, CommunityReadErrorSchema, requestsCommunityContract } from "@alook/shared"++export function rejectUnknownCommunityContract(request: Request): Response | null {+ const version = request.headers.get(COMMUNITY_CONTRACT_HEADER)+ return new URL(request.url).pathname.startsWith("/api/community/") && version !== null && version !== "1" && version !== String(COMMUNITY_CONTRACT_VERSION)+ ? Response.json({ error: "unsupported community contract" }, { status: 400 }) : null+}++export async function protectCommunityJsonResponse(request: Request, response: Response): Promise<Response> {+ if (!new URL(request.url).pathname.startsWith("/api/community/")) return response+ const contentType = response.headers.get("Content-Type")?.split(";", 1)[0].trim().toLowerCase()+ if (contentType !== "application/json" && !contentType?.endsWith("+json")) return response+ let result = new Response(response.body, response)+ if (!response.ok && requestsCommunityContract(request.headers)) {+ const body: unknown = await result.clone().json()+ const alreadyVersioned = CommunityReadErrorSchema.safeParse(body)+ if (!alreadyVersioned.success) {+ const raw = typeof body === "object" && body !== null && "error" in body ? body.error : undefined+ const message = typeof raw === "string" ? raw : "request failed"+ const code = response.status === 401 ? "unauthenticated" : response.status === 404 ? "not_found"+ : response.status === 403 ? message === "blocked" ? "blocked" : "not_allowed"+ : response.status === 409 ? "idempotency_conflict" : response.status === 429 ? "rate_limited"+ : response.status >= 500 ? "temporarily_unavailable" : "invalid_input"+ result = new Response(JSON.stringify(CommunityReadErrorSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION,+ error: { code, message, retryable: response.status === 429 || response.status >= 500 } })), result)+ result.headers.delete("Content-Length")+ }+ result.headers.set(COMMUNITY_CONTRACT_HEADER, String(COMMUNITY_CONTRACT_VERSION))+ }+ result.headers.set("Cache-Control", "private, no-store, max-age=0")+ result.headers.delete("ETag")+ result.headers.delete("Last-Modified")+ const vary = result.headers.get("Vary")?.split(",").map((field) => field.trim()).filter(Boolean) ?? []+ const fields = new Set(vary.map((field) => field.toLowerCase()))+ if (!fields.has("*")) {+ const missing = [COMMUNITY_CONTRACT_HEADER, "Cookie", "Authorization"].filter((field) => !fields.has(field.toLowerCase()))+ result.headers.set("Vary", [...vary, ...missing].join(", "))+ }+ return result+}+export function varyPrivateResponseByCredentials(response: Response): Response {const directives = response.headers.get("Cache-Control")?.split(",") ?? []if (!directives.some((directive) => directive.split("=", 1)[0].trim().toLowerCase() === "private")) return responsediff --git a/src/web/src/lib/observability/client-document-restore.dom.test.tsx b/src/web/src/lib/observability/client-document-restore.dom.test.tsxindex b25cd9e01..5182bf19f 100644--- a/src/web/src/lib/observability/client-document-restore.dom.test.tsx+++ b/src/web/src/lib/observability/client-document-restore.dom.test.tsx@@ -57,12 +57,13 @@ it("retires the old document before native resume, then exports one original Bacreturn <p>{router.pathname === forum ? "forum" : "empty text"}</p>}function Root() {+ const pathname = router.pathnameuseLayoutEffect(() => setTelemetryUser("account-a"), [])- useLayoutEffect(() => commitNavigation(router.pathname), [router.pathname])+ useLayoutEffect(() => commitNavigation(pathname), [pathname])return <QueryClientProvider client={queryClient!}><Content /></QueryClientProvider>}await act(async () => { bootstrapObservability("web"); view = render(<Root />) })- await vi.waitFor(() => expect(native.faro?.api.getSession()?.id).toBeTruthy())+ await act(async () => { await vi.waitFor(() => expect(native.faro?.api.getSession()?.id).toBeTruthy()) })await act(async () => { await vi.advanceTimersByTimeAsync(3000) })const originalSession = native.faro!.api.getSession()!.idconst initialReady = sent.flatMap(body => body.events ?? []).filter(event => event.name === "navigation.ready")diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex c3b8a468d..9a3fae596 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -46,7 +46,7 @@ describe("communityKeys", () => {...server, "forum-sidebar-retained", "post_1",])expect(communityKeys.channelMeta("s1", "post_1")).toEqual([- ...server, "channel-meta", "post_1",+ "community", "channel", "post_1", "metadata",])expect(communityKeys.forumOpenerHint("s1", "message_1")).toEqual([...server, "forum-opener-hint", "message_1",@@ -113,7 +113,7 @@ describe("communityKeys", () => {it("nests DM-scoped keys under a stable DM prefix", () => {const dmRoot = communityKeys.dmMessages("d1")- expect(dmRoot).toEqual(["community", "dm", "d1", "messages"])+ expect(dmRoot).toEqual(["community", "channel", "d1", "messages"])expect(communityKeys.dmMessagesPage("d1", "cur-1")).toEqual([...dmRoot,@@ -171,16 +171,16 @@ describe("communityKeys", () => {])expect(communityKeys.messageContext("dm", "d1", 7)).toEqual(["community",- "message-context",- "dm",+ "channel","d1",+ "message-context",7,])expect(communityKeys.messageContexts("dm", "d1")).toEqual(["community",- "message-context",- "dm",+ "channel","d1",+ "message-context",])expect(communityKeys.reactionDetails("m1")).toEqual([...communityKeys.reactionDetailsAll(),diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex d06e855d7..cfc0e1fa3 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -35,9 +35,8 @@ export const communityKeys = {[...communityKeys.forumSidebarRetainedRoot(serverId), childId] as const,channelMetaRoot: (serverId: string) =>[...communityKeys.server(serverId), "channel-meta"] as const,- channelMeta: (serverId: string | null, channelId: string) => serverId === null- ? [...communityKeys.all, "channel", channelId, "metadata"] as const- : [...communityKeys.channelMetaRoot(serverId), channelId] as const,+ channelMeta: (_serverId: string | null, channelId: string) =>+ [...communityKeys.all, "channel", channelId, "metadata"] as const,forumOpenerHintRoot: (serverId: string) =>[...communityKeys.server(serverId), "forum-opener-hint"] as const,forumOpenerHint: (serverId: string, messageId: string) =>@@ -72,14 +71,15 @@ export const communityKeys = {[...communityKeys.channelMessages(channelId), cursor ?? null] as const,dmMessages: (dmId: string) =>- [...communityKeys.all, "dm", dmId, "messages"] as const,+ communityKeys.channelMessages(dmId),dmMessagesPage: (dmId: string, cursor?: string | null) =>[...communityKeys.dmMessages(dmId), cursor ?? null] as const,// Explicit membership roster of a private-category channel + the addable// (not-yet-member) server members for its picker.- channelMembers: (channelId: string) =>- [...communityKeys.all, "channel", channelId, "members"] as const,+ channelMembers: (channelId: string, relation?: "access" | "notify") =>+ relation ? [...communityKeys.all, "channel", channelId, "members", relation] as const+ : [...communityKeys.all, "channel", channelId, "members"] as const,channelAddableMembers: (channelId: string) =>[...communityKeys.all, "channel", channelId, "addable-members"] as const,@@ -106,7 +106,7 @@ export const communityKeys = {// hook latches the first non-null response so the "New" divider anchor// stays put while the progressive watermark advances.dmReadStateSnapshot: (dmId: string) =>- [...communityKeys.all, "dm", dmId, "read-state-snapshot"] as const,+ communityKeys.channelReadStateSnapshot(dmId),accountReadStateSnapshot: () =>[...communityKeys.all, "read-state-snapshot"] as const,accountAttention: () =>@@ -115,8 +115,8 @@ export const communityKeys = {// Single hydrated message (opener block, deep-link previews).message: (messageId: string) =>[...communityKeys.all, "message", messageId] as const,- messageContexts: (type: "channel" | "dm", channelId: string) =>- [...communityKeys.all, "message-context", type, channelId] as const,+ messageContexts: (_type: "channel" | "dm", channelId: string) =>+ [...communityKeys.all, "channel", channelId, "message-context"] as const,messageContext: (type: "channel" | "dm", channelId: string, targetSeq: number | null) =>[...communityKeys.messageContexts(type, channelId), targetSeq] as const,reactionDetailsAll: () =>diff --git a/src/web/src/lib/query-persister.race.test.ts b/src/web/src/lib/query-persister.race.test.tsindex fec31b350..fbd4d560d 100644--- a/src/web/src/lib/query-persister.race.test.ts+++ b/src/web/src/lib/query-persister.race.test.ts@@ -1,15 +1,20 @@import "fake-indexeddb/auto"import { del, get, set } from "idb-keyval"import { afterEach, describe, expect, it, vi } from "vitest"+import { QueryClient, dehydrate } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import { canonicalChannelRow } from "@/lib/community-db/schema"import type { PersistedClient } from "@tanstack/react-query-persist-client"-import { clearPersistedCache, createIdbPersister } from "./query-persister"+import { clearPersistedCache, createIdbPersister, PERSIST_BUSTER,+ PERSIST_VERSION,+ PERSIST_CACHE_PREFIX, cacheInvalidation } from "./query-persister"const client: PersistedClient = {timestamp: 1,- buster: "v2",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },}-const blobKey = (user: string) => `alook:qc:v3:${user}:client`+const blobKey = (user: string) => `${PERSIST_CACHE_PREFIX}:${user}:client`afterEach(() => vi.restoreAllMocks())describe("native IDB persistence retirement", () => {@@ -64,6 +69,26 @@ describe("native IDB persistence retirement", () => {expect((await fresh.restoreClient())?.timestamp).toBe(2)})+ it.each([undefined, PERSIST_VERSION - 1, "invalid"])("discards version %s within the account cache and fences existing owners", async (version) => {+ const user = `u_mismatch_${version}`+ const old = createIdbPersister(user), sibling = createIdbPersister(`${user}_other`)+ await old.persistClient(client)+ await sibling.persistClient(client)+ await set(blobKey(user), JSON.stringify({ ...client, version, channelFences: [] }))+ const fresh = createIdbPersister(user)+ await expect(fresh.restoreClient()).resolves.toBeUndefined()+ expect(await get(blobKey(user))).toBeUndefined()+ await expect(old.isCurrent()).resolves.toBe(false)+ await old.persistClient({ ...client, timestamp: 9 })+ expect(await get(blobKey(user))).toBeUndefined()+ await expect(sibling.restoreClient()).resolves.toEqual(client)+ await fresh.persistClient({ ...client, timestamp: 2 })+ await expect(fresh.restoreClient()).resolves.toMatchObject({ timestamp: 2 })+ await set(blobKey(user), JSON.stringify({ ...client, version, channelFences: [] }))+ await expect(fresh.restoreClient()).resolves.toBeUndefined()+ expect(await get(blobKey(user))).toBeUndefined()+ })+it("a retired remover cannot delete a newly qualified owner's payload", async () => {const user = "u_retired_remove"const stale = createIdbPersister(user)@@ -115,3 +140,208 @@ describe("qualified native owner disk retirement", () => {expect(await original.isCurrent()).toBe(false)})})++function readingSnapshot(user: string): PersistedClient {+ const queryClient = new QueryClient()+ const setRows = (name: string, rows: unknown[]) => queryClient.setQueryData(communityKeys.communityDbCollection(user, name), rows)+ setRows("channels", ["dm-A", "dm-B"].map((id) => canonicalChannelRow({ id, type: "dm", name: id, preview: `body-${id}`, unread: true })))+ setRows("messages", ["dm-A", "dm-B"].map((channelId) => ({ id: `m-${channelId}`, channelId, type: "chat", authorId: user, authorName: "Viewer", authorAvatar: "V", authorAvatarVersion: 0, seq: 1, content: `body-${channelId}` })))+ setRows("channelMemberships", ["dm-A", "dm-B"].map((channelId) => ({ id: `${channelId}:peer:access`, channelId, userId: "peer", relation: "access" })))+ return { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(queryClient) }+}+function readingRows(snapshot: PersistedClient | undefined, name: string) {+ return snapshot?.clientState.queries.find((query) => query.queryKey[3] === name)?.state.data as Array<Record<string, unknown>> | undefined+}++describe("native channel persistence fence", () => {+ it.each([+ ["account", false], ["account", true], ["channel", false], ["channel", true],+ ] as const)("retires existing v3 eligibility on %s retirement with payload=%s", async (kind, hasPayload) => {+ const user = `u_v3_qualified_${kind}_${hasPayload}`+ await clearPersistedCache(user)+ const owner = createIdbPersister(user)+ const before = readingSnapshot(user)+ await owner.persistClient(before)+ const other = createIdbPersister(`${user}_other`)+ await other.persistClient(client)+ const device = await get("alook:qc:device-epoch")+ const oldNamespace = `alook:qc:v3:${user}`+ const oldKeys = [`${oldNamespace}:account-epoch`, `${oldNamespace}:client:epoch`, `${oldNamespace}:application:client:epoch`]+ const epochs = oldKeys.map(() => crypto.randomUUID())+ for (let i = 0; i < oldKeys.length; i++) await set(oldKeys[i]!, epochs[i])+ if (hasPayload) await set(`${oldNamespace}:client`, JSON.stringify(client))+ const otherEpoch = crypto.randomUUID(), otherKey = `alook:qc:v3:${user}_other:account-epoch`+ await set(otherKey, otherEpoch)+ const unrelated = `${oldNamespace}:preference`+ await set(unrelated, "keep")+ if (!hasPayload) expect(await get(`${oldNamespace}:client`)).toBeUndefined()+ if (kind === "account") await owner.retireAccount()+ else await owner.retireChannels(["dm-A"])+ for (let i = 0; i < oldKeys.length; i++) expect(await get(oldKeys[i]!)).not.toBe(epochs[i])+ expect(await get(`${oldNamespace}:client`)).toBeUndefined()+ expect(await get(otherKey)).toBe(otherEpoch)+ expect(await get(unrelated)).toBe("keep")+ expect(await get("alook:qc:device-epoch")).toBe(device)+ expect(await other.isCurrent()).toBe(true)+ expect(await owner.isCurrent()).toBe(kind === "channel")+ if (kind === "channel") {+ const restored = await owner.restoreClient()+ expect(readingRows(restored, "messages")).toEqual(readingRows(before, "messages")!.filter((row) => row.channelId === "dm-B"))+ }+ })++ it("clearPersistedCache deletes prior namespace payloads and invalidates their existing qualifications only for the account", async () => {+ const user = "u_v3_existing_payload"+ const namespace = `alook:qc:v3:${user}`+ const account = crypto.randomUUID(), scope = crypto.randomUUID()+ await set(`${namespace}:account-epoch`, account)+ await set(`${namespace}:client:epoch`, scope)+ await set(`${namespace}:client`, JSON.stringify(client))+ await set(`${namespace}:application:client`, "application")+ const otherKey = `alook:qc:v3:${user}_other:client`+ await set(otherKey, "other account bytes")+ await clearPersistedCache(user)+ expect(await get(`${namespace}:client`)).toBeUndefined()+ expect(await get(`${namespace}:application:client`)).toBeUndefined()+ expect(await get(`${namespace}:account-epoch`)).not.toBe(account)+ expect(await get(`${namespace}:client:epoch`)).not.toBe(scope)+ expect(await get(otherKey)).toBe("other account bytes")+ })++ it("keeps sibling bytes and the account owner while fencing a later old-document write", async () => {+ const user = "u_channel_late_writer"+ await clearPersistedCache(user)+ const old = createIdbPersister(user)+ const before = readingSnapshot(user)+ await old.persistClient(before)+ const invalidation = cacheInvalidation.get()+ vi.resetModules()+ const otherDocument = await import("./query-persister")+ await otherDocument.createIdbPersister(user).retireChannels(["dm-A"])+ expect(await old.isCurrent()).toBe(true)+ expect(cacheInvalidation.get()).toBe(invalidation)+ await old.persistClient(before)+ const restored = await otherDocument.createIdbPersister(user).restoreClient()+ expect(readingRows(restored, "messages")?.map((row) => row.channelId)).toEqual(["dm-B"])+ expect(readingRows(restored, "channels")).toEqual(expect.arrayContaining([+ expect.objectContaining({ id: "dm-A", preview: "", unread: false }),+ expect.objectContaining({ id: "dm-B", preview: "body-dm-B", unread: true }),+ ]))+ expect(readingRows(restored, "channelMemberships")).toHaveLength(2)+ const fresh = otherDocument.createIdbPersister(user)+ await fresh.persistClient(before)+ expect(readingRows(await fresh.restoreClient(), "messages")).toHaveLength(2)+ })++ it("scrubs a transaction that already passed writer eligibility", async () => {+ const user = "u_channel_inflight_writer"+ await clearPersistedCache(user)+ const old = createIdbPersister(user)+ await old.restoreClient()+ let retirement: Promise<void> | undefined+ const put = IDBObjectStore.prototype.put+ vi.spyOn(IDBObjectStore.prototype, "put").mockImplementation(function (this: IDBObjectStore, value: unknown, key?: IDBValidKey) {+ if (key === blobKey(user) && !retirement) retirement = old.retireChannels(["dm-A"])+ return put.call(this, value, key)+ })+ await old.persistClient(readingSnapshot(user))+ expect(retirement).toBeDefined()+ await retirement+ expect(readingRows(await createIdbPersister(user).restoreClient(), "messages")?.map((row) => row.channelId)).toEqual(["dm-B"])+ })++ it("distinguishes physical deletion from denied DM identity", async () => {+ const user = "u_channel_deleted"+ await clearPersistedCache(user)+ const persister = createIdbPersister(user)+ const before = readingSnapshot(user)+ await persister.persistClient(before)+ await persister.retireChannels(["dm-A"], true)+ await persister.persistClient(before)+ const restored = await createIdbPersister(user).restoreClient()+ expect(readingRows(restored, "channels")?.map((row) => row.id)).toEqual(["dm-B"])+ expect(readingRows(restored, "channelMemberships")?.map((row) => row.channelId)).toEqual(["dm-B"])+ })++ it("compares stored epochs before a fresh owner restores an earlier snapshot", async () => {+ const user = "u_channel_old_snapshot"+ await clearPersistedCache(user)+ const owner = createIdbPersister(user)+ await owner.persistClient(readingSnapshot(user))+ const before = await get(blobKey(user))+ await owner.retireChannels(["dm-A"])+ await set(blobKey(user), before)+ expect(readingRows(await createIdbPersister(user).restoreClient(), "messages")?.map((row) => row.channelId)).toEqual(["dm-B"])+ })++ it("scrubs only retired channel notification settings and preserves server and sibling settings", async () => {+ const user = "u_notification_scope_retire", owner = createIdbPersister(user), snapshot = readingSnapshot(user)+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.communityDbCollection(user, "notificationSettings"), [+ { id: "A", channelId: "dm-A", serverId: null, level: "all" },+ { id: "B", channelId: "dm-B", serverId: null, level: "mentions" },+ { id: "server", channelId: null, serverId: "server", level: "all" },+ ])+ snapshot.clientState.queries.push(...dehydrate(qc).queries)+ await owner.persistClient(snapshot)+ await owner.retireChannels(["dm-A"])+ expect(readingRows(await owner.restoreClient(), "notificationSettings")?.map(row => row.id)).toEqual(["B", "server"])+ })++ it("deletes an undecodable payload during native channel retirement", async () => {+ const user = "u_corrupt_payload_retire", owner = createIdbPersister(user)+ await owner.persistClient(readingSnapshot(user))+ await set(blobKey(user), "not-json")+ await expect(owner.retireChannels(["dm-A"])).resolves.toBeUndefined()+ expect(await get(blobKey(user))).toBeUndefined()+ await set(blobKey(user), JSON.stringify({ ...client, channelFences: "invalid" }))+ await owner.retireChannels(["dm-A"])+ expect(await get(blobKey(user))).toBeUndefined()+ expect(await owner.restoreClient()).toBeUndefined()+ expect(await owner.isCurrent()).toBe(true)+ })++ it("retires attention by scope, child and read target while keeping unrelated items and friend requests", async () => {+ const user = "u_attention_retirement", owner = createIdbPersister(user)+ const snapshot = readingSnapshot(user), qc = new QueryClient()+ const item = (id: string, extra: Record<string, unknown> = {}) => ({ id, kind: "reply", sourceId: id, createdAt: "2026-10-08T00:00:00Z", ...extra })+ qc.setQueryData(communityKeys.communityDbCollection(user, "attentionItems"), [+ item("scope", { scopeId: "dm-A" }), item("child", { childChannelId: "dm-A" }),+ item("target", { readTarget: { channelId: "dm-A", seq: 1 } }),+ item("sibling", { scopeId: "dm-B", readTarget: { channelId: "dm-B", seq: 1 } }),+ item("unscoped"), item("friend", { kind: "friend_request", actorUserId: "peer" }),+ ])+ snapshot.clientState.queries.push(...dehydrate(qc).queries)+ await owner.persistClient(snapshot)+ await owner.retireChannels(["dm-A"])+ const restored = await owner.restoreClient()+ expect(readingRows(restored, "attentionItems")?.map(row => row.id)).toEqual(["unscoped", "sibling", "friend"])+ expect(readingRows(restored, "messages")?.map(row => row.channelId)).toEqual(["dm-B"])+ await owner.persistClient(snapshot)+ expect(readingRows(await owner.restoreClient(), "attentionItems")?.map(row => row.id)).toEqual(["unscoped", "sibling", "friend"])+ })++ it.each(["missing", "corrupt"])("fails closed for %s stored channel fence metadata", async (kind) => {+ const user = `u_channel_snapshot_${kind}`+ await clearPersistedCache(user)+ const owner = createIdbPersister(user)+ await owner.persistClient(readingSnapshot(user))+ const raw = JSON.parse(await get<string>(blobKey(user)) ?? "null") as Record<string, unknown>+ if (kind === "missing") delete raw.channelFences+ else raw.channelFences = [["dm-A", { epoch: "invalid", deleted: false }]]+ await set(blobKey(user), JSON.stringify(raw))+ expect(await owner.restoreClient()).toBeUndefined()+ })+})++it("a retired account owner cannot fence a newer same-account snapshot", async () => {+ const user = "u_stale_account_channel_retire"+ const old = createIdbPersister(user)+ await old.restoreClient()+ await old.retireAccount()+ const fresh = createIdbPersister(user)+ await fresh.persistClient(readingSnapshot(user))+ await old.retireChannels(["dm-A"], true)+ expect(readingRows(await fresh.restoreClient(), "messages")).toHaveLength(2)+ expect(readingRows(await fresh.restoreClient(), "channels")).toHaveLength(2)+})diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.tsindex c0a7d0c30..b4775a5b1 100644--- a/src/web/src/lib/query-persister.test.ts+++ b/src/web/src/lib/query-persister.test.ts@@ -5,6 +5,9 @@ import { QueryClient } from "@tanstack/react-query"import type { PersistedClient } from "@tanstack/react-query-persist-client"import { communityKeys } from "@/lib/query-keys"import {+ PERSIST_BUSTER,+ PERSIST_VERSION,+ PERSIST_CACHE_PREFIX,clearPersistedCache,clearAllPersistedCaches,createIdbPersister,@@ -164,7 +167,7 @@ function validServerDetail(id = "srv_1") {async function readPersistedBlob(userId: string | null): Promise<PersistedClient> {const raw = await get<string>(- `alook:qc:v3:${userId ?? "anon"}:client`,+ `alook:qc:cache:${userId ?? "anon"}:client`,)if (!raw) throw new Error("no persisted blob")return JSON.parse(raw) as PersistedClient@@ -196,7 +199,7 @@ describe("createIdbPersister — serialize filter", () => {const persister = createIdbPersister("u_1")await persister.persistClient({timestamp: Date.now(),- buster: "v1",+ buster: PERSIST_BUSTER,clientState: {mutations: [],queries: [@@ -237,7 +240,7 @@ describe("createIdbPersister — serialize filter", () => {const persister = createIdbPersister("u_1")await persister.persistClient({timestamp: Date.now(),- buster: "v1",+ buster: PERSIST_BUSTER,clientState: {mutations: [],queries: [@@ -275,7 +278,7 @@ describe("createIdbPersister — serialize filter", () => {await createIdbPersister("u_1").persistClient({timestamp: Date.now(),- buster: "v1",+ buster: PERSIST_BUSTER,clientState: {mutations: [],queries: queryKeys.map((queryKey) => ({@@ -455,7 +458,7 @@ describe("createIdbPersister — serialize filter", () => {]await createIdbPersister("u_1").persistClient({timestamp: Date.now(),- buster: "v2",+ buster: PERSIST_BUSTER,clientState: {mutations: [],queries: keys.map((queryKey) => ({@@ -534,7 +537,7 @@ describe("createIdbPersister — serialize filter", () => {qc.setQueryData(communityKeys.server("srv_1"), { id: "other", categories: [] })const injected: PersistedClient = {timestamp: Date.now(),- buster: "v1",+ buster: PERSIST_BUSTER,clientState: {mutations: [],queries: [communityKeys.servers(), communityKeys.server("srv_1")].map((queryKey) => ({@@ -544,7 +547,7 @@ describe("createIdbPersister — serialize filter", () => {})),},}- await set("alook:qc:v3:u_1:client", JSON.stringify(injected))+ await set("alook:qc:cache:u_1:client", JSON.stringify({ ...injected, version: PERSIST_VERSION, channelFences: [] }))expect((await createIdbPersister("u_1").restoreClient())?.clientState.queries).toEqual([])})@@ -593,7 +596,7 @@ describe("createIdbPersister — serialize filter", () => {qc.setQueryData(queryKey, data)const injected: PersistedClient = {timestamp: Date.now(),- buster: "v1",+ buster: PERSIST_BUSTER,clientState: {mutations: [],queries: [{@@ -603,7 +606,7 @@ describe("createIdbPersister — serialize filter", () => {}],},}- await set("alook:qc:v3:u_1:client", JSON.stringify(injected))+ await set("alook:qc:cache:u_1:client", JSON.stringify({ ...injected, version: PERSIST_VERSION, channelFences: [] }))expect((await createIdbPersister("u_1").restoreClient())?.clientState.queries).toEqual([])})@@ -640,12 +643,12 @@ describe("createIdbPersister — user scoping", () => {const bob = createIdbPersister("u_bob")const stateForAlice: PersistedClient = {timestamp: 1,- buster: "v1",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },}const stateForBob: PersistedClient = {timestamp: 2,- buster: "v1",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },}await alice.persistClient(stateForAlice)@@ -662,19 +665,19 @@ describe("createIdbPersister — user scoping", () => {const bob = createIdbPersister("u_bob")await alice.persistClient({timestamp: 1,- buster: "v1",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },})await bob.persistClient({timestamp: 2,- buster: "v1",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },})await clearPersistedCache("u_alice")// Alice's blob is gone but Bob's is untouched.- expect(await get(`alook:qc:v3:u_alice:client`)).toBeUndefined()+ expect(await get(`alook:qc:cache:u_alice:client`)).toBeUndefined()const bobBlob = await readPersistedBlob("u_bob")expect(bobBlob.timestamp).toBe(2)})@@ -683,13 +686,13 @@ describe("createIdbPersister — user scoping", () => {const persister = createIdbPersister("u_remove")await persister.persistClient({timestamp: 4,- buster: "v1",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },})await persister.removeClient()- expect(await get("alook:qc:v3:u_remove:client")).toBeUndefined()+ expect(await get("alook:qc:cache:u_remove:client")).toBeUndefined()})it("blocks a delayed writer created before clear", async () => {@@ -697,10 +700,10 @@ describe("createIdbPersister — user scoping", () => {await clearPersistedCache("u_alice")await stale.persistClient({timestamp: 3,- buster: "v1",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },})- expect(await get(`alook:qc:v3:u_alice:client`)).toBeUndefined()+ expect(await get(`alook:qc:cache:u_alice:client`)).toBeUndefined()})})@@ -708,24 +711,32 @@ describe("all-account persisted cache management", () => {beforeEach(async () => {await clearAllPersistedCaches()await del("unrelated")- await del("alook:qc:v3:u_alice:metadata")- await del("alook:qc:v3:extra:segment:client")+ await del("alook:qc:cache:u_alice:metadata")+ await del("alook:qc:cache:extra:segment:client")+ })++ it("uses a stable persister key with the sole version field and matching buster", async () => {+ const persister = createIdbPersister("u-version-source")+ const client = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { mutations: [], queries: [] } }+ await persister.persistClient(client)+ expect(await get(`${PERSIST_CACHE_PREFIX}:u-version-source:client`)).toBe(JSON.stringify({ ...client, version: PERSIST_VERSION, channelFences: [] }))+ await expect(persister.restoreClient()).resolves.toEqual(client)})it("sums serialized UTF-8 bytes across account and cache versions", async () => {await set("alook:qc:v1:u_alice:client", "abc")- await set("alook:qc:v3:u_bob:client", "你好")+ await set("alook:qc:cache:u_bob:client", "你好")await set("alook:qc:v99:u_future:client", "!")expect(await getPersistedCacheSizeBytes()).toBe(10)})it("ignores unrelated shapes and non-string values", async () => {- await set("alook:qc:v3:u_alice:client", "cache")+ await set("alook:qc:cache:u_alice:client", "cache")await set("unrelated", "outside")- await set("alook:qc:v3:u_alice:metadata", "outside")- await set("alook:qc:v3:extra:segment:client", "outside")- await set("alook:qc:v3:u_binary:client", new Uint8Array([1, 2, 3]))+ await set("alook:qc:cache:u_alice:metadata", "outside")+ await set("alook:qc:cache:extra:segment:client", "outside")+ await set("alook:qc:cache:u_binary:client", new Uint8Array([1, 2, 3]))expect(await getPersistedCacheSizeBytes()).toBe(5)})@@ -733,25 +744,25 @@ describe("all-account persisted cache management", () => {it("clears every current account blob and preserves unrelated keys", async () => {const stale = createIdbPersister("u_alice")await set("alook:qc:v1:u_legacy:client", "legacy")- await set("alook:qc:v3:u_alice:client", "alice")- await set("alook:qc:v3:u_bob:client", "bob")+ await set("alook:qc:cache:u_alice:client", "alice")+ await set("alook:qc:cache:u_bob:client", "bob")await set("alook:qc:v99:u_future:client", "future")await set("unrelated", "keep")- await set("alook:qc:v3:extra:segment:client", "keep")+ await set("alook:qc:cache:extra:segment:client", "keep")await clearAllPersistedCaches()await stale.persistClient({timestamp: 3,- buster: "v2",+ buster: PERSIST_BUSTER,clientState: { mutations: [], queries: [] },})expect(await get("alook:qc:v1:u_legacy:client")).toBeUndefined()- expect(await get("alook:qc:v3:u_alice:client")).toBeUndefined()- expect(await get("alook:qc:v3:u_bob:client")).toBeUndefined()+ expect(await get("alook:qc:cache:u_alice:client")).toBeUndefined()+ expect(await get("alook:qc:cache:u_bob:client")).toBeUndefined()expect(await get("alook:qc:v99:u_future:client")).toBeUndefined()expect(await get("unrelated")).toBe("keep")- expect(await get("alook:qc:v3:extra:segment:client")).toBe("keep")+ expect(await get("alook:qc:cache:extra:segment:client")).toBe("keep")})it("reports an empty cache as zero bytes", async () => {diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.tsindex 549c3d169..baa05cd22 100644--- a/src/web/src/lib/query-persister.ts+++ b/src/web/src/lib/query-persister.ts@@ -1,4 +1,6 @@+import { messageProfileIds, type Msg } from "@/lib/community/models/message"import { clearLegacyChatCaches, getLegacyChatCacheSizeBytes } from "@/lib/legacy-chat-persistence"+import { clearPublicWorkerCaches, getPublicWorkerCacheSizeBytes } from "@/lib/service-worker/public-cache-storage"import { observeRestoreRead, observeRestoreDecode } from "@/lib/observability/restore"import { createStore as createNativeStore } from "@tanstack/store"import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"@@ -10,24 +12,13 @@ import { createStore, promisifyRequest } from "idb-keyval"import {communityCollectionSchemas,type CommunityCollectionName,+ type CommunityCollectionRows,} from "@/lib/community-db/schema"-/**- * IDB namespace root. Bumping the tail segment (`v1` → `v2`) invalidates every- * cached payload — use it as the escape hatch when the persisted query shape- * changes in a way the runtime can't reconcile against fresh server data.- */-// v3 does not import v2: older tabs write unqualified bare payloads. Their-// late writes must never become a new owner's restore input after clear.-const IDB_PREFIX = "alook:qc:v3"--/**- * Buster tag paired with `PersistedClient`. TanStack throws away restored- * state whose buster doesn't match — a cheap secondary lever when just the- * shape of a specific query needs to be reset without touching the IDB- * namespace.- */-export const PERSIST_BUSTER = "v3"+export const PERSIST_VERSION = 5+export const PERSIST_BUSTER = String(PERSIST_VERSION)+export const PERSIST_CACHE_PREFIX = "alook:qc:cache"+const IDB_PREFIX = PERSIST_CACHE_PREFIX/** Persister max-age; queries older than this are discarded on restore. */export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000@@ -74,6 +65,7 @@ export function shouldPersistQuery(function scrubDehydratedClient(client: PersistedClient,userId: string | null,+ retired: ReadonlyMap<string, ChannelDiskFence> = new Map(),): PersistedClient {const queries: typeof client.clientState.queries = []const canonical = new Map<CommunityCollectionName, unknown[]>()@@ -90,38 +82,22 @@ function scrubDehydratedClient(}}- const retainedServerIds = new Set(- ((canonical.get("servers") ?? []) as Array<{ id: string }>).map((row) => row.id),- )-- const channels = (canonical.get("channels") ?? []) as Array<{- id: string- serverId?: string | null- type: "text" | "forum" | "thread" | "dm"- }>- const attentionScopes = (canonical.get("attentionScopes") ?? []) as Array<{- scopeId: string- channelId: string- }>- const retainedAttentionItems = ((canonical.get("attentionItems") ?? []) as Array<{- id: string- kind: "mention" | "reply" | "friend_request" | "pending"- messageId?: string | null- actorUserId: string- createdAt: string- }>).slice()- const retainedMessageAttention = retainedAttentionItems- .filter((item) => item.kind !== "friend_request")- .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))- .slice(0, MAX_PERSISTED_ATTENTION_ITEMS)- const retainedFriendAttention = retainedAttentionItems- .filter((item) => item.kind === "friend_request")- retainedAttentionItems.splice(- 0,- retainedAttentionItems.length,- ...retainedMessageAttention,- ...retainedFriendAttention,- )+ const rows = <N extends CommunityCollectionName>(name: N) => (canonical.get(name) ?? []) as CommunityCollectionRows[N][]+ const retainedServerIds = new Set(rows("servers").map((row) => row.id))+ const channels = rows("channels").flatMap((row) => {+ const fence = retired.get(row.id)+ if (!fence) return [row]+ return row.type === "dm" && !fence.deleted+ ? [{ ...row, preview: "", unread: false, baseUnread: false, lastUnreadSeq: undefined }]+ : []+ })+ const attentionScopes = rows("attentionScopes").filter((row) => !retired.has(row.channelId))+ const attentionCandidates = rows("attentionItems").filter((row) => !Boolean(row.scopeId && retired.has(row.scopeId) || row.childChannelId && retired.has(row.childChannelId) || row.readTarget && retired.has(row.readTarget.channelId)))+ const retainedAttentionItems = [+ ...attentionCandidates.filter((item) => item.kind !== "friend_request")+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)).slice(0, MAX_PERSISTED_ATTENTION_ITEMS),+ ...attentionCandidates.filter((item) => item.kind === "friend_request"),+ ]const attentionChannelIds = new Set(attentionScopes.map((row) => row.channelId))const retainedChannels = channels.filter((row) => (attentionChannelIds.has(row.id)@@ -133,15 +109,8 @@ function scrubDehydratedClient(const retainedDmIds = new Set(retainedChannels.filter((row) => row.type === "dm").map((row) => row.id),)- const allMessages = (canonical.get("messages") ?? []) as Array<{- id: string- channelId: string- seq?: number- createdAt?: string- authorId?: string- replyTo?: { authorId?: string }- thread?: { participants?: Array<{ id: string }> }- }>+ const allMessages = (rows("messages") as Array<CommunityCollectionRows["messages"] & Pick<Msg, "replyTo" | "thread" | "approval">>)+ .filter((row) => !retired.has(row.channelId))const messagesByScope = new Map<string, typeof allMessages>()for (const message of allMessages) {if (!retainedChannelIds.has(message.channelId)) continue@@ -171,17 +140,8 @@ function scrubDehydratedClient(}const retainedMessageChannelIds = new Set(retainedMessages.map((row) => row.channelId))const durableChannelIds = new Set([...retainedChannelIds, ...retainedMessageChannelIds])- const serverMemberships = (canonical.get("serverMemberships") ?? []) as Array<{- serverId: string- userId: string- viewer: boolean- }>- const retainedServerMemberships = serverMemberships.filter((row) => row.viewer)- const channelMemberships = (canonical.get("channelMemberships") ?? []) as Array<{- channelId: string- userId: string- relation: "access" | "notify"- }>+ const retainedServerMemberships = rows("serverMemberships").filter((row) => row.viewer)+ const channelMemberships = rows("channelMemberships")const retainedChannelMemberships = channelMemberships.filter((row) => (durableChannelIds.has(row.channelId)&& (@@ -190,39 +150,30 @@ function scrubDehydratedClient()))const referencedProfileIds = new Set<string>(userId ? [userId] : [])- for (const server of (canonical.get("servers") ?? []) as Array<{ ownerId: string }>) {+ for (const server of rows("servers")) {if (server.ownerId) referencedProfileIds.add(server.ownerId)}for (const membership of retainedServerMemberships) referencedProfileIds.add(membership.userId)for (const membership of retainedChannelMemberships) referencedProfileIds.add(membership.userId)for (const message of retainedMessages) {- if (message.authorId) referencedProfileIds.add(message.authorId)- if (message.replyTo?.authorId) referencedProfileIds.add(message.replyTo.authorId)- for (const participant of message.thread?.participants ?? []) {- referencedProfileIds.add(participant.id)- }- for (const profile of [- (message as { approval?: { otherProfile?: { id?: string } } }).approval?.otherProfile,- (message as { approval?: { botProfile?: { id?: string } } }).approval?.botProfile,- (message as { approval?: { waitingOnProfile?: { id?: string } } }).approval?.waitingOnProfile,- ]) {- if (profile?.id) referencedProfileIds.add(profile.id)- }+ for (const id of messageProfileIds(message)) referencedProfileIds.add(id)}- for (const item of retainedAttentionItems) referencedProfileIds.add(item.actorUserId)+ for (const item of retainedAttentionItems) if (item.actorUserId) referencedProfileIds.add(item.actorUserId)const windowed: Partial<Record<CommunityCollectionName, unknown[]>> = {...Object.fromEntries(canonical),- categories: ((canonical.get("categories") ?? []) as Array<{ serverId: string }>).filter(+ categories: rows("categories").filter((row) => retainedServerIds.has(row.serverId),),channels: retainedChannels,serverMemberships: retainedServerMemberships,channelMemberships: retainedChannelMemberships,messages: retainedMessages,+ readStates: rows("readStates").filter((row) => !retired.has(row.channelId)),+ notificationSettings: rows("notificationSettings").filter((row) => !row.channelId || !retired.has(row.channelId)),attentionScopes,attentionItems: retainedAttentionItems,- profiles: ((canonical.get("profiles") ?? []) as Array<{ userId: string }>).filter(+ profiles: rows("profiles").filter((row) => referencedProfileIds.has(row.userId),),}@@ -252,7 +203,7 @@ function publishCacheInvalidation() {cacheInvalidation.setState((version) => version + 1)try { if (typeof localStorage !== "undefined") localStorage.setItem(CACHE_INVALIDATION_STORAGE_KEY, crypto.randomUUID()) } catch {}}-export type QualifiedPersister = Persister & { isCurrent: () => Promise<boolean>; retireAccount: () => Promise<void> }+export type QualifiedPersister = Persister & { isCurrent: () => Promise<boolean>; retireAccount: () => Promise<void>; retireChannels: (ids: Iterable<string>, deleted?: boolean) => Promise<void> }function blobKeyFor(userId: string | null, domain: PersistDomain = "community"): string {return `${namespaceFor(userId)}${domain === "application" ? ":application" : ""}:client`}@@ -279,7 +230,27 @@ const cacheStore = createStore("keyval-store", "keyval")const DEVICE_EPOCH_KEY = "alook:qc:device-epoch"const scopeEpochKey = (key: string) => `${key}:epoch`const accountEpochKey = (userId: string | null) => `${namespaceFor(userId)}:account-epoch`-type PersistEligibility = { device: string; scope: string; account: string }+type ChannelDiskFence = { epoch: string; deleted: boolean }+type PersistEligibility = { device: string; scope: string; account: string; channels: Map<string, ChannelDiskFence> }+const channelFenceKey = (userId: string | null) => `${accountEpochKey(userId)}:channels`+const isChannelFences = (value: unknown): value is Map<string, ChannelDiskFence> => (+ value instanceof Map && [...value].every(([id, fence]) => typeof id === "string" && id.length > 0+ && fence !== null && typeof fence === "object" && isEpoch(fence.epoch) && typeof fence.deleted === "boolean")+)+function changedChannelFences(current: Map<string, ChannelDiskFence>, expected: Map<string, ChannelDiskFence>) {+ return new Map([...current].filter(([id, fence]) => fence.epoch !== expected.get(id)?.epoch))+}+function decodeDiskSnapshot(raw: unknown) {+ try {+ if (typeof raw !== "string") return undefined+ const { version, channelFences, ...snapshot } = JSON.parse(raw) as PersistedClient & { version?: unknown; channelFences?: unknown }+ if (version !== PERSIST_VERSION || snapshot.buster !== PERSIST_BUSTER || !Array.isArray(channelFences)+ || !channelFences.every((entry) => Array.isArray(entry) && entry.length === 2)) return undefined+ const fences = new Map(channelFences)+ return isChannelFences(fences) ? { snapshot, fences } : undefined+ } catch { return undefined }+}+const isEpoch = (value: unknown): value is string => (typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value))@@ -302,12 +273,13 @@ async function cacheTransaction<T>(}async function readEligibility(store: IDBObjectStore, key: string, userId: string | null) {- const [device, scope, account] = await Promise.all([+ const [device, scope, account, channels] = await Promise.all([promisifyRequest<unknown>(store.get(DEVICE_EPOCH_KEY)),promisifyRequest<unknown>(store.get(scopeEpochKey(key))),promisifyRequest<unknown>(store.get(accountEpochKey(userId))),+ promisifyRequest<unknown>(store.get(channelFenceKey(userId))),])- return { device, scope, account }+ return { device, scope, account, channels }}// Qualification starts when the account owner is created, before restore or@@ -315,11 +287,18 @@ async function readEligibility(store: IDBObjectStore, key: string, userId: strin// writer or trusts its payload; generation tombstones survive payload removal.function qualifyPersister(key: string, userId: string | null): Promise<PersistEligibility> {return cacheTransaction("readwrite", async (store) => {+ await clearAccountRows(store, userId, true)+ const raw = await promisifyRequest<unknown>(store.get(key))+ if (raw !== undefined) {+ if (!decodeDiskSnapshot(raw)) await clearAccountRows(store, userId)+ }const current = await readEligibility(store, key, userId)const device = isEpoch(current.device) ? current.device : crypto.randomUUID()- const account = isEpoch(current.account) ? current.account : crypto.randomUUID()+ const intact = isEpoch(current.account) && isChannelFences(current.channels)+ const account = intact ? current.account as string : crypto.randomUUID()+ const channels = intact ? current.channels as Map<string, ChannelDiskFence> : new Map<string, ChannelDiskFence>()let scope = isEpoch(current.scope) ? current.scope : crypto.randomUUID()- if (!isEpoch(current.account)) {+ if (!intact) {for (const domain of ["community", "application"] as const) {const payloadKey = blobKeyFor(userId, domain)const epoch = crypto.randomUUID()@@ -328,11 +307,12 @@ function qualifyPersister(key: string, userId: string | null): Promise<PersistElif (payloadKey === key) scope = epoch}store.put(account, accountEpochKey(userId))+ store.put(channels, channelFenceKey(userId))}if (!isEpoch(current.device) || !isEpoch(current.scope)) store.delete(key)if (!isEpoch(current.device)) store.put(device, DEVICE_EPOCH_KEY)store.put(scope, scopeEpochKey(key))- return { device, scope, account }+ return { device, scope, account, channels }})}@@ -342,13 +322,13 @@ async function withEligiblePersister<T>(eligibility: Promise<PersistEligibility>,mode: IDBTransactionMode,staleValue: T,- operation: (store: IDBObjectStore) => Promise<T>,+ operation: (store: IDBObjectStore, current: Map<string, ChannelDiskFence>, expected: Map<string, ChannelDiskFence>) => Promise<T>,): Promise<T> {const expected = await eligibilityreturn cacheTransaction(mode, async (store) => {const current = await readEligibility(store, key, userId)- if (current.device !== expected.device || current.scope !== expected.scope || current.account !== expected.account) return staleValue- return operation(store)+ if (current.device !== expected.device || current.scope !== expected.scope || current.account !== expected.account || !isChannelFences(current.channels)) return staleValue+ return operation(store, current.channels, expected.channels)})}@@ -361,12 +341,16 @@ export function createIdbPersister(userId: string | null): QualifiedPersister {void eligibility.catch(() => undefined)const persister = createAsyncStoragePersister({storage: {- getItem: () => observeRestoreRead(() => withEligiblePersister(key, userId, eligibility, "readonly", null, async (store) => {- const value = await promisifyRequest<unknown>(store.get(key))- return typeof value === "string" ? value : null+ getItem: () => observeRestoreRead(() => withEligiblePersister(key, userId, eligibility, "readwrite", null, async (store, current) => {+ const decoded = decodeDiskSnapshot(await promisifyRequest<unknown>(store.get(key)))+ if (!decoded) store.delete(key)+ return decoded ? JSON.stringify(scrubDehydratedClient(decoded.snapshot, userId, changedChannelFences(current, decoded.fences))) : null}), persister),setItem: (_k: string, value: string) => withEligiblePersister(- key, userId, eligibility, "readwrite", undefined, async (store) => { store.put(value, key) },+ key, userId, eligibility, "readwrite", undefined, async (store, current, expected) => {+ const snapshot = scrubDehydratedClient(JSON.parse(value) as PersistedClient, userId, changedChannelFences(current, expected))+ store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, channelFences: [...current] }), key)+ },),// Expiry/buster removal removes only this payload. It does not retire// the owner, so its subsequent fresh network results can persist.@@ -380,6 +364,7 @@ export function createIdbPersister(userId: string | null): QualifiedPersister {})return Object.assign(persister, {isCurrent: () => withEligiblePersister(key, userId, eligibility, "readonly", false, async () => true),+ retireChannels: (ids: Iterable<string>, deleted = false) => withEligiblePersister(key, userId, eligibility, "readwrite", undefined, (store, current) => retireChannelRows(store, key, userId, current, ids, deleted)),retireAccount: async () => {const retired = await withEligiblePersister(key, userId, eligibility, "readwrite", false, async (store) => { await clearAccountRows(store, userId); return true })if (retired) publishCacheInvalidation()@@ -387,12 +372,15 @@ export function createIdbPersister(userId: string | null): QualifiedPersister {})}-async function clearAccountRows(store: IDBObjectStore, userId: string | null): Promise<void> {- store.put(crypto.randomUUID(), accountEpochKey(userId))- for (const domain of ["community", "application"] as const) {- const key = blobKeyFor(userId, domain)- store.put(crypto.randomUUID(), scopeEpochKey(key))- store.delete(key)+async function clearAccountRows(store: IDBObjectStore, userId: string | null, legacyOnly = false): Promise<void> {+ if (!legacyOnly) {+ store.put(crypto.randomUUID(), accountEpochKey(userId))+ store.put(new Map(), channelFenceKey(userId))+ for (const domain of ["community", "application"] as const) {+ const key = blobKeyFor(userId, domain)+ store.put(crypto.randomUUID(), scopeEpochKey(key))+ store.delete(key)+ }}await new Promise<void>((resolve, reject) => {const request = store.openCursor()@@ -400,12 +388,31 @@ async function clearAccountRows(store: IDBObjectStore, userId: string | null): Prequest.onsuccess = () => {const cursor = request.resultif (!cursor) { resolve(); return }- if (isPersistedCacheBlobKey(cursor.key) && cursor.key.split(":")[3] === (userId ?? "anon")) cursor.delete()+ const match = typeof cursor.key === "string" && /^(alook:qc:[^:]+):([^:]+):((?:application:)?client(?::epoch)?|account-epoch(?::channels)?)$/.exec(cursor.key)+ if (match && match[2] === (userId ?? "anon") && (!legacyOnly || match[1] !== IDB_PREFIX)) {+ if (match[3] === "account-epoch:channels") cursor.update(new Map())+ else if (match[3]?.endsWith("epoch")) cursor.update(crypto.randomUUID())+ else cursor.delete()+ }cursor.continue()}})}+async function retireChannelRows(store: IDBObjectStore, key: string, userId: string | null, current: Map<string, ChannelDiskFence>, ids: Iterable<string>, deleted: boolean) {+ const scopes = [...ids]+ if (!scopes.length) return+ await clearAccountRows(store, userId, true)+ const fences = new Map(current)+ for (const id of scopes) fences.set(id, { epoch: crypto.randomUUID(), deleted: deleted || fences.get(id)?.deleted === true })+ store.put(fences, channelFenceKey(userId))+ const decoded = decodeDiskSnapshot(await promisifyRequest<unknown>(store.get(key)))+ if (decoded) {+ const snapshot = scrubDehydratedClient(decoded.snapshot, userId, changedChannelFences(fences, decoded.fences))+ store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, channelFences: [...fences] }), key)+ } else store.delete(key)+}+export async function clearPersistedCache(userId: string | null): Promise<void> {await cacheTransaction("readwrite", (store) => clearAccountRows(store, userId))publishCacheInvalidation()@@ -429,8 +436,9 @@ export async function getPersistedCacheSizeBytes(signal?: AbortSignal): Promise<}))if (signal?.aborted) throw new DOMException("Cancelled cache size read", "AbortError")const legacyBytes = await getLegacyChatCacheSizeBytes(signal)+ const publicBytes = await getPublicWorkerCacheSizeBytes(signal)if (signal?.aborted) throw new DOMException("Cancelled cache size read", "AbortError")- return bytes + legacyBytes+ return bytes + legacyBytes + publicBytes}/** Clear this device, including qualified writers with no payload yet. */@@ -446,5 +454,8 @@ export async function clearAllPersistedCaches(): Promise<void> {cursor.continue()}}))- try { await clearLegacyChatCaches() } finally { publishCacheInvalidation() }+ try {+ const results = await Promise.allSettled([clearLegacyChatCaches(), clearPublicWorkerCaches()])+ for (const result of results) if (result.status === "rejected") throw result.reason+ } finally { publishCacheInvalidation() }}diff --git a/src/web/src/lib/sdk-identity-retirement.dom.test.tsx b/src/web/src/lib/sdk-identity-retirement.dom.test.tsxindex 65e8cd400..4c54caca9 100644--- a/src/web/src/lib/sdk-identity-retirement.dom.test.tsx+++ b/src/web/src/lib/sdk-identity-retirement.dom.test.tsx@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act, render, waitFor } from "@/test/react-dom-harness"import { PublicQueryProvider, useApplicationOwner, type ApplicationOwner } from "./application-owner"import { QueryProvider } from "@/app/c/QueryProvider"-import { clearAllPersistedCaches, createIdbPersister } from "./query-persister"+import { PERSIST_BUSTER, clearAllPersistedCaches, createIdbPersister } from "./query-persister"import { getCommunityDbRegistry, type CommunityDbRegistry } from "./community-db/collections"const sdk = vi.hoisted(() => ({ session: { data: { user: { id: "A" } } as { user: { id: string } } | null, isPending: false, error: null } }))vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => sdk.session }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })@@ -21,7 +21,7 @@ function Root({ kind, id, show = true }: { kind: "application" | "community"; idif (!show) return <p>Other route</p>return kind === "application" ? <PublicQueryProvider><AppProbe /></PublicQueryProvider> : <QueryProvider userId={id}><CommunityProbe /></QueryProvider>}-const payload = { timestamp: Date.now(), buster: "v3", clientState: { queries: [], mutations: [] } }+const payload = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { queries: [], mutations: [] } }beforeEach(async () => { await act(async () => { await clearAllPersistedCaches(); }) ; sdk.session = { data: { user: { id: "A" } }, isPending: false, error: null }; const real = window; vi.stubGlobal("window", new Proxy(real, { get: (target, key) => key === "location" ? { reload: vi.fn(), assign: vi.fn() } : Reflect.get(target, key, target) })) })afterEach(async () => {await act(async () => {@@ -41,7 +41,7 @@ describe.each(["application", "community"] as const)("%s original public SDK ideawait waitFor(() => expect(kind === "application" ? application.userId : community.accountId).toBe("B"))await waitFor(() => expect(view.getByText(kind === "application" ? "Application" : "Community")).toHaveAttribute("data-restoring", "false"))await waitFor(async () => expect(await a.isCurrent()).toBe(false))- expect(await get("alook:qc:v2:A:client")).toBeUndefined(); expect(await get("alook:qc:v2:B:client")).toBe("old B"); expect(await b.isCurrent()).toBe(true)+ expect(await get("alook:qc:v2:A:client")).toBeUndefined(); expect(await get("alook:qc:v2:B:client")).toBeUndefined(); expect(await b.isCurrent()).toBe(true); expect((await b.restoreClient())?.timestamp).toBe(payload.timestamp)expect(kind === "application" ? (old as ApplicationOwner).lifecycle.get().active : (old as CommunityDbRegistry).runtime.lifecycle.get().active).toBe(false)})it("keeps same-viewer disk eligibility through ordinary route unmount", async () => {diff --git a/src/web/src/lib/sdk-public-identity.dom.test.tsx b/src/web/src/lib/sdk-public-identity.dom.test.tsxindex 214146e55..229a94748 100644--- a/src/web/src/lib/sdk-public-identity.dom.test.tsx+++ b/src/web/src/lib/sdk-public-identity.dom.test.tsx@@ -3,7 +3,7 @@ import "fake-indexeddb/auto"import React from "react"import { beforeAll, afterAll, describe, expect, it, vi } from "vitest"import { act, render, waitFor } from "@/test/react-dom-harness"-import { createIdbPersister, clearAllPersistedCaches } from "./query-persister"+import { createIdbPersister, PERSIST_BUSTER, clearAllPersistedCaches } from "./query-persister"import { get, set } from "idb-keyval"import { useQueryClient, useIsRestoring } from "@tanstack/react-query"import { getCommunityDbRegistry, type CommunityDbRegistry } from "./community-db/collections"@@ -47,11 +47,11 @@ describe("real BetterAuth public session input", () => {await waitFor(() => expect(restoring.A).toBe(false))await waitFor(() => expect(auth.authClient.$store.atoms.session.get()).toMatchObject({ isPending: false, error: null, data: { user: { id: "A" } } }))const a = createIdbPersister("A"), b = createIdbPersister("B")- await act(async () => { await a.restoreClient(); }) ; await act(async () => { await b.restoreClient(); }) ; await act(async () => { await set("alook:qc:v2:A:client", "old A"); }) ; await act(async () => { await set("alook:qc:v2:B:client", "old B") })+ await act(async () => { await a.restoreClient(); }) ; await act(async () => { await b.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { queries: [], mutations: [] } }); }) ; await act(async () => { await set("alook:qc:v2:A:client", "old A"); }) ; await act(async () => { await set("alook:qc:v2:B:client", "old B") })await act(async () => { const result = await auth.authClient.signIn.email({ email: "[email protected]", password: "fixture-password" }); expect(result.error).toBeNull() })await waitFor(() => expect(owners.A.sessionViewer()).toBe("B"))await waitFor(async () => expect(await a.isCurrent()).toBe(false))- expect(await get("alook:qc:v2:A:client")).toBeUndefined(); expect(await get("alook:qc:v2:B:client")).toBe("old B")+ expect(await get("alook:qc:v2:A:client")).toBeUndefined(); expect(await get("alook:qc:v2:B:client")).toBeUndefined(); expect(await b.restoreClient()).toMatchObject({ buster: PERSIST_BUSTER })await act(async () => view.rerender(<Root />))await waitFor(() => expect(restoring.B).toBe(false))await waitFor(() => expect(owners.B?.sessionViewer()).toBe("B")); expect(owners.B.lifecycle.get().active).toBe(true); expect(await b.isCurrent()).toBe(true)diff --git a/src/web/src/lib/service-worker/cache-identity.ts b/src/web/src/lib/service-worker/cache-identity.tsnew file mode 100644index 000000000..3563c925b--- /dev/null+++ b/src/web/src/lib/service-worker/cache-identity.ts@@ -0,0 +1,10 @@+const publicCacheIdentity = { namespace: "alook-public-", version: "v1" } as const++export function publicWorkerCacheNames() {+ return { cacheId: `${publicCacheIdentity.namespace}${publicCacheIdentity.version}`,+ precache: `${publicCacheIdentity.namespace}precache-${publicCacheIdentity.version}` }+}++export function isPublicWorkerCacheName(name: string) {+ return name.startsWith(publicCacheIdentity.namespace)+}diff --git a/src/web/src/lib/service-worker/public-cache-storage.test.ts b/src/web/src/lib/service-worker/public-cache-storage.test.tsnew file mode 100644index 000000000..e516f9486--- /dev/null+++ b/src/web/src/lib/service-worker/public-cache-storage.test.ts@@ -0,0 +1,97 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import { publicWorkerCacheNames } from "./cache-identity"+import { clearOutdatedPublicWorkerCaches, clearPublicWorkerCaches, getPublicWorkerCacheSizeBytes } from "./public-cache-storage"++function fixture() {+ const response = new Response("你好")+ const entries = new Map(["alook-public-precache-v0", "alook-public-precache-v1", "alook-public-v99-runtime", "unrelated-cache"].map((name) => [name, new Map([["https://alook.test/file", response.clone()]])]))+ const storage = { keys: vi.fn(async () => [...entries.keys()]), delete: vi.fn(async (name: string) => entries.delete(name)),+ open: vi.fn(async (name: string) => ({ keys: async () => [...entries.get(name)?.keys() ?? []].map((url) => new Request(url)),+ match: async (request: Request) => entries.get(name)?.get(request.url)?.clone() })) }+ vi.stubGlobal("caches", storage)+ return { entries, storage }+}++afterEach(() => vi.unstubAllGlobals())++describe("owned public worker cache family", () => {+ it("keeps both existing worker names while sizing every version in the owned family", async () => {+ const { storage } = fixture()+ expect(publicWorkerCacheNames()).toEqual({ cacheId: "alook-public-v1", precache: "alook-public-precache-v1" })+ await expect(getPublicWorkerCacheSizeBytes()).resolves.toBe(18)+ expect(storage.open.mock.calls.map(([name]) => name)).toEqual(["alook-public-precache-v0", "alook-public-precache-v1", "alook-public-v99-runtime"])+ })++ it("clears arbitrary past/current/future owned names and leaves unrelated caches", async () => {+ const { entries, storage } = fixture()+ await clearPublicWorkerCaches()+ expect([...entries.keys()]).toEqual(["unrelated-cache"])+ expect(storage.delete).toHaveBeenCalledTimes(3)+ expect(storage.open).not.toHaveBeenCalled()+ })++ it("removes outdated custom names on activation and keeps current precache/runtime names", async () => {+ const { entries, storage } = fixture()+ entries.set("alook-public-v1-runtime-https://example.test/", new Map())+ entries.set("alook-public-v1", new Map())+ entries.set("alook-public-v10-runtime", new Map())+ await clearOutdatedPublicWorkerCaches()+ expect([...entries.keys()]).toEqual(["alook-public-precache-v1", "unrelated-cache", "alook-public-v1-runtime-https://example.test/", "alook-public-v1"])+ expect(storage.delete).toHaveBeenCalledTimes(3)+ })++ it("finishes other owned deletions before reporting a failed deletion", async () => {+ const { entries, storage } = fixture()+ let release!: () => void+ storage.delete.mockImplementation(async name => {+ if (name === "alook-public-precache-v0") throw new Error("old cache occupied")+ if (name === "alook-public-v99-runtime") await new Promise<void>(resolve => { release = resolve })+ return entries.delete(name)+ })+ let settled = false+ const clearing = clearPublicWorkerCaches().finally(() => { settled = true })+ await Promise.resolve()+ await Promise.resolve()+ expect(settled).toBe(false)+ expect(release).toBeTypeOf("function")+ release()+ await expect(clearing).rejects.toThrow("old cache occupied")+ expect([...entries.keys()]).toEqual(["alook-public-precache-v0", "unrelated-cache"])+ })++ it("skips an entry removed during sizing without consuming another response", async () => {+ const { entries } = fixture()+ entries.get("alook-public-precache-v0")!.clear()+ await expect(getPublicWorkerCacheSizeBytes()).resolves.toBe(12)+ })++ it("has no public cache to clear when the browser has no CacheStorage API", async () => {+ vi.stubGlobal("caches", undefined)+ await expect(getPublicWorkerCacheSizeBytes()).resolves.toBe(0)+ await expect(clearPublicWorkerCaches()).resolves.toBeUndefined()+ })++ it("propagates enumeration and deletion failures instead of claiming a full clear", async () => {+ const { storage } = fixture()+ const unavailable = new Error("cache enumeration unavailable")+ storage.keys.mockRejectedValue(unavailable)+ await expect(getPublicWorkerCacheSizeBytes()).rejects.toBe(unavailable)+ await expect(clearPublicWorkerCaches()).rejects.toBe(unavailable)+ storage.keys.mockResolvedValue(["alook-public-precache-v1"])+ const failed = new Error("cache deletion failed")+ storage.delete.mockRejectedValue(failed)+ await expect(clearPublicWorkerCaches()).rejects.toBe(failed)+ })++ it("retires an aborted size result both before and after enumeration", async () => {+ const { storage } = fixture()+ const first = new AbortController()+ first.abort()+ await expect(getPublicWorkerCacheSizeBytes(first.signal)).rejects.toMatchObject({ name: "AbortError" })+ expect(storage.keys).not.toHaveBeenCalled()+ const second = new AbortController()+ storage.keys.mockImplementationOnce(async () => { second.abort(); return ["alook-public-precache-v1"] })+ await expect(getPublicWorkerCacheSizeBytes(second.signal)).rejects.toMatchObject({ name: "AbortError" })+ expect(storage.open).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/lib/service-worker/public-cache-storage.ts b/src/web/src/lib/service-worker/public-cache-storage.tsnew file mode 100644index 000000000..f8094188b--- /dev/null+++ b/src/web/src/lib/service-worker/public-cache-storage.ts@@ -0,0 +1,39 @@+import { isPublicWorkerCacheName, publicWorkerCacheNames } from "./cache-identity"++function assertRead(signal?: AbortSignal) {+ if (signal?.aborted) throw new DOMException("Cancelled public cache read", "AbortError")+}++export async function getPublicWorkerCacheSizeBytes(signal?: AbortSignal): Promise<number> {+ assertRead(signal)+ if (typeof caches === "undefined") return 0+ const names = await caches.keys()+ let bytes = 0+ for (const name of names.filter(isPublicWorkerCacheName)) {+ assertRead(signal)+ const cache = await caches.open(name)+ for (const request of await cache.keys()) {+ assertRead(signal)+ const response = await cache.match(request)+ if (response) bytes += (await response.clone().arrayBuffer()).byteLength+ }+ }+ assertRead(signal)+ return bytes+}++async function deletePublicWorkerCaches(keep: (name: string) => boolean): Promise<void> {+ if (typeof caches === "undefined") return+ const names = await caches.keys()+ const results = await Promise.allSettled(names.filter(name => isPublicWorkerCacheName(name) && !keep(name)).map(name => caches.delete(name)))+ for (const result of results) if (result.status === "rejected") throw result.reason+}++export function clearPublicWorkerCaches(): Promise<void> {+ return deletePublicWorkerCaches(() => false)+}++export function clearOutdatedPublicWorkerCaches(): Promise<void> {+ const current = publicWorkerCacheNames()+ return deletePublicWorkerCaches(name => name === current.precache || name === current.cacheId || name.startsWith(`${current.cacheId}-`))+}diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex f5395bdc7..825dcdf3a 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -1,6 +1,13 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"import {COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,+ decodeCommunityBrowserEvent,+ decodeCommunityBrowserEventBatch,+ deriveCommunityDeliveryOperationId,+ encodeCommunityBrowserEventBatch,+ encodeCommunityBrowserEventBatchForContract,+ prepareCommunityDeliveryEvents,+ type CommunityWsEvent,type WsMessage,} from "@alook/shared"import type { UseUserWsOptions } from "./use-user-ws"@@ -250,7 +257,7 @@ describe("useUserWs", () => {})async function mountHook(- onMessage: (msg: WsMessage) => void,+ onMessage: (msg: WsMessage, assertCurrent?: () => void) => void | Promise<void>,options?: UseUserWsOptions,) {// Re-import to get fresh module with fresh mocks@@ -261,6 +268,147 @@ describe("useUserWs", () => {return mod}+ it("requires protocol confirmation before a v2 batch reaches the callback", async () => {+ setupTokenFetch()+ const callback = vi.fn()+ await mountHook(callback)+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok" })+ ws.simulateMessage({ type: "community:events.batch.v2", events: [] })+ await flushPromises()+ expect(callback).not.toHaveBeenCalled()+ })++ const explicitMembership = {+ type: "community:channel.membership.change",+ serverId: "server-1",+ channelId: "channel-1",+ userId: "user-1",+ relation: "notify",+ present: false,+ } as const+ const legacyMembership = {+ type: "community:channel.member_remove",+ serverId: "server-1",+ channelId: "channel-1",+ userId: "user-1",+ } as const++ async function legacyBatch(events: CommunityWsEvent[]) {+ const prepared = await prepareCommunityDeliveryEvents(events)+ if (!prepared.ok) throw new Error("invalid regression events")+ const encoded = await encodeCommunityBrowserEventBatch({+ operationId: await deriveCommunityDeliveryOperationId("protocol-regression"),+ operationDigest: prepared.prepared.digest,+ events,+ })+ if (!encoded.ok) throw new Error("invalid regression batch")+ expect(decodeCommunityBrowserEventBatch(encoded.batch).ok).toBe(true)+ return encoded.batch+ }++ it.each([undefined, 1] as const)("rejects a new membership single without V2 confirmation (%s)", async (contract) => {+ setupTokenFetch()+ const callback = vi.fn()+ await mountHook(callback)+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok", ...(contract === undefined ? {} : { communityContract: contract }) })+ expect(decodeCommunityBrowserEvent(explicitMembership).ok).toBe(true)+ ws.simulateMessage(explicitMembership)+ await flushPromises()+ expect(callback).not.toHaveBeenCalled()+ ws.simulateMessage(legacyMembership)+ expect(callback).toHaveBeenCalledExactlyOnceWith(legacyMembership)+ })++ it.each([undefined, 1] as const)("rejects an entire legacy batch containing a new membership child without V2 confirmation (%s)", async (contract) => {+ const incompatibleBatch = await legacyBatch([legacyMembership, explicitMembership])+ const compatibleBatch = await legacyBatch([legacyMembership])+ setupTokenFetch()+ const callback = vi.fn()+ await mountHook(callback)+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok", ...(contract === undefined ? {} : { communityContract: contract }) })+ ws.simulateMessage(incompatibleBatch)+ await flushPromises()+ expect(callback).not.toHaveBeenCalled()+ ws.simulateMessage(compatibleBatch)+ expect(callback).toHaveBeenCalledExactlyOnceWith(compatibleBatch)+ })++ it("admits new representations and older producer frames after V2 confirmation", async () => {+ const oldBatch = await legacyBatch([legacyMembership])+ const prepared = await prepareCommunityDeliveryEvents([explicitMembership])+ if (!prepared.ok) throw new Error("invalid regression events")+ const newBatch = await encodeCommunityBrowserEventBatchForContract({+ operationId: await deriveCommunityDeliveryOperationId("protocol-regression-v2"),+ prepared: prepared.prepared,+ contract: 2,+ })+ if (!newBatch.ok) throw new Error("invalid regression batch")+ expect(decodeCommunityBrowserEventBatch(newBatch.batch).ok).toBe(true)+ setupTokenFetch()+ const received: WsMessage[] = []+ await mountHook((message) => { received.push(message) })+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok", communityContract: 2 })+ ws.simulateMessage(explicitMembership)+ ws.simulateMessage(legacyMembership)+ ws.simulateMessage(oldBatch)+ ws.simulateMessage(newBatch.batch)+ await flushPromises()+ expect(received).toEqual([explicitMembership, legacyMembership, oldBatch, newBatch.batch])+ })++ it("preserves frame order behind asynchronous v2 admission", async () => {+ setupTokenFetch()+ let release!: () => void+ const gate = new Promise<void>((resolve) => { release = resolve })+ const received: string[] = []+ await mountHook(async (message, assertCurrent) => {+ if (message.type === "community:events.batch.v2") await gate+ assertCurrent?.()+ received.push(message.type)+ })+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok", communityContract: 2 })+ ws.simulateMessage({ type: "community:events.batch.v2", events: [] })+ ws.simulateMessage({ type: "runtime.status", status: "online" })+ await flushPromises()+ expect(received).toEqual([])+ release()+ await flushPromises()+ await vi.waitFor(() => expect(received).toEqual(["community:events.batch.v2", "runtime.status"]))+ })++ it("retires an in-flight admission and queued frames with their original socket", async () => {+ setupTokenFetch()+ let release!: () => void+ const gate = new Promise<void>((resolve) => { release = resolve })+ const received: string[] = []+ await mountHook(async (message, assertCurrent) => {+ await gate+ assertCurrent?.()+ received.push(message.type)+ })+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok", communityContract: 2 })+ ws.simulateMessage({ type: "community:events.batch.v2", events: [] })+ ws.simulateMessage({ type: "runtime.status", status: "online" })+ await flushPromises()+ mockNavigator.onLine = false+ mockWindow.dispatch("offline")+ release()+ await flushPromises()+ expect(received).toEqual([])+ })+it("connect memo is stable — changing onMessage does NOT create a new connect reference", async () => {setupTokenFetch()@@ -307,7 +455,7 @@ describe("useUserWs", () => {ws.simulateMessage({ type: "auth.ok" })expect(ws.sent).toEqual([- JSON.stringify({ type: "auth", token: "tok-123" }),+ JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }),JSON.stringify({ type: "check_daemon_status" }),])expect(onMsg).not.toHaveBeenCalled()@@ -324,7 +472,7 @@ describe("useUserWs", () => {ws.simulateMessage({ type: "auth.ok" })expect(ws.sent).toEqual([- JSON.stringify({ type: "auth", token: "tok-123" }),+ JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }),])expect(onMsg).not.toHaveBeenCalled()})@@ -392,7 +540,7 @@ describe("useUserWs", () => {ws.simulateMessage({ type: "auth.ok" })expect(ws.sent).toEqual([- JSON.stringify({ type: "auth", token: "tok-123" }),+ JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }),JSON.stringify({ type: "check_daemon_status" }),])expect(onMsg).not.toHaveBeenCalled()@@ -1160,7 +1308,7 @@ describe("useUserWs", () => {await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })const first = MockWebSocket.instances[0]!first.simulateOpen()- expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123" }))+ expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }))mockNavigator.onLine = falsemockWindow.dispatch("offline")@@ -1606,7 +1754,7 @@ describe("useUserWs", () => {})const first = MockWebSocket.instances[0]!first.simulateOpen()- expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123" }))+ expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }))mockDocument.visibilityState = "hidden"mockDocument.dispatch("visibilitychange")diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 33b4ac4bb..c544bda45 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -2,6 +2,9 @@import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"import { useEffect, useRef, useCallback } from "react"import {+ COMMUNITY_CONTRACT_VERSION,+ type CommunityContract,+ communityBrowserEventBatchType,COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,COMMUNITY_BROWSER_EVENT_MAX_BYTES,isCommunityBrowserEventBatchCandidate,@@ -168,7 +171,7 @@ function reportDroppedFrame(}export function useUserWs(- onMessage: (msg: WsMessageIncoming) => void,+ onMessage: (msg: WsMessageIncoming, assertCurrent?: () => void) => void | Promise<void>,options?: UseUserWsOptions,): { send: (msg: object) => void; reconnectNow: () => void } {const wsRef = useRef<WebSocket | null>(null)@@ -608,6 +611,9 @@ export function useUserWs(trackCommunityWsAuthFailure({ failureClass })}+ let communityContract: CommunityContract = 1+ let communityAdmission = Promise.resolve()+ let pendingAdmissions = 0let ws: WebSockettry {if (generation !== connectionGenerationRef.current || isOffline()) return@@ -645,7 +651,7 @@ export function useUserWs(openedAt = Date.now()reportOpenStage("success")try {- ws.send(JSON.stringify({ type: "auth", token: authToken }))+ ws.send(JSON.stringify({ type: "auth", token: authToken, communityContract: COMMUNITY_CONTRACT_VERSION }))} catch {reportAuthStage("failure")reportAuthFailure("network")@@ -710,6 +716,7 @@ export function useUserWs(reportDroppedFrame("duplicate-auth-ok", msg)return}+ communityContract = msg.communityContract === COMMUNITY_CONTRACT_VERSION ? COMMUNITY_CONTRACT_VERSION : 1reportAuthStage("success")authenticatedGenerationRef.current = generationif (connectTimeoutRef.current !== null) {@@ -763,8 +770,31 @@ export function useUserWs(return}}+ if (communityContract !== COMMUNITY_CONTRACT_VERSION && (+ msg.type === communityBrowserEventBatchType()+ || msg.type === "community:channel.membership.change"+ || (isCommunityBatch && Array.isArray(msg.events) && msg.events.some((event: unknown) =>+ isCommunityEventCandidate(event) && event.type === "community:channel.membership.change"))+ )) {+ reportDroppedFrame("invalid-payload", msg)+ return+ }+ const callback = onMessageRef.current+ const assertAdmissionCurrent = () => {+ if (!ownsAuthenticatedConnection(ws, generation) || isOffline() || callback !== onMessageRef.current) throw new DOMException("Retired WebSocket admission", "AbortError")+ }+ if (msg.type === communityBrowserEventBatchType() || pendingAdmissions > 0) {+ if (pendingAdmissions >= 32) { ws.close(1011, "Community admission overloaded"); return }+ pendingAdmissions+++ communityAdmission = communityAdmission.then(async () => {+ if (!ownsAuthenticatedConnection(ws, generation) || isOffline() || callback !== onMessageRef.current) return+ await callback(msg as WsMessageIncoming, assertAdmissionCurrent)+ }).catch(() => { reportDroppedFrame("invalid-payload", msg) }).finally(() => { pendingAdmissions-- })+ return+ }try {- onMessageRef.current(msg as WsMessageIncoming)+ const callbackResult = callback(msg as WsMessageIncoming)+ if (callbackResult) void callbackResult.catch(() => reportDroppedFrame("invalid-payload", msg))} catch {console.warn("[ws] message callback threw", {type: /^[a-z0-9_.:-]+$/i.test(msg.type) && msg.type.length <= 96 ? msg.type : "unknown",diff --git a/src/web/src/stores/community/message-stream-store.ts b/src/web/src/stores/community/message-stream-store.tsindex 73869ca35..c655763a3 100644--- a/src/web/src/stores/community/message-stream-store.ts+++ b/src/web/src/stores/community/message-stream-store.ts@@ -5,15 +5,15 @@ import {getOutboxRetryPayload,reduceMessageOverlay,type MessageOverlayEvent,- type MessageOverlayState,+ type MessageOverlayIds,+ emptyMessageOverlay,type MessageScope,type NewOutboxIntent,type OutboxRetryPayload,type CanonicalMessage,} from "@/lib/community/message-stream"-type StoredOverlay = { liveIds: readonly string[]; outboxByNonce: MessageOverlayState["outboxByNonce"] }-type ScopeEntry = { scope: MessageScope; state: StoredOverlay }+type ScopeEntry = { scope: MessageScope; state: MessageOverlayIds }type MessageStreamStoreState = {entries: ReadonlyMap<string, ScopeEntry>@@ -24,17 +24,8 @@ type MessageStreamStoreState = {removeScope: (scope: MessageScope) => voidremoveServer: (serverId: string) => voidresetAll: () => void- overlayFor: (scope: MessageScope) => MessageOverlayState-}-export const EMPTY_STORED: StoredOverlay = { liveIds: [], outboxByNonce: new Map() }--export function hydrate(state: StoredOverlay, messages: ReadonlyMap<string, CanonicalMessage>): MessageOverlayState {- return { liveById: new Map(state.liveIds.flatMap((id) => { const message = messages.get(id); return message ? [[id, message] as const] : [] })), outboxByNonce: state.outboxByNonce }-}--function storeOverlay(state: MessageOverlayState): StoredOverlay {- return { liveIds: [...state.liveById.keys()], outboxByNonce: state.outboxByNonce }}+export const EMPTY_STORED = emptyMessageOverlay()export function messageScopeKey(scope: Pick<MessageScope, "kind" | "id">): string {return `${scope.kind}:${scope.id}`@@ -44,13 +35,13 @@ function executeEffects(effects: ReturnType<typeof reduceMessageOverlay>["effectfor (const effect of effects) URL.revokeObjectURL(effect.url)}-export function createMessageStreamStore(readMessages: () => ReadonlyMap<string, CanonicalMessage> = () => new Map(), diagnosticOwner?: object) {+export function createMessageStreamStore(readMessages: () => Pick<ReadonlyMap<string, CanonicalMessage>, "get"> = () => new Map(), diagnosticOwner?: object) {return createStore({ entries: new Map<string, ScopeEntry>() as ReadonlyMap<string, ScopeEntry>, nextOrdinal: 1 }, ({ setState, get }): Omit<MessageStreamStoreState, "entries" | "nextOrdinal"> => ({accept: (scope, intent) => {const key = messageScopeKey(scope)const current = get()- const overlay = hydrate(current.entries.get(key)?.state ?? EMPTY_STORED, readMessages())+ const overlay = current.entries.get(key)?.state ?? EMPTY_STOREDif (overlay.outboxByNonce.has(intent.nonce)) return falseconst transition = reduceMessageOverlay(overlay, {type: "submit",@@ -58,7 +49,7 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,})beginMessageObservation(diagnosticOwner, intent.nonce, scope.kind)const entries = new Map(current.entries)- entries.set(key, { scope, state: storeOverlay(transition.state) })+ entries.set(key, { scope, state: transition.state })setState((state) => ({ ...state, ...{ entries, nextOrdinal: current.nextOrdinal + 1 } }))executeEffects(transition.effects)messageMilestone(diagnosticOwner, intent.nonce, "optimistic", "success")@@ -68,14 +59,14 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,dispatch: (scope, event) => {const key = messageScopeKey(scope)const current = get()- const overlay = hydrate(current.entries.get(key)?.state ?? EMPTY_STORED, readMessages())+ const overlay = current.entries.get(key)?.state ?? EMPTY_STOREDif (event.type === "retry" && overlay.outboxByNonce.has(event.nonce)) beginMessageObservation(diagnosticOwner, event.nonce, scope.kind)const applied = event.type === "postAck" ? { type: "wsMessage" as const, message: { ...event.message, clientNonce: event.nonce } } : eventif (applied.type === "wsMessage") sourceEvidence(applied.message, event.type === "postAck" ? "network" : "ws")- const transition = reduceMessageOverlay(overlay, applied)+ const transition = reduceMessageOverlay(overlay, applied, readMessages())if (transition.state !== overlay) {const entries = new Map(current.entries)- entries.set(key, { scope, state: storeOverlay(transition.state) })+ entries.set(key, { scope, state: transition.state })setState((state) => ({ ...state, ...{ entries } }))}executeEffects(transition.effects)@@ -90,7 +81,7 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,getRetryPayload: (scope, nonce) => {const entry = get().entries.get(messageScopeKey(scope))- return entry ? getOutboxRetryPayload(hydrate(entry.state, readMessages()), nonce) : undefined+ return entry ? getOutboxRetryPayload(entry.state, nonce) : undefined},removeScope: (scope) => {@@ -98,7 +89,7 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,const current = get()const entry = current.entries.get(key)if (!entry) return- const transition = reduceMessageOverlay(hydrate(entry.state, readMessages()), { type: "clear" })+ const transition = reduceMessageOverlay(entry.state, { type: "clear" })const entries = new Map(current.entries)entries.delete(key)setState((state) => ({ ...state, ...{ entries } }))@@ -112,7 +103,7 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,let changed = falsefor (const [key, entry] of current.entries) {if (entry.scope.kind !== "channel" || entry.scope.serverId !== serverId) continue- effects.push(...reduceMessageOverlay(hydrate(entry.state, readMessages()), { type: "clear" }).effects)+ effects.push(...reduceMessageOverlay(entry.state, { type: "clear" }).effects)entries.delete(key)changed = true}@@ -123,11 +114,10 @@ export function createMessageStreamStore(readMessages: () => ReadonlyMap<string,resetAll: () => {const current = get()const effects = [...current.entries.values()].flatMap((entry) =>- reduceMessageOverlay(hydrate(entry.state, readMessages()), { type: "clear" }).effects)+ reduceMessageOverlay(entry.state, { type: "clear" }).effects)setState((state) => ({ ...state, ...{ entries: new Map(), nextOrdinal: 1 } }))executeEffects(effects)if (diagnosticOwner) disposeMessageObservations(diagnosticOwner)},- overlayFor: (scope) => hydrate(get().entries.get(messageScopeKey(scope))?.state ?? EMPTY_STORED, readMessages()),}))}diff --git a/src/web/src/stores/community/message-stream.ts b/src/web/src/stores/community/message-stream.tsindex ddf8aa67a..1fb904260 100644--- a/src/web/src/stores/community/message-stream.ts+++ b/src/web/src/stores/community/message-stream.ts@@ -1,22 +1,13 @@"use client"import { useSelector } from "@tanstack/react-store"-import type { QueryClient } from "@tanstack/react-query"-import { useMemo } from "react"-import { getCommunityRuntime, useCommunityRuntime } from "./runtime"-import { useMessageProjection } from "@/lib/community-db/projections"-import type { MessageOverlayState, MessageScope, CanonicalMessage } from "@/lib/community/message-stream"-import { EMPTY_STORED, hydrate, messageScopeKey } from "./message-stream-store"+import { useCommunityRuntime } from "./runtime"+import type { MessageScope } from "@/lib/community/message-stream"+import { EMPTY_STORED, messageScopeKey } from "./message-stream-store"export { createMessageStreamStore } from "./message-stream-store"-export function getMessageOverlay(queryClient: QueryClient, scope: MessageScope): MessageOverlayState {- return getCommunityRuntime(queryClient).messageStream.actions.overlayFor(scope)-}--export function useMessageOverlay(scope: MessageScope): MessageOverlayState {+export function useMessageOverlayIds(scope: MessageScope) {const key = messageScopeKey(scope)- const state = useSelector(useCommunityRuntime().messageStream, (current) => current.entries.get(key)?.state ?? EMPTY_STORED)- const messages = useMessageProjection(scope.id, state.liveIds)- return useMemo(() => hydrate(state, new Map((messages ?? []).flatMap((message) => typeof message.seq === "number" ? [[message.id, message as CanonicalMessage] as const] : []))), [state, messages])+ return useSelector(useCommunityRuntime().messageStream, (current) => current.entries.get(key)?.state ?? EMPTY_STORED)}diff --git a/src/web/src/stores/community/ws-store.ts b/src/web/src/stores/community/ws-store.tsindex 0b47f831f..2a97a34f5 100644--- a/src/web/src/stores/community/ws-store.ts+++ b/src/web/src/stores/community/ws-store.ts@@ -1,3 +1,4 @@+import type { Presence as CommunityPresence } from "@/lib/community/models/people"import { createStore } from "@tanstack/store"// Cap the seen-message set to bound memory. Mirrors the current dedup logic@@ -14,7 +15,6 @@ type DeliveryOperationState = {completed: boolean}-type CommunityPresence = "online" | "offline"type CommunityPresenceSnapshot = {viewerId: string | nullaccountEpoch: number@@ -25,7 +25,7 @@ export type CommunityWsConnectionStatus = "connected" | "reconnecting" | "failedconst NOOP_RECONNECT = () => undefinedtype ChannelAccessScope = {- serverId: string+ serverId: string | nullparentChannelId?: string | nullgeneration: numberrevoked: boolean@@ -35,13 +35,13 @@ type CommunityWsStoreState = {accessEpoch: numberchannelAccessScopes: Map<string, ChannelAccessScope>revokedServerIds: Set<string>- beginChannelMembershipChange: (serverId: string, channelId: string) => number+ beginChannelMembershipChange: (serverId: string | null, channelId: string) => numberobserveChannelScope: (serverId: string, channelId: string, parentChannelId?: string | null) => void- rememberChannelAccess: (serverId: string, channelId: string, parentChannelId?: string | null) => void- revokeChannelAccess: (serverId: string, channelId: string) => string[]+ rememberChannelAccess: (serverId: string | null, channelId: string, parentChannelId?: string | null) => void+ revokeChannelAccess: (serverId: string | null, channelId: string) => string[]revokeServerAccess: (serverId: string) => voidgrantServerAccess: (serverId: string) => void- isChannelAccessRevoked: (channelId: string, serverId?: string, parentChannelId?: string) => boolean+ isChannelAccessRevoked: (channelId: string, serverId?: string | null, parentChannelId?: string) => booleanaccessConnected: booleanconnectionStatus: CommunityWsConnectionStatusreconnectNow: () => void@@ -220,7 +220,7 @@ export function createCommunityWsStore(viewerId: string | null) {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 })+ scopes.set(channelId, { ...previous, serverId, revoked: false, generation })setState((state) => ({ ...state, ...{ channelAccessScopes: scopes } }))return generation},@@ -252,9 +252,9 @@ export function createCommunityWsStore(viewerId: string | null) {}for (const id of affected) {const previous = scopes.get(id)- scopes.set(id, { serverId, ...previous, generation: (previous?.generation ?? 0) + 1, revoked: true })+ scopes.set(id, { serverId, ...previous, generation: (previous?.generation ?? 0) + (previous?.revoked ? 0 : 1), revoked: true })}- setState((state) => ({ ...state, ...{ channelAccessScopes: scopes, accessEpoch: get().accessEpoch + 1 } }))+ setState((state) => ({ ...state, ...{ channelAccessScopes: scopes } }))return [...affected]},diff --git a/src/web/src/test/community-loading-geometry-lanes.test.ts b/src/web/src/test/community-loading-geometry-lanes.test.tsnew file mode 100644index 000000000..4b0d7a07a--- /dev/null+++ b/src/web/src/test/community-loading-geometry-lanes.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it, vi } from "vitest"+import type { BrowserContext, Page } from "@playwright/test"+import { runDesktopPersistedPendingGeometry } from "./e2e-ui/_fixtures/community-loading-geometry"++const steps = vi.hoisted(() => vi.fn())+vi.mock("./e2e-ui/_fixtures/community-fixture", async () => {+ const { expect: nativeExpect } = await import("vitest")+ const fixtureExpect = (value: unknown, message?: string) => {+ if (value && typeof value === "object" && "fixtureLocator" in value) {+ const locator = value as { visible: boolean; count: number; attributes: Record<string, string> }+ return {+ toBeVisible: async () => nativeExpect(locator.visible).toBe(true),+ toHaveAttribute: async (name: string, expected: string) => nativeExpect(locator.attributes[name]).toBe(expected),+ toHaveCount: async (count: number) => nativeExpect(locator.count).toBe(count),+ not: { toHaveCount: async (count: number) => nativeExpect(locator.count).not.toBe(count) },+ }+ }+ return nativeExpect(value, message)+ }+ return {+ test: { step: (label: string, work: () => Promise<void>) => { steps(label); return work() } },+ expect: Object.assign(fixtureExpect, {+ poll: (read: () => number | Promise<number>) => ({ toBeGreaterThan: async (minimum: number) => {+ let actual = 0+ for (let i = 0; i < 100; i++) {+ actual = await read()+ if (actual > minimum) break+ await Promise.resolve()+ }+ nativeExpect(actual).toBeGreaterThan(minimum)+ } }),+ }),+ sessionCookie: () => "", userId: () => "",+ }+})+vi.mock("./e2e-ui/_fixtures/community-ssr-frame", () => ({+ expectUniqueSsrInitialFrame: async (page: Page) => page.getByTestId("fixture-frame"),+}))++type Visit = {+ account: string+ scale: number+ width: number+ sidebar: number | null+ waits: number[]+ events: string[]+ closed: boolean+}+type RequestRoute = { request: () => { url: () => string; method: () => string }; continue: () => Promise<void> }++function fixtureRun(failure?: "navigation" | "overflow" | "empty") {+ const visits: Visit[] = [], active = new Set<string>()+ const originalFailure = new Error("original navigation failure")+ const asUser: Parameters<typeof runDesktopPersistedPendingGeometry>[1] = async (account, options) => {+ expect(active.has(account), "one mutable context per account").toBe(false)+ active.add(account)+ const visit: Visit = { account, scale: options?.deviceScaleFactor ?? 1, width: 0, sidebar: null, waits: [], events: [], closed: false }+ visits.push(visit)+ let sidebarWidth = 317+ const handlers = new Map<string, (route: RequestRoute) => Promise<void>>()+ const listeners = new Map<string, (event: { url: () => string }) => void>()+ const pending: Promise<void>[] = []+ const request = (kind: "script" | "read") => {+ const url = () => kind === "script" ? "https://fixture.test/_next/app.js" : "https://fixture.test/api/community/servers"+ listeners.get("request")?.({ url })+ const handler = handlers.get(kind === "script" ? "**/_next/**" : "**/api/community/**")!+ const operation = handler({ request: () => ({ url, method: () => "GET" }), continue: async () => {+ visit.events.push(`${kind}.continue`)+ listeners.get("response")?.({ url })+ if (kind === "script") request("read")+ } })+ pending.push(operation)+ }+ const locator = (count = 1) => ({+ fixtureLocator: true, visible: true, count,+ attributes: { "aria-busy": "true", "aria-label": "Loading community" },+ locator: () => locator(),+ evaluate: async () => ({ overflow: 0, root: { x: 0, y: 0, width: visit.width, height: 900 } }),+ })+ const page = {+ on: (event: string, listener: (event: { url: () => string }) => void) => listeners.set(event, listener),+ route: async (pattern: string, handler: (route: RequestRoute) => Promise<void>) => { handlers.set(pattern, handler) },+ setViewportSize: async ({ width }: { width: number }) => { visit.width = width },+ emulateMedia: async () => {},+ addInitScript: async (_script: unknown, input: { persistedLayout: { sidebar: number } | null }) => {+ visit.sidebar = input.persistedLayout ? Math.round(input.persistedLayout.sidebar * (visit.width - 59) / 100) : null+ sidebarWidth = visit.sidebar ?? 317+ },+ goto: async () => {+ visit.events.push("navigation")+ request("script")+ if (failure === "navigation" && visits[0] === visit) throw originalFailure+ },+ getByTestId: () => locator(),+ locator: (selector: string) => locator(selector.includes("restore-bootstrap") ? 0 : 1),+ waitForTimeout: async (time: number) => { visit.waits.push(time); visit.events.push("sample.wait") },+ evaluate: async (callback: () => unknown) => {+ if (!callback.toString().includes("__communityDesktopPendingFrameSamples")) return undefined+ visit.events.push("samples")+ if (failure === "empty" && visits[0] === visit) return []+ return [{ overflow: failure === "overflow" && visits[0] === visit ? 3 : 0, sidebarWidth, sidebarRight: 10, mainLeft: 11, userBarRight: 11 }]+ },+ } as unknown as Page+ const context = { close: async () => {+ await Promise.all(pending)+ visit.events.push("close"); visit.closed = true; active.delete(account)+ } } as unknown as BrowserContext+ return { context, page }+ }+ return { visits, active, originalFailure, run: () => runDesktopPersistedPendingGeometry("light", asUser) }+}++describe("geometry fixture account lanes and resource release", () => {+ it("runs all 48 distinct contexts with separate accounts, original gates and one 250ms sample", async () => {+ steps.mockClear()+ const fixture = fixtureRun()+ await fixture.run()+ const expected = [640, 768, 1024, 1280].flatMap(width => [null, 100, 160, 240, 350, 360].flatMap(sidebar => [1, 1.25].map(scale => `${width}:${sidebar}:${scale}`)))+ expect(fixture.visits.map(v => `${v.width}:${v.sidebar}:${v.scale}`).sort()).toEqual(expected.sort())+ expect(fixture.visits.filter(v => v.account === "dave")).toHaveLength(24)+ expect(fixture.visits.filter(v => v.account === "geometry")).toHaveLength(24)+ expect(steps).toHaveBeenCalledTimes(48)+ for (const visit of fixture.visits) {+ expect(visit.waits).toEqual([250])+ expect(visit.events).toEqual(["navigation", "script.continue", "sample.wait", "samples", "read.continue", "close"])+ expect(visit.closed).toBe(true)+ }+ expect(fixture.active.size).toBe(0)+ })++ it.each(["navigation", "overflow", "empty"] as const)("releases gates and awaits the other lane before propagating %s failure", async failure => {+ const fixture = fixtureRun(failure)+ const error = await fixture.run().catch((error: unknown) => error)+ if (failure === "navigation") expect(error).toBe(fixture.originalFailure)+ else expect(error).toBeInstanceOf(Error)+ expect(fixture.visits.filter(v => v.account === "geometry")).toHaveLength(24)+ expect(fixture.visits.filter(v => v.account === "dave")).toHaveLength(1)+ expect(fixture.visits.every(v => v.closed && v.events.includes("script.continue") && v.events.includes("read.continue"))).toBe(true)+ expect(fixture.active.size).toBe(0)+ })+})diff --git a/src/web/src/test/community-query-owner.ts b/src/web/src/test/community-query-owner.tsindex d1f531952..dc61f8f00 100644--- a/src/web/src/test/community-query-owner.ts+++ b/src/web/src/test/community-query-owner.ts@@ -4,8 +4,20 @@ import { QueryClient, type InfiniteData, type QueryKey, type SetDataOptions, typimport { createCommunityDbRegistry, getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { ingestMessages } from "@/lib/community-db/sync"import type { MessagesPage } from "@/hooks/community/use-messages"+import { getCommunityRuntime } from "@/stores/community/runtime"+import { EMPTY_STORED, messageScopeKey } from "@/stores/community/message-stream-store"+import type { MessageScope } from "@/lib/community/message-stream"const owners = new Set<CommunityDbRegistry>()+export function getMessageStreamState(client: QueryClient, scope: MessageScope) {+ return getCommunityRuntime(client).messageStream.get().entries.get(messageScopeKey(scope))?.state ?? EMPTY_STORED+}+export function canonicalMessageReader(client: QueryClient) {+ return { get: (id: string) => {+ const row = getCommunityDbRegistry(client)?.collections.messages.get(id)+ return row && typeof row.seq === "number" ? { ...row, seq: row.seq } : undefined+ } }+}export async function createCommunityQueryOwner(accountId = "viewer", config?: QueryClientConfig) {const client = new QueryClient(config ?? { defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })const registry = createCommunityDbRegistry(client, accountId)diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex a76dd8d5a..1c50b972a 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -3,7 +3,7 @@ import { test, expect, userId, userName } from "./_fixtures/community-fixture"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 { seedDm, seedDmMessage } from "./_fixtures/seed"import { captureNotificationRequests, gotoAfterNotificationStartup, notificationPaths, notificationResponsesFinished } from "./_fixtures/community-notification-requests"import { lastMeLocationKey } from "@/lib/community/last-me-location"@@ -99,6 +99,24 @@ test.describe.serial("direct messages", () => {}})+ let releaseMetadata!: () => void+ let metadataStarted!: () => void+ let metadataFinished!: () => void+ const metadataGate = new Promise<void>(resolve => { releaseMetadata = resolve })+ const metadataRequest = new Promise<void>(resolve => { metadataStarted = resolve })+ const metadataSettled = new Promise<void>(resolve => { metadataFinished = resolve })+ const metadataPattern = (url: URL) => url.pathname === `/api/community/channels/${dmId}`+ await alice.page.route(metadataPattern, async route => {+ if (route.request().method() !== "GET") { await route.continue(); return }+ metadataStarted()+ try {+ await metadataGate+ await route.continue()+ } catch (error) {+ if (!(error instanceof Error && error.message.includes("already handled"))) throw error+ } finally { metadataFinished() }+ })+let releaseRead!: () => voidlet readStarted!: () => voidlet readFinished!: () => void@@ -149,12 +167,26 @@ test.describe.serial("direct messages", () => {const dmTitle = alice.page.getByTestId(tid.dmHeaderTitle)await expect(dmHeader).toHaveCount(1, { timeout: 20_000 })await expect(dmTitle).toContainText(userName("bob"))+ await metadataRequestawait readRequestawait expect(alice.page.locator('[data-onboarding-target="dm-composer"] [data-slot="skeleton"]').first()).toBeVisible()await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)await expect(alice.page.getByTestId(tid.message(messageId))).toHaveCount(0)await expect(alice.page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]')).not.toHaveCount(0)+ const metadataResponse = alice.page.waitForResponse(response => response.request().method() === "GET" && metadataPattern(new URL(response.url())))+ releaseMetadata()+ await metadataSettled+ const permission = await metadataResponse+ expect(permission.status()).toBe(200)+ expect(permission.headers()["x-alook-community-contract"]).toBe("2")+ const resource = await permission.json()+ expect(resource.channel.id).toBe(dmId)+ expect(resource.access).toMatchObject({ channelId: dmId, canRead: true })+ await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()+ await expect(alice.page.getByTestId(tid.message(messageId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]')).not.toHaveCount(0)+releaseRead()await readSettledawait messagesRequest@@ -172,10 +204,13 @@ test.describe.serial("direct messages", () => {await expect(alice.page.getByTestId(tid.message(messageId))).toHaveCount(1)await expect(alice.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })} finally {+ releaseMetadata()releaseRead()releaseMessages()+ await metadataSettledawait readSettledawait messagesSettled+ await alice.page.unroute(metadataPattern)await alice.page.unroute(readPattern)await alice.page.unroute(messagesPattern)}@@ -270,15 +305,40 @@ test.describe.serial("direct messages", () => {})test("blocking replaces the composer with a blocked notice", async ({ asUser }) => {- // Carol blocks Bob, then opens a DM with him: composer is replaced.const dmId = await seedDm("carol", userId("bob"))- await seedBlock("carol", userId("bob"))-+ const body = `visible before block ${Date.now()}`+ const messageId = await seedDmMessage("carol", dmId, body)const carol = await asUser("carol")+ const bob = await asUser("bob")+ const bobProxy = await proxyCommunityWebSockets(bob.context)await carol.page.goto(`/c/me/${dmId}`)- await carol.page.waitForURL(new RegExp(dmId), { timeout: 20_000 , waitUntil: "commit" })+ await bob.page.goto(`/c/me/${dmId}`)+ for (const page of [carol.page, bob.page]) {+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()+ }+ await expect.poll(() => bobProxy.connectionFrames.some((frame) => frame.type === "auth.ok")).toBe(true)+ await carol.page.goto("/c/me/friends")+ const bobRow = carol.page.getByRole("button").filter({ hasText: userName("bob") })+ await expect(bobRow).toHaveCount(1)+ await bobRow.click({ button: "right" })+ const blockResponse = carol.page.waitForResponse((response) => response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/users/${userId("bob")}/block`)+ await carol.page.getByRole("menuitem", { name: "Block", exact: true }).click()+ expect((await blockResponse).status()).toBe(200)+ await expect(bob.page.getByTestId(tid.message(messageId))).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.composerInput)).toHaveCount(0)+ await expect(bob.page.getByRole("alert").filter({ hasText: "You can no longer read this conversation." })).toBeVisible()+ await expect(bob.page.getByRole("alert").filter({ hasText: "Couldn't verify this conversation" })).toHaveCount(0)+ await expect(bob.page.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.dmBlockedNotice)).toHaveCount(0)+ await expect(bob.page).toHaveURL(new RegExp(`/c/me/${dmId}$`))+ await carol.page.getByTestId(tid.dmRow(dmId)).click()await expect(carol.page.getByTestId(tid.dmBlockedNotice)).toBeVisible()await expect(carol.page.getByTestId(tid.composerInput)).toHaveCount(0)+ await expect(carol.page.getByTestId(tid.message(messageId))).toHaveCount(0)+ await expect(carol.page.getByRole("alert").filter({ hasText: "Couldn't verify this conversation" })).toHaveCount(0)+ await expect(carol.page.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0)})})diff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.tsindex 40620de4b..42ca3495d 100644--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts@@ -453,6 +453,8 @@ test.describe.serial("forum sidebar Stage B request shape", () => {}await route.continue()})+ const firstChildMetadata = page.waitForResponse((response) => response.request().method() === "GET"+ && isExactChannelRequest(response.url(), threadId) && response.ok())const clickStartedAt = Date.now()let warmVisibleMs: numbertry {@@ -468,7 +470,13 @@ test.describe.serial("forum sidebar Stage B request shape", () => {await expect(childPanel(page).getByTestId(tid.composerInput)).toBeVisible({ timeout: 1_000 })warmVisibleMs = Date.now() - clickStartedAt- expect(requests.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(0)+ expect(requests.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)+ const metadataResponse = await firstChildMetadata+ expect(metadataResponse.headers()["x-alook-community-contract"]).toBe("2")+ expect(await metadataResponse.json()).toMatchObject({+ channelId: threadId, channel: { id: threadId, serverId, archived: false },+ access: { channelId: threadId, canRead: true },+ })await expect.poll(() => successfulResponses.filter((url) =>new URL(url).pathname === `/api/community/channels/${threadId}/read-state`).length).toBe(1)@@ -492,6 +500,8 @@ test.describe.serial("forum sidebar Stage B request shape", () => {isSidebarRequest(url, serverId)&& new URL(url).searchParams.get("retainId") === threadId))).toHaveLength(1)+ expect(requests.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)+ expect(successfulResponses.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)const threadMessageRequests = requests.filter((url) => (isChannelMessagesRequest(url, threadId)))@@ -521,6 +531,8 @@ test.describe.serial("forum sidebar Stage B request shape", () => {await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`,)+ await page.waitForTimeout(300) // current read proof reuse: no additional metadata validation+ expect(requests.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)})})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 df726f4d4..e7a91c6df 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@@ -12,6 +12,7 @@ import {} from "./_fixtures/seed"import {communityFrameEvents,+ isCommunityBatchFrame,proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"@@ -114,7 +115,7 @@ test.describe.serial("committed message delivery QA", () => {expect(gapRequests.length).toBeGreaterThan(0)expect(proxy.heldCount()).toBe(1)const heldBatch = proxy.frames.find((frame) => messageFrame(frame, channelId, missing))- expect(heldBatch?.type).toBe("community:events.batch")+ expect(heldBatch?.type).toBe("community:events.batch.v2")expect(communityFrameEvents(heldBatch!).some((event) =>event.type === "community:mention.create")).toBe(true)expect(proxy.releaseHeld((frame) => messageFrame(frame, channelId, missing))).toBe(1)@@ -199,7 +200,7 @@ test.describe.serial("committed message delivery QA", () => {if (armed&& !duplicated- && frame.type === "community:events.batch"+ && isCommunityBatchFrame(frame)&& messageFrame(frame, channelId, body)) {duplicated = true@@ -222,11 +223,13 @@ test.describe.serial("committed message delivery QA", () => {await expect.poll(() => duplicated, { timeout: 20_000 }).toBe(true)const batches = proxy.frames.filter((frame) =>- frame.type === "community:events.batch" && messageFrame(frame, channelId, body))+ isCommunityBatchFrame(frame) && messageFrame(frame, channelId, body))expect(batches).toHaveLength(1)const batch = batches[0]!+ expect(batch.type).toBe("community:events.batch.v2")expect(batch.operationId).toMatch(/^message:[A-Za-z0-9_-]{43}$/)expect(batch.operationDigest).toMatch(/^[0-9a-f]{64}$/)+ expect(batch.wireDigest).toMatch(/^[0-9a-f]{64}$/)expect(communityFrameEvents(batch).map((event) => event.type)).toEqual(["community:message.create","community:unread.bump",@@ -275,12 +278,12 @@ test.describe.serial("committed message delivery QA", () => {await editable.pressSequentially(" batch channel")await alice.page.keyboard.press("Enter")await expect.poll(() => firstProxy.frames.slice(firstChannelStart).some((frame) =>- frame.type === "community:events.batch"+ isCommunityBatchFrame(frame)&& communityFrameEvents(frame).some((event) => event.type === "community:mention.create")), {timeout: 20_000,}).toBe(true)await expect.poll(() => secondProxy.frames.slice(secondChannelStart).some((frame) =>- frame.type === "community:events.batch"+ isCommunityBatchFrame(frame)&& communityFrameEvents(frame).some((event) => event.type === "community:mention.create")), {timeout: 20_000,}).toBe(true)@@ -298,8 +301,8 @@ test.describe.serial("committed message delivery QA", () => {await expectMessageVisible(secondBob.page, dmBody)expect(firstProxy.frames.slice(firstDmStart).filter((frame) =>- frame.type === "community:events.batch" && messageFrame(frame, dmId, dmBody))).toHaveLength(1)+ isCommunityBatchFrame(frame) && messageFrame(frame, dmId, dmBody))).toHaveLength(1)expect(secondProxy.frames.slice(secondDmStart).filter((frame) =>- frame.type === "community:events.batch" && messageFrame(frame, dmId, dmBody))).toHaveLength(1)+ isCommunityBatchFrame(frame) && messageFrame(frame, dmId, dmBody))).toHaveLength(1)})})diff --git a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.tsindex 41b738d27..076269ee7 100644--- a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts+++ b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts@@ -223,7 +223,7 @@ test.describe.serial("invite and participant picker async states", () => {let failParticipants = truelet participantGets = 0let parentGets = 0- await page.route(`**/api/community/channels/${failureThreadId}/members`, async (route) => {+ await page.route((url) => url.pathname === `/api/community/channels/${failureThreadId}/members` && url.searchParams.get("relation") === "notify", async (route) => {if (route.request().method() !== "GET") return route.continue()participantGets += 1if (failParticipants) {@@ -232,7 +232,7 @@ test.describe.serial("invite and participant picker async states", () => {}await route.continue()})- await page.route(`**/api/community/channels/${parentChannelId}/members`, async (route) => {+ await page.route((url) => url.pathname === `/api/community/channels/${parentChannelId}/members` && url.searchParams.get("relation") === "access", async (route) => {if (route.request().method() === "GET") parentGets += 1await route.continue()})@@ -267,7 +267,7 @@ test.describe.serial("invite and participant picker async states", () => {await page.setViewportSize({ width: 1280, height: 844 })const parentGate = deferred()let parentGets = 0- await page.route(`**/api/community/channels/${parentChannelId}/members`, async (route) => {+ await page.route((url) => url.pathname === `/api/community/channels/${parentChannelId}/members` && url.searchParams.get("relation") === "access", async (route) => {if (route.request().method() !== "GET") return route.continue()parentGets += 1await parentGate.promise@@ -293,11 +293,11 @@ test.describe.serial("invite and participant picker async states", () => {let failParent = truelet participantGets = 0let parentGets = 0- await page.route(`**/api/community/channels/${parentFailureThreadId}/members`, async (route) => {+ await page.route((url) => url.pathname === `/api/community/channels/${parentFailureThreadId}/members` && url.searchParams.get("relation") === "notify", async (route) => {if (route.request().method() === "GET") participantGets += 1await route.continue()})- await page.route(`**/api/community/channels/${parentChannelId}/members`, async (route) => {+ await page.route((url) => url.pathname === `/api/community/channels/${parentChannelId}/members` && url.searchParams.get("relation") === "access", async (route) => {if (route.request().method() !== "GET") return route.continue()parentGets += 1if (failParent) {diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.tsindex f9cbcee37..39fffa3c6 100644--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts@@ -12,6 +12,7 @@ import {} from "./_fixtures/seed"import {communityFrameEvents,+ isCommunityBatchFrame,proxyCommunityWebSockets,} from "./_fixtures/community-ws-proxy"@@ -238,7 +239,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(await stopWatchingA()).toBe(false)await expect.poll(() => proxy.frames.slice(frameStart).filter((frame) => (- frame.type === "community:events.batch"+ isCommunityBatchFrame(frame)&& communityFrameEvents(frame).some((event) => (event.type === "community:message.create"&& [messageA, messageB, messageDm].includes(event.message?.id ?? "")diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.tsindex 417468676..4691f7522 100644--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts@@ -3,6 +3,7 @@ import { expect, test, userId } from "./_fixtures/community-fixture"import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"import {communityFrameEvents,+ isCommunityBatchFrame,proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"@@ -83,7 +84,7 @@ function hasCorrelatedBundle(channelId: string,) {return frames.some((frame) => {- if (frame.type !== "community:events.batch") return false+ if (!isCommunityBatchFrame(frame)) return falseconst events = communityFrameEvents(frame)return events.some((event) => (event.type === "community:message.create"diff --git a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.tsindex 4ffc2a444..e23330c1d 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts@@ -5,7 +5,7 @@ import type {Page,TestInfo,} from "@playwright/test"-import { expect, sessionCookie, userId } from "./community-fixture"+import { test, expect, sessionCookie, userId } from "./community-fixture"import {COMMUNITY_RAIL_WIDTH,COMMUNITY_SEPARATOR_WIDTH,@@ -594,64 +594,73 @@ export async function runDesktopPersistedPendingGeometry(theme: Theme,asUser: CommunityAsUser,) {- for (const viewportWidth of [640, 768, 1024, 1280] as const) {- for (const sidebarWidth of [null, 100, 160, 240, 350, 360] as const) {- for (const deviceScaleFactor of DESKTOP_DENSITY_SCALES) {- const caseLabel = `${viewportWidth}px @${deviceScaleFactor}x, sidebar ${sidebarWidth ?? "default"}`- const { context, page } = await asUser(ISOLATED_GEOMETRY_USER, {- deviceScaleFactor,- })- await page.setViewportSize({ width: viewportWidth, height: 900 })- await page.emulateMedia({ colorScheme: theme })- await installDesktopPendingFrameProbe(page, viewportWidth, sidebarWidth)- const scripts = await holdApplicationScripts(page)- const communityReads = await holdCommunityReads(page)- await page.goto("/c/me/machines", { waitUntil: "commit" })- await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)- expect(scripts.received).toEqual([])- expect(scripts.sessionRequests()).toBe(0)- await expectServerSeededRouteFrame(page, viewportWidth, 900)- scripts.release()- await expect.poll(communityReads.hits).toBeGreaterThan(0)- await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()- await page.waitForTimeout(250)-- const samples = await desktopPendingFrameSamples(page)- await page.evaluate(() => Reflect.set(- window,- "__communityDesktopPendingFrameProbeStopped",- true,- ))- expect(samples.length, caseLabel).toBeGreaterThan(0)- for (const [index, sample] of samples.entries()) {- expect(sample.overflow, `${caseLabel}, frame ${index} horizontal overflow`).toBe(0)- expect(- Math.abs(sample.userBarRight - sample.mainLeft),- `${caseLabel}, frame ${index} User bar/main boundary: ${JSON.stringify(sample)}`,- ).toBeLessThanOrEqual(1)- const separatorWidth = sample.mainLeft - sample.sidebarRight- expect(- separatorWidth,- `${caseLabel}, frame ${index} separator width: ${JSON.stringify(sample)}`,- ).toBeGreaterThanOrEqual(0)+ const cases = ([640, 768, 1024, 1280] as const).flatMap((viewportWidth) =>+ ([null, 100, 160, 240, 350, 360] as const).flatMap((sidebarWidth) =>+ DESKTOP_DENSITY_SCALES.map((deviceScaleFactor) => ({ viewportWidth, sidebarWidth, deviceScaleFactor }))))+ const results = await Promise.allSettled(([ISOLATED_GEOMETRY_USER, "geometry"] as const).map(async (account, lane) => {+ for (const entry of cases.filter((_, index) => index % 2 === lane)) {+ const { viewportWidth, sidebarWidth, deviceScaleFactor } = entry+ const caseLabel = `${viewportWidth}px @${deviceScaleFactor}x, sidebar ${sidebarWidth ?? "default"}`+ await test.step(caseLabel, async () => {+ const { context, page } = await asUser(account, { deviceScaleFactor })+ let scripts: Awaited<ReturnType<typeof holdApplicationScripts>> | undefined+ let communityReads: Awaited<ReturnType<typeof holdCommunityReads>> | undefined+ try {+ await page.setViewportSize({ width: viewportWidth, height: 900 })+ await page.emulateMedia({ colorScheme: theme })+ await installDesktopPendingFrameProbe(page, viewportWidth, sidebarWidth)+ const scriptGate = await holdApplicationScripts(page)+ scripts = scriptGate+ communityReads = await holdCommunityReads(page)+ await page.goto("/c/me/machines", { waitUntil: "commit" })+ await expect.poll(() => scriptGate.blocked.length).toBeGreaterThan(0)+ expect(scriptGate.received).toEqual([])+ expect(scriptGate.sessionRequests()).toBe(0)+ await expectServerSeededRouteFrame(page, viewportWidth, 900)+ scriptGate.release()+ await expect.poll(communityReads.hits).toBeGreaterThan(0)+ await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()+ await page.waitForTimeout(250)++ const samples = await desktopPendingFrameSamples(page)+ await page.evaluate(() => Reflect.set(+ window,+ "__communityDesktopPendingFrameProbeStopped",+ true,+ ))+ expect(samples.length, caseLabel).toBeGreaterThan(0)+ for (const [index, sample] of samples.entries()) {+ expect(sample.overflow, `${caseLabel}, frame ${index} horizontal overflow`).toBe(0)+ expect(+ Math.abs(sample.userBarRight - sample.mainLeft),+ `${caseLabel}, frame ${index} User bar/main boundary: ${JSON.stringify(sample)}`,+ ).toBeLessThanOrEqual(1)+ const separatorWidth = sample.mainLeft - sample.sidebarRight+ expect(+ separatorWidth,+ `${caseLabel}, frame ${index} separator width: ${JSON.stringify(sample)}`,+ ).toBeGreaterThanOrEqual(0)+ expect(+ separatorWidth,+ `${caseLabel}, frame ${index} separator width: ${JSON.stringify(sample)}`,+ ).toBeLessThanOrEqual(1)+ }+ const expectedSidebarWidth = sidebarWidth === null+ ? COMMUNITY_SIDEBAR_DEFAULT_WIDTH+ : Math.max(COMMUNITY_SIDEBAR_MIN_WIDTH, sidebarWidth)expect(- separatorWidth,- `${caseLabel}, frame ${index} separator width: ${JSON.stringify(sample)}`,- ).toBeLessThanOrEqual(1)+ Math.abs(samples.at(-1)!.sidebarWidth - expectedSidebarWidth),+ `${caseLabel}, final sidebar width: ${JSON.stringify(samples.at(-1))}`,+ ).toBeLessThanOrEqual(ONE_CSS_PIXEL_WITH_LAYOUT_QUANTIZATION)+ } finally {+ scripts?.release()+ communityReads?.release()+ await context.close()}- const expectedSidebarWidth = sidebarWidth === null- ? COMMUNITY_SIDEBAR_DEFAULT_WIDTH- : Math.max(COMMUNITY_SIDEBAR_MIN_WIDTH, sidebarWidth)- expect(- Math.abs(samples.at(-1)!.sidebarWidth - expectedSidebarWidth),- `${caseLabel}, final sidebar width: ${JSON.stringify(samples.at(-1))}`,- ).toBeLessThanOrEqual(ONE_CSS_PIXEL_WITH_LAYOUT_QUANTIZATION)-- communityReads.release()- await context.close()- }+ })}- }+ }))+ for (const result of results) if (result.status === "rejected") throw result.reason}export async function runSkeletonLoadingMotion(asUser: CommunityAsUser) {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.tsindex fa74cdc5d..3be1174a8 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts@@ -28,10 +28,12 @@ export function captureNotificationRequests(page: Page) {page.on("websocket", (socket) => {socket.on("framereceived", ({ payload }) => {try {- const frame = JSON.parse(payload.toString()) as CommunityWsEvent | { type: "community:events.batch"; events: CommunityWsEvent[] }+ const frame = JSON.parse(payload.toString()) as CommunityWsEvent+ | { type: "community:events.batch"; events: CommunityWsEvent[] }+ | { type: "community:events.batch.v2"; 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]) {+ for (const event of frame.type === "community:events.batch" || frame.type === "community:events.batch.v2" ? frame.events : [frame]) {events.push(event)record({ kind: "event", type: event.type,channelId: "channelId" in event ? event.channelId : undefined,diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.tsindex f3c57425d..169a3136e 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts@@ -1,4 +1,5 @@import type { BrowserContext, WebSocketRoute } from "@playwright/test"+import { isCommunityBrowserEventBatchCandidate } from "@alook/shared"export type CapturedCommunityFrame = {type: string@@ -21,6 +22,7 @@ export type CapturedConnectionFrame = {direction: "client-to-server" | "server-to-client"type: "auth" | "auth.ok" | "connection.ping" | "connection.pong" | "raw.ping" | "raw.pong"nonce?: string+ communityContract?: 1 | 2at: number}@@ -90,7 +92,7 @@ function parseConnectionFrame(}}try {- const value = JSON.parse(raw) as { type?: unknown; nonce?: unknown }+ const value = JSON.parse(raw) as { type?: unknown; nonce?: unknown; communityContract?: unknown }if (value.type !== "auth"&& value.type !== "auth.ok"@@ -102,6 +104,7 @@ function parseConnectionFrame(direction,type: value.type,...(typeof value.nonce === "string" ? { nonce: value.nonce } : {}),+ ...(value.communityContract === 1 || value.communityContract === 2 ? { communityContract: value.communityContract } : {}),at: Date.now(),}} catch {@@ -231,8 +234,12 @@ export async function proxyCommunityWebSockets(}}+export function isCommunityBatchFrame(frame: CapturedCommunityFrame): boolean {+ return isCommunityBrowserEventBatchCandidate(frame) && Array.isArray(frame.events)+}+export function communityFrameEvents(frame: CapturedCommunityFrame): CapturedCommunityFrame[] {- return frame.type === "community:events.batch" && Array.isArray(frame.events)+ return isCommunityBrowserEventBatchCandidate(frame) && Array.isArray(frame.events)? frame.events: [frame]}diff --git a/src/web/src/test/e2e-ui/_setup/users.ts b/src/web/src/test/e2e-ui/_setup/users.tsindex a822c123d..1de7c3a97 100644--- a/src/web/src/test/e2e-ui/_setup/users.ts+++ b/src/web/src/test/e2e-ui/_setup/users.ts@@ -1,6 +1,6 @@-export type UserKey = "alice" | "bob" | "carol" | "dave" | "logout" | "sole-delete"+export type UserKey = "alice" | "bob" | "carol" | "dave" | "geometry" | "logout" | "sole-delete"-export const USER_KEYS: UserKey[] = ["alice", "bob", "carol", "dave", "logout", "sole-delete"]+export const USER_KEYS: UserKey[] = ["alice", "bob", "carol", "dave", "geometry", "logout", "sole-delete"]export function emailFor(key: UserKey, stamp: string): string {return `e2e-${key}-${stamp}@alook.test`diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.tsindex 9a22cf8e4..f7a3a132d 100644--- a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts@@ -1,5 +1,6 @@import type { Page } from "@playwright/test"-import { expect, test, userId } from "./_fixtures/community-fixture"+import { PERSIST_CACHE_PREFIX } from "@/lib/query-persister"+import { expect, test, userId, userName } from "./_fixtures/community-fixture"import {seedChannel,seedDm,@@ -70,7 +71,7 @@ async function persistedQueries(page: Page, viewerId: string): Promise<Persisted)))}}- }), `alook:qc:v3:${viewerId}:client`)+ }), `${PERSIST_CACHE_PREFIX}:${viewerId}:client`)}function containsPersistedId(value: unknown, id: string): boolean {@@ -316,7 +317,9 @@ test("a warm DM reload qualifies cached identity and history before showing persawait expectCacheFirstReload(page, async () => {await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible({ timeout: 10_000 })- await expect(page.getByRole("main", { name: "Loading direct message" })).toBeVisible()+ await expect(page.getByTestId(tid.dmHeader)).toBeVisible()+ await expect(page.getByTestId(tid.dmHeader)).toContainText(userName("bob"))+ await expect(page.locator(`main[data-slot="community-conversation-surface"][data-channel-id="${dmId}"]`)).toBeVisible()await expect(page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]').first()).toBeVisible()await expect(page.getByTestId(tid.composerInput)).toHaveCount(0)await expect(page.getByTestId(tid.message(messageId))).toHaveCount(0)diff --git a/src/web/src/test/e2e-ui/perf/perf-query-cache.ts b/src/web/src/test/e2e-ui/perf/perf-query-cache.tsnew file mode 100644index 000000000..d4abf6a56--- /dev/null+++ b/src/web/src/test/e2e-ui/perf/perf-query-cache.ts@@ -0,0 +1,70 @@+import type { PersistedClient } from "@tanstack/react-query-persist-client"++export function operatePerfQueryCache(input: {+ key: string+} & ({+ action: "remove"+} | {+ action: "contains"+ version: number+ buster: string+ queryKey: readonly unknown[]+ channelIds: readonly string[]+})): Promise<boolean> {+ return new Promise((resolve, reject) => {+ let db: IDBDatabase | undefined+ let settled = false+ const finish = (result: boolean, error?: Error | DOMException | null) => {+ if (settled) return+ settled = true+ clearTimeout(timeout)+ db?.close()+ if (error) reject(error)+ else resolve(result)+ }+ const timeout = setTimeout(() => finish(false, new Error("query cache operation timed out")), 3_000)+ const open = indexedDB.open("keyval-store")+ open.onupgradeneeded = () => {+ open.transaction?.abort()+ open.result.close()+ finish(input.action === "remove")+ }+ open.onerror = () => finish(false, open.error ?? new Error("failed to open query cache"))+ open.onsuccess = () => {+ db = open.result+ if (settled) { db.close(); return }+ if (!db.objectStoreNames.contains("keyval")) {+ finish(false, new Error("query cache store unavailable"))+ return+ }+ const tx = db.transaction("keyval", input.action === "remove" ? "readwrite" : "readonly")+ const store = tx.objectStore("keyval")+ let result = input.action === "remove"+ tx.onerror = tx.onabort = () => finish(false, tx.error ?? new Error("query cache transaction failed"))+ tx.oncomplete = () => finish(result)+ if (input.action === "remove") {+ store.delete(input.key)+ return+ }+ const request = store.get(input.key)+ request.onerror = () => finish(false, request.error ?? new Error("failed to read query cache"))+ request.onsuccess = () => {+ if (typeof request.result !== "string") return+ let client: PersistedClient & { version?: unknown; channelFences?: unknown }+ try { client = JSON.parse(request.result) } catch { return }+ if (!client || client.version !== input.version || client.buster !== input.buster+ || !Array.isArray(client.channelFences) || !Array.isArray(client.clientState?.queries)) return+ const query = client.clientState.queries.find(candidate => (+ Array.isArray(candidate?.queryKey) && candidate.queryKey.length === input.queryKey.length+ && candidate.queryKey.every((value, index) => value === input.queryKey[index])+ && candidate.state?.status === "success"+ ))+ const rows = query?.state.data+ result = Array.isArray(rows) && input.channelIds.length > 0 && input.channelIds.every(channelId => (+ rows.some(row => row && typeof row === "object" && typeof row.id === "string"+ && row.id.length > 0 && row.channelId === channelId)+ ))+ }+ }+ })+}diff --git a/src/web/src/test/e2e-ui/perf/switch.perf.ts b/src/web/src/test/e2e-ui/perf/switch.perf.tsindex b3e8c1001..b017d4296 100644--- a/src/web/src/test/e2e-ui/perf/switch.perf.ts+++ b/src/web/src/test/e2e-ui/perf/switch.perf.ts@@ -33,6 +33,9 @@ import { test, expect, type Page, type BrowserContext } from "@playwright/test"import { readFileSync, mkdirSync, writeFileSync } from "node:fs"import { resolve } from "node:path"import { DEV_PASSWORD } from "@alook/shared"+import { PERSIST_BUSTER, PERSIST_CACHE_PREFIX, PERSIST_VERSION } from "@/lib/query-persister"+import { communityKeys } from "@/lib/query-keys"+import { operatePerfQueryCache } from "./perf-query-cache"import { tid } from "../_fixtures/testids"import type {CacheState,@@ -344,40 +347,8 @@ test("community switch perceived-latency capture", async ({ browser }) => {writeFileSync(CAPTURE_OUT, JSON.stringify(out, null, 2))}- // Force a cold pass by clearing the persister's IndexedDB. Do NOT- // `deleteDatabase` — the app holds an open connection to `keyval-store`, so- // the delete request fires `onblocked` and can hang indefinitely. Instead- // clear the object store's CONTENTS (a transaction that doesn't need the DB- // closed), with a hard timeout so a switch can never wedge the whole run.- async function clearIdb(): Promise<void> {- await page.evaluate(- () =>- new Promise<void>((res) => {- const done = setTimeout(res, 3000) // never wedge the run- const open = indexedDB.open("keyval-store")- open.onerror = () => {- clearTimeout(done)- res()- }- open.onsuccess = () => {- const db = open.result- if (!db.objectStoreNames.contains("keyval")) {- db.close()- clearTimeout(done)- res()- return- }- const tx = db.transaction("keyval", "readwrite")- tx.objectStore("keyval").clear()- tx.oncomplete = tx.onerror = () => {- db.close()- clearTimeout(done)- res()- }- }- }),- )- }+ const persistedKey = `${PERSIST_CACHE_PREFIX}:${manifest.owner.userId}:client`+ const clearQueryPayload = () => page.evaluate(operatePerfQueryCache, { key: persistedKey, action: "remove" as const })// Matrix size is env-configurable and defaults SMALL: against a live Next dev// build each switch costs full API fan-out + paint + reflow settle (often@@ -390,7 +361,7 @@ test("community switch perceived-latency capture", async ({ browser }) => {// --- Channel switches: cold, then memory-warm (immediate repeat) ---for (let i = 1; i < Math.min(channels.length, N_CHANNEL + 1); i++) {const ch = channels[i]- await clearIdb()+ await clearQueryPayload()await measureSwitch("channel", ch.id, "cold", async () => {await page.getByTestId(tid.channelRow(ch.id)).click()})@@ -409,40 +380,18 @@ test("community switch perceived-latency capture", async ({ browser }) => {// --- disk-warm channel pass: let the app persist to IDB, reload preserving// it, then measure the first switch (messages paint from disk, read-state// still refetches). ---- const persistedKey = `alook:qc:v1:${manifest.owner.userId}:client`- const persistedChannelId = channels[Math.min(channels.length, N_CHANNEL + 1) - 1]!.id- await expect.poll(() => page.evaluate(({ key, channelId }) => (- new Promise<boolean>((resolvePersisted, rejectPersisted) => {- const open = indexedDB.open("keyval-store")- open.onerror = () => rejectPersisted(open.error ?? new Error("failed to open query persister"))- open.onsuccess = () => {- const db = open.result- if (!db.objectStoreNames.contains("keyval")) {- db.close()- resolvePersisted(false)- return- }- const tx = db.transaction("keyval", "readonly")- const request = tx.objectStore("keyval").get(key)- request.onsuccess = () => {- db.close()- if (typeof request.result !== "string") {- resolvePersisted(false)- return- }- const client = JSON.parse(request.result) as {- clientState?: { queries?: Array<{ queryKey?: unknown[] }> }- }- resolvePersisted(client.clientState?.queries?.some((query) =>- Array.isArray(query.queryKey) && query.queryKey.includes(channelId)) ?? false)- }- request.onerror = () => {- db.close()- rejectPersisted(request.error ?? new Error("failed to read query persister"))- }- }- })- ), { key: persistedKey, channelId: persistedChannelId })).toBe(true)+ const diskChannel = channels[1]+ await page.getByTestId(tid.channelRow(channels[0].id)).click()+ await page.waitForURL(firstLeaf, { waitUntil: "commit" })+ await expect(page.getByTestId(tid.messageScroller).locator("[data-msg-id]").first()).toBeVisible()+ await expect.poll(() => page.evaluate(operatePerfQueryCache, {+ key: persistedKey,+ action: "contains" as const,+ version: PERSIST_VERSION,+ buster: PERSIST_BUSTER,+ queryKey: communityKeys.communityDbCollection(manifest.owner.userId, "messages"),+ channelIds: [channels[0].id, diskChannel.id],+ })).toBe(true)await page.addInitScript(() => {window.__PERF_WARM_RELOAD__ = { customBootstrapSeen: false, skeletonSeen: false }const inspect = () => {@@ -493,16 +442,15 @@ test("community switch perceived-latency capture", async ({ browser }) => {expect(warmReload.stableTs).toBeGreaterThanOrEqual(warmReload.firstCachedPaintTs)flushCapture(){- const ch = channels[1]- await measureSwitch("channel", ch.id, "disk-warm", async () => {- await page.getByTestId(tid.channelRow(ch.id)).click()+ await measureSwitch("channel", diskChannel.id, "disk-warm", async () => {+ await page.getByTestId(tid.channelRow(diskChannel.id)).click()})}// --- Server switches (cold) ---const otherServers = manifest.servers.filter((s) => s.id !== targetServer.id).slice(0, N_SERVER)for (const srv of otherServers) {- await clearIdb()+ await clearQueryPayload()await measureSwitch("server", srv.id, "cold", async () => {await page.getByTestId(tid.serverIcon(srv.id)).click()})diff --git a/src/web/test-runtime/d1-bind-community.runtime.test.ts b/src/web/test-runtime/d1-bind-community.runtime.test.tsindex 7fcfda302..e69b1db62 100644--- a/src/web/test-runtime/d1-bind-community.runtime.test.ts+++ b/src/web/test-runtime/d1-bind-community.runtime.test.ts@@ -135,6 +135,21 @@ describe("community high-cardinality D1 queries", () => {expect(await queries.communityCategory.getCategoriesByIds(db, categoryIds)).toHaveLength(125);expect(await queries.communityReaction.listReactionsByMessageIds(db, messageIds, ownerId)).toHaveLength(125);+ await run(+ "INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq, client_nonce) VALUES (?, ?, 'later sequence', ?, ?, 2, 'nonce')",+ `${prefix}_second_message`, userIds[0], "2026-08-27T00:00:00.000Z", channelIds[0],+ );+ const scoped = await queries.communityMessage.getMessagesByIdsInChannels(+ db, [...messageIds, messageIds[0], `${prefix}_second_message`], channelIds.slice(0, 124),+ );+ expect(scoped).toHaveLength(125);+ expect(scoped.some((message) => message.channelId === channelIds[124])).toBe(false);+ expect(scoped.find((message) => message.id === `${prefix}_second_message`)).toMatchObject({ seq: 2, clientNonce: "nonce" });+ const firstMessages = await queries.communityMessage.getFirstMessageResourcesByChannelIds(db, [...channelIds, channelIds[0]]);+ expect(firstMessages).toHaveLength(125);+ expect(new Set(firstMessages.map((message) => message.id))).toEqual(new Set(messageIds));+ expect(firstMessages.every((message) => message.seq === 1)).toBe(true);+const submitted = categoryIds.slice(0, 100).reverse();expect(await queries.communityCategory.reorderCategories(db, serverId, submitted)).toHaveLength(100);const persisted = await rows<{ id: string; position: number }>(diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex 268bdde0a..8f30934a9 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -101,6 +101,7 @@ binding = "CACHE_KV"id = "3aaa92b4c2c74185b888977e5552e9bf"[vars]+COMMUNITY_EVENT_CONTRACT = "1"RUNTIME_MODEL_OPTIONS = '{"claude":["claude-opus-4-6","claude-sonnet-4-6","claude-haiku-4-5"],"codex":["gpt-5.4","gpt-5.3-codex"]}'MIN_CLI_VERSION = "0.0.159"BLOG_DISCOVERY_REQUIRED = "true"diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.tsindex e9a75a248..5164b47a3 100644--- a/src/ws-do/src/community-browser-event-ingress.test.ts+++ b/src/ws-do/src/community-browser-event-ingress.test.ts@@ -69,9 +69,9 @@ function worstEscapingTarget(index: number) {}describe("community browser event ingress", () => {- it("normalizes all 45 current fixtures without a contract version field", () => {+ it("normalizes all 46 current fixtures without a contract version field", () => {const fixtures = Object.values(communityWsEventFixtures)- expect(fixtures).toHaveLength(45)+ expect(fixtures).toHaveLength(46)for (const fixture of fixtures) {const normalized = normalizeCommunityBrowserEvent(fixture)expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })diff --git a/src/ws-do/src/community-content-access.ts b/src/ws-do/src/community-content-access.tsindex fac1c4b11..22d0b6dee 100644--- a/src/ws-do/src/community-content-access.ts+++ b/src/ws-do/src/community-content-access.ts@@ -23,6 +23,7 @@ export const communityContentAccessKinds = {"community:member.leave": "control","community:server.delete": "control","community:channel.member_add": "control",+ "community:channel.membership.change": "control","community:member.join": "control","community:server.update": "control","community:channel.reorder": "control",diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.tsindex 48c9f23ad..cc49012bd 100644--- a/src/ws-do/src/routes/message-delivery.test.ts+++ b/src/ws-do/src/routes/message-delivery.test.ts@@ -94,6 +94,24 @@ describe("message delivery route", () => {vi.resetModules()})+ it("delivers every actual joined participant and one bounded roster refresh to each other reader", async () => {+ const inputs = new Map<string, InternalBundleBody>()+ doMock.stubFetch.mockImplementation(async (request: Request) => {+ const target = decodeURIComponent(request.headers.get(INTERNAL_USER_TARGET_HEADER)!)+ inputs.set(target, await request.clone().json() as InternalBundleBody)+ return successfulReceipt(request)+ })+ const input: MessageDeliveryBatch = { ...batch, memberAdded: undefined,+ contentUserIds: ["author", "overlap", "joined-reply", "reader"], joinedParticipantUserIds: ["author", "overlap", "joined-reply"], rosterRefreshUserId: "author" }+ expect((await handler.fetch(await deliveryRequest(input), env as never)).status).toBe(200)+ for (const id of input.contentUserIds) {+ const changes = inputs.get(id)!.events.filter((event) => event.type === "community:channel.membership.change")+ expect(changes).toEqual([{ type: "community:channel.membership.change", channelId: "thread-1", serverId: "server-1",+ userId: id === "reader" ? "author" : id, relation: "notify", present: true }])+ expect(inputs.get(id)!.events.length).toBeLessThanOrEqual(MESSAGE_DELIVERY_MAX_EVENTS_PER_USER)+ }+ })+it("settles mixed delivered and revoked targets while retaining temporary failures for retry", async () => {const inputs = new Map<string, InternalBundleBody[]>()let failTransient = truediff --git a/src/ws-do/src/routes/message-delivery.ts b/src/ws-do/src/routes/message-delivery.tsindex dc44ff2e1..f853cf67a 100644--- a/src/ws-do/src/routes/message-delivery.ts+++ b/src/ws-do/src/routes/message-delivery.ts@@ -160,6 +160,16 @@ export async function handleMessageDelivery(...batch.memberAdded,})}+ if (batch.joinedParticipantUserIds && batch.rosterRefreshUserId && batch.messageEvent.serverId) {+ const joined = new Set(batch.joinedParticipantUserIds)+ for (const userId of batch.contentUserIds) {+ addEvent(bundles, userId, {+ type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE, channelId: batch.messageEvent.channelId,+ serverId: batch.messageEvent.serverId, userId: joined.has(userId) ? userId : batch.rosterRefreshUserId,+ relation: "notify", present: true,+ })+ }+ }if (batch.parentProjection && batch.parentProjectionUserIds) {for (const userId of batch.parentProjectionUserIds) {addEvent(bundles, userId, batch.parentProjection)diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.tsindex 1c2b30876..b6a567b84 100644--- a/src/ws-do/src/ws-durable/internal.ts+++ b/src/ws-do/src/ws-durable/internal.ts@@ -1,4 +1,4 @@-import type { Logger } from "@alook/shared"+import type { CommunityContract, Logger } from "@alook/shared"export const COMMUNITY_DELIVERY_PROGRESS_LIMIT = 64export const COMMUNITY_CONNECTION_STATE_JSON_MAX_BYTES = 12 * 1024@@ -18,6 +18,7 @@ export type ConnectionState =authenticated: booleanname?: stringdiscriminator?: string+ communityContract?: CommunityContractcommunityDeliveryProgress?: CompactCommunityDeliveryProgress[]}| { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }@@ -40,10 +41,7 @@ export interface CommunityMachineIdentity {credentialHash: string}-export interface CommunityMachineHandle {- userId: string- machineId: string-}+export type CommunityMachineHandle = Pick<CommunityMachineIdentity, "userId" | "machineId">export const IDENTITY_KEY = "community-machine-identity"export const HANDLE_KEY = "community-machine-handle"diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.tsindex e5f5139e4..35d3d827d 100644--- a/src/ws-do/src/ws-durable/test-harness.ts+++ b/src/ws-do/src/ws-durable/test-harness.ts@@ -10,7 +10,7 @@ const loggerMocks = vi.hoisted(() => ({const deliveryTransportMocks = vi.hoisted(() => ({encodePreparedCommunityBrowserEventBatch: vi.fn(),}))-export const mockEncodePreparedCommunityBrowserEventBatch =+export const mockEncodeCommunityBrowserEventBatchForContract =deliveryTransportMocks.encodePreparedCommunityBrowserEventBatchexport const mockLogDebug = loggerMocks.mockLogDebugconst mockLogInfo = loggerMocks.mockLogInfo@@ -166,9 +166,9 @@ export const mockToSummary = vi.fn((row: any) => ({vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- mockEncodePreparedCommunityBrowserEventBatch.mockImplementation(- (input: Parameters<typeof actual.encodePreparedCommunityBrowserEventBatch>[0]) =>- actual.encodePreparedCommunityBrowserEventBatch(input),+ mockEncodeCommunityBrowserEventBatchForContract.mockImplementation(+ (input: Parameters<typeof actual.encodeCommunityBrowserEventBatchForContract>[0]) =>+ actual.encodeCommunityBrowserEventBatchForContract(input),)const noopLogger = {debug: mockLogDebug,@@ -302,9 +302,9 @@ vi.mock("@alook/shared", async () => {}return {...actual,- encodePreparedCommunityBrowserEventBatch: (- input: Parameters<typeof actual.encodePreparedCommunityBrowserEventBatch>[0],- ) => mockEncodePreparedCommunityBrowserEventBatch(input),+ encodeCommunityBrowserEventBatchForContract: (+ input: Parameters<typeof actual.encodeCommunityBrowserEventBatchForContract>[0],+ ) => mockEncodeCommunityBrowserEventBatchForContract(input),// Real WS event-type strings the DO reads at runtime (#5 T2 — ws-do// broadcasts now use WS_EVENTS.* instead of raw literals). Values match// @alook/shared so the event assertions still hold.diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.tsindex 55a9f1dff..b0e0285f8 100644--- a/src/ws-do/src/ws-durable/user-auth.test.ts+++ b/src/ws-do/src/ws-durable/user-auth.test.ts@@ -15,7 +15,7 @@ import {flushAsyncWork,mockCheckAliveFetch,mockCreateDb,- mockEncodePreparedCommunityBrowserEventBatch,+ mockEncodeCommunityBrowserEventBatchForContract,mockFindCredentialByHash,mockGetBotBinding,mockGetBotBindingWithOwner,@@ -308,6 +308,29 @@ describe("WebSocketDurableObject", () => {})})+ it("restores selected formats from attachments and retains source progress for mixed tabs", async () => {+ const { durable, ctx } = createDO()+ const old = createMockWebSocket(), current = createMockWebSocket()+ old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true })+ current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 2 })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([old, current])+ const change = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "user-42", relation: "notify", present: true }+ const request = await requestFor([change])+ const source = await request.clone().json() as { operationDigest: string }+ expect((await durable.fetch(request.clone())).status).toBe(200)+ const oldFrame = JSON.parse(old.send.mock.calls[0]![0] as string)+ const newFrame = JSON.parse(current.send.mock.calls[0]![0] as string)+ expect(Object.keys(oldFrame)).toHaveLength(4)+ expect(oldFrame.events).toEqual([{ type: "community:channel.member_add", serverId: "server", channelId: "thread", userId: "user-42" }])+ expect(newFrame).toMatchObject({ type: "community:events.batch.v2", operationDigest: source.operationDigest, events: [change] })+ expect(oldFrame.operationDigest).not.toBe(source.operationDigest)+ expect((old.deserializeAttachment() as { communityDeliveryProgress: string[][] }).communityDeliveryProgress[0]![1]).toBe(source.operationDigest)+ expect((current.deserializeAttachment() as { communityDeliveryProgress: string[][] }).communityDeliveryProgress[0]![1]).toBe(source.operationDigest)+ expect((await durable.fetch(request)).status).toBe(200)+ expect(old.send).toHaveBeenCalledTimes(1)+ expect(current.send).toHaveBeenCalledTimes(1)+ })+it("sends zero frames when any event is invalid", async () => {const { durable, ctx } = createDO()const ws = createMockWebSocket()@@ -499,7 +522,7 @@ describe("WebSocketDurableObject", () => {const second = createMockWebSocket()second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])- mockEncodePreparedCommunityBrowserEventBatch.mockReturnValueOnce({+ mockEncodeCommunityBrowserEventBatchForContract.mockReturnValueOnce({ok: false,reason: "batch-invariant-oversized",byteLength: 328_705,@@ -781,6 +804,7 @@ describe("WebSocketDurableObject", () => {userId: "user-42",targetUserId: "user-42",authenticated: true,+ communityContract: 1,name: "Ana",discriminator: "0012",})@@ -810,6 +834,16 @@ describe("WebSocketDurableObject", () => {})})+ it.each([1, 2] as const)("keeps contract %s fixed across successful reauthentication", async (version) => {+ const { durable } = createDO()+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "user-42", targetUserId: "user-42", authenticated: true, communityContract: version })+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: version === 1 ? 2 : 1 }))+ expect(ws.deserializeAttachment()).toMatchObject({ authenticated: true, communityContract: version })+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", ...(version === 2 ? { communityContract: 2 } : {}) }))+ })+it("retries a transient session lookup before authenticating", async () => {const { durable } = createDO()mockGetValidSessionWithIdentitydiff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.tsindex 8a4d8f554..6583510b5 100644--- a/src/ws-do/src/ws-durable/user-auth.ts+++ b/src/ws-do/src/ws-durable/user-auth.ts@@ -1,6 +1,9 @@import {+ COMMUNITY_CONTRACT_VERSION,createDb,- encodePreparedCommunityBrowserEventBatch,+ encodeCommunityBrowserEventBatchForContract,+ encodeCommunityBrowserEvent,+ projectCommunityEventForContract,isUserWsConnectionPing,isValidCommunityUserTarget,queries,@@ -94,7 +97,7 @@ export async function handleUserFetch(return invalidCommunityBrowserEventResponse(event)}if (!hasAuthenticatedTargetSocket(context, targetUserId)) {- return jsonResponse({ sent: broadcast(context, event.body, targetUserId) })+ return jsonResponse({ sent: broadcastCommunity(context, event.event, targetUserId) })}try {if (!await canDeliverCommunityContent(createDb(context.env.DB), targetUserId, [event.event])) {@@ -105,7 +108,7 @@ export async function handleUserFetch(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)+ const sent = broadcastCommunity(context, event.event, targetUserId)return new Response(JSON.stringify({ sent }), {headers: { "Content-Type": "application/json" },})@@ -239,6 +242,7 @@ export async function handleWebSocketMessage(token?: stringmachineToken?: stringdaemonId?: string+ communityContract?: unknown}if (msg.type === "auth") {@@ -292,6 +296,8 @@ export async function handleWebSocketMessage(return}const wasOnline = countAuthenticatedUserConnections(context, userId) > 0+ const communityContract = state?.type === "user" && state.authenticated+ ? state.communityContract === COMMUNITY_CONTRACT_VERSION ? COMMUNITY_CONTRACT_VERSION : 1 : msg.communityContract === COMMUNITY_CONTRACT_VERSION ? COMMUNITY_CONTRACT_VERSION : 1ws.serializeAttachment({type: "user",userId,@@ -299,12 +305,13 @@ export async function handleWebSocketMessage(authenticated: true,name,discriminator,+ communityContract,...(state?.type === "user" && state.communityDeliveryProgress? { communityDeliveryProgress: state.communityDeliveryProgress }: {}),} as ConnectionState)context.log.info("websocket authenticated", { userId })- ws.send(JSON.stringify({ type: "auth.ok" }))+ ws.send(JSON.stringify({ type: "auth.ok", ...(communityContract === COMMUNITY_CONTRACT_VERSION ? { communityContract: COMMUNITY_CONTRACT_VERSION } : {}) }))if (!wasOnline) {broadcastPresence(context, userId, true).catch(() => { })}@@ -411,6 +418,20 @@ function broadcast(return sent}+function broadcastCommunity(context: WsDurableContext, event: import("@alook/shared").CommunityWsEvent, targetUserId: string) {+ let sent = 0+ for (const ws of context.ctx.getWebSockets()) {+ const state = ws.deserializeAttachment() as ConnectionState+ if (state?.type !== "user" || !state.authenticated || state.userId !== targetUserId) continue+ const projected = projectCommunityEventForContract(event, state.communityContract === COMMUNITY_CONTRACT_VERSION ? COMMUNITY_CONTRACT_VERSION : 1)+ if (!projected) continue+ const encoded = encodeCommunityBrowserEvent(projected)+ if (!encoded.ok) continue+ try { ws.send(encoded.body); sent++ } catch { }+ }+ return sent+}+type ValidCommunityBundle = Extract<Awaited<ReturnType<typeof readCommunityBrowserEventBundleRequest>>,{ ok: true }@@ -464,16 +485,15 @@ function safeCloseAmbiguousSocket(ws: WebSocket): void {try { ws.close(1011, "Delivery state unavailable") } catch { }}-function deliverCommunityBundle(+async function deliverCommunityBundle(context: WsDurableContext,bundle: ValidCommunityBundle,targetUserId: string,-): Response {- const encodedBatch = encodePreparedCommunityBrowserEventBatch({- operationId: bundle.operationId,- operationDigest: bundle.operationDigest,- prepared: bundle.prepared,- })+): Promise<Response> {+ const formats = await Promise.all(([1, COMMUNITY_CONTRACT_VERSION] as const).map((contract) => encodeCommunityBrowserEventBatchForContract({+ operationId: bundle.operationId, prepared: bundle.prepared, contract,+ })))+ const encodedBatch = formats[1]!const targetSockets: Array<{ws: WebSocketstate: Extract<ConnectionState, { type: "user" }>@@ -490,13 +510,10 @@ function deliverCommunityBundle(targetSockets.push({ ws, state })}- const plans: DeliveryPlan[] = targetSockets.map(({ ws, state }, socketIndex) => ({- socketIndex,- ws,- state,- frames: encodedBatch.ok ? [encodedBatch.body] : [],- progress: null,- }))+ const plans: DeliveryPlan[] = targetSockets.map(({ ws, state }, socketIndex) => {+ const encoded = formats[state.communityContract === COMMUNITY_CONTRACT_VERSION ? 1 : 0]!+ return { socketIndex, ws, state, frames: encoded.ok ? [encoded.body] : [], progress: null }+ })if (!encodedBatch.ok) {context.log.error("community_delivery_batch_encoder_invariant_failed", {@@ -518,6 +535,7 @@ function deliverCommunityBundle(let hasConflict = falsefor (const plan of plans) {+ if (plan.frames.length === 0) { plan.outcome = "preflightFailed"; continue }const decoded = readCommunityDeliveryProgress(plan.state)if (!decoded.ok) {plan.outcome = "preflightFailed"