Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): preserve complete resources and legacy ingress

Gener1dafbd0c73ea
diff --git a/src/shared/src/community-attention.ts b/src/shared/src/community-attention.ts
index 38353b182..d5803b53a 100644
--- a/src/shared/src/community-attention.ts
+++ b/src/shared/src/community-attention.ts
@@ -1,4 +1,5 @@
import { z } from "zod"
+import { CommunityChannelResourceSchema, CommunityMessagePreviewSchema, CommunityResourceProfileSchema } from "./community-resources"
const id = z.string().min(1)
@@ -67,16 +68,13 @@ export const AttentionIncludedServerSchema = z.strictObject({
discriminator: z.string(),
})
-export const AttentionIncludedChannelSchema = z.strictObject({
- id,
- serverId: id,
- name: z.string(),
- type: z.enum(["text", "forum", "thread"]),
- parentChannelId: id.nullable(),
- parentMessageId: id.nullable(),
- creatorId: id.nullable(),
- archived: z.boolean(),
- lastMessageAt: z.string().nullable(),
+export const AttentionIncludedChannelSchema = CommunityChannelResourceSchema.pick({
+ id: true, serverId: true, name: true, type: true, parentChannelId: true, parentMessageId: true,
+ creatorId: true, archived: true, lastMessageAt: true,
+}).extend({
+ serverId: CommunityChannelResourceSchema.shape.serverId.unwrap(),
+ name: CommunityChannelResourceSchema.shape.name.unwrap(),
+ type: CommunityChannelResourceSchema.shape.type.extract(["text", "forum", "thread"]),
openerSeq: z.number().int().nonnegative().optional(),
openerUnread: z.boolean().optional(),
})
@@ -93,23 +91,16 @@ export const AttentionIncludedDmSchema = z.strictObject({
})
export const AttentionIncludedProfileSchema = z.strictObject({
- userId: id,
- name: z.string(),
+ userId: CommunityResourceProfileSchema.shape.id,
+ ...CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).shape,
+ // The existing unversioned Attention wire uses strings for absent identity.
discriminator: z.string(),
avatar: z.string(),
- avatarVersion: z.number().int().nonnegative(),
})
-export const AttentionIncludedMessageSchema = z.strictObject({
- id,
- channelId: id,
- type: z.enum(["chat", "system"]),
- authorId: id.optional(),
- authorName: z.string().optional(),
- seq: z.number().int().nonnegative(),
- createdAt: z.string(),
- content: z.string(),
-})
+export const AttentionIncludedMessageSchema = CommunityMessagePreviewSchema.pick({
+ id: true, channelId: true, type: true, authorId: true, authorName: true, seq: true, createdAt: true, content: true,
+}).required({ channelId: true, seq: true, createdAt: true, content: true })
export const AttentionIncludedSchema = z.strictObject({
servers: z.array(AttentionIncludedServerSchema),
diff --git a/src/shared/src/community-contract.ts b/src/shared/src/community-contract.ts
index d86f920dd..6d821e436 100644
--- a/src/shared/src/community-contract.ts
+++ b/src/shared/src/community-contract.ts
@@ -1,8 +1,18 @@
export const COMMUNITY_CONTRACT_HEADER = "X-Alook-Community-Contract"
export const COMMUNITY_CONTRACT_VERSION = 2 as const
+export const COMMUNITY_RESOURCE_CONTRACT_VERSION = 3 as const
-export type CommunityContract = 1 | typeof COMMUNITY_CONTRACT_VERSION
+export type CommunityContract = 1 | 2 | 3
+
+export function requestedCommunityContract(headers: Pick<Headers, "get">): CommunityContract | null {
+ const value = headers.get(COMMUNITY_CONTRACT_HEADER)
+ if (value === null || value === "1") return 1
+ if (value === "2") return 2
+ if (value === "3") return 3
+ return null
+}
export function requestsCommunityContract(headers: Pick<Headers, "get">): boolean {
- return headers.get(COMMUNITY_CONTRACT_HEADER) === String(COMMUNITY_CONTRACT_VERSION)
+ const contract = requestedCommunityContract(headers)
+ return contract === 2 || contract === 3
}
diff --git a/src/shared/src/community-message-delivery.ts b/src/shared/src/community-message-delivery.ts
index 696433b25..3b4f23efc 100644
--- a/src/shared/src/community-message-delivery.ts
+++ b/src/shared/src/community-message-delivery.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import {
- CommunityWsEventSchema,
+ communityWsEventSchemaForContract,
isValidCommunityUserTarget,
utf8ByteLength,
} from "./community-ws-events";
@@ -20,6 +20,7 @@ export type MessageDeliveryMemberAdded = {
};
export type MessageDeliveryBatch = {
+ communityContract?: 3;
messageId: string;
messageEvent: CommunityMessageCreate;
contentUserIds: string[];
@@ -44,6 +45,7 @@ const memberAddedSchema = z.strictObject({
});
const batchShape = z.strictObject({
+ communityContract: z.literal(3).optional(),
messageId: z.string().min(1),
messageEvent: z.unknown(),
contentUserIds: targetList,
@@ -73,7 +75,8 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP
const outer = batchShape.safeParse(value);
if (!outer.success) return { ok: false, reason: "invalid-payload" };
const data = outer.data;
- const message = CommunityWsEventSchema.safeParse(data.messageEvent);
+ const schema = communityWsEventSchemaForContract(data.communityContract ?? 2);
+ const message = schema.safeParse(data.messageEvent);
if (!message.success || message.data.type !== "community:message.create") {
return { ok: false, reason: "invalid-payload" };
}
@@ -83,7 +86,7 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP
let parentProjection: CommunityChildChannelUpdate | undefined;
if (data.parentProjection !== undefined) {
- const parsed = CommunityWsEventSchema.safeParse(data.parentProjection);
+ const parsed = schema.safeParse(data.parentProjection);
if (!parsed.success || parsed.data.type !== "community:channel.child_update") {
return { ok: false, reason: "invalid-payload" };
}
@@ -143,6 +146,7 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP
return {
ok: true,
batch: {
+ ...(data.communityContract === 3 ? { communityContract: 3 } : {}),
messageId: data.messageId,
messageEvent: message.data,
contentUserIds: data.contentUserIds,
diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.ts
index fccfbddd9..27c43c8ae 100644
--- a/src/shared/src/community-resources.ts
+++ b/src/shared/src/community-resources.ts
@@ -1,5 +1,5 @@
import { z } from "zod"
-import { COMMUNITY_CONTRACT_VERSION } from "./community-contract"
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "./community-contract"
import { FriendApprovalPayloadSchema } from "./community-friend-approval"
const id = z.string().min(1)
@@ -47,7 +47,7 @@ export const CommunityAccessDecisionSchema = z.strictObject({
canCreateDiscussion: z.boolean(),
})
-export const CommunityMessageAttachmentSchema = z.strictObject({
+export const CommunityLegacyMessageAttachmentSchema = z.strictObject({
kind: z.enum(["image", "file"]),
name: z.string(),
url: z.string(),
@@ -59,6 +59,58 @@ export const CommunityMessageAttachmentSchema = z.strictObject({
height: z.number().nonnegative().optional(),
})
+
+export const CommunityMessageAttachmentSchema = z.strictObject({
+ id,
+ name: z.string(),
+ url: z.string(),
+ thumbnailUrl: z.string().nullable(),
+ contentType: z.string().nullable(),
+ sizeBytes: z.number().int().nonnegative().nullable(),
+ width: z.number().int().nonnegative().nullable(),
+ height: z.number().int().nonnegative().nullable(),
+})
+
+export const CommunityMessagePreviewAttachmentSchema = CommunityMessageAttachmentSchema.partial().required({ name: true, url: true })
+
+export const CommunityResourceProfileSchema = z.strictObject({
+ id,
+ name: z.string(),
+ discriminator: z.string().min(1).nullable(),
+ avatar: z.string().nullable(),
+ avatarVersion: z.number().int().nonnegative(),
+ aboutMe: z.string().optional(),
+ bannerColor: z.string().nullable().optional(),
+ kind: z.enum(["human", "bot"]).optional(),
+ ownerUserId: nullableId.optional(),
+ ownerHandle: z.string().nullable().optional(),
+ mutualServers: z.number().int().nonnegative().optional(),
+ ownedByViewer: z.boolean().optional(),
+ statusEmoji: z.string().nullable().optional(),
+ statusText: z.string().nullable().optional(),
+})
+
+
+export const CommunityMessageThreadParticipantSchema = CommunityResourceProfileSchema.pick({ id: true, name: true, avatar: true, avatarVersion: true })
+const messageThreadSchema = z.strictObject({
+ id,
+ name: CommunityChannelResourceSchema.shape.name,
+ messageCount: CommunityChannelResourceSchema.shape.messageCount,
+ lastReplyAt: CommunityChannelResourceSchema.shape.lastMessageAt.optional(),
+ tags: z.array(z.string()).optional(),
+ preview: z.string().optional(),
+ participants: z.array(CommunityMessageThreadParticipantSchema).optional(),
+ participantCount: z.number().int().nonnegative().optional(),
+})
+const legacyMessageThreadSchema = messageThreadSchema.extend({
+ name: z.string(),
+ lastReplyAt: z.string().optional(),
+ participants: z.array(CommunityMessageThreadParticipantSchema.extend({ avatar: z.string() })).optional(),
+})
+const messageThreadPreviewSchema = messageThreadSchema.partial().required({ id: true }).extend({
+ participants: z.array(CommunityMessageThreadParticipantSchema.partial().required({ id: true })).optional(),
+})
+
export const CommunityMessageResourceSchema = z.strictObject({
id,
channelId: id,
@@ -72,7 +124,7 @@ export const CommunityMessageResourceSchema = z.strictObject({
attachments: z.array(CommunityMessageAttachmentSchema),
systemKind: z.literal("thread").optional(),
authorName: z.string().optional(),
- authorAvatar: z.string().optional(),
+ authorAvatar: z.string().nullable().optional(),
authorAvatarVersion: z.number().int().nonnegative().optional(),
mentionType: z.literal("everyone").nullable().optional(),
replyTo: z.strictObject({
@@ -89,19 +141,14 @@ export const CommunityMessageResourceSchema = z.strictObject({
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(),
+ thread: messageThreadSchema.optional(),
approval: FriendApprovalPayloadSchema.optional(),
})
+export const CommunityMessagePreviewSchema = CommunityMessageResourceSchema.partial().required({
+ id: true, type: true,
+}).extend({ attachments: z.array(CommunityMessagePreviewAttachmentSchema).optional(), thread: messageThreadPreviewSchema.optional() })
+
export const CommunityReadStateResourceSchema = z.strictObject({
channelId: id,
lastReadMessageId: nullableId,
@@ -119,15 +166,6 @@ export const CommunityMemberRelationSchema = z.strictObject({
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(),
@@ -137,10 +175,14 @@ export const CommunityPageSchema = z.strictObject({
latestSeq: z.number().int().nonnegative(),
})
-const envelope = { contractVersion: z.literal(COMMUNITY_CONTRACT_VERSION), channelId: id }
+const envelope = { contractVersion: z.literal(COMMUNITY_RESOURCE_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 CommunityMessagePostedSchema = CommunityMessagesReadSchema.pick({ contractVersion: true, channelId: true }).extend({
+ message: CommunityMessageResourceSchema, deduped: z.boolean(), threadId: id.optional(),
+})
+export const CommunityMessageReadSchema = CommunityMessagePostedSchema.omit({ deduped: true, threadId: true })
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,
@@ -150,11 +192,39 @@ export const CommunityThreadsReadSchema = z.strictObject({ ...envelope, channel:
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({
+export const CommunityReadErrorSchema = z.strictObject({ contractVersion: z.literal(COMMUNITY_RESOURCE_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(),
}) })
+const legacyProfileSchema = CommunityResourceProfileSchema.pick({
+ id: true, name: true, avatar: true, avatarVersion: true,
+}).extend({ discriminator: z.string().nullable(), statusEmoji: z.string().nullable(), statusText: z.string() })
+export const CommunityLegacyMessageResourceSchema = CommunityMessageResourceSchema.extend({ authorAvatar: z.string().optional(), attachments: z.array(CommunityLegacyMessageAttachmentSchema), thread: legacyMessageThreadSchema.optional() })
+const legacyEnvelope = { contractVersion: z.literal(2), channelId: id }
+const legacyReadSchemas = {
+ channel: CommunityChannelReadSchema.extend(legacyEnvelope),
+ messages: CommunityMessagesReadSchema.extend({ ...legacyEnvelope, messages: z.array(CommunityLegacyMessageResourceSchema) }),
+ readState: CommunityReadStateReadSchema.extend(legacyEnvelope),
+ members: CommunityMembersReadSchema.extend({ ...legacyEnvelope, profiles: z.array(legacyProfileSchema) }),
+ threads: CommunityThreadsReadSchema.extend({ ...legacyEnvelope, included: CommunityThreadsReadSchema.shape.included.extend({
+ messages: z.array(CommunityLegacyMessageResourceSchema), profiles: z.array(legacyProfileSchema),
+ }) }),
+ readAdvance: CommunityReadAdvanceSchema.extend(legacyEnvelope),
+ error: CommunityReadErrorSchema.extend({ contractVersion: z.literal(2) }),
+}
+const resourceReadSchemas = {
+ channel: CommunityChannelReadSchema, messages: CommunityMessagesReadSchema, readState: CommunityReadStateReadSchema,
+ members: CommunityMembersReadSchema, threads: CommunityThreadsReadSchema, readAdvance: CommunityReadAdvanceSchema, error: CommunityReadErrorSchema,
+}
+
+export function communityReadSchemas(contract: 2): typeof legacyReadSchemas
+export function communityReadSchemas(contract: 3): typeof resourceReadSchemas
+export function communityReadSchemas(contract: 2 | 3): typeof legacyReadSchemas | typeof resourceReadSchemas
+export function communityReadSchemas(contract: 2 | 3) {
+ return contract === 2 ? legacyReadSchemas : resourceReadSchemas
+}
+
export type CommunityChannelResource = z.infer<typeof CommunityChannelResourceSchema>
export type CommunityChannelIdentity = z.infer<typeof CommunityChannelIdentitySchema>
export type CommunityMessageResource = z.infer<typeof CommunityMessageResourceSchema>
@@ -163,11 +233,23 @@ export type CommunityReadStateResource = z.infer<typeof CommunityReadStateResour
export type CommunityAccessDecision = z.infer<typeof CommunityAccessDecisionSchema>
export type CommunityResourceProfile = z.infer<typeof CommunityResourceProfileSchema>
export type CommunityMessageAttachment = z.infer<typeof CommunityMessageAttachmentSchema>
+export type CommunityMessagePreview = z.infer<typeof CommunityMessagePreviewSchema>
+export type CommunityMessagePreviewAttachment = z.infer<typeof CommunityMessagePreviewAttachmentSchema>
+export type CommunityLegacyMessageAttachment = z.infer<typeof CommunityLegacyMessageAttachmentSchema>
export type CommunityMessagesRead = z.infer<typeof CommunityMessagesReadSchema>
export type CommunityThreadsRead = z.infer<typeof CommunityThreadsReadSchema>
+export type CommunityLegacyThreadsRead = z.infer<typeof legacyReadSchemas.threads>
export type CommunityMembersRead = z.infer<typeof CommunityMembersReadSchema>
export type CommunityMessageSurfaceReceipt = CommunityMessagesRead["surfaceReceipt"]
+const legacyChannelResourcePreviewSchema = CommunityChannelResourceSchema.partial().strip().extend({
+ archived: legacyArchivedSchema.optional(),
+})
+
+export function normalizeCommunityChannelResourcePreview(value: unknown): Partial<CommunityChannelResource> {
+ return legacyChannelResourcePreviewSchema.parse(value)
+}
+
const legacyChannelResourceSchema = CommunityChannelResourceSchema.strip().extend({
topic: CommunityChannelResourceSchema.shape.topic.nullish().transform((value) => value ?? ""),
position: CommunityChannelResourceSchema.shape.position.nullish().transform((value) => value ?? 0),
@@ -184,16 +266,43 @@ export function normalizeCommunityChannelResource(value: unknown): CommunityChan
return legacyChannelResourceSchema.parse(value)
}
-const legacyMessageResourceSchema = CommunityMessageResourceSchema.strip().extend({
+export function communityChannelResourceFromStorage(value: unknown): CommunityChannelResource {
+ return CommunityChannelResourceSchema.strip().extend({ archived: legacyArchivedSchema }).parse(value)
+}
+
+const legacyMessageResourceSchema = CommunityLegacyMessageResourceSchema.strip().extend({
channelId: id.optional(),
replyToId: nullableId.optional(),
clientNonce: CommunityMessageResourceSchema.shape.clientNonce.default(null),
- attachments: CommunityMessageResourceSchema.shape.attachments.default([]),
+ attachments: CommunityLegacyMessageResourceSchema.shape.attachments.default([]),
embeds: CommunityMessageResourceSchema.shape.embeds.nullable().transform((value) => value ?? undefined),
})
-export function normalizeCommunityMessageResource(value: unknown, channelId: string): CommunityMessageResource {
+export function normalizeCommunityMessageResource(value: unknown, channelId: string) {
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 }
}
+
+export function communityMessagePreviewFromLegacy(value: unknown, channelId: string): CommunityMessagePreview {
+ const input = typeof value === "object" && value !== null ? value as Record<string, unknown> : {}
+ const message = normalizeCommunityMessageResource(value, channelId)
+ const attachments = message.attachments.map(({ kind: _kind, size: _size, ...metadata }) => metadata)
+ const preview = CommunityMessagePreviewSchema.parse({
+ ...message,
+ attachments: input.attachments === undefined ? undefined : attachments,
+ clientNonce: input.clientNonce === undefined ? undefined : message.clientNonce,
+ replyToId: input.replyToId === undefined ? message.replyTo?.id : input.replyToId,
+ thread: message.thread ? {
+ ...message.thread,
+ participants: message.thread.participants?.map(({ avatar, name, ...identity }) => ({
+ ...identity,
+ ...(name ? { name } : {}),
+ ...(avatar && avatar !== (name.trim().charAt(0) || "?").toUpperCase() ? { avatar } : {}),
+ })),
+ } : undefined,
+ })
+ return Object.fromEntries(Object.entries(preview).filter(([, field]) => field !== undefined)) as CommunityMessagePreview
+}
+
+export type CommunityLegacyMessageResource = z.infer<typeof CommunityLegacyMessageResourceSchema>
diff --git a/src/shared/src/community-ws-bundle.ts b/src/shared/src/community-ws-bundle.ts
index 72afd2d76..fa3ebd06f 100644
--- a/src/shared/src/community-ws-bundle.ts
+++ b/src/shared/src/community-ws-bundle.ts
@@ -12,7 +12,8 @@ export const COMMUNITY_BROWSER_EVENT_BATCH_TYPE = "community:events.batch" as co
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
+ if (contract === 2) return `${COMMUNITY_BROWSER_EVENT_BATCH_TYPE}.v2` as const
+ if (contract === 3) return `${COMMUNITY_BROWSER_EVENT_BATCH_TYPE}.v3` as const
throw new Error("unsupported community event contract")
}
export const COMMUNITY_DELIVERY_OPERATION_ID_PREFIX = "message:" as const
@@ -39,6 +40,7 @@ export type CommunityBrowserEventBatch = {
}
export type PreparedCommunityDeliveryEvents = {
+ contract: CommunityContract
events: CommunityWsEvent[]
envelopes: CommunityWsEvent[]
bodies: string[]
@@ -73,6 +75,7 @@ export type CommunityBrowserEventBatchEncodeResult =
| CommunityDeliveryPrepareFailureReason
| "invalid-operation-id"
| "invalid-operation-digest"
+ | "invalid-contract"
| "digest-mismatch"
| "batch-invariant-oversized"
eventIndex?: number
@@ -193,6 +196,7 @@ export async function computeCommunityDeliveryDigestFromBodies(
export async function prepareCommunityDeliveryEvents(
values: readonly unknown[],
+ contract: CommunityContract = 2,
): Promise<CommunityDeliveryPrepareResult> {
if (values.length < 1 || values.length > MESSAGE_DELIVERY_MAX_EVENTS_PER_USER) {
return { ok: false, reason: "invalid-event-count" }
@@ -201,9 +205,9 @@ export async function prepareCommunityDeliveryEvents(
const envelopes: CommunityWsEvent[] = []
const bodies: string[] = []
for (let eventIndex = 0; eventIndex < values.length; eventIndex += 1) {
- const decoded = decodeCommunityBrowserEvent(values[eventIndex])
+ const decoded = decodeCommunityBrowserEvent(values[eventIndex], contract)
if (!decoded.ok) return { ok: false, reason: "invalid-child", eventIndex }
- const encoded = encodeCommunityBrowserEvent(decoded.event)
+ const encoded = encodeCommunityBrowserEvent(decoded.event, contract)
if (!encoded.ok) {
return {
ok: false,
@@ -219,6 +223,7 @@ export async function prepareCommunityDeliveryEvents(
return {
ok: true,
prepared: {
+ contract,
events,
envelopes,
bodies,
@@ -231,6 +236,7 @@ export async function encodeCommunityBrowserEventBatch(input: {
operationId: unknown
operationDigest: unknown
events: readonly unknown[]
+ contract?: CommunityContract
}): Promise<CommunityBrowserEventBatchEncodeResult> {
if (!isCommunityDeliveryOperationId(input.operationId)) {
return { ok: false, reason: "invalid-operation-id" }
@@ -238,12 +244,14 @@ export async function encodeCommunityBrowserEventBatch(input: {
if (!isCommunityDeliveryDigest(input.operationDigest)) {
return { ok: false, reason: "invalid-operation-digest" }
}
- const prepared = await prepareCommunityDeliveryEvents(input.events)
+ const prepared = await prepareCommunityDeliveryEvents(input.events, input.contract ?? 1)
if (!prepared.ok) return prepared
return encodePreparedCommunityBrowserEventBatch({
operationId: input.operationId,
operationDigest: input.operationDigest,
prepared: prepared.prepared,
+ contract: input.contract ?? 1,
+ ...(input.contract === 2 || input.contract === 3 ? { sourceDigest: prepared.prepared.digest } : {}),
})
}
@@ -252,6 +260,7 @@ export function encodePreparedCommunityBrowserEventBatch(input: {
operationDigest: unknown
prepared: PreparedCommunityDeliveryEvents
sourceDigest?: CommunityDeliveryDigest
+ contract?: CommunityContract
}): CommunityBrowserEventBatchEncodeResult {
if (!isCommunityDeliveryOperationId(input.operationId)) {
return { ok: false, reason: "invalid-operation-id" }
@@ -267,8 +276,10 @@ export function encodePreparedCommunityBrowserEventBatch(input: {
}
}
if (input.sourceDigest !== undefined && !isCommunityDeliveryDigest(input.sourceDigest)) return { ok: false, reason: "invalid-operation-digest" }
+ const contract = input.contract ?? 1
+ if ((contract === 1) !== (input.sourceDigest === undefined) || (input.prepared.contract === 3) !== (contract === 3)) return { ok: false, reason: "invalid-contract" }
const envelope = {
- type: communityBrowserEventBatchType(input.sourceDigest === undefined ? 1 : COMMUNITY_CONTRACT_VERSION),
+ type: communityBrowserEventBatchType(contract),
operationId: input.operationId,
operationDigest: input.sourceDigest ?? input.operationDigest,
...(input.sourceDigest === undefined ? {} : { wireDigest: input.prepared.digest }),
@@ -289,7 +300,7 @@ export function encodePreparedCommunityBrowserEventBatch(input: {
export function isCommunityBrowserEventBatchCandidate(
value: unknown,
): value is Record<string, unknown> & { type: ReturnType<typeof communityBrowserEventBatchType> } {
- return isRecord(value) && (value.type === COMMUNITY_BROWSER_EVENT_BATCH_TYPE || value.type === communityBrowserEventBatchType())
+ return isRecord(value) && ([1, 2, 3] as const).some((contract) => value.type === communityBrowserEventBatchType(contract))
}
export function decodeCommunityBrowserEventBatch(
@@ -304,7 +315,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 && value.type !== communityBrowserEventBatchType()) {
+ if (!([1, 2, 3] as const).some((contract) => value.type === communityBrowserEventBatchType(contract))) {
return { ok: false, reason: "wrong-type" }
}
if (!isCommunityDeliveryOperationId(value.operationId)) {
@@ -313,7 +324,8 @@ export function decodeCommunityBrowserEventBatch(
if (!isCommunityDeliveryDigest(value.operationDigest)) {
return { ok: false, reason: "invalid-operation-digest" }
}
- const current = value.type === communityBrowserEventBatchType()
+ const contract: CommunityContract = value.type === communityBrowserEventBatchType(3) ? 3 : value.type === communityBrowserEventBatchType(2) ? 2 : 1
+ const current = contract !== 1
if (
Object.keys(value).length !== (current ? 5 : 4)
|| (current && !isCommunityDeliveryDigest(value.wireDigest))
@@ -334,7 +346,7 @@ export function decodeCommunityBrowserEventBatch(
const events: CommunityWsEvent[] = []
const envelopes: CommunityWsEvent[] = []
for (let eventIndex = 0; eventIndex < value.events.length; eventIndex += 1) {
- const child = decodeCommunityBrowserEvent(value.events[eventIndex])
+ const child = decodeCommunityBrowserEvent(value.events[eventIndex], contract)
if (!child.ok) {
return { ok: false, reason: "invalid-child", eventIndex }
}
@@ -344,7 +356,7 @@ export function decodeCommunityBrowserEventBatch(
return {
ok: true,
batch: {
- type: value.type,
+ type: communityBrowserEventBatchType(contract),
...(current ? { wireDigest: value.wireDigest as string } : {}),
operationId: value.operationId,
operationDigest: value.operationDigest,
@@ -354,27 +366,57 @@ export function decodeCommunityBrowserEventBatch(
}
}
-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 function projectCommunityEventForContract(event: CommunityWsEvent, contract: CommunityContract, sourceContract: CommunityContract = 2): CommunityWsEvent | null {
+ let projected: unknown = event
+ if (sourceContract === 3 && contract !== 3) {
+ if (event.type === "community:message.create") {
+ const decoded = decodeCommunityBrowserEvent(event, 3)
+ if (!decoded.ok || decoded.event.type !== event.type) return null
+ const { channelId: _channelId, thread: _thread, reactions: _reactions, ...message } = decoded.event.message
+ projected = { ...event, message: {
+ ...message,
+ authorAvatar: message.authorAvatar ?? undefined, clientNonce: message.clientNonce ?? undefined,
+ attachments: message.attachments.length ? message.attachments.map((attachment) => ({
+ id: attachment.id, filename: attachment.name, url: attachment.url,
+ thumbnailUrl: attachment.thumbnailUrl ?? undefined, contentType: attachment.contentType ?? undefined,
+ size: attachment.sizeBytes ?? undefined, width: attachment.width, height: attachment.height,
+ })) : undefined,
+ } }
+ } else if (event.type === "community:channel.create") {
+ const channel = event.channel
+ projected = { ...event, channel: { id: channel.id, name: channel.name ?? "", type: channel.type,
+ categoryId: channel.categoryId, topic: channel.topic, position: channel.position, createdAt: channel.createdAt } }
+ } else if (event.type === "community:channel.child_create") {
+ const channel = event.channel
+ projected = { ...event, channel: { id: channel.id, name: channel.name ?? "", type: channel.type,
+ creatorId: channel.creatorId ?? undefined, createdAt: channel.createdAt } }
+ } else if (event.type === "community:identity.update") {
+ projected = { ...event, avatar: event.avatar ?? "" }
+ }
+ }
+ const decoded = decodeCommunityBrowserEvent(projected, contract)
+ if (!decoded.ok) return null
+ const admitted = decoded.event
+ if (contract !== 1) return admitted
+ if (admitted.type === "community:friend.block") return { type: admitted.type, userId: admitted.userId }
+ if (admitted.type !== "community:channel.membership.change") return admitted
+ if (admitted.serverId === null) return null
+ return { type: admitted.present ? "community:channel.member_add" : "community:channel.member_remove",
+ serverId: admitted.serverId, channelId: admitted.channelId, userId: admitted.userId }
}
export async function encodeCommunityBrowserEventBatchForContract(input: {
operationId: CommunityDeliveryOperationId; prepared: PreparedCommunityDeliveryEvents; contract: CommunityContract;
}): Promise<CommunityBrowserEventBatchEncodeResult> {
- const source = await prepareCommunityDeliveryEvents(input.prepared.events)
+ const source = await prepareCommunityDeliveryEvents(input.prepared.events, input.prepared.contract)
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))
+ const events = input.prepared.events.map((event) => projectCommunityEventForContract(event, input.contract, input.prepared.contract))
if (events.some((event) => event === null)) return { ok: false, reason: "invalid-child" }
- const wire = await prepareCommunityDeliveryEvents(events)
+ const wire = await prepareCommunityDeliveryEvents(events, input.contract)
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 } : {}) })
+ prepared: wire.prepared, contract: input.contract, ...(input.contract !== 1 ? { sourceDigest: input.prepared.digest } : {}) })
}
export function admitCommunityBrowserEventBatch(value: unknown): CommunityBrowserEventBatchDecodeResult | Promise<CommunityBrowserEventBatchDecodeResult> {
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index b816685a2..edff711b0 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -1,7 +1,8 @@
import { z } from "zod"
-import { CommunityMachineRuntimeSchema } from "./schemas"
+import type { CommunityContract } from "./community-contract"
+import { CommunityMachineSummarySchema } from "./schemas"
import { FriendApprovalPayloadSchema } from "./community-friend-approval"
-import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMemberRelationSchema } from "./community-resources"
+import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "./community-resources"
export { FriendApprovalPayloadSchema } from "./community-friend-approval"
export type { FriendApprovalPayload, FriendApprovalProfile } from "./community-friend-approval"
@@ -29,6 +30,7 @@ const messageSchema = CommunityMessageResourceSchema.pick({
seq: z.number(),
authorId: string,
authorName: string,
+ authorAvatar: string.optional(),
authorAvatarVersion: CommunityMessageResourceSchema.shape.authorAvatarVersion.unwrap(),
replyToId: nullableString.optional(),
replyTo: CommunityMessageResourceSchema.shape.replyTo.unwrap().extend({
@@ -39,7 +41,7 @@ const messageSchema = CommunityMessageResourceSchema.pick({
clientNonce: string.optional(),
})
-const communityMessageCreateSchema = z.strictObject({
+export const CommunityLegacyMessageCreateSchema = z.strictObject({
type: z.literal("community:message.create"),
channelId: string,
serverId: string.optional(),
@@ -405,28 +407,6 @@ const communityProfileUpdateSchema = z.strictObject({
ownerUserId: nullableString,
})
-const machineRuntimeSchema = CommunityMachineRuntimeSchema.strict()
-
-export const CommunityMachineSummarySchema = z.strictObject({
- id: string,
- hostname: string,
- displayName: string,
- platform: string,
- arch: string,
- osRelease: string,
- daemonVersion: string,
- lastSeenAt: nullableString,
- status: z.enum(["online", "offline"]),
- availableRuntimes: z.array(machineRuntimeSchema),
- lastRuntimeError: z.strictObject({
- requested: string,
- available: z.array(string),
- at: string,
- }).optional(),
- createdAt: string,
- updatedAt: string,
-})
-
const communityMachineCreatedSchema = z.strictObject({
type: z.literal("community:machine.created"),
machine: CommunityMachineSummarySchema,
@@ -461,8 +441,7 @@ const communityBotAuditEventSchema = z.strictObject({
createdAt: string,
}).refine((event) => Object.prototype.hasOwnProperty.call(event, "payload"))
-const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
- communityMessageCreateSchema,
+const commonCommunityEventSchemas = [
communityMessageUpdatedSchema,
communityMessageEditedSchema,
communityReactionAddSchema,
@@ -471,12 +450,8 @@ const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
communityPinRemoveSchema,
communityTypingStartSchema,
communityTypingStopSchema,
- communityChildChannelCreateSchema,
- communityChildChannelUpdateSchema,
communityServerUpdateSchema,
communityServerDeleteSchema,
- communityChannelCreateSchema,
- communityChannelUpdateSchema,
communityChannelDeleteSchema,
communityChannelReorderSchema,
communityChannelMemberAddSchema,
@@ -501,15 +476,39 @@ const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
communityInboxChangedSchema,
communityPresenceUpdateSchema,
communityStatusUpdateSchema,
- communityIdentityUpdateSchema,
- communityProfileUpdateSchema,
communityMachineCreatedSchema,
communityMachineStatusSchema,
communityMachineUpdatedSchema,
communityMachineRemovedSchema,
communityBotAuditEventSchema,
+] as const
+
+const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
+ ...commonCommunityEventSchemas, CommunityLegacyMessageCreateSchema, communityChildChannelCreateSchema,
+ communityChannelCreateSchema, communityChildChannelUpdateSchema, communityChannelUpdateSchema,
+ communityIdentityUpdateSchema, communityProfileUpdateSchema,
+])
+
+const CommunityResourceWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
+ ...commonCommunityEventSchemas,
+ CommunityLegacyMessageCreateSchema.extend({ message: CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }) }).refine((event) => event.message.channelId === event.channelId),
+ communityChildChannelCreateSchema.extend({ channel: CommunityChannelResourceSchema.extend({ type: z.literal("thread") }) })
+ .refine((event) => event.channel.parentChannelId === event.parentChannelId && (event.parentMessageId === undefined || event.parentMessageId === event.channel.parentMessageId)),
+ communityChannelCreateSchema.extend({ channel: CommunityChannelResourceSchema.extend({ type: channelTypeSchema }) })
+ .refine((event) => event.channel.serverId === event.serverId),
+ communityChildChannelUpdateSchema.extend({ changes: CommunityChannelResourceSchema.pick({ name: true, archived: true, lastMessageAt: true, messageCount: true }).partial()
+ .extend({ tags: z.array(string).nullable().optional() }) }),
+ communityChannelUpdateSchema.extend({ changes: CommunityChannelResourceSchema.pick({ name: true, topic: true, categoryId: true, type: true }).partial()
+ .extend({ type: channelTypeSchema.optional() }) }),
+ communityIdentityUpdateSchema.extend({ avatar: CommunityResourceProfileSchema.shape.avatar, avatarVersion: CommunityResourceProfileSchema.shape.avatarVersion.refine((version) => version > 0) }),
+ CommunityResourceProfileSchema.pick({ name: true, discriminator: true, aboutMe: true, bannerColor: true, kind: true, ownerUserId: true }).required()
+ .extend({ type: z.literal("community:profile.update"), userId: string }),
])
+export function communityWsEventSchemaForContract(contract: CommunityContract) {
+ return contract === 3 ? CommunityResourceWsEventSchema : CommunityWsEventSchema
+}
+
type InferredCommunityWsEvent = z.infer<typeof CommunityWsEventDiscriminatedSchema>
type InferredCommunityMessageEdited = Extract<
InferredCommunityWsEvent,
@@ -530,7 +529,18 @@ export const CommunityWsEventSchema = CommunityWsEventDiscriminatedSchema.transf
(event): CommunityWsEventOutput => event as CommunityWsEventOutput,
)
-export type CommunityWsEvent = z.infer<typeof CommunityWsEventSchema>
+type CommunityResourceWsEventOutput = Exclude<
+ z.infer<typeof CommunityResourceWsEventDiscriminatedSchema>,
+ { type: "community:message.edited" }
+> | CommunityMessageEditedOutput
+export const CommunityResourceWsEventSchema = CommunityResourceWsEventDiscriminatedSchema.transform(
+ (event): CommunityResourceWsEventOutput => event as CommunityResourceWsEventOutput,
+)
+
+export type CommunityLegacyWsEvent = z.infer<typeof CommunityWsEventSchema>
+export type CommunityResourceWsEvent = z.infer<typeof CommunityResourceWsEventSchema>
+export type CommunityWsEvent = CommunityLegacyWsEvent | CommunityResourceWsEvent
+export type CommunityLegacyMessageCreate = z.infer<typeof CommunityLegacyMessageCreateSchema>
export type CommunityMessageCreate = Extract<CommunityWsEvent, { type: "community:message.create" }>
export type CommunityMessageUpdated = Extract<CommunityWsEvent, { type: "community:message.updated" }>
export type CommunityMessageEdited = Extract<CommunityWsEvent, { type: "community:message.edited" }>
@@ -577,8 +587,6 @@ export type CommunityMachineStatus = Extract<CommunityWsEvent, { type: "communit
export type CommunityMachineUpdated = Extract<CommunityWsEvent, { type: "community:machine.updated" }>
export type CommunityMachineRemoved = Extract<CommunityWsEvent, { type: "community:machine.removed" }>
export type CommunityBotAuditEvent = Extract<CommunityWsEvent, { type: "community:bot.audit_event" }>
-export type CommunityMachineSummary = z.infer<typeof CommunityMachineSummarySchema>
-export type CommunityMachineRuntime = CommunityMachineSummary["availableRuntimes"][number]
export type BotAddedFrame = {
type: "bot:added"
@@ -682,18 +690,18 @@ export type CommunityBrowserEventFailureReason =
| "pre-auth-frame"
| "duplicate-auth-ok"
-export type CommunityBrowserEventDecodeResult =
- | { ok: true; event: CommunityWsEvent }
+export type CommunityBrowserEventDecodeResult<Event = CommunityWsEvent> =
+ | { ok: true; event: Event }
| {
ok: false
reason: CommunityBrowserEventFailureReason
type: CommunityWsEvent["type"] | "unknown"
}
-export type CommunityBrowserEventEncodeResult =
+export type CommunityBrowserEventEncodeResult<Event = CommunityWsEvent> =
| {
ok: true
- event: CommunityWsEvent
+ event: Event
body: string
byteLength: number
}
@@ -749,7 +757,10 @@ export function encodeCommunityUserTargetPathSegment(target: string): string {
return `${COMMUNITY_USER_TARGET_PATH_PREFIX}${encodeURIComponent(target)}`
}
-export function decodeCommunityBrowserEvent(value: unknown): CommunityBrowserEventDecodeResult {
+export function decodeCommunityBrowserEvent(value: unknown, contract: 3): CommunityBrowserEventDecodeResult<CommunityResourceWsEvent>
+export function decodeCommunityBrowserEvent(value: unknown, contract?: 1 | 2): CommunityBrowserEventDecodeResult<CommunityLegacyWsEvent>
+export function decodeCommunityBrowserEvent(value: unknown, contract: CommunityContract): CommunityBrowserEventDecodeResult
+export function decodeCommunityBrowserEvent(value: unknown, contract: CommunityContract = 2): CommunityBrowserEventDecodeResult {
if (!isRecord(value)) return { ok: false, reason: "non-object", type: "unknown" }
if (typeof value.type !== "string" || value.type.length === 0) {
return { ok: false, reason: "missing-type", type: "unknown" }
@@ -761,13 +772,16 @@ export function decodeCommunityBrowserEvent(value: unknown): CommunityBrowserEve
return { ok: false, reason: "unknown-community-type", type: "unknown" }
}
- const parsed = CommunityWsEventSchema.safeParse(value)
+ const parsed = communityWsEventSchemaForContract(contract).safeParse(value)
if (!parsed.success) return { ok: false, reason: "invalid-payload", type: value.type }
return { ok: true, event: parsed.data }
}
-export function encodeCommunityBrowserEvent(value: unknown): CommunityBrowserEventEncodeResult {
- const parsed = CommunityWsEventSchema.safeParse(value)
+export function encodeCommunityBrowserEvent(value: unknown, contract: 3): CommunityBrowserEventEncodeResult<CommunityResourceWsEvent>
+export function encodeCommunityBrowserEvent(value: unknown, contract?: 1 | 2): CommunityBrowserEventEncodeResult<CommunityLegacyWsEvent>
+export function encodeCommunityBrowserEvent(value: unknown, contract: CommunityContract): CommunityBrowserEventEncodeResult
+export function encodeCommunityBrowserEvent(value: unknown, contract: CommunityContract = 2): CommunityBrowserEventEncodeResult {
+ const parsed = communityWsEventSchemaForContract(contract).safeParse(value)
const type = isRecord(value) && isCommunityEventType(value.type) ? value.type : "unknown"
if (!parsed.success) return { ok: false, reason: "invalid-payload", type }
const event = parsed.data
diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.ts
index d4bf6da1c..f2237f4d7 100644
--- a/src/shared/src/db/community-machine-schema.ts
+++ b/src/shared/src/db/community-machine-schema.ts
@@ -2,7 +2,7 @@ import { check, index, integer, primaryKey, sqliteTable, text, uniqueIndex } fro
import { sql } from "drizzle-orm";
import { nanoid } from "nanoid";
import { user } from "./schema";
-import type { CommunityMachineRuntime } from "../community-ws-events";
+import type { CommunityMachineRuntime } from "../schemas";
import type { QuotaLimit } from "../provider-telemetry";
export const DIAGNOSTIC_REPORT_FAILURE_CODES = [
diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.ts
index fe8a0b85f..139c60a29 100644
--- a/src/shared/src/db/queries/community/machine.ts
+++ b/src/shared/src/db/queries/community/machine.ts
@@ -17,7 +17,7 @@ import { isPresenceOnline } from "../../../utils/status";
import type {
CommunityMachineRuntime,
CommunityMachineSummary,
-} from "../../../community-ws-events";
+} from "../../../schemas";
import type { ProviderQuotaObservation, ProviderQuotaSnapshot } from "../../../provider-telemetry";
// ---------------------------------------------------------------------------
diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.ts
index 071450717..01b509704 100644
--- a/src/shared/src/db/queries/community/thread.ts
+++ b/src/shared/src/db/queries/community/thread.ts
@@ -144,6 +144,7 @@ export async function listParticipantsForChannels(
userName: user.name,
userImage: user.image,
userAvatarVersion: user.avatarVersion,
+ discriminator: user.discriminator,
participantCount: sql<number>`count(*) over (partition by ${communityChannelMember.channelId})`.as("participant_count"),
rank: sql<number>`row_number() over (partition by ${communityChannelMember.channelId} order by ${communityChannelMember.addedAt}, ${communityChannelMember.userId})`.as("participant_rank"),
})
@@ -162,6 +163,7 @@ export async function listParticipantsForChannels(
userName: ranked.userName,
userImage: ranked.userImage,
userAvatarVersion: ranked.userAvatarVersion,
+ discriminator: ranked.discriminator,
participantCount: ranked.participantCount,
})
.from(ranked)
@@ -182,6 +184,7 @@ export async function listParticipantsForChannels(
userName: user.name,
userImage: user.image,
userAvatarVersion: user.avatarVersion,
+ discriminator: user.discriminator,
})
.from(communityChannelMember)
.innerJoin(user, eq(user.id, communityChannelMember.userId))
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 25c6f6ea4..c5e47fc4c 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -217,7 +217,6 @@ export {
TaskApiBaseSchema,
TaskApiSchema,
HeartbeatRequestSchema,
- SweepRequestSchema,
PollRequestSchema,
MAX_POLL_TASKS,
PollResponseSchema,
@@ -240,7 +239,6 @@ export {
IssueStatusSchema,
CreateIssueRequestSchema,
UpdateIssueRequestSchema,
- CreateIssueCommentRequestSchema,
CreateIssueCommentBodySchema,
IssueCommentApiSchema,
IssueApiSchema,
@@ -346,7 +344,6 @@ export type {
TaskApiBase,
TaskApi,
HeartbeatRequest,
- SweepRequest,
PollRequest,
PollResponse,
PollMeetingItem,
@@ -367,7 +364,6 @@ export type {
CalendarEventApi,
CreateIssueRequestInput,
UpdateIssueRequestInput,
- CreateIssueCommentRequestInput,
CreateIssueCommentBody,
IssueCommentApi,
IssueApi,
@@ -581,7 +577,7 @@ export {
} from "./community/bot-activity-presets";
export type { BotActivityPreset } from "./community/bot-activity-presets";
-export type { CommunityMachineSummary, CommunityMachineRuntime } from "./community-ws-events";
+export type { CommunityMachineSummary, CommunityMachineRuntime } from "./schemas";
export type {
BotAddedFrame,
BotUpdatedFrame,
@@ -640,12 +636,18 @@ export type {
CommunityMachineRemoved,
CommunityBotAuditEvent,
CommunityWsEvent,
+ CommunityLegacyWsEvent,
+ CommunityResourceWsEvent,
+ CommunityLegacyMessageCreate,
CommunityBrowserEventFailureReason,
CommunityBrowserEventDecodeResult,
CommunityBrowserEventEncodeResult,
} from "./community-ws-events";
export {
CommunityWsEventSchema,
+ CommunityResourceWsEventSchema,
+ CommunityLegacyMessageCreateSchema,
+ communityWsEventSchemaForContract,
FriendApprovalPayloadSchema,
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
COMMUNITY_USER_TARGET_MAX_BYTES,
@@ -822,5 +824,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 { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, COMMUNITY_RESOURCE_CONTRACT_VERSION, requestedCommunityContract, requestsCommunityContract, type CommunityContract } from "./community-contract";
export * from "./community-resources";
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 43f8c462b..b312b7522 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -135,8 +135,6 @@ export const HeartbeatRequestSchema = z.object({
});
export type HeartbeatRequest = z.infer<typeof HeartbeatRequestSchema>;
-export const SweepRequestSchema = HeartbeatRequestSchema;
-export type SweepRequest = HeartbeatRequest;
// ---------------------------------------------------------------------------
// Poll request/response (replaces heartbeat + per-runtime claim)
@@ -437,9 +435,6 @@ export const CreateIssueCommentBodySchema = z.object({
});
export type CreateIssueCommentBody = z.infer<typeof CreateIssueCommentBodySchema>;
-/** @deprecated Use CreateIssueCommentBodySchema instead */
-export const CreateIssueCommentRequestSchema = CreateIssueCommentBodySchema;
-export type CreateIssueCommentRequestInput = CreateIssueCommentBody;
export const IssueCommentApiSchema = z.object({
id: z.string(),
@@ -948,7 +943,7 @@ const CommunityRunningAgentListSchema = z.array(z.string()).transform((list) =>
return out;
});
-export const CommunityMachineSummarySchema = z.object({
+export const CommunityMachineSummarySchema = z.strictObject({
id: z.string(),
hostname: z.string(),
displayName: z.string(),
@@ -958,14 +953,14 @@ export const CommunityMachineSummarySchema = z.object({
daemonVersion: z.string(),
lastSeenAt: z.string().nullable(),
status: z.enum(["online", "offline"]),
- availableRuntimes: z.array(CommunityMachineRuntimeSchema).default([]),
+ availableRuntimes: z.array(CommunityMachineRuntimeSchema.strict()),
/**
* Last runtime error reported by the daemon (optimistically cleared on
* subsequent `agent:wake` forward). Optional so pre-error summaries
* omit the field entirely — undefined == "no known error."
*/
lastRuntimeError: z
- .object({
+ .strictObject({
requested: z.string(),
available: z.array(z.string()),
at: z.string(),
@@ -974,6 +969,7 @@ export const CommunityMachineSummarySchema = z.object({
createdAt: z.string(),
updatedAt: z.string(),
});
+export type CommunityMachineSummary = z.infer<typeof CommunityMachineSummarySchema>;
/**
* `HostReady` message — the daemon's post-connect state dump. `runtimes`
diff --git a/src/shared/test/community-resources.contract.test.ts b/src/shared/test/community-resources.contract.test.ts
index 0f6d900a8..d788ca141 100644
--- a/src/shared/test/community-resources.contract.test.ts
+++ b/src/shared/test/community-resources.contract.test.ts
@@ -1,11 +1,21 @@
import { describe, expect, it } from "vitest"
-import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, normalizeCommunityChannelIdentity, normalizeCommunityChannelResource, normalizeCommunityMessageResource } from "../src"
+import { communityMessagePreviewFromLegacy, CommunityLegacyMessageResourceSchema, communityChannelResourceFromStorage, CommunityMessageAttachmentSchema, CommunityMessagePreviewSchema, CommunityResourceProfileSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, normalizeCommunityChannelIdentity, normalizeCommunityChannelResource, normalizeCommunityChannelResourcePreview, normalizeCommunityMessageResource } from "../src"
+import { communityResourceChannelFixture, communityResourceMessageFixture } from "./community-ws-events.fixtures"
import { COMMUNITY_CONTRACT_HEADER, requestsCommunityContract } from "../src/community-contract"
+import { communityReadSchemas } from "../src/community-resources"
describe("common community resources", () => {
+ it.each([2, 3] as const)("selects read contract %s without accepting the other version", (contractVersion) => {
+ const schemas = communityReadSchemas(contractVersion)
+ const body = { contractVersion, channelId: "channel", changed: true, targetSeq: 7, revision: 9 }
+ expect(schemas.readAdvance.parse(body)).toEqual(body)
+ expect(schemas.readAdvance.safeParse({ ...body, contractVersion: contractVersion === 2 ? 3 : 2 }).success).toBe(false)
+ expect(schemas.error.parse({ contractVersion, error: { code: "not_allowed", message: "Denied", retryable: false } }))
+ .toEqual({ contractVersion, error: { code: "not_allowed", message: "Denied", retryable: false } })
+ })
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")
+ expect(requestsCommunityContract(headers)).toBe(version === "2" || version === "3")
})
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",
@@ -20,6 +30,24 @@ describe("common community resources", () => {
expect(() => normalizeCommunityChannelIdentity({ ...input, id: "" })).toThrow()
expect(() => normalizeCommunityChannelIdentity({ ...input, archived: 2 })).toThrow()
})
+ it.each([[false, false], [true, true], [0, false], [1, true]] as const)("normalizes only the present preview archive fact %s", (archived, expected) => {
+ expect(normalizeCommunityChannelResourcePreview({ id: "preview", archived })).toEqual({ id: "preview", archived: expected })
+ })
+ it("keeps omitted preview fields absent", () => {
+ const input = { id: "preview", name: "Preview" }
+ expect(normalizeCommunityChannelResourcePreview(input)).toEqual(input)
+ expect(normalizeCommunityChannelResourcePreview({})).toEqual({})
+ })
+ it("preserves supplied preview facts without complete or authority markers", () => {
+ const input = { ...communityResourceChannelFixture, name: null, categoryId: "category", creatorId: null, lastMessageAt: "last", messageCount: 7, archived: 1 }
+ expect(normalizeCommunityChannelResourcePreview({ ...input, resourceComplete: true, contractVersion: 3, accessDecision: { canRead: true }, proof: { revision: 7 } }))
+ .toEqual({ ...input, archived: true })
+ })
+ it.each([{ archived: 2 }, { archived: -1 }, { archived: "0" }, { archived: "true" }, { archived: null }, { topic: null },
+ { messageCount: -1 }, { messageCount: 0.5 }, { position: Infinity }, { id: "" },
+ ])("rejects malformed supplied preview facts %j", (fields) => {
+ expect(() => normalizeCommunityChannelResourcePreview({ id: "preview", ...fields })).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: [] })
@@ -56,3 +84,61 @@ describe("common community resources", () => {
}
})
})
+
+
+describe("full v3 resource facts", () => {
+ it("preserves nullable metadata, IDs, order and raw embeds without presentation fields", () => {
+ const value = JSON.parse(JSON.stringify(communityResourceMessageFixture.message))
+ expect(CommunityMessageResourceSchema.parse(value)).toEqual(value)
+ expect(CommunityMessageResourceSchema.parse(CommunityMessageResourceSchema.parse(value))).toEqual(value)
+ expect(value.attachments.map((row: { id: string }) => row.id)).toEqual(["attachment-2", "attachment-1"])
+ for (const key of ["id", "name", "url", "thumbnailUrl", "contentType", "sizeBytes", "width", "height"]) {
+ const attachment = { ...value.attachments[0] }
+ delete attachment[key]
+ expect(CommunityMessageAttachmentSchema.safeParse(attachment).success).toBe(false)
+ }
+ for (const sizeBytes of [-1, 0.5, Infinity]) expect(CommunityMessageAttachmentSchema.safeParse({ ...value.attachments[0], sizeBytes }).success).toBe(false)
+ expect(CommunityMessagePreviewSchema.parse({ id: "preview", type: "chat" })).toEqual({ id: "preview", type: "chat" })
+ expect(CommunityMessageResourceSchema.safeParse({ id: "preview", type: "chat" }).success).toBe(false)
+ })
+ it("decodes only actual storage booleans and requires every full channel field", () => {
+ const value = { ...communityResourceChannelFixture, archived: 0 }
+ expect(communityChannelResourceFromStorage(value)).toEqual(communityResourceChannelFixture)
+ for (const key of Object.keys(value)) {
+ const incomplete: Record<string, unknown> = { ...value }
+ delete incomplete[key]
+ expect(() => communityChannelResourceFromStorage(incomplete)).toThrow()
+ }
+ expect(() => communityChannelResourceFromStorage({ ...value, archived: 2 })).toThrow()
+ const profile = { id: "user-1", name: "Author", discriminator: "12345", avatar: null, avatarVersion: 0 }
+ expect(CommunityResourceProfileSchema.parse(profile)).toEqual(profile)
+ expect(CommunityResourceProfileSchema.parse(profile)).not.toHaveProperty("statusText")
+ })
+})
+
+
+describe("nested resource and legacy preview boundaries", () => {
+ it("keeps unknown legacy nonce and reply identity omitted", () => {
+ const input = { id: "preview", seq: 1, authorId: "author", createdAt: "now", type: "chat", content: "body" }
+ const preview = communityMessagePreviewFromLegacy(input, "channel")
+ for (const field of ["clientNonce", "replyToId", "attachments"]) expect(preview).not.toHaveProperty(field)
+ expect(communityMessagePreviewFromLegacy({ ...input, clientNonce: null, replyToId: null, attachments: [] }, "channel"))
+ .toMatchObject({ clientNonce: null, replyToId: null, attachments: [] })
+ })
+ it("preserves actual nested NULLs only in full 3 and never stores a legacy initial as a fact", () => {
+ const thread = { id: "thread", name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] }
+ const message = { ...communityResourceMessageFixture.message, thread }
+ expect(CommunityMessageResourceSchema.parse(message).thread).toEqual(thread)
+ expect(CommunityLegacyMessageResourceSchema.safeParse({ ...message, attachments: [] }).success).toBe(false)
+ const legacyThread = { ...thread, name: "Thread", lastReplyAt: "now", participants: [{ id: "peer", name: "Peer", avatar: "P", avatarVersion: 4 }] }
+ const legacy = { ...message, authorAvatar: "A", attachments: [], thread: legacyThread }
+ expect(CommunityLegacyMessageResourceSchema.parse(legacy).thread).toEqual(legacyThread)
+ const preview = communityMessagePreviewFromLegacy(legacy, message.channelId)
+ expect(preview.thread?.participants).toEqual([{ id: "peer", name: "Peer", avatarVersion: 4 }])
+ for (const field of ["name", "avatar", "avatarVersion"]) {
+ const participant: Record<string, unknown> = { ...thread.participants[0] }
+ delete participant[field]
+ expect(CommunityMessageResourceSchema.safeParse({ ...message, thread: { ...thread, participants: [participant] } }).success).toBe(false)
+ }
+ })
+})
diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.ts
index 7c0b557f6..e4efedecc 100644
--- a/src/shared/test/community-ws-bundle.contract.test.ts
+++ b/src/shared/test/community-ws-bundle.contract.test.ts
@@ -22,7 +22,7 @@ import {
type CommunityBotAuditEvent,
type CommunityWsEvent,
} from "../src"
-import { communityWsEventFixtures } from "./community-ws-events.fixtures"
+import { communityWsEventFixtures, communityResourceMessageFixture, communityResourceChannelFixture } from "./community-ws-events.fixtures"
function maximizeAuditPadding(): CommunityBotAuditEvent {
let low = 0
@@ -47,12 +47,13 @@ function maximizeAuditPadding(): CommunityBotAuditEvent {
}
describe("community WS batch transport contract", () => {
- it("derives both wire names from one family and the supported contract", () => {
+ it("derives all three 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")
+ expect(communityBrowserEventBatchType(3)).toBe("community:events.batch.v3")
+ expect(() => communityBrowserEventBatchType(4)).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
@@ -295,3 +296,70 @@ describe("community WS batch transport contract", () => {
expect(decodeCommunityBrowserEventBatch(encoded.batch, encoded.byteLength)).toMatchObject({ ok: true })
})
})
+
+
+describe("explicit v3 delivery codec", () => {
+ it.each([1, 2] as const)("projects empty attachments and full channel/identity facts to contract %s", async (contract) => {
+ const events = [
+ { ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, attachments: [] } },
+ { type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: { ...communityResourceChannelFixture, name: null } },
+ { type: "community:channel.child_create", parentChannelId: "channel-1", parentMessageId: "message-1", channel: {
+ ...communityResourceChannelFixture, id: "thread-1", type: "thread", name: null, creatorId: null,
+ parentChannelId: "channel-1", parentMessageId: "message-1",
+ } },
+ { type: WS_EVENTS.IDENTITY_UPDATE, userId: "user-1", avatar: null, avatarVersion: 1 },
+ ]
+ const prepared = await prepareCommunityDeliveryEvents(events, 3)
+ if (!prepared.ok) throw new Error("invalid resource fixtures")
+ const encoded = await encodeCommunityBrowserEventBatchForContract({
+ operationId: await deriveCommunityDeliveryOperationId("legacy-resource-projection"), prepared: prepared.prepared, contract,
+ })
+ if (!encoded.ok) throw new Error("invalid legacy projection")
+ const wire = JSON.parse(encoded.body)
+ expect(wire.type).toBe(communityBrowserEventBatchType(contract))
+ expect(wire.events[0].message).not.toHaveProperty("attachments")
+ expect(wire.events[0].message).not.toHaveProperty("channelId")
+ expect(wire.events[1]).toEqual({ type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: {
+ id: "channel-1", name: "", type: "text", categoryId: null, topic: "Keep this topic", position: 4, createdAt: communityResourceChannelFixture.createdAt,
+ } })
+ expect(wire.events[2]).toEqual({ type: "community:channel.child_create", parentChannelId: "channel-1", parentMessageId: "message-1",
+ channel: { id: "thread-1", name: "", type: "thread", createdAt: communityResourceChannelFixture.createdAt } })
+ expect(wire.events[3]).toEqual({ ...events[3], avatar: "" })
+ expect(await admitCommunityBrowserEventBatch(wire)).toMatchObject({ ok: true, events: wire.events })
+ })
+ it("captures original source bytes before digest and projects strict 1/2/3 frames", async () => {
+ const prepared = await prepareCommunityDeliveryEvents([communityResourceMessageFixture], 3)
+ if (!prepared.ok) throw new Error("invalid v3 fixture")
+ expect(prepared.prepared.contract).toBe(3)
+ expect(JSON.parse(prepared.prepared.bodies[0]!)).toEqual(communityResourceMessageFixture)
+ const operationId = await deriveCommunityDeliveryOperationId("full-resource")
+ for (const contract of [1, 2, 3] as const) {
+ const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract })
+ if (!encoded.ok) throw new Error(`invalid v${contract} projection`)
+ expect(encoded.byteLength).toBe(utf8ByteLength(encoded.body))
+ expect(await admitCommunityBrowserEventBatch(JSON.parse(encoded.body))).toMatchObject({ ok: true })
+ if (contract === 3) {
+ expect(encoded.batch.events).toEqual([communityResourceMessageFixture])
+ expect(encoded.batch.operationDigest).toBe(prepared.prepared.digest)
+ } else {
+ const event = encoded.batch.events[0]
+ if (event.type !== WS_EVENTS.MESSAGE_CREATE) throw new Error("invalid projection")
+ expect(event.message).not.toHaveProperty("channelId")
+ expect(event.message.attachments?.map((row) => "filename" in row ? row.filename : "invalid")).toEqual(["unknown.bin", "photo.png"])
+ expect(JSON.parse(encoded.body).events[0].message).not.toHaveProperty("authorAvatar")
+ }
+ }
+ await expect(prepareCommunityDeliveryEvents([communityResourceMessageFixture])).resolves.toMatchObject({ ok: false })
+ const old = await prepareCommunityDeliveryEvents([communityWsEventFixtures["community:message.create"]])
+ if (!old.ok) throw new Error("invalid old fixture")
+ expect(await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: old.prepared, contract: 3 })).toMatchObject({ ok: false })
+ expect(await encodePreparedCommunityBrowserEventBatch({ operationId, operationDigest: prepared.prepared.digest, prepared: prepared.prepared, contract: 3 })).toMatchObject({ ok: false, reason: "invalid-contract" })
+ const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 3 })
+ if (!encoded.ok) throw new Error("invalid full frame")
+ const tampered = JSON.parse(encoded.body)
+ tampered.events[0].message.attachments.reverse()
+ expect(await admitCommunityBrowserEventBatch(tampered)).toMatchObject({ ok: false })
+ tampered.type = "community:events.batch.v4"
+ expect(await admitCommunityBrowserEventBatch(tampered)).toMatchObject({ ok: false })
+ })
+})
diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.ts
index c0633c4e1..d74fee50f 100644
--- a/src/shared/test/community-ws-events.contract.test.ts
+++ b/src/shared/test/community-ws-events.contract.test.ts
@@ -15,7 +15,7 @@ import {
type CommunityMessageCreate,
type CommunityWsEvent,
} from "../src/community-ws-events"
-import { communityWsEventFixtures, requiredFixturePaths } from "./community-ws-events.fixtures"
+import { communityWsEventFixtures, communityResourceMessageFixture, communityResourceChannelFixture, requiredFixturePaths } from "./community-ws-events.fixtures"
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T
@@ -235,3 +235,41 @@ describe("Community browser event runtime contract", () => {
.toBe(COMMUNITY_BULK_BODY_MAX_BYTES)
})
})
+
+
+describe("explicit v3 browser events", () => {
+ it("admits child resources only with matching parent identities", () => {
+ const event = { type: "community:channel.child_create", parentChannelId: "parent", parentMessageId: "opener", channel: {
+ ...communityResourceChannelFixture, id: "thread", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
+ } }
+ expect(decodeCommunityBrowserEvent(event, 3)).toEqual({ ok: true, event })
+ const { parentMessageId: _parentMessageId, ...withoutOpenerClaim } = event
+ expect(decodeCommunityBrowserEvent(withoutOpenerClaim, 3)).toEqual({ ok: true, event: withoutOpenerClaim })
+ for (const fields of [{ parentChannelId: "other" }, { parentMessageId: "other" }]) {
+ expect(decodeCommunityBrowserEvent({ ...event, ...fields }, 3)).toMatchObject({ ok: false, reason: "invalid-payload" })
+ }
+ })
+ it("requires a positive avatar version on a v3 identity update", () => {
+ const event = { type: WS_EVENTS.IDENTITY_UPDATE, userId: "user-1", avatar: null, avatarVersion: 1 }
+ expect(decodeCommunityBrowserEvent(event, 3)).toEqual({ ok: true, event })
+ for (const avatarVersion of [0, -1, 0.5]) {
+ expect(decodeCommunityBrowserEvent({ ...event, avatarVersion }, 3)).toMatchObject({ ok: false, reason: "invalid-payload" })
+ }
+ })
+ it("requires full resources on create and preserves partial deltas", () => {
+ expect(decodeCommunityBrowserEvent(communityResourceMessageFixture, 3)).toEqual({ ok: true, event: communityResourceMessageFixture })
+ expect(decodeCommunityBrowserEvent(communityResourceMessageFixture, 2).ok).toBe(false)
+ expect(decodeCommunityBrowserEvent(communityWsEventFixtures["community:message.create"], 3).ok).toBe(false)
+ expect(decodeCommunityBrowserEvent({ ...communityResourceMessageFixture, channelId: "other" }, 3).ok).toBe(false)
+ const create = { type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: communityResourceChannelFixture }
+ expect(decodeCommunityBrowserEvent(create, 3)).toEqual({ ok: true, event: create })
+ expect(decodeCommunityBrowserEvent({ ...create, serverId: "other" }, 3).ok).toBe(false)
+ expect(decodeCommunityBrowserEvent({ ...create, channel: { id: "channel-1", name: "Channel", type: "text" } }, 3).ok).toBe(false)
+ const delta = { type: WS_EVENTS.CHANNEL_UPDATE, serverId: "server-1", channelId: "channel-1", changes: { name: "Renamed" } }
+ expect(decodeCommunityBrowserEvent(delta, 3)).toEqual({ ok: true, event: delta })
+ const encoded = encodeCommunityBrowserEvent(communityResourceMessageFixture, 3)
+ expect(encoded.ok).toBe(true)
+ if (encoded.ok) expect(encoded.byteLength).toBe(utf8ByteLength(encoded.body))
+ expect(encodeCommunityBrowserEvent({ ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, content: "😀".repeat(COMMUNITY_BROWSER_EVENT_MAX_BYTES) } }, 3).ok).toBe(false)
+ })
+})
diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.ts
index 196b87077..dbbd681e7 100644
--- a/src/shared/test/community-ws-events.fixtures.ts
+++ b/src/shared/test/community-ws-events.fixtures.ts
@@ -342,3 +342,24 @@ export const requiredFixturePaths = {
"community:machine.removed": ["machineId"],
"community:bot.audit_event": ["payload"],
} satisfies Record<CommunityWsEvent["type"], readonly [string, ...string[]]>
+
+export const communityResourceChannelFixture = {
+ id: "channel-1", type: "text", serverId: "server-1", categoryId: null,
+ name: "Channel", topic: "Keep this topic", parentChannelId: null, parentMessageId: null,
+ creatorId: "user-1", position: 4, archived: false, createdAt: "2026-01-01T00:00:00.000Z",
+ lastMessageAt: null, messageCount: 0,
+} as const
+
+export const communityResourceMessageFixture = {
+ ...communityWsEventFixtures["community:message.create"],
+ message: {
+ id: "message-1", channelId: "channel-1", seq: 1, authorId: "user-1", authorName: "Author",
+ authorAvatar: null, authorAvatarVersion: 0, type: "chat", content: "é 😀", replyToId: null,
+ clientNonce: null, createdAt: "2026-01-01T00:00:00.000Z",
+ attachments: [
+ { id: "attachment-2", name: "unknown.bin", url: "/file", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
+ { id: "attachment-1", name: "photo.png", url: "/photo", thumbnailUrl: "/thumbnail", contentType: "image/png", sizeBytes: 2048, width: 640, height: 480 },
+ ],
+ embeds: [null, { title: "Card", fields: [null, { name: "Key", value: "Value" }] }, { raw: "unknown" }],
+ },
+} as const
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index f695f340d..309a04a13 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -5,8 +5,8 @@ import type {
CommunityMessageEdited,
CommunityMachineCreated,
CommunityMachineUpdated,
- CommunityMachineSummary,
} from "../src/community-ws-events";
+import type { CommunityMachineSummary } from "../src/schemas";
describe("CommunityChannelDelete post-unit address contract", () => {
it("accepts canonical post identity while preserving legacy/top-level compatibility", () => {
diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.ts
index 61f84cad8..ba9a92592 100644
--- a/src/shared/test/queries/community-thread.test.ts
+++ b/src/shared/test/queries/community-thread.test.ts
@@ -54,6 +54,7 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {
image TEXT
,avatarVersion INTEGER NOT NULL DEFAULT 0
,avatarObjectKey TEXT
+ ,discriminator TEXT
);
CREATE TABLE community_channel_member (
id TEXT PRIMARY KEY,
@@ -176,6 +177,24 @@ describe("listForumThreadsByCreatedAt against real SQLite", () => {
expect(rows.map((row) => row.userId)).toEqual(["A", "a"]);
});
+ it.each([undefined, 1])("retains real participant numbers across chunks and duplicate channel ids (limit %s)", async (limit) => {
+ sqlite.prepare("INSERT INTO user (id, name, discriminator) VALUES (?, ?, ?)").run("numbered", "Numbered", "123456");
+ sqlite.prepare("INSERT INTO user (id, name, discriminator) VALUES (?, ?, ?)").run("later", "Later", "0042");
+ const insert = sqlite.prepare("INSERT INTO community_channel_member (id, channel_id, user_id, relation, source, added_at) VALUES (?, ?, ?, 'notify', 'added', ?)");
+ const channelIds = Array.from({ length: 100 }, (_, index) => `numbered_thread_${index}`);
+ for (const channelId of channelIds) {
+ insert.run(`${channelId}:first`, channelId, "numbered", "2026-10-11T01:00:00Z");
+ insert.run(`${channelId}:second`, channelId, "later", "2026-10-11T02:00:00Z");
+ }
+ const rows = await threadQueries.listParticipantsForChannels(db as never, [...channelIds, ...channelIds], limit);
+ expect(rows).toHaveLength(limit === undefined ? 200 : 100);
+ expect(rows.filter((row) => row.userId === "numbered")).toHaveLength(100);
+ expect(rows.filter((row) => row.userId === "numbered").every((row) => row.discriminator === "123456")).toBe(true);
+ expect(new Set(rows.map((row) => `${row.channelId}:${row.userId}`)).size).toBe(rows.length);
+ if (limit !== undefined) expect(rows.every((row) => "participantCount" in row && row.participantCount === 2)).toBe(true);
+ else expect(rows.filter((row) => row.userId === "later").every((row) => row.discriminator === "0042")).toBe(true);
+ });
+
it("keeps retained disposition explicit when the participating query is disabled", async () => {
for (const params of [
{ parentChannelIds: [] as string[], limitPerParent: 5 },
diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.ts
index 9574625a0..3d2828869 100644
--- a/src/shared/test/schemas/community-runtime.test.ts
+++ b/src/shared/test/schemas/community-runtime.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
import {
CommunityMachineRuntimeSchema,
CommunityMachineRuntimeListSchema,
+ CommunityMachineSummarySchema,
CommunityDaemonReadySchema,
HostReadyMessageSchema,
MachineHeartbeatAckMessageSchema,
@@ -12,6 +13,29 @@ import {
COMMUNITY_REASONING_DESCRIPTION_MAX,
COMMUNITY_REASONING_MODELS_MAX,
} from "../../src/schemas";
+import { CommunityWsEventSchema } from "../../src/community-ws-events";
+
+describe("CommunityMachineSummarySchema", () => {
+ const summary = { id: "machine", hostname: "host", displayName: "Host", platform: "darwin", arch: "arm64", osRelease: "26", daemonVersion: "0.1.48", lastSeenAt: null, status: "offline", availableRuntimes: [], createdAt: "2026-10-11T01:00:00Z", updatedAt: "2026-10-11T01:00:00Z" };
+ it("keeps actual empty runtime lists and applies the same complete contract to WS", () => {
+ expect(CommunityMachineSummarySchema.parse(summary)).toEqual(summary);
+ expect(CommunityWsEventSchema.parse({ type: "community:machine.updated", machine: summary })).toEqual({ type: "community:machine.updated", machine: summary });
+ const { availableRuntimes: _runtimes, ...missing } = summary;
+ expect(CommunityMachineSummarySchema.safeParse(missing).success).toBe(false);
+ expect(CommunityWsEventSchema.safeParse({ type: "community:machine.updated", machine: missing }).success).toBe(false);
+ });
+ it("rejects unknown summary, runtime and error fields without changing runtime health tolerance", () => {
+ for (const invalid of [
+ { ...summary, extra: true },
+ { ...summary, availableRuntimes: [{ id: "codex", extra: true }] },
+ { ...summary, lastRuntimeError: { requested: "codex", available: [], at: summary.updatedAt, extra: true } },
+ ]) {
+ expect(CommunityMachineSummarySchema.safeParse(invalid).success).toBe(false);
+ expect(CommunityWsEventSchema.safeParse({ type: "community:machine.updated", machine: invalid }).success).toBe(false);
+ }
+ expect(CommunityMachineSummarySchema.parse({ ...summary, availableRuntimes: [{ id: "codex", status: null }] }).availableRuntimes).toEqual([{ id: "codex", status: "healthy" }]);
+ });
+});
describe("CommunityMachineRuntimeSchema", () => {
it("accepts a plain id and defaults status to 'healthy' (wire back-compat for older daemons)", () => {
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.ts
index a76825398..370929c9d 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,7 +18,7 @@ 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 { requestsCommunityContract, requestedCommunityContract } from "@alook/shared"
import { readCommunityMembers } from "@/lib/community/member-read"
import { resolveMessageTarget } from "@/lib/community/message-door"
@@ -49,7 +49,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
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"))
+ return readCommunityMembers(db, resolved.value.target.channelId, ctx.actor.userId, req.nextUrl.searchParams.get("relation"), requestedCommunityContract(req.headers) === 3 ? 3 : 2)
}
if (ctx.actor.kind === "bot") {
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index 63229571e..751f49d38 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
@@ -283,6 +283,24 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetDMBetween.mockResolvedValue(null)
})
+ it.each([false, true])("confirms a full v3 human message with replay=%s", async (replay) => {
+ const row = { id: "m1", channelId: "c1", seq: 12, authorId: "u1", authorName: "Alice", authorImage: null, authorAvatarVersion: 0,
+ content: "hello", type: "default", mentionType: null, replyToId: null, clientNonce: "v3-nonce", embeds: null, createdAt: "now" }
+ mockGetMessage.mockResolvedValue(row)
+ mockGetMessageByAuthorAndNonce.mockResolvedValue(replay ? row : null)
+ const request = postReq({ content: "hello", nonce: "v3-nonce" })
+ request.headers.set("x-alook-community-contract", "3")
+ const response = await POST(request, ctx)
+ expect(response.status).toBe(replay ? 200 : 201)
+ expect(response.headers.get("x-alook-community-contract")).toBe("3")
+ expect(await response.json()).toEqual({ contractVersion: 3, channelId: "c1", deduped: replay, message: {
+ id: "m1", channelId: "c1", seq: 12, authorId: "u1", authorName: "Alice", authorAvatar: null, authorAvatarVersion: 0,
+ content: "hello", type: "chat", mentionType: null, replyToId: null, clientNonce: "v3-nonce", createdAt: "now", attachments: [],
+ } })
+ if (replay) expect(mockCreateMessage).not.toHaveBeenCalled()
+ else expect(mockCreateMessage).toHaveBeenCalledOnce()
+ })
+
it.each([
{
name: "field types",
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.ts
index c20edf990..168b7e17d 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
@@ -15,7 +15,7 @@ import {
} from "@/lib/community/messages"
import { mapPostedMessageForApi } from "@/lib/community/message-payload"
import { enrichMessages } from "@/lib/community/enrich-messages"
-import { requestsCommunityContract } from "@alook/shared"
+import { requestsCommunityContract, requestedCommunityContract, COMMUNITY_CONTRACT_HEADER, CommunityMessagePostedSchema, type CommunityContract } from "@alook/shared"
import { writeCommunityMessagesRead } from "@/lib/community/read-contract"
import { checkRateLimit } from "@/lib/rate-limit"
import { createCommunityMessage, getCommunityMessageReplay } from "@/lib/community/message-handler"
@@ -152,7 +152,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
{ hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },
)
- const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)
+ const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum, contract: requestedCommunityContract(req.headers) ?? 1 }, items)
return writeCommunityMessagesRead(req, channelId, { messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq, surfaceReceipt })
}
@@ -164,7 +164,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
tag,
})
const { items, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor } = buildSinceResponse(rows, pageSize)
- const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)
+ const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum, contract: requestedCommunityContract(req.headers) ?? 1 }, items)
return writeCommunityMessagesRead(req, channelId, { messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq, surfaceReceipt })
}
@@ -176,7 +176,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())
+ const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum, contract: requestedCommunityContract(req.headers) ?? 1 }, items.slice().reverse())
return writeCommunityMessagesRead(req, channelId, { messages, hasMore, cursor: nextCursor, latestSeq, surfaceReceipt })
})
@@ -218,7 +218,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
if (ctx.actor.kind === "bot") {
return handleBotSend(db, ctx.actor.userId, ctx.env, raw)
}
- return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw)
+ return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, requestedCommunityContract(req.headers) ?? 1)
})
/**
@@ -233,6 +233,7 @@ async function handleHumanSend(
env: Env,
pathId: string | undefined,
raw: unknown,
+ contract: CommunityContract,
): Promise<NextResponse> {
if (!pathId || pathId === REF_PLACEHOLDER_ID) {
return NextResponse.json({ error: "missing channel id" }, { status: 400 })
@@ -275,11 +276,11 @@ async function handleHumanSend(
source: "web",
})
if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })
- return NextResponse.json({
- message: created.message,
+ return humanMessageConfirmation(contract, target.channelId, {
+ message: contract === 3 ? await mapPostedMessageForApi(db, target.channelId, created.message, contract) : created.message,
threadId: created.thread.id,
deduped: created.deduped,
- }, { status: created.deduped ? 200 : 201 })
+ }, created.deduped ? 200 : 201)
}
const replay = await getCommunityMessageReplay({
@@ -289,7 +290,7 @@ async function handleHumanSend(
clientNonce,
})
if (replay) {
- return NextResponse.json({ message: await mapPostedMessageForApi(db, target.channelId, replay.row), deduped: true }, { status: 200 })
+ return humanMessageConfirmation(contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, replay.row, contract), deduped: true }, 200)
}
const result = await createCommunityMessage({
@@ -303,7 +304,14 @@ 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: await mapPostedMessageForApi(db, target.channelId, result.row), deduped: result.deduped }, { status: 201 })
+ return humanMessageConfirmation(contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, result.row, contract), deduped: result.deduped }, 201)
+}
+
+function humanMessageConfirmation(contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): NextResponse {
+ if (contract !== 3) return NextResponse.json(payload, { status })
+ return NextResponse.json(CommunityMessagePostedSchema.parse({ contractVersion: 3, channelId, ...payload, deduped: payload.deduped === true }), {
+ status, headers: { [COMMUNITY_CONTRACT_HEADER]: "3" },
+ })
}
/**
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.test.ts b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
index 6ba916d9a..4149954a2 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
@@ -118,6 +118,20 @@ describe("PUT /api/community/channels/[id]/read", () => {
mockIsBlocked.mockResolvedValue(false)
})
+ it.each([2, 3] as const)("confirms contract %s with the committed exact target and revision", async (contract) => {
+ allow()
+ mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", createdAt: "now", seq: 6 })
+ const request = putReq({ lastReadMessageId: "m1" })
+ request.headers.set("x-alook-community-contract", String(contract))
+ const response = await PUT(request, { params: { id: "c1" } } as never)
+ expect(response.status).toBe(200)
+ expect(response.headers.get("x-alook-community-contract")).toBe(String(contract))
+ expect(await response.json()).toEqual({ contractVersion: contract, channelId: "c1", changed: true, targetSeq: 6, revision: 7 })
+ expect(mockMarkReadToExistingMessageBuilder).toHaveBeenCalledWith(expect.anything(), { userId: "u1", channelId: "c1",
+ message: { id: "m1", channelId: "c1", createdAt: "now", seq: 6 } })
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledOnce()
+ })
+
it.each(["text", "forum", "thread", "dm"])(
"uses the same exact-target cursor path for %s channels",
async (type) => {
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.ts
index cfcda2e9c..2a316174f 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,4 +1,4 @@
-import { COMMUNITY_CONTRACT_VERSION, requestsCommunityContract, CommunityReadAdvanceSchema } from "@alook/shared"
+import { requestsCommunityContract, requestedCommunityContract, communityReadSchemas } from "@alook/shared"
import { writeCommunityContractJSON } from "@/lib/community/read-contract"
import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
@@ -123,6 +123,9 @@ 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 }))
+ if (requestsCommunityContract(req.headers)) {
+ const contract = requestedCommunityContract(req.headers) === 3 ? 3 : 2
+ return writeCommunityContractJSON(communityReadSchemas(contract).readAdvance.parse({ contractVersion: contract, channelId, changed, targetSeq: target.seq, revision }), contract)
+ }
return writeJSON({ changed, targetSeq: target.seq, revision })
})
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.ts
index 36804327f..14bbbf6c3 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,7 +2,7 @@ import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH, requestsCommunityContract } from "@alook/shared"
+import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH, requestsCommunityContract, requestedCommunityContract } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
import { writeCommunityThreadsRead } from "@/lib/community/thread-read"
import { parseBoundedInt } from "@/lib/community/messages"
@@ -15,13 +15,14 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const currentContract = requestsCommunityContract(req.headers)
+ const contract = requestedCommunityContract(req.headers) === 3 ? 3 : 2
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, [])
+ if (channel.type === "dm") return writeCommunityThreadsRead(db, ctx.userId, channel, [], undefined, undefined, contract)
const archivedParam = req.nextUrl.searchParams.get("archived")
const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefined
@@ -124,7 +125,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
])
if (currentContract) {
- return writeCommunityThreadsRead(db, ctx.userId, channel, threads, { messages: [...parentMessages, ...firstMessages], tags, participants }, { hasMore, nextCursor: nextCursor ?? null })
+ return writeCommunityThreadsRead(db, ctx.userId, channel, threads, { messages: [...parentMessages, ...firstMessages], tags, participants }, { hasMore, nextCursor: nextCursor ?? null }, contract)
}
return writeJSON({
serverId: channel.serverId,
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index acbe26e0c..30f9cbf7b 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -20,6 +20,8 @@ import {
} from "@/lib/community/fanout"
import { loadApiMessageContext, mapMessageForApi } from "@/lib/community/message-payload"
import { scheduleForumPostMediaCleanup } from "@/lib/community/forum-post-media-cleanup"
+import { CommunityMessageReadSchema, requestedCommunityContract, type CommunityContract } from "@alook/shared"
+import { writeCommunityContractJSON } from "@/lib/community/read-contract"
// A bot addresses by ref-in-query (`?ref=` + `?seq=`, the folded `resolve`
// verb); the path `[id]` is then the `resolve` placeholder (a ref carries `/`
@@ -56,7 +58,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
if (ctx.actor.kind === "bot") {
return handleBotResolve(db, ctx.actor.userId, req)
}
- return handleHumanGet(db, ctx.actor.userId, ctx.params?.id)
+ return handleHumanGet(db, ctx.actor.userId, ctx.params?.id, requestedCommunityContract(req.headers) ?? 1)
})
/** PATCH /api/community/messages/[id] — edit only the caller's own text.
@@ -224,6 +226,7 @@ async function handleHumanGet(
db: ReturnType<typeof getDb>,
userId: string,
messageId: string | undefined,
+ contract: CommunityContract,
) {
if (!messageId || messageId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)
@@ -245,7 +248,8 @@ async function handleHumanGet(
? queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId], { channelId: message.channelId })
: Promise.resolve([]),
)
- const payload = mapMessageForApi(message, contextForChannel(message.channelId))
+ const payload = mapMessageForApi(message, contextForChannel(message.channelId), contract === 3 ? 3 : 1, message.channelId)
+ if (contract === 3) return writeCommunityContractJSON(CommunityMessageReadSchema.parse({ contractVersion: 3, channelId: message.channelId, message: payload }), 3)
return writeJSON({ ...payload, channelId: message.channelId })
}
diff --git a/src/web/src/app/api/daemon/sweep/route.ts b/src/web/src/app/api/daemon/sweep/route.ts
index 363e45903..ab815d7c7 100644
--- a/src/web/src/app/api/daemon/sweep/route.ts
+++ b/src/web/src/app/api/daemon/sweep/route.ts
@@ -1,5 +1,5 @@
import { NextRequest } from "next/server";
-import { SweepRequestSchema } from "@alook/shared";
+import { HeartbeatRequestSchema } from "@alook/shared";
import { getDb } from "@/lib/db";
import { withAuth } from "@/lib/middleware/auth";
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
@@ -10,7 +10,7 @@ import { log } from "@/lib/logger";
export const POST = withAuth(async (req: NextRequest, ctx) => {
const { throttled } = await import("@/lib/cache");
- const [, err] = await parseBody(req, SweepRequestSchema);
+ const [, err] = await parseBody(req, HeartbeatRequestSchema);
if (err) return err;
if (!ctx.workspaceId) {
diff --git a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx b/src/web/src/app/c/QueryProvider.observability.dom.test.tsx
index 93121975c..e7f31b2a7 100644
--- a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.observability.dom.test.tsx
@@ -32,7 +32,7 @@ function activate(id: string) {
}
async function seed(id: string) {
const client = new QueryClient()
- client.setQueryData(key(id), [{ userId: id, name: "Private " + id, discriminator: "0001", avatar: "A", avatarVersion: 0 }], { updatedAt: Date.now() - 1000 })
+ client.setQueryData(key(id), [{ id, identityComplete: true, name: "Private " + id, discriminator: "0001", avatar: "A", avatarVersion: 0 }], { updatedAt: Date.now() - 1000 })
await createIdbPersister(id).persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) })
client.clear()
}
@@ -82,7 +82,7 @@ it("attributes a delayed real IDB snapshot only after the actual Provider hydrat
expect(events.some(event => event.name === "cache.restore.finish" && event.attributes.phase === "hydrate")).toBe(false)
await act(async () => read.release())
await waitFor(() => expect(restoring.get("account-a")).toBe(false))
- expect(client.getQueryData(key("account-a"))).toEqual([expect.objectContaining({ userId: "account-a" })])
+ expect(client.getQueryData(key("account-a"))).toEqual([expect.objectContaining({ id: "account-a" })])
expect(events.filter(event => event.name === "cache.restore.finish").map(event => [event.attributes.phase, event.attributes.outcome])).toEqual([["idb_read", "hit"], ["deserialize", "hit"], ["hydrate", "success"]])
expect(JSON.stringify(events)).not.toContain("Private")
})
@@ -123,6 +123,6 @@ it("regrant during a real Provider restore preserves business hydration without
events.length = 0
await act(async () => read.release())
await waitFor(() => expect(restoring.get("account-a")).toBe(false))
- expect(client.getQueryData(key("account-a"))).toEqual([expect.objectContaining({ userId: "account-a" })])
+ expect(client.getQueryData(key("account-a"))).toEqual([expect.objectContaining({ id: "account-a" })])
expect(events.filter(event => event.name.startsWith("cache.restore."))).toEqual([])
})
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.tsx
index 0cfa61507..394b09528 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
@@ -86,7 +86,7 @@ describe("QueryProvider persistence ordering", () => {
const viewerId = "restore-order-viewer"
const profileKey = communityKeys.communityDbCollection(viewerId, "profiles")
const seed = new QueryClient()
- seed.setQueryData(profileKey, [{ userId: viewerId, name: "Disk viewer", discriminator: "0001", avatar: "D", avatarVersion: 1 }], { updatedAt: Date.now() - 60_000 })
+ seed.setQueryData(profileKey, [{ id: viewerId, identityComplete: true, name: "Disk viewer", discriminator: "0001", avatar: "D", avatarVersion: 1 }], { updatedAt: Date.now() - 60_000 })
persister.restoreClient.mockResolvedValue(hasDiskSnapshot ? { buster: PERSIST_BUSTER, timestamp: Date.now(), clientState: dehydrate(seed) } : undefined)
const mark = vi.spyOn(performance, "mark")
mark.mockClear()
@@ -130,7 +130,7 @@ describe("QueryProvider persistence ordering", () => {
)
seedClient.setQueryData(
communityKeys.communityDbCollection(viewerId, "channels"),
- [{
+ [{ topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "persisted-dm",
serverId: null,
categoryId: null,
@@ -170,7 +170,7 @@ describe("QueryProvider persistence ordering", () => {
seedClient.setQueryData(
communityKeys.communityDbCollection(viewerId, "profiles"),
[{
- userId: "peer",
+ identityComplete: true, id: "peer",
name: "Persisted peer",
discriminator: "0001",
avatar: "P",
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index 061051fe2..6c69fbf5f 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -35,6 +35,7 @@ import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { installCommunityDbSync } from "@/lib/community-db/sync"
import { profileSchema } from "@/lib/community-db/schema"
+import { avatarInitial } from "@/lib/community/avatar"
import type { CurrentUser } from "@/contexts/community/current-user"
import { observeHydration, discardHydration } from "@/lib/observability/restore"
import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"
@@ -129,8 +130,10 @@ function ScopedQueryProvider({
const client = createQueryClient()
if (initialUser && initialUser.id === userId) {
client.setQueryData(communityKeys.communityDbCollection(userId, "profiles"), [profileSchema.parse({
- userId, name: initialUser.name, discriminator: initialUser.discriminator ?? "",
- avatar: initialUser.avatar, avatarVersion: initialUser.avatarVersion ?? 0,
+ id: userId, name: initialUser.name, discriminator: initialUser.discriminator || null,
+ ...(initialUser.avatar === avatarInitial(initialUser.name) ? {} : { avatar: initialUser.avatar }),
+ avatarVersion: initialUser.avatarVersion,
+ identityComplete: !!initialUser.discriminator && initialUser.avatar !== avatarInitial(initialUser.name) && initialUser.avatarVersion !== undefined,
aboutMe: initialUser.aboutMe, statusEmoji: initialUser.statusEmoji, statusText: initialUser.statusText,
})], { updatedAt: 0 })
}
diff --git a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
index 9c1130772..bd89a211d 100644
--- a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
+++ b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
@@ -49,7 +49,7 @@ describe("real DmView accepted send UI lifecycle", () => {
expect(mocks.api.mock.calls[0][0]).toBe("/api/community/channels/dm_1/messages")
view.rerender(React.createElement(DmView, { dmId: "dm_2" }))
expect(options.signal.aborted).toBe(false)
- await act(async () => finish({ message: { id: "confirmed", seq: 9, type: "chat", content: body.content, authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T00:00:00Z", embeds: [] } }))
+ await act(async () => finish({ message: { id: "confirmed", seq: 9, type: "chat", content: body.content, authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T00:00:00Z", embeds: [] } }))
await waitFor(() => expect(owner.registry.collections.messages.get("confirmed")?.channelId).toBe("dm_1"))
expect(mocks.advance).not.toHaveBeenCalled()
expect(mocks.api).toHaveBeenCalledOnce()
@@ -59,7 +59,7 @@ describe("real DmView accepted send UI lifecycle", () => {
const owner = await createCommunityQueryOwner("u_me")
owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })
owner.runtime.messageStream.actions.dispatch({ kind: "dm", id: "dm_1" }, { type: "postFail", nonce: "retry_nonce" })
- mocks.api.mockResolvedValueOnce({ message: { id: "confirmed", seq: 9, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T00:00:00Z", embeds: [] } })
+ mocks.api.mockResolvedValueOnce({ message: { id: "confirmed", seq: 9, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T00:00:00Z", embeds: [] } })
const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })
await act(async () => screen.getByRole("button", { name: action === "send" ? "Send" : "Retry" }).click())
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.ts
index 7767791fc..bdfd95be4 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,14 +11,14 @@ import { useCommunityRuntime } from "@/stores/community/runtime"
import { useCallback, useEffect, useLayoutEffect, useMemo } from "react"
-import { materializeIntent, type CanonicalMessage } from "@/lib/community/message-stream"
+import { materializeIntent } from "@/lib/community/message-stream"
+import { presentCanonicalMessage } from "@/lib/community/message-wire"
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, CommunityMessageResource, CommunityResourceProfile } from "@alook/shared"
import { apiFetchProfiles } from "@/lib/community/profile-seed"
-import { avatarInitial } from "@/lib/community/avatar"
import type { Msg } from "@/lib/community/models/message"
import type { SendAttachment } from "./composer"
import {
@@ -127,7 +127,7 @@ export function useMessageChannelController({
"/api/community/messages/search?" + params,
(response) => response.results.map((result) => ({
id: result.author.id, identityAbout: { name: result.author.name },
- avatar: { avatar: result.author.image ?? avatarInitial(result.author.name), avatarVersion: result.author.avatarVersion },
+ avatar: { avatar: result.author.image, avatarVersion: result.author.avatarVersion },
})),
communityRequestOptions(profileQueryClient, token, signal), token.registry,
)
@@ -204,7 +204,7 @@ export function useMessageChannelController({
const getMessage = useCallback((id: string): Msg | undefined => {
const registry = getCommunityDbRegistry(profileQueryClient)
const row = registry?.collections.messages.get(id)
- let message: Msg | undefined = row?.channelId === channelId ? row as CanonicalMessage : undefined
+ let message: Msg | undefined = row?.channelId === channelId ? presentCanonicalMessage(row) : 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)
@@ -212,7 +212,8 @@ export function useMessageChannelController({
}
if (!message) return undefined
const profile = message.authorId ? registry?.collections.profiles.get(message.authorId) : undefined
- return profile ? { ...message, authorName: profile.name, authorAvatar: profile.avatar, authorAvatarVersion: profile.avatarVersion } : message
+ const identity = profile ? readCommunityProfile(profile, profile.id) : null
+ return identity ? { ...message, authorName: identity.name, authorAvatar: identity.avatar, authorAvatarVersion: identity.avatarVersion } : message
}, [profileQueryClient, communityRuntime, channelId])
const jumpToSeq = useCallback((seq: number) => {
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
index 069c00e3e..67f3000f3 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
@@ -76,7 +76,10 @@ export function CommunityOnboardingForm() {
avatar: { avatar: bot.image ?? requested.image, avatarVersion: bot.avatarVersion },
}], origin.registry, { snapshot: profileSnapshot })
},
- resolveBot: (id) => origin.registry?.collections.profiles.get(id),
+ resolveBot: (id) => {
+ const profile = origin.registry?.collections.profiles.get(id)
+ return profile?.name === undefined ? undefined : { name: profile.name, discriminator: profile.discriminator ?? undefined }
+ },
readChannels: async (serverId) => {
assert()
await queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
@@ -89,7 +92,7 @@ export function CommunityOnboardingForm() {
assert()
await queryClient.query({ ...options, select: undefined })
assert()
- return [...origin.registry!.collections.channels.values()].filter((channel) => channel.serverId === serverId && !channel.parentChannelId).map(({ id, name, type, categoryId }) => ({ id, name, type, categoryId: categoryId ?? null }))
+ return [...origin.registry!.collections.channels.values()].filter((channel) => channel.serverId === serverId && !channel.parentChannelId).map(({ id, name, type, categoryId }) => ({ id, name: name ?? "", type, categoryId: categoryId ?? null }))
} finally { assert.signal.removeEventListener("abort", unsubscribe); unsubscribe() }
},
},
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
index 0640fdb33..acfc6baa9 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
@@ -389,7 +389,7 @@ describe("useShellInboxController", () => {
const actualVerifier = await vi.importActual<typeof import("@/hooks/community/channel-route-verification")>("@/hooks/community/channel-route-verification")
mocks.warmup.mockImplementation(actualWarmup.startConversationNavigationWarmup)
mocks.verifyDm.mockImplementation(actualVerifier.startChannelRouteVerification)
- const metadata = { id: "dm1", serverId: null, type: "dm", name: null,
+ const metadata = { categoryId: null, topic: "", position: 0, messageCount: 0, id: "dm1", serverId: null, type: "dm", name: null,
parentChannelId: null, parentMessageId: null, creatorId: null, archived: false,
lastMessageAt: null, createdAt: "2026-10-02T00:00:00Z" }
const json = (value: unknown) => new Response(JSON.stringify(value), { status: 200, headers: { "Content-Type": "application/json" } })
diff --git a/src/web/src/contexts/community/current-user.tsx b/src/web/src/contexts/community/current-user.tsx
index 99921ef87..3f6a2fd33 100644
--- a/src/web/src/contexts/community/current-user.tsx
+++ b/src/web/src/contexts/community/current-user.tsx
@@ -62,7 +62,7 @@ export function useCurrentUser(): CurrentUser {
avatar: profile?.avatar ?? "",
avatarVersion: profile?.avatarVersion,
aboutMe: profile?.aboutMe,
- discriminator: profile?.discriminator,
+ discriminator: profile?.discriminator ?? undefined,
statusEmoji: profile?.statusEmoji,
statusText: profile?.statusText,
presence: profile?.presence,
diff --git a/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts b/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
index 3a91b2c6d..8bbf35ab0 100644
--- a/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
@@ -14,7 +14,7 @@ import { materializeMessageStream } from "@/lib/community/message-stream"
function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
const author = { id: "u_me", name: "Me", avatar: "M" }
-const posted = { message: { id: "confirmed", seq: 12, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T01:00:00Z", embeds: [] } }
+const posted = { message: { id: "confirmed", seq: 12, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T01:00:00Z", embeds: [] } }
afterEach(() => vi.unstubAllGlobals())
describe("accepted IO survives real view retirement", () => {
diff --git a/src/web/src/hooks/community/channel-metadata.test.ts b/src/web/src/hooks/community/channel-metadata.test.ts
index 81fbc6cc9..155d98929 100644
--- a/src/web/src/hooks/community/channel-metadata.test.ts
+++ b/src/web/src/hooks/community/channel-metadata.test.ts
@@ -10,7 +10,7 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => fetchMock
const metadata = {
id: "child", serverId: "server", type: "thread", name: "Child",
parentChannelId: "parent", parentMessageId: "opener", creatorId: "owner",
- archived: 0, lastMessageAt: null, createdAt: "2026-09-05T00:00:00Z",
+ topic: "Actual topic", categoryId: null, position: 0, messageCount: 0, archived: false, lastMessageAt: null, createdAt: "2026-09-05T00:00:00Z",
}
beforeEach(() => {
@@ -68,7 +68,7 @@ describe("canonical channel metadata lifecycle", () => {
const serverId = type === "dm" ? null : "server"
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 })
+ await expect(fetchChannelMetadata(client, serverId, "child")).resolves.toMatchObject({ id: "child", serverId, type, name: type === "dm" ? null : metadata.name })
expect(runtime.ws.get().channelAccessScopes.has("child")).toBe(true)
})
it.each(["account", "parent", "server", "membership"] as const)(
diff --git a/src/web/src/hooks/community/channel-metadata.ts b/src/web/src/hooks/community/channel-metadata.ts
index a0bfa38ac..8bdff3bb2 100644
--- a/src/web/src/hooks/community/channel-metadata.ts
+++ b/src/web/src/hooks/community/channel-metadata.ts
@@ -5,9 +5,10 @@ import { retryConversationRead, withConversationReadDeadline } from "@/lib/commu
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"
+import { CommunityChannelResourceSchema, type CommunityChannelIdentity, type CommunityChannelResource, type CommunityAccessDecision } from "@alook/shared"
-export type ChannelMetadata = CommunityChannelIdentity & {
+export type ChannelMetadata = CommunityChannelResource & {
+ resourceComplete: true
accessDecision?: CommunityAccessDecision
}
@@ -50,7 +51,7 @@ export async function fetchChannelMetadata(
let meta: ChannelMetadata
try {
const response = await apiFetch<ChannelMetadata>(`/api/community/channels/${encodeURIComponent(channelId)}`, { ...communityRequestOptions(queryClient, token, readSignal, assertActive), ...(observation && { observation }) })
- meta = { ...response, ...normalizeCommunityChannelIdentity(response) }
+ meta = { ...response, ...CommunityChannelResourceSchema.strip().parse(response), resourceComplete: true }
assertActive()
} catch (error) {
assertActive()
@@ -67,7 +68,7 @@ export async function fetchChannelMetadata(
if (serverId) token.registry!.runtime.ws.actions.grantServerAccess(serverId)
token.registry!.runtime.ws.actions.rememberChannelAccess(serverId, channelId, meta.parentChannelId)
}
- return { ...meta, name: meta.name ?? "",
+ return { ...meta,
activityAt: meta.lastMessageAt ?? meta.createdAt ?? "", identityProof: token }
})
}
diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.ts
index 8856129b3..f6524b755 100644
--- a/src/web/src/hooks/community/community-ws/cache.test.ts
+++ b/src/web/src/hooks/community/community-ws/cache.test.ts
@@ -27,7 +27,7 @@ describe("community WS canonical publication and ID windows", () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
ingestMessages(registry, "ch_1", [{ id: "m_1", content: "one" }, { id: "m_2", content: "two" }])
const other = registry.collections.messages.get("m_2")
- const profile = { id: "u_1", name: "User", discriminator: "0001", image: null }
+ const profile = { id: "u_1", name: "User", discriminator: "0001", image: null, avatarVersion: 0 }
const approval = { friendshipId: "friendship_1", status: "approved" as const, waitingOn: null, otherProfile: profile, botProfile: { ...profile, id: "bot_1" } }
projectCommunityWsEventToDb(client, { type: "community:message.updated", channelId: "ch_1", messageId: "m_1", approval })
projectCommunityWsEventToDb(client, { type: "community:message.edited", channelId: "ch_1", messageId: "m_1", content: "edited" })
diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.ts
index 34a8cbaaf..9cd33f804 100644
--- a/src/web/src/hooks/community/community-ws/handler-context.ts
+++ b/src/web/src/hooks/community/community-ws/handler-context.ts
@@ -1,7 +1,7 @@
import type { QueryClient } from "@tanstack/react-query"
import type { CommunityRuntime } from "@/stores/community/runtime"
import type { CommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
-import type { CommunityWsEvent } from "@alook/shared"
+import type { CommunityWsEvent, CommunityContract } from "@alook/shared"
export type Subscription = {
// The focused regular channel/thread.
@@ -20,6 +20,7 @@ export type Subscription = {
* hook usable in places where the viewer identity isn't yet loaded.
*/
export type UseCommunityWsOptions = {
+ communityContract?: CommunityContract
viewerUserId?: string | null
}
@@ -29,6 +30,7 @@ export type CommunityInboxRefreshRequest = {
}
export type CommunityWsDispatchContext = {
+ contract?: CommunityContract
deliveryMode: "single" | "batch"
queryClient: QueryClient
communityStore: CommunityRuntime["ui"]
diff --git a/src/web/src/hooks/community/community-ws/identity-events.test.ts b/src/web/src/hooks/community/community-ws/identity-events.test.ts
index 927b9e299..44c0fb359 100644
--- a/src/web/src/hooks/community/community-ws/identity-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/identity-events.test.ts
@@ -20,7 +20,7 @@ async function harness() {
function profile(queryClient: QueryClient, userId: string) {
return queryClient.getQueryData<ProfileRow[]>(
communityKeys.communityDbCollection("viewer", "profiles"),
- )?.find((row) => row.userId === userId)
+ )?.find((row) => row.id === userId)
}
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.ts
index ee464d51f..a688be116 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
@@ -620,7 +620,7 @@ describe("membership metadata and access lifetime", () => {
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 })
+ api.mockResolvedValue({ categoryId: null, topic: "", position: 0, messageCount: 0, creatorId: null, createdAt: "2026-10-01T00:00:00Z", lastMessageAt: null, 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)
@@ -679,7 +679,7 @@ describe("membership metadata and access lifetime", () => {
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))
+ ? Promise.resolve({ categoryId: null, topic: "", position: 0, messageCount: 0, 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)
@@ -695,7 +695,7 @@ describe("membership metadata and access lifetime", () => {
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",
+ const payload = { categoryId: null, topic: "", position: 0, messageCount: 0, 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",
@@ -743,7 +743,7 @@ describe("membership metadata and access lifetime", () => {
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",
+ const payload = { categoryId: null, topic: "", position: 0, messageCount: 0, 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"))
@@ -763,7 +763,7 @@ describe("membership metadata and access lifetime", () => {
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")
- const payload = {
+ const payload = { categoryId: null, topic: "", position: 0, messageCount: 0,
id: "child", serverId: "server", type: "thread", parentChannelId: "parent",
parentMessageId: "opener", creatorId: "u_me", name: "Current child", archived: false,
lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",
@@ -807,7 +807,7 @@ describe("membership metadata and access lifetime", () => {
it("hands one batched add/remove to the latest participation generation", async () => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("server", "parent", "text", "child")
- const payload = {
+ const payload = { categoryId: null, topic: "", position: 0, messageCount: 0,
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",
}
@@ -838,7 +838,7 @@ describe("membership metadata and access lifetime", () => {
it("settles a failed current-generation read without rebuilding it and recovers on explicit Retry", async () => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("server", "parent", "forum", "child")
- const payload = {
+ const payload = { categoryId: null, topic: "", position: 0, messageCount: 0,
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",
}
@@ -864,7 +864,7 @@ describe("membership metadata and access lifetime", () => {
it.each(["parent", "server", "account", "unmount"] as const)("does not restart participation metadata after %s retirement before handoff", async (race) => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("server", "parent", "forum", "child")
- const payload = {
+ const payload = { categoryId: null, topic: "", position: 0, messageCount: 0,
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",
}
@@ -906,7 +906,7 @@ describe("membership metadata and access lifetime", () => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("server", "parent", parentType, "child")
act(() => { setCanonicalCommunityChannelMember(capturedQueryClient, "child", "u_me", "notify", true) })
- getCommunityApiFetchMock().mockResolvedValue({
+ getCommunityApiFetchMock().mockResolvedValue({ categoryId: null, topic: "", position: 0, messageCount: 0,
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",
@@ -931,7 +931,7 @@ describe("membership metadata and access lifetime", () => {
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 })
+ api.mockResolvedValue({ categoryId: null, topic: "", position: 0, messageCount: 0, creatorId: null, createdAt: "2026-10-01T00:00:00Z", lastMessageAt: null, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", name: "Child", archived: false })
const key = communityKeys.channelMessages("child")
const content = { pages: [{ messages: [{ id: "m1", content: "readable" }] }] }
capturedQueryClient.setQueryData(key, content)
@@ -965,7 +965,7 @@ describe("membership metadata and access lifetime", () => {
api.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
await vi.waitFor(() => expect(release).toBeTypeOf("function"))
- const meta = {
+ const meta = { categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "child", serverId: "server", name: "Child", type: "thread",
parentChannelId: "parent", parentMessageId: "opener", creatorId: null,
archived: false, lastMessageAt: null,
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.ts
index d67c46a10..3e11089da 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
@@ -160,7 +160,7 @@ describe("useCommunityWs — message.create", () => {
expect(hasCanonicalChannel("post_live")).toBe(false)
getCommunityApiFetchMock().mockImplementation(async (url: string) => {
if (url === "/api/community/channels/post_live") {
- return {
+ return { categoryId: null, topic: "", position: 0, messageCount: 0,
id: "post_live",
serverId: "srv_1",
name: "Live post",
@@ -1320,7 +1320,7 @@ describe("canonical message refresh and edit ownership", () => {
await mountHook()
const event = messageCreate(scope.id)
seedCanonicalMessages(scope.id, [{ ...event.message,
- attachments: [{ kind: "file", name: "settled.txt", url: "/media/settled", size: "1 KB" }],
+ attachments: [{ name: "settled.txt", url: "/media/settled", sizeBytes: 1024 }],
embeds: [{ title: "Prior" }],
}])
await act(async () => { capturedOnMessage!({ ...event, message: { ...event.message, attachments: [], embeds: [] } }) })
@@ -1333,13 +1333,13 @@ describe("canonical message refresh and edit ownership", () => {
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 attachments = [{ name: "settled.txt", url: "/media/settled", sizeBytes: 1024 }]
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)
+ expect(canonicalMessage(event.message.id)?.attachments).toEqual([{ ...attachments[0], kind: "file", size: "1.0 KB" }])
})
it("refreshes only an existing live fallback and never absorbs outbox", async () => {
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index 6b7f52bb9..3bb53f082 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -62,6 +62,7 @@ export function handleMessageCreate(
viewerUserIdRef,
matchesFocus,
projection,
+ contract,
}: CommunityWsHandlerContext,
) {
warmLiveForumChildOwner(queryClient, event)
@@ -69,7 +70,7 @@ export function handleMessageCreate(
const hasSeenMessage = wsStore.actions.hasSeenMessage(event.message.id)
const isForeignFocused = event.message.authorId !== viewerId
&& matchesFocus(event)
- const projected = projectCommunityWsEventToDb(queryClient, event)
+ const projected = projectCommunityWsEventToDb(queryClient, event, contract)
if (!projected) return
if (isForeignFocused && !hasSeenMessage) {
armInboxReadReservationCandidate(queryClient, {
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 2e9866a38..5b0da5d5e 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -189,7 +189,7 @@ export function dispatchCommunityWsEvents(
const receipt = { id: telemetryId(), start: performance.now(), type: event.type }
receipts.push(receipt)
entry.handler(event, handlerContext)
- if (event.type !== "community:message.create") projectCommunityWsEventToDb(context.queryClient, event)
+ if (event.type !== "community:message.create") projectCommunityWsEventToDb(context.queryClient, event, context.contract)
if ([
"community:server.delete",
"community:channel.delete",
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.ts
index 57ffa1b8b..020dfb4e5 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
@@ -332,7 +332,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
})) })
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,
+ const metadata = { categoryId: null, topic: "", position: 0, messageCount: 0, 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()
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
index 892577ea6..57c835a41 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -21,7 +21,7 @@ import {
import { getForumSidebarBase } from "@/hooks/community/use-forum-sidebar-threads"
import { useAccountAttention } from "@/hooks/community/use-account-attention"
import { useCanonicalMessagesById } from "@/lib/community-db/projections"
-import type { Msg } from "@/lib/community/models/message"
+import type { MessageInput } from "@/lib/community/models/message"
import type { MessageScope, MessageOverlayEvent } from "@/lib/community/message-stream"
const communityApiFetch = vi.hoisted(() => vi.fn(async (...args: unknown[]) => {
@@ -215,7 +215,7 @@ export function unmountHook() {
renderedHook = null
}
-export function seedCanonicalMessages(channelId: string, messages: Array<Partial<Msg> & Pick<Msg, "id">>) {
+export function seedCanonicalMessages(channelId: string, messages: MessageInput[]) {
if (!canonicalRegistry) throw new Error("Community test owner missing")
act(() => ingestMessages(canonicalRegistry!, channelId, messages.map((message) => ({ type: "chat", content: "", seq: 1, ...message }))))
}
diff --git a/src/web/src/hooks/community/forum-feed-window.test.ts b/src/web/src/hooks/community/forum-feed-window.test.ts
new file mode 100644
index 000000000..69f0ea529
--- /dev/null
+++ b/src/web/src/hooks/community/forum-feed-window.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest"
+import { communityReadSchemas } from "@alook/shared"
+import { normalizeThreadResources } from "./forum-feed-window"
+
+describe("versioned forum resource normalization", () => {
+ it.each([2, 3] as const)("preserves contract %s resources, scopes and pagination", (contractVersion) => {
+ const channel = { id: "forum", type: "forum", serverId: "server", name: "Forum", topic: "Topic", categoryId: null,
+ parentChannelId: null, parentMessageId: null, creatorId: "author", position: 0, archived: false, createdAt: "now", lastMessageAt: null, messageCount: 1 }
+ const message = { id: "opener", channelId: "forum", seq: 1, authorId: "author", authorName: "Author", authorAvatarVersion: 0,
+ type: "chat", content: "Title", replyToId: null, clientNonce: null, createdAt: "now", attachments: [] }
+ const profile = { id: "author", name: "Author", discriminator: "1234", avatar: null, avatarVersion: 0 }
+ const body = communityReadSchemas(contractVersion).threads.parse({ contractVersion, channelId: "forum", channel,
+ threads: [{ ...channel, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener" }],
+ included: { messages: [message, { ...message, id: "reply", channelId: "thread", content: "Reply" }],
+ profiles: [contractVersion === 2 ? { ...profile, statusEmoji: "😀", statusText: "Available" } : profile],
+ members: [{ channelId: "thread", userId: "author", relation: "notify", source: "spoke", isCreator: true, role: null, memberId: null }], tags: [{ messageId: "opener", tag: "bug" }],
+ participantCounts: [{ channelId: "thread", count: 1 }] }, page: { hasMore: true, nextCursor: "cursor" } })
+ const result = normalizeThreadResources("forum", body)
+ expect(result.channel).toEqual(channel)
+ expect(result.threads).toEqual(body.threads.map((thread) => ({ ...thread, resourceComplete: true })))
+ expect(result.included.messages).toEqual(body.included.messages.map((row) => ({ ...row, resourceComplete: contractVersion === 3 })))
+ expect(result.included.profiles).toEqual([profile])
+ expect(result.included.previews).toEqual([body.included.messages[1]])
+ expect(result.included.members).toEqual(body.included.members)
+ expect(result.page).toEqual(body.page)
+ expect(() => normalizeThreadResources("forum", { ...body, contractVersion: 4 } as never)).toThrow("Unknown thread resource contract")
+ expect(() => normalizeThreadResources("forum", { ...body, threads: [{ ...body.threads[0], messageCount: -1 }] } as never)).toThrow()
+ })
+})
diff --git a/src/web/src/hooks/community/forum-feed-window.ts b/src/web/src/hooks/community/forum-feed-window.ts
index ce5f4a5dc..95c1c9036 100644
--- a/src/web/src/hooks/community/forum-feed-window.ts
+++ b/src/web/src/hooks/community/forum-feed-window.ts
@@ -1,15 +1,14 @@
-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 { FORUM_ARCHIVE_TAG, CommunityChannelResourceSchema, CommunityMessagePreviewSchema, CommunityMessageResourceSchema, communityReadSchemas, communityMessagePreviewFromLegacy, type CommunityLegacyThreadsRead, type CommunityChannelResource, type CommunityThreadsRead, type CommunityMessageResource, type CommunityResourceProfile, type CommunityMemberRelation } from "@alook/shared"
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 { threadParticipantResources } from "@/lib/community/participant-resources"
+import type { MessageInput, Msg, Thread } from "@/lib/community/models/message"
import type { ChannelRow } from "@/lib/community-db/schema"
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,
+ 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 ?? "" },
@@ -28,34 +27,48 @@ export type ForumFeedTransportPage = Pick<CommunityThreadsRead["page"], "hasMore
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 }>
+ participants: Array<Pick<CommunityMemberRelation, "channelId" | "userId"> & { userName: CommunityResourceProfile["name"] | null; discriminator?: CommunityResourceProfile["discriminator"]; 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">> }
+ threads: Array<Pick<CommunityChannelResource, "id"> & Partial<Omit<CommunityChannelResource, "id">> & { resourceComplete?: boolean }>
+ included: Omit<CommunityThreadsRead["included"], "messages" | "profiles"> & { profiles: Array<Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">>>; messages: Array<MessageInput & { channelId: string }>; previews: Array<Pick<CommunityMessageResource, "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) } }
+export function normalizeThreadResources(channelId: string, value: ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead): CommunityThreadResources {
+ if ("contractVersion" in value) {
+ if (value.contractVersion !== 2 && value.contractVersion !== 3) throw new Error("Unknown thread resource contract")
+ const data = communityReadSchemas(value.contractVersion).threads.parse(value)
+ return {
+ ...data, threads: data.threads.map((thread) => ({ ...CommunityChannelResourceSchema.parse(thread), resourceComplete: true })),
+ included: { ...data.included,
+ messages: data.included.messages.map((message) => data.contractVersion === 3
+ ? { ...CommunityMessageResourceSchema.parse(message), channelId: message.channelId, resourceComplete: true }
+ : { ...communityMessagePreviewFromLegacy(message, message.channelId), channelId: message.channelId, resourceComplete: false }),
+ profiles: data.contractVersion === 3 ? data.included.profiles : data.included.profiles.map(({ statusEmoji: _emoji, statusText: _text, ...identity }) => identity),
+ previews: data.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 }),
+ profile: { id: participant.userId, ...(participant.userName !== null ? { name: participant.userName } : {}), ...(participant.discriminator ? { discriminator: participant.discriminator } : {}), 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
- }),
+ threads: value.threads.map(({ activityAt: _activity, messageCount, ...thread }) => ({
+ ...thread, type: "thread", serverId: value.serverId, parentChannelId: channelId,
+ ...(messageCount === null ? {} : { messageCount }), resourceComplete: false,
+ })),
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)),
+ messages: value.included.parentMessages.map(({ authorImage, ...message }) => ({
+ ...CommunityMessagePreviewSchema.partial({ type: true }).parse({ ...message, channelId, authorAvatar: canonicalUserImage(message.authorId, authorImage, message.authorAvatarVersion) }), channelId, resourceComplete: false,
+ })),
previews: value.included.firstMessages, tags: value.included.tags, ...participants,
},
page: { hasMore: value.hasMore, nextCursor: value.nextCursor ?? null },
@@ -72,7 +85,7 @@ export type ForumFeedPage = Pick<CommunityThreadsRead["page"], "hasMore"> & {
export function forumFeedWindow(page: CommunityThreadResources): ForumFeedPage {
return {
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) })),
+ threads: page.threads.map((thread) => ({ id: thread.id, openerMessageId: thread.parentMessageId ?? null, 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/inbox-read-reservation.test.ts b/src/web/src/hooks/community/inbox-read-reservation.test.ts
index 41a28e143..c58233aa0 100644
--- a/src/web/src/hooks/community/inbox-read-reservation.test.ts
+++ b/src/web/src/hooks/community/inbox-read-reservation.test.ts
@@ -53,14 +53,14 @@ async function seedProjection(queryClient: QueryClient, data: {
const registry = getCommunityDbRegistry(queryClient)!
await registry.preload()
const scopes: Array<{ scopeId: string; channelId: string; serverId: string; parentChannelId: string | null; ordinaryUnread: boolean; lastUnreadSeq: number; lastAttentionSeq: number | null; attentionCount: number }> = []
- const items: Array<{ id: string; kind: "forum_post"; sourceId: string; scopeId: string; childChannelId: string; messageId: string; openerSeq: number; createdAt: string }> = []
+ const items: Array<{ id: string; kind: "forum_post"; sourceId: string; scopeId: string; childChannelId: string; messageId: string; openerSeq: number; readTarget: { channelId: string; seq: number }; createdAt: string }> = []
for (const server of data.servers) {
const serverId = server.serverId ?? "server"
const channels = server.channels.flatMap((parent) => {
scopes.push({ scopeId: parent.channelId, channelId: parent.channelId, serverId, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 7, lastAttentionSeq: null, attentionCount: 0 })
for (const child of parent.children ?? []) if (child.openerUnread && child.openerMessageId && child.openerSeq !== undefined) {
ingestMessages(registry, parent.channelId, [{ id: child.openerMessageId, type: "chat", seq: child.openerSeq, createdAt: child.lastMessageAt }])
- items.push({ id: "forum:" + child.channelId, kind: "forum_post", sourceId: child.channelId, scopeId: parent.channelId, childChannelId: child.channelId, messageId: child.openerMessageId, openerSeq: child.openerSeq, createdAt: child.lastMessageAt })
+ items.push({ id: "forum:" + child.channelId, kind: "forum_post", sourceId: child.channelId, scopeId: parent.channelId, childChannelId: child.channelId, messageId: child.openerMessageId, openerSeq: child.openerSeq, readTarget: { channelId: parent.channelId, seq: child.openerSeq }, createdAt: child.lastMessageAt })
}
return [{ id: parent.channelId, name: parent.channelId, type: parent.children?.length ? "forum" as const : "text" as const, active: false, unread: true, lastMessageAt: parent.lastMessageAt }, ...(parent.children ?? []).map((child) => ({ id: child.channelId, name: child.channelId, type: "thread" as const, active: false, unread: true, lastMessageAt: child.lastMessageAt, parentChannelId: parent.channelId, parentMessageId: child.openerMessageId }))]
})
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index 0fbc845cd..c911a100c 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -101,7 +101,7 @@ export function useCreateChannel() {
return persistTreeChange(origin, queryClient, args, (db) => {
const rows = [...db.collections.channels.values()].filter((row) => row.serverId === args.serverId && row.categoryId === categoryId)
const position = Math.max(-1, ...rows.map((row) => row.position)) + 1
- pending = { id, serverId: args.serverId, categoryId, name: args.name.trim(), type: args.type,
+ pending = { id, serverId: args.serverId, categoryId, name: args.name.trim(), type: args.type, resourceComplete: false,
parentChannelId: null, parentMessageId: null, creatorId: db.accountId,
position, archived: false, muted: false, unread: false, tags: [], pending: true, lastMessageAt: null }
db.collections.channels.insert(pending)
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.ts
index f485ca695..1950c3a89 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
@@ -97,7 +97,7 @@ describe("Native forum creation", () => {
})
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" }
+ const opener = { id: "created-opener", seq: 40, type: "chat", content: "New post", authorId: "viewer", authorName: "Viewer", authorImage: null, authorAvatarVersion: 0, 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" }) })
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 342811488..7b5df4a24 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -68,7 +68,7 @@ export function useCreateForumThread() {
const parent = origin.registry!.collections.channels.get(channelId)
if (parent && structure.message) {
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 })
+ 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, resourceComplete: false }, { token, signal: assertActive?.signal })
}
assert()
const reply = await origin.request<{ message: PostedMessage }>(token, `/api/community/channels/${structure.threadId}/messages`, {
diff --git a/src/web/src/hooks/community/mutations/members.dom.test.ts b/src/web/src/hooks/community/mutations/members.dom.test.ts
index 6fb098a40..563b693c8 100644
--- a/src/web/src/hooks/community/mutations/members.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/members.dom.test.ts
@@ -23,7 +23,7 @@ async function setup(kind: "role" | "kick") {
const key = serverMembershipKey("srv_1", "u_1")
const member = { id: "mem_1", userId: "u_1", role: "member", name: "n", discriminator: "0000", avatar: "N", status: "offline", sub: "" }
owner.registry.collections.serverMemberships.utils.writeUpsert({ id: key, serverId: "srv_1", userId: "u_1", memberId: "mem_1", role: "member", viewer: false })
- owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ userId: "u_1", kind: "human", name: "n", discriminator: "0000", avatar: "N", avatarVersion: 0, presence: "offline" }))
+ owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, id: "u_1", kind: "human", name: "n", discriminator: "0000", avatar: "N", avatarVersion: 0, presence: "offline" }))
owner.client.setQueryData(communityKeys.members("srv_1"), { pages: [{ members: [{ id: "mem_1", userId: "u_1" }], hasMore: false, limit: 50, total: 1, liveRevision: 0 }], pageParams: [null] })
const held = deferred()
let remote = [member]
diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.ts
index 0a724fecb..61540b16a 100644
--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts
@@ -97,11 +97,11 @@ function attentionIncluded(overrides: {
} = {}) {
return {
servers: [{ id: "s_1", name: "Server", discriminator: "0001" }],
- channels: [{
+ channels: [{ categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "channel", serverId: "s_1", name: "Channel", type: "text",
parentChannelId: null, parentMessageId: null, creatorId: null,
archived: false, lastMessageAt: null,
- }, {
+ }, { categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "ch_1", serverId: "s_1", name: "Channel", type: "text",
parentChannelId: null, parentMessageId: null, creatorId: null,
archived: false, lastMessageAt: null,
@@ -309,7 +309,7 @@ describe("useSendMessage — happy path", () => {
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(canonicalRegistry.collections.messages.get(confirmed.id)?.attachments).toEqual([{ name: remoteAttachment.name, url: remoteAttachment.url, contentType: remoteAttachment.contentType, sizeBytes: remoteAttachment.sizeBytes }])
expect(materializeMessageStream(currentBase, getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc))).toEqual([
expect.objectContaining({ id: older.id }),
expect.objectContaining({ id: confirmed.id, replyTo, attachments: [remoteAttachment] }),
@@ -576,7 +576,7 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
})
it("continues the upload intent when its view retires after upload succeeds, before native POST", async () => {
- apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
+ apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
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" }] })
@@ -600,7 +600,7 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
})
it("continues the accepted channel intent when its view retires before native POST starts", async () => {
- apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
+ apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
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",
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 81926693e..1090f5a05 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -217,6 +217,18 @@ export function getConfirmedSentMessage(
}
}
+function postedMessageForIntent(message: PostedMessage, nonce: string, channelId: string, attachments?: readonly UploadFileResult[]) {
+ const canonical = projectPostedMessage(message, nonce, channelId)
+ if (canonical.resourceComplete || canonical.attachments !== undefined || !attachments?.length) return canonical
+ return { ...canonical, attachments: attachments.map((attachment) => ({
+ id: attachment.id, name: attachment.filename, url: attachmentUrl(channelId, attachment.id),
+ contentType: attachment.contentType, sizeBytes: attachment.size,
+ ...(attachment.hasThumbnail === undefined ? {} : { thumbnailUrl: attachment.hasThumbnail ? attachmentThumbnailUrl(channelId, attachment.id) : null }),
+ ...(attachment.width === undefined ? {} : { width: attachment.width }),
+ ...(attachment.height === undefined ? {} : { height: attachment.height }),
+ })) }
+}
+
function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(kind: MessageScope["kind"]) {
const origin = useCommunityMutationOrigin()
const queryClient = useQueryClient()
@@ -236,9 +248,9 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
})
await origin.registry!.collections.messages.preload()
origin.assert(token); (assertCommand ?? assertActive)?.()
- const message = projectPostedMessage(result.message, nonce ?? "", scope.id)
+ const message = postedMessageForIntent(result.message, nonce ?? "", scope.id, attachments)
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 } : {}) }],
+ messages: [{ ...message, ...(acceptedReply && !("replyTo" in result.message) && (!("replyToId" in result.message) || result.message.replyToId === acceptedReply.id) ? { replyTo: acceptedReply } : {}) }],
proof: { token, ...(scope.kind === "channel" && !assertCommand ? { signal: assertActive?.signal } : {}) } })
return result
},
@@ -288,7 +300,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
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),
+ type: "postAck", nonce, message: postedMessageForIntent(data.message, nonce, scope.id, args.attachments),
})
},
})
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 24f5ac0a0..6418a74b6 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -9,7 +9,6 @@ writeCommunityProfilePatches,
} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { BotActivityDay,CommunityProfilePatch } from "@/lib/community/models/people"
-import { avatarInitial } from "@/lib/community/avatar"
import type { DailyUsageMetric,ReasoningEffort } from "@alook/shared"
import { useCallback,useMemo } from "react"
import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
@@ -80,7 +79,7 @@ type OriginalBotView = (() => void) & { signal: AbortSignal }
type BotViewInput = { assertActive?: OriginalBotView }
function botProfilePatch(bot: Pick<BotSummary, "id" | "name" | "image" | "avatarVersion"> & { description?: string }): CommunityProfilePatch {
- return { id: bot.id, identityAbout: { name: bot.name, kind: "bot", ...("discriminator" in bot && typeof bot.discriminator === "string" ? { discriminator: bot.discriminator } : {}), ...(bot.description === undefined ? {} : { aboutMe: bot.description }) }, avatar: { avatar: bot.image ?? avatarInitial(bot.name), avatarVersion: bot.avatarVersion } }
+ return { id: bot.id, identityAbout: { name: bot.name, kind: "bot", ...("discriminator" in bot && typeof bot.discriminator === "string" ? { discriminator: bot.discriminator } : {}), ...(bot.description === undefined ? {} : { aboutMe: bot.description }) }, avatar: { avatar: bot.image, avatarVersion: bot.avatarVersion } }
}
export function useBots(): UseQueryResult<BotsResourceResponse> & { bots: BotSummary[] } {
diff --git a/src/web/src/hooks/community/use-channel-members.dom.test.ts b/src/web/src/hooks/community/use-channel-members.dom.test.ts
index 3f04c91c0..a24f68c0c 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
@@ -40,7 +40,7 @@ describe("useChannelMembers", () => {
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)
const rendered = renderHook(({ enabled }) => useChannelMembers("private", enabled, "server", "access"), { wrapper, initialProps: { enabled: true } })
await waitFor(() => expect(rendered.result.current).toMatchObject({ isSuccess: true, loading: false, failed: true }))
- await act(async () => owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 })))
+ await act(async () => owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 })))
await waitFor(() => expect(rendered.result.current).toMatchObject({ loading: false, failed: false, members: [expect.objectContaining({ userId: "peer", discriminator: "0042" })] }))
expect(rendered.result.current.profiles.get("peer")?.discriminator).toBe("0042")
await act(async () => owner.registry.collections.serverMemberships.utils.writeDelete(serverMembershipKey("server", "peer")))
@@ -90,7 +90,7 @@ describe("useChannelMembers", () => {
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) } })
+ publishCommunityChannelMetadata(owner.client, { metadata: { categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z", 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 })
diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.ts
index c224859d6..294841709 100644
--- a/src/web/src/hooks/community/use-channel-members.ts
+++ b/src/web/src/hooks/community/use-channel-members.ts
@@ -6,7 +6,7 @@ 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 { COMMUNITY_CONTRACT_VERSION, CommunityMembersReadSchema, CommunityResourceProfileSchema, type CommunityMembersRead, type CommunityRole, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"
+import { communityReadSchemas, CommunityResourceProfileSchema, type CommunityMembersRead, type CommunityRole, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"
import type { CommunityProfile, CommunityUserCore, Presence } from "@/lib/community/models/people"
import { fetchAllServerMembers } from "./fetch-all-server-members"
@@ -26,11 +26,11 @@ export type ChannelMember = CommunityUserCore & Pick<CommunityMemberRelation, "u
source: NonNullable<ChannelMembershipRow["source"]>
}
-function normalizeChannelRoster(channelId: string, relation: CommunityMemberRelation["relation"], response: { members: ChannelMember[] } | CommunityMembersRead): CommunityMembersRead {
+function normalizeChannelRoster(channelId: string, relation: CommunityMemberRelation["relation"], response: { members: ChannelMember[] } | CommunityMembersRead): Omit<CommunityMembersRead, "contractVersion"> & { contractVersion: 2 | 3 } {
if ("contractVersion" in response) return response
- return CommunityMembersReadSchema.parse({ contractVersion: COMMUNITY_CONTRACT_VERSION, channelId, relation,
+ return communityReadSchemas(2).members.parse({ contractVersion: 2, 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 ?? "" })),
+ profiles: response.members.map((member) => CommunityResourceProfileSchema.strip().parse({ ...member, id: member.userId, discriminator: member.discriminator || null, statusEmoji: member.statusEmoji ?? null, statusText: member.statusText ?? "" })),
})
}
export type AddableMember = Pick<ChannelMember, "userId" | "avatar" | "avatarVersion"> & { [Field in "name" | "discriminator"]: ChannelMember[Field] | null }
@@ -62,7 +62,7 @@ function channelMembersOptions(client: QueryClient, channelId: string, serverId?
const response = await apiFetch<{ members: ChannelMember[] } | CommunityMembersRead>("/api/community/channels/" + encodeURIComponent(channelId) + "/members?relation=" + dimension, communityRequestOptions(client, token, signal, assert))
assert()
const resources = normalizeChannelRoster(channelId, dimension, response)
- publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles)
+ publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles, { legacyPresentation: resources.contractVersion !== 3 })
assert()
return { serverId: scopeId, relation: dimension, members: resources.members.map(({ memberId, userId }) => ({ id: memberId ?? userId, userId })) }
},
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.ts
index f19319ad1..60b4b6b11 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
@@ -18,7 +18,7 @@ import { startChannelRouteVerification } from "./channel-route-verification"
const apiFetch = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
-const metadata = { id: "dm-a", serverId: null, type: "dm", name: null,
+const metadata = { categoryId: null, topic: "", position: 0, messageCount: 0, id: "dm-a", serverId: null, type: "dm", name: null,
parentChannelId: null, parentMessageId: null, creatorId: null, archived: false,
lastMessageAt: null, createdAt: "2026-10-02T00:00:00Z" }
const dms = { conversations: [{ id: metadata.id, userId: "peer", name: "Peer", discriminator: "0001",
@@ -307,7 +307,7 @@ describe("shared Channel resource and canonical DM publication", () => {
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.collections.channels.get(metadata.id)).toMatchObject({ name: null, serverId: null, type: "dm" })
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()
@@ -585,7 +585,7 @@ describe("restored forum archive ambiguity", () => {
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 }
+ const post = { categoryId: null, topic: "", position: 0, messageCount: 0, creatorId: null, createdAt: "2026-10-01T00:00:00Z", lastMessageAt: null, ...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 })
diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.ts
index e6a870477..3da87e323 100644
--- a/src/web/src/hooks/community/use-channel-panels.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.test.ts
@@ -20,6 +20,22 @@ beforeEach(async () => {
const project = (data: ThreadsResponse) => materializeThreadsResponse(data, new Map(getCanonicalCommunityMessages(qc).map((row) => [row.id, row])), new Map(getCanonicalCommunityChannels(qc).map((row) => [row.id, row])))
describe("useThreads / threadsQueryFn", () => {
+ it("carries batch participant numbers into canonical profiles without a DM read or erasing them on a legacy read", async () => {
+ const { threadsQueryFn } = await import("./use-channel-panels")
+ for (const discriminator of ["123456", undefined]) {
+ apiFetchMock.mockReset()
+ apiFetchMock
+ .mockResolvedValueOnce({ serverId: "s1", parentType: "forum", threads: [{ id: "t_1", name: "thread", type: "thread", creatorId: "u1", parentMessageId: "m1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
+ .mockResolvedValueOnce({ messages: [{ id: "m1", channelId: "ch_1", content: "root", seq: 1, authorId: "u1", authorName: "Alice", authorImage: null }], firstMessages: [] })
+ .mockResolvedValueOnce({ tags: [] })
+ .mockResolvedValueOnce({ participants: [{ channelId: "t_1", userId: "u1", userName: "Alice", userImage: null, userAvatarVersion: 0, ...(discriminator === undefined ? {} : { discriminator }) }] })
+ await threadsQueryFn("ch_1", qc)()
+ expect(getCommunityDbRegistry(qc)!.collections.profiles.get("u1")).toMatchObject({ name: "Alice", discriminator: "123456" })
+ expect(apiFetchMock).toHaveBeenCalledTimes(4)
+ expect(apiFetchMock.mock.calls.some(([url]) => String(url).includes("/dm"))).toBe(false)
+ }
+ })
+
it("fetches from /channels/:id/threads and returns { threads }", async () => {
apiFetchMock
.mockResolvedValueOnce({ serverId: "s1", parentType: "forum", threads: [{ id: "t_1", name: "t", type: "thread", creatorId: "u1", parentMessageId: "m1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
@@ -100,8 +116,8 @@ describe("usePins / pinsQueryFn", () => {
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 }],
+ attachments: [{ name: "known.txt", url: "/known", sizeBytes: 1024 }],
+ embeds: [{ title: "Known" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
}
ingestMessages(getCommunityDbRegistry(qc)!, "ch_1", [rich])
apiFetchMock.mockResolvedValueOnce({ pins: [{ id: rich.id, authorId: rich.authorId,
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index 40c44f424..ebb7963e8 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -22,7 +22,7 @@ import {
} from "@/lib/community-db/sync"
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 { CommunityMessagePreviewSchema, type CommunityLegacyThreadsRead, type CommunityThreadsRead, type CommunityChannelResource, type CommunityMessageResource } from "@alook/shared"
import type { ChannelRow } from "@/lib/community-db/schema"
/**
@@ -43,7 +43,7 @@ export type ThreadsResponse = {
async function loadThreadResources(queryClient: QueryClient, channelId: string, proof: CommunityFreshQueryProof) {
const options = qualifiedCommunityRequestOptions(queryClient, proof.token, proof.signal)
- const response = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants`, options)
+ const response = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants`, options)
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
if ("contractVersion" in response || response.included) return normalizeThreadResources(channelId, response)
const openerIds = response.threads.flatMap((thread) => thread.parentMessageId ? [thread.parentMessageId] : [])
@@ -53,7 +53,7 @@ async function loadThreadResources(queryClient: QueryClient, channelId: string,
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 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 })) } })
+ return normalizeThreadResources(channelId, { ...response, hasMore: false, included: { parentMessages: messages.messages, firstMessages: messages.firstMessages, tags: tags.tags, participants: participants.participants } })
}
export const threadsQueryFn = (channelId: string, queryClient: QueryClient) => async ({ signal }: { signal?: AbortSignal } = {}) => {
@@ -123,7 +123,7 @@ export const pinsQueryFn = (channelId: string, queryClient: QueryClient) =>
)
{
publishCommunityEmbeddedMessages(queryClient, {
- entries: data.pins.map((message) => ({ channelId, message })),
+ entries: data.pins.map((message) => ({ channelId, message: { ...CommunityMessagePreviewSchema.partial({ type: true }).parse({ ...message, channelId }), resourceComplete: false } })),
proof: { token: publicationToken, signal },
})
}
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.ts
index 4d60abf57..5a1cc66af 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
@@ -64,7 +64,7 @@ function deferred() {
}
function payload(id = "post-1") {
return {
- id, serverId: "server-1", name: "post", type: "thread", parentChannelId: "parent-1",
+ categoryId: null, topic: "", position: 0, messageCount: 0, id, serverId: "server-1", name: "post", type: "thread", parentChannelId: "parent-1",
parentMessageId: "opener-1", creatorId: "viewer-1", archived: false,
lastMessageAt: "2026-08-09T00:00:00.000Z", createdAt: "2026-08-08T00:00:00.000Z",
}
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.ts
index 0e3507ce5..a76beaf7c 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
@@ -15,7 +15,7 @@ vi.mock("@/lib/api/client", () => ({
import { useChannelMetadata } from "./use-channel-metadata"
-const meta = (overrides: Partial<ReturnType<typeof channelSchema.parse>> = {}) => channelSchema.parse({
+const meta = (overrides: Partial<ReturnType<typeof channelSchema.parse>> = {}) => channelSchema.parse({ categoryId: null, topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
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",
@@ -32,7 +32,7 @@ async function fixture() {
beforeEach(() => {
apiFetchMock.mockReset()
- apiFetchMock.mockResolvedValue({
+ apiFetchMock.mockResolvedValue({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "post-1",
serverId: "server-1",
name: "post",
@@ -151,7 +151,7 @@ describe("child channel metadata stale rendering", () => {
it("builds a structural placeholder from a complete canonical thread row", async () => {
apiFetchMock.mockImplementation(() => new Promise(() => {}))
const { client: queryClient } = await createCommunityQueryOwner()
- createCommunityDbRegistry(queryClient, "viewer").collections.channels.utils.writeUpsert(channelSchema.parse({
+ createCommunityDbRegistry(queryClient, "viewer").collections.channels.utils.writeUpsert(channelSchema.parse({ categoryId: null, topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "post-1",
serverId: "server-1",
name: "post",
diff --git a/src/web/src/hooks/community/use-community-ws.dom.test.ts b/src/web/src/hooks/community/use-community-ws.dom.test.ts
index 960bcd8ac..c3c718b1b 100644
--- a/src/web/src/hooks/community/use-community-ws.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.dom.test.ts
@@ -23,11 +23,33 @@ import {
import {
COMMUNITY_WS_FAILED_AFTER_MS,
} from "./community-ws/connection-status"
+import { deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatch, prepareCommunityDeliveryEvents } from "@alook/shared"
+import * as analytics from "@/lib/analytics"
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — non-community events bail", () => {
+ it("drops a v3 batch on a v2 connection while retaining legacy admission", async () => {
+ await mountHook()
+ const dropped = vi.spyOn(analytics, "trackCommunityWsFrameDropped")
+ const setSpy = vi.spyOn(capturedQueryClient, "setQueryData")
+ const invalid = { type: "community:events.batch.v3", events: [] }
+ await capturedOnMessage!(invalid)
+ expect(dropped).toHaveBeenCalledExactlyOnceWith({ reason: "invalid-payload", type: invalid.type })
+ expect(setSpy).not.toHaveBeenCalled()
+ const events = [{ type: "community:presence.update", userId: "peer", online: true }]
+ const prepared = await prepareCommunityDeliveryEvents(events)
+ if (!prepared.ok) throw new Error("invalid presence fixture")
+ const encoded = await encodeCommunityBrowserEventBatch({ operationDigest: prepared.prepared.digest, operationId: await deriveCommunityDeliveryOperationId("legacy-presence"),
+ events })
+ if (!encoded.ok) throw new Error("invalid legacy fixture")
+ expect(encoded.batch.type).toBe("community:events.batch")
+ await capturedOnMessage!(encoded.batch)
+ await vi.waitFor(() => expect(getCapturedRuntime().ws.get().presenceByUserId.get("peer")).toBe("online"))
+ expect(dropped).toHaveBeenCalledOnce()
+ dropped.mockRestore()
+ })
it("rejects non-community and unknown community-prefixed events", async () => {
await mountHook()
const setSpy = vi.spyOn(capturedQueryClient, "setQueryData")
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 9805df202..0450648b1 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -36,12 +36,14 @@ import type {
import { flushPendingReadIntents } from "@/hooks/community/read-coordinator"
import {
decodeCommunityBrowserEvent,
+ communityBrowserEventBatchType,
admitCommunityBrowserEventBatch,
isCommunityBrowserEventBatchCandidate,
isCommunityEventType,
TYPING_INDICATOR_THROTTLE_MS,
type AgentInterruptRequest,
type CommunityWsEvent,
+ type CommunityContract,
} from "@alook/shared"
import { trackCommunityWsFrameDropped } from "@/lib/analytics"
import {
@@ -349,7 +351,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}, [runInboxGeneration])
const handleMessage = useCallback(
- async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void) => {
+ async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void, contract: CommunityContract = 2) => {
if (!msg.type.startsWith("community:")) return
if (!runtime.lifecycle.get().active) return
const communityStore = runtime.ui
@@ -371,6 +373,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
deliveryMode: "single" | "batch",
requestInboxRefresh = scheduleInboxInvalidate,
): CommunityWsDispatchContext => ({
+ contract,
deliveryMode,
queryClient,
communityStore,
@@ -397,6 +400,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}
if (isCommunityBrowserEventBatchCandidate(msg)) {
+ if (msg.type !== communityBrowserEventBatchType(contract)
+ && !(contract === 2 && msg.type === communityBrowserEventBatchType(1))) {
+ trackCommunityWsFrameDropped({ reason: "invalid-payload", type: msg.type })
+ return
+ }
const token = captureCommunityLiveSnapshotToken(queryClient)
const admission = admitCommunityBrowserEventBatch(msg)
const decoded = admission instanceof Promise ? await admission : admission
@@ -486,7 +494,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
return
}
- const decoded = decodeCommunityBrowserEvent(msg)
+ const decoded = decodeCommunityBrowserEvent(msg, contract)
if (!decoded.ok) {
const metadata = {
reason: decoded.reason,
@@ -537,6 +545,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
return reconcileFocusedCommunityMessages(queryClient)
}, [queryClient, runtime.ws, viewerUserId])
const { send, reconnectNow } = useUserWs(handleMessage, {
+ communityContract: options?.communityContract,
onReconnect: handleReconnect,
onDisconnect: runtime.ws.actions.markAccessDisconnected,
onAuthenticated: handleAuthenticated,
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.ts
index 78a8e9790..cd3de2658 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
@@ -59,8 +59,18 @@ describe("Native DM sender", () => {
const receipt = owner.accept({ content: "@Peer\nhello", replyTo: { id: "prior", authorName: "Peer", text: "quoted" } })
expect(owner.overlay().outboxByNonce.get("fresh_nonce")?.message).toMatchObject({ authorId: "u_me", authorName: "Me", content: "@Peer\nhello", replyTo: { id: "prior", authorName: "Peer", text: "quoted" } })
await waitFor(() => expect(mocks.post).toHaveBeenCalledExactlyOnceWith({ content: "@Peer\nhello", replyToId: "prior", nonce: "fresh_nonce" }))
- resolve(posted())
+ resolve({ message: Object.assign({}, posted().message, { channelId: scope.id, type: "default", replyToId: "prior",
+ authorEmail: "[email protected]", storageMetadata: { legacy: true } }) })
expect(await owner.settle(receipt)).toMatchObject({ ok: true, message: { id: "server_1", seq: 7 } })
+ const canonical = owner.registry.collections.messages.get("server_1")
+ expect(canonical).toMatchObject({ id: "server_1", seq: 7, channelId: scope.id, clientNonce: "fresh_nonce",
+ type: "chat", content: "hello", replyToId: "prior", replyTo: { id: "prior", authorName: "Peer", text: "quoted" } })
+ expect(canonical).not.toHaveProperty("authorEmail")
+ expect(canonical).not.toHaveProperty("storageMetadata")
+ const { awaitCommittedInvite } = await import("@/components/community/social/invite-dialog")
+ const onCommitted = vi.fn()
+ await awaitCommittedInvite(receipt, onCommitted)
+ expect(onCommitted).toHaveBeenCalledOnce()
})
it("normalizes upload failure, marks the intent failed and never POSTs", async () => {
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.ts
index 2e0568a26..788068557 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
@@ -14,7 +14,7 @@ const apiFetch = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
const dm = { id: "dm-a", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", status: "offline" as const, preview: "" }
-const metadata = { id: dm.id, serverId: null, type: "dm", name: null, parentChannelId: null,
+const metadata = { categoryId: null, topic: "", position: 0, messageCount: 0, id: dm.id, serverId: null, type: "dm", name: null, parentChannelId: null,
parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null, createdAt: "2026-10-02T00:00:00Z" }
const denied = () => Object.assign(new Error("missing"), { status: 404 })
function deferred<T>() {
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index 569fb7dca..a2e281146 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -52,7 +52,7 @@ const loadDms = (
) =>
apiFetchProfiles<DmsResponse>(
"/api/community/users/me/dms",
- (data) => data.conversations.map((dm) => communityUserProfilePatch(dm.userId, dm)),
+ (data) => data.conversations.map((dm) => communityUserProfilePatch(dm.userId, dm, { legacyPresentation: true })),
context.signal ? { signal: context.signal } : undefined, getCommunityDbRegistry(context.client),
)
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.ts
index c02840279..9853f973d 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
@@ -38,7 +38,7 @@ async function projectPages(pages: ForumFeedTransportPage[], canonical?: Readonl
for (const page of pages) apiFetchMock.mockResolvedValueOnce(page)
const data = await client.infiniteQuery({ queryKey: communityKeys.forumFeed("forum_1", null), queryFn: forumFeedPageQueryFn("forum_1", null, client), initialPageParam: null as string | null, getNextPageParam: (last) => last.hasMore ? last.nextCursor : undefined, pages: pages.length })
const registry = getCommunityDbRegistry(client)!
- return mapForumFeedPages(data.pages, canonical ?? 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])))
+ return mapForumFeedPages(data.pages, canonical ?? 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.id, row])))
}
const emptyIncluded = {
@@ -175,10 +175,10 @@ describe("mapForumFeedPages", () => {
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) })
+ expect(result[0]).toMatchObject({ name: "Fallback", messageCount: 0, lastMessageAt: "", 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])))
+ 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.id, 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 () => {
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 62d9c84ca..d2c50feb4 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -2,7 +2,7 @@
import { 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, type CommunityThreadsRead } from "@alook/shared"
+import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityLegacyThreadsRead, type CommunityThreadsRead } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"
@@ -51,7 +51,7 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null, quer
const 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 transport = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead>(`/api/community/channels/${channelId}/threads?${params}`, communityRequestOptions(queryClient, token, readSignal))
+ const transport = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/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))
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.ts
index 7748fa32f..89d309c65 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
@@ -67,7 +67,7 @@ beforeEach(() => async () => {
function envelope(overrides: Partial<SidebarThreadEnvelope> = {}): SidebarThreadEnvelope {
const activityAt = new Date(Date.now() - 60_000).toISOString()
return {
- channels: [{
+ channels: [{ categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "post-1",
name: "fallback",
parentChannelId: "forum-1",
@@ -195,10 +195,10 @@ describe("forum sidebar canonical projection", () => {
}), { wrapper })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
const activityAt = new Date(Date.now() - 60_000).toISOString()
- const metadata = {
+ const metadata = { categoryId: null, topic: "", position: 0, messageCount: 0,
id: "post-1", serverId: "server-1", name: "Readable archived post", type: "thread",
parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: "viewer",
- archived: 0, lastMessageAt: activityAt, createdAt: activityAt,
+ archived: false, lastMessageAt: activityAt, createdAt: activityAt,
}
const negative: SidebarThreadEnvelope = {
...envelopeFor(["post-2", "post-3", "post-4", "post-5", "post-6"]),
@@ -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) => void
const retained = new Promise<SidebarThreadEnvelope>((resolve) => { releaseRetained = resolve })
- 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)
+ apiFetchMock.mockImplementation((url) => url === "/api/community/channels/post-1" ? Promise.resolve({ categoryId: null, topic: "", position: 0, messageCount: 0, parentChannelId: null, parentMessageId: null, creatorId: null, lastMessageAt: null, ...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(() => {
@@ -975,7 +975,7 @@ describe("forum sidebar canonical projection", () => {
}))
await act(async () => Promise.resolve())
expect(registry.collections.channels.get("post-1")).toMatchObject({
- serverId: "server-1", type: "thread", name: "", pending: true, tags: ["archived"],
+ serverId: "server-1", type: "thread", name: null, pending: true, tags: ["archived"],
parentChannelId: null, parentMessageId: null,
})
expect(registry.collections.channelMemberships.get("post-1:viewer:access")).toBeUndefined()
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index 45b6f02c8..83784480c 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -438,7 +438,7 @@ function reconcileForumSidebarNotifyMembershipsFromBase(
id: channel.id,
parentChannelId: channel.parentChannelId,
parentMessageId: channel.parentMessageId ?? "",
- title: channel.name,
+ title: channel.name ?? "",
activityAt,
expiresAt: Number.isFinite(activityMs)
? new Date(activityMs + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
diff --git a/src/web/src/hooks/community/use-friends.dom.test.ts b/src/web/src/hooks/community/use-friends.dom.test.ts
index 66f6a007d..4ee9e06f8 100644
--- a/src/web/src/hooks/community/use-friends.dom.test.ts
+++ b/src/web/src/hooks/community/use-friends.dom.test.ts
@@ -136,7 +136,7 @@ describe("useFriends / friendsQueryFn", () => {
...raw.blocked.map((blocked) => ({ id: "blocked:" + ("userId" in blocked ? blocked.userId : blocked.id), userId: "userId" in blocked ? blocked.userId : blocked.id, kind: "blocked" }))]) await act(async () => { registry.collections.friendships.utils.writeUpsert(friendshipSchema.parse(row)) });
for (const row of [...raw.friends, ...raw.pending, ...raw.blocked]) {
const userId = "userId" in row ? row.userId : row.id
- await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ discriminator: "", ...row, kind: "human", userId })) });
+ await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, discriminator: null, ...row, kind: "human", id: userId })) });
}
const window = { ids: [...registry.collections.friendships.values()].map((row) => row.id) }
queryClient.setQueryData(communityKeys.friends(), window)
@@ -164,7 +164,7 @@ describe("useFriends / friendsQueryFn", () => {
avatarVersion: 6,
}],
])
- for (const [userId, fields] of canonicalProfiles) await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ ...registry.collections.profiles.get(userId), ...fields, userId })) });
+ for (const [userId, fields] of canonicalProfiles) await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, ...registry.collections.profiles.get(userId), ...fields, id: userId })) });
await act(async () => { registry.runtime.ws.actions.seedPresence(registry.runtime.ws.actions.beginPresenceSnapshot(), [["friend_1", "online"]]) });
let rendered!: ReturnType<typeof renderHook<ReturnType<typeof useFriends>, unknown>>
await act(async () => { rendered = renderHook(() => useFriends(), {
diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.ts
index eae1d1f4f..2cb047700 100644
--- a/src/web/src/hooks/community/use-friends.ts
+++ b/src/web/src/hooks/community/use-friends.ts
@@ -62,7 +62,7 @@ export const friendsQueryFn = async (context: QueryFunctionContext) => {
"/api/community/friends/accepted",
(data) => {
throwIfStale(data)
- return data.friends.map((friend) => communityUserProfilePatch(friend.userId ?? friend.id, friend))
+ return data.friends.map((friend) => communityUserProfilePatch(friend.userId ?? friend.id, friend, { legacyPresentation: true }))
}, { signal: context.signal }, getCommunityDbRegistry(context.client),
),
apiFetchProfiles<{ blocked: BlockedUser[]; stale?: boolean }>(
diff --git a/src/web/src/hooks/community/use-inbox.dom.test.ts b/src/web/src/hooks/community/use-inbox.dom.test.ts
index 0170e98af..1a5d1b2aa 100644
--- a/src/web/src/hooks/community/use-inbox.dom.test.ts
+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts
@@ -570,7 +570,7 @@ describe("useInboxAttention", () => {
channel: "General",
channelId: "channel",
m: {
- id: "message",
+ id: "message", authorId: "peer",
type: "chat",
seq: 5,
createdAt: "2026-09-28T00:00:05.000Z",
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index 3644931df..20cbd52d8 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -14,6 +14,7 @@ import { communityRequestOptions } from "@/lib/community-db/sync"
import { apiFetch } from "@/lib/api/client"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { communityKeys } from "@/lib/query-keys"
+import { communityMessagePreviewFromLegacy } from "@alook/shared"
import type {
InboxFriendRequest,
Marked,
@@ -102,7 +103,7 @@ export function useInboxAttention() {
if (!parent) continue
const parentRow = serverChannels.get(parent.id) ?? {
channelId: parent.id,
- channelName: parent.name,
+ channelName: parent.name ?? "",
type: parent.type === "forum" ? "forum" : "text",
lastMessageAt: parent.lastMessageAt ?? "",
mentionCount: 0,
@@ -111,7 +112,7 @@ export function useInboxAttention() {
}
parentRow.children.push({
channelId: channel.id,
- channelName: channel.name,
+ channelName: channel.name ?? "",
type: "thread",
lastMessageAt: channel.lastMessageAt ?? "",
lastUnreadSeq: scope.lastUnreadSeq,
@@ -128,7 +129,7 @@ export function useInboxAttention() {
const previous = serverChannels.get(channel.id)
serverChannels.set(channel.id, {
channelId: channel.id,
- channelName: channel.name,
+ channelName: channel.name ?? "",
type: channel.type === "forum" ? "forum" : "text",
lastMessageAt: channel.lastMessageAt ?? "",
lastUnreadSeq: scope.lastUnreadSeq,
@@ -157,7 +158,7 @@ export function useInboxAttention() {
grouped.set(scope.serverId, serverChannels)
const parentRow = serverChannels.get(parent.id) ?? {
channelId: parent.id,
- channelName: parent.name,
+ channelName: parent.name ?? "",
type: "forum",
lastMessageAt: parent.lastMessageAt ?? "",
mentionCount: scope.attentionCount,
@@ -167,7 +168,7 @@ export function useInboxAttention() {
const existingIndex = parentRow.children.findIndex((row) => row.channelId === child.id)
const childRow = {
channelId: child.id,
- channelName: opener.content?.trim() || child.name,
+ channelName: opener.content?.trim() || child.name || "",
type: "thread" as const,
lastMessageAt: opener.createdAt ?? child.lastMessageAt ?? "",
lastUnreadSeq: item.openerSeq,
@@ -228,7 +229,7 @@ export function useInboxAttention() {
? serversById.get(scope.serverId)?.name ?? ""
: dmById.get(scope.channelId)?.name ?? "",
...(scope.serverId ? { serverId: scope.serverId } : {}),
- channel: channel.name,
+ channel: channel.name ?? "",
channelId: channel.id,
m: message,
}]
@@ -290,7 +291,7 @@ const inboxMarkedQueryFn = (queryClient: QueryClient) =>
publishCommunityEmbeddedMessages(queryClient, {
entries: data.marked.map((marked) => ({
channelId: marked.channelId,
- message: marked.m,
+ message: { ...communityMessagePreviewFromLegacy(marked.m, marked.channelId), resourceComplete: false },
})),
proof: { token: publicationToken, signal },
})
diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.ts
index 7643e8eef..e45918b30 100644
--- a/src/web/src/hooks/community/use-message.test.ts
+++ b/src/web/src/hooks/community/use-message.test.ts
@@ -18,11 +18,11 @@ 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 }],
+ attachments: [{ name: "old.txt", url: "/old", sizeBytes: 1024 }],
+ embeds: [{ title: "Old" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
replyTo: { id: "reply", authorName: "Peer", text: "Old reply" },
}])
- apiFetchMock.mockResolvedValueOnce(payload)
+ apiFetchMock.mockResolvedValueOnce({ ...payload, resourceComplete: true, seq: 1, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] })
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()
@@ -57,13 +57,14 @@ describe("useMessage / messageQueryFn", () => {
const message = {
...payload, content: "cached opener",
replyTo: { id: "m_0", authorName: "Bob", text: "parent" },
- attachments: [{ kind: "file" as const, name: "notes.txt", url: "/notes.txt", size: "1 KB" }],
+ attachments: [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024 }],
embeds: [{ title: "Reference" }],
reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_1"] }],
}
ingestMessages(registry, "channel-1", [message])
client.setQueryData(communityKeys.channelMessages("channel-1"), { pages: [{ ids: [message.id], hasMoreOlder: false, hasMoreNewer: false }], pageParams: [{ mode: "newest" }] })
- expect(findCachedMessage(client, message.id)).toMatchObject(message)
+ const { channelId: _channelId, ...view } = message
+ expect(findCachedMessage(client, message.id)).toMatchObject({ ...view, attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, size: "1.0 KB" }] })
expect(findCachedMessage(client, "missing")).toBeUndefined()
})
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index 2a8e614d2..34b39a0d2 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -12,7 +12,8 @@ import {
} from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { communityKeys } from "@/lib/query-keys"
-import type { Msg } from "@/lib/community/models/message"
+import type { MessageInput, Msg } from "@/lib/community/models/message"
+import { presentCanonicalMessage } from "@/lib/community/message-wire"
import {
useCanonicalMessagesById,
useOptionalCommunityDbRegistry,
@@ -51,7 +52,7 @@ export const messageQueryFn = (
) => async (context: QueryFunctionContext) => {
if (context.client !== queryClient) throw new DOMException("Mismatched message query owner", "AbortError")
const token = captureCommunityLiveSnapshotToken(queryClient, channelId)
- const message = await apiFetchCommunity<OpenerPayload>(
+ const message = await apiFetchCommunity<MessageInput>(
`/api/community/messages/${messageId}`,
context.signal ? { signal: context.signal } : undefined, token,
)
@@ -59,8 +60,7 @@ export const messageQueryFn = (
if (publishChannelId) {
publishCommunityMessages(queryClient, {
channelId: publishChannelId,
- messages: [{ ...message, attachments: message.attachments ?? [], embeds: message.embeds ?? [],
- reactions: message.reactions ?? [], replyTo: message.replyTo }],
+ messages: [message],
proof: { token, signal: context.signal },
})
}
@@ -73,11 +73,12 @@ export function findCachedMessage(
): OpenerPayload | undefined {
const message = getCanonicalCommunityMessages(queryClient).find((row) => row.id === messageId)
if (!message?.authorId || !message.createdAt) return undefined
+ const view = presentCanonicalMessage(message)
return {
- ...message,
+ ...view,
authorId: message.authorId,
authorName: message.authorName ?? "Deleted user",
- authorAvatar: message.authorAvatar ?? "",
+ authorAvatar: view.authorAvatar ?? "",
authorAvatarVersion: message.authorAvatarVersion ?? 0,
content: message.content ?? "",
createdAt: message.createdAt,
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.ts
index 37d1b3dc4..546ca6aa4 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
@@ -98,15 +98,16 @@ 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 attachments = [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024 }]
+ const presentedAttachments = [{ ...attachments[0], kind: "file", size: "1.0 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 })])
+ expect(rendered.result.current.messages).toEqual([expect.objectContaining({ id: message.id, attachments: presentedAttachments, 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 })])
+ expect(rendered.result.current.messages).toEqual([expect.objectContaining({ id: message.id, content: "sparse live", attachments: presentedAttachments, 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 })])
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 07cc1a4ae..2b2c8c8db 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -29,7 +29,6 @@ import type {
import { messageWindowPage } from "@/lib/community/models/message"
import {
materializeMessageStream,
- type CanonicalMessage,
type MessageScope,
} from "@/lib/community/message-stream"
import { useMessageOverlayIds } from "@/stores/community/message-stream"
@@ -815,12 +814,13 @@ function useMessagesInner(
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[]>(() => {
- const selected = projection.windowIds.flatMap((id) => { const message = canonicalById.get(id); return message ? [message] : [] }).sort((a, b) => a.seq - b.seq)
- return selected
- }, [projection.windowIds, canonicalById])
+ const canonicalById = useMemo(() => new Map((projection.canonicalMessages ?? []).flatMap((message) =>
+ typeof message.seq === "number" ? [[message.id, { ...message, seq: message.seq }] as const] : [])), [projection.canonicalMessages])
+ const canonicalMessages = useMemo(() => projection.windowIds.flatMap((id) => {
+ const message = canonicalById.get(id)
+ return message ? [message] : []
+ }).sort((a, b) => a.seq - b.seq), [projection.windowIds, canonicalById])
+ const messages = useMemo<Msg[]>(() => (projection.messages ?? []).filter((message) => projection.windowIds.includes(message.id)), [projection.messages, projection.windowIds])
const latestSeq = useMemo<number>(() => {
if (!query.data) return 0
@@ -897,6 +897,7 @@ function useMessagesInner(
isLoading: query.isLoading || (!anchorResolved && messages.length === 0),
navigationBlocked: false,
canonicalById,
+ canonicalMessages,
messages,
latestSeq,
hasMoreOlder,
@@ -947,9 +948,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | Channe
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])
+ const canonicalBase = base.canonicalMessages
useEffect(() => {
if (!channelId) return
getCommunityRuntime(queryClient).messageStream.actions.dispatch(scope, {
diff --git a/src/web/src/hooks/community/use-server-members.dom.test.ts b/src/web/src/hooks/community/use-server-members.dom.test.ts
index 358a9e98b..50a02a382 100644
--- a/src/web/src/hooks/community/use-server-members.dom.test.ts
+++ b/src/web/src/hooks/community/use-server-members.dom.test.ts
@@ -48,7 +48,7 @@ import type {
} from "@alook/shared"
function m(id: string, userId = id, role: Member["role"] = "member"): Member {
- return { id, userId, name: `n_${id}`, discriminator: "0000", avatar: `A`, status: "offline", sub: "", role }
+ return { id, userId, name: `n_${id}`, discriminator: "0000", avatar: `A`, avatarVersion: 0, status: "offline", sub: "", role }
}
function joinEvent(userId: string, id = userId): CommunityMemberJoin {
@@ -459,7 +459,7 @@ describe("useServerMembers search lifecycle", () => {
expect(resultRef.current).toMatchObject({ loading: true, failed: false })
expect(observations.every((value) => value.loading || value.failed)).toBe(true)
await act(async () => {
- queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ userId: person.userId, name: person.name, discriminator: person.discriminator, avatar: person.avatar, avatarVersion: 0 })])
+ queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ identityComplete: false, id: person.userId, name: person.name, discriminator: person.discriminator, avatar: person.avatar, avatarVersion: 0 })])
restore.resolve(); await registry.preload()
})
await vi.waitFor(() => expect(resultRef.current).toMatchObject({ loading: false, failed: false, members: [expect.objectContaining({ id: "a", discriminator: "0000" })] }))
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index 57a843c80..f82fd7f5b 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -271,7 +271,7 @@ export const membersPageQueryFn = (serverId: string, search = "", limit?: number
const data = await apiFetch<MembersEnvelope | SearchEnvelope>(path, communityRequestOptions(client, token, signal, assert))
assert()
if (data.hasMore && !data.cursor) throw new Error("members page missing cursor")
- writeCommunityProfilePatches(data.members.map((member) => communityUserProfilePatch(member.userId, member)), registry, { snapshot: profileSnapshot })
+ writeCommunityProfilePatches(data.members.map((member) => communityUserProfilePatch(member.userId, member, { legacyPresentation: true })), registry, { snapshot: profileSnapshot })
publishCommunityMembersSnapshot(client, serverId, data.members, { token, signal })
assert()
return { members: data.members.map(({ id, userId }) => ({ id, userId })), hasMore: data.hasMore, cursor: data.cursor, limit: data.limit, ...("total" in data ? { total: data.total } : {}), liveRevision: protocol.liveRevision }
diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.ts
index f8c19faea..82004d31d 100644
--- a/src/web/src/hooks/community/use-servers.dom.test.ts
+++ b/src/web/src/hooks/community/use-servers.dom.test.ts
@@ -372,12 +372,16 @@ describe("useServer / projected canonical detail", () => {
})
it("composes a single server detail from canonical resources", async () => {
- apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [{ id: "ch_1", name: "general", categoryId: "cat_1" }, { id: "ch_2", name: "loose", categoryId: null }] } : detailApi(url))
+ const legacyChannel = { id: "ch_1", name: "general", type: "text", serverId: identity.id, categoryId: "cat_1", topic: "Legacy topic", parentChannelId: null,
+ parentMessageId: null, creatorId: "viewer", position: 2, archived: 0, createdAt: "created", lastMessageAt: null, messageCount: 3 }
+ apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [legacyChannel, { ...legacyChannel, id: "ch_2", name: "loose", categoryId: null, archived: 1 }] } : detailApi(url))
await fetchDetail()
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server).toMatchObject({ ...identity, categories: [{ id: "cat_1", channels: [{ id: "ch_1", unread: false }] }, { id: "__uncategorized__", channels: [{ id: "ch_2", unread: false }] }] }))
expect(client.getQueryData(communityKeys.server(identity.id))).toBe(identity.id)
expect(client.getQueryData(communityKeys.servers())).toEqual([identity.id])
+ expect(registry.collections.channels.get("ch_1")).toMatchObject({ topic: "Legacy topic", createdAt: "created", messageCount: 3, archived: false, resourceComplete: false })
+ expect(registry.collections.channels.get("ch_2")).toMatchObject({ archived: true, resourceComplete: false })
})
it("passes the navigation AbortSignal to every server-detail resource", async () => {
diff --git a/src/web/src/hooks/community/use-user-profile.test.ts b/src/web/src/hooks/community/use-user-profile.test.ts
index 9725de73c..c0a37bf98 100644
--- a/src/web/src/hooks/community/use-user-profile.test.ts
+++ b/src/web/src/hooks/community/use-user-profile.test.ts
@@ -20,7 +20,7 @@ describe("useUserProfile / userProfileQueryFn", () => {
const key = communityKeys.profile(profile.id)
expect(await client.query({ queryKey: key, queryFn: userProfileQueryFn(profile.id) })).toEqual({ id: profile.id })
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/u_1/profile", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
- expect(registry.collections.profiles.get(profile.id)).toMatchObject({ userId: profile.id, name: "Alice", aboutMe: "about", mutualServers: 2, avatarVersion: 2 })
+ expect(registry.collections.profiles.get(profile.id)).toMatchObject({ id: profile.id, name: "Alice", aboutMe: "about", mutualServers: 2, avatarVersion: 2 })
expect(client.getQueryData(key)).toEqual({ id: profile.id })
})
diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.ts
index aef366aac..4b081302f 100644
--- a/src/web/src/hooks/community/use-user-profile.ts
+++ b/src/web/src/hooks/community/use-user-profile.ts
@@ -4,7 +4,6 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import type { QueryFunctionContext } from "@tanstack/react-query"
import { apiFetchProfiles } from "@/lib/community/profile-seed"
-import { avatarInitial } from "@/lib/community/avatar"
/**
* Fetches a public user profile card (avatar, name, aboutMe, mutual-server
@@ -50,7 +49,7 @@ export const userProfileQueryFn = (userId: string) => async (context: QueryFunct
ownerUserId: profile.kind === "bot" ? profile.ownerProfile.id : null,
},
avatar: {
- avatar: profile.image ?? avatarInitial(profile.name),
+ avatar: profile.image,
avatarVersion: profile.avatarVersion,
},
status: {
diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.ts
index 1ccc00900..885be345a 100644
--- a/src/web/src/lib/api/client.ts
+++ b/src/web/src/lib/api/client.ts
@@ -1,4 +1,4 @@
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestedCommunityContract } from "@alook/shared"
import { communityReadTarget, decodeCommunityReadResponse } from "@/lib/community/read-response"
import { createStore } from "@tanstack/store";
import { ApiError, UnauthorizedError, isAbortError } from "@/lib/errors";
@@ -171,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, async () => decodeCommunityReadResponse(path, options?.method, res, await res.json()) as T, () => {
+ const data = await readObservedResponse(res, async () => decodeCommunityReadResponse(path, options?.method, res, await res.json(), new Headers(options?.headers).has(COMMUNITY_CONTRACT_HEADER) ? requestedCommunityContract(new Headers(options?.headers)) ?? COMMUNITY_CONTRACT_VERSION : COMMUNITY_CONTRACT_VERSION) as T, () => {
options?.assertActive?.();
if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");
});
diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.ts
index 98df7a8bc..680528bff 100644
--- a/src/web/src/lib/broadcast.ts
+++ b/src/web/src/lib/broadcast.ts
@@ -2,24 +2,30 @@ import { getCloudflareContext } from "@opennextjs/cloudflare"
import type { WsMessage, DaemonPushMessage } from "@alook/shared"
import {
COMMUNITY_BULK_BODY_MAX_BYTES,
+ COMMUNITY_CONTRACT_HEADER,
DEV_WS_DO_URL,
createLogger,
encodeCommunityBrowserEvent,
encodeCommunityUserTargetPathSegment,
isValidCommunityUserTarget,
+ type CommunityContract,
} from "@alook/shared"
import { fetchViaBindingOrDevFallback } from "./dev-binding-fetch"
-import { projectCommunityProducerEvent } from "./community/producer-contract"
+import { communityProducerContract, projectCommunityProducerEvent } from "./community/producer-contract"
const log = createLogger({ service: "broadcast" })
const bulkBroadcastMaxUserIds = 1000
const 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))
+ const contract = communityProducerContract(env as Env)
+ const encoded = encodeCommunityBrowserEvent(message, contract === 3 ? 3 : 2)
+ if (!encoded.ok) return encoded
+ const wire = encoded.event.type === "community:channel.membership.change"
+ ? encodeCommunityBrowserEvent(projectCommunityProducerEvent(encoded.event, env as Env, contract === 3 ? 3 : 2), contract)
+ : encoded
+ return wire.ok ? { ...wire, contract } : wire
}
/**
@@ -54,12 +60,12 @@ export async function wsDoFetch(
async function doSend(
url: string,
body: string,
- opts: { label: string; type: string },
+ opts: { label: string; type: string; contract?: CommunityContract },
): Promise<{ sent: number }> {
const { env } = getCloudflareContext()
const res = await wsDoFetch(env as Env, url, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...(opts.contract === 3 ? { [COMMUNITY_CONTRACT_HEADER]: "3" } : {}) },
body,
}, opts)
if (!res.ok) {
@@ -73,7 +79,7 @@ async function doSend(
}
}
-function sendBroadcast(url: string, body: string, opts: { label: string; type: string }): Promise<void> {
+function sendBroadcast(url: string, body: string, opts: { label: string; type: string; contract?: CommunityContract }): Promise<void> {
const promise = doSend(url, body, opts)
try {
const { ctx } = getCloudflareContext()
@@ -163,7 +169,7 @@ async function runBroadcastToUsers(
const result = await doSend(
community ? "/broadcast/community/users" : "/broadcast/users",
serializeBulkBroadcast(chunk, wireMessage, excludeUserId, community),
- { label: `${target}:chunk:${chunkNumber}/${chunks.length}`, type: message.type },
+ { label: `${target}:chunk:${chunkNumber}/${chunks.length}`, type: message.type, contract: encoded?.contract },
)
safeLog(() => log.info("broadcast_users_chunk_complete", {
target,
@@ -233,7 +239,7 @@ export function broadcastToUser(userId: string, message: WsMessage): Promise<voi
return sendBroadcast(
`/broadcast/community/user/${encodeCommunityUserTargetPathSegment(userId)}`,
encoded.body,
- { label: userId, type: message.type },
+ { label: userId, type: message.type, contract: encoded.contract },
)
}
return sendBroadcast(
diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.ts
index e8028d9a8..741c0ff30 100644
--- a/src/web/src/lib/community-db/collections.ts
+++ b/src/web/src/lib/community-db/collections.ts
@@ -1,4 +1,5 @@
import type { z } from "zod"
+import { AttentionScopeSchema, AttentionItemSchema } from "@alook/shared"
import { clearPersistedCache, type QualifiedPersister } from "@/lib/query-persister"
import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"
import {
@@ -19,8 +20,6 @@ import type { CanonicalMessage } from "@/lib/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
import {
categorySchema,
- attentionItemSchema,
- attentionScopeSchema,
channelMembershipSchema,
channelSchema,
folderItemSchema,
@@ -93,12 +92,12 @@ function buildCommunityDbRegistry(
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 profiles = collectionFor("profiles", profileSchema, (row) => row.id)
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 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)
diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.ts
index d95d91c69..65d5dbffd 100644
--- a/src/web/src/lib/community-db/projections.dom.test.ts
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -44,7 +44,7 @@ describe("community DB projections", () => {
await act(async () => reject(new Error("controlled profile restore failure")))
await waitFor(() => expect(rendered.result.current.profiles.isError).toBe(true))
expect(rendered.result.current.state).toEqual({ loading: false, failed: true })
- await act(async () => client.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 1 })]))
+ await act(async () => client.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ identityComplete: false, id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 1 })]))
await waitFor(() => expect(rendered.result.current.state).toEqual({ loading: false, failed: false }))
expect(rendered.result.current.profiles.data.get("peer")?.discriminator).toBe("0042")
} finally { rendered.unmount(); await registry.cleanup(); client.clear() }
@@ -400,9 +400,9 @@ describe("community DB projections", () => {
{ id: "dm-no-profile:ghost:access", channelId: "dm-no-profile", userId: "ghost", relation: "access" },
])
collection("profiles", [
- { userId: "viewer", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 1 },
- { userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 2 },
- { userId: "quiet", name: "Quiet", discriminator: "0003", avatar: "Q", avatarVersion: 1 },
+ { identityComplete: true, id: "viewer", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 1 },
+ { identityComplete: true, id: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 2 },
+ { identityComplete: true, id: "quiet", name: "Quiet", discriminator: "0003", avatar: "Q", avatarVersion: 1 },
])
collection("messages", [
{ id: "m2", channelId: "c1", type: "chat", authorId: "peer", content: "second", seq: 2 },
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 2734b8459..1a74fd95e 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -8,11 +8,14 @@ import { CommunityRuntimeProvider } from "@/stores/community/runtime"
import { notifLevelDisplay } from "@alook/shared"
import { projectForumSidebar } from "@/lib/community/forum-sidebar"
import { avatarInitial } from "@/lib/community/avatar"
+import { readCommunityProfile } from "@/lib/community/profile-read"
import type { DM } from "@/lib/community/models/people"
import { sortDmsByActivity } from "@/lib/community/dm-order"
import type { CommunityProfile } from "@/lib/community/models/people"
import type { Category, CommunityFolder, Server } from "@/lib/community/models/navigation"
import type { Msg } from "@/lib/community/models/message"
+import { presentCanonicalMessage } from "@/lib/community/message-wire"
+import type { CommunityMessagePreview } from "@alook/shared"
import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
import type { CommunityDbRegistry } from "./collections"
import { useCommunityPreviewProfiles } from "@/stores/community/profile-preview"
@@ -29,10 +32,12 @@ import type {
ServerRow,
} from "./schema"
+function projectedCanonicalMessage(message: MessageRow, child?: ChannelRow): CommunityMessagePreview & { resourceComplete: boolean } {
+ return { ...message, ...(child ? { thread: { id: child.id, name: child.name ?? "", messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, preview: child.preview, participantCount: child.participantCount } } : {}) }
+}
+
function projectedMessage(message: MessageRow, child?: ChannelRow): Msg {
- const { channelId: _channelId, replyToId: _replyToId, ...model } = message
- const value = { ...model, ...(child ? { thread: { id: child.id, name: child.name, messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, preview: child.preview, participantCount: child.participantCount } } : {}) } as Msg
- return value
+ return presentCanonicalMessage(projectedCanonicalMessage(message, child))
}
let communityDbContext: Context<CommunityDbRegistry | null> | null = null
@@ -215,7 +220,7 @@ export function useServerTreeProjection(serverId: string | null) {
))
const channelView = (channel: ChannelRow): Category["channels"][number] => ({
id: channel.id,
- name: channel.name,
+ name: channel.name ?? "",
active: false,
unread: channel.unread,
muted: channel.muted,
@@ -262,14 +267,14 @@ 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 = useCollectionQuery("profiles", ({ row }) => inArray(row.userId, userIds)).data
+ const profiles = useCollectionQuery("profiles", ({ row }) => inArray(row.id, userIds)).data
const readStates = useCollectionQuery("readStates", ({ row }) => inArray(row.channelId, channelIds)).data
const rows = { registry, channels, channelMemberships, profiles, readStates }
return useMemo(() => {
const viewerId = rows.registry?.accountId
if (!viewerId || !rows.channels || !rows.channelMemberships || !rows.profiles) return undefined
const channelMemberships = rows.channelMemberships
- const profileById = new Map(rows.profiles.map((profile) => [profile.userId, profile]))
+ const profileById = new Map(rows.profiles.map((profile) => [profile.id, profile]))
const readStateByChannel = new Map((rows.readStates ?? []).map((state) => [state.channelId, state]))
const result = sortDmsByActivity(rows.channels
.filter((channel) => channel.type === "dm")
@@ -284,12 +289,9 @@ export function useDmProjection() {
if (!profile) return []
const readState = readStateByChannel.get(channel.id)
return [{
+ ...readCommunityProfile(profile, profile.id),
id: channel.id,
- userId: profile.userId,
- name: profile.name,
- discriminator: profile.discriminator,
- avatar: profile.avatar,
- avatarVersion: profile.avatarVersion,
+ userId: profile.id,
status: "offline",
preview: channel.preview ?? "",
...(channel.lastMessageAt ? { activityAt: channel.lastMessageAt } : {}),
@@ -355,8 +357,12 @@ export function useMessageWindowProjection(channelId: string | null, ids: readon
: undefined }).data as Array<{ id: string }> | undefined
const selected = useMemo(() => ids ?? warm?.map((message) => message.id) ?? [], [ids, warm])
const allIds = useMemo(() => [...new Set([...selected, ...liveIds])], [selected, liveIds])
- const messages = useMessageProjection(channelId, allIds)
- return { messages, windowIds: selected }
+ const { data } = useJoinedMessageQuery(channelId, allIds)
+ const canonicalMessages = useMemo(() => !channelId || !data ? undefined : data
+ .sort((a, b) => (a.message.seq ?? 0) - (b.message.seq ?? 0))
+ .map(({ message, child }) => projectedCanonicalMessage(message, child)), [channelId, data])
+ const messages = useMemo(() => canonicalMessages?.map(presentCanonicalMessage), [canonicalMessages])
+ return { messages, canonicalMessages, windowIds: selected }
}
function useCollectionById<N extends "channels" | "servers">(name: N) {
@@ -420,14 +426,14 @@ export function useNotificationSettingsProjection() {
export function useCanonicalProfilesProjection(userIds?: readonly string[]) {
const previewProfiles = useCommunityPreviewProfiles()
- const projection = useCollectionQuery("profiles", ({ row }) => userIds === undefined ? eq(1, 1) : inArray(row.userId, [...userIds]))
+ const projection = useCollectionQuery("profiles", ({ row }) => userIds === undefined ? eq(1, 1) : inArray(row.id, [...userIds]))
const { registry } = projection
const livePresence = useSelector(registry?.runtime.ws ?? absentPresence, (state) => previewProfiles ? null : userIds === undefined ? [...state.presenceByUserId] : userIds.map((id) => [id, state.presenceByUserId.get(id)] as const), { compare: (left, right) => left === right || (!!left && !!right && left.length === right.length && left.every(([id, presence], index) => id === right[index]?.[0] && presence === right[index]?.[1])) })
const data: ReadonlyMap<string, CommunityProfile> = useMemo(() => {
if (previewProfiles) return previewProfiles
const merged = new Map<string, CommunityProfile>()
for (const profile of projection.data ?? []) {
- merged.set(profile.userId, { ...profile, id: profile.userId })
+ merged.set(profile.id, { ...profile, id: profile.id })
}
for (const [userId, presence] of livePresence ?? []) {
if (presence === undefined) continue
@@ -478,7 +484,7 @@ export function useChannelRosterRows(channelId: string, relation: "access" | "no
export function useCanonicalCommunityProfile(userId: string | null | undefined) {
const preview = useCommunityPreviewProfiles()
- const { registry, data } = useCollectionQuery("profiles", ({ row }) => eq(row.userId, userId), !!userId)
+ const { registry, data } = useCollectionQuery("profiles", ({ row }) => eq(row.id, userId), !!userId)
const profile = data?.[0]
const presence = useSelector(registry?.runtime.ws ?? absentPresence, (state) => userId ? state.presenceByUserId.get(userId) : undefined)
return useMemo(() => {
@@ -512,7 +518,7 @@ export function useChannelRefDirectoryProjection(): ChannelRefDirectory | undefi
.filter((channel) => channel.serverId === server.id)
.flatMap((channel) => (
channel.type === "text" || channel.type === "forum"
- ? [{ id: channel.id, name: channel.name, type: channel.type }]
+ ? [{ id: channel.id, name: channel.name ?? "", type: channel.type }]
: []
)),
}))
diff --git a/src/web/src/lib/community-db/schema.test.ts b/src/web/src/lib/community-db/schema.test.ts
index 243f3d311..7b2babcab 100644
--- a/src/web/src/lib/community-db/schema.test.ts
+++ b/src/web/src/lib/community-db/schema.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest"
import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"
+import { AttentionScopeSchema, AttentionItemSchema } from "@alook/shared"
import {
+ canonicalChannelRow, channelSchema, messageSchema, profileSchema,
channelMembershipKey,
channelMembershipSchema,
communityCollectionSchemas,
@@ -12,6 +14,29 @@ import {
} from "./schema"
describe("community DB schemas", () => {
+ it("uses shared attention schemas and rejects their invalid relationships on cache input", () => {
+ expect(communityCollectionSchemas.attentionScopes).toBe(AttentionScopeSchema)
+ expect(communityCollectionSchemas.attentionItems).toBe(AttentionItemSchema)
+ const valid = { id: "attention", kind: "forum_post", sourceId: "child", scopeId: "forum", messageId: "opener", childChannelId: "child", openerSeq: 9, readTarget: { channelId: "forum", seq: 9 }, createdAt: "2026-10-11T01:00:00Z" }
+ expect(communityCollectionSchemas.attentionItems.parse(valid)).toEqual(valid)
+ for (const invalid of [
+ { ...valid, sourceId: "other-child" },
+ { ...valid, readTarget: { channelId: "forum", seq: 8 } },
+ { ...valid, actorUserId: "actor" },
+ { ...valid, kind: "mention" },
+ { ...valid, kind: "reply", scopeId: null },
+ { ...valid, kind: "friend_request", actorUserId: "actor" },
+ ]) expect(communityCollectionSchemas.attentionItems.safeParse(invalid).success).toBe(false)
+ for (const kind of ["mention", "reply"]) {
+ const message = { id: "attention", kind, sourceId: "source", scopeId: "channel", messageId: "message", actorUserId: "actor", createdAt: valid.createdAt }
+ expect(communityCollectionSchemas.attentionItems.parse(message)).toEqual(message)
+ expect(communityCollectionSchemas.attentionItems.safeParse({ ...message, actorUserId: null }).success).toBe(false)
+ }
+ const friend = { id: "attention", kind: "friend_request", sourceId: "request", actorUserId: "actor", createdAt: valid.createdAt }
+ expect(communityCollectionSchemas.attentionItems.parse(friend)).toEqual(friend)
+ expect(communityCollectionSchemas.attentionItems.safeParse({ ...friend, scopeId: "channel" }).success).toBe(false)
+ })
+
it("defines the canonical collection families, including independent attention state", () => {
expect(Object.keys(communityCollectionSchemas)).toEqual([
"servers",
@@ -90,3 +115,29 @@ describe("community DB schemas", () => {
expect(parsed).not.toHaveProperty("position")
})
})
+
+
+describe("canonical completeness", () => {
+ const full = { id: "channel", type: "text" as const, serverId: "server", categoryId: null, name: "Channel", topic: "Preserve topic", parentChannelId: null, parentMessageId: null, creatorId: "author", position: 3, archived: false, createdAt: "created", lastMessageAt: null, messageCount: 0, resourceComplete: true as const }
+ it("keeps full fields through sparse deltas and rejects an invalid full claim before merging", () => {
+ const loaded = canonicalChannelRow(full)
+ expect(canonicalChannelRow({ id: full.id, type: full.type, name: "Renamed", topic: undefined }, loaded)).toEqual({ ...loaded, name: "Renamed" })
+ const stub = canonicalChannelRow({ id: "stub", type: "thread", name: "Preview" })
+ expect(stub.resourceComplete).toBe(false)
+ expect(stub).not.toHaveProperty("topic")
+ expect(canonicalChannelRow({ ...full, id: "stub" }, stub).resourceComplete).toBe(true)
+ const { topic: _topic, ...incomplete } = full
+ expect(() => canonicalChannelRow(incomplete, loaded)).toThrow()
+ expect(channelSchema.safeParse({ ...loaded, topic: undefined }).success).toBe(false)
+ })
+ it("uses profile id without relationship aliases and distinguishes incomplete identity", () => {
+ const profile = { id: "author", name: "Author", discriminator: "12345", avatar: null, avatarVersion: 0, identityComplete: true }
+ expect(profileSchema.parse(profile)).toEqual(profile)
+ expect(profileSchema.parse({ id: "author", name: "Author", identityComplete: false })).toEqual({ id: "author", name: "Author", identityComplete: false })
+ expect(profileSchema.safeParse({ ...profile, discriminator: null }).success).toBe(false)
+ expect(profileSchema.safeParse({ ...profile, avatarVersion: undefined }).success).toBe(false)
+ const preview = { id: "message", channelId: "channel", type: "chat", resourceComplete: false }
+ expect(messageSchema.parse(preview)).toEqual(preview)
+ expect(messageSchema.safeParse({ ...preview, resourceComplete: true }).success).toBe(false)
+ })
+})
diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.ts
index 7edc77574..28ce9187d 100644
--- a/src/web/src/lib/community-db/schema.ts
+++ b/src/web/src/lib/community-db/schema.ts
@@ -1,6 +1,6 @@
import { z } from "zod"
-import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityReadStateResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "@alook/shared"
import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"
+import { AttentionScopeSchema, AttentionItemSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMessagePreviewSchema, CommunityReadStateResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "@alook/shared"
const nullableString = z.string().nullable()
const optionalNullableString = nullableString.optional()
@@ -32,15 +32,7 @@ export const categorySchema = z.object({
pending: 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(),
+export const channelLocalSchema = z.object({
muted: z.boolean(),
unread: z.boolean(),
/** Forum channel's own unread bit, excluding participating child rows. */
@@ -54,6 +46,20 @@ export const channelSchema = CommunityChannelResourceSchema.pick({
participantCount: z.number().int().nonnegative().optional(),
})
+export const channelSchema = z.discriminatedUnion("resourceComplete", [
+ CommunityChannelResourceSchema.strip().extend({
+ ...channelLocalSchema.shape,
+ resourceComplete: z.literal(true),
+ }),
+ CommunityChannelResourceSchema.partial({
+ serverId: true, categoryId: true, parentChannelId: true, parentMessageId: true,
+ creatorId: true, lastMessageAt: true, createdAt: true, messageCount: true, topic: true,
+ }).strip().extend({
+ ...channelLocalSchema.shape,
+ resourceComplete: z.literal(false).default(false),
+ }),
+])
+
export const serverMembershipSchema = z.object({
id: z.string().min(1),
serverId: z.string().min(1),
@@ -65,44 +71,31 @@ export const serverMembershipSchema = z.object({
viewer: z.boolean(),
})
-export const channelMembershipSchema = CommunityMemberRelationSchema.pick({
- channelId: true, userId: true, relation: true, isCreator: true,
-}).strip().partial({ isCreator: true }).extend({
+export const channelMembershipSchema = CommunityMemberRelationSchema.strip().partial({
+ source: true, isCreator: true, role: true, memberId: true,
+}).extend({
id: z.string().min(1),
- memberId: z.string().optional(),
- source: z.enum([
- "explicit",
- "inherited",
- "admin",
- PARTICIPANT_SOURCE.MENTION,
- PARTICIPANT_SOURCE.SPOKE,
- PARTICIPANT_SOURCE.ADDED,
- ]).optional(),
+ source: z.enum(["explicit", "inherited", "admin", PARTICIPANT_SOURCE.MENTION, PARTICIPANT_SOURCE.SPOKE, PARTICIPANT_SOURCE.ADDED]).optional(),
})
-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(),
- ownerUserId: optionalNullableString,
- ownerHandle: optionalNullableString,
- mutualServers: z.number().int().nonnegative().optional(),
- ownedByViewer: z.boolean().optional(),
- statusEmoji: CommunityResourceProfileSchema.shape.statusEmoji.optional(),
- statusText: CommunityResourceProfileSchema.shape.statusText.nullable().optional(),
+const incompleteProfileSchema = CommunityResourceProfileSchema.partial().required({ id: true }).strip().extend({
+ identityComplete: z.literal(false),
})
-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(),
- failed: z.boolean().optional(),
- replyToId: z.string().nullable().optional(),
-}).loose()
+export const profileSchema = z.discriminatedUnion("identityComplete", [
+ CommunityResourceProfileSchema.strip().extend({
+ discriminator: CommunityResourceProfileSchema.shape.discriminator.unwrap(),
+ identityComplete: z.literal(true),
+ }),
+ incompleteProfileSchema,
+])
+
+export const messageSchema = z.discriminatedUnion("resourceComplete", [
+ CommunityMessageResourceSchema.strip().extend({ resourceComplete: z.literal(true) }),
+ CommunityMessagePreviewSchema.strip().required({ channelId: true }).extend({
+ resourceComplete: z.literal(false).default(false),
+ }),
+])
export const readStateSchema = CommunityReadStateResourceSchema.strip()
@@ -119,33 +112,6 @@ export const readStateClockSchema = z.object({
revision: z.number().int().nonnegative(),
})
-export const attentionScopeSchema = z.strictObject({
- scopeId: z.string().min(1),
- channelId: z.string().min(1),
- serverId: optionalNullableString,
- parentChannelId: optionalNullableString,
- ordinaryUnread: z.boolean(),
- lastUnreadSeq: z.number().int().nonnegative(),
- lastAttentionSeq: z.number().int().nonnegative().nullable().optional(),
- attentionCount: z.number().int().nonnegative(),
-})
-
-export const attentionItemSchema = z.strictObject({
- id: z.string().min(1),
- kind: z.enum(["mention", "reply", "friend_request", "forum_post"]),
- sourceId: z.string().min(1),
- scopeId: optionalNullableString,
- messageId: optionalNullableString,
- actorUserId: optionalNullableString,
- createdAt: z.string(),
- childChannelId: z.string().min(1).optional(),
- openerSeq: z.number().int().nonnegative().optional(),
- readTarget: z.strictObject({
- channelId: z.string().min(1),
- seq: z.number().int().nonnegative(),
- }).optional(),
-})
-
export const folderSchema = z.object({
id: z.string().min(1),
name: z.string(),
@@ -184,8 +150,8 @@ export const communityCollectionSchemas = {
friendships: friendshipSchema,
readStates: readStateSchema,
readStateClock: readStateClockSchema,
- attentionScopes: attentionScopeSchema,
- attentionItems: attentionItemSchema,
+ attentionScopes: AttentionScopeSchema,
+ attentionItems: AttentionItemSchema,
folders: folderSchema,
folderItems: folderItemSchema,
notificationSettings: notificationSettingSchema,
@@ -203,8 +169,8 @@ export type MessageRow = z.infer<typeof messageSchema>
export type FriendshipRow = z.infer<typeof friendshipSchema>
export type ReadStateRow = z.infer<typeof readStateSchema>
export type ReadStateClockRow = z.infer<typeof readStateClockSchema>
-export type AttentionScopeRow = z.infer<typeof attentionScopeSchema>
-export type AttentionItemRow = z.infer<typeof attentionItemSchema>
+export type AttentionScopeRow = z.infer<typeof AttentionScopeSchema>
+export type AttentionItemRow = z.infer<typeof AttentionItemSchema>
export type FolderRow = z.infer<typeof folderSchema>
export type FolderItemRow = z.infer<typeof folderItemSchema>
export type NotificationSettingRow = z.infer<typeof notificationSettingSchema>
@@ -213,6 +179,8 @@ export function canonicalChannelRow(
input: Pick<ChannelRow, "id" | "type"> & Partial<Omit<ChannelRow, "id" | "type" | "name">> & { name?: string | null },
previous?: ChannelRow,
): ChannelRow {
+ if (input.resourceComplete === true) CommunityChannelResourceSchema.strip().parse(input)
+ const fields = Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined))
return channelSchema.parse({
serverId: null,
categoryId: null,
@@ -227,8 +195,9 @@ export function canonicalChannelRow(
pending: false,
lastMessageAt: null,
...previous,
- ...input,
- name: input.name === undefined ? previous?.name ?? "" : input.name ?? "",
+ ...fields,
+ name: input.name === undefined ? previous?.name ?? null : input.name,
+ resourceComplete: input.resourceComplete === true || previous?.resourceComplete === true,
})
}
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index 7181e5de1..a3f9da902 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -1,7 +1,7 @@
import { projectPostedMessage } from "@/lib/community/message-wire"
import { QueryClient } from "@tanstack/react-query"
import { afterEach, describe, expect, it, vi } from "vitest"
-import { AccountAttentionSnapshotSchema, type CommunityWsEvent } from "@alook/shared"
+import { AccountAttentionSnapshotSchema, CommunityMessageResourceSchema, communityMessagePreviewFromLegacy, type CommunityWsEvent } from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { rememberMessageAccessScope } from "./message-access-scope"
@@ -33,6 +33,7 @@ import {
publishCommunityDmSummary,
publishCommunityMessages,
publishCommunityChannelDirectory,
+ publishCommunityChannelMetadata,
publishCommunityServerFields,
publishCommunityChannelFields,
publishCommunityLiveSnapshot as publishCommunityLiveSnapshotWithProof,
@@ -48,6 +49,11 @@ import {
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore } from "@/stores/community/ws"
import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
+import { decodeCommunityReadResponse } from "@/lib/community/read-response"
+import type { MessageInput } from "@/lib/community/models/message"
+import { writeCommunityCollectionRows } from "./write"
+
+const pendingApproval = { friendshipId: "friendship", status: "pending" as const, waitingOn: null, otherProfile: { id: "approval", name: "Approval", discriminator: "0004", image: null, avatarVersion: 1 }, botProfile: { id: "bot", name: "Bot", discriminator: "0005", image: null, avatarVersion: 1 } }
const registries: CommunityDbRegistry[] = []
const unregisters: Array<() => void> = []
@@ -151,11 +157,129 @@ describe("community DB sync", () => {
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" } : {}) }])
+ ...(field === "author" ? { authorId: "other" } : field === "nonce" ? { clientNonce: "other" } : { channelId: "c2" }) }])
expect(db.collections.messages.get(identity.id)?.replyTo).toBeUndefined()
expect(db.collections.messages.get(identity.id)?.replyToId).toBeNull()
})
+ it("keeps full raw facts across a weak preview and explicit full clearing", async () => {
+ const db = await registry()
+ const full = CommunityMessageResourceSchema.parse({ id: "raw", channelId: "c1", seq: 1, type: "chat", authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 4, content: "full", createdAt: "now", replyToId: "reply", replyTo: { id: "reply", authorName: "Peer", text: "prior" }, clientNonce: "nonce", attachments: [{ id: "a2", name: "raw", url: "/raw", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }], embeds: [null, { unsupported: true }], thread: { id: "thread", name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] } })
+ ingestMessages(db, "c1", [{ ...full, resourceComplete: true }])
+ const preview = communityMessagePreviewFromLegacy({ id: "raw", seq: 1, type: "chat", authorId: "peer", createdAt: "now", content: "preview" }, "c1")
+ ingestMessages(db, "c1", [preview])
+ expect(db.collections.messages.get(full.id)).toMatchObject({ ...full, content: "preview", resourceComplete: true })
+ ingestMessages(db, "c1", [{ id: "raw", thread: { id: "thread", participants: [{ id: "peer", avatarVersion: 4 }, { id: "unknown" }] } }])
+ expect(db.collections.messages.get(full.id)?.thread?.participants).toEqual(full.thread!.participants)
+ expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer", avatar: null, avatarVersion: 4 })
+ expect(db.collections.profiles.get("unknown")).toMatchObject({ id: "unknown", identityComplete: false })
+ expect(db.collections.profiles.get("unknown")).not.toHaveProperty("name")
+ ingestMessages(db, "c1", [{ ...full, resourceComplete: true, attachments: [], embeds: [], clientNonce: null, replyToId: null, replyTo: undefined }])
+ expect(db.collections.messages.get(full.id)).toMatchObject({ resourceComplete: true, attachments: [], embeds: [], clientNonce: null, replyToId: null })
+ expect(db.collections.messages.get(full.id)?.replyTo).toBeUndefined()
+ })
+
+ it.each([
+ ["legacy", "empty"], ["legacy", "incomplete"],
+ ["confirmed2", "empty"], ["confirmed2", "incomplete"],
+ ] as const)("preserves full attachments through %s %s read publication", async (contract, shape) => {
+ const db = await registry()
+ const full = CommunityMessageResourceSchema.parse({
+ id: "attachment-read", channelId: "c1", seq: 1, type: "chat", authorId: "peer",
+ createdAt: "now", content: "full", replyToId: null, clientNonce: null,
+ attachments: [
+ { id: "a2", name: "unknown", url: "/a2", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
+ { id: "a1", name: "photo", url: "/a1", thumbnailUrl: "/thumb", contentType: "image/png", sizeBytes: 12, width: 2, height: 3 },
+ ],
+ })
+ const legacy = { ...full, content: "read preview", attachments: shape === "empty" ? [] : [{ kind: "file", name: "old", url: "/old" }] }
+ const body = contract === "legacy" ? { messages: [legacy] } : {
+ contractVersion: 2, channelId: "c1", messages: [legacy],
+ page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 1 },
+ surfaceReceipt: { channelId: "c1", surfaceKind: "channel" },
+ }
+ const response = new Response(null, { headers: contract === "legacy" ? {} : { "X-Alook-Community-Contract": "2" } })
+ const read = decodeCommunityReadResponse("/api/community/channels/c1/messages", "GET", response, body, 2) as { messages: MessageInput[] }
+ expect(read.messages[0]).toMatchObject({ resourceComplete: false, attachments: shape === "empty" ? [] : [{ name: "old", url: "/old" }] })
+ ingestMessages(db, "c1", [{ ...read.messages[0]!, id: "weak-only" }])
+ expect(db.collections.messages.get("weak-only")).toMatchObject({ resourceComplete: false, attachments: read.messages[0]!.attachments })
+ ingestMessages(db, "c1", [{ ...full, resourceComplete: true }])
+ expect(() => ingestMessages(db, "c1", read.messages)).not.toThrow()
+ expect(db.collections.messages.get(full.id)).toMatchObject({ content: "read preview", resourceComplete: true, attachments: full.attachments })
+ ingestMessages(db, "c1", [{ ...full, resourceComplete: true, attachments: [...full.attachments].reverse() }])
+ expect(db.collections.messages.get(full.id)?.attachments).toEqual([...full.attachments].reverse())
+ ingestMessages(db, "c1", [{ ...full, resourceComplete: true, attachments: [] }])
+ expect(db.collections.messages.get(full.id)?.attachments).toEqual([])
+ })
+
+ it.each([false, true])("does not canonicalize an Attention initial for a known full profile=%s", async known => {
+ const db = await registry()
+ if (known) {
+ writeCommunityCollectionRows(db, "profiles", [{
+ id: "peer", name: "Peer", discriminator: "0002", aboutMe: "actual bio",
+ avatar: null, avatarVersion: 4, statusEmoji: "🌿", statusText: "Actual status",
+ ownerHandle: "owner#12345", mutualServers: 2, ownedByViewer: false, identityComplete: true,
+ }], row => row.id)
+ expect(db.collections.profiles.get("peer")).toMatchObject({ identityComplete: true, avatar: null, avatarVersion: 4 })
+ }
+ const snapshot = forumAttentionSnapshot()
+ snapshot.included.profiles[0]!.avatarVersion = 4
+ ingestAttentionSnapshot(db, snapshot)
+ const profile = db.collections.profiles.get("peer")
+ expect(profile).toMatchObject({ id: "peer", name: "Peer", discriminator: "0002", avatarVersion: 4, identityComplete: known })
+ if (known) expect(profile).toMatchObject({ avatar: null, aboutMe: "actual bio", statusEmoji: "🌿", statusText: "Actual status", ownerHandle: "owner#12345", mutualServers: 2, ownedByViewer: false })
+ else expect(profile).not.toHaveProperty("avatar")
+ snapshot.included.profiles[0]!.avatar = "https://cdn.example/peer.png"
+ snapshot.included.profiles[0]!.avatarVersion = 5
+ ingestAttentionSnapshot(db, snapshot)
+ expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "https://cdn.example/peer.png", avatarVersion: 5, identityComplete: true })
+ snapshot.included.profiles[0]!.avatar = "P"
+ snapshot.included.profiles[0]!.avatarVersion = 4
+ ingestAttentionSnapshot(db, snapshot)
+ expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "https://cdn.example/peer.png", avatarVersion: 5, identityComplete: true })
+ })
+
+ it("rejects invalid full batches before writing child rows", async () => {
+ const db = await registry()
+ const good = { id: "good", channelId: "c1", seq: 1, type: "chat" as const, authorId: "peer", createdAt: "now", content: "body", clientNonce: null, replyToId: null, attachments: [], resourceComplete: true, thread: { id: "child", name: "Child", messageCount: 0 } }
+ expect(() => ingestMessages(db, "c1", [good, { ...good, id: "bad", attachments: undefined }])).toThrow()
+ expect(db.collections.messages.size).toBe(0)
+ expect(db.collections.channels.get("child")).toBeUndefined()
+ })
+
+ it("keeps full topic and times through a later weak sidebar read", async () => {
+ const db = await registry()
+ const full = { id: "c1", type: "text" as const, serverId: "s1", categoryId: "cat1", name: "Channel", topic: "Full topic", parentChannelId: null, parentMessageId: null, creatorId: "peer", position: 2, archived: false, createdAt: "created", lastMessageAt: "last", messageCount: 7, resourceComplete: true }
+ publishCommunityChannelMetadata(db.queryClient, { metadata: full, proof: { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined } })
+ const detail = { id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "Category", channels: [{ id: "c1", name: "Renamed", active: false, unread: false, archived: 0 }] }] }
+ ingestServerDetail(db, detail)
+ expect(db.collections.channels.get(full.id)).toMatchObject({ topic: "Full topic", createdAt: "created", lastMessageAt: "last", messageCount: 7, archived: false, resourceComplete: true, name: "Renamed" })
+ ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [{ ...detail.categories[0].channels[0], archived: 1 }] }] })
+ expect(db.collections.channels.get(full.id)).toMatchObject({ archived: true, resourceComplete: true, topic: "Full topic", lastMessageAt: "last", messageCount: 7 })
+ const { archived: _archived, ...omitted } = detail.categories[0].channels[0]
+ ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [omitted] }] })
+ expect(db.collections.channels.get(full.id)).toMatchObject({ archived: true, resourceComplete: true, topic: "Full topic", createdAt: "created", lastMessageAt: "last", messageCount: 7 })
+ const before = db.collections.channels.get(full.id)
+ expect(() => ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [{ ...detail.categories[0].channels[0], archived: false, resourceComplete: true }] }] })).toThrow()
+ expect(() => ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [{ ...full, active: false, unread: false, archived: 0 }] }] })).toThrow()
+ expect(db.collections.channels.get(full.id)).toEqual(before)
+ })
+
+ it.each([{ archived: 2 }, { archived: "0" }, { archived: null }, { topic: null }, { messageCount: -1 }, { serverId: "foreign" }])("rejects an invalid later sidebar row before publication %j", async (fields) => {
+ const db = await registry()
+ const original = { id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "Category", channels: [{ id: "old", name: "Old", active: false, unread: false }] }] }
+ ingestServerDetail(db, original)
+ const previousServer = db.collections.servers.get("s1")
+ const previousChannel = db.collections.channels.get("old")
+ const valid = { id: "new", name: "New", active: false, unread: false, archived: 0 }
+ const invalid = { ...valid, id: "bad", ...fields }
+ expect(() => ingestServerDetail(db, { ...original, name: "Changed", categories: [{ ...original.categories[0], channels: [valid, invalid] }] })).toThrow()
+ expect(db.collections.servers.get("s1")).toEqual(previousServer)
+ expect(db.collections.channels.get("old")).toEqual(previousChannel)
+ expect(db.collections.channels.has("new")).toBe(false)
+ expect(db.collections.channels.has("bad")).toBe(false)
+ })
+
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 }] }] }
@@ -365,14 +489,14 @@ describe("community DB sync", () => {
seq: 1,
content: "message",
createdAt: "2026-09-26T00:00:00.000Z",
- reactions: [{ emoji: "👍", count: 1, me: false }],
+ reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
}
ingestMessages(db, "c1", [staleMessage])
const token = captureCommunityLiveSnapshotToken(db.queryClient)
patchCanonicalCommunityMessage(db.queryClient, "m-local", (message) => ({
...message,
- reactions: [{ emoji: "👍", count: 2, me: true }],
+ reactions: [{ emoji: "👍", count: 2, me: true, userIds: ["peer", "viewer"] }],
}))
publishCommunityMessages(db.queryClient, {
channelId: "c1",
@@ -381,7 +505,7 @@ describe("community DB sync", () => {
})
expect(db.collections.messages.get("m-local")?.reactions).toEqual([
- { emoji: "👍", count: 2, me: true },
+ { emoji: "👍", count: 2, me: true, userIds: ["peer", "viewer"] },
])
})
@@ -1957,8 +2081,8 @@ describe("community DB sync", () => {
authorId: "u2",
authorName: "Alice",
content: "rich",
- attachments: [{ kind: "image", name: "proof.png", url: "/proof.png" }],
- replyTo: { id: "m0", authorId: "u3", authorName: "Bob", content: "earlier" },
+ attachments: [{ name: "proof.png", url: "/proof.png", contentType: "image/png" }],
+ replyTo: { id: "m0", authorId: "u3", authorName: "Bob", text: "earlier" },
}])
ingestAttentionSnapshot(db, {
@@ -1993,7 +2117,7 @@ describe("community DB sync", () => {
})
expect(db.collections.messages.get("m1")).toMatchObject({
content: "new preview",
- attachments: [{ kind: "image", name: "proof.png", url: "/proof.png" }],
+ attachments: [{ name: "proof.png", url: "/proof.png", contentType: "image/png" }],
replyTo: { id: "m0", authorId: "u3" },
})
})
@@ -2240,10 +2364,10 @@ describe("community DB sync", () => {
}],
})
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" },
+ { id: "scope-item", kind: "mention", sourceId: "source-1", scopeId: "c1", messageId: "message-1", actorUserId: "peer", createdAt: "now" },
+ { id: "child-item", kind: "forum_post", sourceId: "c1", scopeId: "forum", messageId: "opener-2", childChannelId: "c1", openerSeq: 2, readTarget: { channelId: "forum", seq: 2 }, createdAt: "now" },
+ { id: "target-item", kind: "forum_post", sourceId: "other-child", scopeId: "other-forum", messageId: "opener-3", childChannelId: "other-child", openerSeq: 3, readTarget: { channelId: "c1", seq: 3 }, createdAt: "now" },
+ { id: "dm-item", kind: "mention", sourceId: "source-4", scopeId: "dm1", messageId: "message-4", actorUserId: "peer", createdAt: "now" },
], limit: 100, truncated: false })
purgeCommunityServer(db, "s1")
expect(db.collections.servers.get("s1")).toBeUndefined()
@@ -2368,10 +2492,7 @@ describe("community DB sync", () => {
id: "thread1", name: "Thread", messageCount: 1,
participants: [{ id: "participant", name: "Participant", avatar: "P", avatarVersion: 1 }],
},
- approval: {
- status: "pending",
- otherProfile: { id: "approval", name: "Approval", discriminator: "0004", image: null, avatarVersion: 1 },
- },
+ approval: pendingApproval,
}])
ingestReadStateSnapshot(db, {
revision: 1,
@@ -2567,7 +2688,7 @@ describe("community DB sync", () => {
channelId: "c1",
serverId: "s1",
message: {
- id: "m1", seq: 1,
+ id: "m1", seq: 1, authorAvatarVersion: 0,
type: "chat",
authorId: "peer",
authorName: "Peer",
@@ -2640,23 +2761,8 @@ describe("community DB sync", () => {
} as CommunityWsEvent)
expect(db.collections.messages.get("m-attachment")?.attachments).toEqual([
- {
- kind: "image",
- name: "photo.png",
- url: "/photo.png",
- contentType: "image/png",
- sizeBytes: 2_048,
- width: undefined,
- height: 480,
- },
- {
- kind: "file",
- name: "notes.txt",
- url: "/notes.txt",
- contentType: undefined,
- sizeBytes: undefined,
- size: "",
- },
+ { id: "image", name: "photo.png", url: "/photo.png", contentType: "image/png", sizeBytes: 2048, width: null, height: 480, thumbnailUrl: undefined },
+ { id: "file", name: "notes.txt", url: "/notes.txt", contentType: undefined, sizeBytes: undefined, width: undefined, height: undefined, thumbnailUrl: undefined },
])
})
@@ -2697,7 +2803,7 @@ describe("community DB sync", () => {
channel: { id: "missing-parent", name: "Missing", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },
})
event({ type: "community:unread.bump", serverId: "s1", channelId: "c1", userId: "other", isMention: true })
- event({ type: "community:message.updated", channelId: "c1", messageId: "m1", approval: { status: "pending" } })
+ event({ type: "community:message.updated", channelId: "c1", messageId: "m1", approval: pendingApproval })
event({ type: "community:reaction.add", channelId: "c1", messageId: "m1", userId: "viewer", emoji: "👍" })
event({ type: "community:reaction.remove", channelId: "c1", messageId: "m1", userId: "peer", emoji: "👍" })
event({ type: "community:server.update", serverId: "s1", changes: { name: "Renamed" } })
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 4b86bd92d..04cd15bb5 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -11,12 +11,17 @@ import {
UNCATEGORIZED_CATEGORY_ID,
FORUM_ARCHIVE_TAG,
normalizeCommunityChannelIdentity,
+normalizeCommunityChannelResourcePreview,
+CommunityChannelResourceSchema,
+CommunityMessageResourceSchema,
+CommunityResourceProfileSchema,
type CommunityChannelIdentity,
type CommunityMemberRelation,
type CommunityResourceProfile,
type CommunityMessageResource,
type AccountAttentionSnapshot,
type CommunityWsEvent,
+type CommunityContract,
type ServerRailProjection,
} from "@alook/shared"
import type { DmsResponse } from "@/hooks/community/use-dms"
@@ -40,7 +45,8 @@ import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
import { avatarInitial } from "@/lib/community/avatar"
-import { projectCommunityMessageCreate, projectMessageRichContent } from "@/lib/community/message-wire"
+import { canonicalUserImage } from "@/lib/community/storage"
+import { projectCommunityMessageCreate } 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"
@@ -54,12 +60,11 @@ import {
channelMembershipKey,
canonicalChannelMembershipRow,
channelMembershipSchema,
-channelSchema,
+channelLocalSchema,
canonicalChannelRow,
folderItemKey,
messageSchema,
notificationSettingKey,
-profileSchema,
serverMembershipKey,
serverSchema,
communityCollectionSchemas,
@@ -425,7 +430,7 @@ function garbageCollectCommunityProfiles(registry: CommunityDbRegistry) {
deleteRows(
registry,
"profiles",
- (row) => !referenced.has(row.userId),
+ (row) => !referenced.has(row.id),
)
}
@@ -646,17 +651,23 @@ export function ingestServerDetail(
})
}
category.channels.forEach((channel, channelIndex) => {
+ const previous = registry.collections.channels.get(channel.id)
+ const complete = "resourceComplete" in channel && channel.resourceComplete === true
+ const resource = complete ? CommunityChannelResourceSchema.strip().parse(channel)
+ : normalizeCommunityChannelResourcePreview(channel)
+ if (resource.serverId !== undefined && resource.serverId !== detail.id) throw new Error("Channel resource scope mismatch")
channels.push(canonicalChannelRow({
+ ...resource,
id: channel.id,
serverId: detail.id,
categoryId: uncategorized ? null : category.id,
name: channel.name,
- type: channel.type ?? "text",
+ type: channel.type ?? previous?.type ?? "text",
parentChannelId: null,
parentMessageId: null,
creatorId: channel.creatorId,
- position: channelIndex,
- archived: false,
+ position: resource.position ?? channelIndex,
+ archived: resource.archived ?? previous?.archived ?? false,
muted: channel.muted === true,
unread: channel.unread,
...(channel.type === "forum" ? {
@@ -664,8 +675,8 @@ export function ingestServerDetail(
} : {}),
tags: channel.tags ?? [],
pending: channel.pending === true,
- lastMessageAt: null,
- }))
+ resourceComplete: complete,
+ }, previous))
})
})
const currentTopLevelIds = new Set(
@@ -757,9 +768,10 @@ function ingestChannelMetadata(
input: unknown,
proof?: CommunityFreshQueryProof,
) {
- const metadata = normalizeCommunityChannelIdentity(input)
- const hints = channelSchema.pick({ openerSeq: true, openerUnread: true }).parse(input)
- const changes = { ...metadata, ...hints, name: metadata.name ?? "", pending: false }
+ const full = typeof input === "object" && input !== null && "resourceComplete" in input && input.resourceComplete === true
+ const metadata = full ? CommunityChannelResourceSchema.strip().parse(input) : normalizeCommunityChannelIdentity(input)
+ const hints = channelLocalSchema.pick({ openerSeq: true, openerUnread: true }).parse(input)
+ const changes = { ...metadata, ...hints, ...(full ? { resourceComplete: true as const } : {}), pending: false }
const existing = registry.collections.channels.get(metadata.id)
if (proof && existing) {
publishConfirmedFields(registry.queryClient, "channels", metadata.id, changes, proof)
@@ -788,12 +800,12 @@ export function ingestDms(
id: dm.id, type: "dm", position,
unread: dm.unread === true, lastMessageAt: dm.activityAt ?? null, preview: dm.preview,
...(dm.lastUnreadSeq === undefined ? {} : { lastUnreadSeq: dm.lastUnreadSeq }),
- }))
+ }, registry.collections.channels.get(dm.id)))
memberships.push(
canonicalChannelMembershipRow(dm.id, viewerId, "access"),
canonicalChannelMembershipRow(dm.id, dm.userId, "access"),
)
- profilePatches.push(communityUserProfilePatch(dm.userId, dm))
+ profilePatches.push(communityUserProfilePatch(dm.userId, dm, { legacyPresentation: true }))
}
const dmIds = new Set(channels.map((row) => row.id))
const authoritativeDmIds = new Set([...currentDmIds, ...dmIds])
@@ -885,14 +897,41 @@ export function publishCommunityServerRailCommit(queryClient: QueryClient, proje
export function ingestMessages(
registry: CommunityDbRegistry,
channelId: string,
- messages: readonly (MessageInput | CommunityMessageResource)[],
+ messages: readonly MessageInput[],
) {
const previous = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))
+ for (const message of messages) {
+ if (message.id.startsWith("temp_") || message.failed === true) continue
+ if (message.channelId !== undefined && message.channelId !== channelId) throw new Error("Message channel mismatch")
+ if (message.resourceComplete === true) CommunityMessageResourceSchema.strip().parse(message)
+ }
+ const profileMessages: MessageInput[] = []
const rows: MessageRow[] = messages
.filter((message) => !message.id.startsWith("temp_") && !("failed" in message && message.failed === true))
.map((message) => {
- const { thread, clientNonce, ...fields } = message
+ const full = message.resourceComplete === true
+ const { thread: incomingThread, clientNonce, ...incoming } = message
+ const fields = Object.fromEntries(Object.entries(incoming).filter(([, value]) => value !== undefined))
+ if (message.resourceComplete !== true && message.authorAvatar === avatarInitial(message.authorName ?? "")) delete fields.authorAvatar
const existingMessage = previous.get(message.id)
+ if (!full && existingMessage?.resourceComplete === true) delete fields.attachments
+ let thread = incomingThread
+ if (!full && incomingThread && existingMessage?.resourceComplete === true) {
+ const known = existingMessage.thread?.id === incomingThread.id ? existingMessage.thread : undefined
+ const fields = Object.fromEntries(Object.entries(incomingThread).filter(([, value]) => value !== undefined))
+ const participants = incomingThread.participants?.map((participant) => ({
+ ...known?.participants?.find((row) => row.id === participant.id),
+ ...Object.fromEntries(Object.entries(participant).filter(([, value]) => value !== undefined)),
+ }))
+ const merged = { ...known, ...fields, ...(participants ? { participants } : {}) }
+ const parsed = CommunityMessageResourceSchema.shape.thread.safeParse(merged)
+ if (parsed.success) thread = parsed.data
+ else {
+ const { participants: _participants, ...withoutUnknownParticipants } = fields
+ const partial = CommunityMessageResourceSchema.shape.thread.safeParse({ ...known, ...withoutUnknownParticipants })
+ thread = partial.success ? partial.data : known
+ }
+ }
const retainReply = existingMessage?.channelId === channelId
&& (!message.authorId || message.authorId === existingMessage.authorId)
&& (clientNonce === undefined || clientNonce === existingMessage.clientNonce)
@@ -905,17 +944,24 @@ export function ingestMessages(
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.lastReplyAt !== undefined ? { 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 } : {}),
+ profileMessages.push({ ...fields, id: message.id, type: message.type, ...(incomingThread ? { thread: incomingThread } : {}) })
+ const merged = { ...existingMessage, ...fields,
+ ...(thread ? { thread } : {}),
+ replyTo: retainReply ? existingMessage!.replyTo : message.replyTo,
+ replyToId: retainReply ? existingMessage!.replyToId : "replyToId" in message ? message.replyToId : message.replyTo?.id ?? (retainReply ? existingMessage?.replyToId : null),
+ type: message.type ?? existingMessage?.type ?? "chat", channelId,
+ ...(clientNonce !== undefined ? { clientNonce } : {}),
+ resourceComplete: full || existingMessage?.resourceComplete === true,
}
+ return messageSchema.parse(merged)
})
upsertRows(registry, "messages", rows)
- writeCanonicalProfilePatches(registry, messageProfilePatches(messages))
+ writeCanonicalProfilePatches(registry, messageProfilePatches(profileMessages))
}
export function ingestReadStateSnapshot(
@@ -980,7 +1026,7 @@ function ingestAttentionIncluded(
lastMessageAt: dm.lastMessageAt,
preview: existing?.preview ?? "",
lastUnreadSeq: dm.lastUnreadSeq,
- })
+ }, existing)
})
upsertRows(registry, "channels", dmChannels)
if (viewerId) {
@@ -994,23 +1040,17 @@ function ingestAttentionIncluded(
],
)
}
- const profiles = profileSchema.array().safeParse(included?.profiles ?? [])
+ const profiles = CommunityResourceProfileSchema.array().safeParse((included?.profiles ?? []).map(({ userId, ...profile }) => ({
+ ...profile, id: userId, discriminator: profile.discriminator || null, avatar: canonicalUserImage(userId, profile.avatar, profile.avatarVersion),
+ })))
if (profiles.success) {
writeCanonicalProfilePatches(registry, profiles.data.map((profile) => (
- communityUserProfilePatch(profile.userId, profile)
+ communityUserProfilePatch(profile.id, profile, { legacyPresentation: true })
)))
}
- const messages = messageSchema.array().safeParse(included?.messages ?? [])
- if (messages.success) {
- const current = new Map(
- 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", merged)
- }
+ const byChannel = new Map<string, MessageInput[]>()
+ for (const message of included?.messages ?? []) byChannel.set(message.channelId, [...(byChannel.get(message.channelId) ?? []), { ...message, resourceComplete: false }])
+ for (const [channelId, messages] of byChannel) ingestMessages(registry, channelId, messages)
}
type AttentionDomain = "channels" | "dms" | "mentions"
@@ -1540,14 +1580,14 @@ function withCommunityQueryProof<T>(queryClient: QueryClient, proof: CommunityFr
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 })
+function ingestResourceProfiles(registry: CommunityDbRegistry, profiles: readonly (Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">>)[], proof: CommunityFreshQueryProof, options?: { legacyPresentation: boolean }) {
+ writeCommunityProfilePatches(profiles.map((profile) => communityUserProfilePatch(profile.id, profile, options)), 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[] = []) {
+export function publishCommunityChannelMembersSnapshot(queryClient: QueryClient, serverId: string | null, channelId: string, relation: CommunityMemberRelation["relation"], members: readonly CommunityMemberRelation[], proof: CommunityFreshQueryProof, profiles: readonly CommunityResourceProfile[] = [], options?: { legacyPresentation: boolean }) {
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)
+ ingestResourceProfiles(registry, profiles, proof, options)
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)
})
}
@@ -1688,7 +1728,7 @@ export function publishCommunityMessages(
queryClient: QueryClient,
publication: {
channelId: string
- messages: Msg[]
+ messages: MessageInput[]
proof: CommunityFreshQueryProof
},
) {
@@ -1739,7 +1779,7 @@ function qualifyCanonicalChannelMetadata(registry: CommunityDbRegistry, channelI
export function publishCommunityChannelMetadata(
queryClient: QueryClient,
publication: {
- metadata: CommunityChannelIdentity
+ metadata: CommunityChannelIdentity & { resourceComplete?: boolean }
proof: CommunityFreshQueryProof
},
) {
@@ -2024,16 +2064,15 @@ export function publishCommunityForumFeed(queryClient: QueryClient, forumChannel
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,
+ pending: false,
tags: page.included.tags.filter((tag) => tag.messageId === thread.parentMessageId).map((tag) => tag.tag),
- 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 })))
+ upsertRows(registry, "channelMemberships", page.included.members.map((member) => channelMembershipSchema.parse({ ...member, id: channelMembershipKey(member.channelId, member.userId, member.relation) })))
}))
}
@@ -2137,7 +2176,8 @@ function publishCreatedTreeRow<N extends "channels" | "categories">(
}
}
-export function publishCommunityCreatedChannel(queryClient: QueryClient, row: ChannelRow, proof: CommunityFreshQueryProof) {
+export function publishCommunityCreatedChannel(queryClient: QueryClient, input: Parameters<typeof canonicalChannelRow>[0], proof: CommunityFreshQueryProof) {
+ const row = canonicalChannelRow(input, proof.token.registry!.collections.channels.get(input.id))
publishCreatedTreeRow(queryClient, "channels", row, proof)
const registry = proof.token.registry!
if (!registry.accountId || !collectionRows(registry, "channels").some((current) => current.id === row.id)) return
@@ -2424,6 +2464,7 @@ function projectProfilePatch(
export function projectCommunityWsEventToDb(
queryClient: QueryClient,
event: CommunityWsEvent,
+ contract: CommunityContract = 2,
) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry) return
@@ -2458,7 +2499,7 @@ export function projectCommunityWsEventToDb(
return
}
case "community:message.create": {
- const projected = projectCommunityMessageCreate(event.message, event.channelId)
+ const projected = projectCommunityMessageCreate(event.message, event.channelId, contract)
ingestMessages(registry, event.channelId, [projected])
if (event.message.createdAt) {
patchRows(
@@ -2503,11 +2544,14 @@ export function projectCommunityWsEventToDb(
)
return
case "community:channel.child_create": {
- if (!event.parentMessageId) return
+ const full = contract === 3 ? CommunityChannelResourceSchema.parse(event.channel) : null
+ if (!full && !event.parentMessageId) return
const parent = collectionRows(registry, "channels")
.find((row) => row.id === event.parentChannelId)
if (!parent?.serverId) return
- upsertRows(registry, "channels", [canonicalChannelRow({
+ if (full && full.serverId !== parent.serverId) throw new Error("Child channel server mismatch")
+ const existing = collectionRows(registry, "channels").find((row) => row.id === event.channel.id)
+ upsertRows(registry, "channels", [canonicalChannelRow(full ? { ...full, resourceComplete: true } : {
id: event.channel.id,
serverId: parent.serverId,
name: event.channel.name,
@@ -2515,8 +2559,8 @@ export function projectCommunityWsEventToDb(
parentChannelId: event.parentChannelId,
parentMessageId: event.parentMessageId,
creatorId: event.channel.creatorId ?? null,
- lastMessageAt: event.channel.createdAt,
- })])
+ createdAt: event.channel.createdAt,
+ }, existing)])
if (registry.accountId) {
upsertRows(
registry,
@@ -2553,17 +2597,20 @@ export function projectCommunityWsEventToDb(
Object.keys(event.changes),
)
return
- case "community:channel.create":
- upsertRows(registry, "channels", [canonicalChannelRow({
+ case "community:channel.create": {
+ const existing = collectionRows(registry, "channels").find((row) => row.id === event.channel.id)
+ const full = contract === 3 ? CommunityChannelResourceSchema.parse(event.channel) : null
+ upsertRows(registry, "channels", [canonicalChannelRow(full ? { ...full, resourceComplete: true } : {
id: event.channel.id,
serverId: event.serverId,
categoryId: event.channel.categoryId ?? null,
name: event.channel.name,
type: event.channel.type,
position: event.channel.position,
- lastMessageAt: event.channel.createdAt,
- })])
+ createdAt: event.channel.createdAt,
+ }, existing)])
return
+ }
case "community:channel.update":
patchRows(
registry,
@@ -2651,7 +2698,7 @@ export function projectCommunityWsEventToDb(
writeCommunityProfilePatches([communityUserProfilePatch(event.member.userId, {
name: event.member.name,
discriminator: event.member.discriminator,
- avatar: event.member.avatar ?? "",
+ ...(event.member.avatar === undefined ? {} : { avatar: canonicalUserImage(event.member.userId, event.member.avatar, event.member.avatarVersion) }),
avatarVersion: event.member.avatarVersion,
})], registry, { event: true })
return
diff --git a/src/web/src/lib/community-db/write.test.ts b/src/web/src/lib/community-db/write.test.ts
index 4b7b3ff7d..5c222eb14 100644
--- a/src/web/src/lib/community-db/write.test.ts
+++ b/src/web/src/lib/community-db/write.test.ts
@@ -27,8 +27,8 @@ describe("canonical collection publication", () => {
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" }]
+ authorAvatar: "peer-avatar", authorAvatarVersion: 0, content: "before", createdAt: "2026-08-07T10:00:00.000Z" }
+ const attachments = [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024 }]
const embeds = [{ title: "Reference" }]
ingestMessages(registry, "channel", [{ ...message, attachments, embeds }])
const summaryFacts = { type: "system" as const, clientNonce: "known-nonce", replyToId: "reply" }
@@ -107,12 +107,12 @@ describe("canonical collection publication", () => {
writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alicia" } }], registry)
expect(upsert).toHaveBeenCalledOnce()
- expect(upsert.mock.calls[0]?.[0]).toMatchObject([{ userId: "alice", name: "Alicia" }])
+ expect(upsert.mock.calls[0]?.[0]).toMatchObject([{ id: "alice", name: "Alicia" }])
expect(publish).toHaveBeenCalledOnce()
expect(registry.collections.profiles.get("bob")).toBe(bob)
expect(registry.queryClient.getQueryData(
communityKeys.communityDbCollection("viewer", "profiles"),
- )).toMatchObject([{ userId: "alice", name: "Alicia" }, { userId: "bob", name: "Bob" }])
+ )).toMatchObject([{ id: "alice", name: "Alicia" }, { id: "bob", name: "Bob" }])
})
it("keeps equal rows silent and synchronizes deleting the final row", async () => {
@@ -122,10 +122,10 @@ describe("canonical collection publication", () => {
const current = Array.from(registry.collections.profiles.values())
const publish = vi.spyOn(registry.queryClient, "setQueryData")
- writeCommunityCollectionRows(registry, "profiles", current.map((row) => ({ ...row })), (row) => row.userId)
+ writeCommunityCollectionRows(registry, "profiles", current.map((row) => ({ ...row })), (row) => row.id)
expect(publish).not.toHaveBeenCalled()
- writeCommunityCollectionRows(registry, "profiles", [], (row) => row.userId)
+ writeCommunityCollectionRows(registry, "profiles", [], (row) => row.id)
expect(publish).toHaveBeenCalledOnce()
expect(registry.collections.profiles.size).toBe(0)
expect(registry.queryClient.getQueryData(
@@ -143,23 +143,23 @@ describe("canonical collection publication", () => {
transaction.mutate(() => registry.collections.profiles.update("alice", (row) => { row.name = "Alicia" }))
await transaction.when("settled")
expect(registry.collections.profiles.get("alice")?.name).toBe("Alicia")
- expect(registry.queryClient.getQueryData(communityKeys.communityDbCollection("viewer", "profiles"))).toMatchObject([{ userId: "alice", name: "Alicia" }])
+ expect(registry.queryClient.getQueryData(communityKeys.communityDbCollection("viewer", "profiles"))).toMatchObject([{ id: "alice", name: "Alicia" }])
})
it("seeds a not-ready collection through the restore snapshot and then synchronizes", async () => {
const registry = owner()
- const row = profileSchema.parse({
- userId: "alice", name: "Alice", discriminator: "0001", avatar: "A", avatarVersion: 1,
+ const row = profileSchema.parse({ identityComplete: false,
+ id: "alice", name: "Alice", discriminator: "0001", avatar: "A", avatarVersion: 1,
})
expect(registry.collections.profiles.status).not.toBe("ready")
- writeCommunityCollectionRows(registry, "profiles", [row], (profile) => profile.userId)
+ writeCommunityCollectionRows(registry, "profiles", [row], (profile) => profile.id)
expect(registry.queryClient.getQueryData(
communityKeys.communityDbCollection("viewer", "profiles"),
)).toEqual([row])
await registry.preload()
expect(registry.collections.profiles.get("alice")).toMatchObject(row)
- writeCommunityCollectionRows(registry, "profiles", [{ ...row, name: "Alicia" }], (profile) => profile.userId)
+ writeCommunityCollectionRows(registry, "profiles", [{ ...row, name: "Alicia" }], (profile) => profile.id)
expect(registry.collections.profiles.get("alice")?.name).toBe("Alicia")
})
})
diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.ts
index 1bcf7eed6..485e9173e 100644
--- a/src/web/src/lib/community/attachment-presentation.ts
+++ b/src/web/src/lib/community/attachment-presentation.ts
@@ -1,4 +1,4 @@
-import type { CommunityMessageAttachment } from "@alook/shared"
+import type { CommunityMessagePreviewAttachment, CommunityLegacyMessageAttachment } from "@alook/shared"
import type { Attachment } from "./models/message"
import { isInlineAttachmentContentType } from "./attachment-content-type"
@@ -280,11 +280,20 @@ export function formatAttachmentSize(bytes?: number): string {
}
export function presentMessageAttachment(
- attachment: Omit<CommunityMessageAttachment, "kind"> & Partial<Pick<CommunityMessageAttachment, "kind">>,
+ attachment: CommunityMessagePreviewAttachment | CommunityLegacyMessageAttachment,
): 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) }
+ const legacy = "kind" in attachment ? attachment : undefined
+ const kind = legacy?.kind ?? (isInlineAttachmentContentType(attachment.contentType) ? "image" : "file")
+ const metadata = {
+ name: attachment.name, url: attachment.url,
+ ...(attachment.contentType != null ? { contentType: attachment.contentType } : {}),
+ ...(attachment.sizeBytes != null ? { sizeBytes: attachment.sizeBytes } : {}),
+ }
+ if (kind === "image") return {
+ ...metadata, kind,
+ ...(attachment.thumbnailUrl != null ? { thumbnailUrl: attachment.thumbnailUrl } : {}),
+ ...(attachment.width != null ? { width: attachment.width } : {}),
+ ...(attachment.height != null ? { height: attachment.height } : {}),
+ }
+ return { ...metadata, kind, size: legacy?.size ?? formatAttachmentSize(attachment.sizeBytes ?? undefined) }
}
diff --git a/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx b/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx
index d6715e07c..a20c8745e 100644
--- a/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx
+++ b/src/web/src/lib/community/conversation-navigation-warmup-owner.dom.test.tsx
@@ -76,7 +76,7 @@ describe("warmup original owner and complete intent resources", () => {
await owner.registry.preload()
const serverId = kind === "dm" ? null : "s1"
if (serverId) owner.client.setQueryData(communityKeys.server(serverId), serverId)
- const metadata = { id: "d1", serverId, type: kind, name: kind === "dm" ? null : "Thread",
+ const metadata = { categoryId: null, topic: "", position: 0, messageCount: 0, id: "d1", serverId, type: kind, name: kind === "dm" ? null : "Thread",
parentChannelId: kind === "dm" ? null : "parent", parentMessageId: kind === "dm" ? null : "opener",
creatorId: null, archived: false, lastMessageAt: null, createdAt: "2026-10-02T00:00:00Z" }
const json = (value: unknown) => new Response(JSON.stringify(value), { status: 200, headers: { "Content-Type": "application/json" } })
diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.ts
index fb4f07828..49e319884 100644
--- a/src/web/src/lib/community/create-channels.test.ts
+++ b/src/web/src/lib/community/create-channels.test.ts
@@ -1,5 +1,8 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
+const producerEnv = vi.hoisted(() => ({ COMMUNITY_EVENT_CONTRACT: "1" }))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: () => ({ env: producerEnv, ctx: {} }) }))
+
const mockCreateCommunityMessage = vi.fn()
const mockCreateChannel = vi.fn()
const mockGetThreadChannelByParentMessage = vi.fn()
@@ -11,19 +14,23 @@ const mockDeleteChannel = vi.fn()
const mockListMessageAttachments = vi.fn()
const mockGetMessage = vi.fn()
const mockRequireChannelMember = vi.fn()
+const mockRequireServerMember = vi.fn()
+const mockGetCategory = vi.fn()
+const mockCreateChannelMember = vi.fn()
+const mockFanOutToServerMembers = vi.fn()
vi.mock("@/lib/community/message-handler", () => ({
createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),
}))
vi.mock("@/lib/community/fanout", () => ({
- fanOutToServerMembers: vi.fn(),
+ fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
vi.mock("@/lib/community/permissions", () => ({
- requireServerMember: vi.fn(),
+ requireServerMember: (...a: unknown[]) => mockRequireServerMember(...a),
requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),
}))
@@ -38,7 +45,9 @@ vi.mock("@alook/shared", async () => {
createChannel: (...a: unknown[]) => mockCreateChannel(...a),
getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),
deleteChannel: (...a: unknown[]) => mockDeleteChannel(...a),
+ createChannelMember: (...a: unknown[]) => mockCreateChannelMember(...a),
},
+ communityCategory: { ...actual.queries.communityCategory, getCategory: (...a: unknown[]) => mockGetCategory(...a) },
communityMessage: {
...actual.queries.communityMessage,
getMessage: (...a: unknown[]) => mockGetMessage(...a),
@@ -56,7 +65,36 @@ vi.mock("@alook/shared", async () => {
}
})
-import { createMessageWithThread, createThreadForUser } from "./create-channels"
+import { createMessageWithThread, createThreadForUser, createServerChannelForUser } from "./create-channels"
+
+describe("createServerChannelForUser producer contracts", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ producerEnv.COMMUNITY_EVENT_CONTRACT = "1"
+ mockRequireServerMember.mockResolvedValue({ ok: true, value: { role: "owner" } })
+ })
+ it.each([["1", false], ["1", true], ["3", false], ["3", true]] as const)("fans out contract %s only to the private=%s audience", async (contract, privateCategory) => {
+ producerEnv.COMMUNITY_EVENT_CONTRACT = contract
+ const row = { id: "channel", type: "text", serverId: "server", name: "channel", categoryId: "category", topic: "Topic",
+ parentChannelId: null, parentMessageId: null, creatorId: "viewer", position: 4, archived: 0, createdAt: "now", lastMessageAt: null, messageCount: 0 }
+ mockGetCategory.mockResolvedValue({ id: "category", serverId: "server", private: privateCategory })
+ mockCreateChannel.mockResolvedValue(row)
+ const result = await createServerChannelForUser({} as never, { serverId: "server", actorUserId: "viewer", name: "channel", type: "text", categoryId: "category", topic: "Topic" })
+ const legacyChannel = { id: "channel", name: "channel", type: "text", categoryId: "category", topic: "Topic", position: 4, createdAt: "now" }
+ expect(result).toEqual({ ok: true, value: legacyChannel })
+ const event = { type: "community:channel.create", serverId: "server", channel: contract === "3" ? { ...row, archived: false } : legacyChannel }
+ if (privateCategory) {
+ expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), { channelId: "channel", userId: "viewer", addedBy: "viewer" })
+ expect(mockFanOutToChannel).toHaveBeenCalledExactlyOnceWith("channel", event)
+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
+ } else {
+ expect(mockFanOutToServerMembers).toHaveBeenCalledExactlyOnceWith("server", event)
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ expect(mockCreateChannelMember).not.toHaveBeenCalled()
+ }
+ producerEnv.COMMUNITY_EVENT_CONTRACT = "1"
+ })
+})
describe("createThreadForUser", () => {
beforeEach(() => {
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index 95ac32f5c..52d6958aa 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -8,6 +8,8 @@ import {
WS_EVENTS,
slugify,
PARTICIPANT_SOURCE,
+ CommunityResourceWsEventSchema,
+ communityChannelResourceFromStorage,
type ChannelType,
type StoredChannelType,
type Database,
@@ -19,6 +21,8 @@ import { requireMessageBearingSurface } from "@/lib/community/channel-write-guar
import { guardDmOpen } from "@/lib/community/dm-guard"
import { createCommunityMessage, type IncomingMessageBody } from "@/lib/community/message-handler"
import { nanoid } from "nanoid"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { communityProducerContract } from "./producer-contract"
/**
* Single-source creation cores for the `POST /channels` create door (route/disc
@@ -134,18 +138,18 @@ export async function createServerChannelForUser(
createdAt: row.createdAt,
}
- if (isPrivateCategory) {
- await fanOutToChannel(row.id, {
+ const contract = communityProducerContract(getCloudflareContext().env as Env)
+ const event = contract === 3
+ ? CommunityResourceWsEventSchema.parse({ type: WS_EVENTS.CHANNEL_CREATE, serverId, channel: communityChannelResourceFromStorage(row) })
+ : {
type: WS_EVENTS.CHANNEL_CREATE,
serverId,
channel,
- })
+ }
+ if (isPrivateCategory) {
+ await fanOutToChannel(row.id, event)
} else {
- await fanOutToServerMembers(serverId, {
- type: WS_EVENTS.CHANNEL_CREATE,
- serverId,
- channel,
- })
+ await fanOutToServerMembers(serverId, event)
}
@@ -266,10 +270,11 @@ export async function createThreadForUser(
if (!threadResult.ok) return { ok: false, status: 404, error: "thread not found" }
const childChannel = threadResult.value
if (createdByThisAttempt) {
- void fanOutToChannel(message.channelId, {
+ const contract = communityProducerContract(getCloudflareContext().env as Env)
+ const event = {
type: WS_EVENTS.CHILD_CHANNEL_CREATE,
parentChannelId: message.channelId,
- channel: {
+ channel: contract === 3 ? communityChannelResourceFromStorage(childChannel) : {
id: childChannel.id,
name: childChannel.name,
type: "thread" as const,
@@ -277,6 +282,9 @@ export async function createThreadForUser(
createdAt: childChannel.createdAt,
},
parentMessageId: messageId,
+ }
+ void fanOutToChannel(message.channelId, contract === 3 ? CommunityResourceWsEventSchema.parse(event) : {
+ ...event, channel: { id: childChannel.id, name: childChannel.name, type: "thread", creatorId: actorUserId, createdAt: childChannel.createdAt },
})
}
diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.ts
index dd82d8f1f..b74ecb260 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -58,7 +58,7 @@ const serverRows = [{
mentions: 0,
}]
const channelRows = [
- {
+ { topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "channel_1",
serverId: "server_1",
categoryId: null,
@@ -75,7 +75,7 @@ const channelRows = [
pending: false,
lastMessageAt: null,
},
- {
+ { topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "thread_1",
serverId: "server_1",
categoryId: null,
@@ -178,7 +178,7 @@ describe("desktop system notification candidates", () => {
it("resolves a cold channel name before formatting the desktop copy", async () => {
const queryClient = await createClient()
seedCanonicalDirectory(queryClient, { channels: false })
- channelMetadataMocks.fetch.mockResolvedValue({
+ channelMetadataMocks.fetch.mockResolvedValue({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "channel_1",
serverId: "server_1",
name: "general",
@@ -204,7 +204,7 @@ describe("desktop system notification candidates", () => {
it("uses the default empty snapshot while resolving cold channel metadata", async () => {
const queryClient = await createClient()
- channelMetadataMocks.fetch.mockResolvedValue({
+ channelMetadataMocks.fetch.mockResolvedValue({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "channel_1",
serverId: "server_1",
name: "general",
@@ -232,7 +232,7 @@ describe("desktop system notification candidates", () => {
it("resolves cold thread and parent channel names before formatting the desktop copy", async () => {
const queryClient = await createClient()
seedCanonicalDirectory(queryClient, { channels: false })
- channelMetadataMocks.fetch.mockResolvedValueOnce({
+ channelMetadataMocks.fetch.mockResolvedValueOnce({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "thread_1",
serverId: "server_1",
name: "Release notes",
@@ -243,7 +243,7 @@ describe("desktop system notification candidates", () => {
archived: false,
lastMessageAt: null,
createdAt: "2026-09-12T00:00:00.000Z",
- }).mockResolvedValueOnce({
+ }).mockResolvedValueOnce({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "channel_1",
serverId: "server_1",
name: "general",
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
index 5b09deca1..911c97d1d 100644
--- a/src/web/src/lib/community/enrich-messages.test.ts
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -248,4 +248,15 @@ describe("enrichMessages attachment projection", () => {
},
})
})
+ it("keeps actual NULL thread facts in contract 3 and rejects unknown participant identity", async () => {
+ mocks.listAttachments.mockResolvedValue([])
+ mocks.listForumChildren.mockResolvedValue([{ id: "thread", parentMessageId: "m1", name: null, messageCount: 0, lastMessageAt: null, createdAt: "now" }])
+ mocks.listParticipants.mockResolvedValue([{ channelId: "thread", userId: "peer", userName: "Peer", userImage: null, userAvatarVersion: 4, participantCount: 1 }])
+ const row = { id: "m1", channelId: "forum", seq: 1, authorId: "author", authorName: "Author", authorImage: null, authorAvatarVersion: 2, content: "body", type: "default", mentionType: null, replyToId: null, embeds: null, createdAt: "now" }
+ const result = await enrichMessages({} as never, "viewer", { channelId: "forum", isForum: true, contract: 3 }, [row])
+ expect(result.messages[0]).toMatchObject({ authorAvatar: null, thread: { name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] } })
+ mocks.listParticipants.mockResolvedValue([{ channelId: "thread", userId: "peer", userName: null, userImage: null, userAvatarVersion: 4 }])
+ await expect(enrichMessages({} as never, "viewer", { channelId: "forum", isForum: true, contract: 3 }, [row])).rejects.toThrow()
+ })
+
})
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index 5a2e6726e..c5823814f 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -1,4 +1,4 @@
-import { queries, withD1Retry, type CommunityMessageResource } from "@alook/shared"
+import { queries, withD1Retry, CommunityChannelResourceSchema, CommunityMessageThreadParticipantSchema, type CommunityMessageResource, type CommunityContract } from "@alook/shared"
import type { getDb } from "@/lib/db"
import { loadApiMessageContext, mapMessageForApi } from "@/lib/community/message-payload"
import { avatarInitial } from "@/lib/community/avatar"
@@ -16,7 +16,7 @@ import { canonicalUserImage } from "@/lib/community/storage"
type Db = ReturnType<typeof getDb>
-export type MessageScope = { channelId: string; isDm?: boolean; isForum?: boolean }
+export type MessageScope = { channelId: string; isDm?: boolean; isForum?: boolean; contract?: CommunityContract }
export async function enrichMessages(
db: Db,
@@ -75,9 +75,9 @@ export async function enrichMessages(
...(participantsByChannel.get(row.channelId) ?? []),
{
id: row.userId,
- name: row.userName ?? "",
- avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)
- ?? avatarInitial(row.userName ?? ""),
+ name: scope.contract === 3 ? CommunityMessageThreadParticipantSchema.shape.name.parse(row.userName) : row.userName ?? "",
+ avatar: scope.contract === 3 ? canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)
+ : canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion) ?? avatarInitial(row.userName ?? ""),
avatarVersion: row.userAvatarVersion,
},
])
@@ -91,8 +91,8 @@ export async function enrichMessages(
return [c.parentMessageId!, {
id: c.id,
name: c.name,
- messageCount: c.messageCount ?? 0,
- lastReplyAt: c.lastMessageAt ?? c.createdAt,
+ messageCount: scope.contract === 3 ? CommunityChannelResourceSchema.shape.messageCount.parse(c.messageCount) : c.messageCount ?? 0,
+ lastReplyAt: scope.contract === 3 ? c.lastMessageAt : c.lastMessageAt ?? c.createdAt,
...(scope.isForum ? {
tags: tagsByMessage.get(c.parentMessageId!) ?? [],
preview: (first?.content ?? "").slice(0, 100),
@@ -108,7 +108,7 @@ export async function enrichMessages(
...context,
threadByMessageId,
approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,
- }),
+ }, scope.contract, scope.channelId),
)
return { messages, latestSeq }
}
diff --git a/src/web/src/lib/community/forum-sidebar.ts b/src/web/src/lib/community/forum-sidebar.ts
index b70f88e1c..dddce7779 100644
--- a/src/web/src/lib/community/forum-sidebar.ts
+++ b/src/web/src/lib/community/forum-sidebar.ts
@@ -36,7 +36,7 @@ export function forumSidebarCandidates(
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 }]
+ title: messageById.get(channel.parentMessageId)?.content ?? channel.name ?? "", activityAt, expiresAt, unread: channel.unread }]
}).sort(compareForumSidebarThreads)
}
diff --git a/src/web/src/lib/community/member-read.ts b/src/web/src/lib/community/member-read.ts
index 83c6fdb0b..077a3f720 100644
--- a/src/web/src/lib/community/member-read.ts
+++ b/src/web/src/lib/community/member-read.ts
@@ -1,11 +1,11 @@
-import { COMMUNITY_CONTRACT_VERSION, CommunityMembersReadSchema, queries, type Database } from "@alook/shared"
+import { CommunityResourceProfileSchema, communityReadSchemas, 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) {
+export async function readCommunityMembers(db: Database, channelId: string, userId: string, relation: string | null, contract: 2 | 3 = 2) {
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)
@@ -23,12 +23,14 @@ export async function readCommunityMembers(db: Database, channelId: string, user
? 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,
+ const profiles = users.map((row) => resourceProfile({ id: row.id, name: contract === 3 ? CommunityResourceProfileSchema.shape.name.parse(row.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 ?? "" }))
+ ...(memberByUser.has(row.id) ? {
+ statusEmoji: memberByUser.get(row.id)!.statusEmoji, 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,
+ return writeCommunityContractJSON(communityReadSchemas(contract).members.parse({ contractVersion: contract, 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 }))
+ role: memberByUser.get(row.userId)?.role ?? null, memberId: memberByUser.get(row.userId)?.id ?? null })), profiles: contract === 2 ? profiles.map((profile) => ({ id: profile.id, name: profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "" })) : profiles }), contract)
}
diff --git a/src/web/src/lib/community/message-delivery-transport.ts b/src/web/src/lib/community/message-delivery-transport.ts
index 19cb153cc..51f1f5938 100644
--- a/src/web/src/lib/community/message-delivery-transport.ts
+++ b/src/web/src/lib/community/message-delivery-transport.ts
@@ -35,6 +35,7 @@ function selectTargets(batch: MessageDeliveryBatch, selected: ReadonlySet<string
const keep = (ids: readonly string[]) => ids.filter((id) => selected.has(id))
const parentProjectionUserIds = keep(batch.parentProjectionUserIds ?? [])
return {
+ ...(batch.communityContract === 3 ? { communityContract: 3 as const } : {}),
messageId: batch.messageId,
messageEvent: batch.messageEvent,
contentUserIds: keep(batch.contentUserIds),
diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.ts
index d1bf1a673..6c71d65b8 100644
--- a/src/web/src/lib/community/message-dispatcher.test.ts
+++ b/src/web/src/lib/community/message-dispatcher.test.ts
@@ -80,6 +80,7 @@ const message = {
authorName: "Author",
authorEmail: "[email protected]",
authorImage: null,
+ authorAvatarVersion: 0,
content: "hello",
type: "default",
mentionType: null,
diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.ts
index 901e221e4..3ede6ad41 100644
--- a/src/web/src/lib/community/message-dispatcher.ts
+++ b/src/web/src/lib/community/message-dispatcher.ts
@@ -1,21 +1,24 @@
import { getCloudflareContext } from "@opennextjs/cloudflare"
import {
deriveCommunityDeliveryOperationId,
+ decodeCommunityBrowserEvent,
reachIsParticipantSet,
WS_EVENTS,
createLogger,
queries,
withD1Retry,
- type CommunityMessageCreate,
type CommunityDeliveryOperationId,
type Database,
type MessageDeliveryBatch,
+ type CommunityContract,
type AlookQueueTask,
} from "@alook/shared"
import { mapMessageForWs, type MessageRow } from "./message-payload"
import { sendMessageDeliveryBatch } from "./message-delivery-transport"
import { enqueueQueueTasks } from "./queue-producer"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
+import { communityProducerContract } from "./producer-contract"
+import { groupAttachments } from "./messages"
const log = createLogger({ service: "committed-message-dispatcher" })
@@ -57,6 +60,7 @@ export async function planCommittedMessage(
db: Database,
messageId: string,
structural: CommittedMessageStructuralOutcome = {},
+ contract: CommunityContract = 2,
): Promise<MessageDeliveryPlan> {
const message = await withD1Retry(
() => queries.communityMessage.getMessage(db, messageId),
@@ -178,7 +182,7 @@ export async function planCommittedMessage(
content: replyTarget.content,
})
}
- const messageEvent: CommunityMessageCreate = {
+ const messageInput = {
type: WS_EVENTS.MESSAGE_CREATE,
channelId: message.channelId,
...(channel.serverId ? { serverId: channel.serverId } : {}),
@@ -186,6 +190,7 @@ export async function planCommittedMessage(
message: mapMessageForWs(message, {
replyMap,
clientNonce: clientNonce ?? undefined,
+ ...(contract === 3 ? { resourceAttachments: groupAttachments(attachments)[message.id] ?? [] } : {}),
attachments: attachments.map((attachment) => ({
id: attachment.id,
filename: attachment.filename,
@@ -198,8 +203,11 @@ export async function planCommittedMessage(
width: attachment.width ?? undefined,
height: attachment.height ?? undefined,
})),
- }),
+ }, contract, message.channelId),
}
+ const messageResult = decodeCommunityBrowserEvent(messageInput, contract)
+ if (!messageResult.ok || messageResult.event.type !== WS_EVENTS.MESSAGE_CREATE) throw new Error("Invalid committed message event")
+ const messageEvent = messageResult.event
const includeParent = Boolean(channel.parentChannelId && !structural.suppressParentProjection)
const parentProjectionUserIds = includeParent
@@ -212,7 +220,7 @@ export async function planCommittedMessage(
channelId: channel.id,
changes: {
messageCount: channel.messageCount,
- lastMessageAt: channel.lastMessageAt ?? message.createdAt,
+ lastMessageAt: contract === 3 ? channel.lastMessageAt : channel.lastMessageAt ?? message.createdAt,
},
} as const
: undefined
@@ -227,6 +235,7 @@ export async function planCommittedMessage(
}
return {
+ ...(contract === 3 ? { communityContract: 3 as const } : {}),
operationId: await deriveCommunityDeliveryOperationId(message.id),
messageId: message.id,
messageEvent,
@@ -258,10 +267,13 @@ async function runCommittedMessageDispatch(
structural: CommittedMessageStructuralOutcome,
): Promise<void> {
const startedAt = Date.now()
+ const { env } = getCloudflareContext()
+ const contract = communityProducerContract(env as Env)
const plan = await planCommittedMessage(
db,
messageId,
structural,
+ contract,
)
const { operationId, wakeBotUserIds, pushUserIds, ...browserBatch } = plan
const pushTasks: AlookQueueTask[] = pushUserIds.map((userId) => ({
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 3fb35c5b2..6ab1fbadb 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: () => ({ env: {} }) }))
+
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
const mockGetMessageByAuthorAndNonce = vi.fn()
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 652b44f12..8b3687c80 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -11,6 +11,8 @@ import {
withD1Retry,
reachIsParticipantSet,
WS_EVENTS,
+ CommunityResourceWsEventSchema,
+ communityChannelResourceFromStorage,
} from "@alook/shared"
import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
@@ -18,6 +20,8 @@ import { nanoid } from "nanoid"
import { dispatchCommittedMessage } from "./message-dispatcher"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
import { broadcastToUserSafe, fanOutToChannel } from "./fanout"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
+import { communityProducerContract } from "./producer-contract"
const log = createLogger({ service: "community-message-handler" })
@@ -560,11 +564,16 @@ export async function createCommunityMessage(params: {
}))
}
if (created.createdThread && !params.suppressThreadFanout) {
- deliveries.push(fanOutToChannel(target.channelId, {
+ const contract = communityProducerContract(getCloudflareContext().env as Env)
+ const child = contract === 3 ? await queries.communityChannel.getThreadChannelByParentMessage(db, target.channelId, created.id) : null
+ const event = {
type: WS_EVENTS.CHILD_CHANNEL_CREATE,
parentChannelId: target.channelId,
parentMessageId: created.id,
- channel: { ...created.createdThread, type: "thread", creatorId: authorId },
+ channel: contract === 3 ? communityChannelResourceFromStorage(child) : { ...created.createdThread, type: "thread" as const, creatorId: authorId },
+ }
+ deliveries.push(fanOutToChannel(target.channelId, contract === 3 ? CommunityResourceWsEventSchema.parse(event) : {
+ ...event, channel: { ...created.createdThread, type: "thread", creatorId: authorId },
}))
}
await Promise.all(deliveries)
diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.ts
index 141a3509e..cfc542718 100644
--- a/src/web/src/lib/community/message-payload.test.ts
+++ b/src/web/src/lib/community/message-payload.test.ts
@@ -195,3 +195,16 @@ describe("mapMessageForWs", () => {
expect(mapMessageForWs({ ...baseRow, content: null }, emptyWsCtx).content).toBe("")
})
})
+
+
+describe("attachment contract selection", () => {
+ it("keeps NULL metadata in 3 and preserves the original absent size field in 1/2", () => {
+ const attachment = { id: "attachment", name: "file.bin", url: "/file", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }
+ const ctx = { ...emptyApiCtx, attachmentsByMessage: { m1: [attachment] } }
+ for (const contract of [1, 2] as const) {
+ const value = JSON.parse(JSON.stringify(mapMessageForApi(baseRow, ctx, contract)))
+ expect(value.attachments).toEqual([{ kind: "file", name: "file.bin", url: "/file" }])
+ }
+ expect(mapMessageForApi({ ...baseRow, authorAvatarVersion: 2 }, ctx, 3, "channel").attachments).toEqual([attachment])
+ })
+})
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 4d50fe68c..be0eb732d 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -14,19 +14,20 @@
* embeds pass-through, and mentionType projection so adding/removing a
* field on the wire is one edit, not four.
*/
-import { queries, truncateMessagePreview, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment, type CommunityMessageCreate } from "@alook/shared"
+import { CommunityMessageResourceSchema, queries, truncateMessagePreview, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment, type CommunityLegacyMessageCreate } 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"
+import { presentMessageAttachment } from "./attachment-presentation"
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 ReplyTargetRow = Pick<MessageRow, "id" | "authorId" | "authorName" | "content">
-type WsAttachment = NonNullable<CommunityMessageCreate["message"]["attachments"]>[number]
+type WsAttachment = NonNullable<CommunityLegacyMessageCreate["message"]["attachments"]>[number]
type UiReaction = NonNullable<CommunityMessageResource["reactions"]>[number]
type ReplyPreview = NonNullable<CommunityMessageResource["replyTo"]>
type ThreadPreview = NonNullable<CommunityMessageResource["thread"]>
@@ -112,25 +113,44 @@ export async function loadApiMessageContext(db: Database, userId: string, ids: s
// in message-wire-type so cross-scope feeds (Mentions/Marked) use the exact
// same DB-to-wire normalization as channel message responses.
-export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {
+export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext, contract: CommunityContract = 1, channelId?: string) {
+ if (contract === 3) return CommunityMessageResourceSchema.strip().parse({
+ ...coreFields(row, ctx.replyMap), channelId,
+ authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion),
+ clientNonce: row.clientNonce && !row.clientNonce.startsWith("srv:") ? row.clientNonce : null,
+ attachments: ctx.attachmentsByMessage[row.id] ?? [],
+ ...(Array.isArray(row.embeds) ? { embeds: row.embeds } : {}),
+ reactions: ctx.reactionsByMessage[row.id], thread: ctx.threadByMessageId?.get(row.id),
+ approval: ctx.approvalByMessageId?.get(row.id),
+ })
return {
...coreFields(row, ctx.replyMap),
embeds: row.embeds,
- attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id] : undefined,
+ attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id]!.map((attachment) => {
+ const presented = presentMessageAttachment(attachment)
+ return presented.kind === "file" && attachment.sizeBytes == null ? { ...presented, size: undefined } : presented
+ }) : undefined,
reactions: ctx.reactionsByMessage[row.id]?.length ? ctx.reactionsByMessage[row.id] : undefined,
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 async function mapPostedMessageForApi(db: Database, channelId: string, row: MessageRow, contract: CommunityContract = 2) {
+ const [replies, attachments] = await Promise.all([
+ row.replyToId ? queries.communityMessage.getMessagesByIdsInScope(db, [row.replyToId], { channelId }) : Promise.resolve([]),
+ contract === 3 ? queries.communityAttachment.listByMessageIds(db, [row.id]) : Promise.resolve([]),
+ ])
+ const replyMap = new Map(replies.filter((reply) => reply.channelId === channelId).map((reply) => [reply.id, reply]))
+ const attachmentsByMessage = groupAttachments(attachments)
+ if (contract === 3) return mapMessageForApi(row, { replyMap, attachmentsByMessage, reactionsByMessage: {} }, 3, channelId)
+ return { ...row, replyTo: resolveReply(row, replyMap) }
}
export type WsMessageContext = {
replyMap: Map<string, ReplyTargetRow>
attachments: WsAttachment[]
+ resourceAttachments?: CommunityMessageAttachment[]
/**
* The sender's client-provided idempotency nonce, echoed on the broadcast so
* the sender's optimistic row can be reconciled in place (see
@@ -141,7 +161,15 @@ export type WsMessageContext = {
clientNonce?: string
}
-export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext) {
+export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext, contract: CommunityContract = 2, channelId?: string) {
+ if (contract === 3) return CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }).parse({
+ ...coreFields(row, ctx.replyMap, ctx.clientNonce ?? null),
+ channelId,
+ authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion),
+ clientNonce: ctx.clientNonce && !ctx.clientNonce.startsWith("srv:") ? ctx.clientNonce : null,
+ attachments: ctx.resourceAttachments,
+ embeds: Array.isArray(row.embeds) ? row.embeds : undefined,
+ })
// 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
diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.ts
index 93eb65868..a2b7c12fe 100644
--- a/src/web/src/lib/community/message-stream.test.ts
+++ b/src/web/src/lib/community/message-stream.test.ts
@@ -14,7 +14,7 @@ import {
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { ingestMessages } from "@/lib/community-db/sync"
-function message(id: string, seq: number, extra: Partial<Msg> = {}): CanonicalMessage {
+function message(id: string, seq: number, extra: Partial<CanonicalMessage> = {}): CanonicalMessage {
return {
id,
seq,
@@ -79,12 +79,12 @@ function canonical(
id = "m1",
seq = 11,
nonce = "n1",
- extra: Partial<Msg> = {},
+ extra: Partial<CanonicalMessage> = {},
): CanonicalMessage {
return message(id, seq, { clientNonce: nonce, authorName: "Canonical", ...extra })
}
-function confirmation(nonce = "n1", id = "m1", seq = 11, extra: Partial<Msg> = {}): MessageOverlayEvent {
+function confirmation(nonce = "n1", id = "m1", seq = 11, extra: Partial<CanonicalMessage> = {}): MessageOverlayEvent {
return { type: "wsMessage", message: canonical(id, seq, nonce, extra) }
}
@@ -418,13 +418,14 @@ describe("attachment ownership effects", () => {
const retryFile = { name: "notes.txt", size: 1024, type: "text/plain" } as File
const retryThumbnail = new Blob(["thumbnail"], { type: "image/jpeg" })
const settledAttachments: NonNullable<Msg["attachments"]> = [{
- kind: "image",
+ kind: "image", contentType: "image/png",
name: "photo.png",
url: "/media/photo",
thumbnailUrl: "/media/photo/thumbnail",
width: 320,
height: 240,
}]
+ const settledResourceAttachments = [{ id: "photo", name: "photo.png", url: "/media/photo", thumbnailUrl: "/media/photo/thumbnail", contentType: "image/png", sizeBytes: null, width: 320, height: 240 }]
const attachedIntent = () => intent("files", 1, {
localUploads: [
{ file: retryFile, thumbnailBlob: retryThumbnail, previewObjectUrl: "blob:a", width: 640, height: 480 },
@@ -496,7 +497,7 @@ describe("attachment ownership effects", () => {
["WS then base", (state: MessageOverlayIds) => {
const ws = apply(state, {
type: "wsMessage",
- message: canonical("mf", 20, "files", { attachments: settledAttachments }),
+ message: canonical("mf", 20, "files", { attachments: settledResourceAttachments }),
})
return apply(ws.state, {
type: "baseChanged",
@@ -516,7 +517,7 @@ describe("attachment ownership effects", () => {
expect(converged.outboxByNonce.size).toBe(0)
expect(converged.liveIds).toContain("mf")
- expect(canonicalRows().get("mf")?.attachments).toEqual(settledAttachments)
+ expect(canonicalRows().get("mf")?.attachments).toEqual(settledResourceAttachments)
expect(materializeMessageStream([currentBase], converged)[0]?.attachments).toEqual(
settledAttachments,
)
@@ -525,7 +526,7 @@ describe("attachment ownership effects", () => {
it("lets an explicit canonical empty attachment list replace prior attachments", () => {
let state = apply(emptyMessageOverlay(), {
type: "wsMessage",
- message: canonical("mf", 20, "files", { attachments: settledAttachments }),
+ message: canonical("mf", 20, "files", { attachments: settledResourceAttachments }),
}).state
const emptyCanonical = canonical("mf", 20, "files", { attachments: [] })
@@ -544,15 +545,15 @@ describe("attachment ownership effects", () => {
kind: "file",
name: "canonical.txt",
url: "/media/canonical",
- size: "2 KB",
+ sizeBytes: 2048, size: "2.0 KB",
}]
let state = apply(emptyMessageOverlay(), {
type: "wsMessage",
- message: canonical("mf", 20, "files", { attachments: settledAttachments }),
+ message: canonical("mf", 20, "files", { attachments: settledResourceAttachments }),
}).state
const replacementCanonical = canonical("mf", 20, "files", {
- attachments: replacement,
+ attachments: [{ id: "replacement", name: "canonical.txt", url: "/media/canonical", sizeBytes: 2048 }],
})
state = apply(state, {
type: "baseChanged",
@@ -560,7 +561,7 @@ describe("attachment ownership effects", () => {
}).state
expect(state.liveIds).toContain("mf")
- expect(canonicalRows().get("mf")?.attachments).toEqual(replacement)
+ expect(canonicalRows().get("mf")?.attachments).toEqual([{ id: "replacement", name: "canonical.txt", url: "/media/canonical", sizeBytes: 2048 }])
expect(materializeMessageStream([replacementCanonical], state)[0]?.attachments).toEqual(
replacement,
)
@@ -569,9 +570,9 @@ describe("attachment ownership effects", () => {
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 }),
+ message: canonical("ws-id", 20, "files", { attachments: settledResourceAttachments }),
}).state
- const completeBase = canonical("base-id", 20, "files", { attachments: settledAttachments })
+ const completeBase = canonical("base-id", 20, "files", { attachments: settledResourceAttachments })
state = apply(state, { type: "baseChanged", messages: [completeBase] }).state
expect(materializeMessageStream([completeBase], state)).toEqual([
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index 323f6f248..9df0a7450 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -1,10 +1,11 @@
-import type { Msg, SendAttachment } from "@/lib/community/models/message"
-import type { MentionType, CommunityMessageResource } from "@alook/shared"
+import type { Msg, SendAttachment, CanonicalMessage } from "@/lib/community/models/message"
+import type { MentionType, CommunityMessagePreview } from "@alook/shared"
+import { presentCanonicalMessage } from "@/lib/community/message-wire"
import { presentMessageAttachment } from "@/lib/community/attachment-presentation"
export const MAX_LIVE_MESSAGE_DELTAS = 500
-export type CanonicalMessage = Msg & Pick<CommunityMessageResource, "seq"> & Partial<Pick<CommunityMessageResource, "replyToId">>
+export type { CanonicalMessage } from "@/lib/community/models/message"
export type MessageScope =
| { kind: "channel"; id: string; serverId: string }
@@ -103,7 +104,7 @@ function updateIntent(
return { state: { ...state, outboxByNonce }, effects: [] }
}
-function compoundIdentity(message: Pick<Msg, "authorId" | "clientNonce">): string | undefined {
+function compoundIdentity(message: Pick<CommunityMessagePreview, "authorId" | "clientNonce">): string | undefined {
return message.authorId && message.clientNonce && !message.clientNonce.startsWith("srv:")
? JSON.stringify([message.authorId, message.clientNonce]) : undefined
}
@@ -193,11 +194,11 @@ export function materializeMessageStream(
for (const id of overlay.liveIds) {
const message = canonical.get(id)
if (message) upsertMaterialized(byId, idByIdentity, {
- message: { ...message, failed: false },
+ message: { ...presentCanonicalMessage(message), failed: false },
})
}
for (const message of baseMessages) {
- upsertMaterialized(byId, idByIdentity, { message })
+ upsertMaterialized(byId, idByIdentity, { message: presentCanonicalMessage(message) })
}
return [...byId.values()].sort(materializedOrder).map((entry) => entry.message)
diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.ts
index 57c5e0ffc..1c8216225 100644
--- a/src/web/src/lib/community/message-wire.test.ts
+++ b/src/web/src/lib/community/message-wire.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"
import type { CommunityMessageCreate } from "@alook/shared"
-import { projectCommunityMessageCreate, projectPostedMessage } from "./message-wire"
+import { presentCanonicalMessage, projectCommunityMessageCreate, projectPostedMessage } from "./message-wire"
function wire(
overrides: Partial<CommunityMessageCreate["message"]> = {},
@@ -10,6 +10,7 @@ function wire(
seq: 42,
authorId: "u1",
authorName: "Gus",
+ authorAvatarVersion: 0,
content: "hello",
type: "chat",
createdAt: "2026-08-06T00:00:00.000Z",
@@ -18,6 +19,22 @@ function wire(
}
describe("projectCommunityMessageCreate", () => {
+ it("presents sparse thread participants without altering stored facts", () => {
+ const thread = { id: "thread", name: null, messageCount: 2, lastReplyAt: null, participants: [
+ { id: "unknown" },
+ { id: "initial", name: "Peer", avatar: null },
+ { id: "known", name: "Author", avatar: "/avatar", avatarVersion: 4 },
+ ] }
+ expect(presentCanonicalMessage({ id: "opener", type: "chat", thread }).thread).toEqual({
+ id: "thread", name: "", messageCount: 2, lastReplyAt: undefined, participants: [
+ { id: "unknown", name: "", avatar: "?", avatarVersion: 0 },
+ { id: "initial", name: "Peer", avatar: "P", avatarVersion: 0 },
+ { id: "known", name: "Author", avatar: "/avatar", avatarVersion: 4 },
+ ],
+ })
+ expect(thread.participants[0]).toEqual({ id: "unknown" })
+ expect(thread.participants[1].avatar).toBeNull()
+ })
it("keeps explicit empty rich fields distinct from omission", () => {
expect(projectCommunityMessageCreate(wire({ attachments: [], embeds: [] }), "channel-1"))
.toMatchObject({ attachments: [], embeds: [] })
@@ -56,20 +73,24 @@ describe("projectCommunityMessageCreate", () => {
replyTo,
approval,
}))
+ expect(() => projectCommunityMessageCreate(Object.assign({}, wire(), { storageMetadata: { legacy: true } }), "channel-1"))
+ .toThrow()
})
it("keeps valid embed fields and omits an entirely malformed field list", () => {
- const result = projectCommunityMessageCreate(wire({ embeds: [
+ const raw = 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")
+ const result = presentCanonicalMessage(raw)
+ expect(raw.embeds?.[0]).toMatchObject({ fields: [null, { name: "Key", value: "Value", inline: true }, { name: "Missing value" }] })
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({
+ const raw = projectCommunityMessageCreate(wire({
embeds: [{ title: "Card", url: "https://example.com" }, { url: "missing-title" }, null],
attachments: [
{ id: "a1", filename: "photo.png", url: "/photo", contentType: "image/png", size: 2048, width: 640, height: 480 },
@@ -77,6 +98,9 @@ describe("projectCommunityMessageCreate", () => {
{ id: "a3", filename: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", size: 1024 },
],
}), "channel-1")
+ const projected = presentCanonicalMessage(raw)
+ expect(raw.attachments?.map((row) => row.id)).toEqual(["a1", "a2", "a3"])
+ expect(raw.embeds).toHaveLength(3)
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 },
@@ -87,6 +111,44 @@ describe("projectCommunityMessageCreate", () => {
})
describe("projectPostedMessage", () => {
+ it.each([0, 46])("keeps valid legacy POST facts at seq %s without storage extras", (seq) => {
+ const replyTo = { id: "prior", authorName: "Peer", text: "quoted" }
+ const attachments = [{ id: "file", name: "file.txt", url: "/file", thumbnailUrl: null,
+ contentType: "text/plain", sizeBytes: 4, width: null, height: null }]
+ const embeds = [{ title: "Card" }]
+ const reactions = [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }]
+ const thread = { id: "thread", name: "Thread", messageCount: 1, lastReplyAt: null }
+ const row = { id: "legacy", channelId: "channel-1", seq, authorId: "author", authorName: "Author",
+ authorImage: null, authorAvatarVersion: 4, createdAt: "2026-10-07T12:00:00Z", content: "body", type: "default",
+ mentionType: null, replyToId: replyTo.id, replyTo, attachments, embeds, reactions, thread,
+ clientNonce: "stored-nonce", authorEmail: "[email protected]", storageMetadata: { legacy: true } }
+
+ expect(projectPostedMessage(row, "accepted-nonce", "channel-1")).toEqual({
+ id: row.id, channelId: row.channelId, seq, authorId: row.authorId, authorName: row.authorName,
+ authorAvatar: null, authorAvatarVersion: 4, createdAt: row.createdAt, content: row.content, type: "chat",
+ mentionType: null, replyToId: replyTo.id, replyTo, attachments, embeds, reactions, thread,
+ clientNonce: "accepted-nonce", resourceComplete: false,
+ })
+ })
+
+ it.each([{ seq: undefined }, { seq: -1 }, { seq: 0.5 },
+ { replyTo: { id: "prior", authorName: "Peer", text: "quoted", extra: true } },
+ ])("rejects malformed known legacy POST facts %j", (fields) => {
+ const row = { id: "legacy", seq: 1, authorId: "author", authorName: "Author", authorImage: null,
+ authorAvatarVersion: 0, createdAt: "2026-10-07T12:00:00Z", content: "body", type: "default", embeds: null }
+ expect(() => projectPostedMessage(Object.assign({}, row, fields), "nonce", "channel-1")).toThrow()
+ })
+
+ it("keeps full POST resource and confirmation requirements", () => {
+ const full = { id: "full", channelId: "channel-1", seq: 47, authorId: "author", authorName: "Author",
+ authorAvatar: null, authorAvatarVersion: 4, createdAt: "2026-10-07T12:00:00Z", content: "body", type: "chat" as const,
+ replyToId: null, clientNonce: "nonce", attachments: [], resourceComplete: true as const }
+ expect(projectPostedMessage(full, "nonce", "channel-1")).toEqual(full)
+ for (const fields of [{ attachments: undefined }, { channelId: "foreign" }, { clientNonce: "foreign" }]) {
+ expect(() => projectPostedMessage(Object.assign({}, full, fields), "nonce", "channel-1")).toThrow()
+ }
+ })
+
it("falls back to an initial when the posted author has no canonical avatar", () => {
const projected = projectPostedMessage({
id: "m2",
@@ -102,10 +164,11 @@ describe("projectPostedMessage", () => {
}, "nonce-2", "dm-1")
expect(projected).toMatchObject({
- authorAvatar: "G",
+ authorAvatar: null,
authorAvatarVersion: 0,
clientNonce: "nonce-2",
})
+ expect(presentCanonicalMessage(projected).authorAvatar).toBe("G")
})
it("rejects an absent or mismatched actual POST channel scope", () => {
@@ -118,12 +181,15 @@ describe("projectPostedMessage", () => {
})
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")
+ const row = { 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" }
+ const posted = projectPostedMessage(row, "nonce-4", "dm-1")
+ expect(projectPostedMessage(Object.assign({}, row, { attachments: [], embeds: [] }), "nonce-4", "dm-1"))
+ .toMatchObject({ attachments: [], embeds: [] })
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.channelId).toBe(message.id === "m4" ? "dm-1" : "channel-1")
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.ts
index 2b7835409..1ac76b3a4 100644
--- a/src/web/src/lib/community/message-wire.ts
+++ b/src/web/src/lib/community/message-wire.ts
@@ -1,16 +1,16 @@
-import { normalizeCommunityMessageResource, CommunityMessageResourceSchema, type CommunityMessageCreate, type CommunityMessageResource } from "@alook/shared"
-import { MessageEmbedSchema, type Msg } from "@/lib/community/models/message"
+import { CommunityLegacyMessageCreateSchema, CommunityMessagePreviewSchema, CommunityMessageResourceSchema, type CommunityMessageCreate, type CommunityMessageResource, type CommunityMessagePreview } from "@alook/shared"
+import { MessageEmbedSchema, type Msg, type CanonicalMessage } from "@/lib/community/models/message"
import type { MessageRow } from "./message-payload"
import { avatarInitial } from "@/lib/community/avatar"
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()
+const richContentSchema = CommunityMessagePreviewSchema.pick({ attachments: true, embeds: true }).strip()
-export type PostedMessage = Pick<MessageRow, "id" | "seq" | "createdAt" | "content" | "authorId" | "authorName" | "authorImage" | "authorAvatarVersion" | "type" | "embeds"> & Partial<Pick<CommunityMessageResource, "replyToId" | "replyTo" | "attachments">>
+type LegacyPostedMessage = Pick<MessageRow, "id" | "seq" | "createdAt" | "content" | "authorId" | "authorName" | "authorImage" | "authorAvatarVersion" | "type" | "embeds"> & Partial<Pick<CommunityMessageResource, "replyToId" | "replyTo" | "attachments" | "clientNonce">>
+export type PostedMessage = LegacyPostedMessage | (CommunityMessageResource & { resourceComplete: true })
function omitUndefined<T>(value: T): T {
if (Array.isArray(value)) return value.map(omitUndefined) as T
@@ -24,7 +24,7 @@ function projectEmbed(value: unknown): UiEmbed | undefined {
return parsed.success ? omitUndefined(parsed.data) : undefined
}
-export function projectMessageRichContent(value: unknown): Pick<Msg, "attachments" | "embeds"> {
+function projectMessageRichContent(value: unknown): Pick<Msg, "attachments" | "embeds"> {
const { attachments, embeds } = richContentSchema.parse(value)
return {
...(attachments ? { attachments: attachments.map(presentMessageAttachment) } : {}),
@@ -32,34 +32,51 @@ export function projectMessageRichContent(value: unknown): Pick<Msg, "attachment
}
}
+export function presentCanonicalMessage(message: CommunityMessagePreview): Msg {
+ const { channelId: _channelId, replyToId: _replyToId, clientNonce, authorAvatar, attachments: _attachments, embeds: _embeds, thread, ...fields } = message
+ return {
+ ...fields,
+ ...(authorAvatar === undefined ? {} : { authorAvatar: authorAvatar ?? avatarInitial(message.authorName ?? "") }),
+ ...(clientNonce != null ? { clientNonce } : {}),
+ ...(thread ? { thread: presentMessageThread(thread) } : {}),
+ ...projectMessageRichContent(message),
+ }
+}
+
+function presentMessageThread(thread: NonNullable<CommunityMessagePreview["thread"]>): NonNullable<Msg["thread"]> {
+ const { participants, ...fields } = thread
+ return { ...fields, name: thread.name ?? "", messageCount: thread.messageCount ?? 0, lastReplyAt: thread.lastReplyAt ?? undefined,
+ ...(participants ? { participants: participants.map((participant) => ({
+ ...participant, name: participant.name ?? "", avatar: participant.avatar ?? avatarInitial(participant.name ?? ""), avatarVersion: participant.avatarVersion ?? 0,
+ })) } : {}),
+ }
+}
+
export function projectCommunityMessageCreate(
message: CommunityMessageCreate["message"],
channelId: string,
+ contract: 1 | 2 | 3 = 2,
): CanonicalMessage {
- 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,
+ if (contract === 3) {
+ const full = CommunityMessageResourceSchema.parse(message)
+ if (full.channelId !== channelId) throw new Error("Message resource scope mismatch")
+ return { ...full, resourceComplete: true }
+ }
+ const legacy = CommunityLegacyMessageCreateSchema.shape.message.parse(message)
+ const attachments = legacy.attachments?.map((attachment) => ({
+ id: attachment.id, name: attachment.filename, url: attachment.url,
+ contentType: attachment.contentType, sizeBytes: attachment.size,
+ thumbnailUrl: attachment.thumbnailUrl, width: attachment.width, height: attachment.height,
}))
- return projectCanonicalMessage({
- ...message,
- authorAvatar: message.authorAvatar || avatarInitial(message.authorName),
- attachments,
- }, channelId)
+ return projectCanonicalMessage({ ...legacy, 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 } : {}),
- }
+ const message = CommunityMessagePreviewSchema.strip().parse({ ...value, channelId })
+ if (typeof message.seq !== "number") throw new Error("Confirmed message sequence missing")
+ if (value.channelId !== undefined && value.channelId !== channelId) throw new Error("Message resource scope mismatch")
+ const fields = Object.fromEntries(Object.entries(message).filter(([, value]) => value !== undefined))
+ return { ...fields, id: message.id, type: message.type, channelId, seq: message.seq, resourceComplete: false }
}
export function projectPostedMessage(
@@ -67,13 +84,19 @@ export function projectPostedMessage(
clientNonce: string,
channelId: string,
): CanonicalMessage {
+ if ("resourceComplete" in message && message.resourceComplete === true) {
+ const full = CommunityMessageResourceSchema.strip().parse(message)
+ if (full.channelId !== channelId || (clientNonce && full.clientNonce !== clientNonce)) throw new Error("Posted message confirmation mismatch")
+ return { ...full, resourceComplete: true }
+ }
+ if (!("authorImage" in message)) throw new Error("Posted message confirmation missing resource contract")
const { authorImage, type, content, embeds, ...fields } = message
return projectCanonicalMessage({
...fields,
...projectMessageWireType(type),
- authorAvatar: canonicalUserImage(message.authorId, authorImage, message.authorAvatarVersion) || avatarInitial(message.authorName),
+ authorAvatar: canonicalUserImage(message.authorId, authorImage, message.authorAvatarVersion),
content: content ?? "",
embeds: Array.isArray(embeds) ? embeds : undefined,
- clientNonce,
+ ...(clientNonce ? { clientNonce } : {}),
}, channelId)
}
diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.ts
index a3a298496..83b047d7a 100644
--- a/src/web/src/lib/community/messages.test.ts
+++ b/src/web/src/lib/community/messages.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest"
import { groupAttachments, buildSinceResponse } from "./messages"
+import { presentMessageAttachment } from "./attachment-presentation"
// A since response is a forward delta, but it can land as the sole/oldest page
// in the cache (reconnect install, persister rehydrate). The client reads the
@@ -48,71 +49,38 @@ describe("buildSinceResponse", () => {
})
})
-// `groupAttachments` derives the render `url` from the row's `targetId` + `id`
-// via the shared `attachmentUrl` helper — the URL is id-addressed and served by
-// the canonical `channels/{id}/attachments/{attachmentId}` door (route/disc
-// attachments fold). The DB row carries no `url` column. `width`/`height` are
-// optional on the output shape, so we assert on the actual returned object
-// rather than relying on the declared type to catch a missing field.
describe("groupAttachments", () => {
- it("projects a canonical thumbnail URL only when the row declares one", () => {
+ it("retains stable IDs, attachment order, raw metadata and declared thumbnail URLs", () => {
const result = groupAttachments([
- { id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "original", thumbnailR2Key: "thumb", contentType: "image/png", size: 1000 },
- { id: "att2", messageId: "m2", targetId: "c1", filename: "legacy.png", r2Key: "legacy", thumbnailR2Key: null, contentType: "image/png", size: 1000 },
- ])
- expect(result.m1?.[0]).toMatchObject({
- url: "/api/community/channels/c1/attachments/att1",
- thumbnailUrl: "/api/community/channels/c1/attachments/att1/thumbnail",
- })
- expect(result.m2?.[0]).not.toHaveProperty("thumbnailUrl")
- })
-
- it("projects width/height onto an image-kind entry when present on the row", () => {
- const result = groupAttachments([
- { id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
+ { id: "att-b", messageId: "m1", targetId: "c1", filename: "photo.png", r2Key: "original", thumbnailR2Key: "thumb", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
+ { id: "att-a", messageId: "m1", targetId: "c1", filename: "unknown.bin", r2Key: "legacy", thumbnailR2Key: null, contentType: null, size: null, width: null, height: null },
])
expect(result.m1).toEqual([
- { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", contentType: "image/png", sizeBytes: 1000, width: 1920, height: 1080 },
+ { id: "att-b", name: "photo.png", url: "/api/community/channels/c1/attachments/att-b", thumbnailUrl: "/api/community/channels/c1/attachments/att-b/thumbnail", contentType: "image/png", sizeBytes: 1000, width: 1920, height: 1080 },
+ { id: "att-a", name: "unknown.bin", url: "/api/community/channels/c1/attachments/att-a", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
])
+ expect(result.m1?.[0]).not.toHaveProperty("kind")
+ expect(result.m1?.[1]).not.toHaveProperty("size")
})
- it("leaves width/height undefined on an image-kind entry when the row has none", () => {
- const result = groupAttachments([
- { id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: null, height: null },
- ])
- expect(result.m1).toEqual([
- { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", contentType: "image/png", sizeBytes: 1000, width: undefined, height: undefined },
- ])
+ it("retains file dimensions while formatting them only for the read view", () => {
+ const raw = groupAttachments([{ id: "att1", messageId: "m1", targetId: "c1", filename: "a.pdf", r2Key: "key", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 }]).m1![0]!
+ expect(raw).toMatchObject({ id: "att1", width: 1920, height: 1080, sizeBytes: 2048, thumbnailUrl: null })
+ expect(presentMessageAttachment(raw)).toEqual({ kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" })
})
- it("never adds width/height to a file-kind entry, even if present on the row", () => {
- const result = groupAttachments([
- { id: "att1", messageId: "m1", targetId: "c1", filename: "a.pdf", r2Key: "channel/c1/uuid/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },
- ])
- expect(result.m1).toEqual([
- { kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" },
- ])
+ it.each(["image/svg+xml", "image/x-forged"])("preserves unsafe %s metadata and renders a file", (contentType) => {
+ const raw = groupAttachments([{ id: "att1", messageId: "m1", targetId: "c1", filename: "unsafe.img", r2Key: "key", contentType, size: 2048, width: 1920, height: 1080 }]).m1![0]!
+ expect(raw).toMatchObject({ id: "att1", contentType, width: 1920, height: 1080 })
+ expect(presentMessageAttachment(raw)).toMatchObject({ kind: "file", size: "2.0 KB" })
})
- it.each(["image/svg+xml", "image/x-forged"])(
- "materializes unsafe %s attachments as file-kind",
- (contentType) => {
- const result = groupAttachments([
- { id: "att1", messageId: "m1", targetId: "c1", filename: "unsafe.img", r2Key: "channel/c1/uuid/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },
- ])
- expect(result.m1).toEqual([
- { kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att1", contentType, sizeBytes: 2048, size: "2.0 KB" },
- ])
- },
- )
-
- it("skips pending rows (messageId=null) so agent-uploaded pending attachments never surface", () => {
+ it("skips pending attachments without losing a linked row's NULL metadata", () => {
const result = groupAttachments([
- { id: "att0", messageId: null, targetId: "c1", filename: "pending.png", r2Key: "channel/c1/uuid/pending.png", contentType: "image/png", size: 100, width: null, height: null },
- { id: "att1", messageId: "m1", targetId: "c1", filename: "linked.png", r2Key: "channel/c1/uuid/linked.png", contentType: "image/png", size: 100, width: null, height: null },
+ { id: "att0", messageId: null, targetId: "c1", filename: "pending.png", r2Key: "pending", contentType: "image/png", size: 100, width: null, height: null },
+ { id: "att1", messageId: "m1", targetId: "c1", filename: "linked.png", r2Key: "linked", contentType: "image/png", size: 100, width: null, height: null },
])
- expect(result).toEqual({
- m1: [{ kind: "image", name: "linked.png", url: "/api/community/channels/c1/attachments/att1", contentType: "image/png", sizeBytes: 100, width: undefined, height: undefined }],
- })
+ expect(Object.keys(result)).toEqual(["m1"])
+ expect(result.m1).toEqual([{ id: "att1", name: "linked.png", url: "/api/community/channels/c1/attachments/att1", thumbnailUrl: null, contentType: "image/png", sizeBytes: 100, width: null, height: null }])
})
})
diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.ts
index ab04c35de..ffd2541b2 100644
--- a/src/web/src/lib/community/messages.ts
+++ b/src/web/src/lib/community/messages.ts
@@ -1,6 +1,4 @@
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) {
@@ -172,18 +170,15 @@ export function groupAttachments(
const map: Record<string, CommunityMessageAttachment[]> = {}
for (const a of attachments) {
if (!a.messageId) continue
- const kind = isInlineAttachmentContentType(a.contentType) ? "image" : "file"
const entry: CommunityMessageAttachment = {
- kind,
+ id: a.id,
name: a.filename,
url: attachmentUrl(a.targetId, a.id),
- ...(a.contentType ? { contentType: a.contentType } : {}),
- ...(a.size !== null ? { sizeBytes: a.size } : {}),
- ...(kind === "image" && a.thumbnailR2Key
- ? { thumbnailUrl: attachmentThumbnailUrl(a.targetId, a.id) }
- : {}),
- ...(kind === "file" && a.size !== null ? { size: formatAttachmentSize(a.size) } : {}),
- ...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),
+ thumbnailUrl: a.thumbnailR2Key ? attachmentThumbnailUrl(a.targetId, a.id) : null,
+ contentType: a.contentType,
+ sizeBytes: a.size,
+ width: a.width ?? null,
+ height: a.height ?? null,
}
;(map[a.messageId] ??= []).push(entry)
}
diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.ts
index 62433fe4f..d97fac8a5 100644
--- a/src/web/src/lib/community/models/message.ts
+++ b/src/web/src/lib/community/models/message.ts
@@ -1,8 +1,8 @@
import { z } from "zod"
-import type { CommunityChannelResource, CommunityMessageResource, CommunityMessageAttachment, CommunityMessagesRead } from "@alook/shared"
+import type { CommunityChannelResource, CommunityMessageResource, CommunityMessagePreview, CommunityLegacyMessageResource, CommunityLegacyMessageAttachment, CommunityMessagesRead } from "@alook/shared"
// ── Messages ───────────────────────────────────────────────────────────────
-type AttachmentMetadata = Pick<CommunityMessageAttachment, "name" | "url" | "contentType" | "sizeBytes">
+type AttachmentMetadata = Pick<CommunityLegacyMessageAttachment, "name" | "url" | "contentType" | "sizeBytes">
export type FileAttachment = AttachmentMetadata & { kind: "file"; size: string }
@@ -39,16 +39,19 @@ 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"
+ "id" | "type" | "channelId" | "replyToId" | "clientNonce" | "attachments" | "embeds" | "authorAvatar" | "thread"
>> & {
color?: string
failed?: boolean
clientNonce?: string
attachments?: Attachment[]
embeds?: Embed[]
+ authorAvatar?: string
+ thread?: CommunityLegacyMessageResource["thread"]
}
-export type MessageInput = Pick<Msg, "id"> & Partial<Msg> & Partial<Pick<CommunityMessageResource, "replyToId">>
+export type MessageInput = Pick<CommunityMessagePreview, "id"> & Partial<Omit<CommunityMessagePreview, "id">> & { resourceComplete?: boolean; failed?: boolean }
+export type CanonicalMessage = CommunityMessagePreview & Pick<CommunityMessageResource, "seq"> & { resourceComplete?: boolean }
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] }))
@@ -60,7 +63,7 @@ export function applyMessageReaction(source: Msg["reactions"], emoji: string, us
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[] {
+export function messageProfileIds(message: Pick<CommunityMessagePreview, "authorId" | "replyTo" | "thread" | "approval">): string[] {
return [
...(message.authorId ? [message.authorId] : []),
...(message.replyTo?.authorId ? [message.replyTo.authorId] : []),
@@ -96,7 +99,7 @@ export type ForumThread = Thread & Required<Pick<CommunityMessageResource,
openerCreatedAt?: CommunityMessageResource["createdAt"]
tags: NonNullable<NonNullable<CommunityMessageResource["thread"]>["tags"]>
preview: NonNullable<NonNullable<CommunityMessageResource["thread"]>["preview"]>
- participants: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participants"]>
+ participants: NonNullable<NonNullable<CommunityLegacyMessageResource["thread"]>["participants"]>
participantCount: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participantCount"]>
}
@@ -109,7 +112,7 @@ export type SendAttachment = {
}
export type MessagesPage = Partial<{ [Field in keyof CommunityMessagesRead["page"]]: NonNullable<CommunityMessagesRead["page"][Field]> }> & {
- messages: Msg[]
+ messages: MessageInput[]
hasMore?: CommunityMessagesRead["page"]["hasMoreOlder"]
cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>
}
diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.ts
index 94adbecae..c8797f680 100644
--- a/src/web/src/lib/community/models/people.ts
+++ b/src/web/src/lib/community/models/people.ts
@@ -2,25 +2,14 @@ import type { CommunityResourceProfile, CommunityMemberRelation, CommunityChanne
export type Presence = "online" | "offline"
-export type CommunityProfile = Pick<CommunityResourceProfile, "id"> & Partial<CommunityUserCore> & {
- aboutMe?: string
- bannerColor?: string | null
- kind?: "human" | "bot"
- ownerUserId?: string | null
- ownerHandle?: string | null
- mutualServers?: number
- ownedByViewer?: boolean
- statusEmoji?: CommunityResourceProfile["statusEmoji"]
- statusText?: CommunityResourceProfile["statusText"] | null
- presence?: Presence
-}
+export type CommunityProfile = Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">> & { presence?: Presence }
export type CommunityProfilePatch = Pick<CommunityProfile, "id"> & {
identityAbout?: Partial<Pick<
CommunityProfile,
"name" | "discriminator" | "aboutMe" | "bannerColor" | "kind" | "ownerUserId"
>>
- avatar?: Pick<CommunityUserCore, "avatar" | "avatarVersion">
+ avatar?: Pick<CommunityResourceProfile, "avatarVersion"> & Partial<Pick<CommunityResourceProfile, "avatar">>
status?: Pick<CommunityProfile, "statusEmoji" | "statusText">
card?: Pick<CommunityProfile, "ownerHandle" | "mutualServers" | "ownedByViewer">
presence?: Presence
@@ -35,7 +24,7 @@ export type Member = CommunityUserCore & Pick<CommunityProfile, "statusEmoji" |
status: Presence
sub: string
role: import("@alook/shared").CommunityRole
- source?: "explicit" | "inherited" | "admin" | import("@alook/shared").ParticipantSource
+ source?: CommunityMemberRelation["source"]
}
export type Friend = CommunityUserCore & Pick<CommunityProfile, "statusEmoji" | "statusText"> & Partial<Pick<CommunityMemberRelation, "userId">> & {
diff --git a/src/web/src/lib/community/participant-resources.ts b/src/web/src/lib/community/participant-resources.ts
index a618f660d..9860464fb 100644
--- a/src/web/src/lib/community/participant-resources.ts
+++ b/src/web/src/lib/community/participant-resources.ts
@@ -1,18 +1,18 @@
import type { CommunityMemberRelation, CommunityResourceProfile, CommunityThreadsRead } from "@alook/shared"
export function resourceProfile(
- fields: Pick<CommunityResourceProfile, "id" | "name" | "avatar" | "avatarVersion"> & Partial<CommunityResourceProfile>,
+ fields: Pick<CommunityResourceProfile, "id" | "name" | "discriminator" | "avatar" | "avatarVersion"> & Partial<CommunityResourceProfile>,
): CommunityResourceProfile {
- return { discriminator: null, statusEmoji: null, statusText: "", ...fields }
+ return { ...fields }
}
-type Participant = Pick<CommunityMemberRelation, "channelId" | "userId" | "isCreator"> & {
- profile: CommunityResourceProfile
+type Participant<Profile> = Pick<CommunityMemberRelation, "channelId" | "userId" | "isCreator"> & {
+ profile: Profile
participantCount?: number
}
-export function threadParticipantResources(rows: readonly Participant[]): Pick<CommunityThreadsRead["included"], "members" | "profiles" | "participantCounts"> {
- const profiles = new Map<string, CommunityResourceProfile>()
+export function threadParticipantResources<Profile extends Pick<CommunityResourceProfile, "id">>(rows: readonly Participant<Profile>[]): Pick<CommunityThreadsRead["included"], "members" | "participantCounts"> & { profiles: Profile[] } {
+ const profiles = new Map<string, Profile>()
const counts = new Map<string, number>()
const authoritativeCounts = new Map<string, number>()
const members = rows.map((row): CommunityMemberRelation => {
diff --git a/src/web/src/lib/community/producer-contract.test.ts b/src/web/src/lib/community/producer-contract.test.ts
index 4d3efd8c1..cbba27c78 100644
--- a/src/web/src/lib/community/producer-contract.test.ts
+++ b/src/web/src/lib/community/producer-contract.test.ts
@@ -8,7 +8,7 @@ const batch: MessageDeliveryBatch = { messageId: "message", messageEvent: { type
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, { COMMUNITY_EVENT_CONTRACT: "2" })).toEqual(event)
expect(() => projectCommunityProducerEvent({ ...event, serverId: null }, {})).toThrow("requires producer contract v2")
})
it("selects the old committed-delivery shape without mutating its source", () => {
diff --git a/src/web/src/lib/community/producer-contract.ts b/src/web/src/lib/community/producer-contract.ts
index 2f2bcc3ee..5222c132e 100644
--- a/src/web/src/lib/community/producer-contract.ts
+++ b/src/web/src/lib/community/producer-contract.ts
@@ -1,15 +1,20 @@
-import { projectCommunityEventForContract, type CommunityWsEvent, type MessageDeliveryBatch } from "@alook/shared"
+import { projectCommunityEventForContract, type CommunityContract, 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)
+export function communityProducerContract(env: ProducerEnvironment): CommunityContract {
+ if (env.COMMUNITY_EVENT_CONTRACT === "3") return 3
+ return env.COMMUNITY_EVENT_CONTRACT === "2" ? 2 : 1
+}
+
+export function projectCommunityProducerEvent(event: CommunityWsEvent, env: ProducerEnvironment, sourceContract: CommunityContract = 2) {
+ const selected = projectCommunityEventForContract(event, communityProducerContract(env), sourceContract)
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
+ if (batch.communityContract === 3 || communityProducerContract(env) !== 1 || !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.test.ts b/src/web/src/lib/community/profile-seed.test.ts
index 8655e51c8..53a03139b 100644
--- a/src/web/src/lib/community/profile-seed.test.ts
+++ b/src/web/src/lib/community/profile-seed.test.ts
@@ -128,7 +128,7 @@ describe("messageProfilePatches", () => {
{
id: "other",
identityAbout: { name: "Other", discriminator: "0002" },
- avatar: { avatar: "O", avatarVersion: 2 },
+ avatar: { avatar: null, avatarVersion: 2 },
},
{
id: "bot",
@@ -140,6 +140,20 @@ describe("messageProfilePatches", () => {
})
describe("profile seeding boundaries", () => {
+ it.each([null, "/actual.png"])("upgrades real complete identity with avatar %s and retained enrichment", avatar => {
+ writeCommunityProfilePatches([{
+ id: "complete", identityAbout: { name: "Complete", discriminator: "12345", aboutMe: "actual bio" },
+ avatar: { avatar, avatarVersion: 4 }, status: { statusEmoji: null, statusText: "actual status" },
+ }], registry)
+ expect(registry.collections.profiles.get("complete")).toMatchObject({
+ id: "complete", name: "Complete", discriminator: "12345", avatar, avatarVersion: 4,
+ aboutMe: "actual bio", statusEmoji: null, statusText: "actual status", identityComplete: true,
+ })
+ writeCommunityProfilePatches([{ id: "partial", identityAbout: { name: "Partial", discriminator: "67890" }, avatar: { avatarVersion: 4 } }], registry)
+ expect(registry.collections.profiles.get("partial")).toMatchObject({ identityComplete: false, avatarVersion: 4 })
+ expect(registry.collections.profiles.get("partial")).not.toHaveProperty("avatar")
+ })
+
it("writes profile patches into the canonical collection", () => {
writeCommunityProfilePatches([{
id: "u1",
@@ -174,6 +188,16 @@ describe("profile seeding boundaries", () => {
})
})
+ it("keeps a known number when a name-only or unknown-number identity is seeded", () => {
+ writeCommunityProfilePatches([{ id: "numbered", identityAbout: { name: "Original", discriminator: "123456" }, status: { statusEmoji: "🌱", statusText: "Known" } }], registry)
+ const patch = communityUserProfilePatch("numbered", { name: "Renamed", discriminator: "", avatar: "avatar", avatarVersion: 1 })
+ expect(patch.identityAbout).toEqual({ name: "Renamed" })
+ expect(patch).not.toHaveProperty("status")
+ writeCommunityProfilePatches([patch], registry)
+ writeCommunityProfilePatches([{ id: "numbered", identityAbout: { name: "Latest", discriminator: "" } }], registry)
+ expect(registry.collections.profiles.get("numbered")).toMatchObject({ name: "Latest", discriminator: "123456", statusEmoji: "🌱", statusText: "Known" })
+ })
+
it("rejects a request snapshot captured by a different registry", async () => {
const other = createCommunityDbRegistry(new QueryClient(), "other")
await other.preload()
@@ -234,3 +258,15 @@ describe("profile seeding boundaries", () => {
})
})
})
+
+
+describe("partial identity facts", () => {
+ it("keeps the actual legacy avatar version and does not manufacture an unknown identity", () => {
+ expect(communityUserProfilePatch("peer", { name: "Peer", avatar: "P", avatarVersion: 4 }, { legacyPresentation: true }))
+ .toEqual({ id: "peer", identityAbout: { name: "Peer" }, avatar: { avatarVersion: 4 } })
+ expect(communityUserProfilePatch("peer", {})).toEqual({ id: "peer", identityAbout: {} })
+ expect(communityUserProfilePatch("peer", { name: "Peer", avatar: "P", avatarVersion: 4 }).avatar).toEqual({ avatar: "P", avatarVersion: 4 })
+ expect(messageProfilePatches([{ thread: { id: "thread", participants: [{ id: "peer", avatar: null, avatarVersion: 4 }] } }]))
+ .toEqual([{ id: "peer", avatar: { avatar: null, avatarVersion: 4 } }])
+ })
+})
diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.ts
index 2f4482da0..90805398e 100644
--- a/src/web/src/lib/community/profile-seed.ts
+++ b/src/web/src/lib/community/profile-seed.ts
@@ -1,13 +1,11 @@
import { loadCommunityRequest } from "@/lib/community/account-cache-lifecycle"
import { createStore } from "@tanstack/react-store"
import type {
- CommunityProfile, CommunityProfilePatch,
- CommunityUserCore,
+ CommunityProfilePatch,
} from "@/lib/community/models/people"
-import type { Msg } from "@/lib/community/models/message"
-import type { FriendApprovalPayload } from "@alook/shared"
+import type { MessageInput } from "@/lib/community/models/message"
+import { CommunityResourceProfileSchema, type CommunityResourceProfile, type FriendApprovalPayload } from "@alook/shared"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
-import { avatarInitial } from "@/lib/community/avatar"
import { communityKeys } from "@/lib/query-keys"
import {
type CommunityDbRegistry,
@@ -15,6 +13,7 @@ import {
import { profileSchema, type ProfileRow } from "@/lib/community-db/schema"
import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { avatarInitial } from "@/lib/community/avatar"
type ProfileFieldRevisions = {
identityAbout: number
@@ -33,6 +32,8 @@ export type CommunityProfileSeedSnapshot = {
revision: number
}
+const profileIdentitySchema = CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatar: true, avatarVersion: true }).extend({ discriminator: CommunityResourceProfileSchema.shape.discriminator.unwrap() })
+
const createProfileRevisions = () => createStore<ProfileRevisionState>({ revision: 0, fieldsByUserId: new Map() })
const profileRevisionState = new WeakMap<CommunityDbRegistry, ReturnType<typeof createProfileRevisions>>()
@@ -51,38 +52,40 @@ export function beginCommunityProfileSeed(
return { registry, revision: registry ? revisionState(registry).get().revision : 0 }
}
-type CommunityUserProfileSeed = CommunityUserCore & Pick<CommunityProfile, "statusEmoji" | "statusText">
+type CommunityUserProfileSeed = Partial<Pick<CommunityResourceProfile, "name" | "discriminator" | "avatarVersion" | "statusEmoji" | "statusText" | "avatar">>
export function communityUserProfilePatch(
userId: string,
row: CommunityUserProfileSeed,
+ options?: { legacyPresentation?: boolean },
): CommunityProfilePatch {
+ const statusText = options?.legacyPresentation && row.statusText === "" ? undefined : row.statusText
return {
id: userId,
identityAbout: {
- name: row.name,
- discriminator: row.discriminator,
+ ...(row.name !== undefined ? { name: row.name } : {}),
+ ...(row.discriminator ? { discriminator: row.discriminator } : {}),
},
- avatar: { avatar: row.avatar, avatarVersion: row.avatarVersion },
- ...(row.statusEmoji === undefined && row.statusText === undefined
+ ...(row.avatarVersion === undefined ? {} : { avatar: { avatarVersion: row.avatarVersion, ...(row.avatar === undefined || options?.legacyPresentation && row.avatar === avatarInitial(row.name ?? "") ? {} : { avatar: row.avatar }) } }),
+ ...(row.statusEmoji === undefined && statusText === undefined
? {}
: { status: {
...(row.statusEmoji !== undefined ? { statusEmoji: row.statusEmoji } : {}),
- ...(row.statusText !== undefined ? { statusText: row.statusText } : {}),
+ ...(statusText !== undefined ? { statusText } : {}),
} }),
}
}
-export function messageProfilePatches(messages: readonly Partial<Pick<Msg, "authorId" | "authorName" | "authorAvatar" | "authorAvatarVersion" | "replyTo" | "thread" | "approval">>[]): CommunityProfilePatch[] {
+export function messageProfilePatches(messages: readonly Partial<Pick<MessageInput, "authorId" | "authorName" | "authorAvatar" | "authorAvatarVersion" | "replyTo" | "thread" | "approval">>[]): CommunityProfilePatch[] {
const patches: CommunityProfilePatch[] = []
for (const message of messages) {
if (message.authorId) {
patches.push({
id: message.authorId,
...(message.authorName ? { identityAbout: { name: message.authorName } } : {}),
- ...(message.authorAvatar !== undefined && message.authorAvatarVersion !== undefined
+ ...(message.authorAvatarVersion !== undefined
? { avatar: {
- avatar: message.authorAvatar,
+ ...(message.authorAvatar === undefined ? {} : { avatar: message.authorAvatar }),
avatarVersion: message.authorAvatarVersion,
} }
: {}),
@@ -97,11 +100,11 @@ export function messageProfilePatches(messages: readonly Partial<Pick<Msg, "auth
for (const participant of message.thread?.participants ?? []) {
patches.push({
id: participant.id,
- identityAbout: { name: participant.name },
- avatar: {
+ ...(participant.name !== undefined ? { identityAbout: { name: participant.name } } : {}),
+ ...(participant.avatarVersion === undefined ? {} : { avatar: {
avatar: participant.avatar,
avatarVersion: participant.avatarVersion,
- },
+ } }),
})
}
patches.push(...approvalProfilePatches(message.approval))
@@ -124,7 +127,7 @@ export function approvalProfilePatches(
discriminator: profile.discriminator,
},
avatar: {
- avatar: profile.image ?? avatarInitial(profile.name),
+ avatar: profile.image,
avatarVersion: profile.avatarVersion,
},
}] : [])
@@ -140,7 +143,7 @@ export function writeCommunityProfilePatches(
const queryKey = communityKeys.communityDbCollection(registry.scopeId, "profiles")
const cached = registry.queryClient.getQueryData<ProfileRow[]>(queryKey)
?? Array.from(registry.collections.profiles.values())
- const profiles = new Map(cached.map((profile) => [profile.userId, profile]))
+ const profiles = new Map(cached.map((profile) => [profile.id, profile]))
const revisionStore = revisionState(registry)
const previous = revisionStore.get()
const revisions = { ...previous, fieldsByUserId: new Map(previous.fieldsByUserId) }
@@ -165,16 +168,15 @@ export function writeCommunityProfilePatches(
const card = patch.card && accepts("card") ? patch.card : undefined
const incomingAvatar = patch.avatar && accepts("avatar") && (
current === undefined
- || patch.avatar.avatarVersion > current.avatarVersion
+ || patch.avatar.avatarVersion > (current.avatarVersion ?? -1)
|| (!options?.event && patch.avatar.avatarVersion === current.avatarVersion)
) ? patch.avatar : undefined
- const name = identityAbout?.name ?? current?.name ?? ""
- const next = profileSchema.parse({
- userId: patch.id,
- name,
- discriminator: identityAbout?.discriminator ?? current?.discriminator ?? "",
- avatar: incomingAvatar?.avatar ?? current?.avatar ?? avatarInitial(name),
- avatarVersion: incomingAvatar?.avatarVersion ?? current?.avatarVersion ?? 0,
+ const fields = {
+ id: patch.id,
+ name: identityAbout?.name ?? current?.name,
+ discriminator: identityAbout?.discriminator || current?.discriminator,
+ avatar: incomingAvatar?.avatar === undefined ? current?.avatar : incomingAvatar.avatar,
+ avatarVersion: incomingAvatar?.avatarVersion ?? current?.avatarVersion,
aboutMe: identityAbout?.aboutMe ?? current?.aboutMe,
bannerColor: identityAbout?.bannerColor === undefined
? current?.bannerColor
@@ -192,7 +194,15 @@ export function writeCommunityProfilePatches(
statusText: status?.statusText === undefined
? current?.statusText
: status.statusText,
+ }
+ const identity = profileIdentitySchema.safeParse({
+ id: fields.id,
+ name: fields.name,
+ discriminator: fields.discriminator,
+ avatar: fields.avatar,
+ avatarVersion: fields.avatarVersion,
})
+ const next = profileSchema.parse({ ...Object.fromEntries(Object.entries(fields).filter(([, field]) => field !== undefined)), identityComplete: current?.identityComplete === true || identity.success })
profiles.set(patch.id, next)
if (writeRevision !== null) {
const nextRevisions = { ...fieldRevisions }
@@ -209,7 +219,7 @@ export function writeCommunityProfilePatches(
if (advanced && writeRevision !== null) revisions.revision = writeRevision
if (advanced) revisionStore.setState(() => revisions)
const rows = [...profiles.values()]
- writeCommunityCollectionRows(registry, "profiles", rows, (row) => row.userId)
+ writeCommunityCollectionRows(registry, "profiles", rows, (row) => row.id)
}
export async function loadAndSeedProfiles<T>(
diff --git a/src/web/src/lib/community/read-contract.test.ts b/src/web/src/lib/community/read-contract.test.ts
index f3ef20e9c..035f3ce88 100644
--- a/src/web/src/lib/community/read-contract.test.ts
+++ b/src/web/src/lib/community/read-contract.test.ts
@@ -3,6 +3,8 @@ import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { writeCommunityChannelRead, writeCommunityMessagesRead, writeCommunityReadState } from "./read-contract"
import { decodeCommunityReadResponse } from "./read-response"
import { parseCommunityMessageWindow } from "./messages"
+import { mapMessageForWs } from "./message-payload"
+import { projectCommunityMessageCreate } from "./message-wire"
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 } : {} })
@@ -28,6 +30,7 @@ describe("common reading negotiation", () => {
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(body.messages[0]).not.toHaveProperty("resourceComplete")
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 })
@@ -41,7 +44,7 @@ describe("common reading negotiation", () => {
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(decoded).toMatchObject({ latestSeq: 1, messages: [{ ...message, channelId: "channel", resourceComplete: false }] })
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")
})
@@ -50,3 +53,21 @@ describe("common reading negotiation", () => {
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()
})
})
+
+
+describe("explicit resource 3 ingress", () => {
+ it.each(["channel", "forum", "thread", "dm"] as const)("converges HTTP and WS raw facts for %s", async (surfaceKind) => {
+ const attachments = [{ id: "a2", name: "first", url: "/first", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }, { id: "a1", name: "second", url: "/second", thumbnailUrl: null, contentType: "image/png", sizeBytes: 1024, width: 40, height: 50 }]
+ const row = { id: "full", seq: 2, authorId: "peer", authorName: "Peer", authorImage: null, authorAvatarVersion: 4, createdAt: "now", type: "chat", content: "body", clientNonce: "nonce", replyToId: null, mentionType: null, embeds: [null, { unsupported: true }] }
+ const full = mapMessageForWs(row, { replyMap: new Map(), attachments: [], resourceAttachments: attachments, clientNonce: "nonce" }, 3, "channel")
+ const response = writeCommunityMessagesRead(request("3"), "channel", { messages: [full], latestSeq: 2, surfaceReceipt: { channelId: "channel", surfaceKind } })
+ const body = await response.json()
+ const http = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body, 3) as { messages: unknown[] }
+ const ws = projectCommunityMessageCreate(full, "channel", 3)
+ expect(http.messages).toEqual([ws])
+ expect(ws).toMatchObject({ resourceComplete: true, authorAvatar: null, attachments, embeds: row.embeds, clientNonce: "nonce" })
+ const missing = { ...body, messages: [{ ...full, attachments: undefined }] }
+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, missing, 3)).toThrow()
+ expect(() => projectCommunityMessageCreate({ ...full, channelId: "foreign" }, "channel", 3)).toThrow("scope mismatch")
+ })
+})
diff --git a/src/web/src/lib/community/read-contract.ts b/src/web/src/lib/community/read-contract.ts
index dffa32236..8ad3cf81d 100644
--- a/src/web/src/lib/community/read-contract.ts
+++ b/src/web/src/lib/community/read-contract.ts
@@ -1,21 +1,22 @@
import { NextResponse } from "next/server"
import {
- COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestsCommunityContract,
- CommunityChannelReadSchema, CommunityMessagesReadSchema, CommunityReadStateReadSchema,
+ COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestedCommunityContract, communityReadSchemas, communityChannelResourceFromStorage, CommunityMessageResourceSchema,
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) } })
+function versionedJSON(data: unknown, contract: 2 | 3 = COMMUNITY_CONTRACT_VERSION): NextResponse {
+ return NextResponse.json(data, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(contract) } })
}
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 } }))
+ const contract = requestedCommunityContract(request.headers)
+ if (contract !== 2 && contract !== 3) return writeJSON(channel)
+ return versionedJSON(communityReadSchemas(contract).channel.parse({ contractVersion: contract, channelId,
+ channel: contract === 3 ? communityChannelResourceFromStorage(channel) : normalizeCommunityChannelResource(channel),
+ access: { channelId, ...access } }), contract)
}
type MessagePage = Pick<CommunityMessagesRead["page"], "latestSeq"> & Partial<{ [Field in Exclude<keyof CommunityMessagesRead["page"], "latestSeq">]: NonNullable<CommunityMessagesRead["page"][Field]> }> & {
@@ -26,18 +27,20 @@ type MessagePage = Pick<CommunityMessagesRead["page"], "latestSeq"> & Partial<{
}
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)),
+ const contract = requestedCommunityContract(request.headers)
+ if (contract !== 2 && contract !== 3) return writeJSON(page)
+ return versionedJSON(communityReadSchemas(contract).messages.parse({ contractVersion: contract, channelId,
+ messages: page.messages.map((message) => contract === 3 ? CommunityMessageResourceSchema.parse(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 }))
+ latestSeq: page.latestSeq }, surfaceReceipt: page.surfaceReceipt }), contract)
}
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 } }))
+ const contract = requestedCommunityContract(request.headers)
+ if (contract !== 2 && contract !== 3) return writeJSON(state)
+ return versionedJSON(communityReadSchemas(contract).readState.parse({ contractVersion: contract, channelId, readState: { channelId, ...state } }), contract)
}
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.ts
index bdaad15a6..fef7f9967 100644
--- a/src/web/src/lib/community/read-response.test.ts
+++ b/src/web/src/lib/community/read-response.test.ts
@@ -16,10 +16,18 @@ const members = () => ({ contractVersion: 2, channelId: "thread", relation: "not
const decodeMembers = (body: unknown, path = "/api/community/channels/thread/members?relation=notify") => decodeCommunityReadResponse(path, "GET", confirmed(), body)
describe("common read response publication", () => {
+ it("admits a legacy single-message preview only with an explicit valid scope", () => {
+ const value = { id: "legacy", channelId: "thread", seq: 1, authorId: "viewer", createdAt: "now", type: "chat", content: "body" }
+ expect(decodeCommunityReadResponse("/api/community/messages/legacy", "GET", new Response(), value))
+ .toEqual({ ...value, resourceComplete: false })
+ for (const invalid of [null, {}, { ...value, channelId: undefined }, { ...value, channelId: 4 }, { ...value, channelId: "" }]) {
+ expect(() => decodeCommunityReadResponse("/api/community/messages/legacy", "GET", new Response(), invalid)).toThrow()
+ }
+ })
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"]]) {
+ 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/messages/search?q=term", "GET"], ["/api/community/messages/batch", "GET"]]) {
expect(communityReadTarget(path!, method)).toBeNull()
const body = { contractVersion: 2, private: "unrelated endpoint" }
expect(decodeCommunityReadResponse(path!, method, confirmed(), body)).toBe(body)
@@ -31,7 +39,7 @@ describe("common read response publication", () => {
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).toEqual({ ...channel, resourceComplete: true, accessDecision: access })
expect(current).not.toHaveProperty("readContractVersion")
expect(decodeCommunityReadResponse(path, "GET", new Response(), { ...channel, readContractVersion: 2, accessDecision: access })).toEqual(channel)
})
@@ -99,3 +107,29 @@ describe("common read response publication", () => {
expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "GET", new Response(), {})).toThrow("resource missing")
})
})
+
+
+describe("explicit v3 HTTP confirmation", () => {
+ const full = { ...message("message", "thread"), authorAvatar: null, attachments: [
+ { id: "a2", name: "unknown", url: "/a2", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
+ { id: "a1", name: "photo", url: "/a1", thumbnailUrl: null, contentType: "image/png", sizeBytes: 12, width: 1, height: 1 },
+ ], embeds: [null, { raw: "unknown" }] }
+ const response = (version: string | null) => new Response(null, { headers: version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: version } })
+ const body = { contractVersion: 3, channelId: "thread", message: full, deduped: false }
+ it("retains full POST and single-read resources with exact positive v3 claims", () => {
+ expect(communityReadTarget("/api/community/channels/thread/messages", "POST")).toEqual({ channelId: "thread", resource: "posted" })
+ expect(decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response("3"), body, 3)).toEqual({ message: { ...full, resourceComplete: true }, deduped: false })
+ const { deduped: _deduped, ...read } = body
+ expect(decodeCommunityReadResponse("/api/community/messages/message", "GET", response("3"), read, 3)).toEqual({ ...full, resourceComplete: true })
+ expect(() => decodeCommunityReadResponse("/api/community/messages/other", "GET", response("3"), read, 3)).toThrow("scope mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/other/messages", "POST", response("3"), body, 3)).toThrow("scope mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response("3"), { ...body, message: { ...full, attachments: undefined } }, 3)).toThrow()
+ })
+ it("refuses missing, mixed and unknown confirmation without downgrading a v3 request", () => {
+ for (const header of [null, "1", "2", "4"]) expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(header), body, 3)).toThrow("confirmation mismatch")
+ for (const contractVersion of [undefined, 1, 2, 4]) expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response("3"), { ...body, contractVersion }, 3)).toThrow("confirmation mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(null), { message: full }, 3)).toThrow("confirmation mismatch")
+ const old = { message: { id: "old" } }
+ expect(decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(null), old, 2)).toBe(old)
+ })
+})
diff --git a/src/web/src/lib/community/read-response.ts b/src/web/src/lib/community/read-response.ts
index 5bc57f717..1de4f3df3 100644
--- a/src/web/src/lib/community/read-response.ts
+++ b/src/web/src/lib/community/read-response.ts
@@ -1,69 +1,94 @@
import {
- COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, CommunityChannelReadSchema, CommunityMessagesReadSchema,
- CommunityReadStateReadSchema, CommunityMembersReadSchema, CommunityThreadsReadSchema, CommunityReadAdvanceSchema,
- normalizeCommunityMessageResource,
+ COMMUNITY_CONTRACT_HEADER, communityReadSchemas, communityMessagePreviewFromLegacy,
+ CommunityMessagePostedSchema, CommunityMessageReadSchema,
+ type CommunityContract,
} from "@alook/shared"
export function communityReadTarget(path: string, method = "GET") {
+ if (method.toUpperCase() === "POST") {
+ const matched = /^\/api\/community\/channels\/([^/?]+)\/messages(?:\?|$)/.exec(path)
+ return matched ? { channelId: decodeURIComponent(matched[1]), resource: "posted" } : null
+ }
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 single = /^\/api\/community\/messages\/([^/?]+)(?:\?|$)/.exec(path)
+ if (single && !["search", "batch", "tags"].includes(single[1])) return { channelId: "", messageId: decodeURIComponent(single[1]), resource: "message" }
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 {
+export function decodeCommunityReadResponse(path: string, method: string | undefined, response: Response, value: unknown, requestedContract: CommunityContract = 2): 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 (headerVersion === null && bodyVersion === undefined) {
+ if (requestedContract === 3) throw new Error("Community read protocol confirmation mismatch")
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 }
+ return { ...communityMessagePreviewFromLegacy(message, target.channelId), resourceComplete: false }
}) }
}
+ if (target.resource === "message") {
+ if (typeof value !== "object" || value === null || !("channelId" in value) || typeof value.channelId !== "string") throw new Error("Community message scope missing")
+ return { ...communityMessagePreviewFromLegacy(value, value.channelId), resourceComplete: false }
+ }
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")
+ if ((requestedContract !== 2 && requestedContract !== 3) || headerVersion !== String(requestedContract) || bodyVersion !== requestedContract) throw new Error("Community read protocol confirmation mismatch")
+ const schemas = communityReadSchemas(requestedContract)
const assertScope = (channelId: string) => {
if (channelId !== target.channelId) throw new Error("Community read resource scope mismatch")
}
+ if (target.resource === "message") {
+ if (requestedContract !== 3) throw new Error("Community message protocol confirmation mismatch")
+ const data = CommunityMessageReadSchema.parse(value)
+ if (data.channelId !== data.message.channelId || data.message.id !== target.messageId) throw new Error("Community message resource scope mismatch")
+ return { ...data.message, resourceComplete: true }
+ }
if (target.resource === "metadata") {
- const data = CommunityChannelReadSchema.parse(value)
+ const data = schemas.channel.parse(value)
assertScope(data.channelId); assertScope(data.channel.id); assertScope(data.access.channelId)
- return { ...data.channel, accessDecision: data.access }
+ return { ...data.channel, resourceComplete: true, accessDecision: data.access }
+ }
+ if (target.resource === "posted") {
+ if (requestedContract !== 3) throw new Error("Community posted protocol confirmation mismatch")
+ const data = CommunityMessagePostedSchema.parse(value)
+ assertScope(data.channelId); assertScope(data.message.channelId)
+ return { message: { ...data.message, resourceComplete: true }, deduped: data.deduped, ...(data.threadId ? { threadId: data.threadId } : {}) }
}
if (target.resource === "messages") {
- const data = CommunityMessagesReadSchema.parse(value)
+ const data = schemas.messages.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 })),
+ return { messages: data.messages.map((message) => requestedContract === 3
+ ? { ...message, resourceComplete: true }
+ : { ...communityMessagePreviewFromLegacy(message, target.channelId), resourceComplete: false }),
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)
+ const data = schemas.readState.parse(value)
assertScope(data.channelId); assertScope(data.readState.channelId)
return data.readState
}
if (target.resource === "read") {
- const data = CommunityReadAdvanceSchema.parse(value)
+ const data = schemas.readAdvance.parse(value)
assertScope(data.channelId)
return { changed: data.changed, targetSeq: data.targetSeq, revision: data.revision }
}
if (target.resource === "threads") {
- const data = CommunityThreadsReadSchema.parse(value)
+ const data = schemas.threads.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")
@@ -79,7 +104,7 @@ export function decodeCommunityReadResponse(path: string, method: string | undef
return data
}
if (target.resource === "members") {
- const data = CommunityMembersReadSchema.parse(value)
+ const data = schemas.members.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")
diff --git a/src/web/src/lib/community/reading.routes.test.ts b/src/web/src/lib/community/reading.routes.test.ts
index bcd36a5e2..795c5da15 100644
--- a/src/web/src/lib/community/reading.routes.test.ts
+++ b/src/web/src/lib/community/reading.routes.test.ts
@@ -95,12 +95,12 @@ describe("negotiated complete read route boundaries", () => {
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 }])
+ mocks.threadParticipants.mockResolvedValue([{ channelId: "thread", userId: "viewer", userName: "Viewer", discriminator: "123456", 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) } })
+ profiles: [{ id: "viewer", discriminator: "123456" }], 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" })
diff --git a/src/web/src/lib/community/thread-read.test.ts b/src/web/src/lib/community/thread-read.test.ts
index 28b35bd3c..b28c2fe6e 100644
--- a/src/web/src/lib/community/thread-read.test.ts
+++ b/src/web/src/lib/community/thread-read.test.ts
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER, CommunityThreadsReadSchema } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, communityReadSchemas } 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: {
@@ -16,7 +16,7 @@ const row = (id: string, channelId: string) => ({ id, channelId, seq: 4, authorI
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 }] })
+ participants: [{ channelId: "thread", userId: "viewer", userName: "Viewer", discriminator: "123456", userImage: null, userAvatarVersion: 0, participantCount: 8 }] })
beforeEach(() => {
vi.clearAllMocks()
@@ -32,10 +32,10 @@ describe("complete thread read resource", () => {
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())
+ const body = communityReadSchemas(2).threads.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" } })
+ profiles: [{ id: "viewer", name: "Viewer", discriminator: "123456", avatar: null, 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")
@@ -47,7 +47,7 @@ describe("complete thread read resource", () => {
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())
+ const body = communityReadSchemas(2).threads.parse(await response.json())
expect(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", text: "", deleted: true })
})
@@ -55,7 +55,7 @@ describe("complete thread read resource", () => {
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())
+ const body = communityReadSchemas(2).threads.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"])
@@ -63,18 +63,18 @@ describe("complete thread read resource", () => {
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(communityReadSchemas(2).threads.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 participant = { channelId: "thread", userId: "viewer", userName: null, discriminator: "123456", 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())
+ const body = communityReadSchemas(2).threads.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 }])
diff --git a/src/web/src/lib/community/thread-read.ts b/src/web/src/lib/community/thread-read.ts
index 36fe3674d..55d1e59d0 100644
--- a/src/web/src/lib/community/thread-read.ts
+++ b/src/web/src/lib/community/thread-read.ts
@@ -1,4 +1,4 @@
-import { COMMUNITY_CONTRACT_VERSION, CommunityThreadsReadSchema, normalizeCommunityChannelResource, normalizeCommunityMessageResource, queries, type Database } from "@alook/shared"
+import { CommunityResourceProfileSchema, communityReadSchemas, communityChannelResourceFromStorage, normalizeCommunityChannelResource, normalizeCommunityMessageResource, queries, type Database } from "@alook/shared"
import { writeCommunityContractJSON } from "./read-contract"
import { loadApiMessageContext, mapMessageForApi } from "./message-payload"
import { canonicalUserImage } from "./storage"
@@ -9,9 +9,10 @@ type Included = { messages: Array<Parameters<typeof mapMessageForApi>[0] & { cha
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)
+ page = { nextCursor: null as string | null, hasMore: false }, contract: 2 | 3 = 2) {
+ const normalizeChannel = contract === 3 ? (value: unknown) => communityChannelResourceFromStorage(value) : normalizeCommunityChannelResource
+ const parent = normalizeChannel(channel)
+ const children = threads.map(normalizeChannel)
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")
@@ -20,12 +21,15 @@ export async function writeCommunityThreadsRead(db: Database, userId: string, ch
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 messages = items.map((item) => {
+ const message = mapMessageForApi(item, contextForChannel(item.channelId), contract, item.channelId)
+ return contract === 3 ? message : normalizeCommunityMessageResource(message, 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 }),
+ profile: resourceProfile({ id: row.userId, name: contract === 3 ? CommunityResourceProfileSchema.shape.name.parse(row.userName) : row.userName ?? "", discriminator: row.discriminator, 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 }))
+ return writeCommunityContractJSON(communityReadSchemas(contract).threads.parse({ contractVersion: contract, channelId: parent.id, channel: parent, threads: children,
+ included: { messages, ...participants, profiles: contract === 2 ? participants.profiles.map((profile) => ({ id: profile.id, name: profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "" })) : participants.profiles, tags: included?.tags ?? [] }, page }), contract)
}
diff --git a/src/web/src/lib/middleware/response-cache.test.ts b/src/web/src/lib/middleware/response-cache.test.ts
index 656f64782..e2b5e28c6 100644
--- a/src/web/src/lib/middleware/response-cache.test.ts
+++ b/src/web/src/lib/middleware/response-cache.test.ts
@@ -15,10 +15,10 @@ describe("protected community JSON policy", () => {
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 request = new Request("https://alook.test/api/community/channels/c/icon", { headers: { [COMMUNITY_CONTRACT_HEADER]: "4" } })
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()
+ expect(rejectUnknownCommunityContract(new Request("https://alook.test/api/calendar", { headers: { [COMMUNITY_CONTRACT_HEADER]: "4" } }))).toBeNull()
})
})
diff --git a/src/web/src/lib/middleware/response-cache.ts b/src/web/src/lib/middleware/response-cache.ts
index 18f952365..bb03447f2 100644
--- a/src/web/src/lib/middleware/response-cache.ts
+++ b/src/web/src/lib/middleware/response-cache.ts
@@ -1,8 +1,8 @@
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, CommunityReadErrorSchema, requestsCommunityContract } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, requestedCommunityContract, communityReadSchemas, 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)
+ return new URL(request.url).pathname.startsWith("/api/community/") && version !== null && requestedCommunityContract(request.headers) === null
? Response.json({ error: "unsupported community contract" }, { status: 400 }) : null
}
@@ -12,8 +12,10 @@ export async function protectCommunityJsonResponse(request: Request, response: R
if (contentType !== "application/json" && !contentType?.endsWith("+json")) return response
let result = new Response(response.body, response)
if (!response.ok && requestsCommunityContract(request.headers)) {
+ const contract = requestedCommunityContract(request.headers) === 3 ? 3 : 2
+ const schema = communityReadSchemas(contract).error
const body: unknown = await result.clone().json()
- const alreadyVersioned = CommunityReadErrorSchema.safeParse(body)
+ const alreadyVersioned = schema.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"
@@ -21,11 +23,11 @@ export async function protectCommunityJsonResponse(request: Request, response: R
: 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,
+ result = new Response(JSON.stringify(schema.parse({ contractVersion: contract,
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(COMMUNITY_CONTRACT_HEADER, String(contract))
}
result.headers.set("Cache-Control", "private, no-store, max-age=0")
result.headers.delete("ETag")
diff --git a/src/web/src/lib/query-persister.race.test.ts b/src/web/src/lib/query-persister.race.test.ts
index fbd4d560d..e7348a4bd 100644
--- a/src/web/src/lib/query-persister.race.test.ts
+++ b/src/web/src/lib/query-persister.race.test.ts
@@ -1,5 +1,5 @@
import "fake-indexeddb/auto"
-import { del, get, set } from "idb-keyval"
+import { createStore, del, get, promisifyRequest, 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"
@@ -145,7 +145,7 @@ 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("messages", ["dm-A", "dm-B"].map((channelId) => ({ id: `m-${channelId}`, channelId, type: "chat", resourceComplete: false, 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) }
}
@@ -304,21 +304,22 @@ describe("native channel persistence fence", () => {
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 })
+ const createdAt = "2026-10-08T00:00:00Z"
+ const reply = (id: string, scopeId: string) => ({ id, kind: "reply", sourceId: id, scopeId, messageId: `m-${scopeId}`, actorUserId: "peer", createdAt })
+ const forumPost = (id: string, childChannelId: string, channelId: string) => ({ id, kind: "forum_post", sourceId: childChannelId, scopeId: "forum", messageId: `opener-${id}`, childChannelId, openerSeq: 1, readTarget: { channelId, seq: 1 }, createdAt })
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" }),
+ reply("scope", "dm-A"), forumPost("child", "dm-A", "forum"),
+ forumPost("target", "other-child", "dm-A"), reply("sibling", "dm-B"),
+ reply("unrelated", "other-scope"), { id: "friend", kind: "friend_request", sourceId: "friend", actorUserId: "peer", createdAt },
])
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, "attentionItems")?.map(row => row.id)).toEqual(["unrelated", "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"])
+ expect(readingRows(await owner.restoreClient(), "attentionItems")?.map(row => row.id)).toEqual(["unrelated", "sibling", "friend"])
})
it.each(["missing", "corrupt"])("fails closed for %s stored channel fence metadata", async (kind) => {
@@ -345,3 +346,109 @@ it("a retired account owner cannot fence a newer same-account snapshot", async (
expect(readingRows(await fresh.restoreClient(), "messages")).toHaveLength(2)
expect(readingRows(await fresh.restoreClient(), "channels")).toHaveLength(2)
})
+
+// The old writer compares the captured UUID directly in the same native IDB
+// transaction. This fixture checks that guard; it is not an old-browser receipt.
+describe("v6 community scope qualification", () => {
+ it.each([false, true])("retires a v5 UUID scope with payload=%s while preserving other domains", async (hasPayload) => {
+ const user = `u_v6_scope_${hasPayload}`
+ const owner = createIdbPersister(user)
+ await owner.restoreClient()
+ const namespace = `${PERSIST_CACHE_PREFIX}:${user}`
+ const device = await get("alook:qc:device-epoch")
+ const account = await get(`${namespace}:account-epoch`)
+ const fences = new Map([["channel", { epoch: crypto.randomUUID(), deleted: true }]])
+ await set(`${namespace}:account-epoch:channels`, fences)
+ const oldScope = crypto.randomUUID()
+ await set(`${blobKey(user)}:epoch`, oldScope)
+ if (hasPayload) await set(blobKey(user), JSON.stringify({ ...client, version: 5, buster: "5", channelFences: [] }))
+ else await del(blobKey(user))
+ const applicationKey = `${namespace}:application:client`
+ const applicationScope = crypto.randomUUID()
+ await set(applicationKey, "application payload")
+ await set(`${applicationKey}:epoch`, applicationScope)
+ const legacyStore = createStore("keyval-store", "keyval")
+ const legacyPayload = JSON.stringify({ ...client, version: 5, buster: "5", channelFences: [] })
+ const legacyOperation = (operation: "write" | "remove" | "channel" | "account") => legacyStore("readwrite", async (store) => {
+ const committed = promisifyRequest(store.transaction)
+ const [currentDevice, currentScope, currentAccount, currentFences] = await Promise.all([
+ promisifyRequest<unknown>(store.get("alook:qc:device-epoch")),
+ promisifyRequest<unknown>(store.get(`${blobKey(user)}:epoch`)),
+ promisifyRequest<unknown>(store.get(`${namespace}:account-epoch`)),
+ promisifyRequest<unknown>(store.get(`${namespace}:account-epoch:channels`)),
+ ])
+ const validFences = currentFences instanceof Map && [...currentFences].every(([id, fence]) => (
+ typeof id === "string" && id.length > 0 && fence !== null && typeof fence === "object"
+ && typeof fence.epoch === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(fence.epoch)
+ && typeof fence.deleted === "boolean"
+ ))
+ const eligible = currentDevice === device && currentScope === oldScope && currentAccount === account && validFences
+ if (eligible) {
+ if (operation === "write") store.put(legacyPayload, blobKey(user))
+ else store.delete(blobKey(user))
+ if (operation === "channel") store.put(new Map([["channel", { epoch: crypto.randomUUID(), deleted: true }]]), `${namespace}:account-epoch:channels`)
+ if (operation === "account") {
+ store.put(crypto.randomUUID(), `${namespace}:account-epoch`)
+ store.put(new Map(), `${namespace}:account-epoch:channels`)
+ for (const key of [blobKey(user), applicationKey]) {
+ store.delete(key)
+ store.put(crypto.randomUUID(), `${key}:epoch`)
+ }
+ }
+ }
+ await committed
+ return eligible
+ })
+ expect(await legacyOperation(hasPayload ? "write" : "remove")).toBe(true)
+ expect(await get(blobKey(user))).toBe(hasPayload ? legacyPayload : undefined)
+ const sibling = createIdbPersister(`${user}_other`)
+ await sibling.persistClient(client)
+ const fresh = createIdbPersister(user)
+ expect(await fresh.restoreClient()).toBeUndefined()
+ const qualified = await get<{ version: number; epoch: string }>(`${blobKey(user)}:epoch`)
+ expect(qualified).toEqual({ version: 6, epoch: expect.any(String) })
+ expect(qualified!.epoch).not.toBe(oldScope)
+ expect(await get("alook:qc:device-epoch")).toBe(device)
+ expect(await get(`${namespace}:account-epoch`)).toBe(account)
+ expect(await get(`${namespace}:account-epoch:channels`)).toEqual(fences)
+ expect(await get(applicationKey)).toBe("application payload")
+ expect(await get(`${applicationKey}:epoch`)).toBe(applicationScope)
+ expect(await sibling.restoreClient()).toEqual(client)
+ await fresh.persistClient(client)
+ const before = await get(blobKey(user))
+ for (const operation of ["write", "remove", "channel", "account"] as const) {
+ expect(await legacyOperation(operation)).toBe(false)
+ expect(await get(blobKey(user))).toBe(before)
+ expect(await get("alook:qc:device-epoch")).toBe(device)
+ expect(await get(`${namespace}:account-epoch`)).toBe(account)
+ expect(await get(`${namespace}:account-epoch:channels`)).toEqual(fences)
+ expect(await get(applicationKey)).toBe("application payload")
+ expect(await get(`${applicationKey}:epoch`)).toBe(applicationScope)
+ expect(await sibling.restoreClient()).toEqual(client)
+ }
+ await owner.persistClient({ ...client, timestamp: 99 })
+ await owner.removeClient()
+ await owner.retireChannels(["channel"], true)
+ await owner.retireAccount()
+ expect(await get(blobKey(user))).toBe(before)
+ expect(await get(`${namespace}:account-epoch:channels`)).toEqual(fences)
+ expect(await fresh.isCurrent()).toBe(true)
+ })
+
+ it.each([false, true])("allows two v6 owners to share a valid scope with payload=%s", async (hasPayload) => {
+ const user = `u_two_v6_${hasPayload}`
+ const first = createIdbPersister(user)
+ await first.restoreClient()
+ if (hasPayload) await first.persistClient(client)
+ const scope = await get(`${blobKey(user)}:epoch`)
+ const second = createIdbPersister(user)
+ await second.restoreClient()
+ expect(await get(`${blobKey(user)}:epoch`)).toEqual(scope)
+ expect(await first.isCurrent()).toBe(true)
+ expect(await second.isCurrent()).toBe(true)
+ await first.persistClient(client)
+ expect(await second.restoreClient()).toEqual(client)
+ await second.persistClient({ ...client, timestamp: 2 })
+ expect(await first.restoreClient()).toMatchObject({ timestamp: 2 })
+ })
+})
diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.ts
index b4775a5b1..a2915cbf9 100644
--- a/src/web/src/lib/query-persister.test.ts
+++ b/src/web/src/lib/query-persister.test.ts
@@ -4,6 +4,7 @@ import { del, get, set } from "idb-keyval"
import { QueryClient } from "@tanstack/react-query"
import type { PersistedClient } from "@tanstack/react-query-persist-client"
import { communityKeys } from "@/lib/query-keys"
+import { canonicalChannelRow } from "@/lib/community-db/schema"
import {
PERSIST_BUSTER,
PERSIST_VERSION,
@@ -293,6 +294,32 @@ describe("createIdbPersister — serialize filter", () => {
expect(blob.clientState.queries.map((query) => query.queryKey)).toEqual([])
})
+ it("round trips full nullable raw resources through qualified version 6", async () => {
+ const qc = new QueryClient()
+ const channel = canonicalChannelRow({ id: "dm_1", type: "dm", serverId: null, categoryId: null, name: null, topic: "Raw topic", parentChannelId: null, parentMessageId: null, creatorId: null, position: 0, archived: false, createdAt: "2026-10-11T00:00:00Z", lastMessageAt: null, messageCount: 1, resourceComplete: true })
+ const message = { id: "raw", channelId: channel.id, seq: 1, type: "chat", authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 4, createdAt: channel.createdAt, content: "raw", replyToId: null, clientNonce: "nonce", resourceComplete: true,
+ attachments: [{ id: "second", name: "raw", url: "/raw", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }, { id: "first", name: "image", url: "/image", thumbnailUrl: null, contentType: "image/png", sizeBytes: 1024, width: 20, height: 30 }], embeds: [null, { unsupported: true }] }
+ const data: Record<string, unknown[]> = {
+ channels: [channel], messages: [message],
+ profiles: [{ id: "peer", name: "Peer", discriminator: "0002", avatar: null, avatarVersion: 4, identityComplete: true }],
+ channelMemberships: [{ id: "dm_1:u_1:access", channelId: "dm_1", userId: "u_1", relation: "access" }],
+ }
+ const keys = Object.entries(data).map(([name, rows]) => {
+ const key = communityKeys.communityDbCollection("u_1", name)
+ qc.setQueryData(key, rows)
+ return key
+ })
+ const owner = createIdbPersister("u_1")
+ await owner.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { mutations: [], queries: keys.map((queryKey) => ({ queryKey, queryHash: JSON.stringify(queryKey), state: qc.getQueryState(queryKey)! })) } })
+ const raw = JSON.parse((await get<string>("alook:qc:cache:u_1:client"))!)
+ expect(raw.version).toBe(6)
+ const restored = await createIdbPersister("u_1").restoreClient()
+ const collection = (name: string) => restored!.clientState.queries.find((query) => query.queryKey[3] === name)!.state.data
+ expect(collection("channels")).toEqual([expect.objectContaining(channel)])
+ expect(collection("messages")).toEqual([message])
+ expect(collection("profiles")).toEqual(data.profiles)
+ })
+
it("windows canonical server trees, message tails, and referenced profiles", async () => {
const qc = new QueryClient()
const detailKeys = Array.from({ length: 7 }, (_, index) => communityKeys.server(`srv_${index}`))
@@ -333,12 +360,13 @@ describe("createIdbPersister — serialize filter", () => {
...(scopeIndex === MAX_PERSISTED_MESSAGE_SCOPES + 1
&& messageIndex === MAX_PERSISTED_MESSAGES_PER_SCOPE ? {
approval: {
- otherProfile: { id: "approval_other" },
- botProfile: { id: "approval_bot" },
- waitingOnProfile: { id: "approval_waiting" },
+ friendshipId: "friendship", status: "pending", waitingOn: "you",
+ otherProfile: { id: "approval_other", name: "Other", discriminator: "0001", image: null, avatarVersion: 0 },
+ botProfile: { id: "approval_bot", name: "Bot", discriminator: "0001", image: null, avatarVersion: 0 },
+ waitingOnProfile: { id: "approval_waiting", name: "Owner", discriminator: "0001", image: null, avatarVersion: 0 },
},
- replyTo: { authorId: "reply_author" },
- thread: { participants: [{ id: "thread_participant" }] },
+ replyTo: { id: "reply", authorId: "reply_author", authorName: "Reply", text: "Prior" },
+ thread: { id: "thread", name: "Thread", messageCount: 0, participants: [{ id: "thread_participant", name: "Participant", avatar: "P", avatarVersion: 0 }] },
} : {}),
}))
)), {
@@ -392,33 +420,33 @@ describe("createIdbPersister — serialize filter", () => {
messages,
profiles: [
...Array.from({ length: MAX_PERSISTED_MESSAGE_SCOPES + 2 }, (_, index) => ({
- userId: `author_${index}`,
+ id: `author_${index}`,
name: `Author ${index}`,
discriminator: "0001",
avatar: "A",
- avatarVersion: 0,
+ avatarVersion: 0, identityComplete: true,
})),
...Array.from({ length: 7 }, (_, index) => ({
- userId: `owner_${index}`,
+ id: `owner_${index}`,
name: `Owner ${index}`,
discriminator: "0001",
avatar: "O",
- avatarVersion: 0,
+ avatarVersion: 0, identityComplete: true,
})),
...[
"approval_other", "approval_bot", "approval_waiting", "reply_author",
"thread_participant", "dm_peer", "roster_only", "notify_only",
].map(
(userId) => ({
- userId,
+ id: userId,
name: userId,
discriminator: "0001",
avatar: "P",
- avatarVersion: 0,
+ avatarVersion: 0, identityComplete: true,
}),
),
- { userId: "u_1", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0 },
- { userId: "orphan", name: "Orphan", discriminator: "0001", avatar: "O", avatarVersion: 0 },
+ { id: "u_1", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0, identityComplete: true },
+ { id: "orphan", name: "Orphan", discriminator: "0001", avatar: "O", avatarVersion: 0, identityComplete: true },
],
serverMemberships: [
{ id: "srv_6:u_1", serverId: "srv_6", userId: "u_1", role: "member", viewer: true },
@@ -496,8 +524,8 @@ describe("createIdbPersister — serialize filter", () => {
).map((row) => row.serverId)).toEqual([
"srv_0", "srv_1", "srv_2", "srv_3", "srv_4", "srv_5", "srv_6",
])
- const profileIds = new Set((collection("profiles") as Array<{ userId: string }>).map(
- (row) => row.userId,
+ const profileIds = new Set((collection("profiles") as Array<{ id: string }>).map(
+ (row) => row.id,
))
expect(profileIds.has("orphan")).toBe(false)
expect(profileIds.has("u_1")).toBe(true)
@@ -532,6 +560,8 @@ describe("createIdbPersister — serialize filter", () => {
})
it("drops malformed shell payloads during deserialize scrub", async () => {
+ const owner = createIdbPersister("u_1")
+ await owner.restoreClient()
const qc = new QueryClient()
qc.setQueryData(communityKeys.servers(), { nope: [] })
qc.setQueryData(communityKeys.server("srv_1"), { id: "other", categories: [] })
@@ -592,6 +622,8 @@ describe("createIdbPersister — serialize filter", () => {
},
],
])("drops a malformed %s query as one unit during restore", async (_label, queryKey, data) => {
+ const owner = createIdbPersister("u_1")
+ await owner.restoreClient()
const qc = new QueryClient()
qc.setQueryData(queryKey, data)
const injected: PersistedClient = {
diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.ts
index baa05cd22..eb5101888 100644
--- a/src/web/src/lib/query-persister.ts
+++ b/src/web/src/lib/query-persister.ts
@@ -15,7 +15,7 @@ import {
type CommunityCollectionRows,
} from "@/lib/community-db/schema"
-export const PERSIST_VERSION = 5
+export const PERSIST_VERSION = 6
export const PERSIST_BUSTER = String(PERSIST_VERSION)
export const PERSIST_CACHE_PREFIX = "alook:qc:cache"
const IDB_PREFIX = PERSIST_CACHE_PREFIX
@@ -174,7 +174,7 @@ function scrubDehydratedClient(
attentionScopes,
attentionItems: retainedAttentionItems,
profiles: rows("profiles").filter(
- (row) => referencedProfileIds.has(row.userId),
+ (row) => referencedProfileIds.has(row.id),
),
}
for (const q of client.clientState.queries) {
@@ -255,6 +255,13 @@ 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)
)
+function communityScopeEpoch(value: unknown): string | undefined {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined
+ const scope = value as Record<string, unknown>
+ return Object.keys(scope).length === 2 && scope.version === PERSIST_VERSION && isEpoch(scope.epoch)
+ ? scope.epoch : undefined
+}
+
async function cacheTransaction<T>(
mode: IDBTransactionMode,
operation: (store: IDBObjectStore) => Promise<T>,
@@ -289,15 +296,14 @@ function qualifyPersister(key: string, userId: string | null): Promise<PersistEl
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 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()
+ const currentScope = communityScopeEpoch(current.scope)
+ const compatiblePayload = raw === undefined || Boolean(decodeDiskSnapshot(raw))
+ let scope = currentScope && compatiblePayload ? currentScope : crypto.randomUUID()
if (!intact) {
for (const domain of ["community", "application"] as const) {
const payloadKey = blobKeyFor(userId, domain)
@@ -309,9 +315,9 @@ function qualifyPersister(key: string, userId: string | null): Promise<PersistEl
store.put(account, accountEpochKey(userId))
store.put(channels, channelFenceKey(userId))
}
- if (!isEpoch(current.device) || !isEpoch(current.scope)) store.delete(key)
+ if (!isEpoch(current.device) || !currentScope || !compatiblePayload) store.delete(key)
if (!isEpoch(current.device)) store.put(device, DEVICE_EPOCH_KEY)
- store.put(scope, scopeEpochKey(key))
+ store.put({ version: PERSIST_VERSION, epoch: scope }, scopeEpochKey(key))
return { device, scope, account, channels }
})
}
@@ -327,7 +333,7 @@ async function withEligiblePersister<T>(
const expected = await eligibility
return cacheTransaction(mode, async (store) => {
const current = await readEligibility(store, key, userId)
- if (current.device !== expected.device || current.scope !== expected.scope || current.account !== expected.account || !isChannelFences(current.channels)) return staleValue
+ if (current.device !== expected.device || communityScopeEpoch(current.scope) !== expected.scope || current.account !== expected.account || !isChannelFences(current.channels)) return staleValue
return operation(store, current.channels, expected.channels)
})
}
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 825dcdf3a..a95ad285b 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import {
COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,
+ admitCommunityBrowserEventBatch,
decodeCommunityBrowserEvent,
decodeCommunityBrowserEventBatch,
deriveCommunityDeliveryOperationId,
@@ -8,6 +9,7 @@ import {
encodeCommunityBrowserEventBatchForContract,
prepareCommunityDeliveryEvents,
type CommunityWsEvent,
+ type CommunityContract,
type WsMessage,
} from "@alook/shared"
import type { UseUserWsOptions } from "./use-user-ws"
@@ -257,7 +259,7 @@ describe("useUserWs", () => {
})
async function mountHook(
- onMessage: (msg: WsMessage, assertCurrent?: () => void) => void | Promise<void>,
+ onMessage: (msg: WsMessage, assertCurrent?: () => void, communityContract?: CommunityContract) => void | Promise<void>,
options?: UseUserWsOptions,
) {
// Re-import to get fresh module with fresh mocks
@@ -320,7 +322,7 @@ describe("useUserWs", () => {
await flushPromises()
expect(callback).not.toHaveBeenCalled()
ws.simulateMessage(legacyMembership)
- expect(callback).toHaveBeenCalledExactlyOnceWith(legacyMembership)
+ expect(callback).toHaveBeenCalledExactlyOnceWith(legacyMembership, undefined, 1)
})
it.each([undefined, 1] as const)("rejects an entire legacy batch containing a new membership child without V2 confirmation (%s)", async (contract) => {
@@ -336,7 +338,7 @@ describe("useUserWs", () => {
await flushPromises()
expect(callback).not.toHaveBeenCalled()
ws.simulateMessage(compatibleBatch)
- expect(callback).toHaveBeenCalledExactlyOnceWith(compatibleBatch)
+ expect(callback).toHaveBeenCalledExactlyOnceWith(compatibleBatch, undefined, 1)
})
it("admits new representations and older producer frames after V2 confirmation", async () => {
@@ -364,6 +366,104 @@ describe("useUserWs", () => {
expect(received).toEqual([explicitMembership, legacyMembership, oldBatch, newBatch.batch])
})
+ const resourceMessage = {
+ type: "community:message.create", channelId: "channel-1", serverId: "server-1",
+ message: {
+ id: "resource-message", channelId: "channel-1", seq: 1, type: "chat", authorId: "user-1", authorName: "User", authorAvatarVersion: 4,
+ createdAt: "2026-10-11T00:00:00Z", content: "actual body", replyToId: null, clientNonce: null,
+ attachments: [{ id: "a1", name: "file", url: "/file", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }],
+ embeds: [null, { unsupported: true }],
+ },
+ } as const
+
+ async function resourceBatch() {
+ const prepared = await prepareCommunityDeliveryEvents([resourceMessage], 3)
+ if (!prepared.ok) throw new Error("invalid resource regression event")
+ const encoded = await encodeCommunityBrowserEventBatchForContract({
+ operationId: await deriveCommunityDeliveryOperationId("protocol-regression-v3"),
+ prepared: prepared.prepared, contract: 3,
+ })
+ if (!encoded.ok) throw new Error("invalid resource regression batch")
+ expect((await admitCommunityBrowserEventBatch(encoded.batch)).ok).toBe(true)
+ return encoded.batch
+ }
+
+ async function mountResourceConnection() {
+ setupTokenFetch()
+ const received: CommunityWsEvent[] = []
+ const callback = vi.fn(async (message: WsMessage, assertCurrent?: () => void, contract?: CommunityContract) => {
+ expect(contract).toBe(3)
+ if (message.type === "community:events.batch.v3") {
+ const admitted = await admitCommunityBrowserEventBatch(message)
+ if (!admitted.ok) throw new Error("invalid resource batch")
+ assertCurrent?.()
+ received.push(...admitted.batch.events)
+ } else {
+ const decoded = decodeCommunityBrowserEvent(message, 3)
+ if (!decoded.ok) throw new Error("invalid resource event")
+ assertCurrent?.()
+ received.push(decoded.event)
+ }
+ })
+ const onAuthenticated = vi.fn()
+ await mountHook(callback, { communityContract: 3, requestDaemonStatusOnAuth: false, onAuthenticated })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ expect(JSON.parse(ws.sent[0]!)).toEqual({ type: "auth", token: "tok-123", communityContract: 3 })
+ return { ws, callback, received, onAuthenticated }
+ }
+
+ it("requests and positively confirms explicit v3 before real resource admission", async () => {
+ const batch = await resourceBatch()
+ const { ws, callback, received, onAuthenticated } = await mountResourceConnection()
+ ws.simulateMessage(batch)
+ await flushPromises()
+ expect(callback).not.toHaveBeenCalled()
+ ws.simulateMessage({ type: "auth.ok", communityContract: 3 })
+ expect(onAuthenticated).toHaveBeenCalledOnce()
+ ws.simulateMessage(resourceMessage)
+ ws.simulateMessage(batch)
+ await vi.waitFor(() => expect(received).toEqual([resourceMessage, resourceMessage]))
+ expect(callback).toHaveBeenLastCalledWith(batch, expect.any(Function), 3)
+ expect(ws.closed).toBe(false)
+ })
+
+ it.each([undefined, 1, 2, 4] as const)("rejects mismatched or unknown explicit v3 confirmation %s", async confirmed => {
+ const { ws, callback, received, onAuthenticated } = await mountResourceConnection()
+ ws.simulateMessage({ type: "auth.ok", ...(confirmed === undefined ? {} : { communityContract: confirmed }) })
+ expect(ws.closed).toBe(true)
+ expect(onAuthenticated).not.toHaveBeenCalled()
+ ws.simulateMessage(resourceMessage)
+ await flushPromises()
+ expect(callback).not.toHaveBeenCalled()
+ expect(received).toEqual([])
+ })
+
+ it("rejects v2 representations on explicit v3 while retaining valid resource delivery", async () => {
+ const prepared = await prepareCommunityDeliveryEvents([legacyMembership], 2)
+ if (!prepared.ok) throw new Error("invalid legacy regression event")
+ const oldBatch = await encodeCommunityBrowserEventBatchForContract({
+ operationId: await deriveCommunityDeliveryOperationId("protocol-v2-on-v3"), prepared: prepared.prepared, contract: 2,
+ })
+ if (!oldBatch.ok) throw new Error("invalid legacy regression batch")
+ const batch = await resourceBatch()
+ const { ws, callback, received } = await mountResourceConnection()
+ ws.simulateMessage({ type: "auth.ok", communityContract: 3 })
+ ws.simulateMessage(oldBatch.batch)
+ await flushPromises()
+ expect(callback).not.toHaveBeenCalled()
+ const { channelId: _channel, attachments: _attachments, replyToId: _reply, clientNonce: _nonce, ...legacyMessage } = resourceMessage.message
+ const oldSingle = { ...resourceMessage, message: legacyMessage }
+ expect(decodeCommunityBrowserEvent(oldSingle, 2).ok).toBe(true)
+ expect(decodeCommunityBrowserEvent(oldSingle, 3).ok).toBe(false)
+ ws.simulateMessage(oldSingle)
+ await flushPromises()
+ expect(received).toEqual([])
+ ws.simulateMessage(batch)
+ await vi.waitFor(() => expect(received).toEqual([resourceMessage]))
+ expect(ws.closed).toBe(false)
+ })
+
it("preserves frame order behind asynchronous v2 admission", async () => {
setupTokenFetch()
let release!: () => void
@@ -583,7 +683,7 @@ describe("useUserWs", () => {
// Deliver a message — should go to cb1
ws.simulateMessage({ type: "test", data: "hello" })
- expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" })
+ expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" }, undefined, 1)
// Now simulate a re-render with a new callback by updating the ref directly
// In real React, the hook body runs `onMessageRef.current = onMessage` on each render
@@ -594,7 +694,7 @@ describe("useUserWs", () => {
if (onMessageRef) onMessageRef.current = cb2
ws.simulateMessage({ type: "test", data: "world" })
- expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" })
+ expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" }, undefined, 1)
expect(cb1).toHaveBeenCalledTimes(1) // cb1 not called again
})
@@ -2417,7 +2517,7 @@ describe("useUserWs", () => {
ws.simulateMessage({ type: "auth.ok" })
ws.simulateMessage({ type: "task.updated", taskId: "after" })
- expect(onMessage).toHaveBeenCalledWith({ type: "task.updated", taskId: "after" })
+ expect(onMessage).toHaveBeenCalledWith({ type: "task.updated", taskId: "after" }, undefined, 1)
})
it("does not report an access disconnect for a socket that never authenticated", async () => {
@@ -2468,7 +2568,7 @@ describe("useUserWs", () => {
ws.simulateMessage({ type: "auth.ok" })
const valid = { type: "email.received", agentId: "agent-1" }
ws.simulateMessage(valid)
- expect(onMessage).toHaveBeenCalledWith(valid)
+ expect(onMessage).toHaveBeenCalledWith(valid, undefined, 1)
})
it("consumes the raw pong liveness response without reporting a dropped frame", async () => {
@@ -2659,7 +2759,7 @@ describe("useUserWs", () => {
payload: "x".repeat(70_000),
}
ws.simulateMessage(legalLargeBatch)
- expect(onMessage).toHaveBeenCalledWith(legalLargeBatch)
+ expect(onMessage).toHaveBeenCalledWith(legalLargeBatch, undefined, 1)
onMessage.mockClear()
ws.simulateRawMessage(JSON.stringify({
@@ -2670,6 +2770,6 @@ describe("useUserWs", () => {
const generic = { type: "task.updated", payload: "x".repeat(65_536) }
ws.simulateMessage(generic)
- expect(onMessage).toHaveBeenCalledWith(generic)
+ expect(onMessage).toHaveBeenCalledWith(generic, undefined, 1)
})
})
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index c544bda45..03845a6da 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -129,6 +129,7 @@ export type WsMessageIncoming = WsMessage & { [key: string]: unknown }
export type UserWsConnectionPhase = "authenticated" | "reconnecting" | "suspended"
export type UseUserWsOptions = {
+ communityContract?: CommunityContract
onReconnect?: (info: { reconnectDurationMs: number }) => void | Promise<void>
onDisconnect?: () => void | Promise<void>
onAuthenticated?: () => void | Promise<void>
@@ -171,13 +172,14 @@ function reportDroppedFrame(
}
export function useUserWs(
- onMessage: (msg: WsMessageIncoming, assertCurrent?: () => void) => void | Promise<void>,
+ onMessage: (msg: WsMessageIncoming, assertCurrent?: () => void, communityContract?: CommunityContract) => void | Promise<void>,
options?: UseUserWsOptions,
): { send: (msg: object) => void; reconnectNow: () => void } {
const wsRef = useRef<WebSocket | null>(null)
const reconnectDelay = useRef(WS_RECONNECT_INIT)
const reconnectAttemptRef = useRef(0)
const onMessageRef = useRef(onMessage)
+ const requestedCommunityContractRef = useRef(options?.communityContract ?? COMMUNITY_CONTRACT_VERSION)
const onReconnectRef = useRef(options?.onReconnect)
const onDisconnectRef = useRef(options?.onDisconnect)
const onAuthenticatedRef = useRef(options?.onAuthenticated)
@@ -216,7 +218,8 @@ export function useUserWs(
useEffect(() => {
onMessageRef.current = onMessage
- }, [onMessage])
+ requestedCommunityContractRef.current = options?.communityContract ?? COMMUNITY_CONTRACT_VERSION
+ }, [onMessage, options?.communityContract])
useEffect(() => {
onReconnectRef.current = options?.onReconnect
@@ -612,6 +615,7 @@ export function useUserWs(
}
let communityContract: CommunityContract = 1
+ const requestedCommunityContract = requestedCommunityContractRef.current
let communityAdmission = Promise.resolve()
let pendingAdmissions = 0
let ws: WebSocket
@@ -651,7 +655,7 @@ export function useUserWs(
openedAt = Date.now()
reportOpenStage("success")
try {
- ws.send(JSON.stringify({ type: "auth", token: authToken, communityContract: COMMUNITY_CONTRACT_VERSION }))
+ ws.send(JSON.stringify({ type: "auth", token: authToken, communityContract: requestedCommunityContract }))
} catch {
reportAuthStage("failure")
reportAuthFailure("network")
@@ -716,7 +720,14 @@ export function useUserWs(
reportDroppedFrame("duplicate-auth-ok", msg)
return
}
- communityContract = msg.communityContract === COMMUNITY_CONTRACT_VERSION ? COMMUNITY_CONTRACT_VERSION : 1
+ const confirmed = msg.communityContract ?? 1
+ if ((confirmed !== 1 && confirmed !== 2 && confirmed !== 3)
+ || (confirmed !== requestedCommunityContract && !(confirmed === 1 && requestedCommunityContract === 2))) {
+ reportDroppedFrame("invalid-payload", msg)
+ ws.close(1008, "Community contract confirmation mismatch")
+ return
+ }
+ communityContract = confirmed
reportAuthStage("success")
authenticatedGenerationRef.current = generation
if (connectTimeoutRef.current !== null) {
@@ -770,30 +781,30 @@ 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"))
- )) {
+ if ((isCommunityBatch && msg.type !== communityBrowserEventBatchType(communityContract)
+ && !(communityContract === 2 && msg.type === communityBrowserEventBatchType(1)))
+ || (communityContract === 1 && (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 ((isCommunityBatch && msg.type !== communityBrowserEventBatchType(1)) || 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)
+ await callback(msg as WsMessageIncoming, assertAdmissionCurrent, communityContract)
}).catch(() => { reportDroppedFrame("invalid-payload", msg) }).finally(() => { pendingAdmissions-- })
return
}
try {
- const callbackResult = callback(msg as WsMessageIncoming)
+ const callbackResult = callback(msg as WsMessageIncoming, undefined, communityContract)
if (callbackResult) void callbackResult.catch(() => reportDroppedFrame("invalid-payload", msg))
} catch {
console.warn("[ws] message callback threw", {
diff --git a/src/ws-do/src/community-browser-event-ingress.ts b/src/ws-do/src/community-browser-event-ingress.ts
index 6a55ab03b..a2d00cdc1 100644
--- a/src/ws-do/src/community-browser-event-ingress.ts
+++ b/src/ws-do/src/community-browser-event-ingress.ts
@@ -1,5 +1,7 @@
import {
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
+ COMMUNITY_CONTRACT_HEADER,
+ type CommunityContract,
MESSAGE_DELIVERY_BODY_MAX_BYTES,
MESSAGE_DELIVERY_MAX_EVENTS_PER_USER,
COMMUNITY_USER_TARGET_PATH_PREFIX,
@@ -29,6 +31,7 @@ type CommunityBrowserEventIngressSuccess = {
envelope: CommunityWsEvent
body: string
byteCount: number
+ contract: CommunityContract
}
export type CommunityBrowserEventIngressResult =
@@ -94,10 +97,11 @@ export async function readBoundedJsonRequest(
export function normalizeCommunityBrowserEvent(
value: unknown,
byteCount?: number,
+ contract: CommunityContract = 2,
): CommunityBrowserEventIngressResult {
- const decoded = decodeCommunityBrowserEvent(value)
+ const decoded = decodeCommunityBrowserEvent(value, contract)
if (!decoded.ok) return { ...decoded, ok: false, ...(byteCount === undefined ? {} : { byteCount }) }
- const encoded = encodeCommunityBrowserEvent(decoded.event)
+ const encoded = encodeCommunityBrowserEvent(decoded.event, contract)
if (!encoded.ok) {
return {
ok: false,
@@ -112,6 +116,7 @@ export function normalizeCommunityBrowserEvent(
envelope: encoded.event,
body: encoded.body,
byteCount: encoded.byteLength,
+ contract,
}
}
@@ -120,7 +125,9 @@ export async function readCommunityBrowserEventRequest(
): Promise<CommunityBrowserEventIngressResult> {
const parsed = await readBoundedJsonRequest(request, COMMUNITY_BROWSER_EVENT_MAX_BYTES)
if (!parsed.ok) return parsed
- return normalizeCommunityBrowserEvent(parsed.value, parsed.byteCount)
+ const version = request.headers.get(COMMUNITY_CONTRACT_HEADER)
+ if (version !== null && version !== "1" && version !== "2" && version !== "3") return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
+ return normalizeCommunityBrowserEvent(parsed.value, parsed.byteCount, version === "3" ? 3 : version === "1" ? 1 : 2)
}
export async function readCommunityBrowserEventBundleRequest(
@@ -141,7 +148,7 @@ export async function readCommunityBrowserEventBundleRequest(
typeof parsed.value !== "object"
|| parsed.value === null
|| Array.isArray(parsed.value)
- || Object.keys(parsed.value).length !== 3
+ || Object.keys(parsed.value).length !== ("communityContract" in parsed.value && parsed.value.communityContract === 3 ? 4 : 3)
|| !Object.prototype.hasOwnProperty.call(parsed.value, "operationId")
|| !Object.prototype.hasOwnProperty.call(parsed.value, "operationDigest")
|| !Object.prototype.hasOwnProperty.call(parsed.value, "events")
@@ -149,12 +156,14 @@ export async function readCommunityBrowserEventBundleRequest(
return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
}
const input = parsed.value as {
+ communityContract?: unknown
operationId?: unknown
operationDigest?: unknown
events?: unknown
}
if (
- !isCommunityDeliveryOperationId(input.operationId)
+ (Object.hasOwn(input, "communityContract") && input.communityContract !== 3)
+ || !isCommunityDeliveryOperationId(input.operationId)
|| !isCommunityDeliveryDigest(input.operationDigest)
) {
return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
@@ -167,7 +176,7 @@ export async function readCommunityBrowserEventBundleRequest(
) {
return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
}
- const prepared = await prepareCommunityDeliveryEvents(events)
+ const prepared = await prepareCommunityDeliveryEvents(events, input.communityContract === 3 ? 3 : 2)
if (!prepared.ok || prepared.prepared.digest !== input.operationDigest) {
return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
}
diff --git a/src/ws-do/src/internal-user-broadcast.test.ts b/src/ws-do/src/internal-user-broadcast.test.ts
new file mode 100644
index 000000000..c1af3d59e
--- /dev/null
+++ b/src/ws-do/src/internal-user-broadcast.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest"
+import { createInternalCommunityUserBundleRequest, getInternalCommunityUserTarget } from "./internal-user-broadcast"
+
+describe("internal community bundle request", () => {
+ it("defaults to the legacy contract while keeping the target and operation intact", async () => {
+ const events = [{ type: "community:presence.update", userId: "peer", online: true }]
+ const request = createInternalCommunityUserBundleRequest("viewer/你好", "operation", "digest", events)
+ expect(request.url).toBe("http://internal/community-broadcast-bundle")
+ expect(request.method).toBe("POST")
+ expect(request.headers.get("content-type")).toBe("application/json")
+ expect(getInternalCommunityUserTarget(request)).toBe("viewer/你好")
+ expect(await request.json()).toEqual({ operationId: "operation", operationDigest: "digest", events })
+ expect(await createInternalCommunityUserBundleRequest("viewer", "operation", "digest", events, 3).json())
+ .toEqual({ operationId: "operation", operationDigest: "digest", events, communityContract: 3 })
+ })
+})
diff --git a/src/ws-do/src/internal-user-broadcast.ts b/src/ws-do/src/internal-user-broadcast.ts
index 2e707863e..8ae01b07a 100644
--- a/src/ws-do/src/internal-user-broadcast.ts
+++ b/src/ws-do/src/internal-user-broadcast.ts
@@ -1,5 +1,7 @@
import {
encodeCommunityBrowserEvent,
+ COMMUNITY_CONTRACT_HEADER,
+ type CommunityContract,
isCommunityEventCandidate,
} from "@alook/shared"
@@ -29,11 +31,13 @@ export function createInternalUserBroadcastRequest(
export function createInternalCommunityUserBroadcastRequest(
targetUserId: string,
body: BodyInit | null,
+ contract: CommunityContract = 2,
): Request {
const headers = new Headers({
"content-type": "application/json",
[INTERNAL_USER_TARGET_HEADER]: encodeURIComponent(targetUserId),
})
+ if (contract === 3) headers.set(COMMUNITY_CONTRACT_HEADER, "3")
return new Request("http://internal/community-broadcast", {
method: "POST",
headers,
@@ -46,6 +50,7 @@ export function createInternalCommunityUserBundleRequest(
operationId: string,
operationDigest: string,
events: readonly unknown[],
+ contract: CommunityContract = 2,
): Request {
const headers = new Headers({
"content-type": "application/json",
@@ -54,7 +59,7 @@ export function createInternalCommunityUserBundleRequest(
return new Request("http://internal/community-broadcast-bundle", {
method: "POST",
headers,
- body: JSON.stringify({ operationId, operationDigest, events }),
+ body: JSON.stringify({ operationId, operationDigest, events, ...(contract === 3 ? { communityContract: 3 } : {}) }),
})
}
diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.ts
index 65e7f272f..8252fe68a 100644
--- a/src/ws-do/src/routes/broadcast.ts
+++ b/src/ws-do/src/routes/broadcast.ts
@@ -1,7 +1,9 @@
import type { RouterContext } from "../router-context"
import {
COMMUNITY_BULK_BODY_MAX_BYTES,
+ COMMUNITY_CONTRACT_HEADER,
isValidCommunityUserTarget,
+ type CommunityContract,
} from "@alook/shared"
import {
createInternalCommunityUserBroadcastRequest,
@@ -105,10 +107,11 @@ async function broadcastCommunityToBulkTarget(
env: Env,
userId: string,
messageBody: string,
+ contract: CommunityContract,
): Promise<BulkTargetResult> {
const doId = env.WS_DO.idFromName("user:" + userId)
const stub = env.WS_DO.get(doId)
- const response = await stub.fetch(createInternalCommunityUserBroadcastRequest(userId, messageBody))
+ const response = await stub.fetch(createInternalCommunityUserBroadcastRequest(userId, messageBody, contract))
if (!response.ok) return { ok: false, failureKind: "non-ok", status: response.status }
let payload: unknown
try {
@@ -168,7 +171,7 @@ export async function handleCommunityUserBroadcast({ request, env, url, traceId,
reqLog.debug("broadcasting community event to user")
const doId = env.WS_DO.idFromName("user:" + target.target)
const stub = env.WS_DO.get(doId)
- return stub.fetch(createInternalCommunityUserBroadcastRequest(target.target, event.body))
+ return stub.fetch(createInternalCommunityUserBroadcastRequest(target.target, event.body, event.contract))
}
export async function handleUsersBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
@@ -291,7 +294,9 @@ export async function handleCommunityUsersBroadcast({ request, env, url, traceId
logCommunityBrowserEventRejected(log, "strict-bulk", failure, body.userIds.length)
return invalidCommunityBrowserEventResponse(failure)
}
- const event = normalizeCommunityBrowserEvent(body.message)
+ const version = request.headers.get(COMMUNITY_CONTRACT_HEADER)
+ if (version !== null && version !== "1" && version !== "2" && version !== "3") return invalidCommunityBrowserEventResponse(strictFailure("invalid-payload", parsed.byteCount))
+ const event = normalizeCommunityBrowserEvent(body.message, undefined, version === "3" ? 3 : version === "1" ? 1 : 2)
if (!event.ok) {
logCommunityBrowserEventRejected(log, "strict-bulk", event, body.userIds.length)
return invalidCommunityBrowserEventResponse(event)
@@ -319,7 +324,7 @@ export async function handleCommunityUsersBroadcast({ request, env, url, traceId
active += 1
maxActive = Math.max(maxActive, active)
try {
- return await broadcastCommunityToBulkTarget(env, userId, event.body)
+ return await broadcastCommunityToBulkTarget(env, userId, event.body, event.contract)
} finally {
active -= 1
}
diff --git a/src/ws-do/src/routes/message-delivery.ts b/src/ws-do/src/routes/message-delivery.ts
index f853cf67a..0e375ba83 100644
--- a/src/ws-do/src/routes/message-delivery.ts
+++ b/src/ws-do/src/routes/message-delivery.ts
@@ -36,8 +36,9 @@ async function deliverTarget(
userId: string,
events: CommunityWsEvent[],
operationId: CommunityDeliveryOperationId,
+ contract: 2 | 3,
): Promise<TargetResult> {
- const prepared = await prepareCommunityDeliveryEvents(events)
+ const prepared = await prepareCommunityDeliveryEvents(events, contract)
if (!prepared.ok) return { ok: false, kind: "invalid-receipt" }
try {
const id = env.WS_DO.idFromName(`user:${userId}`)
@@ -47,6 +48,7 @@ async function deliverTarget(
operationId,
prepared.prepared.digest,
prepared.prepared.envelopes,
+ contract,
),
)
if (!response.ok) return { ok: false, kind: "non-ok" }
@@ -180,7 +182,7 @@ export async function handleMessageDelivery(
const startedAt = Date.now()
const results = await settleInBatches(
entries,
- ([userId, events]) => deliverTarget(env, userId, events, operationId),
+ ([userId, events]) => deliverTarget(env, userId, events, operationId, batch.communityContract ?? 2),
targetBatchSize,
)
const failedUserIds: string[] = []
diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.ts
index b0e0285f8..21d3eb4f6 100644
--- a/src/ws-do/src/ws-durable/user-auth.test.ts
+++ b/src/ws-do/src/ws-durable/user-auth.test.ts
@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
deriveCommunityDeliveryOperationId,
prepareCommunityDeliveryEvents,
+ decodeCommunityBrowserEventBatch,
+ utf8ByteLength,
} from "@alook/shared"
import { createMockWebSocket } from "../__mocks__/cf"
import { handleUpgrade } from "../routes/upgrade"
@@ -189,9 +191,9 @@ describe("WebSocketDurableObject", () => {
async function requestFor(
inputEvents: readonly unknown[] = events,
- overrides: { operationId?: string; operationDigest?: string } = {},
+ overrides: { operationId?: string; operationDigest?: string; contract?: 2 | 3 } = {},
): Promise<Request> {
- const prepared = await prepareCommunityDeliveryEvents(inputEvents)
+ const prepared = await prepareCommunityDeliveryEvents(inputEvents, overrides.contract ?? 2)
if (!prepared.ok) throw new Error(`invalid fixture: ${prepared.reason}`)
return new Request("http://internal/community-broadcast-bundle", {
method: "POST",
@@ -200,6 +202,7 @@ describe("WebSocketDurableObject", () => {
operationId: overrides.operationId ?? await deriveCommunityDeliveryOperationId("m-1"),
operationDigest: overrides.operationDigest ?? prepared.prepared.digest,
events: prepared.prepared.envelopes,
+ ...(overrides.contract === 3 ? { communityContract: 3 } : {}),
}),
})
}
@@ -331,6 +334,97 @@ describe("WebSocketDurableObject", () => {
expect(current.send).toHaveBeenCalledTimes(1)
})
+ const resourceEvents = [
+ { ...events[0], message: {
+ ...events[0]!.message,
+ channelId: "ch-1", authorAvatar: null, replyToId: null, clientNonce: null,
+ attachments: [
+ { id: "att-b", name: "é 😀.bin", url: "/b", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
+ { id: "att-a", name: "photo.png", url: "/a", thumbnailUrl: "/thumb", contentType: "image/png", sizeBytes: 1024, width: 640, height: 480 },
+ ],
+ embeds: [null, { unknown: "raw" }, { title: "é 😀", fields: [{ name: "key", value: "value", inline: true }] }],
+ } },
+ ...events.slice(1),
+ ]
+
+ it("delivers exact resource data to 1/2/3 sockets and restores source progress after reconstruction", async () => {
+ const { durable, ctx, env } = createDO()
+ const sockets = [1, 2, 3].map((communityContract) => {
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract })
+ return ws
+ })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(sockets)
+ const request = await requestFor(resourceEvents, { contract: 3 })
+ const source = await request.clone().json() as { operationId: string; operationDigest: string; events: unknown[] }
+ expect((await durable.fetch(request.clone())).status).toBe(200)
+ for (const [index, ws] of sockets.entries()) {
+ const frame = ws.send.mock.calls[0]![0] as string
+ const decoded = await decodeCommunityBrowserEventBatch(JSON.parse(frame))
+ expect(decoded.ok).toBe(true)
+ if (index === 2 && decoded.ok) expect(decoded.events).toEqual(source.events)
+ expect(utf8ByteLength(frame)).toBe(new TextEncoder().encode(frame).byteLength)
+ expect(JSON.parse(frame).type).toBe(index === 0 ? "community:events.batch" : `community:events.batch.v${index + 1}`)
+ expect(ws.deserializeAttachment()).toMatchObject({ communityDeliveryProgress: [[source.operationId, source.operationDigest, 1, 1]] })
+ ws.send.mockClear()
+ }
+ const encoded = await prepareCommunityDeliveryEvents(resourceEvents, 3)
+ expect(encoded.ok && encoded.prepared.envelopes).toEqual(source.events)
+ const { WebSocketDurableObject } = await import("../ws-durable")
+ const restored = new WebSocketDurableObject(ctx, env)
+ const retry = await restored.fetch(request)
+ expect(retry.status).toBe(200)
+ await expect(retry.json()).resolves.toMatchObject({ operationDigest: source.operationDigest, alreadyEnqueued: 3, attempted: 0 })
+ for (const ws of sockets) expect(ws.send).not.toHaveBeenCalled()
+ })
+
+ it("retries the original three-key payload after reconstruction and rejects a rebuilt cross-version operation before any frame or progress change", async () => {
+ const { durable, ctx, env } = createDO()
+ const completed = createMockWebSocket(), retrying = createMockWebSocket()
+ completed.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 1 })
+ retrying.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 2 })
+ retrying.send.mockImplementationOnce(() => { throw new Error("transient send") })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying])
+ const original = await requestFor()
+ const originalBody = await original.clone().text()
+ expect(Object.keys(JSON.parse(originalBody))).toEqual(["operationId", "operationDigest", "events"])
+ expect((await durable.fetch(original.clone())).status).toBe(503)
+ const saved = [completed, retrying].map((ws) => ws.deserializeAttachment())
+ completed.send.mockClear()
+ retrying.send.mockClear()
+ const unstarted = createMockWebSocket()
+ unstarted.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 3 })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying, unstarted])
+ const { WebSocketDurableObject } = await import("../ws-durable")
+ const restored = new WebSocketDurableObject(ctx, env)
+ const rebuilt = await requestFor(resourceEvents, { contract: 3 })
+ expect((await restored.fetch(rebuilt)).status).toBe(409)
+ expect([completed, retrying].map((ws) => ws.deserializeAttachment())).toEqual(saved)
+ expect(unstarted.deserializeAttachment()).not.toHaveProperty("communityDeliveryProgress")
+ for (const ws of [completed, retrying, unstarted]) expect(ws.send).not.toHaveBeenCalled()
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying])
+ const retry = await restored.fetch(original.clone())
+ expect(await original.text()).toBe(originalBody)
+ expect(retry.status).toBe(200)
+ await expect(retry.json()).resolves.toMatchObject({ enqueued: 1, alreadyEnqueued: 1, attempted: 1 })
+ expect(completed.send).not.toHaveBeenCalled()
+ expect(retrying.send).toHaveBeenCalledTimes(1)
+ expect(JSON.parse(retrying.send.mock.calls[0]![0] as string).type).toBe("community:events.batch.v2")
+ })
+
+ it("rejects unknown bundle versions and does not upgrade original v2 summary bytes for a v3 socket", async () => {
+ const { durable, ctx } = createDO()
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, communityContract: 3 })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
+ const request = await requestFor()
+ const body = await request.clone().json()
+ expect((await durable.fetch(new Request(request.url, { method: "POST", headers: request.headers, body: JSON.stringify({ ...body, communityContract: 4 }) }))).status).toBe(400)
+ expect((await durable.fetch(request)).status).toBe(503)
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.deserializeAttachment()).not.toHaveProperty("communityDeliveryProgress")
+ })
+
it("sends zero frames when any event is invalid", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
@@ -834,14 +928,36 @@ describe("WebSocketDurableObject", () => {
})
})
- it.each([1, 2] as const)("keeps contract %s fixed across successful reauthentication", async (version) => {
+ it.each([1, 2, 3] 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 } : {}) }))
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", ...(version !== 1 ? { communityContract: version } : {}) }))
+ })
+
+ it.each([2, 3])("confirms an explicitly requested contract %s on first authentication", async (communityContract) => {
+ const { durable } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "", targetUserId: "user-42", authenticated: false })
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract }))
+ expect(ws.deserializeAttachment()).toMatchObject({ authenticated: true, communityContract })
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", communityContract }))
+ })
+
+ it("rejects an unknown requested contract before storing authentication", async () => {
+ const { durable } = createDO()
+ mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
+ const ws = createMockWebSocket()
+ const original = { type: "user", userId: "", targetUserId: "user-42", authenticated: false }
+ ws.serializeAttachment(original)
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: 4 }))
+ expect(ws.deserializeAttachment()).toEqual(original)
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unsupported community contract")
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.error", error: "Unsupported community contract" }))
})
it("retries a transient session lookup before authenticating", async () => {
diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.ts
index 6583510b5..b0fc3cb5d 100644
--- a/src/ws-do/src/ws-durable/user-auth.ts
+++ b/src/ws-do/src/ws-durable/user-auth.ts
@@ -1,5 +1,5 @@
import {
- COMMUNITY_CONTRACT_VERSION,
+ type CommunityContract,
createDb,
encodeCommunityBrowserEventBatchForContract,
encodeCommunityBrowserEvent,
@@ -97,7 +97,7 @@ export async function handleUserFetch(
return invalidCommunityBrowserEventResponse(event)
}
if (!hasAuthenticatedTargetSocket(context, targetUserId)) {
- return jsonResponse({ sent: broadcastCommunity(context, event.event, targetUserId) })
+ return jsonResponse({ sent: broadcastCommunity(context, event.event, targetUserId, event.contract) })
}
try {
if (!await canDeliverCommunityContent(createDb(context.env.DB), targetUserId, [event.event])) {
@@ -108,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 = broadcastCommunity(context, event.event, targetUserId)
+ const sent = broadcastCommunity(context, event.event, targetUserId, event.contract)
return new Response(JSON.stringify({ sent }), {
headers: { "Content-Type": "application/json" },
})
@@ -296,8 +296,13 @@ 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 : 1
+ const selected = state?.type === "user" && state.authenticated ? state.communityContract : msg.communityContract
+ if (selected !== undefined && selected !== 1 && selected !== 2 && selected !== 3) {
+ ws.send(JSON.stringify({ type: "auth.error", error: "Unsupported community contract" }))
+ ws.close(1008, "Unsupported community contract")
+ return
+ }
+ const communityContract: CommunityContract = selected ?? 1
ws.serializeAttachment({
type: "user",
userId,
@@ -311,7 +316,7 @@ export async function handleWebSocketMessage(
: {}),
} as ConnectionState)
context.log.info("websocket authenticated", { userId })
- ws.send(JSON.stringify({ type: "auth.ok", ...(communityContract === COMMUNITY_CONTRACT_VERSION ? { communityContract: COMMUNITY_CONTRACT_VERSION } : {}) }))
+ ws.send(JSON.stringify({ type: "auth.ok", ...(communityContract !== 1 ? { communityContract } : {}) }))
if (!wasOnline) {
broadcastPresence(context, userId, true).catch(() => { })
}
@@ -418,14 +423,16 @@ function broadcast(
return sent
}
-function broadcastCommunity(context: WsDurableContext, event: import("@alook/shared").CommunityWsEvent, targetUserId: string) {
+function broadcastCommunity(context: WsDurableContext, event: import("@alook/shared").CommunityWsEvent, targetUserId: string, sourceContract: CommunityContract = 2) {
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)
+ const contract = state.communityContract ?? 1
+ if (contract !== 1 && contract !== 2 && contract !== 3) continue
+ const projected = projectCommunityEventForContract(event, contract, sourceContract)
if (!projected) continue
- const encoded = encodeCommunityBrowserEvent(projected)
+ const encoded = encodeCommunityBrowserEvent(projected, contract)
if (!encoded.ok) continue
try { ws.send(encoded.body); sent++ } catch { }
}
@@ -490,10 +497,10 @@ async function deliverCommunityBundle(
bundle: ValidCommunityBundle,
targetUserId: string,
): Promise<Response> {
- const formats = await Promise.all(([1, COMMUNITY_CONTRACT_VERSION] as const).map((contract) => encodeCommunityBrowserEventBatchForContract({
+ const formats = await Promise.all(([1, 2, 3] as const).map((contract) => encodeCommunityBrowserEventBatchForContract({
operationId: bundle.operationId, prepared: bundle.prepared, contract,
})))
- const encodedBatch = formats[1]!
+ const encodedBatch = formats[bundle.prepared.contract === 3 ? 2 : 1]!
const targetSockets: Array<{
ws: WebSocket
state: Extract<ConnectionState, { type: "user" }>
@@ -511,8 +518,9 @@ async function deliverCommunityBundle(
}
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 }
+ const contract = state.communityContract ?? 1
+ const encoded = contract === 1 || contract === 2 || contract === 3 ? formats[contract - 1] : undefined
+ return { socketIndex, ws, state, frames: encoded?.ok ? [encoded.body] : [], progress: null }
})
if (!encodedBatch.ok) {
@@ -535,7 +543,6 @@ async function deliverCommunityBundle(
let hasConflict = false
for (const plan of plans) {
- if (plan.frames.length === 0) { plan.outcome = "preflightFailed"; continue }
const decoded = readCommunityDeliveryProgress(plan.state)
if (!decoded.ok) {
plan.outcome = "preflightFailed"
@@ -547,6 +554,7 @@ async function deliverCommunityBundle(
hasConflict = true
continue
}
+ if (plan.frames.length === 0) { plan.outcome = "preflightFailed"; continue }
if (progress && progress.frameCount !== plan.frames.length) {
plan.outcome = "preflightFailed"
continue