Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): unify message previews and reply context (#1170)

Gener04bb8f2ae00b
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 32d07667d..a531d9660 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -227,9 +227,51 @@ importers:
drizzle-orm:
specifier: ^0.45.4
+ mdast-util-find-and-replace:
+ specifier: ^3.0.3
+ version: 3.0.3
+ mdast-util-from-markdown:
+ specifier: ^2.1.0
+ version: 2.1.0
+ micromark-util-chunked:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-classify-character:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-resolve-all:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-symbol:
+ specifier: ^2.0.1
+ version: 2.0.1
+ micromark-util-types:
+ specifier: ^2.0.3
+ version: 2.0.3
nanoid:
specifier: ^5.1.16
version: 5.1.16
+ remark-breaks:
+ specifier: ^4.0.0
+ version: 4.0.0
+ remark-cjk-friendly:
+ specifier: ^2.3.1
+ remark-cjk-friendly-gfm-strikethrough:
+ specifier: ^2.3.1
+ remark-gfm:
+ specifier: ^4.0.1
+ version: 4.0.1
+ remark-math:
+ specifier: 6.0.0
+ version: 6.0.0
+ remark-parse:
+ specifier: ^11.0.0
+ version: 11.0.0
+ unified:
+ specifier: ^11.0.5
+ version: 11.0.5
zod:
specifier: ^4.6
version: 4.6.7
@@ -240,6 +282,9 @@ importers:
'@types/better-sqlite3':
specifier: ^7.6.13
version: 7.6.13
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/node':
specifier: ^25.9.4
version: 25.9.4
@@ -326,7 +371,7 @@ importers:
version: 4.5.0
'@streamdown/cjk':
specifier: ^1.0.4
'@streamdown/math':
specifier: ^1.0.3
version: 1.0.3([email protected])
@@ -426,30 +471,12 @@ importers:
lucide-react:
specifier: ^1.61.0
version: 1.61.0(@types/[email protected])([email protected])
- mdast-util-find-and-replace:
- specifier: ^3.0.3
- version: 3.0.3
mdast-util-from-markdown:
specifier: ^2.1.0
version: 2.1.0
mdast-util-to-hast:
specifier: ^13.2.1
version: 13.2.1
- micromark-util-chunked:
- specifier: ^2.0.1
- version: 2.0.1
- micromark-util-classify-character:
- specifier: ^2.0.1
- version: 2.0.1
- micromark-util-resolve-all:
- specifier: ^2.0.1
- version: 2.0.1
- micromark-util-symbol:
- specifier: ^2.0.1
- version: 2.0.1
- micromark-util-types:
- specifier: ^2.0.3
- version: 2.0.3
nanoid:
specifier: ^5.1.16
version: 5.1.16
@@ -504,15 +531,9 @@ importers:
rehype-slug:
specifier: ^6.0.0
version: 6.0.0
- remark-breaks:
- specifier: ^4.0.0
- version: 4.0.0
remark-gfm:
specifier: ^4.0.1
version: 4.0.1
- remark-math:
- specifier: 6.0.0
- version: 6.0.0
remark-parse:
specifier: ^11.0.0
version: 11.0.0
@@ -7513,9 +7534,6 @@ packages:
resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}
- resolution: {integrity: sha512-wgyJtgUkUcdU7zci7uuwc/tzoAhm0TswWhaXuvnWolqug+8jY7bgNkBBL0dYBnHgc/tHL7lCzRdPsdUxUKKBqw==}
-
resolution: {integrity: sha512-2Jn/ADrHFFyyniBMi0bncTbJqU78K3/TEYvzvwrWWzD9MYPUa/Gm4r3nOeKFQg/PDM5BsbDYdc8ackW4NTY6NA==}
@@ -13003,7 +13021,7 @@ snapshots:
'@standard-schema/[email protected]': {}
dependencies:
mdast-util-gfm-autolink-literal: 2.0.1
react: 19.3.1
@@ -15542,7 +15560,7 @@ snapshots:
dependencies:
'@types/esrecurse': 4.3.1
- '@types/estree': 1.0.9
+ '@types/estree': 1.0.10
esrecurse: 4.3.0
estraverse: 5.3.0
@@ -17161,7 +17179,7 @@ snapshots:
devlop: 1.1.0
longest-streak: 3.1.0
mdast-util-from-markdown: 2.1.0
- mdast-util-to-markdown: 2.1.3
+ mdast-util-to-markdown: 2.2.0
unist-util-remove-position: 5.0.0
transitivePeerDependencies:
- supports-color
@@ -17240,7 +17258,7 @@ snapshots:
dependencies:
mdast-util-gfm-strikethrough: 2.0.1
- mdast-util-to-markdown: 2.1.3
+ mdast-util-to-markdown: 2.2.0
micromark-extension-cjk-friendly-util: 3.0.1([email protected])
micromark-util-symbol: 2.0.1
optionalDependencies:
@@ -17251,7 +17269,7 @@ snapshots:
dependencies:
- mdast-util-to-markdown: 2.1.3
+ mdast-util-to-markdown: 2.2.0
micromark-extension-cjk-friendly-util: 3.0.1([email protected])
micromark-util-symbol: 2.0.1
optionalDependencies:
@@ -17271,20 +17289,6 @@ snapshots:
unist-util-visit: 5.1.0
zwitch: 2.0.4
- dependencies:
- '@types/mdast': 4.0.4
- '@types/unist': 3.0.3
- longest-streak: 3.1.0
- mdast-util-phrasing: 4.1.0
- mdast-util-to-string: 4.0.0
- micromark-util-character: 2.1.1
- micromark-util-classify-character: 2.0.1
- micromark-util-decode-string: 2.0.1
- micromark-util-html-tag-name: 2.0.1
- unist-util-visit: 5.1.0
- zwitch: 2.0.4
-
dependencies:
'@types/mdast': 4.0.4
diff --git a/src/queue-worker/src/mobile-push.test.ts b/src/queue-worker/src/mobile-push.test.ts
index 8be79905d..221173f5e 100644
--- a/src/queue-worker/src/mobile-push.test.ts
+++ b/src/queue-worker/src/mobile-push.test.ts
@@ -55,7 +55,7 @@ const target = {
serverName: null,
channelName: null,
parentChannelName: null,
- attachmentContentTypes: [],
+ attachments: [],
}
function dependencies() {
diff --git a/src/queue-worker/src/notification-payload.test.ts b/src/queue-worker/src/notification-payload.test.ts
index a61b84644..38dfd1684 100644
--- a/src/queue-worker/src/notification-payload.test.ts
+++ b/src/queue-worker/src/notification-payload.test.ts
@@ -13,7 +13,7 @@ function target(overrides: Partial<{
serverName: string | null
channelName: string | null
parentChannelName: string | null
- attachmentContentTypes: Array<string | null>
+ attachments: Array<{ name: string; contentType: string | null }>
}> = {}) {
return {
messageId: "message-1",
@@ -24,7 +24,7 @@ function target(overrides: Partial<{
serverName: null,
channelName: null,
parentChannelName: null,
- attachmentContentTypes: [],
+ attachments: [],
...overrides,
}
}
@@ -123,7 +123,7 @@ describe("mobile notification payload", () => {
])("uses an attachment-type fallback for %j", async (attachmentContentTypes, expected) => {
const payload = await buildPushNotificationPayload(target({
content: " ",
- attachmentContentTypes,
+ attachments: attachmentContentTypes.map(contentType => ({ name: "", contentType })),
}), "user-1")
expect(payload.body).toBe(expected)
})
@@ -134,7 +134,7 @@ describe("mobile notification payload", () => {
conversationKind: "channel",
serverName: "Studio",
channelName: "general",
- attachmentContentTypes: ["image/png"],
+ attachments: [{ name: "", contentType: "image/png" }],
}), "user-1")
expect(payload.body).toBe("Alice: Photo")
diff --git a/src/queue-worker/src/notification-payload.ts b/src/queue-worker/src/notification-payload.ts
index 5bf7f69df..7d015c5f2 100644
--- a/src/queue-worker/src/notification-payload.ts
+++ b/src/queue-worker/src/notification-payload.ts
@@ -54,7 +54,11 @@ export async function buildPushNotificationPayload(
conversationKind: target.conversationKind,
authorName: target.authorName,
content: target.content,
- attachmentContentTypes: target.attachmentContentTypes,
+ attachments: target.attachments,
+ approval: target.approval,
+ botCreation: target.botCreation,
+ systemKind: target.systemKind,
+ embeds: target.embeds,
serverName: target.serverName,
channelName: target.channelName,
parentChannelName: target.parentChannelName,
diff --git a/src/shared/package.json b/src/shared/package.json
index 462b5b359..98fa06899 100644
--- a/src/shared/package.json
+++ b/src/shared/package.json
@@ -14,7 +14,12 @@
"./utils/community-roles": "./src/utils/community-roles.ts",
"./lib/discriminator": "./src/lib/discriminator.ts",
"./lib/invite-link": "./src/lib/invite-link.ts",
- "./db/resilience-testing": "./src/db/resilience-testing.ts"
+ "./db/resilience-testing": "./src/db/resilience-testing.ts",
+ "./chat-markdown": "./src/lib/chat-markdown.ts",
+ "./chat-syntax": "./src/lib/chat-syntax-plugin.ts",
+ "./spoiler-syntax": "./src/lib/spoiler-syntax.ts",
+ "./html-preview": "./src/lib/html-preview.ts",
+ "./redaction": "./src/lib/redaction.ts"
},
"scripts": {
"knip": "knip",
@@ -24,7 +29,21 @@
"dependencies": {
"drizzle-orm": "^0.45.4",
"nanoid": "^5.1.16",
- "zod": "^4.6"
+ "zod": "^4.6",
+ "unified": "^11.0.5",
+ "remark-parse": "^11.0.0",
+ "remark-gfm": "^4.0.1",
+ "remark-breaks": "^4.0.0",
+ "remark-math": "6.0.0",
+ "mdast-util-find-and-replace": "^3.0.3",
+ "mdast-util-from-markdown": "^2.1.0",
+ "micromark-util-chunked": "^2.0.1",
+ "micromark-util-classify-character": "^2.0.1",
+ "micromark-util-resolve-all": "^2.0.1",
+ "micromark-util-symbol": "^2.0.1",
+ "micromark-util-types": "^2.0.3",
+ "remark-cjk-friendly": "^2.3.1",
+ "remark-cjk-friendly-gfm-strikethrough": "^2.3.1"
},
"devDependencies": {
"@cloudflare/workers-types": "^5.20261023.1",
@@ -34,6 +53,7 @@
"knip": "^6.32.2",
"playwright-core": "^1.64.1",
"typescript": "^6.0.3",
- "vitest": "5.1.0"
+ "vitest": "5.1.0",
+ "@types/mdast": "^4.0.4"
}
}
diff --git a/src/shared/src/business-schema-version.ts b/src/shared/src/business-schema-version.ts
index 6c964050c..427ba71c8 100644
--- a/src/shared/src/business-schema-version.ts
+++ b/src/shared/src/business-schema-version.ts
@@ -1 +1 @@
-export const BUSINESS_SCHEMA_VERSION = 8 as const
+export const BUSINESS_SCHEMA_VERSION = 9 as const
diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.ts
index 8afd78056..0dcd932ae 100644
--- a/src/shared/src/community-resources.ts
+++ b/src/shared/src/community-resources.ts
@@ -81,7 +81,7 @@ const messageThreadSchema = z.strictObject({
messageCount: CommunityChannelResourceSchema.shape.messageCount,
lastReplyAt: CommunityChannelResourceSchema.shape.lastMessageAt.optional(),
tags: z.array(z.string()).optional(),
- preview: z.string().optional(),
+ firstMessageId: id.nullable().optional(),
participants: z.array(CommunityMessageThreadParticipantSchema).optional(),
participantCount: z.number().int().nonnegative().optional(),
})
@@ -105,7 +105,6 @@ export const CommunityMessageResourceSchema = z.strictObject({
id,
authorId: id.optional(),
authorName: z.string(),
- text: z.string(),
deleted: z.boolean().optional(),
}).refine(reply => reply.deleted === true || reply.authorId !== undefined, { message: "Live reply author identity missing" }).optional(),
embeds: z.array(z.unknown()).optional(),
@@ -134,6 +133,15 @@ export const CommunityMessageResourcesSchema = z.strictObject({
}
})
+function validateRelatedMessageGraph(read: { messages: CommunityMessageResource[]; relatedMessages?: CommunityMessageResource[]; opener?: CommunityMessageResource; profiles: z.infer<typeof CommunityResourceProfileSchema>[] }, ctx: z.RefinementCtx) {
+ const roots = [...read.messages, ...(read.opener ? [read.opener] : [])]
+ if (read.relatedMessages?.some(message => !roots.some(root => root.channelId === message.channelId && root.replyToId === message.id))) ctx.addIssue({ code: "custom", path: ["relatedMessages"], message: "Reply resource scope mismatch" })
+ const all = [...roots, ...(read.relatedMessages ?? [])]
+ if (new Set(all.map(message => message.id)).size !== all.length) ctx.addIssue({ code: "custom", path: ["relatedMessages"], message: "Duplicated message resource" })
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: all, profiles: read.profiles })
+ if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
+}
+
export const CommunityReadStateResourceSchema = z.strictObject({
channelId: id,
lastReadMessageId: nullableId,
@@ -191,7 +199,8 @@ export type CommunityResourceBundle = z.infer<typeof CommunityResourceBundleSche
export const CommunityChannelReadSchema = z.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema })
export const CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({ ...envelope, page: CommunityPageSchema,
- surfaceReceipt: z.strictObject({ channelId: id, surfaceKind: z.enum(["channel", "forum", "thread", "dm"]) }) })
+ relatedMessages: z.array(CommunityMessageResourceSchema).optional(),
+ surfaceReceipt: z.strictObject({ channelId: id, surfaceKind: z.enum(["channel", "forum", "thread", "dm"]) }) }).superRefine(validateRelatedMessageGraph)
export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
viewerId: id,
peer: CommunityResourceProfileSchema.nullable(),
@@ -207,10 +216,6 @@ export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.
anchorMessageId: nullableId,
}),
}).superRefine((entry, ctx) => {
- if (entry.opener) {
- const graph = CommunityMessageResourcesSchema.safeParse({ messages: [...entry.messages, entry.opener], profiles: entry.profiles })
- if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
- }
for (const [path, channelId] of [
[["channel", "id"], entry.channel.id],
[["access", "channelId"], entry.access.channelId],
@@ -241,10 +246,10 @@ export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.
if (entry.selection.reason === "read_pointer_missing" && entry.readState.lastReadMessageId === null) ctx.addIssue({ code: "custom", path: ["selection", "reason"], message: "Conversation entry missing read pointer" })
})
export const CommunityMessageReadSchema = z.strictObject({ ...envelope,
- message: CommunityMessageResourceSchema, profiles: CommunityMessageResourcesSchema.shape.profiles,
+ message: CommunityMessageResourceSchema, relatedMessages: z.array(CommunityMessageResourceSchema).optional(), profiles: CommunityMessageResourcesSchema.shape.profiles,
}).superRefine((read, ctx) => {
- const graph = CommunityMessageResourcesSchema.safeParse({ messages: [read.message], profiles: read.profiles })
- if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
+ if (read.message.channelId !== read.channelId) ctx.addIssue({ code: "custom", path: ["message", "channelId"], message: "Message resource scope mismatch" })
+ validateRelatedMessageGraph({ messages: [read.message], relatedMessages: read.relatedMessages, profiles: read.profiles }, ctx)
})
export const CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: z.boolean(), threadId: id.optional() })
export const CommunityMembersReadSchema = z.strictObject({ ...envelope, relation: z.enum(["access", "notify"]), members: z.array(CommunityMemberRelationSchema), profiles: z.array(CommunityResourceProfileSchema) })
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index b7df6f46c..838d88958 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -19,10 +19,14 @@ const communityMessageCreateSchema = z.strictObject({
channelId: string,
serverId: string.optional(),
parentChannelId: string.optional(),
+ relatedMessages: z.array(CommunityMessageResourceSchema).optional(),
message: CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }),
profiles: CommunityMessageResourcesSchema.shape.profiles,
}).refine(event => event.message.channelId === event.channelId).superRefine((event, ctx) => {
- const graph = CommunityMessageResourcesSchema.safeParse({ messages: [event.message], profiles: event.profiles })
+ if (event.relatedMessages?.some(message => message.channelId !== event.channelId || message.id !== event.message.replyToId)) ctx.addIssue({ code: "custom", path: ["relatedMessages"], message: "Reply resource scope mismatch" })
+ const messages = [event.message, ...(event.relatedMessages ?? [])]
+ if (new Set(messages.map(message => message.id)).size !== messages.length) ctx.addIssue({ code: "custom", path: ["relatedMessages"], message: "Duplicated message resource" })
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages, profiles: event.profiles })
if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
})
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 0f72b2701..0d8cf12a0 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -1054,6 +1054,7 @@ export async function getMessage(db: Database, messageId: string) {
.select({
...messageProjection,
seq: communityMessage.seq,
+ friendshipId: communityMessage.friendshipId,
authorEmail: user.email,
})
.from(communityMessage)
@@ -1237,6 +1238,7 @@ export async function getMessagesByIdsInChannels(db: Database, ids: string[], ch
...messageProjection,
seq: communityMessage.seq,
clientNonce: communityMessage.clientNonce,
+ friendshipId: communityMessage.friendshipId,
discriminator: user.discriminator,
authorEmail: user.email,
})
diff --git a/src/shared/src/db/queries/community/notification-target.ts b/src/shared/src/db/queries/community/notification-target.ts
index c1fb5035b..28c1a375c 100644
--- a/src/shared/src/db/queries/community/notification-target.ts
+++ b/src/shared/src/db/queries/community/notification-target.ts
@@ -7,9 +7,11 @@ import {
communityServer,
} from "../../community-schema";
import { user } from "../../schema";
+import { communityBotCreationRequest } from "../../bot-creation-schema";
+import type { MessagePreviewInput } from "../../../lib/message-preview";
import type { Database } from "../../index";
-export interface PushNotificationTarget {
+export interface PushNotificationTarget extends Pick<MessagePreviewInput, "attachments" | "approval" | "botCreation" | "systemKind" | "embeds"> {
messageId: string;
channelId: string;
authorName: string;
@@ -18,7 +20,6 @@ export interface PushNotificationTarget {
serverName: string | null;
channelName: string | null;
parentChannelName: string | null;
- attachmentContentTypes: Array<string | null>;
}
export async function getPushNotificationTarget(
@@ -35,6 +36,10 @@ export async function getPushNotificationTarget(
channelId: communityMessage.channelId,
authorName: user.name,
content: communityMessage.content,
+ type: communityMessage.type,
+ requestId: communityBotCreationRequest.id,
+ friendshipId: communityMessage.friendshipId,
+ embeds: communityMessage.embeds,
channelType: communityChannel.type,
channelName: communityChannel.name,
parentChannelId: communityChannel.parentChannelId,
@@ -55,13 +60,14 @@ export async function getPushNotificationTarget(
communityServer,
eq(communityServer.id, communityChannel.serverId),
)
+ .leftJoin(communityBotCreationRequest, eq(communityBotCreationRequest.messageId, communityMessage.id))
.where(eq(communityMessage.id, messageId))
.limit(1);
const message = rows[0];
if (!message) return null;
const attachments = await db
- .select({ contentType: communityAttachment.contentType })
+ .select({ id: communityAttachment.id, name: communityAttachment.filename, contentType: communityAttachment.contentType, sizeBytes: communityAttachment.size })
.from(communityAttachment)
.innerJoin(communityMessageAttachment, eq(communityMessageAttachment.attachmentId, communityAttachment.id))
.where(eq(communityMessageAttachment.messageId, messageId))
@@ -83,6 +89,10 @@ export async function getPushNotificationTarget(
serverName: message.serverName,
channelName: message.channelName,
parentChannelName: message.parentChannelName,
- attachmentContentTypes: attachments.map((row) => row.contentType),
+ attachments,
+ ...(message.friendshipId ? { approval: { friendshipId: message.friendshipId } } : {}),
+ ...(message.requestId ? { botCreation: { requestId: message.requestId } } : {}),
+ ...(message.type === "thread_created" ? { systemKind: "thread" as const } : {}),
+ ...(Array.isArray(message.embeds) ? { embeds: message.embeds } : {}),
};
}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 7c7591d75..5d2b4ba87 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -853,3 +853,6 @@ export { CommunityDmReadItemSchema, CommunityDmsReadSchema, parseCommunityDmsRea
export * from "./community-profile-reads"
export * from "./machine-refresh-contract";
+
+export { messagePreview, messagePreviewText } from "./lib/message-preview";
+export type { MessagePreviewInput } from "./lib/message-preview";
diff --git a/src/shared/src/lib/chat-markdown.ts b/src/shared/src/lib/chat-markdown.ts
new file mode 100644
index 000000000..5a883d790
--- /dev/null
+++ b/src/shared/src/lib/chat-markdown.ts
@@ -0,0 +1,55 @@
+import { unified, type PluggableList } from "unified"
+import remarkParse from "remark-parse"
+import remarkGfm from "remark-gfm"
+import remarkBreaks from "remark-breaks"
+import type { Root } from "mdast"
+import { formatHandle } from "./discriminator"
+import type { MentionCandidate, MentionType } from "../utils/community-mentions"
+import remarkCjkFriendly from "remark-cjk-friendly"
+import remarkCjkFriendlyGfmStrikethrough from "remark-cjk-friendly-gfm-strikethrough"
+import remarkMath from "remark-math"
+import { chatSyntaxPlugin, type MentionNode } from "./chat-syntax-plugin"
+
+export const CHAT_REMARK_PLUGINS: PluggableList = [remarkGfm, chatSyntaxPlugin, remarkBreaks]
+
+export const chatMarkdownProcessor = unified()
+ .use(remarkParse)
+ .use(remarkCjkFriendly)
+ .use(CHAT_REMARK_PLUGINS)
+ .use(remarkCjkFriendlyGfmStrikethrough)
+ .use(remarkMath, { singleDollarTextMath: true })
+ .freeze()
+
+function parsedMentions(content: string): MentionNode[] {
+ if (!content.includes("@")) return []
+ const tree = chatMarkdownProcessor.runSync(chatMarkdownProcessor.parse(content)) as Root
+ const mentions: MentionNode[] = []
+ function visit(node: { type: string; children?: unknown[] }): void {
+ if (node.type === "mention") mentions.push(node as MentionNode)
+ if (node.children) {
+ for (const child of node.children) visit(child as Parameters<typeof visit>[0])
+ }
+ }
+ visit(tree)
+ return mentions
+}
+
+export function detectChatMentionType(content: string): MentionType | undefined {
+ return parsedMentions(content).some((node) => node.everyone) ? "everyone" : undefined
+}
+
+export function extractChatMentionedUserIds(content: string, candidates: MentionCandidate[]): string[] {
+ const byHandle = new Map<string, string>()
+ for (const candidate of candidates) {
+ if (!candidate.name || !candidate.discriminator) continue
+ const handle = `@${formatHandle(candidate.name, candidate.discriminator)}`.toLowerCase()
+ if (!byHandle.has(handle)) byHandle.set(handle, candidate.userId)
+ }
+ const found = new Set<string>()
+ for (const node of parsedMentions(content)) {
+ if (node.everyone || !node.discriminator) continue
+ const userId = byHandle.get(`${node.value}#${node.discriminator}`.toLowerCase())
+ if (userId) found.add(userId)
+ }
+ return [...found]
+}
diff --git a/src/shared/src/lib/chat-syntax-plugin.ts b/src/shared/src/lib/chat-syntax-plugin.ts
new file mode 100644
index 000000000..5be7fc073
--- /dev/null
+++ b/src/shared/src/lib/chat-syntax-plugin.ts
@@ -0,0 +1,421 @@
+import type { Root, PhrasingContent, Text } from "mdast"
+import { findAndReplace } from "mdast-util-find-and-replace"
+import type { CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle } from "mdast-util-from-markdown"
+import { codes } from "micromark-util-symbol"
+import type { Construct, Effects, Extension, State, TokenizeContext } from "micromark-util-types"
+import type { Plugin } from "unified"
+import { MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary, isMentionEndBoundary } from "../utils/community-mentions"
+import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"
+
+// Chat-only syntax (`||spoiler||`, `@mention`, `/server#disc/channel` and bare
+// `/server#disc` refs), parsed as real markdown AST nodes rather than
+// string-spliced HTML tags fed through `rehype-raw`. `channelRef`/`serverRef`
+// content is a nanoid charset (`[A-Za-z0-9_-]`); a member `mention` is
+// `@<name>#dddd` where the name may contain spaces, Unicode, and Markdown/HTML
+// metacharacters. Member handles are recognized by a micromark text tokenizer
+// before Markdown can split them into sibling nodes; the later find/replace
+// pass remains as a compatibility path for ordinary text-only handles and
+// handles @everyone/refs. `spoiler` uses its own micromark tokenizer extension
+// in `spoiler-syntax.ts`.
+
+// Matches a `/server#disc/channel`, `/server#disc/channel/#N` (thread), or
+// `/server#disc/channel/#N#M` thread-reply ref — the CLI's path grammar
+// (`parseRef`/`formatRef` in `community-cli-contract.ts`). Segment charset
+// `[^\s/#.,;:!?)\]]+` = "any char slugify can emit, minus the terminator
+// punctuation": server names travel with their required discriminator and
+// channel names remain wire names rather than ids. Name segments preserve
+// Unicode; normalization strips only `/` and `#` and collapses whitespace. So
+// the base of the class is the inverse of what slugify removes (everything
+// except whitespace, `/`, `#`), which is what lets non-ASCII names
+// (`/Gus#0042/架构`, `/总部-🎉#0042/general`, `/studio#0042/café`) render as pills like their
+// ASCII kin — matching the `\p{L}` + `u` treatment `MENTION_RE` already uses
+// for `@names`. We ALSO exclude the trailing-boundary punctuation (`REF_TERM`
+// below) from the segment class: the old ASCII class `[A-Za-z0-9_-]` happened
+// to be disjoint from the terminator set, and that disjointness is
+// load-bearing — the segment class `[^\s/#…]+` is GREEDY, so without excluding
+// a terminator char from the segment it gets eaten BEFORE the lookahead can
+// fire (a greedy segment swallows the sentence period in `/studio#0042/general.`;
+// same for the full-width `。` in `看 /Gus#0042/架构。`). So a terminator must live
+// in BOTH places: excluded from the segment (so the match stops there) AND
+// present in the lookahead (so stopping there is legal). slugify never emits a
+// leading/trailing terminator anyway, and a mid-name terminator is a rare
+// corner that degrading to plain text is acceptable for; keeping the boundary
+// correct for ALL refs matters more.
+//
+// `REF_TERM` is the single source of truth for the terminator set — used BOTH
+// as the segment-class exclusion (`REF_SEG`) and the trailing lookahead, so
+// the two can't drift out of the disjointness the boundary relies on. It
+// covers ASCII sentence/closing punctuation and the common Unicode variants
+// used by CJK prose and smart quotes. A Chinese sentence ends in `。`, so
+// `看 /Gus#0042/架构。` must
+// yield pill `/Gus#0042/架构` + literal `。`, not swallow the period — full-width
+// terminators matter MORE here since this fix targets CJK names (Blair's QA
+// flag). Kept as a string spliced into `new RegExp(...)` so the shared set is
+// declared once.
+//
+// Trailing `(?=\s|$|[REF_TERM])` boundary lookahead: a 2-segment path followed
+// by ANOTHER `/segment` (e.g. `/api/user/123` in a docs URL) must NOT match —
+// otherwise this regex would greedily take `/api/user` and orphan `/123` as
+// trailing text next to a broken pill. The leading guard permits a
+// discriminator-bearing ref after prose or an opening bracket, e.g.
+// `see(/Gus#5994/架构/#722#17)` and `text/Gus#5994/架构`, while preventing the
+// regex engine from restarting after an earlier slash in the same unbroken
+// path or URL (`/api/Gus#5994/架构`, `https://Gus#5994/架构`). Ref terminators
+// stop that backward scan so a second adjacent ref after punctuation still
+// matches. The trailing boundary
+// remains load-bearing so the match still ends at the exact ref. `u` flag for
+// correct astral/emoji handling.
+const REF_TERM = ".,;:!?)\\]}\"'\\u2014\\u2019\\u201D\\u2026\\u3001\\u3002\\u3009\\u300B\\u300D\\u300F\\u3011\\u3015\\u3017\\u3019\\u301B\\uFF01\\uFF02\\uFF07\\uFF09\\uFF0C\\uFF0E\\uFF1A\\uFF1B\\uFF1F\\uFF3D\\uFF5D"
+const REF_SEG = `[^\\s/#${REF_TERM}]+`
+const HANDLE_SEG = `${REF_SEG}#\\d{4,}`
+// `/server#disc/channel` plus an optional message/thread suffix. The suffix has two
+// branches (message-ref-upgrade.md):
+// `#\d+` — a channel-MESSAGE ref, seq glued straight to the channel
+// (`/server#disc/channel#N`). Single seq ONLY — `#N#M` without a
+// slash is not a valid form (Cecilia #295, load-bearing).
+// `/#\d+(?:#\d+)?` — a THREAD (`/server#disc/channel/#N`) or thread-message
+// (`/server#disc/channel/#N#M`) ref; the inner `#M` lives only
+// on this slash branch.
+// `REF_SEG` excludes `#`, so the 2nd segment stops at the `#` and the seq falls
+// cleanly into the suffix group. The discriminator-bearing full path — never a
+// bare `#` — is what lets us drop the old bare-`#N` MESSAGE_REF pass and
+// root-solve the disambiguation Gus flagged.
+const CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu")
+
+// A bare `/server` ref — one segment, no channel. Unlike `CHANNEL_REF_RE`, this
+// intentionally keeps its leading `(?<=^|\s)` boundary; the current change is
+// scoped to channel/message refs. Its trailing `REF_TERM` boundary excludes
+// being followed by another `/segment` — so this never double-matches
+// the first segment of a genuine `/server#disc/channel` ref (that trailing boundary
+// fails when the next char is `/`, and the segment class backtracking can't
+// produce a shorter match that satisfies it either, since every character up
+// to the next `/` is in the segment charset). Same `REF_SEG`/`REF_TERM` +
+// `u` flag as `CHANNEL_REF_RE` above (Unicode server names, full-width
+// terminators). Registered after `CHANNEL_REF_RE` in `chatSyntaxPlugin`'s
+// pairs list purely for readability (server-only is the "smaller" grammar);
+// the boundary already makes the ordering non-load-bearing for correctness.
+const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu")
+
+// (The old bare-`#N` MESSAGE_REF_RE was removed in message-ref-upgrade.md — a
+// message ref is now always the full path `/server#disc/channel#N`, matched by
+// CHANNEL_REF_RE's suffix group above. A bare `#N` now renders as plain text.
+// This kills the fragile "works only because it's the last consumption pass"
+// disambiguation: the prefix-anchored full-path form can't collide with a bare
+// `#`, so no ordering hazard with mentions/spoilers/other `#` syntax.)
+
+// Two-branch mention grammar:
+//
+// 1. The literal `@everyone` token, with a trailing `(?![\p{L}\p{N}_-])`
+// boundary guard so `@everyoneee` is NOT matched as `@everyone` — this MUST
+// agree with `detectMentionType`'s boundary check (mention-extension.ts)
+// and `community-mentions.ts`'s `ID_CHAR_RE`. `@here` was removed as a
+// broadcast trigger; a literal `@here`
+// now falls through as ordinary text, matching option b: no legacy
+// rendering for historical `@here`.)
+//
+// 2. A member mention `@<name>#dddd` where the trailing `#dddd` is REQUIRED
+// and acts as an unambiguous terminator. Because member names are validated
+// to never contain `#`, `@`, or line breaks (validateCommunityName), the
+// name-run may safely include spaces/unicode: `[^@#\n\r]*[^@#\n\r\s]`. The
+// final class forces the name-run to END in a non-whitespace char, so
+// ordinary prose like `@bob check issue #0042` is NOT swallowed into one
+// pill (the only `#` there is space-preceded). The tag is `#dddd` with 4+
+// digits (variable-width disc); the digit run is greedy so a widened 5+-digit
+// tag matches in full. A hand-typed bare `@Alice` (no tag) is intentionally
+// NOT a mention — it stays text.
+const MENTION_RE = new RegExp(
+ String.raw`(?<!/|${MENTION_IDENTIFIER_CHARACTERS})(?:@everyone(?!${MENTION_IDENTIFIER_CHARACTERS})|@[^@#\n\r]*[^@#\n\r\s]#\d{4,}(?!${MENTION_IDENTIFIER_CHARACTERS}))`,
+ "gu",
+)
+
+/** mdast node produced by `@name`/`@name#0042`/`@everyone`. */
+export interface MentionNode {
+ type: "mention"
+ /** Display name — `#dddd` discriminator, if present, is stripped from here (matches the old `<mention>` tag's content). */
+ value: string
+ everyone: boolean
+ /** The discriminator (4+ decimal digits), if the mention carried one (never set for `@everyone`). */
+ discriminator?: string
+}
+
+/** mdast node produced by a `/server#disc/channel` or `/server#disc/channel/#N` ref. */
+export interface ChannelRefNode {
+ type: "channelRef"
+ value: string
+}
+
+/** mdast node produced by a bare `/server` ref (no channel segment). */
+export interface ServerRefNode {
+ type: "serverRef"
+ value: string
+}
+
+declare module "mdast" {
+ interface RootContentMap {
+ chatLiteral: ChatLiteralNode
+ mention: MentionNode
+ channelRef: ChannelRefNode
+ serverRef: ServerRefNode
+ }
+ interface PhrasingContentMap {
+ chatLiteral: ChatLiteralNode
+ mention: MentionNode
+ channelRef: ChannelRefNode
+ serverRef: ServerRefNode
+ }
+}
+
+declare module "micromark-util-types" {
+ interface TokenTypeMap {
+ memberMention: "memberMention"
+ memberMentionBoundary: "memberMentionBoundary"
+ }
+}
+
+function memberMentionSyntax(): Extension {
+ const construct: Construct = {
+ name: "memberMention",
+ previous(code) {
+ if (code === codes.slash) return false
+ if (code === null || code < 0) return true
+ let previous = String.fromCodePoint(code)
+ if (code >= 0xDC00 && code <= 0xDFFF) {
+ const tail = this.events.at(-1)?.[1]
+ if (tail) previous = this.sliceSerialize({ start: tail.start, end: this.now() })
+ }
+ return isMentionStartBoundary(previous)
+ },
+ tokenize: tokenizeMemberMention,
+ }
+ return { text: { [codes.atSign]: construct } }
+}
+
+function tokenizeMemberMention(this: TokenizeContext, effects: Effects, ok: State, nok: State): State {
+ let nameSize = 0
+ let previousWasWhitespace = false
+ let discriminatorSize = 0
+
+ return start
+
+ function start(code: Parameters<State>[0]): State | undefined {
+ effects.enter("memberMention")
+ effects.consume(code)
+ return name
+ }
+
+ function name(code: Parameters<State>[0]): State | undefined {
+ if (
+ code === codes.eof ||
+ code === codes.atSign ||
+ code === codes.carriageReturn ||
+ code === codes.lineFeed ||
+ code === codes.carriageReturnLineFeed
+ ) {
+ return nok(code)
+ }
+ if (code === codes.numberSign) {
+ if (nameSize === 0 || previousWasWhitespace) return nok(code)
+ effects.consume(code)
+ return discriminator
+ }
+ effects.consume(code)
+ nameSize++
+ previousWasWhitespace = code === codes.space || code === codes.horizontalTab || code === codes.virtualSpace
+ return name
+ }
+
+ function discriminator(code: Parameters<State>[0]): State | undefined {
+ if (code !== null && code >= codes.digit0 && code <= codes.digit9) {
+ effects.consume(code)
+ discriminatorSize++
+ return discriminator
+ }
+ if (discriminatorSize < 4) return nok(code)
+ return effects.check(memberMentionEndBoundary, finish, nok)(code)
+ }
+
+ function finish(code: Parameters<State>[0]): State | undefined {
+ effects.exit("memberMention")
+ return ok(code)
+ }
+}
+
+const memberMentionEndBoundary: Construct = {
+ tokenize(effects, ok, nok) {
+ let high = ""
+ return start
+
+ function start(code: Parameters<State>[0]): State | undefined {
+ if (code === null || code < 0) return ok(code)
+ if (code >= 0xD800 && code <= 0xDBFF) {
+ high = String.fromCharCode(code)
+ effects.enter("memberMentionBoundary")
+ effects.consume(code)
+ return afterHigh
+ }
+ return isMentionEndBoundary(String.fromCodePoint(code)) ? ok(code) : nok(code)
+ }
+
+ function afterHigh(code: Parameters<State>[0]): State | undefined {
+ effects.exit("memberMentionBoundary")
+ const suffix = code !== null && code >= 0xDC00 && code <= 0xDFFF
+ ? high + String.fromCharCode(code)
+ : high
+ return isMentionEndBoundary(suffix) ? ok(code) : nok(code)
+ }
+ },
+}
+
+interface ChatLiteralNode extends Omit<Text, "type"> {
+ type: "chatLiteral"
+}
+
+function literalFromMarkdown(): FromMarkdownExtension {
+ return {
+ enter: {
+ characterEscape: enterLiteral,
+ characterReference: enterLiteral,
+ },
+ exit: {
+ characterEscapeValue: appendEscapeValue,
+ characterEscape: exitLiteral,
+ characterReference: exitLiteral,
+ },
+ }
+}
+
+const enterLiteral: FromMarkdownHandle = function (token) {
+ this.enter({ type: "chatLiteral", value: "" }, token)
+}
+
+const appendEscapeValue: FromMarkdownHandle = function (token) {
+ const node = this.stack.at(-1) as ChatLiteralNode
+ node.value += this.sliceSerialize(token)
+}
+
+const exitLiteral: FromMarkdownHandle = function (token) {
+ this.exit(token)
+}
+
+function restoreLiteralNodes(node: TraversableSyntaxNode): void {
+ if (!node.children) return
+ for (const child of node.children) {
+ if (child.type === "chatLiteral") child.type = "text"
+ restoreLiteralNodes(child)
+ }
+}
+
+function memberMentionFromMarkdown(): FromMarkdownExtension {
+ return {
+ enter: { memberMention: enterMemberMention },
+ exit: { memberMention: exitMemberMention },
+ }
+}
+
+const enterMemberMention: FromMarkdownHandle = function (this: CompileContext, token) {
+ const serialized = this.sliceSerialize(token)
+ const tagStart = serialized.lastIndexOf("#")
+ this.enter({
+ type: "mention",
+ value: serialized.slice(0, tagStart),
+ everyone: false,
+ discriminator: serialized.slice(tagStart + 1),
+ }, token)
+}
+
+const exitMemberMention: FromMarkdownHandle = function (this: CompileContext, token) {
+ this.exit(token)
+}
+
+type TraversableSyntaxNode = {
+ type: string
+ children?: TraversableSyntaxNode[]
+ value?: string
+ discriminator?: string
+ everyone?: boolean
+}
+
+function restoreProtectedMemberMentions(
+ node: TraversableSyntaxNode,
+ protectedAncestor = false,
+): void {
+ if (!node.children) return
+ const childrenAreProtected = protectedAncestor || IGNORE_NODE_TYPES.includes(node.type)
+ node.children = node.children.map((child) => {
+ if (
+ childrenAreProtected
+ && child.type === "mention"
+ && !child.everyone
+ && child.value
+ && child.discriminator
+ ) {
+ return {
+ type: "text",
+ value: `${child.value}#${child.discriminator}`,
+ }
+ }
+ restoreProtectedMemberMentions(child, childrenAreProtected)
+ return child
+ })
+}
+
+// `ignore` list mirrors mdast-util-find-and-replace's own default protection
+// for GFM autolinks/definitions, plus `code`/`inlineCode` so `@fake-mention`,
+// `#0042`, `/server#disc/channel`, and `||spoiler||` all stay literal inside a
+// code span or fenced code block — replacing the old `preprocessMarkdown`'s
+// manual stash/unstash sentinel dance, which existed only because that
+// implementation operated on a raw string before markdown parsing.
+const IGNORE_NODE_TYPES = ["code", "inlineCode", "link", "linkReference"]
+
+function mentionReplacer(value: string): MentionNode {
+ const everyone = value === "@everyone"
+ if (everyone) return { type: "mention", value, everyone: true }
+ const tag = /#(\d{4,})$/.exec(value)
+ const bare = value.replace(/#\d{4,}$/, "")
+ return tag ? { type: "mention", value: bare, everyone: false, discriminator: tag[1] } : { type: "mention", value: bare, everyone: false }
+}
+
+function channelRefReplacer(value: string): ChannelRefNode {
+ return { type: "channelRef", value }
+}
+
+function serverRefReplacer(value: string): ServerRefNode {
+ return { type: "serverRef", value }
+}
+
+/**
+ * remark plugin: combines the spoiler micromark extension (`spoiler-syntax.ts`)
+ * with a `mdast-util-find-and-replace` pass for `mention`/`channelRef`.
+ * Registers `spoilerSyntax`'s micromark/from-markdown extensions on the
+ * processor (the `remark-gfm`-style `this.data(...)` convention) and returns
+ * a tree transform running the find-and-replace pass after parsing.
+ */
+export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this: import("unified").Processor) {
+ type ProcessorData = { micromarkExtensions?: unknown[]; fromMarkdownExtensions?: unknown[] }
+ const settings = this.data() as ProcessorData
+ const micromarkExtensions = (settings.micromarkExtensions ??= [])
+ const fromMarkdownExtensions = (settings.fromMarkdownExtensions ??= [])
+ micromarkExtensions.push(memberMentionSyntax())
+ fromMarkdownExtensions.push(memberMentionFromMarkdown(), literalFromMarkdown())
+ micromarkExtensions.push(spoilerSyntax())
+ fromMarkdownExtensions.push(spoilerFromMarkdown())
+
+ return function transform(tree: Root): void {
+ restoreProtectedMemberMentions(tree as TraversableSyntaxNode)
+ findAndReplace(
+ tree,
+ [
+ [MENTION_RE, mentionReplacer as unknown as (value: string, ...rest: unknown[]) => PhrasingContent | string | false],
+ [CHANNEL_REF_RE, channelRefReplacer as unknown as (value: string) => PhrasingContent],
+ // Runs as its own pass AFTER the channelRef pass above — by then every
+ // `/server#disc/channel` span is already a `channelRef` element (no longer
+ // a `text` node `findAndReplace` visits), so this pass only ever sees
+ // genuine bare `/server` refs among the remaining text.
+ [SERVER_REF_RE, serverRefReplacer as unknown as (value: string) => PhrasingContent],
+ ],
+ { ignore: IGNORE_NODE_TYPES },
+ )
+ restoreLiteralNodes(tree)
+ }
+}
+
diff --git a/src/shared/src/lib/html-preview.ts b/src/shared/src/lib/html-preview.ts
new file mode 100644
index 000000000..dcecff368
--- /dev/null
+++ b/src/shared/src/lib/html-preview.ts
@@ -0,0 +1,84 @@
+import { unified } from "unified"
+import remarkParse from "remark-parse"
+import type { Root, RootContent, Paragraph, Link } from "mdast"
+import type { CommunityMessageAttachment } from "../community-resources"
+import { CHAT_REMARK_PLUGINS } from "./chat-markdown"
+
+export const MAX_HTML_PREVIEW_BYTES = 2 * 1024 * 1024
+
+export function isHtmlPreviewFile(name: string, contentType?: string | null): boolean {
+ const type = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
+ return type === "text/html" || (["", "application/octet-stream", "binary/octet-stream"].includes(type) && /\.html?$/i.test(name))
+}
+
+export type HtmlPreviewAttachment = Pick<CommunityMessageAttachment, "name"> & Partial<Pick<CommunityMessageAttachment, "id" | "contentType" | "sizeBytes">>
+
+interface HtmlPreviewNode {
+ type: "htmlPreview"
+ data: { hName: "htmlpreview"; hProperties: { dataAttachmentId: string } }
+}
+
+declare module "mdast" {
+ interface RootContentMap { htmlPreview: HtmlPreviewNode }
+}
+
+type Options<T extends HtmlPreviewAttachment = HtmlPreviewAttachment> = { text: string; attachments?: readonly T[] }
+const parser = unified().use(remarkParse).use(CHAT_REMARK_PLUGINS).freeze()
+
+export function replaceHtmlPreviewMarkers<T extends HtmlPreviewAttachment>(tree: Root, { text, attachments }: Options<T>): Map<string, T> {
+ const files = new Map((attachments ?? []).flatMap((attachment) => attachment.id
+ && isHtmlPreviewFile(attachment.name, attachment.contentType)
+ && (attachment.sizeBytes == null || attachment.sizeBytes <= MAX_HTML_PREVIEW_BYTES)
+ ? [[attachment.id, attachment] as const] : []))
+ const selected = new Map<string, T>()
+ if (!files.size || !text.includes("[alook-html-preview]")) return selected
+
+ function attachmentFor(node: Paragraph["children"][number]): T | undefined {
+ if (node.type !== "link") return
+ const link: Link = node
+ const start = link.position?.start.offset, end = link.position?.end.offset
+ if (start === undefined || end === undefined || link.title
+ || link.children.length !== 1 || link.children[0]?.type !== "text" || link.children[0].value !== "alook-html-preview"
+ || text.slice(start, end) !== `[alook-html-preview](${link.url})`
+ || (start > 0 && !/\s/.test(text[start - 1]!))
+ || (end < text.length && !/\s/.test(text[end]!))) return
+ return files.get(link.url)
+ }
+
+ function walk(parent: { children: RootContent[] }) {
+ parent.children = parent.children.flatMap((node): RootContent[] => {
+ if (node.type === "blockquote" || node.type === "listItem" || node.type === "list") {
+ walk(node)
+ return [node]
+ }
+ if (node.type !== "paragraph") return [node]
+ const blocks: RootContent[] = []
+ let children: Paragraph["children"] = []
+ function flush() {
+ if (children.some((child) => child.type !== "text" || child.value.trim())) blocks.push({ type: "paragraph", children })
+ children = []
+ }
+ for (const child of node.children) {
+ const attachment = attachmentFor(child)
+ if (!attachment?.id) { children.push(child); continue }
+ flush()
+ if (!selected.has(attachment.id)) {
+ selected.set(attachment.id, attachment)
+ blocks.push({ type: "htmlPreview", data: { hName: "htmlpreview", hProperties: { dataAttachmentId: attachment.id } } })
+ }
+ }
+ if (!blocks.length && children.length === node.children.length) return [node]
+ flush()
+ return blocks
+ })
+ }
+ walk(tree)
+ return selected
+}
+
+export function selectHtmlPreviews<T extends HtmlPreviewAttachment>(text: string, attachments?: readonly T[]): Map<string, T> {
+ if (!attachments?.some((attachment) => attachment.id) || !text.includes("[alook-html-preview]")) return new Map()
+ const tree = parser.runSync(parser.parse(text)) as Root
+ return replaceHtmlPreviewMarkers(tree, { text, attachments })
+}
+
diff --git a/src/shared/src/lib/message-preview.test.ts b/src/shared/src/lib/message-preview.test.ts
new file mode 100644
index 000000000..2440766bd
--- /dev/null
+++ b/src/shared/src/lib/message-preview.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest"
+import { MESSAGE_PREVIEW_LENGTH } from "../constants/community"
+import { messagePreview, messagePreviewText } from "./message-preview"
+
+describe("semantic message previews", () => {
+ it("projects complete chat syntax and preserves literal code and filenames", () => {
+ expect(messagePreviewText({ content: "**Hello** [read me](https://example.test/a_(b)) `file_name.ts`\n\n> second\n\n- third" }))
+ .toBe("Hello read me file_name.ts second third")
+ expect(messagePreviewText({ content: "中文**重点** /团队#0042/架构#7" })).toBe("中文重点 /团队#0042/架构#7")
+ expect(messagePreviewText({ content: "中文**重点**,~~删除~~。 @用户#0042 https://example.test。下一句" }))
+ .toBe("中文重点,删除。 @用户#0042 https://example.test。下一句")
+ })
+
+ it("masks spoilers and the existing redaction syntax without exposing hidden text", () => {
+ const text = messagePreviewText({ content: "before ||**private** [secret](https://hidden.test)|| after [REDACTED_EMAIL] `a_[REDACTED_TOKEN]`" })
+ expect(text).toBe("before [Spoiler] after [redacted] a_[redacted]")
+ for (const hidden of ["private", "secret", "hidden.test", "REDACTED_EMAIL", "REDACTED_TOKEN"]) expect(text).not.toContain(hidden)
+ })
+
+ it("keeps block boundaries and supplies readable non-rendering labels", () => {
+ expect(messagePreviewText({ content: "```ts\nconst file_name = 1\n```\n\n| Name | Value |\n| --- | --- |\n| a | b |\n\n$$x + y$$\n\n```mermaid\ngraph LR; A-->B\n```\n\n![a photo](https://example.test/a.png)" }))
+ .toBe("Code: const file_name = 1 Name Value a b Math: x + y Diagram Photo: a photo")
+ })
+
+ it("retains typed HTML as literal safe text, as the body does", () => {
+ expect(messagePreviewText({ content: "<b>literal</b> and x < y" })).toBe("<b>literal</b> and x < y")
+ })
+
+ it("uses exact HTML marker binding and includes attachment-only messages", () => {
+ const html = { id: "html1", name: "page.html", contentType: "text/html", sizeBytes: 50 }
+ expect(messagePreviewText({ content: "[alook-html-preview](html1)", attachments: [html] })).toBe("HTML preview")
+ expect(messagePreviewText({ content: "[alook-html-preview](html1)\n\n[alook-html-preview](html1)", attachments: [html] })).toBe("HTML preview")
+ for (const content of ["[alook-html-preview](missing)", "[alook-html-preview](html1 \"title\")", "x[alook-html-preview](html1)"]) {
+ expect(messagePreviewText({ content, attachments: [html] })).toContain("alook-html-preview")
+ }
+ expect(messagePreviewText({ content: "[alook-html-preview](html1)", attachments: [{ ...html, sizeBytes: 2 * 1024 * 1024 + 1 }] })).toContain("alook-html-preview")
+ expect(messagePreviewText({ attachments: [{ name: "photo_one.png", contentType: "image/png" }, { name: "clip.mp4", contentType: "video/mp4" }, { name: "voice.wav", contentType: "audio/wav" }, { name: "file_name.zip" }] }))
+ .toBe("Photo: photo_one.png Video: clip.mp4 Audio: voice.wav Attachment: file_name.zip")
+ })
+
+ it("summarizes structured cards from their canonical metadata", () => {
+ expect(messagePreviewText({ content: '{"internal":"data"}', approval: { friendshipId: "f1" } })).toBe("Friend request")
+ expect(messagePreviewText({ botCreation: { requestId: "b1" } })).toBe("Bot creation request")
+ expect(messagePreviewText({ type: "system", systemKind: "thread" })).toBe("Thread created")
+ })
+
+ it("parses the entire message before the existing UTF-16 truncation", () => {
+ const label = "x".repeat(MESSAGE_PREVIEW_LENGTH + 20)
+ expect(messagePreview({ content: `[${label}](https://example.test)` })).toBe(`${"x".repeat(MESSAGE_PREVIEW_LENGTH - 1)}…`)
+ expect(messagePreview({ content: `||${"hidden".repeat(100)}|| visible` })).toBe("[Spoiler] visible")
+ })
+})
diff --git a/src/shared/src/lib/message-preview.ts b/src/shared/src/lib/message-preview.ts
new file mode 100644
index 000000000..22597c929
--- /dev/null
+++ b/src/shared/src/lib/message-preview.ts
@@ -0,0 +1,70 @@
+import type { Root } from "mdast"
+import type { CommunityMessageResource } from "../community-resources"
+import { truncateMessagePreview } from "../constants/community"
+import { chatMarkdownProcessor } from "./chat-markdown"
+import { replaceHtmlPreviewMarkers, type HtmlPreviewAttachment } from "./html-preview"
+import { REDACTED } from "./redaction"
+
+export type MessagePreviewInput = Partial<Pick<CommunityMessageResource,
+ "content" | "type" | "systemKind" | "embeds"
+>> & { attachments?: readonly HtmlPreviewAttachment[]; approval?: Pick<NonNullable<CommunityMessageResource["approval"]>, "friendshipId">; botCreation?: Pick<NonNullable<CommunityMessageResource["botCreation"]>, "requestId"> }
+
+type TextNode = {
+ type: string
+ value?: string
+ alt?: string | null
+ lang?: string | null
+ discriminator?: string
+ children?: TextNode[]
+}
+
+function readableNode(node: TextNode): string {
+ const children = () => (node.children ?? []).map(readableNode)
+ switch (node.type) {
+ case "spoiler": return "[Spoiler]"
+ case "htmlPreview": return "HTML preview"
+ case "image":
+ case "imageReference": return node.alt ? `Photo: ${node.alt}` : "Photo"
+ case "mention": return `${node.value ?? ""}${node.discriminator ? `#${node.discriminator}` : ""}`
+ case "code": return node.lang?.toLowerCase() === "mermaid" ? "Diagram" : `Code: ${node.value ?? ""}`
+ case "math":
+ case "inlineMath": return `Math: ${node.value ?? ""}`
+ case "break": return " "
+ case "thematicBreak": return " "
+ case "definition":
+ case "footnoteDefinition": return ""
+ case "root":
+ case "blockquote":
+ case "list":
+ case "listItem":
+ case "table":
+ case "tableRow": return children().join(" ")
+ default: return node.children ? children().join("") : node.value ?? ""
+ }
+}
+
+function attachmentText(attachment: HtmlPreviewAttachment): string {
+ const type = attachment.contentType?.toLowerCase() ?? ""
+ const label = type.startsWith("image/") ? "Photo" : type.startsWith("video/") ? "Video" : type.startsWith("audio/") ? "Audio" : "Attachment"
+ return attachment.name ? `${label}: ${attachment.name}` : label
+}
+
+export function messagePreviewText(message: MessagePreviewInput): string {
+ if (message.approval) return "Friend request"
+ if (message.botCreation) return "Bot creation request"
+ const content = message.content ?? ""
+ const tree = chatMarkdownProcessor.runSync(chatMarkdownProcessor.parse(content)) as Root
+ const selected = replaceHtmlPreviewMarkers(tree, { text: content, attachments: message.attachments })
+ const text = readableNode(tree as TextNode)
+ const attachments = (message.attachments ?? []).filter((attachment) => !attachment.id || !selected.has(attachment.id)).map(attachmentText)
+ const embeds = !text.trim() ? (message.embeds ?? []).flatMap((embed) => {
+ if (!embed || typeof embed !== "object" || !("title" in embed) || typeof embed.title !== "string") return []
+ return [embed.title]
+ }) : []
+ const result = [text, ...attachments, ...embeds].join(" ").replace(REDACTED, "[redacted]").replace(/\s+/gu, " ").trim()
+ return result || (message.systemKind === "thread" ? "Thread created" : "")
+}
+
+export function messagePreview(message: MessagePreviewInput): string {
+ return truncateMessagePreview(messagePreviewText(message))
+}
diff --git a/src/shared/src/lib/redaction.ts b/src/shared/src/lib/redaction.ts
new file mode 100644
index 000000000..0febb3033
--- /dev/null
+++ b/src/shared/src/lib/redaction.ts
@@ -0,0 +1 @@
+export const REDACTED = /\[REDACTED(?:_[A-Z0-9]+)*\]/g
diff --git a/src/shared/src/lib/spoiler-syntax.ts b/src/shared/src/lib/spoiler-syntax.ts
new file mode 100644
index 000000000..4f3e479bf
--- /dev/null
+++ b/src/shared/src/lib/spoiler-syntax.ts
@@ -0,0 +1,170 @@
+import { splice } from "micromark-util-chunked"
+import { classifyCharacter } from "micromark-util-classify-character"
+import { resolveAll } from "micromark-util-resolve-all"
+import { codes } from "micromark-util-symbol"
+import type { Construct, Effects, Event, Extension, State, Token, TokenizeContext } from "micromark-util-types"
+import type { CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle } from "mdast-util-from-markdown"
+
+// Discord-style `||spoiler||` — a micromark inline tokenizer extension +
+// mdast-util-from-markdown extension, structurally mirroring
+// micromark-extension-gfm-strikethrough/mdast-util-gfm-strikethrough (`~~text~~`)
+// with `|` (code 124) in place of `~` (code 126). Recognizing the `||`
+// boundary during TOKENIZATION (the same phase that recognizes `**`/`*`/`` ` ``)
+// — rather than as a text-node find-and-replace pass after parsing — is what
+// lets `||I think **this** is neat||` correctly produce a `spoiler` node
+// containing a nested `strong` node. A text-node find-and-replace can't do
+// this: remark-parse would already have split that input into 3 sibling
+// nodes (text, strong, text) before any post-processing plugin runs, so the
+// two `|` markers never co-occur in one text node to match against.
+
+declare module "micromark-util-types" {
+ interface TokenTypeMap {
+ spoilerSequence: "spoilerSequence"
+ spoilerSequenceTemporary: "spoilerSequenceTemporary"
+ spoiler: "spoiler"
+ spoilerText: "spoilerText"
+ }
+}
+
+declare module "mdast" {
+ interface RootContentMap {
+ spoiler: SpoilerNode
+ }
+ interface PhrasingContentMap {
+ spoiler: SpoilerNode
+ }
+}
+
+/** mdast node produced by `||...||` — a phrasing-content parent, like `emphasis`/`strong`. */
+export interface SpoilerNode {
+ type: "spoiler"
+ children: import("mdast").PhrasingContent[]
+}
+
+/** Micromark extension enabling `||...||` spoiler syntax during tokenization. */
+export function spoilerSyntax(): Extension {
+ const tokenizer: Construct = {
+ name: "spoiler",
+ tokenize: tokenizeSpoiler,
+ resolveAll: resolveAllSpoiler,
+ }
+ return {
+ text: { [codes.verticalBar]: tokenizer },
+ insideSpan: { null: [tokenizer] },
+ attentionMarkers: { null: [codes.verticalBar] },
+ }
+
+ function resolveAllSpoiler(events: Event[], context: TokenizeContext): Event[] {
+ let index = -1
+ while (++index < events.length) {
+ if (
+ events[index][0] === "enter" &&
+ events[index][1].type === "spoilerSequenceTemporary" &&
+ events[index][1]._close
+ ) {
+ let open = index
+ while (open--) {
+ if (
+ events[open][0] === "exit" &&
+ events[open][1].type === "spoilerSequenceTemporary" &&
+ events[open][1]._open &&
+ events[index][1].end.offset - events[index][1].start.offset ===
+ events[open][1].end.offset - events[open][1].start.offset
+ ) {
+ events[index][1].type = "spoilerSequence"
+ events[open][1].type = "spoilerSequence"
+
+ const spoiler: Token = {
+ type: "spoiler",
+ start: Object.assign({}, events[open][1].start),
+ end: Object.assign({}, events[index][1].end),
+ }
+ const text: Token = {
+ type: "spoilerText",
+ start: Object.assign({}, events[open][1].end),
+ end: Object.assign({}, events[index][1].start),
+ }
+
+ const nextEvents: Event[] = [
+ ["enter", spoiler, context],
+ ["enter", events[open][1], context],
+ ["exit", events[open][1], context],
+ ["enter", text, context],
+ ]
+ const insideSpan = context.parser.constructs.insideSpan.null
+ if (insideSpan) {
+ splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context))
+ }
+ splice(nextEvents, nextEvents.length, 0, [
+ ["exit", text, context],
+ ["enter", events[index][1], context],
+ ["exit", events[index][1], context],
+ ["exit", spoiler, context],
+ ])
+ splice(events, open - 1, index - open + 3, nextEvents)
+ index = open + nextEvents.length - 2
+ break
+ }
+ }
+ }
+ }
+ index = -1
+ while (++index < events.length) {
+ if (events[index][1].type === "spoilerSequenceTemporary") {
+ events[index][1].type = "data"
+ }
+ }
+ return events
+ }
+
+ function tokenizeSpoiler(this: TokenizeContext, effects: Effects, ok: State, nok: State): State {
+ const previous = this.previous
+ const events = this.events
+ let size = 0
+ return start
+
+ function start(code: Parameters<State>[0]): State | undefined {
+ if (previous === codes.verticalBar && events[events.length - 1][1].type !== "characterEscape") {
+ return nok(code)
+ }
+ effects.enter("spoilerSequenceTemporary")
+ return more(code)
+ }
+
+ function more(code: Parameters<State>[0]): State | undefined {
+ const before = classifyCharacter(previous)
+ if (code === codes.verticalBar) {
+ if (size > 1) return nok(code)
+ effects.consume(code)
+ size++
+ return more
+ }
+ // Only the doubled `||` marker forms a spoiler boundary — a lone `|`
+ // (e.g. inside a table row, which this codebase's Streamdown/GFM
+ // pipeline also parses) must fall through untouched.
+ if (size < 2) return nok(code)
+ const token = effects.exit("spoilerSequenceTemporary")
+ const after = classifyCharacter(code)
+ token._open = !after || (after === 2 && Boolean(before))
+ token._close = !before || (before === 2 && Boolean(after))
+ return ok(code)
+ }
+ }
+}
+
+/** mdast-util-from-markdown extension: turns the `spoiler` token into a `spoiler` mdast node. */
+export function spoilerFromMarkdown(): FromMarkdownExtension {
+ return {
+ canContainEols: ["spoiler"],
+ enter: { spoiler: enterSpoiler },
+ exit: { spoiler: exitSpoiler },
+ }
+}
+
+const enterSpoiler: FromMarkdownHandle = function (this: CompileContext, token) {
+ this.enter({ type: "spoiler", children: [] }, token)
+}
+
+const exitSpoiler: FromMarkdownHandle = function (this: CompileContext, token) {
+ this.exit(token)
+}
diff --git a/src/shared/src/utils/community-notification-copy.ts b/src/shared/src/utils/community-notification-copy.ts
index 9fb54dd3b..f1aa32c3e 100644
--- a/src/shared/src/utils/community-notification-copy.ts
+++ b/src/shared/src/utils/community-notification-copy.ts
@@ -1,13 +1,12 @@
import { truncateMessagePreview } from "../constants/community";
-import { stripInlineMarkup } from "./title";
+import { messagePreviewText, type MessagePreviewInput } from "../lib/message-preview";
export type CommunityNotificationConversationKind = "dm" | "channel" | "thread";
-export interface CommunityNotificationCopyInput {
+export interface CommunityNotificationCopyInput extends MessagePreviewInput {
conversationKind: CommunityNotificationConversationKind;
authorName: string | null;
content: string;
- attachmentContentTypes: ReadonlyArray<string | null | undefined>;
serverName?: string | null;
channelName?: string | null;
parentChannelName?: string | null;
@@ -22,23 +21,11 @@ function displayName(value: string | null | undefined, fallback: string): string
return value?.trim() || fallback;
}
-function attachmentFallback(contentTypes: ReadonlyArray<string | null | undefined>): string {
- const normalized = contentTypes.map((value) => value?.toLowerCase() ?? "");
- if (normalized.some((value) => value.startsWith("image/"))) return "Photo";
- if (normalized.some((value) => value.startsWith("video/"))) return "Video";
- if (normalized.some((value) => value.startsWith("audio/"))) return "Audio";
- if (normalized.length > 0) return "Attachment";
- return "New message";
-}
-
export function buildCommunityNotificationCopy(
input: CommunityNotificationCopyInput,
): CommunityNotificationCopy {
const authorName = displayName(input.authorName, "Alook");
- const readable = stripInlineMarkup(input.content)
- .replace(/\s+/gu, " ")
- .trim();
- const preview = readable || attachmentFallback(input.attachmentContentTypes);
+ const preview = messagePreviewText(input) || "New message";
if (input.conversationKind === "dm") {
return {
diff --git a/src/shared/src/utils/title.ts b/src/shared/src/utils/title.ts
index f06433cbf..097305ce2 100644
--- a/src/shared/src/utils/title.ts
+++ b/src/shared/src/utils/title.ts
@@ -1,3 +1,5 @@
+import { messagePreviewText, type MessagePreviewInput } from "../lib/message-preview";
+
/**
* Derive a conversation title from the first message body: collapse whitespace,
* trim, and cap length at a word boundary when possible.
@@ -14,45 +16,8 @@ export function truncateTitle(text: string, maxLen = 50): string {
return title + "...";
}
-/**
- * Strip markdown / chat-syntax markup to plain readable text.
- *
- * A community thread's name is derived from the first words of the anchor
- * message body, which is raw markdown and may carry `||spoiler||`, `<spoiler>`
- * HTML tags, `**bold**`, `# headings`, `[label](url)` links, `@mention`
- * discriminators, and code spans. Left as-is those tokens render literally in
- * the Threads panel / breadcrumb and get re-interpreted once the name is
- * spliced into the `thread_created` system message body. This flattens them to
- * the human-readable text so the derived name is clean.
- *
- * Regex-based on purpose: `src/shared` has no markdown/AST dependency, and a
- * full remark pipeline is overkill for a six-word title.
- */
export function stripInlineMarkup(raw: string): string {
- return raw
- // Fenced code blocks → keep inner text, drop the ``` fences.
- .replace(/```[^\n]*\n?([\s\S]*?)```/g, "$1")
- .replace(/~~~[^\n]*\n?([\s\S]*?)~~~/g, "$1")
- // Images ![alt](url) → alt text.
- .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
- // Links [label](url) / [label][ref] → label.
- .replace(/\[([^\]]*)\]\((?:[^)]*)\)/g, "$1")
- .replace(/\[([^\]]*)\]\[[^\]]*\]/g, "$1")
- // HTML/XML-style tags (<spoiler>, </spoiler>, <br/>, …).
- .replace(/<\/?[a-zA-Z][^>]*>/g, "")
- // `||spoiler||` → inner text.
- .replace(/\|\|([\s\S]*?)\|\|/g, "$1")
- // Inline code `code` → inner text.
- .replace(/`+([^`]*)`+/g, "$1")
- // Emphasis / strong / strike markers.
- .replace(/(\*\*|__|~~|\*|_)/g, "")
- // `@name#0042` discriminator → `@name`. Name-run allows spaces but must end
- // in a non-whitespace char, matching the display grammar in
- // `chat-syntax-plugin.ts` so a spaced-name mention (`@John Doe#0042`) strips
- // correctly and ordinary prose (`issue #0042`) does not.
- .replace(/(@[^@#\n\r]*[^@#\n\r\s])#\d{4,}/gu, "$1")
- // Line-leading block markers: heading #, blockquote >, list bullets/numbers.
- .replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d+[.)]\s+)/gm, "");
+ return messagePreviewText({ content: raw })
}
/**
@@ -61,12 +26,12 @@ export function stripInlineMarkup(raw: string): string {
* `fallback` when the message yields no readable text.
*/
export function deriveThreadName(
- raw: string | null | undefined,
+ raw: string | MessagePreviewInput | null | undefined,
fallback: string,
maxWords = 6,
maxChars = 60,
): string {
- const cleaned = stripInlineMarkup(raw ?? "")
+ const cleaned = messagePreviewText(typeof raw === "string" ? { content: raw } : raw ?? {})
.replace(/\s+/g, " ")
.trim();
const name = cleaned.split(" ").filter(Boolean).slice(0, maxWords).join(" ").slice(0, maxChars).trim();
diff --git a/src/shared/test/community-resources.contract.test.ts b/src/shared/test/community-resources.contract.test.ts
index c53fa581f..53c8c4e18 100644
--- a/src/shared/test/community-resources.contract.test.ts
+++ b/src/shared/test/community-resources.contract.test.ts
@@ -37,6 +37,20 @@ describe("current community resources", () => {
})
})
+describe("canonical reply resources", () => {
+ it("accepts one full same-channel reply target and rejects unrelated or duplicated rows", () => {
+ const target = { ...communityResourceMessageFixture.message, id: "target", replyToId: null }
+ const message = { ...target, id: "root", replyToId: target.id }
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: message.channelId, message, relatedMessages: [target], profiles: communityResourceMessageFixture.profiles }
+ expect(CommunityMessageReadSchema.parse(value)).toEqual(value)
+ for (const relatedMessages of [
+ [{ ...target, channelId: "foreign" }], [{ ...target, id: "unrelated" }], [target, target], [message],
+ [target, { ...target, id: "second-level" }],
+ ]) expect(CommunityMessageReadSchema.safeParse({ ...value, relatedMessages }).success).toBe(false)
+ expect(CommunityMessageReadSchema.safeParse({ ...value, channelId: "foreign" }).success).toBe(false)
+ })
+})
+
describe("conversation entry resource", () => {
const entry = () => ({
contractVersion: BUSINESS_SCHEMA_VERSION,
@@ -182,7 +196,7 @@ describe("nested current resource facts", () => {
describe("complete message author dependency graphs", () => {
const author = { id: "author", name: "Former", discriminator: "0042", avatar: null, avatarVersion: 0 }
const replyAuthor = { ...author, id: "reply-author", name: "Reply author" }
- const message = { ...communityResourceMessageFixture.message, authorId: author.id, replyToId: "prior", replyTo: { id: "prior", authorId: replyAuthor.id, authorName: replyAuthor.name, text: "Prior" } }
+ const message = { ...communityResourceMessageFixture.message, authorId: author.id, replyToId: "prior", replyTo: { id: "prior", authorId: replyAuthor.id, authorName: replyAuthor.name } }
it("requires every live author and preserves real nullable profile fields", () => {
const graph = { messages: [message], profiles: [author, replyAuthor] }
expect(CommunityMessageResourcesSchema.parse(graph)).toEqual(graph)
@@ -198,7 +212,7 @@ describe("complete message author dependency graphs", () => {
expect(CommunityMessageResourcesSchema.safeParse(graph).success).toBe(false)
})
it("keeps an explicit deleted reply sentinel separate from a missing live person", () => {
- const sentinel = { ...message, replyTo: { id: "prior", authorName: "Deleted user", text: "", deleted: true } }
+ const sentinel = { ...message, replyTo: { id: "prior", authorName: "Deleted user", deleted: true } }
expect(CommunityMessageResourcesSchema.parse({ messages: [sentinel], profiles: [author] }).messages[0].replyTo).toEqual(sentinel.replyTo)
expect(communityMessageProfileIds([sentinel])).toEqual([author.id])
})
diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.ts
index 025665856..2768a7225 100644
--- a/src/shared/test/community-ws-events.contract.test.ts
+++ b/src/shared/test/community-ws-events.contract.test.ts
@@ -173,6 +173,17 @@ describe("Community browser event runtime contract", () => {
})).toMatchObject({ reason: "unknown-community-type" })
})
+ it("validates full reply targets before a message event can publish any resource", () => {
+ const base = communityWsEventFixtures["community:message.create"]
+ const target = { ...base.message, id: "target", replyToId: null }
+ const event = { ...base, message: { ...base.message, replyToId: target.id }, relatedMessages: [target] }
+ expect(CommunityWsEventSchema.parse(event)).toEqual(event)
+ for (const relatedMessages of [
+ [{ ...target, channelId: "foreign" }], [{ ...target, id: "unrelated" }], [target, target], [event.message],
+ [target, { ...target, id: "second-level" }],
+ ]) expect(CommunityWsEventSchema.safeParse({ ...event, relatedMessages }).success).toBe(false)
+ })
+
it("keeps exact and candidate guards distinct", () => {
expect(isCommunityEventType("community:message.create")).toBe(true)
expect(isCommunityEventType("community:future")).toBe(false)
diff --git a/src/shared/test/queries/community-forum-message-pagination.test.ts b/src/shared/test/queries/community-forum-message-pagination.test.ts
index 27967f49d..3d3508229 100644
--- a/src/shared/test/queries/community-forum-message-pagination.test.ts
+++ b/src/shared/test/queries/community-forum-message-pagination.test.ts
@@ -66,11 +66,11 @@ describe("forum opener message pagination against real SQLite", () => {
sqlite.prepare("UPDATE community_message SET embeds = ?, client_nonce = ?, friendship_id = ? WHERE id = ?")
.run('[{"title":"Native"}]', "nonce", "friendship", "m1")
const reads = [
- { row: await messageQueries.getMessage(db as never, "m1"), extra: ["seq", "authorEmail"] },
+ { row: await messageQueries.getMessage(db as never, "m1"), extra: ["seq", "friendshipId", "authorEmail"] },
{ row: await messageQueries.getMessageByAuthorAndNonce(db as never, "u1", "nonce"), extra: ["seq", "clientNonce", "authorEmail"] },
{ row: (await messageQueries.getMessagesByIds(db as never, ["m1"]))[0], extra: ["seq", "authorEmail"] },
{ row: await messageQueries.getMessageInScope(db as never, "m1", { channelId: "c1" }), extra: ["authorEmail"] },
- { row: (await messageQueries.getMessagesByIdsInChannels(db as never, ["m1"], ["c1"]))[0], extra: ["seq", "clientNonce", "discriminator", "authorEmail"] },
+ { row: (await messageQueries.getMessagesByIdsInChannels(db as never, ["m1"], ["c1"]))[0], extra: ["seq", "clientNonce", "friendshipId", "discriminator", "authorEmail"] },
{ row: (await messageQueries.getFirstMessageResourcesByChannelIds(db as never, ["c1"]))[0], extra: ["seq", "clientNonce"] },
{ row: (await messageQueries.listMessages(db as never, { channelId: "c1", limit: 6 })).find((row) => row.id === "m1"), extra: ["seq", "clientNonce", "friendshipId", "authorEmail"] },
]
diff --git a/src/shared/test/queries/community-notification-target.test.ts b/src/shared/test/queries/community-notification-target.test.ts
index ef4b6a3e7..7e7486258 100644
--- a/src/shared/test/queries/community-notification-target.test.ts
+++ b/src/shared/test/queries/community-notification-target.test.ts
@@ -31,13 +31,16 @@ describe("community notification target query", () => {
id TEXT PRIMARY KEY NOT NULL,
author_id TEXT NOT NULL,
content TEXT NOT NULL,
- channel_id TEXT NOT NULL
+ channel_id TEXT NOT NULL,
+ type TEXT, friendship_id TEXT, embeds TEXT
);
CREATE TABLE community_attachment (
id TEXT PRIMARY KEY NOT NULL,
content_type TEXT,
+ filename TEXT NOT NULL DEFAULT '', size INTEGER,
created_at TEXT NOT NULL
);
+ CREATE TABLE community_bot_creation_request (id TEXT PRIMARY KEY, message_id TEXT);
CREATE TABLE community_message_attachment (message_id TEXT, attachment_id TEXT, position INTEGER);
INSERT INTO user (id, name) VALUES
('author-1', 'Alice'),
@@ -85,7 +88,7 @@ describe("community notification target query", () => {
serverName: null,
channelName: null,
parentChannelName: null,
- attachmentContentTypes: [],
+ attachments: [],
});
});
@@ -99,7 +102,7 @@ describe("community notification target query", () => {
serverName: "Studio",
channelName: "general",
parentChannelName: null,
- attachmentContentTypes: ["image/png", "application/pdf"],
+ attachments: [{ id: "attachment-1", name: "", contentType: "image/png", sizeBytes: null }, { id: "attachment-2", name: "", contentType: "application/pdf", sizeBytes: null }],
});
});
@@ -118,7 +121,7 @@ describe("community notification target query", () => {
serverName: "Studio",
channelName,
parentChannelName,
- attachmentContentTypes: [],
+ attachments: [],
});
},
);
@@ -133,7 +136,7 @@ describe("community notification target query", () => {
serverName: " ",
channelName: null,
parentChannelName: " ",
- attachmentContentTypes: [],
+ attachments: [],
});
});
@@ -147,7 +150,7 @@ describe("community notification target query", () => {
serverName: null,
channelName: "Still pushable",
parentChannelName: null,
- attachmentContentTypes: [],
+ attachments: [],
});
});
diff --git a/src/shared/test/utils/community-notification-copy.test.ts b/src/shared/test/utils/community-notification-copy.test.ts
index f02133dd8..d7cd2474d 100644
--- a/src/shared/test/utils/community-notification-copy.test.ts
+++ b/src/shared/test/utils/community-notification-copy.test.ts
@@ -4,7 +4,7 @@ import { buildCommunityNotificationCopy } from "../../src/utils/community-notifi
const base = {
authorName: " Alice ",
content: "**Hello** [there](https://example.test)\nnext line",
- attachmentContentTypes: [] as Array<string | null>,
+ attachments: [],
};
describe("buildCommunityNotificationCopy", () => {
@@ -52,13 +52,13 @@ describe("buildCommunityNotificationCopy", () => {
conversationKind: "thread",
authorName: " ",
content: " ",
- attachmentContentTypes: ["application/pdf", "IMAGE/PNG"],
+ attachments: [{ name: "notes.pdf", contentType: "application/pdf" }, { name: "photo.png", contentType: "IMAGE/PNG" }],
serverName: null,
channelName: null,
parentChannelName: null,
})).toEqual({
title: "Server · #Channel · Thread",
- body: "Alook: Photo",
+ body: "Alook: Attachment: notes.pdf Photo: photo.png",
});
});
@@ -72,7 +72,7 @@ describe("buildCommunityNotificationCopy", () => {
...base,
conversationKind: "dm",
content: "",
- attachmentContentTypes,
+ attachments: attachmentContentTypes.map(contentType => ({ name: "", contentType })),
})).toEqual({
title: "Alice",
body: expected,
diff --git a/src/shared/test/utils/title.test.ts b/src/shared/test/utils/title.test.ts
index 3a59f3cf0..b73d2caa7 100644
--- a/src/shared/test/utils/title.test.ts
+++ b/src/shared/test/utils/title.test.ts
@@ -41,13 +41,13 @@ describe("truncateTitle", () => {
});
describe("stripInlineMarkup", () => {
- it("unwraps ||spoiler|| to its inner text", () => {
- expect(stripInlineMarkup("a ||secret|| b")).toBe("a secret b");
+ it("masks spoiler text", () => {
+ expect(stripInlineMarkup("a ||secret|| b")).toBe("a [Spoiler] b");
});
- it("removes HTML/XML-style tags but keeps their text", () => {
- expect(stripInlineMarkup("<spoiler>secret</spoiler> plan")).toBe("secret plan");
- expect(stripInlineMarkup("line<br/>break")).toBe("linebreak");
+ it("retains literal typed HTML", () => {
+ expect(stripInlineMarkup("<spoiler>secret</spoiler> plan")).toBe("<spoiler>secret</spoiler> plan");
+ expect(stripInlineMarkup("line<br/>break")).toBe("line<br/>break");
});
it("strips bold/emphasis/strike markers", () => {
@@ -56,7 +56,7 @@ describe("stripInlineMarkup", () => {
it("keeps inner text of inline and fenced code", () => {
expect(stripInlineMarkup("run `npm test` now")).toBe("run npm test now");
- expect(stripInlineMarkup("```ts\nconst x = 1\n```")).toBe("const x = 1\n");
+ expect(stripInlineMarkup("```ts\nconst x = 1\n```")).toBe("Code: const x = 1");
});
it("strips leading block markers (heading, quote, list)", () => {
@@ -68,19 +68,19 @@ describe("stripInlineMarkup", () => {
it("keeps link/image label text", () => {
expect(stripInlineMarkup("see [the docs](https://x.io)")).toBe("see the docs");
- expect(stripInlineMarkup("![alt text](a.png) after")).toBe("alt text after");
- expect(stripInlineMarkup("ref [label][1]")).toBe("ref label");
+ expect(stripInlineMarkup("![alt text](a.png) after")).toBe("Photo: alt text after");
+ expect(stripInlineMarkup("ref [label][1]")).toBe("ref [label][1]");
});
- it("drops a @mention discriminator but keeps unicode names", () => {
- expect(stripInlineMarkup("hi @李四#0042 there")).toBe("hi @李四 there");
+ it("keeps a @mention discriminator but keeps unicode names", () => {
+ expect(stripInlineMarkup("hi @李四#0042 there")).toBe("hi @李四#0042 there");
});
});
describe("deriveThreadName", () => {
it("strips markup then keeps the first six words", () => {
expect(deriveThreadName("||secret|| plan **for** the big launch today", "fallback")).toBe(
- "secret plan for the big launch",
+ "[Spoiler] plan for the big launch",
);
});
@@ -93,7 +93,7 @@ describe("deriveThreadName", () => {
expect(deriveThreadName("", "General")).toBe("General");
expect(deriveThreadName(" \n\t ", "General")).toBe("General");
expect(deriveThreadName(null, "General")).toBe("General");
- expect(deriveThreadName("<br/>", "General")).toBe("General");
+ expect(deriveThreadName("<br/>", "General")).toBe("<br/>");
});
it("collapses whitespace across lines", () => {
diff --git a/src/web/blog/mdx-options.ts b/src/web/blog/mdx-options.ts
index 5edaf7ead..f260fc723 100644
--- a/src/web/blog/mdx-options.ts
+++ b/src/web/blog/mdx-options.ts
@@ -1,10 +1,13 @@
import path from "node:path";
+import { createRequire } from "node:module";
+
+const require = createRequire(import.meta.url);
export const blogMdxOptions: {
remarkPlugins: string[]
rehypePlugins: Array<string | [string, ...unknown[]]>
} = {
- remarkPlugins: ["remark-gfm"],
+ remarkPlugins: [require.resolve("remark-gfm")],
rehypePlugins: [
path.resolve(import.meta.dirname, "rehype-blog-images.mjs"),
"rehype-slug",
diff --git a/src/web/package.json b/src/web/package.json
index 85c9d08c9..cba73a8fd 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -104,14 +104,8 @@
"jose": "^6.2.13",
"katex": "^0.19.0",
"lucide-react": "^1.61.0",
- "mdast-util-find-and-replace": "^3.0.3",
"mdast-util-from-markdown": "^2.1.0",
"mdast-util-to-hast": "^13.2.1",
- "micromark-util-chunked": "^2.0.1",
- "micromark-util-classify-character": "^2.0.1",
- "micromark-util-resolve-all": "^2.0.1",
- "micromark-util-symbol": "^2.0.1",
- "micromark-util-types": "^2.0.3",
"nanoid": "^5.1.16",
"next": "16.4.2",
"next-themes": "^0.4.6",
@@ -130,9 +124,7 @@
"rehype-pretty-code": "^0.14.5",
"rehype-sanitize": "^6.0.0",
"rehype-slug": "^6.0.0",
- "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
- "remark-math": "6.0.0",
"remark-parse": "^11.0.0",
"resend": "6.34.1",
"shadcn": "^4.22.1",
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 09b8813a8..ec6740fba 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
@@ -280,6 +280,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetMessageByAuthorAndNonce.mockResolvedValue(null)
mockListMembers.mockResolvedValue([])
mockListByMessageIds.mockResolvedValue([])
+ mockListReactionsByMessageIds.mockResolvedValue([])
mockListMemberUserIds.mockResolvedValue([])
mockGetMessagesByIdsInScope.mockResolvedValue([])
mockCreateMentions.mockResolvedValue(undefined)
@@ -313,7 +314,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(response.status).toBe(replay ? 200 : 201)
expect(response.headers.get("x-alook-community-contract")).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(response.cookies.get("alook_ga_session")).toBeUndefined()
- expect(await response.json()).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: replay, message: {
+ expect(await response.json()).toEqual({ relatedMessages: [], profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], contractVersion: BUSINESS_SCHEMA_VERSION, 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: [],
} })
@@ -551,7 +552,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped?: boolean }
expect(res.status).toBe(201)
- expect(body).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
+ expect(body).toEqual({ relatedMessages: [], profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: false,
message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),
})
@@ -563,12 +564,12 @@ describe("POST /api/community/channels/[id]/messages", () => {
replyToId: "reply_target", embeds: null, createdAt: "2026-06-30T00:00:00.000Z" }
mockGetMessage.mockResolvedValue(row)
if (replay) mockGetMessageByAuthorAndNonce.mockResolvedValue(row)
- mockGetMessageInScope.mockResolvedValue({ id: "reply_target", channelId: "c1", authorId: "u2", authorName: "Bob", content: "prior" })
- mockGetMessagesByIdsInScope.mockResolvedValue([{ id: "reply_target", channelId: "c1", authorId: "u2", authorName: "Bob", content: "prior" }])
+ mockGetMessageInScope.mockResolvedValue({ seq: 1, createdAt: "2026-06-29T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", embeds: null, mentionType: null, authorImage: null, authorAvatarVersion: 0, id: "reply_target", channelId: "c1", authorId: "u2", authorName: "Bob", content: "prior" })
+ mockGetMessagesByIdsInScope.mockResolvedValue([{ seq: 1, createdAt: "2026-06-29T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", embeds: null, mentionType: null, authorImage: null, authorAvatarVersion: 0, id: "reply_target", channelId: "c1", authorId: "u2", authorName: "Bob", content: "prior" }])
const response = await POST(postReq({ content: "@Bob reply", nonce: "n1", replyToId: "reply_target" }), ctx)
expect(response.status).toBe(replay ? 200 : 201)
expect((await response.json()).message).toMatchObject({ id: row.id, replyToId: "reply_target",
- replyTo: { id: "reply_target", authorId: "u2", authorName: "Bob", text: "prior" } })
+ replyTo: { id: "reply_target", authorId: "u2", authorName: "Bob", } })
expect(mockGetMessagesByIdsInScope).toHaveBeenCalledWith(expect.anything(), ["reply_target"], { channelId: "c1" })
})
@@ -576,10 +577,10 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetMessageByAuthorAndNonce.mockResolvedValue({ id: "reply_message", seq: 8, clientNonce: "n1", channelId: "c1", authorId: "u1", authorName: "Alice",
authorImage: null, authorAvatarVersion: 0, content: "reply", type: "default", mentionType: null,
replyToId: "reply_target", embeds: null, createdAt: "2026-06-30T00:00:00.000Z" })
- mockGetMessagesByIdsInScope.mockResolvedValue([{ id: "reply_target", channelId: "other", authorId: "u2", authorName: "Secret", content: "private" }])
+ mockGetMessagesByIdsInScope.mockResolvedValue([{ seq: 1, createdAt: "2026-06-29T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", embeds: null, mentionType: null, authorImage: null, authorAvatarVersion: 0, id: "reply_target", channelId: "other", authorId: "u2", authorName: "Secret", content: "private" }])
const response = await POST(postReq({ content: "reply", nonce: "n1" }), ctx)
expect(response.status).toBe(200)
- expect((await response.json()).message.replyTo).toEqual({ id: "reply_target", authorName: "Deleted user", text: "", deleted: true })
+ expect((await response.json()).message.replyTo).toEqual({ id: "reply_target", authorName: "Deleted user", deleted: true })
})
it("returns the original canonical contract for a same-nonce replay", async () => {
@@ -604,7 +605,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped: boolean }
expect(res.status).toBe(200)
- expect(body).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
+ expect(body).toEqual({ relatedMessages: [], profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1",
message: expect.objectContaining({ id: "m-existing", seq: 8, clientNonce: "n1" }),
deduped: true,
@@ -637,7 +638,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(response.status).toBe(201)
expect(response.headers.get("x-alook-community-contract")).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(response.cookies.get("alook_ga_session")).toBeUndefined()
- expect(await response.json()).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
+ expect(await response.json()).toEqual({ relatedMessages: [], profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: false,
message: {
id: "m_full", channelId: "c1", seq: 42, clientNonce: "client-1",
@@ -1127,7 +1128,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
// The (mocked) scoped query only ever returns in-scope rows — "r-out-of-scope"
// and "r-missing" are absent, simulating the real WHERE-clause scoping.
mockGetMessagesByIdsInScope.mockResolvedValue([
- { id: "r-in-scope", authorId: "zed", authorName: "Zed", content: "original", channelId: "c1", dmConversationId: null },
+ { seq: 1, createdAt: "2026-06-29T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", embeds: null, mentionType: null, authorImage: null, authorAvatarVersion: 0, id: "r-in-scope", authorId: "zed", authorName: "Zed", content: "original", channelId: "c1", dmConversationId: null },
])
const res = await GET(getReq(), ctx)
@@ -1135,10 +1136,10 @@ describe("GET /api/community/channels/[id]/messages", () => {
const body = await res.json() as { messages: Array<{ id: string; replyTo?: { id: string; authorName: string; text: string; deleted?: boolean } }> }
const byId = new Map(body.messages.map((m) => [m.id, m]))
- expect(byId.get("m-a")?.replyTo).toEqual({ id: "r-in-scope", authorId: "zed", authorName: "Zed", text: "original" })
- expect(byId.get("m-b")?.replyTo).toEqual({ id: "r-out-of-scope", authorName: "Deleted user", text: "", deleted: true })
- expect(byId.get("m-c")?.replyTo).toEqual({ id: "r-missing", authorName: "Deleted user", text: "", deleted: true })
- expect(byId.get("m-d")?.replyTo).toEqual({ id: "r-in-scope", authorId: "zed", authorName: "Zed", text: "original" })
+ expect(byId.get("m-a")?.replyTo).toEqual({ id: "r-in-scope", authorId: "zed", authorName: "Zed" })
+ expect(byId.get("m-b")?.replyTo).toEqual({ id: "r-out-of-scope", authorName: "Deleted user", deleted: true })
+ expect(byId.get("m-c")?.replyTo).toEqual({ id: "r-missing", authorName: "Deleted user", deleted: true })
+ expect(byId.get("m-d")?.replyTo).toEqual({ id: "r-in-scope", authorId: "zed", authorName: "Zed" })
expect(byId.get("m-e")?.replyTo).toBeUndefined()
expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
@@ -1154,11 +1155,11 @@ describe("GET /api/community/channels/[id]/messages", () => {
])
mockGetMessagesByIdsInScope
.mockRejectedValueOnce(new Error("D1_ERROR: database is locked"))
- .mockResolvedValueOnce([{ id: "r1", authorId: "reply-author", authorName: "B", content: "root", channelId: "c1", dmConversationId: null }])
+ .mockResolvedValueOnce([{ seq: 1, createdAt: "2026-06-29T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", embeds: null, mentionType: null, authorImage: null, authorAvatarVersion: 0, id: "r1", authorId: "reply-author", authorName: "B", content: "root", channelId: "c1", dmConversationId: null }])
const res = await GET(getReq(), ctx)
const body = await res.json()
expect(body.messages).toHaveLength(1)
- expect(body.messages[0].replyTo).toEqual({ id: "r1", authorId: "reply-author", authorName: "B", text: "root" })
+ expect(body.messages[0].replyTo).toEqual({ id: "r1", authorId: "reply-author", authorName: "B" })
expect(body.page.hasMoreOlder).toBe(false)
expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(2)
expect(mockListMessages).toHaveBeenCalledTimes(1)
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index 1b3c5e340..76027a284 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -215,14 +215,14 @@ describe("GET /api/community/messages/[id]", () => {
})
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
mockGetMessagesByIdsInScope.mockResolvedValue([
- { id: "m0", authorId: "bob", authorName: "Bob", content: "question?", channelId: "c1" },
+ { seq: 1, createdAt: "2026-06-29T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", embeds: null, mentionType: null, authorImage: null, authorAvatarVersion: 0, id: "m0", authorId: "bob", authorName: "Bob", content: "question?", channelId: "c1" },
])
const res = await GET(req(), { params: { id: "m1" } } as any)
expect(res.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
const envelope = CommunityMessageReadSchema.parse(await res.json())
const body = envelope.message
- expect(body.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob", text: "question?" })
+ expect(body.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob" })
const [, , scope] = mockGetMessagesByIdsInScope.mock.calls[0]
expect(scope).toEqual({ channelId: "c1" })
})
@@ -255,7 +255,7 @@ describe("GET /api/community/messages/[id]", () => {
const envelope = CommunityMessageReadSchema.parse(await res.json())
const body = envelope.message
// Target not found in scope — mapper returns the `deleted` sentinel.
- expect(body.replyTo).toEqual({ id: "m0", authorName: "Deleted user", text: "", deleted: true })
+ expect(body.replyTo).toEqual({ id: "m0", authorName: "Deleted user", deleted: true })
})
it("returns 404 when the message doesn't exist", async () => {
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 ae0229b84..b64b85ac1 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -181,8 +181,8 @@ async function handleHumanGet(
}
const payload = await readCommunityMessageResource(db, userId, message, contract)
- const profiles = await readCommunityMessageProfiles(db, [payload])
- return writeCommunityContractJSON(CommunityMessageReadSchema.parse({ contractVersion: contract, channelId: message.channelId, message: payload, profiles }), contract)
+ const profiles = await readCommunityMessageProfiles(db, [payload.message, ...payload.relatedMessages])
+ return writeCommunityContractJSON(CommunityMessageReadSchema.parse({ contractVersion: contract, channelId: message.channelId, ...payload, profiles }), contract)
}
/**
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 20e9821b3..19421c64a 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -1,5 +1,8 @@
"use client"
+import { useCanonicalMessagesById } from "@/lib/community-db/projections"
+import { messagePreviewText } from "@alook/shared"
+
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useAtom, useCreateAtom } from "@tanstack/react-store"
@@ -169,10 +172,13 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
const messages = useMemo(() => historyAllowed ? fetchedMessages : [], [fetchedMessages, historyAllowed])
+ const [contextSheetId, setContextSheetId] = useAtom(useCreateAtom<string | null>(null))
const [contextSheetSeq, setContextSheetSeq] = useAtom(useCreateAtom<number | null>(null))
+ const jumpToSeq = useCallback((seq: number | null) => { setContextSheetId(null); setContextSheetSeq(seq) }, [setContextSheetSeq, setContextSheetId])
+ useEffect(() => { setContextSheetId(null) }, [dmId, setContextSheetId])
useDmSeqContext({ dmId, historyAllowed,
navigationAllowed: routeCommitted && !navigationBlocked,
- setContextSeq: setContextSheetSeq,
+ setContextSeq: jumpToSeq,
})
// DM composer has no "current server" — flatten every member server's
// channels into one cross-server candidate list so a `/`-ref can be
@@ -272,7 +278,6 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
// pill via the `jumpToSeq` UI-handler. The DM view has no in-place scroll
// target prop (unlike the channel page), so always open the context sheet,
// which resolves seq→id and shows the message with surrounding context.
- const jumpToSeq = useCallback((seq: number) => setContextSheetSeq(seq), [setContextSheetSeq])
useEffect(() => {
communityRuntime.ui.actions.registerUiHandlers({ jumpToSeq })
return () => communityRuntime.ui.actions.registerUiHandlers({ jumpToSeq: undefined })
@@ -287,7 +292,11 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
}
}, [communityRuntime, dmId])
- const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))
+ const [replyIntent, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))
+ const replyIds = useMemo(() => replyIntent ? [replyIntent.id] : [], [replyIntent])
+ const replyResources = useCanonicalMessagesById(replyIds)
+ const replyMessage = replyIntent ? replyResources?.get(replyIntent.id) : undefined
+ const replyTo = useMemo(() => replyIntent && replyMessage ? { ...replyIntent, text: messagePreviewText(replyMessage) } : replyIntent, [replyIntent, replyMessage])
const [localSubmitVersion, setLocalSubmitVersion] = useAtom(useCreateAtom(0))
useEffect(() => {
@@ -335,7 +344,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
id: m.id,
...(m.authorId ? { authorId: m.authorId } : {}),
authorName: m.authorName ?? "",
- text: m.content ?? "",
+ text: messagePreviewText(m),
})
}
},
@@ -453,6 +462,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
>
<ConversationFooterSlotProvider>
{dmBlocked ? null : readDenied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : metadata.status === "retryable-error" ? <ConversationResolutionErrorFrame as="div" onRetry={metadata.retry} retrying={metadata.retrying} /> : !historyAllowed && initialLoadError ? <ConversationResolutionErrorFrame as="div" onRetry={retryInitialLoad} retrying={retryingInitialLoad} /> : <MessageList
+ onOpenContextId={(id) => { setContextSheetSeq(null); setContextSheetId(id) }}
key={dmId}
variant="dm"
channel={displayName}
@@ -551,16 +561,18 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
</ConversationFooterSlotProvider>
</main>
{historyAllowed && <MessageContextSheet
- open={contextSheetSeq !== null}
- onOpenChange={(v) => { if (!v) setContextSheetSeq(null) }}
+ open={contextSheetSeq !== null || contextSheetId !== null}
+ onOpenChange={(v) => { if (!v) { setContextSheetSeq(null); setContextSheetId(null) } }}
channelId={dmId}
targetSeq={contextSheetSeq}
+ targetMessageId={contextSheetId ?? undefined}
type="dm"
onOpenProfile={openProfile}
resolveUserName={resolveUserName}
onReply={dmBlocked ? undefined : (target) => {
setReplyTo(target)
setContextSheetSeq(null)
+ setContextSheetId(null)
}}
/>}
</>
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index 6fd4e9c0d..080cdf1fd 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -142,6 +142,7 @@ export function TextChannelSurface({
>
<ConversationFooterSlotProvider>
<MessageList
+ onOpenContextId={controller.openContextId}
key={channelId}
channel={channelName}
messages={feed.messages}
@@ -238,6 +239,7 @@ export function TextChannelSurface({
serverId={controller.contextTarget?.serverId ?? serverId}
channelLabel={controller.contextTarget?.label}
targetSeq={controller.contextTarget?.seq ?? null}
+ targetMessageId={controller.contextTarget?.messageId}
pinnedIds={controller.pinnedIds}
onOpenProfile={onOpenProfile}
resolveUserName={resolveUserName}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 7e6ca5565..c969a1cbe 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -239,6 +239,7 @@ export function ThreadChannelSurface({
>
<ConversationFooterSlotProvider>
<MessageList
+ onOpenContextId={controller.openContextId}
key={channelId}
channel={displayName}
messages={controller.feed.messages}
@@ -336,6 +337,7 @@ export function ThreadChannelSurface({
serverId={controller.contextTarget?.serverId ?? serverId}
channelLabel={controller.contextTarget?.label}
targetSeq={controller.contextTarget?.seq ?? null}
+ targetMessageId={controller.contextTarget?.messageId}
pinnedIds={controller.pinnedIds}
onOpenProfile={onOpenProfile}
resolveUserName={resolveUserName}
diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
index 57f3392f7..5438522e8 100644
--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
@@ -61,7 +61,7 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
feed,
pinnedIds: new Set(), replyTo: null, setReplyTo: vi.fn(),
scrollTargetId: null, setScrollTargetId: vi.fn(), consumeScrollTarget: vi.fn(),
- contextTarget: null, setContextTarget: vi.fn(), openContextSeq: vi.fn(),
+ contextTarget: null, setContextTarget: vi.fn(), openContextSeq: vi.fn(), openContextId: vi.fn(),
onSheetReply: vi.fn(), jumpToSeq: vi.fn(),
messageActions: {} as MessageChannelControllerValue["messageActions"],
threadActions: {} as MessageChannelControllerValue["threadActions"],
diff --git a/src/web/src/components/community/messages/composer-view.dom.test.ts b/src/web/src/components/community/messages/composer-view.dom.test.ts
index 45f6bdb0c..caf6d4ec9 100644
--- a/src/web/src/components/community/messages/composer-view.dom.test.ts
+++ b/src/web/src/components/community/messages/composer-view.dom.test.ts
@@ -101,6 +101,20 @@ describe("ComposerView", () => {
expect(view.getByTestId(tid.composerInput)).toBe(editor)
})
+ it("keeps a failed selection visible with an actionable error and removal", () => {
+ const file = new File(["image"], "broken.png", { type: "image/png" })
+ const removePendingFile = vi.fn()
+ const view = render(createElement(ComposerView, baseProps({
+ pendingFiles: [{ file, preparationFailed: true, thumbnailUrl: null, thumbnailBlob: null }],
+ removePendingFile,
+ })))
+ expect(view.getByText(file.name)).toBeVisible()
+ expect(view.getByRole("alert").textContent).toBe("Could not prepare. Remove this file and try again.")
+ expect(view.queryByRole("status")).toBeNull()
+ fireEvent.click(view.getByRole("button", { name: "Remove file" }))
+ expect(removePendingFile).toHaveBeenCalledExactlyOnceWith(0)
+ })
+
it.each([false, true])("keeps the composer free of native keyboard controls and reservations (forum=%s)", async (isForumThreadBody) => {
const descriptor = Object.getOwnPropertyDescriptor(window, "webkit")
const tauriDescriptor = Object.getOwnPropertyDescriptor(window, "__TAURI__")
@@ -371,14 +385,14 @@ describe("ComposerView", () => {
)
})
- it("shows the exact same-author reply target as one stripped, whole-row-truncated line", async () => {
+ it("shows the exact same-author reply target as one semantic, whole-row-truncated line", async () => {
const first = {
authorName: "Ada",
- text: "**First** target with [docs](https://example.test) " + "x".repeat(320),
+ text: "First target with docs " + "x".repeat(320),
}
const second = {
authorName: "Ada",
- text: "_Second_ target",
+ text: "Second target",
}
const renderer = render(
createElement(ComposerView, baseProps({ replyingTo: first })),
diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsx
index 264a27ac3..f67330dd9 100644
--- a/src/web/src/components/community/messages/composer-view.tsx
+++ b/src/web/src/components/community/messages/composer-view.tsx
@@ -12,7 +12,7 @@ import {
Smile,
X,
} from "lucide-react"
-import { isMobile, stripInlineMarkup } from "@alook/shared"
+import { isMobile } from "@alook/shared"
import { Skeleton } from "@/components/ui/skeleton"
import type { PendingFile } from "@/hooks/use-file-attachments"
import type {
@@ -95,7 +95,7 @@ export function ComposerView({
}: ComposerViewProps) {
const nativeMobile = useHydratedClient() && isMobile()
const replyPreview = replyingTo
- ? stripInlineMarkup(replyingTo.text).replace(/\s+/g, " ").trim()
+ ? replyingTo.text
: null
const composerRadius = replyingTo || pendingFiles.length > 0
@@ -158,7 +158,7 @@ export function ComposerView({
<div
key={pendingFile.draftId ?? index}
aria-busy={pendingFile.preparing || undefined}
- className="group relative flex items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-xs"
+ className="group relative flex max-w-full flex-wrap items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-xs"
>
{isImage ? (
<ImageIcon className="size-3.5 text-muted-foreground" />
@@ -176,6 +176,7 @@ export function ComposerView({
>
<X className="size-3" />
</button>
+ {pendingFile.preparationFailed && <span role="alert" className="basis-full text-destructive">Could not prepare. Remove this file and try again.</span>}
</div>
)
})}
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
index cb9b19242..a95d6bfce 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
@@ -10,12 +10,11 @@ const mocks = vi.hoisted(() => ({
dispatch: vi.fn(),
toast: vi.fn(),
toastApiError: vi.fn(),
- deriveThreadName: vi.fn(() => "derived thread"),
+
}))
vi.mock("sonner", () => ({ toast: mocks.toast }))
vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))
-vi.mock("@alook/shared", async (load) => ({ ...await load<typeof import("@alook/shared")>(), deriveThreadName: mocks.deriveThreadName }))
const owners: CommunityDbRegistry[] = []
afterEach(async () => {
@@ -178,9 +177,8 @@ describe("createMessageActions", () => {
resolveThread = resolve
}))
const pendingThread = harness.actions.onCreateThread("m1")
- expect(mocks.deriveThreadName).toHaveBeenCalledWith("hello", "general")
expect(harness.createThreadAsync).toHaveBeenCalledWith({
- serverId: "server_1", channelId: "channel_1", messageId: "m1", name: "derived thread", assertActive: expect.any(Function),
+ serverId: "server_1", channelId: "channel_1", messageId: "m1", name: "hello", assertActive: expect.any(Function),
})
const latestOpenThread = vi.fn()
harness.actionContext.setState((state) => ({ ...state, onOpenThread: latestOpenThread }))
@@ -334,14 +332,14 @@ describe("createMessageActions", () => {
id: "m1",
authorId: "viewer_1",
authorName: "Viewer",
- text: "@Alice Smith\n> quote\n\nbody",
+ text: "@Alice Smith quote body",
})
await harness.actions.onCopy("m1")
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("@Alice Smith\n> quote\n\nbody")
await harness.actions.onCreateThread("m1")
- expect(mocks.deriveThreadName).toHaveBeenCalledWith("@Alice Smith\n> quote\n\nbody", "general")
+ expect(harness.createThreadAsync).toHaveBeenCalledWith(expect.objectContaining({ name: "@Alice Smith quote body" }))
})
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.ts b/src/web/src/components/community/messages/message-channel-controller-actions.ts
index 5e6176138..541687fbb 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.ts
@@ -1,3 +1,4 @@
+import { messagePreviewText } from "@alook/shared"
import { deriveThreadName } from "@alook/shared"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
@@ -105,7 +106,7 @@ export function createMessageActions({
id: message.id,
...(message.authorId ? { authorId: message.authorId } : {}),
authorName: message.authorName ?? "",
- text: message.content ?? "",
+ text: messagePreviewText(message),
})
}
},
@@ -133,10 +134,7 @@ export function createMessageActions({
const original = captureView(), context = actionContext.get()
original()
const message = getMessage(id)
- const content = message
- ? (message.content ?? "")
- : undefined
- const name = deriveThreadName(content, context.channelName)
+ const name = deriveThreadName(message, context.channelName)
try {
const data = await createThreadAsync({ serverId, channelId, messageId: id, name, assertActive: original })
original()
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
index b2fb1f77a..07d861149 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
@@ -566,7 +566,7 @@ describe("useMessageChannelController", () => {
expect(getMessage("confirmed")).toMatchObject({ id: "confirmed", content: "confirmed body", authorName: "Current Author", authorAvatarVersion: 7 })
})
- it("ignores non-finite seq params and projects the exact public value surface", () => {
+ it("ignores non-finite seq params and preserves independent thread actions", () => {
mocks.seq = "not-a-number"
mocks.typingIds = ["u1", "u2"]
mocks.typingNames = { u1: "Alice" }
@@ -586,18 +586,6 @@ describe("useMessageChannelController", () => {
expect(latest.typingUsers).toEqual(["Alice", "resolved:u2"])
expect(latest.feed).toBe(projectedFeed)
expect(resolveUserName).toHaveBeenCalledWith("u2")
- expect(Object.keys(latest)).toEqual([
- "feed", "pinnedIds", "replyTo", "setReplyTo", "scrollTargetId", "setScrollTargetId", "consumeScrollTarget",
- "contextTarget", "setContextTarget", "openContextSeq", "onSheetReply", "jumpToSeq",
- "messageActions", "threadActions", "acceptMessage", "localSubmitVersion", "handleTyping", "typingUsers",
- ])
- const actionKeys = [
- "onToggleReaction", "onReact", "onReply", "onPin", "onMark", "onCreateThread",
- "onCopy", "onRetry", "onDismiss", "onPreviewImage",
- "onPreviewAttachment",
- ]
- expect(Object.keys(latest.messageActions)).toEqual(actionKeys)
- expect(Object.keys(latest.threadActions)).toEqual(actionKeys)
expect(latest.threadActions.onCreateThread).toBeUndefined()
})
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 a9965963c..d14cf301e 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
@@ -1,5 +1,7 @@
"use client"
import { createAtom, createStore, useAtom, useCreateAtom } from "@tanstack/react-store";
+import { messagePreviewText } from "@alook/shared"
+import { useCanonicalMessagesById } from "@/lib/community-db/projections"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useQueryClient } from "@tanstack/react-query"
@@ -75,7 +77,11 @@ export function useMessageChannelController({
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
- const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))
+ const [replyIntent, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))
+ const replyIds = useMemo(() => replyIntent ? [replyIntent.id] : [], [replyIntent])
+ const replyResources = useCanonicalMessagesById(replyIds)
+ const replyMessage = replyIntent ? replyResources?.get(replyIntent.id) : undefined
+ const replyTo = useMemo(() => replyIntent && replyMessage ? { ...replyIntent, text: messagePreviewText(replyMessage) } : replyIntent, [replyIntent, replyMessage])
const [localSubmitVersion, setLocalSubmitVersion] = useAtom(useCreateAtom(0))
const targetEntry = useMemo(() => ({ entry: feed.positionEntry, atom: createAtom<string | null>(anchorMessageId) }), [anchorMessageId, feed.positionEntry])
const [scrollTargetId, setScrollTargetId] = useAtom(targetEntry.atom)
@@ -113,10 +119,15 @@ export function useMessageChannelController({
const openContextSeq = useCallback((seq: number) => {
setContextTarget((current) => (
- current ? { ...current, seq } : { serverId, channelId, label: channelName, seq }
+ current ? { ...current, seq, messageId: undefined } : { serverId, channelId, label: channelName, seq }
))
}, [setContextTarget, serverId, channelId, channelName])
+ const openContextId = useCallback((messageId: string) => {
+ source.capture()()
+ setContextTarget({ serverId, channelId, label: channelName, messageId })
+ }, [source, setContextTarget, serverId, channelId, channelName])
+
const onSheetReply = useCallback((target: ReplyTarget) => {
if (contextTarget && contextTarget.channelId !== channelId) {
communityRuntime.ui.actions.setPendingReply({ channelId: contextTarget.channelId, target })
@@ -154,7 +165,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 ? presentCanonicalMessage(row) : undefined
+ let message: Msg | undefined = row?.channelId === channelId ? presentCanonicalMessage(row, row.replyToId ? registry?.collections.messages.get(row.replyToId) : undefined) : 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)
@@ -274,6 +285,7 @@ export function useMessageChannelController({
contextTarget,
setContextTarget,
openContextSeq,
+ openContextId,
onSheetReply,
jumpToSeq,
messageActions,
@@ -285,5 +297,5 @@ export function useMessageChannelController({
communityWsSendTyping(communityRuntime, { channelId })
},
typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),
- }), [feed, pinnedIds, replyTo, setReplyTo, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, onSheetReply, jumpToSeq, messageActions, acceptMessage, localSubmitVersion, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])
+ }), [feed, pinnedIds, replyTo, setReplyTo, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, openContextId, onSheetReply, jumpToSeq, messageActions, acceptMessage, localSubmitVersion, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])
}
diff --git a/src/web/src/components/community/messages/message-channel-controller-types.ts b/src/web/src/components/community/messages/message-channel-controller-types.ts
index ff1499b1d..70c4091ce 100644
--- a/src/web/src/components/community/messages/message-channel-controller-types.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts
@@ -21,8 +21,7 @@ export type MessageContextTarget = {
serverId: string
channelId: string
label: string
- seq: number
-}
+} & ({ seq: number; messageId?: never } | { messageId: string; seq?: never })
export type MessageActions = {
onToggleReaction: (id: string, emoji: string) => void
@@ -48,6 +47,7 @@ export type MessageChannelControllerValue = {
consumeScrollTarget: (targetId: string) => void
contextTarget: MessageContextTarget | null
setContextTarget: (target: MessageContextTarget | null) => void
+ openContextId: (id: string) => void
openContextSeq: (seq: number) => void
onSheetReply: (target: ReplyTarget) => void
jumpToSeq: (seq: number) => void
diff --git a/src/web/src/components/community/messages/message-context-sheet-header.test.ts b/src/web/src/components/community/messages/message-context-sheet-header.test.ts
deleted file mode 100644
index ec2e47159..000000000
--- a/src/web/src/components/community/messages/message-context-sheet-header.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import rawContractInput0 from "./message-context-sheet.tsx?raw"
-import { describe, expect, it } from "vitest"
-
-describe("MessageContextSheet header", () => {
- it("supplies a structured title that truncates only the channel label", () => {
- const source = rawContractInput0
-
- expect(source).toContain("title={channelLabel ? (")
- expect(source).toContain('<span className="flex w-full min-w-0 items-center gap-1.5">')
- expect(source).toContain('<span className="min-w-0 truncate">{channelLabel}</span>')
- expect(source).toContain(
- '<span className="shrink-0 font-mono text-base font-normal text-muted-foreground">#{targetSeq ?? ""}</span>',
- )
- expect(source).not.toContain("CommunitySheetHeader")
- expect(source).not.toContain("CommunitySheetTitle")
- })
-})
diff --git a/src/web/src/components/community/messages/message-context-sheet.entry.dom.test.tsx b/src/web/src/components/community/messages/message-context-sheet.entry.dom.test.tsx
new file mode 100644
index 000000000..2fb9691e9
--- /dev/null
+++ b/src/web/src/components/community/messages/message-context-sheet.entry.dom.test.tsx
@@ -0,0 +1,143 @@
+import React from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, render, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { conversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
+import { messageReadPageFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
+import { captureCommunityLiveSnapshotToken, publishCommunityMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
+import { ApiError } from "@/lib/errors"
+import { COMMUNITY_CONVERSATION_ANCHOR_MISSING } from "@alook/shared"
+
+const load = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => load(...args), toastApiError: vi.fn() }))
+vi.mock("@/components/community/shell/community-sheet", () => ({ CommunitySheet: ({ children, title }: { children: React.ReactNode; title: React.ReactNode }) => <aside role="dialog">{title}{children}</aside> }))
+vi.mock("./message-row", () => ({ MessageRow: ({ m, onJumpToId }: { m: { id: string; content?: string; replyTo?: { id: string } }; onJumpToId?: (id: string) => void }) => <article data-message-id={m.id}>{m.content}{m.replyTo && <button onClick={() => onJumpToId?.(m.replyTo!.id)}>Show original</button>}</article> }))
+vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))
+vi.mock("@/components/ui/skeleton", () => ({ Skeleton: () => <span>Loading context</span> }))
+vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))
+vi.mock("@/hooks/community/mutations", () => ({
+ usePinMessage: () => ({ mutate: vi.fn() }), useUnpinMessage: () => ({ mutate: vi.fn() }), useCreateThread: () => ({ mutateAsync: vi.fn() }),
+ useToggleMark: () => vi.fn(), useToggleReactionApi: () => vi.fn(), useAddReactionApi: () => vi.fn(),
+}))
+vi.mock("@/stores/community", async original => ({ ...await original<typeof import("@/stores/community")>(), useUiHandlers: () => ({}) }))
+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "viewer" }) }))
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }), useParams: () => ({}) }))
+
+import { MessageContextSheet } from "./message-context-sheet"
+
+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+beforeEach(async () => { owner = await createCommunityQueryOwner(); load.mockReset() })
+
+const message = (id: string) => messageResourceFixture({ id, channelId: "c1", authorId: "peer", content: `Body ${id}` })
+function sheet(targetMessageId: string, open = true) {
+ return <MessageContextSheet open={open} onOpenChange={vi.fn()} channelId="c1" serverId="s1" channelLabel="Current channel" targetSeq={null} targetMessageId={targetMessageId} />
+}
+function mount(id: string) {
+ return render(sheet(id), { wrapper: ({ children }) => <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>{children}</CommunityTestProvider> })
+}
+function held() {
+ let resolve!: (value: unknown) => void
+ const promise = new Promise<unknown>(done => { resolve = done })
+ return { promise, resolve }
+}
+
+describe("native context Query ownership", () => {
+ it("shows a qualified canonical target while fetching its separate window by ID", async () => {
+ const entry = await seedConversationEntry(owner.client, conversationEntryFixture())
+ const target = message("older")
+ await publishCommunityMessages(owner.client, { channelId: "c1", messages: [target], profiles: conversationEntryFixture().profiles, proof: { token: captureCommunityLiveSnapshotToken(owner.client, "c1") } })
+ const window = owner.client.getQueryData(entry.resource.windowKey)
+ const pointer = owner.registry.collections.readStates.get("c1")
+ const pending = held()
+ load.mockImplementation(() => pending.promise)
+ const view = mount("older")
+ await waitFor(() => expect(view.getByText("Body older")).toBeInTheDocument())
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(view.getByText("Current channel")).toBeInTheDocument()
+ expect(view.getByText("#1")).toBeInTheDocument()
+ expect(load.mock.calls[0][0]).toBe("/api/community/channels/c1/messages?anchor=older&limit=11")
+ await act(async () => { pending.resolve(messageReadPageFixture({ messages: [target, message("neighbor")] })); await pending.promise })
+ await waitFor(() => expect(view.getByText("Body neighbor")).toBeInTheDocument())
+ expect(owner.client.getQueryData(entry.resource.windowKey)).toBe(window)
+ expect(owner.registry.collections.readStates.get("c1")).toBe(pointer)
+ })
+
+ it("cancels A/B and close races even when the transport delivers after abort", async () => {
+ const a = held(), b = held(), c = held()
+ load.mockImplementationOnce(() => a.promise).mockImplementationOnce(() => b.promise).mockImplementationOnce(() => c.promise)
+ const view = mount("a")
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(1))
+ const aSignal = load.mock.calls[0][1].signal as AbortSignal
+ view.rerender(sheet("b"))
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(2))
+ expect(aSignal.aborted).toBe(true)
+ await act(async () => { a.resolve(messageReadPageFixture({ messages: [message("a")] })); b.resolve(messageReadPageFixture({ messages: [message("b")] })); await Promise.all([a.promise, b.promise]) })
+ await waitFor(() => expect(view.getByText("Body b")).toBeInTheDocument())
+ expect(owner.registry.collections.messages.has("a")).toBe(false)
+ view.rerender(sheet("c"))
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(3))
+ const cSignal = load.mock.calls[2][1].signal as AbortSignal
+ view.rerender(sheet("c", false))
+ expect(cSignal.aborted).toBe(true)
+ await act(async () => { c.resolve(messageReadPageFixture({ messages: [message("c")] })); await c.promise })
+ expect(view.queryByRole("dialog")).toBeNull()
+ expect(owner.registry.collections.messages.has("c")).toBe(false)
+ })
+
+ it("withholds a cached ID from another channel while the scoped lookup is pending", async () => {
+ await seedConversationEntry(owner.client, conversationEntryFixture())
+ await publishCommunityMessages(owner.client, { channelId: "other", messages: [{ ...message("foreign"), channelId: "other", content: "Foreign private body" }], profiles: conversationEntryFixture().profiles, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
+ const pending = held()
+ load.mockImplementation(() => pending.promise)
+ const view = mount("foreign")
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(view.queryByText("Foreign private body")).toBeNull()
+ await act(async () => { pending.resolve(Promise.reject(new ApiError("anchor missing", 404, [COMMUNITY_CONVERSATION_ANCHOR_MISSING]))); await pending.promise.catch(() => undefined) })
+ await waitFor(() => expect(view.getByText(/may have been deleted/)).toBeInTheDocument())
+ expect(view.queryByText("Foreign private body")).toBeNull()
+ })
+
+ it("keeps replies inside the context window local without a second fetch", async () => {
+ const target = message("target")
+ const reply = { ...message("reply"), seq: 2, replyToId: target.id, replyTo: { id: target.id, authorId: target.authorId, authorName: "Peer" } }
+ load.mockResolvedValueOnce(messageReadPageFixture({ messages: [target, reply] }))
+ const view = mount("reply")
+ await waitFor(() => expect(view.getByText("Body reply")).toBeInTheDocument())
+ await act(async () => { view.getByRole("button", { name: "Show original" }).click() })
+ await waitFor(() => expect(view.container.querySelector('[data-anchor-row="1"]')).toHaveTextContent("Body target"))
+ expect(load).toHaveBeenCalledOnce()
+ })
+
+ it.each(["account", "access"] as const)("rejects late publication after %s retirement", async kind => {
+ const pending = held()
+ load.mockImplementation(() => pending.promise)
+ const view = mount("late")
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ await act(async () => {
+ if (kind === "account") retireCommunityAccount(owner.registry)
+ else retireCommunityChannelReading(owner.registry, "c1", { reason: "read-denied", serverId: "s1" })
+ })
+ await act(async () => { pending.resolve(messageReadPageFixture({ messages: [message("late")] })); await pending.promise })
+ expect(owner.registry.collections.messages.has("late")).toBe(false)
+ expect(view.queryByText("Body late")).toBeNull()
+ if (kind === "access") expect(view.getByRole("alert")).toHaveTextContent("You can no longer read")
+ })
+
+ it("distinguishes uncached loading, confirmed absence and retryable failure", async () => {
+ const pending = held()
+ load.mockImplementationOnce(() => pending.promise)
+ const view = mount("missing")
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(view.queryByText(/may have been deleted/)).toBeNull()
+ await act(async () => { pending.resolve(Promise.reject(new ApiError("anchor missing", 404, [COMMUNITY_CONVERSATION_ANCHOR_MISSING]))); await pending.promise.catch(() => undefined) })
+ await waitFor(() => expect(view.getByText(/may have been deleted/)).toBeInTheDocument())
+ load.mockRejectedValueOnce(new ApiError("offline", 0))
+ view.rerender(sheet("retry"))
+ await waitFor(() => expect(view.getByRole("button", { name: "Retry" })).toBeInTheDocument())
+ load.mockResolvedValueOnce(messageReadPageFixture({ messages: [message("retry")] }))
+ await act(async () => { view.getByRole("button", { name: "Retry" }).click() })
+ await waitFor(() => expect(view.getByText("Body retry")).toBeInTheDocument())
+ })
+})
diff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
index fe26c8471..c6a0e999a 100644
--- a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
@@ -3,12 +3,17 @@ import { messageResourceFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act } from "@/test/react-dom-harness"
-import { renderCommunity as render } from "@/test/community-owner-harness"
+import { render as renderBase } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"
import type { MessageInput } from "@/lib/community/models/message"
let navigationOwner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+function render(node: React.ReactNode) {
+ return renderBase(node, { wrapper: ({ children }) => React.createElement(CommunityTestProvider, { client: navigationOwner.client, registry: navigationOwner.registry, userId: "viewer_1", retainOwner: true }, children) })
+}
const mocks = vi.hoisted(() => ({
push: vi.fn(),
cancel: vi.fn(),
@@ -37,6 +42,8 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({ ...await importOri
useQuery: () => ({
data: mocks.noData ? undefined : {
notFound: false,
+ id: "message_1",
+ proof: captureCommunityLiveSnapshotToken(navigationOwner.client, "parent_1"),
anchorId: "message_1",
messages: [{
id: "message_1",
@@ -118,6 +125,7 @@ import {
MessageContextSheet,
openMessageContextThread,
messageContextQueryFn,
+ messageContextIdQueryFn,
} from "./message-context-sheet"
describe("MessageContextSheet native query publication", () => {
@@ -128,18 +136,17 @@ describe("MessageContextSheet native query publication", () => {
const owner = await createCommunityQueryOwner("context_viewer")
const write = vi.spyOn(owner.registry.collections.profiles.utils, "writeBatch")
const signal = new AbortController().signal
- mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockResolvedValueOnce(messageReadPageFixture({ messages: [
+ mocks.apiFetch.mockResolvedValueOnce(messageReadPageFixture({ messages: [
messageResourceFixture({ id: "after", channelId: "context_channel", seq: 3, content: "after", authorId: "author", authorName: "Author" }),
messageResourceFixture({ id: "anchor", channelId: "context_channel", seq: 2, content: "anchor", authorId: "author", authorName: "Author" }),
], hasMore: false }))
- await expect(messageContextQueryFn("channel", "context_channel", 2, owner.client)({ signal })).resolves.toEqual({
+ await expect(messageContextQueryFn("channel", "context_channel", "anchor", owner.client)({ signal })).resolves.toMatchObject({
notFound: false, anchorId: "anchor", messages: [{ id: "anchor" }, { id: "after" }],
})
expect(mocks.apiFetch.mock.calls.map(([url]) => url)).toEqual([
- "/api/community/channels/context_channel/messages/seq/2",
"/api/community/channels/context_channel/messages?anchor=anchor&limit=11",
])
- expect(mocks.apiFetch.mock.calls.every(([, options]) => options.signal === signal)).toBe(true)
+ expect(mocks.apiFetch.mock.calls.every(([, options]) => options.signal instanceof AbortSignal && !options.signal.aborted)).toBe(true)
expect(write).toHaveBeenCalledTimes(1)
expect(owner.registry.collections.messages.get("anchor")).toMatchObject({ content: "anchor", channelId: "context_channel", authorId: "author" })
expect(owner.registry.collections.profiles.get("author")).toMatchObject({ id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 })
@@ -151,7 +158,7 @@ describe("MessageContextSheet native query publication", () => {
const revision = beginCommunityProfileSeed(owner.registry).revision
const { ApiError } = await import("@/lib/errors")
mocks.apiFetch.mockRejectedValueOnce(new ApiError("missing", 404))
- await expect(messageContextQueryFn("dm", "context_dm", 8, owner.client)()).resolves.toEqual({ notFound: true })
+ await expect(messageContextIdQueryFn("dm", "context_dm", 8, owner.client)()).resolves.toMatchObject({ notFound: true })
expect(mocks.apiFetch).toHaveBeenCalledTimes(1)
expect(beginCommunityProfileSeed(owner.registry).revision).toBe(revision)
expect([...owner.registry.collections.messages.values()]).toEqual([])
@@ -161,8 +168,8 @@ describe("MessageContextSheet native query publication", () => {
const owner = await createCommunityQueryOwner("context_viewer")
const { retireCommunityChannelReading } = await import("@/lib/community-db/sync")
let resolvePage!: (page: unknown) => void
- mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockImplementationOnce(() => new Promise((resolve) => { resolvePage = resolve }))
- const pending = messageContextQueryFn("channel", "context_channel", 2, owner.client)().catch((error) => error)
+ mocks.apiFetch.mockImplementationOnce(() => new Promise((resolve) => { resolvePage = resolve }))
+ const pending = messageContextQueryFn("channel", "context_channel", "anchor", owner.client)().catch((error) => error)
while (!resolvePage) await Promise.resolve()
retireCommunityChannelReading(owner.registry, "context_channel", { reason: "read-denied", serverId: "context_server" })
resolvePage({ messages: [messageResourceFixture({ id: "anchor", channelId: "context_channel", seq: 2, content: "late", authorId: "author", authorName: "Late Author" })], hasMore: false })
@@ -198,10 +205,10 @@ describe("MessageContextSheet thread navigation", () => {
expect(mocks.toggleReaction).toBeUndefined()
})
- it("shows a missing anchor when the canonical map exists without its ID", () => {
+ it("does not label an uncached target as deleted", () => {
mocks.canonicalMessages.mockReturnValue(new Map())
const view = render(React.createElement(MessageContextSheet, { open: true, onOpenChange: mocks.close, channelId: "parent_1", targetSeq: 1 }))
- expect(view.getByText("Message not found — it may have been deleted.")).toBeTruthy()
+ expect(view.queryByText("Message not found — it may have been deleted.")).toBeNull()
expect(mocks.reply).toBeUndefined()
expect(mocks.pin).toBeUndefined()
})
@@ -236,7 +243,7 @@ describe("MessageContextSheet thread navigation", () => {
it("opens a rendered channel thread by its flat child id and closes the sheet", () => {
render(React.createElement(MessageContextSheet, {
- open: false,
+ open: true,
onOpenChange: mocks.close,
channelId: "parent_1",
serverId: "target_server",
diff --git a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
index e1b90f26a..8829f2c0c 100644
--- a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
@@ -7,6 +7,7 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { publishCommunityMessages, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { writeCommunityCollectionRows } from "@/lib/community-db/write"
+import { conversationListScopeKey } from "@/lib/community/conversation-qualification"
import { communityKeys } from "@/lib/query-keys"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -90,10 +91,19 @@ function sheetCache(me: boolean) {
}
}
+function seedContext(initial: ReturnType<typeof sheetCache>) {
+ const proof = captureCommunityLiveSnapshotToken(owner.client, "channel_1")
+ const qualification = conversationListScopeKey({ proof, tag: null })
+ const key = [...communityKeys.messageContext("channel", "channel_1", "message_1"), qualification]
+ owner.client.setQueryData([...communityKeys.messageContext("channel", "channel_1", 1), qualification], { id: "message_1", proof, notFound: false })
+ owner.client.setQueryData(key, { ...initial, proof, messages: initial.messages.map(({ id }) => ({ id })) })
+ return key
+}
+
async function renderSheet(me: boolean) {
const initial = sheetCache(me)
await publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
- owner.client.setQueryData(communityKeys.messageContext("channel", "channel_1", 1), { ...initial, messages: initial.messages.map(({ id }) => ({ id })) })
+ seedContext(initial)
const rendered = render(React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, React.createElement(MessageContextSheet, {
open: true, onOpenChange: vi.fn(), channelId: "channel_1", targetSeq: 1,
})))
@@ -130,23 +140,23 @@ describe("MessageContextSheet reaction coordinator", () => {
it("rereads fresh context IDs with a missing author before exposing row actions", async () => {
const initial = sheetCache(false)
await publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
- owner.client.setQueryData(communityKeys.messageContext("channel", "channel_1", 1), { ...initial, messages: [{ id: "message_1" }] })
+ const contextKey = seedContext(initial)
await writeCommunityCollectionRows(owner.registry, "profiles", [], row => row.id)
let release!: (value: ReturnType<typeof messageReadPageFixture>) => void
const held = new Promise<ReturnType<typeof messageReadPageFixture>>(resolve => { release = resolve })
- mocks.apiFetch.mockResolvedValueOnce({ id: "message_1" }).mockImplementationOnce(() => held)
+ mocks.apiFetch.mockImplementationOnce(() => held)
render(React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, React.createElement(MessageContextSheet, {
open: true, onOpenChange: vi.fn(), channelId: "channel_1", targetSeq: 1,
})))
await act(async () => { await vi.advanceTimersByTimeAsync(0) })
- expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1)
expect(mocks.onAdd).toBeUndefined()
expect(mocks.onToggle).toBeUndefined()
await act(async () => { release(messageReadPageFixture({ messages: initial.messages, hasMore: false })); await held; await vi.advanceTimersByTimeAsync(0) })
expect(mocks.onAdd).toEqual(expect.any(Function))
expect(owner.registry.collections.profiles.get("author_1")).toMatchObject({ id: "author_1", name: "Author", discriminator: expect.any(String), avatarVersion: 0 })
- expect(owner.client.getQueryData(communityKeys.messageContext("channel", "channel_1", 1))).toMatchObject({ messages: [{ id: "message_1" }] })
- expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ expect(owner.client.getQueryData(contextKey)).toMatchObject({ messages: [{ id: "message_1" }] })
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1)
})
it("repeats picker add without a rerender and preserves the first timer deadline", async () => {
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index f602a1920..289c18a28 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -1,7 +1,12 @@
"use client"
-import { useAtom, useCreateAtom } from "@tanstack/react-store"
+import { messagePreviewText } from "@alook/shared"
+import { useAtom, useCreateAtom, useSelector } from "@tanstack/react-store"
+
+import { useCommunityRuntime } from "@/stores/community/runtime"
+import { getQualifiedConversationScope } from "@/lib/community/conversation-entry"
+import { isChannelMetadataTokenCurrent, conversationListScopeKey } from "@/lib/community/conversation-qualification"
import { useCallback, useEffect, useMemo, useRef } from "react"
import { useCommunityRouter } from "@/contexts/community/module-route"
import { toast } from "sonner"
@@ -30,6 +35,7 @@ import {
import type { FileAttachment, ImagePreview, MessagesReadPage, Msg, RenderMsg, ReplyTarget } from "@/lib/community/models/message"
import { apiFetchCommunity, communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { isAbortError } from "@/lib/errors"
+import { withConversationReadDeadline, conversationReadRetryPolicy, isConversationAnchorMissingError } from "@/lib/community/conversation-read"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { channelHref } from "@/lib/community/community-route"
@@ -48,7 +54,6 @@ import {
publishCommunityEmbeddedMessages,
} from "@/lib/community-db/sync"
-export type { ReplyTarget } from "@/lib/community/models/message"
// Preview window sizing — small on purpose. The sheet is a read-only
// excerpt with just enough surrounding context to make the target message
@@ -91,16 +96,34 @@ function anchorFetchUrl(_type: ScopeType, id: string, anchor: string, limit: num
type SheetCache = {
notFound?: boolean
anchorId?: Msg["id"]
+ proof?: ReturnType<typeof captureCommunityLiveSnapshotToken>
messages?: Pick<Msg, "id">[]
}
+export function messageContextIdQueryFn(type: ScopeType, channelId: string, seq: number, queryClient: ReturnType<typeof useQueryClient>) {
+ return ({ signal }: { signal?: AbortSignal } = {}) => withConversationReadDeadline(signal, async signal => {
+ const proof = captureCommunityLiveSnapshotToken(queryClient, channelId)
+ await proof.registry?.ready
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, proof, signal)
+ try {
+ const result = await apiFetch<Pick<Msg, "id">>(seqLookupUrl(type, channelId, seq), communityRequestOptions(queryClient, proof, signal))
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, proof, signal)
+ return { id: result.id, proof, notFound: false }
+ } catch (error) {
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, proof, signal)
+ if (error instanceof ApiError && error.status === 404) return { id: undefined, proof, notFound: true }
+ throw error
+ }
+ })
+}
+
export function messageContextQueryFn(
type: ScopeType,
channelId: string,
- targetSeq: number,
+ targetId: string,
queryClient: ReturnType<typeof useQueryClient>,
) {
- return async ({ signal }: { signal?: AbortSignal } = {}): Promise<SheetCache> => {
+ return ({ signal }: { signal?: AbortSignal } = {}): Promise<SheetCache> => withConversationReadDeadline(signal, async signal => {
const publicationToken = captureCommunityLiveSnapshotToken(queryClient, channelId)
const registry = publicationToken.registry
const assert = () => assertCommunityLiveSnapshotTokenCurrent(queryClient, publicationToken, signal)
@@ -108,31 +131,25 @@ export function messageContextQueryFn(
assert()
await registry?.collections.messages.preload()
assert()
- let lookup: Pick<Msg, "id">
- try {
- lookup = await apiFetch<Pick<Msg, "id">>(
- seqLookupUrl(type, channelId, targetSeq),
- communityRequestOptions(queryClient, publicationToken, signal, assert),
- )
+ let page: MessagesReadPage
+ try { page = await apiFetchCommunity<MessagesReadPage>(
+ anchorFetchUrl(type, channelId, targetId, CONTEXT_LIMIT),
+ { signal, assertActive: assert }, publicationToken,
+ )
} catch (error) {
assert()
- if (error instanceof ApiError && error.status === 404) return { notFound: true }
+ if (isConversationAnchorMissingError(error)) return { notFound: true, proof: publicationToken }
throw error
}
- assert()
- const page = await apiFetchCommunity<MessagesReadPage>(
- anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),
- { signal, assertActive: assert }, publicationToken,
- )
const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
await publishCommunityEmbeddedMessages(queryClient, {
- entries: messages.map((message) => ({ channelId, message })),
+ entries: [...messages, ...(page.relatedMessages ?? [])].map((message) => ({ channelId, message })),
profiles: page.profiles,
proof: { token: publicationToken, signal },
})
assert()
- return { notFound: false, anchorId: lookup.id, messages: messages.map(({ id }) => ({ id })) }
- }
+ return { notFound: false, proof: publicationToken, anchorId: targetId, messages: messages.map(({ id }) => ({ id })) }
+ })
}
@@ -158,13 +175,27 @@ export function messageContextQueryFn(
* Retry is disabled — the sheet only shows server-persisted messages, never
* failed optimistic rows.
*/
-export function MessageContextSheet({
+export function MessageContextSheet(props: React.ComponentProps<typeof MessageContextSheetContent>) {
+ const runtime = useCommunityRuntime()
+ const client = useQueryClient()
+ const ws = useSelector(runtime.ws, state => state)
+ const lifecycle = useSelector(runtime.lifecycle, state => state)
+ const denied = runtime.ws.actions.isChannelAccessRevoked(props.channelId, props.serverId)
+ if (!props.open || !lifecycle.active || ws.profileViewerId === null || !getCommunityDbRegistry(client)) return null
+ const token = captureCommunityLiveSnapshotToken(client, props.channelId)
+ const scopeKey = conversationListScopeKey({ proof: token, tag: null })
+ if (denied) return <CommunitySheet open onOpenChange={props.onOpenChange} title="Message"><p role="alert" className="p-4 text-sm text-muted-foreground">You can no longer read this conversation.</p></CommunitySheet>
+ return <MessageContextSheetContent key={JSON.stringify([scopeKey, props.targetMessageId ?? props.targetSeq])} {...props} />
+}
+
+function MessageContextSheetContent({
open,
onOpenChange,
channelId,
serverId,
channelLabel,
targetSeq,
+ targetMessageId,
pinnedIds,
onOpenProfile,
resolveUserName,
@@ -182,6 +213,7 @@ export function MessageContextSheet({
// header names which channel's context this is (Gus #417/#423, Alli #420).
channelLabel?: string
targetSeq: number | null
+ targetMessageId?: string
pinnedIds?: Set<string>
onOpenProfile?: OpenProfile
resolveUserName?: (userId: string) => string
@@ -204,22 +236,36 @@ export function MessageContextSheet({
const toggleReactionApi = useToggleReactionApi()
const addReactionApi = useAddReactionApi()
- const queryKey = useMemo(
- () => communityKeys.messageContext(type, channelId, targetSeq),
- [type, channelId, targetSeq],
- )
-
- // Two-step fetch: seq → id, then anchor-fetch around the id.
+ const [localAnchorId, setLocalAnchorId] = useAtom(useCreateAtom<string | null>(null))
+ const [nestedId, setNestedId] = useAtom(useCreateAtom<string | null>(null))
+ const requestedId = nestedId ?? targetMessageId
+ const qualification = conversationListScopeKey({ proof: captureCommunityLiveSnapshotToken(queryClient, channelId), tag: null })
+ const lookup = useQuery({
+ queryKey: [...communityKeys.messageContext(type, channelId, targetSeq), qualification],
+ enabled: open && !!channelId && !requestedId && !!targetSeq,
+ queryFn: messageContextIdQueryFn(type, channelId, targetSeq!, queryClient),
+ staleTime: 30_000,
+ networkMode: "always",
+ retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.messageContexts(type, channelId) }).retry),
+ })
+ const resolved = lookup.data && isChannelMetadataTokenCurrent(lookup.data.proof) ? lookup.data : undefined
+ const targetId = requestedId ?? resolved?.id
const query = useQuery({
- queryKey,
- enabled: open && !!channelId && !!targetSeq,
- queryFn: messageContextQueryFn(type, channelId, targetSeq!, queryClient),
+ queryKey: [...communityKeys.messageContext(type, channelId, targetId ?? null), qualification],
+ enabled: open && !!channelId && !!targetId,
+ queryFn: messageContextQueryFn(type, channelId, targetId!, queryClient),
staleTime: 30_000,
+ networkMode: "always",
+ retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.messageContexts(type, channelId) }).retry),
})
- const selectedIds = useMemo(() => query.data?.messages?.map((message) => message.id) ?? [], [query.data?.messages])
- const canonicalMessages = useCanonicalMessagesById(selectedIds)
+ const cached = query.data?.proof && isChannelMetadataTokenCurrent(query.data.proof) ? query.data : undefined
const registry = getCommunityDbRegistry(queryClient)
- const selectedResources = selectedIds.map(id => registry?.collections.messages.get(id))
+ const scope = getQualifiedConversationScope(queryClient, { channelId, serverId: type === "dm" ? null : serverId ?? null })
+ const qualified = !!scope && !!targetId && registry?.collections.messages.get(targetId)?.channelId === channelId
+ const references = useMemo(() => cached?.messages ?? (!cached && qualified && targetId ? [{ id: targetId }] : []), [cached, qualified, targetId])
+ const selectedIds = useMemo(() => references.map(message => message.id), [references])
+ const canonicalMessages = useCanonicalMessagesById(selectedIds)
+ const selectedResources = selectedIds.map(id => { const row = registry?.collections.messages.get(id); return row?.channelId === channelId ? row : undefined })
const graph = getCanonicalCommunityMessageResources(queryClient, selectedResources)
const profiles = useCanonicalProfilesProjection(graph ? communityMessageProfileIds(graph.messages) : [])
const nativeGraph = graph && CommunityMessageResourcesSchema.safeParse({ messages: graph.messages, profiles: [...profiles.resourceProfiles.values()].flatMap(profile => {
@@ -229,13 +275,13 @@ export function MessageContextSheet({
const graphReady = !!graph && profiles.isReady && !profiles.isError && nativeGraph?.success === true
const refetch = query.refetch
useEffect(() => {
- if (open && query.data && !query.data.notFound && !graph && query.isSuccess && !query.isFetching) void refetch({ cancelRefetch: false })
- }, [open, query.data, graph, query.isSuccess, query.isFetching, refetch])
+ if (open && cached && !cached.notFound && !graph && query.isSuccess && !query.isFetching) void refetch({ cancelRefetch: false })
+ }, [open, cached, graph, query.isSuccess, query.isFetching, refetch])
const renderRows = useMemo<RenderMsg[]>(() => {
- if (!query.data || query.data.notFound || !query.data.messages) return []
- const src = materializeCanonicalMessages(query.data.messages, canonicalMessages)
+ if (cached?.notFound) return []
+ const src = materializeCanonicalMessages(references, canonicalMessages)
// Same grouping heuristic the main list uses (adjacent same-author within
// ~5 min → collapse header). Inlined here rather than sharing the util
// because the excerpt is small enough that the extra dep isn't worth the
@@ -252,20 +298,25 @@ export function MessageContextSheet({
new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime() < 5 * 60_000
return { ...m, grouped }
})
- }, [canonicalMessages, query.data])
+ }, [canonicalMessages, references, cached])
+
+ const anchorId = cached?.notFound ? null : localAnchorId ?? cached?.anchorId ?? targetId ?? null
- const anchorId = query.data && !query.data.notFound ? (query.data.anchorId ?? null) : null
+ const canonicalPending = !cached?.notFound && (canonicalMessages === undefined || !graphReady)
+ const anchorMissing = cached?.notFound === true || resolved?.notFound === true
- const canonicalPending = !!query.data && !query.data.notFound && (canonicalMessages === undefined || !graphReady)
- const anchorMissing = !canonicalPending && canonicalMessages !== undefined && !!anchorId && !canonicalMessages.has(anchorId)
+ const jumpToReply = useCallback((id: string) => {
+ if (references.some(message => message.id === id)) setLocalAnchorId(id)
+ else { setLocalAnchorId(null); setNestedId(id) }
+ }, [references, setLocalAnchorId, setNestedId])
// ── Sheet-local actions ──────────────────────────────────────────────────
const findMessage = useCallback(
(id: string): Msg | undefined => {
- const transport = query.data?.messages?.find((message) => message.id === id)
+ const transport = references.find((message) => message.id === id)
return transport ? materializeCanonicalMessage(transport, canonicalMessages) : undefined
},
- [canonicalMessages, query.data],
+ [canonicalMessages, references],
)
const runReactionIntent = useCallback((
@@ -311,7 +362,7 @@ export function MessageContextSheet({
id: m.id,
...(m.authorId ? { authorId: m.authorId } : {}),
authorName: m.authorName ?? "",
- text: m.content ?? "",
+ text: messagePreviewText(m),
})
}, [findMessage, onReply])
@@ -348,8 +399,7 @@ export function MessageContextSheet({
if (type === "dm") return
if (!serverId) return
const m = findMessage(id)
- const content = m ? (m.content ?? "") : undefined
- const name = deriveThreadName(content, "channel")
+ const name = deriveThreadName(m, "channel")
try {
await createThreadMut.mutateAsync({ serverId, channelId, messageId: id, name })
} catch (e) {
@@ -420,7 +470,9 @@ export function MessageContextSheet({
cancelAnimationFrame(r1)
if (r2) cancelAnimationFrame(r2)
}
- }, [open, anchorId, targetSeq])
+ }, [open, anchorId, targetSeq, renderRows.length])
+
+ const displayedSeq = canonicalMessages?.get(anchorId ?? "")?.seq ?? (requestedId ? undefined : targetSeq)
return (
<CommunitySheet
@@ -430,33 +482,34 @@ export function MessageContextSheet({
<span className="flex w-full min-w-0 items-center gap-1.5">
<ChannelIcon className="shrink-0 text-muted-foreground" />
<span className="min-w-0 truncate">{channelLabel}</span>
- <span className="shrink-0 font-mono text-base font-normal text-muted-foreground">#{targetSeq ?? ""}</span>
+ <span className="shrink-0 font-mono text-base font-normal text-muted-foreground">#{displayedSeq ?? ""}</span>
</span>
) : (
<span className="font-mono text-2xl">
- <span className="text-muted-foreground">#</span>{targetSeq ?? ""}
+ <span className="text-muted-foreground">#</span>{displayedSeq ?? ""}
</span>
)}
bodyRef={bodyRef}
bodyClassName="px-4 py-3"
>
- {(query.isLoading || canonicalPending) && <ContextSkeleton />}
+ {!anchorMissing && !renderRows.length && !(query.isError || lookup.isError) && <ContextSkeleton />}
- {query.isError && (
+ {(query.isError || lookup.isError) && (
<p className="py-8 text-center text-sm text-muted-foreground">
- Couldn&rsquo;t load the message. Check your connection and retry.
+ Couldn&rsquo;t load the message. <button type="button" className="underline" onClick={() => { void (lookup.isError ? lookup.refetch() : query.refetch()) }}>Retry</button>
</p>
)}
- {(query.data?.notFound || anchorMissing) && (
+ {anchorMissing && (
<p className="py-8 text-center text-sm text-muted-foreground">
Message not found — it may have been deleted.
</p>
)}
- {!query.isLoading && !query.isError && !canonicalPending && !anchorMissing && query.data && !query.data.notFound && (
+ {!anchorMissing && !canonicalPending && renderRows.length > 0 && (
<ContextRows
rows={renderRows}
+ onJumpToId={jumpToReply}
viewerUserId={currentUser.id}
anchorId={anchorId}
pinnedIds={pinnedIds}
@@ -480,6 +533,7 @@ export function MessageContextSheet({
function ContextRows({
rows,
+ onJumpToId,
viewerUserId,
anchorId,
pinnedIds,
@@ -496,6 +550,7 @@ function ContextRows({
onPreviewImage,
onPreviewAttachment,
}: {
+ onJumpToId: (id: string) => void
rows: RenderMsg[]
viewerUserId: string
anchorId: string | null
@@ -543,6 +598,7 @@ function ContextRows({
<div data-anchor-row={isTarget ? "1" : undefined}>
<MessageRow
m={m}
+ onJumpToId={onJumpToId}
hoverCapable={hoverCapable}
viewerUserId={viewerUserId}
pinned={pinnedIds?.has(m.id)}
diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
index a8e14aabb..eb373f262 100644
--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
@@ -695,7 +695,7 @@ describe("useMessageListController", () => {
let renderer: ReturnType<typeof rtlRender>
act(() => {
renderer = rtlRender(
- React.createElement(Probe, { value: props() })
+ React.createElement(Probe, { value: props({ messages: [baseMessage, { ...baseMessage, id: "m2" }] }) })
)
})
act(() => mocks.finishPosition("success"))
@@ -745,7 +745,7 @@ describe("useMessageListController", () => {
visibleMessageIds = []
act(() => {
renderer = rtlRender(
- React.createElement(Probe, { value: props() })
+ React.createElement(Probe, { value: props({ messages: [baseMessage, { ...baseMessage, id: "m2" }] }) })
)
})
act(() => latest.jumpTo("m1"))
diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.ts
index 2b1dd11fc..3257f3d11 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -11,6 +11,7 @@ import type { ResolvedMessageListProps } from "./message-list-types"
export function useMessageListController({
messages,
+ onOpenContextId,
loading,
initialLoadError,
newDividerBefore,
@@ -174,10 +175,11 @@ export function useMessageListController({
const jumpClearTimerRef = useRef<number | null>(null)
const jumpVisibilityFrameRef = useRef<number | null>(null)
const jumpTo = useCallback((id: string, behavior: ScrollBehavior = "smooth") => {
+ if (!messages.some(message => message.id === id)) { onOpenContextId?.(id); return }
setJumped(id)
setJumpRevision((value) => value + 1)
jumpToIndex(id, behavior)
- }, [jumpToIndex, setJumped, setJumpRevision])
+ }, [messages, onOpenContextId, jumpToIndex, setJumped, setJumpRevision])
useEffect(() => {
if (!jumped) return
const id = jumped
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index d053a7813..80d8875e4 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -20,6 +20,7 @@ export type MessageListProps = {
onOpenProfile?: OpenProfile
onToggleReaction?: (id: string, emoji: string) => void
onReact?: (id: string, emoji: string) => void
+ onOpenContextId?: (id: string) => void
onReply?: (id: string) => void
resolveAuthorMentionText?: (authorId: string) => string | null
onInsertMentionText?: (text: string) => void
diff --git a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
index 0154c7f64..1996e0537 100644
--- a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
@@ -6,8 +6,8 @@ import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFr
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
vi.mock("./message-row", () => ({
- MessageRow: ({ m, highlighted }: { m: { id: string }; highlighted: boolean }) =>
- React.createElement("div", { "data-row-id": m.id, "data-highlighted": highlighted }),
+ MessageRow: ({ m, highlighted, onJumpToId }: { m: { id: string; replyTo?: { id: string } }; highlighted: boolean; onJumpToId?: (id: string) => void }) =>
+ React.createElement("div", { "data-row-id": m.id, "data-highlighted": highlighted }, m.replyTo && React.createElement("button", { onClick: () => onJumpToId?.(m.replyTo!.id) }, "Show reply")),
}))
vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))
vi.mock("./typing-indicator", () => ({ TypingIndicator: () => null }))
@@ -56,4 +56,21 @@ describe("MessageList pending jump target with the installed native adapter", ()
expect(renderer.queryByText(/Beginning of the channel/)).toBeNull()
expect(renderer.getByRole("button", { name: "Retry" })).toBeInTheDocument()
})
+ it("opens context only for replies outside the selected window and keeps local highlight", () => {
+ const context = vi.fn()
+ const reply = { ...unrelated, replyTo: { id: target.id, authorName: "Alice", text: "Target" } }
+ const list = (messages: typeof reply[] | typeof target[]) => React.createElement(MessageList, {
+ channel: "general", messages, initialScrollReady: true, onOpenThread: vi.fn(), onOpenContextId: context,
+ })
+ const renderer = render(list([reply]))
+ resize()
+ act(() => renderer.getByRole("button", { name: "Show reply" }).click())
+ expect(context).toHaveBeenCalledExactlyOnceWith(target.id)
+ expect(renderer.container.querySelector('[data-row-id="m_target"]')).toBeNull()
+ renderer.rerender(list([target, reply]))
+ resize()
+ act(() => renderer.getByRole("button", { name: "Show reply" }).click())
+ expect(context).toHaveBeenCalledOnce()
+ expect(highlighted(renderer.container)).toBe(true)
+ })
})
diff --git a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
index 7d152b297..1a7c06ccd 100644
--- a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
@@ -230,7 +230,7 @@ describe("MessageShareDialog session lifecycle", () => {
createdAt,
authorAvatar: "https://avatars.githubusercontent.com/u/1?v=4",
content: "@Bob\n**visible** body",
- replyTo: { id: "original", authorName: "Bob", text: "Original **body**" },
+ replyTo: { id: "original", authorName: "Bob", text: "Original body" },
attachments: [
{ kind: "image", name: "photo.png", url: "/photo.png", width: 800, height: 400 },
{ kind: "file", name: "notes.txt", url: "/notes.txt" },
@@ -347,7 +347,7 @@ describe("MessageShareDialog message projection", () => {
replyTo: {
id: "original",
authorName: "Bob",
- text: "A **formatted** reply",
+ text: "A formatted reply",
},
}))
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index d544a21bb..8519021c6 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -10,7 +10,7 @@ import { toBlob } from "html-to-image"
import { toast } from "sonner"
import { Check, Copy, Download, Highlighter, Loader2 } from "lucide-react"
import { writeImage } from "@tauri-apps/plugin-clipboard-manager"
-import { isDesktop, isMobile, isTauri, stripInlineMarkup } from "@alook/shared"
+import { isDesktop, isMobile, isTauri } from "@alook/shared"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Avatar } from "../avatar"
@@ -331,7 +331,7 @@ export function MessageShareDialog({ m, open, onClose }: {
) : (
<>
<span className="shrink-0 font-medium text-foreground/80">@{replyAuthor?.name ?? msg.replyTo.authorName}</span>
- <span className="min-w-0 truncate">{stripInlineMarkup(msg.replyTo.text)}</span>
+ <span className="min-w-0 truncate">{msg.replyTo.text}</span>
</>
)}
</div>
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index ca13ff34d..26d171437 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -31,7 +31,6 @@ import { tid } from "@/lib/community/testids"
import { cn } from "@/lib/utils"
import { usePageSwipeStart } from "@/components/ui/swipe-container"
import { avatarInitial } from "@/lib/community/avatar"
-import { stripInlineMarkup } from "@alook/shared"
import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { attachmentImageFrameStyle } from "./attachment-layout"
@@ -670,14 +669,14 @@ function MessageImpl({
{m.replyTo && (
<div className="grid grid-cols-[40px_minmax(0,1fr)] gap-2">
- <button onClick={onJumpReply} className="col-start-2 flex min-w-0 items-center gap-2 text-[13px] text-muted-foreground hover:text-foreground">
+ <button aria-label="Show original message" onClick={onJumpReply} className="col-start-2 flex min-w-0 items-center gap-2 text-[13px] text-muted-foreground hover:text-foreground">
<div className="h-2 w-4 shrink-0 rounded-tl-md border-l-2 border-t-2 border-border" />
{m.replyTo.deleted ? (
<span className="italic text-muted-foreground">Original message was deleted</span>
) : (
<>
<span className="shrink-0 font-medium text-foreground/80">@{replyAuthorName}</span>
- <span className="min-w-0 truncate">{stripInlineMarkup(m.replyTo.text)}</span>
+ <span className="min-w-0 truncate">{m.replyTo.text}</span>
</>
)}
</button>
diff --git a/src/web/src/components/community/messages/redacted-text.tsx b/src/web/src/components/community/messages/redacted-text.tsx
index d7b850dc0..1eea47e7b 100644
--- a/src/web/src/components/community/messages/redacted-text.tsx
+++ b/src/web/src/components/community/messages/redacted-text.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from "react"
-export const REDACTED = /\[REDACTED(?:_[A-Z0-9]+)*\]/g
+import { REDACTED } from "@alook/shared/redaction"
+export { REDACTED } from "@alook/shared/redaction"
export function RedactedBadge({ children }: { children?: ReactNode }) {
return <span data-redacted role="img" aria-label="redacted" className="inline-block whitespace-nowrap rounded-sm bg-muted px-1 align-baseline font-sans text-xs font-medium leading-normal text-muted-foreground after:content-['redacted']"><span aria-hidden className="sr-only">{children}</span></span>
diff --git a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
index 3caa39beb..24ca17cb2 100644
--- a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
@@ -2,14 +2,16 @@ import resolvedRawInput0 from "./use-composer-controller.ts?raw"
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
import { forwardRef, createElement, createRef } from "react"
+import { useQueryClient } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act } from "@/test/react-dom-harness"
+import { act, waitFor } from "@/test/react-dom-harness"
import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import { renderCommunity as render } from "@/test/community-owner-harness"
const mocks = vi.hoisted(() => ({
useEditor: vi.fn(),
useFileAttachments: vi.fn(),
+ prepareCommunityImage: vi.fn(),
useSuggestions: vi.fn(),
clearDraft: vi.fn(),
readDraft: vi.fn(),
@@ -58,6 +60,10 @@ vi.mock("@/hooks/use-file-attachments", () => ({
useFileAttachments: (...args: unknown[]) =>
mocks.useFileAttachments(...args),
}))
+vi.mock("@/lib/image-thumbnail", () => ({
+ prepareCommunityImage: (...args: unknown[]) => mocks.prepareCommunityImage(...args),
+ generateThumbnail: vi.fn(),
+}))
vi.mock("@/hooks/use-hover-capable", () => ({
useHoverCapable: () => mocks.hoverCapable,
}))
@@ -107,6 +113,7 @@ import type { ComposerHandle, ComposerProps } from "./composer-types"
import type { PendingFile } from "@/hooks/use-file-attachments"
let controllerView: ReturnType<typeof useComposerController>
+let controllerClient: ReturnType<typeof useQueryClient>
type EditorOptions = {
editorProps: {
@@ -158,6 +165,7 @@ type TestEditor = {
const Harness = forwardRef<ComposerHandle, ComposerProps>(
function Harness(props, ref) {
const view = useComposerController(props, ref)
+ controllerClient = useQueryClient()
controllerView = view
return createElement("div", { "data-controller-probe": "" })
},
@@ -329,6 +337,41 @@ describe("useComposerController", () => {
}))
})
+ it.each(["before-send", "during-send"])("keeps selected files and text unsent when preparation fails %s", async (timing) => {
+ const { useFileAttachments: realHook } = await vi.importActual<typeof import("@/hooks/use-file-attachments")>("@/hooks/use-file-attachments")
+ let files!: ReturnType<typeof realHook>
+ mocks.useFileAttachments.mockImplementation((options: Parameters<typeof realHook>[0]) => {
+ files = realHook(options)
+ return files
+ })
+ let fail!: (error: Error) => void
+ mocks.prepareCommunityImage.mockReturnValue(new Promise((_, reject) => { fail = reject }))
+ const accept = vi.fn(() => true)
+ render(createElement(Harness, acceptedProps(accept)))
+ act(() => editorOptions.onUpdate({ editor }))
+ const file = new File(["image"], "broken.png", { type: "image/png" })
+ let preparation!: Promise<void>
+ act(() => { preparation = files.addPendingFiles([file]) })
+ await waitFor(() => expect(mocks.prepareCommunityImage).toHaveBeenCalledOnce())
+ if (timing === "during-send") await enter()
+ await act(async () => { fail(new Error("decode failed")); await preparation })
+ if (timing === "before-send") await enter()
+ await waitFor(() => expect(controllerClient.isMutating({ mutationKey: ["community", "composer-accept"] })).toBe(0))
+ expect(controllerView.sendDisabled).toBe(true)
+ expect(accept).not.toHaveBeenCalled()
+ expect(clearContent).not.toHaveBeenCalled()
+ expect(mocks.clearDraft).not.toHaveBeenCalled()
+ expect(mocks.clearAttachmentSession).not.toHaveBeenCalled()
+ expect(mocks.transferAttachmentSession).not.toHaveBeenCalled()
+ expect(files.pendingFiles).toEqual([expect.objectContaining({ file, preparationFailed: true })])
+
+ act(() => files.removePendingFile(0))
+ await enter()
+ await waitFor(() => expect(accept).toHaveBeenCalledExactlyOnceWith("hello @everyone", undefined, "everyone"))
+ expect(clearContent).toHaveBeenCalledOnce()
+ expect(mocks.clearDraft).toHaveBeenCalledOnce()
+ })
+
it("forwards the optional channel source into suggestions and its presentation into the view", async () => {
const channelRefCandidateSource = { loading: true, failed: false }
const props = {
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index 152957aae..5426ad632 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -380,7 +380,7 @@ export function useComposerController(
hideEmoji,
showSend: !isForumThreadBody && !hoverCapable,
sendDisabled:
- !active || sendInFlight || (!editorHasContent && pendingFiles.length === 0),
+ !active || sendInFlight || pendingFiles.some((file) => file.preparationFailed) || (!editorHasContent && pendingFiles.length === 0),
onSend: send,
onEmojiPick: (emoji) => {
if (!protocol.get().active) return
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index bfb65c17d..af0f3dca3 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -1,6 +1,6 @@
import { Bookmark, Check, Inbox, LoaderCircle, MoreHorizontal, Trash2, X } from "lucide-react"
-import { formatHandle, stripInlineMarkup } from "@alook/shared"
+import { formatHandle, messagePreviewText } from "@alook/shared"
import { EntityIcon } from "../entity-icon"
import { ServerIcon } from "../server-icon"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
@@ -354,7 +354,7 @@ function MentionsTab({ mentions, loading, error, onRetry, onOpenMention, onDelet
<div className="truncate text-[11px] leading-4 text-muted-foreground/75">
{mn.server} · <ChannelIcon className="inline h-[1em] w-auto align-[-0.1em]" />{mn.channel}
</div>
- <div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(mn.m.content ?? "")}</div>
+ <div className="truncate text-sm text-muted-foreground">{messagePreviewText(mn.m)}</div>
</div>
</button>
{onDeleteMention && (
@@ -402,7 +402,7 @@ function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId,
{mk.m.createdAt && <> · {formatRelativeTime(mk.m.createdAt)}</>}
</span>
</div>
- <div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(mk.m.content ?? "")}</div>
+ <div className="truncate text-sm text-muted-foreground">{messagePreviewText(mk.m)}</div>
</div>
</button>
{onUnmark && (
diff --git a/src/web/src/components/community/shell/community-panel.tsx b/src/web/src/components/community/shell/community-panel.tsx
index b88ffd8a0..87ee582b5 100644
--- a/src/web/src/components/community/shell/community-panel.tsx
+++ b/src/web/src/components/community/shell/community-panel.tsx
@@ -2,7 +2,7 @@
import { useLayoutEffect, useState } from "react"
import { MessagesSquare, Pin, Users } from "lucide-react"
-import { stripInlineMarkup, type CommunityRole as Role } from "@alook/shared"
+import { messagePreviewText, type CommunityRole as Role } from "@alook/shared"
import { Avatar } from "@/components/community/avatar"
import { MemberList } from "@/components/community/members/member-list"
@@ -141,7 +141,7 @@ function renderCommunityPanelBody({
timestampProps={{ dateTime: message.createdAt }}
/>
<div className="truncate text-sm text-muted-foreground">
- {stripInlineMarkup(message.content ?? "")}
+ {messagePreviewText(message)}
</div>
</div>
</button>
@@ -174,7 +174,7 @@ function renderCommunityPanelBody({
<span className="font-medium text-foreground/80">
{author?.name ?? thread.parent.authorName}
</span>{" "}
- {stripInlineMarkup(thread.parent.text)}
+ {thread.parent.text}
</div>
<div className="mt-1 text-xs text-muted-foreground" suppressHydrationWarning>
{thread.messageCount} messages · {formatRelativeTime(thread.lastMessageAt)}
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
index da7448f70..d10fccfd7 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
@@ -110,12 +110,12 @@ describe("complete canonical coverage at the existing repair owner", () => {
it("retains current-window correction of a deleted reply target even when creations are cached", async () => {
const h = await setup()
- ingestMessages(h.registry, "c1", [{ ...row(100), replyTo: { id: "gone", authorId: "peer", authorName: "Peer", text: "old reply" } }, row(101)])
- load.mockResolvedValueOnce(page([{ ...row(100), replyTo: { id: "gone", authorName: "Deleted user", text: "", deleted: true } }], 101))
+ ingestMessages(h.registry, "c1", [{ ...row(100), replyTo: { id: "gone", authorId: "peer", authorName: "Peer", } }, row(101)])
+ load.mockResolvedValueOnce(page([{ ...row(100), replyTo: { id: "gone", authorName: "Deleted user", deleted: true } }], 101))
try {
await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages"])
- expect(h.registry.collections.messages.get("m100")?.replyTo).toEqual({ id: "gone", authorName: "Deleted user", text: "", deleted: true })
+ expect(h.registry.collections.messages.get("m100")?.replyTo).toEqual({ id: "gone", authorName: "Deleted user", deleted: true })
expect(h.ids()).toEqual(["m98", "m99", "m100", "m101"])
} finally { h.unsubscribe() }
})
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
index ae35be056..c8ba6bb4b 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -483,6 +483,7 @@ describe("focused message reconnect catch-up", () => {
expect(publishCommunityMessagesMock).toHaveBeenCalledWith(queryClient, {
profiles: expect.arrayContaining([expect.objectContaining({ id: "viewer", discriminator: "0042", avatar: null, avatarVersion: 0 })]),
channelId: "ch_gap",
+ relatedMessages: [],
messages: expect.arrayContaining([
expect.objectContaining({ id: "m_2" }),
expect.objectContaining({ id: "m_3" }),
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
index 6a7b85b5d..3079fcff2 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -214,7 +214,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
? [prefetched.page, cached] : [...(cached ? [cached] : []), ...(prefetched ? [prefetched.page] : [])]
const pending = [refreshed, ...(prefetched ? [prefetched.page] : [])].filter(page => !published.has(page))
if (pending.length) {
- await publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), profiles: [...new Map(pending.flatMap(page => page.profiles).map(profile => [profile.id, profile])).values()], proof: { token, signal } })
+ await publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), relatedMessages: pending.flatMap(page => page.relatedMessages ?? []), profiles: [...new Map(pending.flatMap(page => page.profiles).map(profile => [profile.id, profile])).values()], proof: { token, signal } })
for (const page of pending) published.add(page)
}
queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)
diff --git a/src/web/src/hooks/community/forum-feed-window.ts b/src/web/src/hooks/community/forum-feed-window.ts
index 22739e688..6ace8f94e 100644
--- a/src/web/src/hooks/community/forum-feed-window.ts
+++ b/src/web/src/hooks/community/forum-feed-window.ts
@@ -1,15 +1,15 @@
-import { FORUM_ARCHIVE_TAG, communityReadSchemas, type CommunityChannelResource, type CommunityThreadsRead, type CommunityMessageResource, type CommunityMemberRelation } from "@alook/shared"
+import { FORUM_ARCHIVE_TAG, communityReadSchemas, messagePreviewText, type CommunityChannelResource, type CommunityThreadsRead, type CommunityMessageResource, type CommunityMemberRelation } from "@alook/shared"
import type { InfiniteData } from "@tanstack/react-query"
import type { 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 {
+export function projectThread(thread: ChannelRow, opener: Msg | undefined, parentType: string, first?: Msg): Thread {
return {
id: thread.id,
name: parentType === "forum" ? (opener?.content?.trim() ? opener.content : thread.name || "Post") : thread.name ?? "",
messageCount: thread.messageCount ?? 0,
lastMessageAt: thread.lastMessageAt ?? "",
- parent: { authorId: opener?.authorId, authorName: opener?.authorName ?? "", text: parentType === "forum" ? thread.preview ?? "" : opener?.content ?? thread.preview ?? "" },
+ parent: { authorId: opener?.authorId, authorName: opener?.authorName ?? "", text: parentType === "forum" ? first ? messagePreviewText(first) : "" : opener ? messagePreviewText(opener) : "" },
...(opener?.seq === undefined ? {} : { parentSeq: opener.seq }),
}
}
@@ -24,7 +24,11 @@ export function normalizeThreadResources(channelId: string, value: unknown): Com
const data = communityReadSchemas().threads.parse(value)
if (data.channelId !== channelId || data.channel.id !== channelId
|| data.threads.some(thread => thread.parentChannelId !== channelId || thread.serverId !== data.channel.serverId)) throw new Error("Thread resource scope mismatch")
- return { ...data, included: { ...data.included, previews: data.included.messages.filter(message => message.channelId !== channelId) } }
+ const previews = data.threads.flatMap(thread => {
+ const first = data.included.messages.filter(message => message.channelId === thread.id).sort((a, b) => a.seq - b.seq)[0]
+ return first ? [first] : []
+ })
+ return { ...data, included: { ...data.included, previews } }
}
export type ForumFeedPage = Pick<CommunityThreadsRead["page"], "hasMore"> & {
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index cb3dd1c92..eb0c33ea0 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -61,7 +61,7 @@ export function useCreateForumThread() {
await Promise.all([origin.registry!.collections.channels.preload(), origin.registry!.collections.messages.preload(), origin.registry!.collections.channelMemberships.preload()])
assert()
const attachmentIds = attachments?.map((a) => a.id)
- const structure = await origin.request<CreateForumThreadResult & Pick<CommunityMessagePosted, "message" | "profiles">>(token,
+ const structure = await origin.request<CreateForumThreadResult & Pick<CommunityMessagePosted, "message" | "profiles" | "relatedMessages">>(token,
`/api/community/channels/${channelId}/messages`,
{
method: "POST", signal: assertActive?.signal, assertActive,
@@ -71,19 +71,19 @@ export function useCreateForumThread() {
assert()
const parent = origin.registry!.collections.channels.get(channelId)
if (parent && structure.message) {
- await publishCommunityMessages(queryClient, { channelId, profiles: structure.profiles, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
+ await publishCommunityMessages(queryClient, { channelId, profiles: structure.profiles, relatedMessages: structure.relatedMessages, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
const child = await origin.request<CommunityChannelResource>(token, `/api/community/channels/${structure.threadId}`, { method: "GET", signal: assertActive?.signal, assertActive })
assert()
if (child.parentChannelId !== channelId || child.parentMessageId !== structure.message.id || child.serverId !== parent.serverId) throw new Error("Created forum child scope mismatch")
await completeCommunityPublication(queryClient, () => publishCommunityCreatedChannel(queryClient, child, { token, signal: assertActive?.signal }))
}
assert()
- const reply = await origin.request<Pick<CommunityMessagePosted, "message" | "profiles">>(token, `/api/community/channels/${structure.threadId}/messages`, {
+ const reply = await origin.request<Pick<CommunityMessagePosted, "message" | "profiles" | "relatedMessages">>(token, `/api/community/channels/${structure.threadId}/messages`, {
method: "POST", signal: assertActive?.signal, assertActive,
body: JSON.stringify({ content, attachments: attachmentIds, nonce: `${nonce}:reply` }),
})
assert()
- if (reply.message) await publishCommunityMessages(queryClient, { channelId: structure.threadId, profiles: reply.profiles, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })
+ if (reply.message) await publishCommunityMessages(queryClient, { channelId: structure.threadId, profiles: reply.profiles, relatedMessages: reply.relatedMessages, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })
for (const query of resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)
return structure
},
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 e7933144b..24a617086 100644
--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts
@@ -197,6 +197,8 @@ describe("useSendMessage — happy path", () => {
runtime.ui.actions.setCurrentServerId(scope.serverId)
runtime.ui.actions.subscribe({ channelId: scope.id })
const replyTo = { id: "reply_1", authorId: "reply-author", authorName: "Reply Author", text: "preview" }
+ const { text: _previewText, ...replyRelation } = replyTo
+ const replyTarget = messageResourceFixture({ id: replyTo.id, channelId: scope.id, authorId: "reply-author", authorName: replyTo.authorName, content: "preview" })
const attachment = { id: "file_1", filename: "notes.txt", contentType: "text/plain", size: 1024 }
const remoteAttachment = { id: attachment.id, kind: "file" as const, name: attachment.filename,
url: "/api/community/channels/ch_1/attachments/file_1", contentType: attachment.contentType,
@@ -224,7 +226,7 @@ describe("useSendMessage — happy path", () => {
let currentBase: import("@/lib/community/message-stream").CanonicalMessage[] = [older]
for (const stage of stages) {
if (stage === "post") {
- await act(async () => { release({ profiles: messageProfilesFixture([postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo, attachments: [wireAttachment] })]), message: postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo, attachments: [wireAttachment] }) }); await pending })
+ await act(async () => { release({ relatedMessages: [replyTarget], profiles: messageProfilesFixture([postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo: replyRelation, attachments: [wireAttachment] })]), message: postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo: replyRelation, attachments: [wireAttachment] }) }); await pending })
expect(getMessageStreamState(capturedQc, scope).liveIds).toContain("server_id_1")
expect(materializeMessageStream([], getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc)).find(row => row.id === "server_id_1")).toMatchObject({
id: "server_id_1", seq: 9, authorName: "Canonical Name", content: "canonical content",
@@ -232,15 +234,15 @@ describe("useSendMessage — happy path", () => {
embeds: [{ title: "Canonical embed" }], replyTo, attachments: [remoteAttachment], clientNonce: "n1", failed: false,
})
} else if (stage === "ws") {
- await act(async () => { dispatchCommunityWsEvent({ profiles: messageProfilesFixture([{ id: "server_id_1", channelId: scope.id, seq: 9, type: "chat", authorId: "u_me",
+ await act(async () => { dispatchCommunityWsEvent({ relatedMessages: [replyTarget], profiles: messageProfilesFixture([{ id: "server_id_1", channelId: scope.id, seq: 9, type: "chat", authorId: "u_me",
authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0, content: "canonical content",
- createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyToId: replyTo.id, replyTo,
+ createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyToId: replyTo.id, replyTo: replyRelation,
embeds: [{ title: "Canonical embed" }],
attachments: [wireAttachment],
}]), type: "community:message.create", serverId: scope.serverId,
channelId: scope.id, message: { id: "server_id_1", channelId: scope.id, seq: 9, type: "chat", authorId: "u_me",
authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0, content: "canonical content",
- createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyToId: replyTo.id, replyTo,
+ createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyToId: replyTo.id, replyTo: replyRelation,
embeds: [{ title: "Canonical embed" }],
attachments: [wireAttachment],
} }, { deliveryMode: "single", queryClient: capturedQc, communityStore: runtime.ui, wsStore: runtime.ws,
@@ -250,9 +252,9 @@ describe("useSendMessage — happy path", () => {
const { channelMessagesQueryFn } = await import("@/hooks/community/use-messages")
const { decodeCommunityReadResponse } = await import("@/lib/community/read-response")
const path = `/api/community/channels/${scope.id}/messages`
- const confirmed = postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo, attachments: [wireAttachment] })
+ const confirmed = postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo: replyRelation, attachments: [wireAttachment] })
apiFetchMock.mockResolvedValueOnce(decodeCommunityReadResponse(path, "GET", new Response(null, { headers: { "X-Alook-Community-Contract": String(BUSINESS_SCHEMA_VERSION) } }), { profiles: messageProfilesFixture([older, confirmed]),
- contractVersion: BUSINESS_SCHEMA_VERSION, channelId: scope.id, messages: [older, confirmed],
+ contractVersion: BUSINESS_SCHEMA_VERSION, relatedMessages: [replyTarget], channelId: scope.id, messages: [older, confirmed],
surfaceReceipt: { channelId: scope.id, surfaceKind: "channel" },
page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 9 },
}))
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 9bbe4e927..823b97231 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -127,7 +127,7 @@ export type SendMessageArgs = {
// the same nonce — `message` is the canonical (original) row, nothing new was
// inserted. The caller treats it as success (reconcile the optimistic row,
// clear the failed pill), never as a failure to resend.
-export type SendMessageResult = Pick<CommunityMessagePosted, "message" | "profiles"> & { deduped?: boolean }
+export type SendMessageResult = Pick<CommunityMessagePosted, "message" | "profiles" | "relatedMessages"> & { deduped?: boolean }
/**
* Channel/thread send. The server infers thread-vs-channel routing from the
@@ -176,7 +176,6 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
const { content, replyToId, replyTo, attachments, nonce, original: token, assertActive, assertCommand } = args
origin.assert(token); (assertCommand ?? assertActive)?.()
const scope = sendMessageScope(args)
- const acceptedReply = replyTo ?? getCommunityRuntime(queryClient).messageStream.actions.getRetryPayload(scope, nonce ?? "")?.message.replyTo
const result = await origin.request<SendMessageResult>(token, `/api/community/channels/${scope.id}/messages`, {
method: "POST", signal: assertCommand ? undefined : assertActive?.signal, assertActive: assertCommand ?? assertActive,
body: JSON.stringify({ content, replyToId: replyTo?.id ?? replyToId,
@@ -187,7 +186,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
origin.assert(token); (assertCommand ?? assertActive)?.()
const message = postedMessageForIntent(result.message, nonce ?? "", scope.id)
await publishCommunityMessages(queryClient, { channelId: scope.id, profiles: result.profiles,
- messages: [{ ...message, ...(acceptedReply && !("replyTo" in result.message) && (!("replyToId" in result.message) || result.message.replyToId === acceptedReply.id) ? { replyTo: acceptedReply } : {}) }],
+ messages: [message], relatedMessages: result.relatedMessages,
proof: { token, ...(scope.kind === "channel" && !assertCommand ? { signal: assertActive?.signal } : {}) } })
return result
},
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 d85ae22cc..324c447e7 100644
--- a/src/web/src/hooks/community/use-channel-panels.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.test.ts
@@ -108,7 +108,7 @@ describe("usePins / pinsQueryFn", () => {
it("publishes rich pin facts only from the supplied full resource", async () => {
const rich = messageResourceFixture({ id: "m_1", channelId: "ch_1", replyToId: "reply", type: "system" as const, systemKind: "thread" as const,
authorId: "u1", content: "full", clientNonce: "known-nonce",
- replyTo: { id: "reply", authorId: "peer", authorName: "Peer", text: "Prior" },
+ replyTo: { id: "reply", authorId: "peer", authorName: "Peer", },
attachments: [{ id: "file", name: "known.txt", url: "/known", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 1024, width: null, height: null }],
embeds: [{ title: "Known" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
})
@@ -151,12 +151,13 @@ describe("materializeThreadsResponse", () => {
const preview = "preview".repeat(30), content = "content".repeat(30)
const base = { ...channelResourceFixture({ id: "base", serverId: "s1", type: "thread", parentChannelId: "forum" }), muted: false, pending: false, tags: [] }
const channels = new Map([
- ["post", channelSchema.parse({ ...base, id: "post", name: "Fallback", createdAt: "created", preview, parentMessageId: "opener" })],
- ["empty", channelSchema.parse({ ...base, id: "empty", name: "", preview, createdAt: "created" })],
+ ["post", channelSchema.parse({ ...base, id: "post", name: "Fallback", createdAt: "created", firstMessageId: "body", parentMessageId: "opener" })],
+ ["empty", channelSchema.parse({ ...base, id: "empty", name: "", firstMessageId: "body", createdAt: "created" })],
["archived", channelSchema.parse({ ...base, id: "archived", name: "Archived", archived: true })],
])
const data = { parentType: "forum", serverId: "s1", parentChannelId: "forum", threads: [{ id: "post", openerMessageId: "opener" }, { id: "empty" }, { id: "archived" }] }
const messages = new Map([["opener", { id: "opener", type: "chat" as const, content: " ", authorId: "u1", authorName: "A", seq: 0 }]])
+ messages.set("body", { id: "body", type: "chat", content: preview, authorId: "u1", authorName: "A", seq: 1 })
const forum = materializeThreadsResponse(data, messages, channels)
expect(forum).toHaveLength(2)
expect(forum[0]).toEqual({ id: "post", name: "Fallback", messageCount: 0, lastMessageAt: "created", parent: { authorId: "u1", authorName: "A", text: preview }, parentSeq: 0, openerMessageId: "opener" })
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index b08dcef79..48eab67ee 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -65,7 +65,7 @@ export function materializeThreadsResponse(data: ThreadsResponse | undefined, me
return data.threads.flatMap((window) => {
const thread = channels.get(window.id), opener = window.openerMessageId ? messages?.get(window.openerMessageId) : undefined
if (!thread || (window.openerMessageId && !opener) || thread.archived) return []
- const core = projectThread(thread, opener, data.parentType)
+ const core = projectThread(thread, opener, data.parentType, thread.firstMessageId ? messages?.get(thread.firstMessageId) : undefined)
return [{ ...core, lastMessageAt: thread.lastMessageAt ?? thread.createdAt ?? "", parent: data.parentType === "forum" ? core.parent : { ...core.parent, text: core.parent.text.slice(0, 100) }, ...(window.openerMessageId ? { openerMessageId: window.openerMessageId } : {}) }]
})
}
@@ -84,7 +84,7 @@ export function useThreads(channelId: string | null, requested = true): UseQuery
: (() => Promise.reject(new Error("disabled"))),
enabled: enabled && presented && requested,
})
- const messageIds = useMemo(() => query.data?.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : []) ?? [], [query.data?.threads])
+ const messageIds = useMemo(() => query.data?.threads.flatMap((thread) => [...(thread.openerMessageId ? [thread.openerMessageId] : []), ...(channels.get(thread.id)?.firstMessageId ? [channels.get(thread.id)!.firstMessageId!] : [])]) ?? [], [query.data?.threads, channels])
const canonicalMessages = useCanonicalMessagesById(messageIds)
const threads = materializeThreadsResponse(query.data, canonicalMessages, channels)
return {
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 de9d8edf5..6b6851172 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
@@ -61,11 +61,11 @@ describe("Native DM sender", () => {
const receipt = owner.accept({ content: "@Peer\nhello", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" } })
expect(owner.overlay().outboxByNonce.get("fresh_nonce")?.message).toMatchObject({ authorId: "u_me", authorName: "Me", content: "@Peer\nhello", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" } })
await waitFor(() => expect(mocks.post).toHaveBeenCalledExactlyOnceWith({ content: "@Peer\nhello", replyToId: "prior", nonce: "fresh_nonce" }))
- resolve({ ...posted(), profiles: [...posted().profiles, profileResourceFixture({ id: "peer", name: "Peer" })], message: { ...posted().message, replyToId: "prior" } })
+ resolve({ ...posted(), profiles: [...posted().profiles, profileResourceFixture({ id: "peer", name: "Peer" })], message: { ...posted().message, replyToId: "prior", replyTo: { id: "prior", authorId: "peer", authorName: "Peer" } } })
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", authorId: "peer", authorName: "Peer", text: "quoted" } })
+ type: "chat", content: "hello", replyToId: "prior", replyTo: { id: "prior", authorId: "peer", authorName: "Peer" } })
expect(canonical).not.toHaveProperty("authorEmail")
expect(canonical).not.toHaveProperty("storageMetadata")
const { awaitCommittedInvite } = await import("@/components/community/social/invite-dialog")
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 8dd1473bb..129970832 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
@@ -7,7 +7,7 @@ import { renderHook, waitFor } from "@/test/react-dom-harness"
import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
-import { getCanonicalCommunityMessages, getCanonicalCommunityChannels, patchCanonicalCommunityChannel } from "@/lib/community-db/sync"
+import { getCanonicalCommunityMessages, getCanonicalCommunityChannels, patchCanonicalCommunityChannel, patchCanonicalCommunityMessage } from "@/lib/community-db/sync"
import { forumFeedWindow, normalizeThreadResources, type ForumFeedTransportPage } from "./forum-feed-window"
import { CONVERSATION_READ_TIMEOUT_MS } from "@/lib/community/conversation-read"
import { communityKeys } from "@/lib/query-keys"
@@ -138,12 +138,26 @@ describe("forumFeedPageQueryFn", () => {
const feed = forumConversationEntryFixture("forum_one", "server_1").forumFeed!
const profiles = ["opener-author", "first-author", "reply-author"].map(id => ({ id, name: id, discriminator: "0042", avatar: null, avatarVersion: 1 }))
const messages = [messageResourceFixture({ id: "m1", channelId: "forum_one", authorId: "opener-author" }),
- messageResourceFixture({ id: "first-t1", channelId: "t1", authorId: "first-author", replyToId: "previous", replyTo: { id: "previous", authorId: "reply-author", authorName: "reply-author", text: "Earlier" } })]
+ messageResourceFixture({ id: "first-t1", channelId: "t1", authorId: "first-author", replyToId: "previous", replyTo: { id: "previous", authorId: "reply-author", authorName: "reply-author" } })]
apiFetchMock.mockResolvedValue({ ...feed, included: { ...feed.included, profiles, messages } })
await forumFeedPageQueryFn("forum_one", null, client)({ pageParam: null })
for (const profile of profiles) expect(getCommunityDbRegistry(client)!.collections.profiles.get(profile.id)).toMatchObject(profile)
})
+ it("publishes an opener's reply target without adding a post or requesting it per row", async () => {
+ const feed = forumConversationEntryFixture("forum_one", "server_1").forumFeed!
+ const target = messageResourceFixture({ id: "old-target", channelId: "forum_one", authorId: "target-author", content: "**Target** ||private||" })
+ const opener = { ...feed.included.messages[0], replyToId: target.id, replyTo: { id: target.id, authorId: target.authorId, authorName: "Target author" } }
+ const profiles = [...feed.included.profiles, { id: target.authorId, name: "Target author", discriminator: "0042", avatar: null, avatarVersion: 1 }]
+ apiFetchMock.mockResolvedValue({ ...feed, included: { ...feed.included, messages: [target, opener, ...feed.included.messages.filter(message => message.id !== opener.id)], profiles } })
+ const page = await forumFeedPageQueryFn("forum_one", null, client)({ pageParam: null })
+ expect(page.threads.map(thread => thread.id)).toEqual(["t1"])
+ expect(page.threads[0].openerMessageId).toBe(opener.id)
+ expect(getCommunityDbRegistry(client)!.collections.messages.get(target.id)?.content).toBe(target.content)
+ expect(getCommunityDbRegistry(client)!.collections.profiles.get(target.authorId)?.name).toBe("Target author")
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ })
+
it("seeds opener and participant profiles while returning only the ID window", async () => {
const page = forumFeedScenarioFixture("forum_one", {
serverId: "server_1", parentType: "forum",
@@ -191,7 +205,8 @@ describe("mapForumFeedPages", () => {
expect(result).toHaveLength(1)
expect(result[0]).toMatchObject({ name: "Fallback", messageCount: 0, lastMessageAt: "", parent: { authorId: "u1", authorName: "A", text: preview }, parentSeq: 0, openerMessageId: "opener", preview })
const updatedPreview = "updated preview".repeat(30)
- patchCanonicalCommunityChannel(client, "post", (row) => ({ ...row, preview: updatedPreview, lastMessageAt: null }))
+ const firstId = getCommunityDbRegistry(client)!.collections.channels.get("post")!.firstMessageId!
+ patchCanonicalCommunityMessage(client, firstId, (row) => ({ ...row, content: updatedPreview }))
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.id, row])))
expect(projected[0]).toMatchObject({ lastMessageAt: "", parent: { text: updatedPreview }, preview: updatedPreview, parentSeq: 0 })
@@ -404,8 +419,8 @@ describe("mapForumFeedPages", () => {
name: "canonical content",
authorId: "transport-author",
authorAvatarVersion: 0,
- preview: "transport preview",
- parent: { authorName: "Canonical", text: "transport preview" },
+ preview: "",
+ parent: { authorName: "Canonical", text: "" },
}),
])
expect(result[0]).not.toHaveProperty("openerCreatedAt")
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index d2b797a2e..67305e111 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -4,7 +4,7 @@ import { useConversationPresentation } from "@/contexts/community/conversation-a
import { useCallback, useEffect, useMemo, useState } 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, messagePreviewText, type CommunityThreadsRead } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { ConversationReadTimeoutError, conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"
@@ -72,7 +72,9 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null, quer
const page = normalizeThreadResources(channelId, transport)
const freshThreads = page.threads.filter((thread) => !protocol.get().publishedIds.has(thread.id))
const ids = new Set(freshThreads.map((thread) => thread.id)), openerIds = new Set(freshThreads.map((thread) => thread.parentMessageId))
- const messages = page.included.messages.filter((message) => openerIds.has(message.id) || ids.has(message.channelId))
+ const roots = page.included.messages.filter((message) => openerIds.has(message.id) || ids.has(message.channelId))
+ const replyIds = new Set(roots.flatMap(message => message.replyToId ? [message.replyToId] : []))
+ const messages = page.included.messages.filter((message) => roots.includes(message) || replyIds.has(message.id) && roots.some(root => root.replyToId === message.id && root.channelId === message.channelId))
const users = new Set([...page.included.members.filter((member) => ids.has(member.channelId)).map((member) => member.userId), ...messages.flatMap(messageProfileIds)])
await publishCommunityForumFeed(queryClient, channelId, { ...page, threads: freshThreads, included: {
messages,
@@ -94,9 +96,9 @@ export function mapForumFeedPages(pages: ForumFeedPage[], messages: ReadonlyMap<
const thread = channels.get(window.id), opener = window.openerMessageId ? messages.get(window.openerMessageId) : undefined
if (!thread || !opener || thread.parentMessageId !== opener.id || !forumFeedMatchesTags(filter, thread.tags)) continue
byId.set(thread.id, {
- ...projectThread(thread, opener, "forum"), authorId: opener.authorId ?? thread.creatorId ?? "",
+ ...projectThread(thread, opener, "forum", thread.firstMessageId ? messages.get(thread.firstMessageId) : undefined), authorId: opener.authorId ?? thread.creatorId ?? "",
authorAvatar: opener.authorAvatar ?? avatarInitial(opener.authorName ?? ""), authorAvatarVersion: opener.authorAvatarVersion ?? 0,
- openerMessageId: opener.id, ...(opener.createdAt === undefined ? {} : { openerCreatedAt: opener.createdAt }), tags: thread.tags, preview: thread.preview ?? "",
+ openerMessageId: opener.id, ...(opener.createdAt === undefined ? {} : { openerCreatedAt: opener.createdAt }), tags: thread.tags, preview: thread.firstMessageId && messages.get(thread.firstMessageId) ? messagePreviewText(messages.get(thread.firstMessageId)!) : "",
participants: window.participantIds.map((id) => { const profile = readCommunityProfile(profiles.get(id), id); return { id, name: profile.name, avatar: profile.avatar, avatarVersion: profile.avatarVersion } }), participantCount: thread.participantCount ?? 0,
})
}
@@ -133,7 +135,7 @@ export function useForumFeed(serverId: string, channelId: string, options?: { ro
enabled: presented && selectionReady && entry.canRead && !entry.verificationFetching && (!entry.verificationFailed || entry.displayWindow !== undefined), subscribed: selectionReady && entry.canRead, staleTime: 5_000,
retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry), networkMode: "always" })
const displayCandidate = selectionReady && entry.canRead && entry.displayWindow !== undefined
- const messageIds = useMemo(() => [...new Set(displayCandidate ? query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : [])) ?? [] : [])], [displayCandidate, query.data?.pages])
+ const messageIds = useMemo(() => [...new Set(displayCandidate ? query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => [...(thread.openerMessageId ? [thread.openerMessageId] : []), ...(channels.get(thread.id)?.firstMessageId ? [channels.get(thread.id)!.firstMessageId!] : [])])) ?? [] : [])], [displayCandidate, query.data?.pages, channels])
const messages = useCanonicalMessagesById(messageIds)
const displayReady = displayCandidate && query.data !== undefined && messageIds.every(id => messages?.has(id))
&& query.data.pages.every(page => page.threads.every(thread => channels.has(thread.id) && thread.participantIds.every(id => profiles.has(id))))
diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.ts
index b5e370621..f31b9f0a4 100644
--- a/src/web/src/hooks/community/use-message.test.ts
+++ b/src/web/src/hooks/community/use-message.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityMessageReadSchema, type CommunityMessageResource } from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { profileResourceFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
import { writeCommunityProfilePatches, communityUserProfilePatch } from "@/lib/community/profile-seed"
import { ingestMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
import { findCachedMessage, messageQueryFn, prefetchCommunityMessage, prefetchCommunityLatestMessage } from "./use-message"
@@ -150,7 +150,7 @@ describe("useMessage / messageQueryFn", () => {
ingestMessages(registry, payload.channelId, [{ ...payload,
attachments: [{ id: "old", name: "old.txt", url: "/old", sizeBytes: 1024, thumbnailUrl: null, contentType: null, width: null, height: null }],
embeds: [{ title: "Old" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
- replyToId: "reply", replyTo: { id: "reply", authorId: "peer", authorName: "Peer", text: "Old reply" },
+ replyToId: "reply", replyTo: { id: "reply", authorId: "peer", authorName: "Peer", },
}])
apiFetchMock.mockResolvedValueOnce(singleRead({ ...payload, seq: 1, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] }))
await client.query({ queryKey: communityKeys.message(payload.id), queryFn: messageQueryFn(payload.id, client) })
@@ -183,19 +183,19 @@ describe("useMessage / messageQueryFn", () => {
})
it("derives an opener placeholder from a persisted canonical message window", async () => {
- const { client, registry } = await createCommunityQueryOwner()
+ const { client, registry } = await createCommunityQueryOwner("u_1")
const message = {
...payload, content: "cached opener",
- replyToId: "m_0", replyTo: { id: "m_0", authorId: "u_0", authorName: "Bob", text: "parent" },
+ replyToId: "m_0", replyTo: { id: "m_0", authorId: "u_0", authorName: "Bob", },
attachments: [{ id: "notes", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, thumbnailUrl: null, contentType: null, width: null, height: null }],
embeds: [{ title: "Reference" }],
reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_1"] }],
}
writeCommunityProfilePatches([authorProfile, profileResourceFixture({ id: "u_0", name: "Bob" })].map(profile => communityUserProfilePatch(profile.id, profile)), registry)
- ingestMessages(registry, "channel-1", [message])
+ ingestMessages(registry, "channel-1", [message, messageResourceFixture({ id: "m_0", channelId: "channel-1", authorId: "u_0", content: "parent" })])
client.setQueryData(communityKeys.channelMessages("channel-1"), { pages: [{ ids: [message.id], hasMoreOlder: false, hasMoreNewer: false }], pageParams: [{ mode: "newest" }] })
const { channelId: _channelId, replyToId: _replyToId, clientNonce: _clientNonce, ...view } = message
- expect(findCachedMessage(client, message.id)).toMatchObject({ ...view, authorAvatar: "A", attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, size: "1.0 KB" }] })
+ expect(findCachedMessage(client, message.id)).toMatchObject({ ...view, replyTo: { ...message.replyTo, text: "parent" }, authorAvatar: "A", 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 62f3ad1ce..0182e8470 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -72,6 +72,7 @@ export const messageQueryFn = (
await publishCommunityMessages(queryClient, {
channelId: publishChannelId,
messages: [message],
+ relatedMessages: read.relatedMessages,
profiles: read.profiles,
proof: { token, signal: readSignal },
})
@@ -119,7 +120,7 @@ export async function prefetchCommunityLatestMessage(queryClient: QueryClient, c
`/api/community/channels/${channelId}/messages?limit=1`,
{ signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } }, token,
)
- await publishCommunityMessages(queryClient, { channelId, messages: page.messages, profiles: page.profiles, proof: { token, signal: readSignal } })
+ await publishCommunityMessages(queryClient, { channelId, messages: page.messages, relatedMessages: page.relatedMessages, profiles: page.profiles, proof: { token, signal: readSignal } })
return page.messages[0]?.id ?? null
}),
select: undefined,
@@ -135,7 +136,7 @@ export function findCachedMessage(
const graph = getCanonicalCommunityMessageResources(queryClient, [message])
const author = graph?.profiles.find(profile => profile.id === message.authorId)
if (!author) return undefined
- const view = presentCanonicalMessage(message)
+ const view = presentCanonicalMessage(message, message.replyToId ? getCanonicalCommunityMessages(queryClient).find(row => row.id === message.replyToId && row.channelId === message.channelId) : undefined)
return {
...view,
authorId: message.authorId,
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 6e13df0de..e7de63112 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
@@ -109,17 +109,18 @@ describe("useMessages — instant channel switch", () => {
const scope: MessageScope = kind === "channel" ? { kind, id: "ch_new", serverId: "s1" } : { kind, id: "dm_new" }
const attachments = [{ id: "attachment", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, thumbnailUrl: null, contentType: "text/plain", width: null, height: null }]
const presentedAttachments = [{ id: "attachment", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, contentType: "text/plain", kind: "file", size: "1.0 KB" }]
- const embeds = [{ title: "Existing embed" }], replyTo = { id: "reply", authorId: "peer", authorName: "Peer", text: "reply" }
+ const embeds = [{ title: "Existing embed" }], replyTo = { id: "reply", authorId: "peer", authorName: "Peer" }
+ const visibleReply = { ...replyTo, 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, [messageResourceFixture({ ...message, channelId: scope.id, replyToId: "reply", attachments, embeds, replyTo })])
+ ingestMessages(registry, scope.id, [messageResourceFixture({ ...message, channelId: scope.id, replyToId: "reply", attachments, embeds, replyTo }), messageResourceFixture({ id: "reply", channelId: scope.id, authorId: "peer", content: "reply" })])
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, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, attachments: presentedAttachments, embeds, replyTo })])
+ expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, attachments: presentedAttachments, embeds, replyTo: visibleReply })])
await act(async () => { publishCommunityMessageFields(client, message.id, { content: "content patch" }, { token: captureCommunityLiveSnapshotToken(client, scope.id) }) })
expect(registry.collections.messages.get(message.id)).toMatchObject({ content: "content patch", attachments, embeds, replyTo })
- expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "content patch", attachments: presentedAttachments, embeds, replyTo })])
+ expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "content patch", attachments: presentedAttachments, embeds, replyTo: visibleReply })])
await act(async () => { dispatchLive(client, scope, { type: "wsMessage", message: { ...message, channelId: scope.id, replyToId: "reply", content: "cleared", attachments: [], embeds: [] } }) })
expect(registry.collections.messages.get(message.id)).toMatchObject({ attachments: [], embeds: [] })
- expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "cleared", attachments: [], embeds: [], replyTo })])
+ expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "cleared", attachments: [], embeds: [], replyTo: visibleReply })])
expect(apiFetchMock).not.toHaveBeenCalled()
})
it("paints a warm cache without waiting on the anchor", async () => {
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index b9e34b3f0..1342c0638 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -142,6 +142,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const projection = useMessageWindowProjection(entry.canRead ? channelId : null, ids, overlay.liveIds)
const canonicalById = useMemo(() => new Map((projection.canonicalMessages ?? []).flatMap((message) =>
typeof message.seq === "number" ? [[message.id, { ...message, seq: message.seq }] as const] : [])), [projection.canonicalMessages])
+ const presentationResources = useMemo(() => new Map([...projection.relatedMessages.map(message => [message.id, message] as const), ...canonicalById]), [canonicalById, projection.relatedMessages])
const missingCanonical = ids.some(id => !canonicalById.has(id))
const projectionFailed = projection.status === "error"
const [projectionFailure, setProjectionFailure] = useState<{ window: object; attempt: object | null; viewKey: string } | null>(null)
@@ -161,8 +162,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
useEffect(() => {
if (channelId) getCommunityRuntime(client).messageStream.actions.dispatch(scope, { type: "baseChanged", messages: canonicalBase })
}, [canonicalBase, channelId, client, scope])
- const messages = useMemo(() => entry.canRead ? materializeMessageStream(canonicalBase, overlay, canonicalById).filter((message) => messageMatchesTag(message, tag)) : [],
- [canonicalBase, canonicalById, overlay, entry.canRead, tag])
+ const messages = useMemo(() => entry.canRead ? materializeMessageStream(canonicalBase, overlay, presentationResources).filter((message) => messageMatchesTag(message, tag)) : [],
+ [canonicalBase, presentationResources, overlay, entry.canRead, tag])
const latestSeq = Math.max(0, ...(query.data?.pages.map((page) => page.latestSeq ?? 0) ?? []))
const landingWindow = entry.resource ? client.getQueryData<MessageWindowData>(entry.resource.windowKey) : undefined
const landingLatestSeq = Math.max(0, ...(landingWindow?.pages.map(page => page.latestSeq ?? 0) ?? []))
diff --git a/src/web/src/hooks/use-file-attachments.dom.test.ts b/src/web/src/hooks/use-file-attachments.dom.test.ts
index 0250f775b..a8781f13d 100644
--- a/src/web/src/hooks/use-file-attachments.dom.test.ts
+++ b/src/web/src/hooks/use-file-attachments.dom.test.ts
@@ -159,7 +159,7 @@ describe("useFileAttachments — DOM drop ownership", () => {
expect(generateThumbnailMock).not.toHaveBeenCalled()
})
- it("removes a DOM-dropped Community image when preparation fails visibly", async () => {
+ it("retains a failed DOM-dropped image until the user explicitly removes it", async () => {
prepareCommunityImageMock.mockRejectedValue(new Error("decode failed"))
const hook = await renderCapture({
thumbnailPolicy: "community",
@@ -167,11 +167,21 @@ describe("useFileAttachments — DOM drop ownership", () => {
})
const dropped = new File(["image"], "broken.png", { type: "image/png" })
- await dropFiles(hook, [dropped])
+ const preventDefault = vi.fn()
+ const stopPropagation = vi.fn()
+ act(() => hook.current.handleDrop({
+ preventDefault, stopPropagation, dataTransfer: { files: [dropped] },
+ } as unknown as React.DragEvent))
+ await waitFor(() => expect(toastErrorMock).toHaveBeenCalledWith('Could not prepare "broken.png" for upload'))
+ await expect(hook.current.awaitPendingFiles()).rejects.toThrow("Attachment preparation failed")
+ expect(preventDefault).toHaveBeenCalledOnce()
+ expect(stopPropagation).toHaveBeenCalledOnce()
+ expect(hook.current.pendingFiles).toEqual([expect.objectContaining({ file: dropped, preparationFailed: true })])
+ expect(readComposerAttachmentSession("server/channel")).toEqual([{ draftId: hook.current.pendingFiles[0]?.draftId, file: dropped }])
- expect(hook.current.pendingFiles).toEqual([])
+ act(() => hook.current.removePendingFile(0))
+ await expect(hook.current.awaitPendingFiles()).resolves.toEqual([])
expect(readComposerAttachmentSession("server/channel")).toEqual([])
- expect(toastErrorMock).toHaveBeenCalledWith('Could not prepare "broken.png" for upload')
})
})
@@ -337,9 +347,10 @@ describe("useFileAttachments — PendingFile width/height", () => {
await hook.addFiles([file])
- expect(hook.current.pendingFiles).toEqual([])
+ await expect(hook.current.awaitPendingFiles()).rejects.toThrow("Attachment preparation failed")
+ expect(hook.current.pendingFiles).toEqual([expect.objectContaining({ file, preparationFailed: true, thumbnailBlob: null, thumbnailUrl: null })])
expect(toastErrorMock).toHaveBeenCalledWith('Could not prepare "photo.png" for upload')
- expect(readComposerAttachmentSession("server/channel")).toEqual([])
+ expect(readComposerAttachmentSession("server/channel")).toEqual([{ draftId: hook.current.pendingFiles[0]?.draftId, file }])
})
it("registers raw Community Files synchronously before async image preparation", async () => {
diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.ts
index 021cbc7b4..a21529eb8 100644
--- a/src/web/src/hooks/use-file-attachments.ts
+++ b/src/web/src/hooks/use-file-attachments.ts
@@ -20,6 +20,7 @@ export type PendingFile = {
thumbnailUrl: string | null;
thumbnailBlob: Blob | null;
preparing?: boolean;
+ preparationFailed?: boolean;
width?: number;
height?: number;
};
@@ -72,7 +73,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
}, [protocol]);
type Preparation = { drafts: readonly AttachmentDraftFile[]; generation: number; policy: "legacy" | "community"; scope?: string; signal: AbortSignal };
const preparation = useMutation({ meta: { observabilityAction: "attachment.prepare" }, mutationKey: key, scope: { id }, gcTime: 0,
- mutationFn: async ({ drafts, generation, policy, scope, signal }: Preparation) => {
+ mutationFn: async ({ drafts, generation, policy, signal }: Preparation) => {
const eligible = () => protocol.get().active && protocol.get().generation === generation && !signal.aborted;
if (!eligible()) return;
for (const { draftId, file } of drafts) {
@@ -96,7 +97,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
const preview = blob ?? (policy === "community" && thumbnail ? file : null);
prepared = { draftId, file, thumbnailUrl: preview ? URL.createObjectURL(preview) : null, thumbnailBlob: blob, width: thumbnail?.width, height: thumbnail?.height };
} catch {
- if (owns()) { toast.error(`Could not prepare "${file.name}" for upload`); if (scope) removeComposerAttachmentSessionFiles(scope, [draftId]); }
+ if (owns()) { toast.error(`Could not prepare "${file.name}" for upload`); prepared = { draftId, file, thumbnailUrl: null, thumbnailBlob: null, preparationFailed: true }; }
}
if (!owns()) { if (prepared) revokeThumbnailUrls([prepared]); continue; }
protocol.setState((state) => {
@@ -177,7 +178,10 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {
original.controller.signal.addEventListener("abort", finish, { once: true });
finish();
});
- assert(); return protocol.get().files;
+ assert();
+ const files = protocol.get().files;
+ if (files.some((file) => file.preparationFailed)) throw new Error("Attachment preparation failed");
+ return files;
}, [client, key, protocol]);
const handleFileSelect = useCallback((event: React.ChangeEvent<HTMLInputElement>) => { if (event.target.files) void addPendingFiles(Array.from(event.target.files)).catch(() => undefined); event.target.value = ""; }, [addPendingFiles]);
const removePendingFile = useCallback((index: number) => {
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 772be4164..7fcab4685 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -41,11 +41,11 @@ import type {
} from "./schema"
function projectedCanonicalMessage(message: MessageRow, child?: ChannelRow): CommunityMessageResource {
- 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 } } : {}) }
+ return { ...message, ...(child ? { thread: { id: child.id, name: child.name ?? "", messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, firstMessageId: child.firstMessageId, participantCount: child.participantCount } } : {}) }
}
-function projectedMessage(message: MessageRow, child?: ChannelRow): Msg {
- return presentCanonicalMessage(projectedCanonicalMessage(message, child))
+function projectedMessage(message: MessageRow, child?: ChannelRow, reply?: MessageRow): Msg {
+ return presentCanonicalMessage(projectedCanonicalMessage(message, child), reply?.channelId === message.channelId ? reply : undefined)
}
let communityDbContext: Context<CommunityDbRegistry | null> | null = null
@@ -345,14 +345,14 @@ export function useRouteChannelProjection(channelId: string | null) {
function useJoinedMessageQuery(channelId: string | null | undefined, ids?: readonly string[]) {
const registry = useOptionalCommunityDbRegistry()
const result = useLiveQuery(communityJoinedMessagesQuery(registry, channelId, ids))
- return { registry, data: result.data as Array<{ message: MessageRow; child?: ChannelRow }> | undefined, status: result.status }
+ return { registry, data: result.data as Array<{ message: MessageRow; child?: ChannelRow; reply?: MessageRow }> | undefined, status: result.status }
}
export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<string, Msg> | undefined {
const { registry, data } = useJoinedMessageQuery(undefined, ids)
return useMemo(() => !registry ? undefined : new Map(
- (data ?? []).map(({ message, child }) => {
- return [message.id, projectedMessage(message, child)]
+ (data ?? []).map(({ message, child, reply }) => {
+ return [message.id, projectedMessage(message, child, reply)]
}),
), [registry, data])
}
@@ -363,7 +363,8 @@ export function useMessageWindowProjection(channelId: string | null, ids: readon
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])
- return { canonicalMessages, windowIds: ids, status }
+ const relatedMessages = useMemo(() => data?.flatMap(({ message, reply }) => reply?.channelId === message.channelId ? [reply] : []) ?? [], [data])
+ return { canonicalMessages, relatedMessages, windowIds: ids, status }
}
function useCollectionById<N extends "channels" | "servers">(name: N) {
diff --git a/src/web/src/lib/community-db/queries.ts b/src/web/src/lib/community-db/queries.ts
index c0f59c0e0..5bd21177a 100644
--- a/src/web/src/lib/community-db/queries.ts
+++ b/src/web/src/lib/community-db/queries.ts
@@ -17,6 +17,7 @@ export function communityJoinedMessagesQuery(registry: CommunityDbRegistry | nul
? q.from({ message: registry.collections.messages }).where(({ message }) => channelId === undefined ? eq(1, 1) : eq(message.channelId, channelId))
.where(({ message }) => ids === undefined ? eq(1, 1) : inArray(message.id, [...ids]))
.leftJoin({ child: registry.collections.channels }, ({ message, child }) => eq(message.id, child.parentMessageId))
- .select(({ message, child }) => ({ message, child }))
+ .leftJoin({ reply: registry.collections.messages }, ({ message, reply }) => eq(message.replyToId, reply.id))
+ .select(({ message, child, reply }) => ({ message, child, reply }))
: undefined }
}
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index d0096a23d..b5ce63e5e 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -73,8 +73,8 @@ const pendingApproval = { friendshipId: "friendship", status: "pending" as const
const registries: CommunityDbRegistry[] = []
const unregisters: Array<() => void> = []
-async function registry(preload = true) {
- const result = createCommunityDbRegistry(new QueryClient(), "viewer")
+async function registry(preload = true, accountId = "viewer") {
+ const result = createCommunityDbRegistry(new QueryClient(), accountId)
registries.push(result)
if (preload) await result.preload()
unregisters.push(registerCommunityDbRegistry(result))
@@ -273,7 +273,7 @@ describe("community DB sync", () => {
it("keeps confirmed reply identity on incomplete same-message input and accepts explicit deletion", async () => {
const db = await registry()
- const replyTo = { id: "reply", authorId: "peer", authorName: "Peer", text: "confirmed" }
+ const replyTo = { id: "reply", authorId: "peer", authorName: "Peer" }
const row = { id: "posted", channelId: "c1", type: "chat" as const, authorId: "viewer", clientNonce: "nonce", seq: 1, replyTo, replyToId: replyTo.id }
ingestMessages(db, "c1", messageSeedFixture("c1", [row]))
ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...row, replyTo: undefined }]))
@@ -286,8 +286,8 @@ describe("community DB sync", () => {
authorAvatar: null, authorAvatarVersion: 0, createdAt: "2026-10-08T00:00:00Z", content: "posted", clientNonce: row.clientNonce, replyToId: row.replyToId, embeds: [] }), row.clientNonce, "c1")
ingestMessages(db, "c1", messageSeedFixture("c1", [posted]))
expect(db.collections.messages.get(row.id)?.replyTo).toEqual(replyTo)
- ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...row, replyTo: { id: replyTo.id, authorName: "Deleted user", text: "", deleted: true } }]))
- expect(db.collections.messages.get(row.id)?.replyTo).toMatchObject({ deleted: true, text: "" })
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...row, replyTo: { id: replyTo.id, authorName: "Deleted user", deleted: true } }]))
+ expect(db.collections.messages.get(row.id)?.replyTo).toMatchObject({ deleted: true })
ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...incomplete, replyToId: null }]))
expect(db.collections.messages.get(row.id)?.replyTo).toBeUndefined()
expect(db.collections.messages.get(row.id)?.replyToId).toBeNull()
@@ -296,7 +296,7 @@ describe("community DB sync", () => {
it.each(["author", "nonce", "channel"])("does not retain a confirmed quote for a different %s owner", async (field) => {
const db = await registry()
const identity = { id: "owned-reply", channelId: "c1", type: "chat" as const, authorId: "viewer", clientNonce: "nonce", seq: 1 }
- ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...identity, replyTo: { id: "target", authorId: "peer", authorName: "Peer", text: "private" }, replyToId: "target" }]))
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...identity, replyTo: { id: "target", authorId: "peer", authorName: "Peer", }, replyToId: "target" }]))
ingestMessages(db, field === "channel" ? "c2" : "c1", messageSeedFixture(field === "channel" ? "c2" : "c1", [{ ...identity,
...(field === "author" ? { authorId: "other" } : field === "nonce" ? { clientNonce: "other" } : { channelId: "c2" }) }]))
expect(db.collections.messages.get(identity.id)?.replyTo).toBeUndefined()
@@ -305,7 +305,7 @@ describe("community DB sync", () => {
it("rejects a weak preview instead of mutating full canonical message facts", 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", authorId: "peer", 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 }] } })
+ 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", authorId: "peer", authorName: "Peer", }, 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", messageSeedFixture("c1", [full]))
const preview = { id: "raw", seq: 1, type: "chat", authorId: "peer", createdAt: "now", content: "preview" }
expect(() => ingestMessages(db, "c1", [preview])).toThrow()
@@ -586,6 +586,28 @@ describe("community DB sync", () => {
expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer" })
})
+ it.each(["alice", "bob"])("derives shared reply target reaction selection for each receiving account when %s reacted", async reactorId => {
+ const alice = await registry(true, "alice"), bob = await registry(true, "bob")
+ const target = messageResourceFixture({ id: "older-target", channelId: "c1", authorId: "alice", seq: 1, content: "Older target",
+ reactions: [{ emoji: "👍", count: 1, me: reactorId === "alice", userIds: [reactorId] }] })
+ const reply = messageResourceFixture({ id: "new-reply", channelId: "c1", authorId: "alice", authorName: "Alice", authorAvatarVersion: 0, seq: 2, content: "Reply",
+ replyToId: target.id, replyTo: { id: target.id, authorId: "alice", authorName: "Alice" } })
+ const profiles = messageProfilesFixture([target, reply])
+ await publishCommunityMessages(bob.queryClient, { channelId: "c1", messages: [{ ...target, reactions: [{ ...target.reactions![0], me: reactorId === "bob" }] }], profiles,
+ proof: { token: captureCommunityLiveSnapshotToken(bob.queryClient, "c1") } })
+ expect(bob.collections.messages.get(target.id)?.reactions?.[0].me).toBe(reactorId === "bob")
+ const delivery = { type: "community:message.create" as const, channelId: "c1", message: reply, relatedMessages: [target], profiles }
+ const parsed = validateCommunityWsEvent(delivery, BUSINESS_SCHEMA_VERSION)
+ if (!parsed.ok) throw new Error("Expected a valid shared reply event")
+ for (const receiver of [alice, bob]) projectCommunityWsEventToDb(receiver.queryClient, parsed.event)
+ for (const receiver of [alice, bob]) {
+ expect(receiver.collections.messages.get(target.id)?.reactions).toEqual([{ emoji: "👍", count: 1, me: receiver.accountId === reactorId, userIds: [reactorId] }])
+ expect(receiver.collections.messages.get(reply.id)?.replyToId).toBe(target.id)
+ }
+ expect(delivery.relatedMessages[0].reactions).toEqual([{ emoji: "👍", count: 1, me: reactorId === "alice", userIds: [reactorId] }])
+ expect(parsed.event).toEqual(delivery)
+ })
+
it("preserves a same-entity WS message reaction over an older HTTP response", async () => {
const db = await registry()
const staleMessage = {
@@ -2269,7 +2291,7 @@ describe("community DB sync", () => {
if (warm) writeCommunityProfilePatches([{ id: profile.id, identityAbout: { name: "Previously Known", discriminator: "0042", aboutMe: "Retained bio" },
avatar: { avatar: "previous.png", avatarVersion: 5 } }], db)
const message = messageResourceFixture({ id: "m1", channelId: "c1", authorId: profile.id, authorName: "Historical Author", authorAvatar: "hint.png", authorAvatarVersion: hintVersion,
- replyToId: "earlier", replyTo: { id: "earlier", authorId: profile.id, authorName: "Historical Reply", text: "Earlier" } })
+ replyToId: "earlier", replyTo: { id: "earlier", authorId: profile.id, authorName: "Historical Reply", } })
const proof = { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") }
if (surface === "bundle") {
const resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1" })], [message], [profile])
@@ -2295,7 +2317,7 @@ describe("community DB sync", () => {
avatar: { avatar: "rich.png", avatarVersion: 2 }, status: { statusEmoji: "Shipping", statusText: "Shipping" } }], db)
const rich = messageResourceFixture({ id: "m1", channelId: "c1", authorId: "u2", authorName: "Alice", content: "rich", replyToId: "m0",
attachments: [{ id: "proof", name: "proof.png", url: "/proof.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: null, width: null, height: null }],
- replyTo: { id: "m0", authorId: "u3", authorName: "Bob", text: "earlier" } })
+ replyTo: { id: "m0", authorId: "u3", authorName: "Bob", } })
ingestMessages(db, "c1", [rich])
const profile = { id: "u2", name: "Alice Updated", discriminator: "0002", avatar: "base.png", avatarVersion: 2 }
const resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1" })], [{ ...rich, content: "new preview" }], [profile, profileResourceFixture({ id: "u3", name: "Bob" })])
@@ -2677,7 +2699,7 @@ describe("community DB sync", () => {
ingestMessages(db, "c1", messageSeedFixture("c1", [{
id: "m1", type: "chat", authorId: "author", authorName: "Author", content: "rich",
createdAt: "2026-09-25T00:00:00.000Z",
- replyTo: { id: "reply", authorId: "reply-author", authorName: "Reply", text: "reply" },
+ replyTo: { id: "reply", authorId: "reply-author", authorName: "Reply", },
thread: {
id: "thread1", name: "Thread", messageCount: 1,
participants: [{ id: "participant", name: "Participant", avatar: "P", avatarVersion: 1 }],
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index a02ff1c67..db5afa4e4 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -963,7 +963,10 @@ export function ingestMessages(
function ingestMessageResources(registry: CommunityDbRegistry, resources: readonly CommunityMessageResource[], profiles: readonly CommunityResourceProfile[]) {
const fullProfiles = new Map(profiles.map(profile => [profile.id, profile]))
- const rows = [...resources]
+ const viewerId = registry.accountId
+ const rows = resources.map(resource => resource.reactions ? { ...resource,
+ reactions: resource.reactions.map(reaction => ({ ...reaction, me: viewerId !== null && reaction.userIds.includes(viewerId) })),
+ } : resource)
upsertRows(registry, "messages", rows)
afterCanonicalWrites(registry, () => {
const threads = new Map<string, CommunityCollectionRows["channels"]>()
@@ -975,7 +978,7 @@ function ingestMessageResources(registry: CommunityDbRegistry, resources: readon
name: thread.name, messageCount: thread.messageCount,
...(thread.lastReplyAt === undefined ? {} : { lastMessageAt: thread.lastReplyAt }),
...(thread.tags === undefined ? {} : { tags: thread.tags }),
- ...(thread.preview === undefined ? {} : { preview: thread.preview }),
+ ...(thread.firstMessageId === undefined ? {} : { firstMessageId: thread.firstMessageId }),
...(thread.participantCount === undefined ? {} : { participantCount: thread.participantCount }),
}))
}
@@ -1772,12 +1775,13 @@ export function publishCommunityMessages(
publication: {
channelId: string
messages: MessageInput[]
+ relatedMessages?: readonly CommunityMessageResource[]
profiles: readonly CommunityResourceProfile[]
proof: CommunityFreshQueryProof
},
) {
return withCommunityQueryProof(queryClient, publication.proof, (registry) => {
- const graph = validateCommunityMessagePublication(registry, publication.messages, publication.profiles)
+ const graph = validateCommunityMessagePublication(registry, [...publication.messages, ...(publication.relatedMessages ?? [])], publication.profiles)
if (graph.messages.some(message => message.channelId !== publication.channelId)) throw new Error("Message channel mismatch")
notifyManager.batch(() => {
ingestResourceProfiles(registry, graph.profiles, publication.proof)
@@ -2059,7 +2063,7 @@ export function publishCommunityForumFeed(queryClient: QueryClient, forumChannel
...thread, type: "thread", serverId: page.channel.serverId, parentChannelId: forumChannelId,
pending: false,
tags: page.included.tags.filter((tag) => tag.messageId === thread.parentMessageId).map((tag) => tag.tag),
- preview: first?.content ?? "",
+
firstMessageId: page.channel.type === "forum" ? first?.id || null : null,
participantCount: page.included.participantCounts.find((row) => row.channelId === thread.id)?.count ?? 0,
}, registry.collections.channels.get(thread.id))
@@ -2500,7 +2504,7 @@ export function projectCommunityWsEventToDb(
}
case "community:message.create": {
const projected = projectCommunityMessageCreate(event.message, event.channelId, contract)
- const graph = validateCommunityMessagePublication(registry, [projected], event.profiles)
+ const graph = validateCommunityMessagePublication(registry, [projected, ...(event.relatedMessages ?? [])], event.profiles)
notifyManager.batch(() => {
writeCanonicalProfilePatches(registry, graph.profiles.map(profile => communityUserProfilePatch(profile.id, profile)), true)
ingestMessages(registry, event.channelId, graph.messages, graph.profiles)
diff --git a/src/web/src/lib/community-image-thumbnail.ts b/src/web/src/lib/community-image-thumbnail.ts
index 5355b2315..9721862aa 100644
--- a/src/web/src/lib/community-image-thumbnail.ts
+++ b/src/web/src/lib/community-image-thumbnail.ts
@@ -1,4 +1,4 @@
-import { MAX_ATTACHMENT_THUMBNAIL_EDGE_PX, MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared"
+import { MAX_ATTACHMENT_THUMBNAIL_EDGE_PX, MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared/constants/community"
const QUALITIES = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
diff --git a/src/web/src/lib/community-image.worker.ts b/src/web/src/lib/community-image.worker.ts
index 43cd21b42..b6eb35552 100644
--- a/src/web/src/lib/community-image.worker.ts
+++ b/src/web/src/lib/community-image.worker.ts
@@ -1,4 +1,4 @@
-import { MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared"
+import { MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES } from "@alook/shared/constants/community"
import { renderCommunityThumbnail, requiresCommunityThumbnail, type CommunityImageWorkerResult } from "./community-image-thumbnail"
self.addEventListener("message", async (event: MessageEvent<File>) => {
diff --git a/src/web/src/lib/community/attention-resources.server.ts b/src/web/src/lib/community/attention-resources.server.ts
index 22858a031..cf968f38e 100644
--- a/src/web/src/lib/community/attention-resources.server.ts
+++ b/src/web/src/lib/community/attention-resources.server.ts
@@ -36,8 +36,9 @@ export async function readCommunityResourceBundle(db: Database, viewerId: string
])
if (input.messageIds?.some(id => !messageRows.some(row => row.id === id))) throw new Error("Requested message resource missing from scope")
const context = await loadApiMessageContext(db, viewerId, messageRows.map(row => row.id), () =>
- queries.communityMessage.getMessagesByIdsInChannels(db, messageRows.flatMap(row => row.replyToId ? [row.replyToId] : []), allowedIds), true)
+ queries.communityMessage.getMessagesByIdsInChannels(db, messageRows.flatMap(row => row.replyToId ? [row.replyToId] : []), allowedIds), { skipEmpty: true, rootMessages: messageRows })
const messages = messageRows.map(row => mapMessageForApi(row, context(row.channelId), COMMUNITY_RESOURCE_CONTRACT_VERSION, row.channelId))
+ messages.push(...[...new Map(messageRows.flatMap(row => context(row.channelId).relatedMessages ?? []).map(message => [message.id, message])).values()])
const profiles = await readCommunityResourceProfiles(db, [viewerId, ...(input.profileIds ?? []), ...communityMessageProfileIds(messages)])
const serverIds = new Set([...(input.serverIds ?? []), ...channels.flatMap(row => row.serverId ? [row.serverId] : [])])
const selectedServers = serverRows.flatMap((row, position) => serverIds.has(row.id) ? [{ row, position }] : [])
diff --git a/src/web/src/lib/community/chat-markdown.ts b/src/web/src/lib/community/chat-markdown.ts
index aef3600a8..df4fe073b 100644
--- a/src/web/src/lib/community/chat-markdown.ts
+++ b/src/web/src/lib/community/chat-markdown.ts
@@ -1,53 +1 @@
-import { unified, type PluggableList } from "unified"
-import remarkParse from "remark-parse"
-import remarkGfm from "remark-gfm"
-import remarkBreaks from "remark-breaks"
-import type { Root } from "mdast"
-import { formatHandle, type MentionCandidate, type MentionType } from "@alook/shared"
-import { cjk } from "@streamdown/cjk"
-import remarkMath from "remark-math"
-import { chatSyntaxPlugin, type MentionNode } from "./chat-syntax-plugin"
-
-export const CHAT_REMARK_PLUGINS: PluggableList = [remarkGfm, chatSyntaxPlugin, remarkBreaks]
-
-const processor = unified()
- .use(remarkParse)
- .use(cjk.remarkPluginsBefore)
- .use(CHAT_REMARK_PLUGINS)
- .use(cjk.remarkPluginsAfter)
- .use(remarkMath, { singleDollarTextMath: true })
- .freeze()
-
-function parsedMentions(content: string): MentionNode[] {
- if (!content.includes("@")) return []
- const tree = processor.runSync(processor.parse(content)) as Root
- const mentions: MentionNode[] = []
- function visit(node: { type: string; children?: unknown[] }): void {
- if (node.type === "mention") mentions.push(node as MentionNode)
- if (node.children) {
- for (const child of node.children) visit(child as Parameters<typeof visit>[0])
- }
- }
- visit(tree)
- return mentions
-}
-
-export function detectChatMentionType(content: string): MentionType | undefined {
- return parsedMentions(content).some((node) => node.everyone) ? "everyone" : undefined
-}
-
-export function extractChatMentionedUserIds(content: string, candidates: MentionCandidate[]): string[] {
- const byHandle = new Map<string, string>()
- for (const candidate of candidates) {
- if (!candidate.name || !candidate.discriminator) continue
- const handle = `@${formatHandle(candidate.name, candidate.discriminator)}`.toLowerCase()
- if (!byHandle.has(handle)) byHandle.set(handle, candidate.userId)
- }
- const found = new Set<string>()
- for (const node of parsedMentions(content)) {
- if (node.everyone || !node.discriminator) continue
- const userId = byHandle.get(`${node.value}#${node.discriminator}`.toLowerCase())
- if (userId) found.add(userId)
- }
- return [...found]
-}
+export { CHAT_REMARK_PLUGINS, detectChatMentionType, extractChatMentionedUserIds } from "@alook/shared/chat-markdown"
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index 40348e54c..ac6e0b738 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -1,426 +1,9 @@
-import type { Root, PhrasingContent, Text } from "mdast"
-import { findAndReplace } from "mdast-util-find-and-replace"
-import type { CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle } from "mdast-util-from-markdown"
import type { Handler, Handlers } from "mdast-util-to-hast"
import type { Element } from "hast"
-import { codes } from "micromark-util-symbol"
-import type { Construct, Effects, Extension, State, TokenizeContext } from "micromark-util-types"
-import type { Plugin } from "unified"
-import { MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary, isMentionEndBoundary } from "@alook/shared"
-import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"
-import type { SpoilerNode } from "./spoiler-syntax"
-
-// Chat-only syntax (`||spoiler||`, `@mention`, `/server#disc/channel` and bare
-// `/server#disc` refs), parsed as real markdown AST nodes rather than
-// string-spliced HTML tags fed through `rehype-raw`. `channelRef`/`serverRef`
-// content is a nanoid charset (`[A-Za-z0-9_-]`); a member `mention` is
-// `@<name>#dddd` where the name may contain spaces, Unicode, and Markdown/HTML
-// metacharacters. Member handles are recognized by a micromark text tokenizer
-// before Markdown can split them into sibling nodes; the later find/replace
-// pass remains as a compatibility path for ordinary text-only handles and
-// handles @everyone/refs. `spoiler` uses its own micromark tokenizer extension
-// in `spoiler-syntax.ts`.
-
-// Matches a `/server#disc/channel`, `/server#disc/channel/#N` (thread), or
-// `/server#disc/channel/#N#M` thread-reply ref — the CLI's path grammar
-// (`parseRef`/`formatRef` in `community-cli-contract.ts`). Segment charset
-// `[^\s/#.,;:!?)\]]+` = "any char slugify can emit, minus the terminator
-// punctuation": server names travel with their required discriminator and
-// channel names remain wire names rather than ids. Name segments preserve
-// Unicode; normalization strips only `/` and `#` and collapses whitespace. So
-// the base of the class is the inverse of what slugify removes (everything
-// except whitespace, `/`, `#`), which is what lets non-ASCII names
-// (`/Gus#0042/架构`, `/总部-🎉#0042/general`, `/studio#0042/café`) render as pills like their
-// ASCII kin — matching the `\p{L}` + `u` treatment `MENTION_RE` already uses
-// for `@names`. We ALSO exclude the trailing-boundary punctuation (`REF_TERM`
-// below) from the segment class: the old ASCII class `[A-Za-z0-9_-]` happened
-// to be disjoint from the terminator set, and that disjointness is
-// load-bearing — the segment class `[^\s/#…]+` is GREEDY, so without excluding
-// a terminator char from the segment it gets eaten BEFORE the lookahead can
-// fire (a greedy segment swallows the sentence period in `/studio#0042/general.`;
-// same for the full-width `。` in `看 /Gus#0042/架构。`). So a terminator must live
-// in BOTH places: excluded from the segment (so the match stops there) AND
-// present in the lookahead (so stopping there is legal). slugify never emits a
-// leading/trailing terminator anyway, and a mid-name terminator is a rare
-// corner that degrading to plain text is acceptable for; keeping the boundary
-// correct for ALL refs matters more.
-//
-// `REF_TERM` is the single source of truth for the terminator set — used BOTH
-// as the segment-class exclusion (`REF_SEG`) and the trailing lookahead, so
-// the two can't drift out of the disjointness the boundary relies on. It
-// covers ASCII sentence/closing punctuation and the common Unicode variants
-// used by CJK prose and smart quotes. A Chinese sentence ends in `。`, so
-// `看 /Gus#0042/架构。` must
-// yield pill `/Gus#0042/架构` + literal `。`, not swallow the period — full-width
-// terminators matter MORE here since this fix targets CJK names (Blair's QA
-// flag). Kept as a string spliced into `new RegExp(...)` so the shared set is
-// declared once.
-//
-// Trailing `(?=\s|$|[REF_TERM])` boundary lookahead: a 2-segment path followed
-// by ANOTHER `/segment` (e.g. `/api/user/123` in a docs URL) must NOT match —
-// otherwise this regex would greedily take `/api/user` and orphan `/123` as
-// trailing text next to a broken pill. The leading guard permits a
-// discriminator-bearing ref after prose or an opening bracket, e.g.
-// `see(/Gus#5994/架构/#722#17)` and `text/Gus#5994/架构`, while preventing the
-// regex engine from restarting after an earlier slash in the same unbroken
-// path or URL (`/api/Gus#5994/架构`, `https://Gus#5994/架构`). Ref terminators
-// stop that backward scan so a second adjacent ref after punctuation still
-// matches. The trailing boundary
-// remains load-bearing so the match still ends at the exact ref. `u` flag for
-// correct astral/emoji handling.
-const REF_TERM = ".,;:!?)\\]}\"'\\u2014\\u2019\\u201D\\u2026\\u3001\\u3002\\u3009\\u300B\\u300D\\u300F\\u3011\\u3015\\u3017\\u3019\\u301B\\uFF01\\uFF02\\uFF07\\uFF09\\uFF0C\\uFF0E\\uFF1A\\uFF1B\\uFF1F\\uFF3D\\uFF5D"
-const REF_SEG = `[^\\s/#${REF_TERM}]+`
-const HANDLE_SEG = `${REF_SEG}#\\d{4,}`
-// `/server#disc/channel` plus an optional message/thread suffix. The suffix has two
-// branches (message-ref-upgrade.md):
-// `#\d+` — a channel-MESSAGE ref, seq glued straight to the channel
-// (`/server#disc/channel#N`). Single seq ONLY — `#N#M` without a
-// slash is not a valid form (Cecilia #295, load-bearing).
-// `/#\d+(?:#\d+)?` — a THREAD (`/server#disc/channel/#N`) or thread-message
-// (`/server#disc/channel/#N#M`) ref; the inner `#M` lives only
-// on this slash branch.
-// `REF_SEG` excludes `#`, so the 2nd segment stops at the `#` and the seq falls
-// cleanly into the suffix group. The discriminator-bearing full path — never a
-// bare `#` — is what lets us drop the old bare-`#N` MESSAGE_REF pass and
-// root-solve the disambiguation Gus flagged.
-const CHANNEL_REF_RE = new RegExp(`(?<!/[^\\s${REF_TERM}]*)(?:/${HANDLE_SEG}/${REF_SEG}|/\\.dm/${HANDLE_SEG})(?:#\\d+|/#\\d+(?:#\\d+)?)?(?=\\s|$|[${REF_TERM}])`, "gu")
-
-// A bare `/server` ref — one segment, no channel. Unlike `CHANNEL_REF_RE`, this
-// intentionally keeps its leading `(?<=^|\s)` boundary; the current change is
-// scoped to channel/message refs. Its trailing `REF_TERM` boundary excludes
-// being followed by another `/segment` — so this never double-matches
-// the first segment of a genuine `/server#disc/channel` ref (that trailing boundary
-// fails when the next char is `/`, and the segment class backtracking can't
-// produce a shorter match that satisfies it either, since every character up
-// to the next `/` is in the segment charset). Same `REF_SEG`/`REF_TERM` +
-// `u` flag as `CHANNEL_REF_RE` above (Unicode server names, full-width
-// terminators). Registered after `CHANNEL_REF_RE` in `chatSyntaxPlugin`'s
-// pairs list purely for readability (server-only is the "smaller" grammar);
-// the boundary already makes the ordering non-load-bearing for correctness.
-const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}])`, "gu")
-
-// (The old bare-`#N` MESSAGE_REF_RE was removed in message-ref-upgrade.md — a
-// message ref is now always the full path `/server#disc/channel#N`, matched by
-// CHANNEL_REF_RE's suffix group above. A bare `#N` now renders as plain text.
-// This kills the fragile "works only because it's the last consumption pass"
-// disambiguation: the prefix-anchored full-path form can't collide with a bare
-// `#`, so no ordering hazard with mentions/spoilers/other `#` syntax.)
-
-// Two-branch mention grammar:
-//
-// 1. The literal `@everyone` token, with a trailing `(?![\p{L}\p{N}_-])`
-// boundary guard so `@everyoneee` is NOT matched as `@everyone` — this MUST
-// agree with `detectMentionType`'s boundary check (mention-extension.ts)
-// and `community-mentions.ts`'s `ID_CHAR_RE`. `@here` was removed as a
-// broadcast trigger; a literal `@here`
-// now falls through as ordinary text, matching option b: no legacy
-// rendering for historical `@here`.)
-//
-// 2. A member mention `@<name>#dddd` where the trailing `#dddd` is REQUIRED
-// and acts as an unambiguous terminator. Because member names are validated
-// to never contain `#`, `@`, or line breaks (validateCommunityName), the
-// name-run may safely include spaces/unicode: `[^@#\n\r]*[^@#\n\r\s]`. The
-// final class forces the name-run to END in a non-whitespace char, so
-// ordinary prose like `@bob check issue #0042` is NOT swallowed into one
-// pill (the only `#` there is space-preceded). The tag is `#dddd` with 4+
-// digits (variable-width disc); the digit run is greedy so a widened 5+-digit
-// tag matches in full. A hand-typed bare `@Alice` (no tag) is intentionally
-// NOT a mention — it stays text.
-const MENTION_RE = new RegExp(
- String.raw`(?<!/|${MENTION_IDENTIFIER_CHARACTERS})(?:@everyone(?!${MENTION_IDENTIFIER_CHARACTERS})|@[^@#\n\r]*[^@#\n\r\s]#\d{4,}(?!${MENTION_IDENTIFIER_CHARACTERS}))`,
- "gu",
-)
-
-/** mdast node produced by `@name`/`@name#0042`/`@everyone`. */
-export interface MentionNode {
- type: "mention"
- /** Display name — `#dddd` discriminator, if present, is stripped from here (matches the old `<mention>` tag's content). */
- value: string
- everyone: boolean
- /** The discriminator (4+ decimal digits), if the mention carried one (never set for `@everyone`). */
- discriminator?: string
-}
-
-/** mdast node produced by a `/server#disc/channel` or `/server#disc/channel/#N` ref. */
-export interface ChannelRefNode {
- type: "channelRef"
- value: string
-}
-
-/** mdast node produced by a bare `/server` ref (no channel segment). */
-export interface ServerRefNode {
- type: "serverRef"
- value: string
-}
-
-declare module "mdast" {
- interface RootContentMap {
- chatLiteral: ChatLiteralNode
- mention: MentionNode
- channelRef: ChannelRefNode
- serverRef: ServerRefNode
- }
- interface PhrasingContentMap {
- chatLiteral: ChatLiteralNode
- mention: MentionNode
- channelRef: ChannelRefNode
- serverRef: ServerRefNode
- }
-}
-
-declare module "micromark-util-types" {
- interface TokenTypeMap {
- memberMention: "memberMention"
- memberMentionBoundary: "memberMentionBoundary"
- }
-}
-
-function memberMentionSyntax(): Extension {
- const construct: Construct = {
- name: "memberMention",
- previous(code) {
- if (code === codes.slash) return false
- if (code === null || code < 0) return true
- let previous = String.fromCodePoint(code)
- if (code >= 0xDC00 && code <= 0xDFFF) {
- const tail = this.events.at(-1)?.[1]
- if (tail) previous = this.sliceSerialize({ start: tail.start, end: this.now() })
- }
- return isMentionStartBoundary(previous)
- },
- tokenize: tokenizeMemberMention,
- }
- return { text: { [codes.atSign]: construct } }
-}
-
-function tokenizeMemberMention(this: TokenizeContext, effects: Effects, ok: State, nok: State): State {
- let nameSize = 0
- let previousWasWhitespace = false
- let discriminatorSize = 0
-
- return start
-
- function start(code: Parameters<State>[0]): State | undefined {
- effects.enter("memberMention")
- effects.consume(code)
- return name
- }
-
- function name(code: Parameters<State>[0]): State | undefined {
- if (
- code === codes.eof ||
- code === codes.atSign ||
- code === codes.carriageReturn ||
- code === codes.lineFeed ||
- code === codes.carriageReturnLineFeed
- ) {
- return nok(code)
- }
- if (code === codes.numberSign) {
- if (nameSize === 0 || previousWasWhitespace) return nok(code)
- effects.consume(code)
- return discriminator
- }
- effects.consume(code)
- nameSize++
- previousWasWhitespace = code === codes.space || code === codes.horizontalTab || code === codes.virtualSpace
- return name
- }
-
- function discriminator(code: Parameters<State>[0]): State | undefined {
- if (code !== null && code >= codes.digit0 && code <= codes.digit9) {
- effects.consume(code)
- discriminatorSize++
- return discriminator
- }
- if (discriminatorSize < 4) return nok(code)
- return effects.check(memberMentionEndBoundary, finish, nok)(code)
- }
-
- function finish(code: Parameters<State>[0]): State | undefined {
- effects.exit("memberMention")
- return ok(code)
- }
-}
-
-const memberMentionEndBoundary: Construct = {
- tokenize(effects, ok, nok) {
- let high = ""
- return start
-
- function start(code: Parameters<State>[0]): State | undefined {
- if (code === null || code < 0) return ok(code)
- if (code >= 0xD800 && code <= 0xDBFF) {
- high = String.fromCharCode(code)
- effects.enter("memberMentionBoundary")
- effects.consume(code)
- return afterHigh
- }
- return isMentionEndBoundary(String.fromCodePoint(code)) ? ok(code) : nok(code)
- }
-
- function afterHigh(code: Parameters<State>[0]): State | undefined {
- effects.exit("memberMentionBoundary")
- const suffix = code !== null && code >= 0xDC00 && code <= 0xDFFF
- ? high + String.fromCharCode(code)
- : high
- return isMentionEndBoundary(suffix) ? ok(code) : nok(code)
- }
- },
-}
-
-interface ChatLiteralNode extends Omit<Text, "type"> {
- type: "chatLiteral"
-}
-
-function literalFromMarkdown(): FromMarkdownExtension {
- return {
- enter: {
- characterEscape: enterLiteral,
- characterReference: enterLiteral,
- },
- exit: {
- characterEscapeValue: appendEscapeValue,
- characterEscape: exitLiteral,
- characterReference: exitLiteral,
- },
- }
-}
-
-const enterLiteral: FromMarkdownHandle = function (token) {
- this.enter({ type: "chatLiteral", value: "" }, token)
-}
-
-const appendEscapeValue: FromMarkdownHandle = function (token) {
- const node = this.stack.at(-1) as ChatLiteralNode
- node.value += this.sliceSerialize(token)
-}
-
-const exitLiteral: FromMarkdownHandle = function (token) {
- this.exit(token)
-}
-
-function restoreLiteralNodes(node: TraversableSyntaxNode): void {
- if (!node.children) return
- for (const child of node.children) {
- if (child.type === "chatLiteral") child.type = "text"
- restoreLiteralNodes(child)
- }
-}
-
-function memberMentionFromMarkdown(): FromMarkdownExtension {
- return {
- enter: { memberMention: enterMemberMention },
- exit: { memberMention: exitMemberMention },
- }
-}
-
-const enterMemberMention: FromMarkdownHandle = function (this: CompileContext, token) {
- const serialized = this.sliceSerialize(token)
- const tagStart = serialized.lastIndexOf("#")
- this.enter({
- type: "mention",
- value: serialized.slice(0, tagStart),
- everyone: false,
- discriminator: serialized.slice(tagStart + 1),
- }, token)
-}
-
-const exitMemberMention: FromMarkdownHandle = function (this: CompileContext, token) {
- this.exit(token)
-}
-
-type TraversableSyntaxNode = {
- type: string
- children?: TraversableSyntaxNode[]
- value?: string
- discriminator?: string
- everyone?: boolean
-}
-
-function restoreProtectedMemberMentions(
- node: TraversableSyntaxNode,
- protectedAncestor = false,
-): void {
- if (!node.children) return
- const childrenAreProtected = protectedAncestor || IGNORE_NODE_TYPES.includes(node.type)
- node.children = node.children.map((child) => {
- if (
- childrenAreProtected
- && child.type === "mention"
- && !child.everyone
- && child.value
- && child.discriminator
- ) {
- return {
- type: "text",
- value: `${child.value}#${child.discriminator}`,
- }
- }
- restoreProtectedMemberMentions(child, childrenAreProtected)
- return child
- })
-}
-
-// `ignore` list mirrors mdast-util-find-and-replace's own default protection
-// for GFM autolinks/definitions, plus `code`/`inlineCode` so `@fake-mention`,
-// `#0042`, `/server#disc/channel`, and `||spoiler||` all stay literal inside a
-// code span or fenced code block — replacing the old `preprocessMarkdown`'s
-// manual stash/unstash sentinel dance, which existed only because that
-// implementation operated on a raw string before markdown parsing.
-const IGNORE_NODE_TYPES = ["code", "inlineCode", "link", "linkReference"]
-
-function mentionReplacer(value: string): MentionNode {
- const everyone = value === "@everyone"
- if (everyone) return { type: "mention", value, everyone: true }
- const tag = /#(\d{4,})$/.exec(value)
- const bare = value.replace(/#\d{4,}$/, "")
- return tag ? { type: "mention", value: bare, everyone: false, discriminator: tag[1] } : { type: "mention", value: bare, everyone: false }
-}
-
-function channelRefReplacer(value: string): ChannelRefNode {
- return { type: "channelRef", value }
-}
-
-function serverRefReplacer(value: string): ServerRefNode {
- return { type: "serverRef", value }
-}
-
-/**
- * remark plugin: combines the spoiler micromark extension (`spoiler-syntax.ts`)
- * with a `mdast-util-find-and-replace` pass for `mention`/`channelRef`.
- * Registers `spoilerSyntax`'s micromark/from-markdown extensions on the
- * processor (the `remark-gfm`-style `this.data(...)` convention) and returns
- * a tree transform running the find-and-replace pass after parsing.
- */
-export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this: import("unified").Processor) {
- type ProcessorData = { micromarkExtensions?: unknown[]; fromMarkdownExtensions?: unknown[] }
- const settings = this.data() as ProcessorData
- const micromarkExtensions = (settings.micromarkExtensions ??= [])
- const fromMarkdownExtensions = (settings.fromMarkdownExtensions ??= [])
- micromarkExtensions.push(memberMentionSyntax())
- fromMarkdownExtensions.push(memberMentionFromMarkdown(), literalFromMarkdown())
- micromarkExtensions.push(spoilerSyntax())
- fromMarkdownExtensions.push(spoilerFromMarkdown())
-
- return function transform(tree: Root): void {
- restoreProtectedMemberMentions(tree as TraversableSyntaxNode)
- findAndReplace(
- tree,
- [
- [MENTION_RE, mentionReplacer as unknown as (value: string, ...rest: unknown[]) => PhrasingContent | string | false],
- [CHANNEL_REF_RE, channelRefReplacer as unknown as (value: string) => PhrasingContent],
- // Runs as its own pass AFTER the channelRef pass above — by then every
- // `/server#disc/channel` span is already a `channelRef` element (no longer
- // a `text` node `findAndReplace` visits), so this pass only ever sees
- // genuine bare `/server` refs among the remaining text.
- [SERVER_REF_RE, serverRefReplacer as unknown as (value: string) => PhrasingContent],
- ],
- { ignore: IGNORE_NODE_TYPES },
- )
- restoreLiteralNodes(tree)
- }
-}
+import type { MentionNode, ChannelRefNode, ServerRefNode } from "@alook/shared/chat-syntax"
+import type { SpoilerNode } from "@alook/shared/spoiler-syntax"
+export { chatSyntaxPlugin } from "@alook/shared/chat-syntax"
+export type { MentionNode, ChannelRefNode, ServerRefNode } from "@alook/shared/chat-syntax"
// `remarkRehypeOptions.handlers` — converts each custom mdast node directly
// into a hast element, skipping the HTML-string round-trip entirely. Tag
diff --git a/src/web/src/lib/community/conversation-entry.server.ts b/src/web/src/lib/community/conversation-entry.server.ts
index 0c76f29ef..f7d658399 100644
--- a/src/web/src/lib/community/conversation-entry.server.ts
+++ b/src/web/src/lib/community/conversation-entry.server.ts
@@ -1,5 +1,5 @@
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
-import { COMMUNITY_CONVERSATION_ANCHOR_MISSING, communityChannelResourceFromStorage, CommunityConversationEntryReadSchema, CommunityThreadsReadSchema, CommunityMessageResourceSchema, queries, withD1Retry, type CommunityConversationEntryRead, type Database } from "@alook/shared"
+import { COMMUNITY_CONVERSATION_ANCHOR_MISSING, communityChannelResourceFromStorage, CommunityConversationEntryReadSchema, CommunityThreadsReadSchema, queries, withD1Retry, type CommunityConversationEntryRead, type Database } from "@alook/shared"
import { createCommunityResourceProfileReader, type CommunityResourceProfileReader } from "./resource-profiles.server"
import { readCommunityMessageWindow } from "./message-window.server"
import { communityMessagesReadFromPage } from "./read-contract"
@@ -37,11 +37,11 @@ export async function readCommunityConversationEntry(db: Database, input: Conver
channel.parentChannelId ? readParent(db, viewerId, channel.parentChannelId) : Promise.resolve(undefined),
])
if (!read.ok) return read
- const openerProfiles = opener ? await readCommunityMessageProfiles(db, [opener], readProfiles) : []
+ const openerProfiles = opener ? await readCommunityMessageProfiles(db, [opener.message, ...opener.relatedMessages], readProfiles) : []
const profiles = [...new Map([...read.page.profiles, ...openerProfiles].map(profile => [profile.id, profile])).values()]
return { ok: true, entry: CommunityConversationEntryReadSchema.parse({
...communityMessagesReadFromPage(channelId, read.page), profiles, viewerId, channel, peer,
- ...(opener ? { opener } : {}),
+ ...(opener ? { opener: opener.message, relatedMessages: [...new Map([...(read.page.relatedMessages ?? []), ...opener.relatedMessages].filter(message => !read.page.messages.some(root => (root as { id: string }).id === message.id) && message.id !== opener.message.id).map(message => [message.id, message])).values()] } : {}),
...(parent ? { parent } : {}),
readState: read.readState, readStateRevision: read.revision, selection: read.selection,
...("forumFeed" in read ? { forumFeed: read.forumFeed } : {}),
@@ -63,7 +63,7 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
const page = await readCommunityForumRows(db, channelId, { tag, pageSize: window.pageSize, includes: new Set(["parentMessage", "firstMessage", "tags", "participants"]) })
const forumFeed = CommunityThreadsReadSchema.parse(await readCommunityThreadsResource(db, viewerId, target.access.channel, page.threads,
{ messages: [...page.parentMessages, ...page.firstMessages], tags: page.tags, participants: page.participants }, { hasMore: page.hasMore, nextCursor: page.nextCursor ?? null }, COMMUNITY_RESOURCE_CONTRACT_VERSION))
- return { ok: true as const, page: { messages: [], profiles: [], latestSeq: readState.lastReadSeq, hasMoreOlder: false, hasMoreNewer: false, surfaceReceipt: { channelId, surfaceKind: "forum" as const } },
+ return { ok: true as const, page: { messages: [], relatedMessages: [], profiles: [], latestSeq: readState.lastReadSeq, hasMoreOlder: false, hasMoreNewer: false, surfaceReceipt: { channelId, surfaceKind: "forum" as const } },
readState, revision, selection: { reason: "tail" as const, anchorMessageId: null }, forumFeed }
}
const anchorId = window.anchorId ?? (preferTail ? undefined : readState.lastReadMessageId ?? undefined)
@@ -91,7 +91,7 @@ async function readPeer(db: Database, peerId: string, readProfiles: CommunityRes
async function readOpener(db: Database, viewerId: string, channelId: string, messageId: string) {
const [message] = await withD1Retry(() => queries.communityMessage.getMessagesByIdsInScope(db, [messageId], { channelId }), { route: "community/messages:entry-opener" })
- return message ? CommunityMessageResourceSchema.parse(await readCommunityMessageResource(db, viewerId, message, COMMUNITY_RESOURCE_CONTRACT_VERSION)) : undefined
+ return message ? readCommunityMessageResource(db, viewerId, message, COMMUNITY_RESOURCE_CONTRACT_VERSION) : undefined
}
async function readParent(db: Database, viewerId: string, channelId: string) {
diff --git a/src/web/src/lib/community/conversation-entry.test.ts b/src/web/src/lib/community/conversation-entry.test.ts
index cc84239e0..be639e0a1 100644
--- a/src/web/src/lib/community/conversation-entry.test.ts
+++ b/src/web/src/lib/community/conversation-entry.test.ts
@@ -442,7 +442,7 @@ it.each(["main", "opener"] as const)("validates the effective retained %s reply
const { client, registry } = await createCommunityQueryOwner()
const value = entry()
const original = { ...value.messages[0], ...(location === "opener" ? { id: "opener", channelId: "parent" } : {}) }
- const retainedReply = { id: "prior", authorId: "prior-author", authorName: "Prior author", text: "Retained reply" }
+ const retainedReply = { id: "prior", authorId: "prior-author", authorName: "Prior author" }
ingestMessages(registry, original.channelId, [{ ...original, replyToId: "prior", replyTo: retainedReply }])
const incoming = { ...original, replyToId: "prior" }
if (location === "main") value.messages = [incoming]
diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.ts
index 4e027207d..f90e2ce4f 100644
--- a/src/web/src/lib/community/conversation-entry.ts
+++ b/src/web/src/lib/community/conversation-entry.ts
@@ -103,7 +103,7 @@ export function publishConversationEntry(
const registry = proof.token.registry!
const parent = channel.parentChannelId
if (parent && (registry.runtime.ws.get().channelAccessScopes.get(parent)?.generation ?? 0) !== (proof.token.channelScopes.get(parent)?.generation ?? 0)) throw new DOMException("Retired conversation parent", "AbortError")
- validateCommunityMessagePublication(registry, entry.messages, entry.profiles)
+ validateCommunityMessagePublication(registry, [...entry.messages, ...(entry.relatedMessages ?? [])], entry.profiles)
if (entry.opener) validateCommunityMessagePublication(registry, [entry.opener], entry.profiles)
if (entry.forumFeed) validateCommunityMessagePublication(registry, entry.forumFeed.included.messages, entry.forumFeed.included.profiles)
const initialWindow: InitialMessageWindow = entry.selection.anchorMessageId ? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }
@@ -118,9 +118,9 @@ export function publishConversationEntry(
if (entry.peer) publishCommunityChannelMembersSnapshot(client, null, channel.id, "access", [entry.viewerId, entry.peer.id].map((userId) => ({
channelId: channel.id, userId, relation: "access", source: "added", isCreator: channel.creatorId === userId, role: null, memberId: null,
})), proof, [entry.peer])
- publishCommunityMessages(client, { channelId: channel.id, messages: entry.messages, profiles: entry.profiles, proof })
+ publishCommunityMessages(client, { channelId: channel.id, messages: entry.messages, relatedMessages: entry.relatedMessages?.filter(message => message.channelId === channel.id), profiles: entry.profiles, proof })
if (entry.opener) {
- publishCommunityMessages(client, { channelId: entry.opener.channelId, messages: [entry.opener], profiles: entry.profiles, proof })
+ publishCommunityMessages(client, { channelId: entry.opener.channelId, messages: [entry.opener], relatedMessages: entry.relatedMessages?.filter(message => message.channelId === entry.opener!.channelId), profiles: entry.profiles, proof })
afterCommunityCollectionWrites(registry, () => { client.setQueryData(communityKeys.message(entry.opener!.id), entry.opener!.id) })
}
publishCommunityConversationReadState(client, entry.readState, entry.readStateRevision, proof)
@@ -135,7 +135,7 @@ export function publishConversationEntry(
else {
afterCommunityCollectionWrites(registry, () => {
if (conversationDisplayWindows(client, target, { channelId: channel.id, proof: qualified, windowKey })?.some(window => hashKey(window.key) === hashKey(windowKey))) return
- const page = messageWindowPage({ ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, profiles: entry.profiles })
+ const page = messageWindowPage({ ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, relatedMessages: entry.relatedMessages?.filter(message => message.channelId === channel.id), profiles: entry.profiles })
client.setQueryData<MessageWindowData>(windowKey, { pages: [page], pageParams: [initialWindow as MessagesPageParam] })
})
}
@@ -278,7 +278,7 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
void reconcileConversationLanding(client, {
kind: target.serverId === null ? "dm" : "channel", scopeId: target.channelId,
serverId: target.serverId ?? undefined,
- }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, profiles: entry.profiles }, initial,
+ }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, relatedMessages: entry.relatedMessages?.filter(message => message.channelId === entry.channelId), profiles: entry.profiles }, initial,
{ query: original!, signal, lifetime: "query", observation: captured }).catch(() => undefined)
}
record("delivered")
diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.ts
index 2ae75e3dd..9169a3f82 100644
--- a/src/web/src/lib/community/desktop-system-notification.ts
+++ b/src/web/src/lib/community/desktop-system-notification.ts
@@ -87,7 +87,11 @@ export function buildDesktopSystemNotificationCandidate(
conversationKind: create.serverId ? conversation?.conversationKind ?? "channel" : "dm",
authorName: create.message.authorName,
content: create.message.content,
- attachmentContentTypes: create.message.attachments?.map((attachment) => attachment.contentType) ?? [],
+ attachments: create.message.attachments,
+ approval: create.message.approval,
+ botCreation: create.message.botCreation,
+ systemKind: create.message.systemKind,
+ embeds: create.message.embeds,
serverName: conversation?.serverName,
channelName: conversation?.channelName,
parentChannelName: conversation?.parentChannelName,
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
index 1b6a20c9e..e64d6b18b 100644
--- a/src/web/src/lib/community/enrich-messages.test.ts
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -78,7 +78,7 @@ describe("enrichMessages attachment projection", () => {
it("skips empty DM attachment, reaction, reply and approval hydration while reading latest sequence", async () => {
const db = {} as never
- expect(await enrichMessages(db, "u1", { channelId: "dm1", isDm: true }, [])).toEqual({ messages: [], profiles: [], latestSeq: 9 })
+ expect(await enrichMessages(db, "u1", { channelId: "dm1", isDm: true }, [])).toEqual({ messages: [], relatedMessages: [], profiles: [], latestSeq: 9 })
expect(mocks.listAttachments).not.toHaveBeenCalled()
expect(mocks.listReactions).not.toHaveBeenCalled()
expect(mocks.getReplies).not.toHaveBeenCalled()
@@ -112,7 +112,7 @@ describe("enrichMessages attachment projection", () => {
})
it("projects a canonical thumbnail beside reply enrichment", async () => {
- mocks.listAttachments.mockResolvedValue([{
+ mocks.listAttachments.mockResolvedValueOnce([{
id: "att_1",
messageId: "m1",
targetId: "c1",
@@ -124,8 +124,9 @@ describe("enrichMessages attachment projection", () => {
width: 640,
height: 480,
}])
+ mocks.listAttachments.mockResolvedValueOnce([])
mocks.getReplies.mockResolvedValue([{
- id: "reply_1",
+ id: "reply_1", seq: 1, createdAt: "2026-08-12T00:00:00.000Z", replyToId: null, clientNonce: null, type: "default", mentionType: null, embeds: null, authorAvatarVersion: 0,
authorId: "bob",
authorName: "Bob",
content: "original",
@@ -154,7 +155,7 @@ describe("enrichMessages attachment projection", () => {
expect(result.messages).toEqual([
expect.objectContaining({
- replyTo: { id: "reply_1", authorId: "bob", authorName: "Bob", text: "original" },
+ replyTo: { id: "reply_1", authorId: "bob", authorName: "Bob" },
attachments: [{
id: "att_1",
name: "photo.png",
@@ -182,7 +183,7 @@ describe("enrichMessages attachment projection", () => {
createdAt: "2026-08-13T00:00:00.000Z",
}])
mocks.getFirstMessages.mockResolvedValue([{
- channelId: "thread-1",
+ id: "body-1", channelId: "thread-1",
content: preview,
}])
mocks.listParticipants.mockResolvedValue([{
@@ -218,7 +219,7 @@ describe("enrichMessages attachment projection", () => {
expect(result.messages[0]).toMatchObject({
thread: {
id: "thread-1",
- preview,
+ firstMessageId: "body-1",
participants: [{
id: "u2",
avatar: "/api/community/users/u2/avatar?v=4",
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index 6abc93b6e..5e5d9daf1 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -24,7 +24,7 @@ export async function enrichMessages(
scope: MessageScope,
items: Array<Parameters<typeof mapMessageForApi>[0] & { channelId: string }>,
readProfiles?: CommunityResourceProfileReader,
-): Promise<{ messages: CommunityMessageResource[]; profiles: CommunityResourceProfile[]; latestSeq: number }> {
+): Promise<{ messages: CommunityMessageResource[]; profiles: CommunityResourceProfile[]; relatedMessages: CommunityMessageResource[]; latestSeq: number }> {
const isDm = scope.isDm === true
const messageIds = items.map((m) => m.id)
const creationMessageIds = items.filter((message) => message.type === "bot_creation_request").map((message) => message.id)
@@ -36,7 +36,7 @@ export async function enrichMessages(
() => queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId: scope.channelId }),
{ route: "community/messages:reply-enrichment" },
)
- : Promise.resolve([]), true),
+ : Promise.resolve([]), { skipEmpty: true }),
// Thread indicators only exist for non-DM channel-scoped messages.
!isDm
? scope.isForum
@@ -99,7 +99,7 @@ export async function enrichMessages(
lastReplyAt: c.lastMessageAt,
...(scope.isForum ? {
tags: tagsByMessage.get(c.parentMessageId!) ?? [],
- preview: first?.content ?? "",
+ firstMessageId: first?.id ?? null,
participants: participantsByChannel.get(c.id) ?? [],
participantCount: participantCountByChannel.get(c.id) ?? 0,
} : {}),
@@ -115,5 +115,5 @@ export async function enrichMessages(
approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,
}, scope.contract, scope.channelId),
)
- return { messages, profiles: await readCommunityMessageProfiles(db, messages, readProfiles), latestSeq }
+ return { messages, relatedMessages: context.relatedMessages ?? [], profiles: await readCommunityMessageProfiles(db, [...messages, ...(context.relatedMessages ?? [])], readProfiles), latestSeq }
}
diff --git a/src/web/src/lib/community/html-preview-markdown.ts b/src/web/src/lib/community/html-preview-markdown.ts
index 8dc203b57..45cee14d3 100644
--- a/src/web/src/lib/community/html-preview-markdown.ts
+++ b/src/web/src/lib/community/html-preview-markdown.ts
@@ -1,78 +1,13 @@
-import { unified, type Plugin } from "unified"
-import remarkParse from "remark-parse"
-import type { Root, RootContent, Paragraph, Link } from "mdast"
+import type { Plugin } from "unified"
+import type { Root } from "mdast"
+import { replaceHtmlPreviewMarkers, selectHtmlPreviews as select } from "@alook/shared/html-preview"
import type { Attachment, FileAttachment } from "./models/message"
-import { CHAT_REMARK_PLUGINS } from "./chat-markdown"
-
-import { isHtmlPreviewFile, MAX_HTML_PREVIEW_BYTES } from "./html-preview-policy"
-
-interface HtmlPreviewNode {
- type: "htmlPreview"
- data: { hName: "htmlpreview"; hProperties: { dataAttachmentId: string } }
-}
-
-declare module "mdast" {
- interface RootContentMap { htmlPreview: HtmlPreviewNode }
-}
type Options = { text: string; attachments?: readonly Attachment[] }
-const parser = unified().use(remarkParse).use(CHAT_REMARK_PLUGINS).freeze()
-
-function replaceMarkers(tree: Root, { text, attachments }: Options): Map<string, FileAttachment> {
- const files = new Map((attachments ?? []).flatMap((attachment) => attachment.kind === "file" && attachment.id
- && isHtmlPreviewFile(attachment.name, attachment.contentType)
- && (attachment.sizeBytes === undefined || attachment.sizeBytes <= MAX_HTML_PREVIEW_BYTES)
- ? [[attachment.id, attachment] as const] : []))
- const selected = new Map<string, FileAttachment>()
- if (!files.size || !text.includes("[alook-html-preview]")) return selected
-
- function attachmentFor(node: Paragraph["children"][number]): FileAttachment | undefined {
- if (node.type !== "link") return
- const link: Link = node
- const start = link.position?.start.offset, end = link.position?.end.offset
- if (start === undefined || end === undefined || link.title
- || link.children.length !== 1 || link.children[0]?.type !== "text" || link.children[0].value !== "alook-html-preview"
- || text.slice(start, end) !== `[alook-html-preview](${link.url})`
- || (start > 0 && !/\s/.test(text[start - 1]!))
- || (end < text.length && !/\s/.test(text[end]!))) return
- return files.get(link.url)
- }
-
- function walk(parent: { children: RootContent[] }) {
- parent.children = parent.children.flatMap((node): RootContent[] => {
- if (node.type === "blockquote" || node.type === "listItem" || node.type === "list") {
- walk(node)
- return [node]
- }
- if (node.type !== "paragraph") return [node]
- const blocks: RootContent[] = []
- let children: Paragraph["children"] = []
- function flush() {
- if (children.some((child) => child.type !== "text" || child.value.trim())) blocks.push({ type: "paragraph", children })
- children = []
- }
- for (const child of node.children) {
- const attachment = attachmentFor(child)
- if (!attachment?.id) { children.push(child); continue }
- flush()
- if (!selected.has(attachment.id)) {
- selected.set(attachment.id, attachment)
- blocks.push({ type: "htmlPreview", data: { hName: "htmlpreview", hProperties: { dataAttachmentId: attachment.id } } })
- }
- }
- if (!blocks.length && children.length === node.children.length) return [node]
- flush()
- return blocks
- })
- }
- walk(tree)
- return selected
-}
-
+const files = (attachments?: readonly Attachment[]): FileAttachment[] => (attachments ?? []).filter((file): file is FileAttachment => file.kind === "file")
export function selectHtmlPreviews(text: string, attachments?: readonly Attachment[]): Map<string, FileAttachment> {
- if (!attachments?.some((attachment) => attachment.id) || !text.includes("[alook-html-preview]")) return new Map()
- const tree = parser.runSync(parser.parse(text)) as Root
- return replaceMarkers(tree, { text, attachments })
+ return select(text, files(attachments))
+}
+export const htmlPreviewPlugin: Plugin<[Options], Root> = (options) => (tree) => {
+ replaceHtmlPreviewMarkers(tree, { text: options.text, attachments: files(options.attachments) })
}
-
-export const htmlPreviewPlugin: Plugin<[Options], Root> = (options) => (tree) => { replaceMarkers(tree, options) }
diff --git a/src/web/src/lib/community/html-preview-policy.ts b/src/web/src/lib/community/html-preview-policy.ts
index 34f3055da..e534362ca 100644
--- a/src/web/src/lib/community/html-preview-policy.ts
+++ b/src/web/src/lib/community/html-preview-policy.ts
@@ -1,12 +1,7 @@
-export const MAX_HTML_PREVIEW_BYTES = 2 * 1024 * 1024
+export { MAX_HTML_PREVIEW_BYTES, isHtmlPreviewFile } from "@alook/shared/html-preview"
export const HTML_PREVIEW_SANDBOX = "allow-scripts allow-forms allow-popups allow-downloads"
export const HTML_PREVIEW_THEME_VARIABLES = [
"background", "foreground", "card", "card-foreground", "popover", "popover-foreground",
"primary", "primary-foreground", "secondary", "secondary-foreground", "muted", "muted-foreground",
"accent", "accent-foreground", "border", "input", "ring", "destructive", "warning", "radius", "font-sans", "font-mono",
] as const
-
-export function isHtmlPreviewFile(name: string, contentType?: string | null): boolean {
- const type = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
- return type === "text/html" || (["", "application/octet-stream", "binary/octet-stream"].includes(type) && /\.html?$/i.test(name))
-}
diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.ts
index 770cf3a08..78fcf6e35 100644
--- a/src/web/src/lib/community/message-dispatcher.test.ts
+++ b/src/web/src/lib/community/message-dispatcher.test.ts
@@ -6,11 +6,13 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockGetMessage = vi.fn()
-const mockGetWakeContextMessageInScope = vi.fn()
+const mockGetMessagesByIdsInScope = vi.fn()
const mockGetMessageClientNonceForDelivery = vi.fn()
const mockGetChannel = vi.fn()
const mockListAttention = vi.fn()
const mockListAttachments = vi.fn()
+const mockRelatedAttachments = vi.fn()
+const mockRelatedReactions = vi.fn()
const mockResolveRecipients = vi.fn()
const mockResolveNotificationRecipients = vi.fn()
const mockResolveEligibility = vi.fn()
@@ -34,8 +36,8 @@ vi.mock("@alook/shared", async () => {
communityUserProfile: { getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 })) },
communityMessage: {
getMessage: (...args: unknown[]) => mockGetMessage(...args),
- getWakeContextMessageInScope: (...args: unknown[]) =>
- mockGetWakeContextMessageInScope(...args),
+ getMessagesByIdsInScope: (...args: unknown[]) =>
+ mockGetMessagesByIdsInScope(...args),
getMessageClientNonceForDelivery: (...args: unknown[]) =>
mockGetMessageClientNonceForDelivery(...args),
},
@@ -45,7 +47,9 @@ vi.mock("@alook/shared", async () => {
communityMention: {
listMessageAttentionTargets: (...args: unknown[]) => mockListAttention(...args),
},
+ communityReaction: { listReactionsByMessageIds: (...args: unknown[]) => mockRelatedReactions(...args) },
communityAttachment: {
+ listByMessageIds: (...args: unknown[]) => mockRelatedAttachments(...args),
listMessageAttachments: (...args: unknown[]) => mockListAttachments(...args),
},
communityMembersResolver: {
@@ -109,7 +113,7 @@ function messageContextRow(overrides: Partial<{
channelId: string
}> = {}) {
return {
- id: "context_1",
+ ...message, id: "context_1", friendshipId: null,
authorId: "human_1",
authorName: "Private Human Name",
authorDiscriminator: "1234",
@@ -161,10 +165,12 @@ describe("planCommittedMessage", () => {
vi.clearAllMocks()
mockGetMessage.mockResolvedValue(message)
mockHydrateCreation.mockResolvedValue(new Map())
- mockGetWakeContextMessageInScope.mockResolvedValue(null)
+ mockGetMessagesByIdsInScope.mockResolvedValue([])
mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")
mockGetChannel.mockResolvedValue(channel)
mockListAttachments.mockResolvedValue([])
+ mockRelatedAttachments.mockResolvedValue([])
+ mockRelatedReactions.mockResolvedValue([])
mockListAttention.mockResolvedValue([
{ userId: "u_mentions", kind: "mention" },
{ userId: "u_mention_only", kind: "mention" },
@@ -275,11 +281,11 @@ describe("planCommittedMessage", () => {
it("rehydrates attachment dimensions and reply preview from committed rows", async () => {
mockGetMessage.mockResolvedValue({ ...message, replyToId: "reply_1" })
- mockGetWakeContextMessageInScope.mockResolvedValue(messageContextRow({
+ mockGetMessagesByIdsInScope.mockResolvedValue([messageContextRow({
id: "reply_1",
authorName: "Earlier",
content: "previous message",
- }))
+ })])
mockListAttachments.mockResolvedValue([{
id: "att_1",
messageId: "msg_1",
@@ -296,7 +302,6 @@ describe("planCommittedMessage", () => {
expect(plan.messageEvent.message.replyTo).toMatchObject({
id: "reply_1",
authorName: "Earlier",
- text: "previous message",
})
expect(plan.messageEvent.message.attachments).toEqual([
expect.objectContaining({
@@ -316,14 +321,14 @@ describe("planCommittedMessage", () => {
mentionType: "everyone",
replyToId: "reply_1",
})
- mockGetWakeContextMessageInScope.mockResolvedValue(messageContextRow({
+ mockGetMessagesByIdsInScope.mockResolvedValue([messageContextRow({
id: "reply_1",
authorId: "bot_1",
authorName: "Bot",
authorDiscriminator: "0001",
authorIsBot: true,
content: "previous message",
- }))
+ })])
mockListAttention.mockResolvedValue([{ userId: "bot_1", kind: "mention" }])
mockListAttachments.mockResolvedValue([{
id: "att_1",
@@ -352,7 +357,6 @@ describe("planCommittedMessage", () => {
expect(plan.messageEvent.message.replyTo).toMatchObject({
id: "reply_1",
authorName: "Bot",
- text: "previous message",
})
})
@@ -573,9 +577,11 @@ describe("dispatchCommittedMessage", () => {
vi.clearAllMocks()
mockGetMessage.mockResolvedValue(message)
mockGetChannel.mockResolvedValue(channel)
- mockGetWakeContextMessageInScope.mockResolvedValue(null)
+ mockGetMessagesByIdsInScope.mockResolvedValue([])
mockGetMessageClientNonceForDelivery.mockResolvedValue("nonce_1")
mockListAttachments.mockResolvedValue([])
+ mockRelatedAttachments.mockResolvedValue([])
+ mockRelatedReactions.mockResolvedValue([])
mockListAttention.mockResolvedValue([])
mockResolveRecipients.mockResolvedValue(["author_1"])
mockResolveNotificationRecipients.mockImplementation(
diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.ts
index ec1cfe3bc..acd22b361 100644
--- a/src/web/src/lib/community/message-dispatcher.ts
+++ b/src/web/src/lib/community/message-dispatcher.ts
@@ -14,7 +14,7 @@ import {
type CommunityContract,
type AlookQueueTask,
} from "@alook/shared"
-import { mapMessageForWs, readCommunityMessageProfiles, type MessageRow } from "./message-payload"
+import { mapMessageForWs, loadApiMessageContext, readCommunityMessageProfiles } from "./message-payload"
import { sendMessageDeliveryBatch } from "./message-delivery-transport"
import { enqueueQueueTasks } from "./queue-producer"
@@ -116,11 +116,7 @@ export async function planCommittedMessage(
),
message.replyToId
? withD1Retry(
- () => queries.communityMessage.getWakeContextMessageInScope(
- db,
- message.replyToId!,
- { channelId: message.channelId },
- ),
+ () => queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId!], { channelId: message.channelId }).then(rows => rows[0] ?? null),
{ route: "message-dispatcher:reply" },
)
: Promise.resolve(null),
@@ -173,15 +169,8 @@ export async function planCommittedMessage(
...mentionUserIds,
])
- const replyMap = new Map<string, Pick<MessageRow, "id" | "authorId" | "authorName" | "content">>()
- if (replyTarget) {
- replyMap.set(replyTarget.id, {
- id: replyTarget.id,
- authorId: replyTarget.authorId,
- authorName: replyTarget.authorName,
- content: replyTarget.content,
- })
- }
+ const relatedContext = (await loadApiMessageContext(db, message.authorId, [], () => Promise.resolve(replyTarget ? [replyTarget] : []), { skipEmpty: true }))(message.channelId)
+ const replyMap = relatedContext.replyMap
const creationRequest = channel.type === "dm" && message.type === "bot_creation_request"
? (await queries.communityBotCreation.hydrateCreationRequestsForDmMessages(db, [message.id], message.authorId)).get(message.id)
: undefined
@@ -190,6 +179,7 @@ export async function planCommittedMessage(
channelId: message.channelId,
...(channel.serverId ? { serverId: channel.serverId } : {}),
...(channel.parentChannelId ? { parentChannelId: channel.parentChannelId } : {}),
+ relatedMessages: relatedContext.relatedMessages,
message: mapMessageForWs(message, {
replyMap,
botCreation: creationRequest,
@@ -197,7 +187,7 @@ export async function planCommittedMessage(
resourceAttachments: groupAttachments(attachments)[message.id] ?? [],
}, contract, message.channelId),
}
- const profiles = await readCommunityMessageProfiles(db, [messageInput.message])
+ const profiles = await readCommunityMessageProfiles(db, [messageInput.message, ...(relatedContext.relatedMessages ?? [])])
const messageResult = validateCommunityWsEvent({ ...messageInput, profiles }, contract)
if (!messageResult.ok || messageResult.event.type !== WS_EVENTS.MESSAGE_CREATE) throw new Error("Invalid committed message event")
const messageEvent = messageResult.event
diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.ts
index c64a51ff7..d82566e0f 100644
--- a/src/web/src/lib/community/message-payload.test.ts
+++ b/src/web/src/lib/community/message-payload.test.ts
@@ -1,9 +1,9 @@
import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { beforeEach, describe, it, expect, vi } from "vitest"
-const creationMocks = vi.hoisted(() => ({ hydrate: vi.fn(), attachments: vi.fn(), reactions: vi.fn() }))
+const creationMocks = vi.hoisted(() => ({ hydrate: vi.fn(), approvals: vi.fn(), attachments: vi.fn(), reactions: vi.fn() }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
- return { ...actual, queries: { ...actual.queries, communityBotCreation: { hydrateCreationRequestsForDmMessages: creationMocks.hydrate }, communityAttachment: { listByMessageIds: creationMocks.attachments }, communityReaction: { listReactionsByMessageIds: creationMocks.reactions } } }
+ return { ...actual, queries: { ...actual.queries, communityFriendship: { ...actual.queries.communityFriendship, hydrateApprovalsForDmMessages: creationMocks.approvals }, communityBotCreation: { hydrateCreationRequestsForDmMessages: creationMocks.hydrate }, communityAttachment: { listByMessageIds: creationMocks.attachments }, communityReaction: { listReactionsByMessageIds: creationMocks.reactions } } }
})
import { botCreationFixture } from "@/test/bot-creation-fixtures"
import { readCommunityMessageResource, mapMessageForApi, mapMessageForWs, type MessageRow } from "./message-payload"
@@ -71,22 +71,21 @@ describe("mapMessageForApi", () => {
it("resolves replyTo from an in-scope replyMap entry", () => {
const replyMap = new Map([["m0", { id: "m0", authorId: "bob", authorName: "Bob", content: "hey there" }]])
const out = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel")
- expect(out.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob", text: "hey there" })
+ expect(out.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob" })
})
it("emits { deleted: true } when replyToId is set but the target is missing (out-of-scope filtered upstream)", () => {
const out = mapMessageForApi({ ...baseRow, replyToId: "m-gone" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
- expect(out.replyTo).toEqual({ id: "m-gone", authorName: "Deleted user", text: "", deleted: true })
+ expect(out.replyTo).toEqual({ id: "m-gone", authorName: "Deleted user", deleted: true })
})
- it("gives API and WS projections the same ellipsized reply preview", () => {
+ it("gives API and WS the same relation without copying source text", () => {
const long = "x".repeat(500)
const replyMap = new Map([["m0", { id: "m0", authorId: "bob", authorName: "Bob", content: long }]])
const apiOut = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel")
const wsOut = mapMessageForWs({ ...baseRow, replyToId: "m0" }, { ...emptyWsCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel")
- const expected = `${"x".repeat(119)}…`
- expect(apiOut.replyTo?.text).toBe(expected)
- expect(wsOut.replyTo?.text).toBe(expected)
+ expect(apiOut.replyTo).toEqual(wsOut.replyTo)
+ expect(apiOut.replyTo).not.toHaveProperty("text")
})
it("omits attachments/reactions when there are none", () => {
@@ -161,7 +160,7 @@ describe("mapMessageForWs", () => {
{ ...baseRow, replyToId: "m0", mentionType: "everyone" },
{ ...emptyWsCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel"
)
- expect(out.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob", text: "hey there" })
+ expect(out.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob" })
expect(out.mentionType).toBe("everyone")
})
@@ -225,12 +224,21 @@ describe("single-message creation payload hydration", () => {
await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type, channelId: "dm" }, BUSINESS_SCHEMA_VERSION)
expect(creationMocks.hydrate).not.toHaveBeenCalled()
})
+ it("hydrates a root friendship card from its canonical relation rather than raw content", async () => {
+ const profile = { id: "peer", name: "Peer", discriminator: "0042", image: null, avatarVersion: 0 }
+ const approval = { friendshipId: "friendship", status: "pending" as const, waitingOn: "you" as const, otherProfile: profile, botProfile: { ...profile, id: "bot" } }
+ creationMocks.approvals.mockResolvedValue(new Map([[baseRow.id, approval]]))
+ const resource = await readCommunityMessageResource({} as never, "viewer", { ...baseRow, friendshipId: approval.friendshipId, channelId: "dm" }, BUSINESS_SCHEMA_VERSION)
+ expect(creationMocks.approvals).toHaveBeenCalledExactlyOnceWith({}, [baseRow.id], "viewer")
+ expect(resource.message.approval).toEqual(approval)
+ expect(resource.message.content).toBe(baseRow.content)
+ })
it("hydrates a creation card with the same immutable owner identity", async () => {
const payload = botCreationFixture()
creationMocks.hydrate.mockResolvedValue(new Map([[baseRow.id, payload]]))
const message = await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type: "bot_creation_request", channelId: "dm" }, BUSINESS_SCHEMA_VERSION)
expect(creationMocks.hydrate).toHaveBeenCalledExactlyOnceWith({}, [baseRow.id], "viewer")
- expect(message.botCreation).toEqual(payload)
- expect(message.botCreation).not.toHaveProperty("canDecide")
+ expect(message.message.botCreation).toEqual(payload)
+ expect(message.message.botCreation).not.toHaveProperty("canDecide")
})
})
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 91cf3db4b..2a38814b4 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -14,7 +14,7 @@
* embeds pass-through, and mentionType projection so adding/removing a
* field on the wire is one edit, not four.
*/
-import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, CommunityMessageResourcesSchema, communityMessageProfileIds, queries, truncateMessagePreview, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, CommunityMessageResourcesSchema, communityMessageProfileIds, queries, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment } from "@alook/shared"
import type { BotCreationPayload, FriendApprovalPayload } from "@alook/shared"
import { readCommunityResourceProfiles, type CommunityResourceProfileReader } from "./resource-profiles.server"
@@ -25,14 +25,15 @@ import { groupAttachments, groupReactions } from "./messages"
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 ReplyIdentity = Pick<MessageRow, "id" | "authorId" | "authorName">
+type ReplyTargetRow = Awaited<ReturnType<typeof queries.communityMessage.getMessagesByIdsInScope>>[number]
type UiReaction = NonNullable<CommunityMessageResource["reactions"]>[number]
type ReplyPreview = NonNullable<CommunityMessageResource["replyTo"]>
type ThreadPreview = NonNullable<CommunityMessageResource["thread"]>
/** Common fields shared by both API and WS variants — derived exactly once. */
-function coreFields(row: MessageRow, replyMap: Map<string, ReplyTargetRow>) {
+function coreFields(row: MessageRow, replyMap: ReadonlyMap<string, ReplyIdentity>) {
return {
...projectMessageWireType(row.type),
replyTo: resolveReply(row, replyMap),
@@ -61,21 +62,21 @@ function coreFields(row: MessageRow, replyMap: Map<string, ReplyTargetRow>) {
* upstream, or actually deleted), we return the `{ deleted: true }` sentinel
* so the client renders "reply to [deleted]" without leaking data.
*/
-function resolveReply(row: MessageRow, replyMap: Map<string, ReplyTargetRow>): ReplyPreview | undefined {
+function resolveReply(row: MessageRow, replyMap: ReadonlyMap<string, ReplyIdentity>): ReplyPreview | undefined {
if (!row.replyToId) return undefined
const target = replyMap.get(row.replyToId)
- if (!target) return { id: row.replyToId, authorName: "Deleted user", text: "", deleted: true }
+ if (!target) return { id: row.replyToId, authorName: "Deleted user", deleted: true }
return {
id: target.id,
authorId: target.authorId,
authorName: target.authorName,
- text: truncateMessagePreview(target.content ?? ""),
}
}
export type ApiMessageContext = {
viewerId: string
- replyMap: Map<string, ReplyTargetRow>
+ relatedMessages?: CommunityMessageResource[]
+ replyMap: ReadonlyMap<string, ReplyIdentity>
attachmentsByMessage: Record<string, CommunityMessageAttachment[] | undefined>
reactionsByMessage: Record<string, UiReaction[] | undefined>
/** Optional: only channel GET surfaces a thread child; DM/thread don't. */
@@ -85,23 +86,42 @@ export type ApiMessageContext = {
botCreationByMessageId?: Map<string, BotCreationPayload>
}
-export async function loadApiMessageContext(db: Database, userId: string, ids: string[], readReplies: () => ReturnType<typeof queries.communityMessage.getMessagesByIdsInChannels>, skipEmpty = false) {
- const [attachments, reactions, replies] = await Promise.all([
- skipEmpty && !ids.length ? Promise.resolve([]) : queries.communityAttachment.listByMessageIds(db, ids),
- skipEmpty && !ids.length ? Promise.resolve([]) : queries.communityReaction.listReactionsByMessageIds(db, ids, userId),
+type MessageContextOptions = { skipEmpty?: boolean; rootReactions?: boolean; rootMessages?: readonly Pick<MessageRow, "id" | "type" | "friendshipId">[] }
+
+export async function loadApiMessageContext(db: Database, userId: string, ids: string[], readReplies: () => ReturnType<typeof queries.communityMessage.getMessagesByIdsInChannels>, options: MessageContextOptions = {}) {
+ const [attachments, reactions, replyRows] = await Promise.all([
+ options.skipEmpty && !ids.length ? Promise.resolve([]) : queries.communityAttachment.listByMessageIds(db, ids),
+ options.rootReactions === false || options.skipEmpty && !ids.length ? Promise.resolve([]) : queries.communityReaction.listReactionsByMessageIds(db, ids, userId),
readReplies(),
])
- const attachmentsByMessage = groupAttachments(attachments), reactionsByMessage = groupReactions(reactions, userId)
- return (channelId: string): ApiMessageContext => ({ viewerId: userId, attachmentsByMessage, reactionsByMessage,
- replyMap: new Map(replies.filter((reply) => reply.channelId === channelId).map((reply) => [reply.id, reply])),
- })
+ const replies = [...new Map(replyRows.map(reply => [`${reply.channelId}:${reply.id}`, reply])).values()]
+ const related = replies.filter(reply => !ids.includes(reply.id))
+ const relatedIds = related.map(reply => reply.id)
+ const cardRows = [...new Map([...(options.rootMessages ?? []), ...related].map(row => [row.id, row])).values()]
+ const [replyAttachments, replyReactions, approvalByMessageId, botCreationByMessageId] = await Promise.all([
+ relatedIds.length ? queries.communityAttachment.listByMessageIds(db, relatedIds) : Promise.resolve([]),
+ relatedIds.length ? queries.communityReaction.listReactionsByMessageIds(db, relatedIds, userId) : Promise.resolve([]),
+ cardRows.some(row => row.friendshipId) ? queries.communityFriendship.hydrateApprovalsForDmMessages(db, cardRows.filter(row => row.friendshipId).map(row => row.id), userId) : Promise.resolve(new Map<string, FriendApprovalPayload>()),
+ cardRows.some(row => row.type === "bot_creation_request") ? queries.communityBotCreation.hydrateCreationRequestsForDmMessages(db, cardRows.filter(row => row.type === "bot_creation_request").map(row => row.id), userId) : Promise.resolve(new Map<string, BotCreationPayload>()),
+ ])
+ const attachmentsByMessage = groupAttachments([...attachments, ...replyAttachments]), reactionsByMessage = groupReactions([...reactions, ...replyReactions], userId)
+ return (channelId: string): ApiMessageContext => {
+ const replyMap = new Map(replies.filter(reply => reply.channelId === channelId).map(reply => [reply.id, reply]))
+ const context: ApiMessageContext = { viewerId: userId, attachmentsByMessage, reactionsByMessage, replyMap, approvalByMessageId, botCreationByMessageId }
+ context.relatedMessages = [...replyMap.values()].filter(reply => !ids.includes(reply.id)).map(reply => {
+ const resource = mapMessageForApi(reply, context, BUSINESS_SCHEMA_VERSION, channelId)
+ delete resource.replyTo
+ return resource
+ })
+ return context
+ }
}
-export async function readCommunityMessageResource(db: Database, userId: string, message: Parameters<typeof mapMessageForApi>[0] & { channelId: string }, contract: CommunityContract) {
+export async function readCommunityMessageResource(db: Database, userId: string, message: Parameters<typeof mapMessageForApi>[0] & { channelId: string }, contract: CommunityContract, options: MessageContextOptions = {}) {
const context = await loadApiMessageContext(db, userId, [message.id], () => message.replyToId
- ? queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId], { channelId: message.channelId }) : Promise.resolve([]))
- const botCreationByMessageId = message.type === "bot_creation_request" ? await queries.communityBotCreation.hydrateCreationRequestsForDmMessages(db, [message.id], userId) : new Map<string, BotCreationPayload>()
- return mapMessageForApi(message, { ...context(message.channelId), botCreationByMessageId }, contract, message.channelId)
+ ? queries.communityMessage.getMessagesByIdsInScope(db, [message.replyToId], { channelId: message.channelId }) : Promise.resolve([]), { ...options, rootMessages: [message] })
+ const ctx = context(message.channelId)
+ return { message: mapMessageForApi(message, ctx, contract, message.channelId), relatedMessages: ctx.relatedMessages ?? [] }
}
// Splits the DB's `type` column value into the wire's `{ type, systemKind }`
@@ -138,16 +158,11 @@ function mapMessageResource(row: MessageRow, ctx: Omit<ApiMessageContext, "viewe
export async function mapPostedMessageForApi(db: Database, channelId: string, row: MessageRow, contract: number = BUSINESS_SCHEMA_VERSION) {
if (contract !== BUSINESS_SCHEMA_VERSION) throw new Error("Posted message protocol mismatch")
- const [replies, attachments] = await Promise.all([
- row.replyToId ? queries.communityMessage.getMessagesByIdsInScope(db, [row.replyToId], { channelId }) : Promise.resolve([]),
- queries.communityAttachment.listByMessageIds(db, [row.id]),
- ])
- const replyMap = new Map(replies.filter(reply => reply.channelId === channelId).map(reply => [reply.id, reply]))
- return mapMessageForApi(row, { viewerId: row.authorId, replyMap, attachmentsByMessage: groupAttachments(attachments), reactionsByMessage: {} }, contract, channelId)
+ return readCommunityMessageResource(db, row.authorId, { ...row, channelId }, contract, { rootReactions: false })
}
export type WsMessageContext = {
- replyMap: Map<string, ReplyTargetRow>
+ replyMap: ReadonlyMap<string, ReplyIdentity>
resourceAttachments: CommunityMessageAttachment[]
clientNonce?: string
botCreation?: BotCreationPayload
diff --git a/src/web/src/lib/community/message-send.server.ts b/src/web/src/lib/community/message-send.server.ts
index 4e24cca4a..192065074 100644
--- a/src/web/src/lib/community/message-send.server.ts
+++ b/src/web/src/lib/community/message-send.server.ts
@@ -60,7 +60,7 @@ export async function handleHumanSend(
})
if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })
const response = humanMessageConfirmation(db, contract, target.channelId, {
- message: await mapPostedMessageForApi(db, target.channelId, { ...created.message, clientNonce }, contract),
+ ...await mapPostedMessageForApi(db, target.channelId, { ...created.message, clientNonce }, contract),
threadId: created.thread.id,
deduped: created.deduped,
}, created.deduped ? 200 : 201)
@@ -74,7 +74,7 @@ export async function handleHumanSend(
clientNonce,
})
if (replay) {
- return humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, { ...replay.row, clientNonce }, contract), deduped: true }, 200)
+ return humanMessageConfirmation(db, contract, target.channelId, { ...await mapPostedMessageForApi(db, target.channelId, { ...replay.row, clientNonce }, contract), deduped: true }, 200)
}
const result = await createCommunityMessage({
@@ -88,13 +88,13 @@ export async function handleHumanSend(
attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,
})
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
- const response = humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, { ...result.row, clientNonce }, contract), deduped: result.deduped }, 201)
+ const response = humanMessageConfirmation(db, contract, target.channelId, { ...await mapPostedMessageForApi(db, target.channelId, { ...result.row, clientNonce }, contract), deduped: result.deduped }, 201)
return response
}
-async function humanMessageConfirmation(db: ReturnType<typeof getDb>, contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): Promise<NextResponse> {
+async function humanMessageConfirmation(db: ReturnType<typeof getDb>, contract: CommunityContract, channelId: string, payload: { message: unknown; relatedMessages?: import("@alook/shared").CommunityMessageResource[]; deduped?: boolean; threadId?: string }, status: number): Promise<NextResponse> {
const message = CommunityMessagePostedSchema.shape.message.parse(payload.message)
- const profiles = await readCommunityMessageProfiles(db, [message])
+ const profiles = await readCommunityMessageProfiles(db, [message, ...(payload.relatedMessages ?? [])])
return NextResponse.json(CommunityMessagePostedSchema.parse({ contractVersion: contract, channelId, ...payload, profiles, deduped: payload.deduped === true }), {
status, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) },
})
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index 3bd958745..6d6351dfc 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -194,11 +194,11 @@ export function materializeMessageStream(
for (const id of overlay.liveIds) {
const message = canonical.get(id)
if (message) upsertMaterialized(byId, idByIdentity, {
- message: { ...presentCanonicalMessage(message), failed: false },
+ message: { ...presentCanonicalMessage(message, message.replyToId ? canonical.get(message.replyToId) : undefined), failed: false },
})
}
for (const message of baseMessages) {
- upsertMaterialized(byId, idByIdentity, { message: presentCanonicalMessage(message) })
+ upsertMaterialized(byId, idByIdentity, { message: presentCanonicalMessage(message, message.replyToId ? canonical.get(message.replyToId) : undefined) })
}
return [...byId.values()].sort(materializedOrder).map((entry) => entry.message)
diff --git a/src/web/src/lib/community/message-window.test.ts b/src/web/src/lib/community/message-window.test.ts
index 50c593365..1564aa898 100644
--- a/src/web/src/lib/community/message-window.test.ts
+++ b/src/web/src/lib/community/message-window.test.ts
@@ -60,4 +60,18 @@ describe("native message window identity", () => {
unsubscribe()
observer.destroy()
})
+
+ it("publishes full reply targets without inserting them into the selected window", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const target = messageResourceFixture({ id: "older", seq: 1, content: "**Full** `file_name.ts`", attachments: [{ id: "file", name: "photo.png", url: "/file", thumbnailUrl: null, contentType: "image/png", sizeBytes: 50, width: 1, height: 1 }] })
+ const reply = messageResourceFixture({ id: "reply", seq: 100, replyToId: target.id, replyTo: { id: target.id, authorId: target.authorId, authorName: "Viewer" } })
+ load.mockResolvedValueOnce({ profiles: [profileResourceFixture()], messages: [reply], relatedMessages: [target], latestSeq: 100, hasMoreOlder: true, hasMoreNewer: false })
+ const options = messageWindowOptions(client, "c1", { mode: "newest" })
+ await client.infiniteQuery({ ...options, select: undefined })
+ const data = client.getQueryData(options.queryKey)!
+ expect(data.pages[0].messages).toEqual([{ id: "reply", seq: 100 }])
+ expect(data.pages[0]).not.toHaveProperty("relatedMessages")
+ expect(registry.collections.messages.get("older")).toMatchObject({ content: target.content, attachments: target.attachments })
+ expect(load).toHaveBeenCalledOnce()
+ })
})
diff --git a/src/web/src/lib/community/message-window.ts b/src/web/src/lib/community/message-window.ts
index 2f9d7a173..22484d55b 100644
--- a/src/web/src/lib/community/message-window.ts
+++ b/src/web/src/lib/community/message-window.ts
@@ -89,6 +89,7 @@ export const channelMessagesQueryFn =
const result = await publishCommunityMessages(originalClient, {
channelId,
messages: page.messages,
+ relatedMessages: page.relatedMessages,
profiles: page.profiles,
proof: { token: publicationToken, signal },
})
diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.ts
index 964525365..31064ce0c 100644
--- a/src/web/src/lib/community/message-wire.test.ts
+++ b/src/web/src/lib/community/message-wire.test.ts
@@ -21,6 +21,15 @@ function wire(
}
describe("projectCommunityMessageCreate", () => {
+ it("derives a semantic reply from the current canonical target without copying raw text into the relation", () => {
+ const target = wire({ id: "target", content: "**Visible** ||hidden|| `file_name.ts`", attachments: [{ id: "a", name: "photo.png", url: "/a", thumbnailUrl: null, contentType: "image/png", sizeBytes: 5, width: 1, height: 1 }] })
+ const reply = wire({ replyToId: target.id, replyTo: { id: target.id, authorId: "u1", authorName: "Gus" } })
+ expect(presentCanonicalMessage(reply, target).replyTo?.text).toBe("Visible [Spoiler] file_name.ts Photo: photo.png")
+ expect(reply.replyTo).not.toHaveProperty("text")
+ expect(presentCanonicalMessage(reply).replyTo?.text).toBe("Loading message…")
+ expect(presentCanonicalMessage(reply, { ...target, channelId: "other" }).replyTo?.text).toBe("Loading message…")
+ expect(presentCanonicalMessage(reply, { ...target, content: "edited" }).replyTo?.text).toBe("edited Photo: photo.png")
+ })
it("presents full thread participants without altering stored facts", () => {
const thread = { id: "thread", name: null, messageCount: 2, lastReplyAt: null, participants: [
{ id: "unknown", name: "", avatar: null, avatarVersion: 0 },
@@ -46,7 +55,7 @@ describe("projectCommunityMessageCreate", () => {
expect(sparse).not.toHaveProperty("embeds")
})
it("preserves canonical identity and presentation fields", () => {
- const replyTo = { authorId: "peer", id: "m0", authorName: "A", text: "prior" }
+ const replyTo = { authorId: "peer", id: "m0", authorName: "A" }
const approval = {
friendshipId: "f1",
status: "pending" as const,
@@ -178,7 +187,7 @@ describe("projectPostedMessage", () => {
})
it.each([0, 46])("preserves all current POST rich facts at seq %s", (seq) => {
- const full = wire({ seq, clientNonce: "nonce", replyToId: "prior", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" },
+ const full = wire({ seq, clientNonce: "nonce", replyToId: "prior", replyTo: { id: "prior", authorId: "peer", authorName: "Peer" },
attachments: [{ id: "file", name: "file.txt", url: "/file", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 4, width: null, height: null }],
embeds: [{ title: "Card" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
thread: { id: "thread", name: "Thread", messageCount: 1, lastReplyAt: null },
diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.ts
index 5b961d3a8..fc2781382 100644
--- a/src/web/src/lib/community/message-wire.ts
+++ b/src/web/src/lib/community/message-wire.ts
@@ -1,4 +1,4 @@
-import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, type CommunityMessageResource } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, messagePreview, type CommunityMessageResource } from "@alook/shared"
import { MessageEmbedSchema, type Msg, type CanonicalMessage } from "@/lib/community/models/message"
import { avatarInitial } from "@/lib/community/avatar"
import { presentMessageAttachment } from "@/lib/community/attachment-presentation"
@@ -28,10 +28,11 @@ function projectMessageRichContent(value: unknown): Pick<Msg, "attachments" | "e
}
}
-export function presentCanonicalMessage(message: CommunityMessageResource): Msg {
- const { channelId: _channelId, replyToId: _replyToId, clientNonce, authorAvatar, attachments: _attachments, embeds: _embeds, thread, ...fields } = message
+export function presentCanonicalMessage(message: CommunityMessageResource, replyTarget?: CommunityMessageResource): Msg {
+ const { channelId: _channelId, replyToId: _replyToId, clientNonce, authorAvatar, attachments: _attachments, embeds: _embeds, thread, replyTo, ...fields } = message
return {
...fields,
+ ...(replyTo ? { replyTo: { ...replyTo, text: replyTarget?.id === replyTo.id && replyTarget.channelId === message.channelId ? messagePreview(replyTarget) : replyTo.deleted ? "" : "Loading message…" } } : {}),
...(authorAvatar === undefined ? {} : { authorAvatar: authorAvatar ?? avatarInitial(message.authorName ?? "") }),
...(clientNonce != null ? { clientNonce } : {}),
...(thread ? { thread: presentMessageThread(thread) } : {}),
diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.ts
index 73fb17a72..17c336e43 100644
--- a/src/web/src/lib/community/models/message.ts
+++ b/src/web/src/lib/community/models/message.ts
@@ -42,11 +42,12 @@ export const MessageEmbedSchema = z.object({
type Embed = z.infer<typeof MessageEmbedSchema>
export type Reaction = NonNullable<CommunityMessageResource["reactions"]>[number]
-export type ReplyTarget = Pick<NonNullable<CommunityMessageResource["replyTo"]>, "id" | "authorId" | "authorName" | "text">
+export type ReplyTarget = Pick<NonNullable<CommunityMessageResource["replyTo"]>, "id" | "authorId" | "authorName"> & { text: string }
export type Msg = Pick<CommunityMessageResource, "id" | "type"> & Partial<Omit<CommunityMessageResource,
- "id" | "type" | "channelId" | "replyToId" | "clientNonce" | "attachments" | "embeds" | "authorAvatar" | "thread"
+ "id" | "type" | "channelId" | "replyToId" | "clientNonce" | "attachments" | "embeds" | "authorAvatar" | "thread" | "replyTo"
>> & {
+ replyTo?: NonNullable<CommunityMessageResource["replyTo"]> & { text: string }
color?: string
failed?: boolean
clientNonce?: string
@@ -94,7 +95,7 @@ export type RenderMsg = Msg & { grouped: boolean }
export type Thread = Pick<CommunityChannelResource, "id" | "messageCount"> & {
name: NonNullable<CommunityChannelResource["name"]>
lastMessageAt: NonNullable<CommunityChannelResource["lastMessageAt"]>
- parent: Omit<NonNullable<CommunityMessageResource["replyTo"]>, "id" | "deleted">
+ parent: Omit<ReplyTarget, "id">
parentSeq?: CommunityMessageResource["seq"]
openerMessageId?: CommunityMessageResource["id"]
}
@@ -105,7 +106,7 @@ export type ForumThread = Thread & Required<Pick<CommunityMessageResource,
openerMessageId: CommunityMessageResource["id"]
openerCreatedAt?: CommunityMessageResource["createdAt"]
tags: NonNullable<NonNullable<CommunityMessageResource["thread"]>["tags"]>
- preview: NonNullable<NonNullable<CommunityMessageResource["thread"]>["preview"]>
+ preview: string
participants: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participants"]>
participantCount: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participantCount"]>
}
@@ -124,13 +125,13 @@ export type MessagesPage = Partial<{ [Field in keyof CommunityMessagesRead["page
cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>
}
-export type MessagesReadPage = MessagesPage & Pick<CommunityMessagesRead, "profiles">
+export type MessagesReadPage = MessagesPage & Pick<CommunityMessagesRead, "profiles" | "relatedMessages">
export type MessagesWindowPage = Omit<MessagesPage, "messages"> & { messages: Array<Pick<CommunityMessageResource, "id"> & Partial<Pick<CommunityMessageResource, "seq">>>; newestCursor?: string }
export function messageWindowPage(page: MessagesPage | MessagesReadPage): MessagesWindowPage {
const newest = [...page.messages].filter((message) => message.createdAt).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id.localeCompare(b.id)).at(-1)
- const { profiles: _profiles, ...window } = page as MessagesReadPage
+ const { profiles: _profiles, relatedMessages: _relatedMessages, ...window } = page as MessagesReadPage
return { ...window, messages: page.messages.map((message) => ({ id: message.id, ...(message.seq === undefined ? {} : { seq: message.seq }) })), ...(newest?.createdAt ? { newestCursor: `${newest.createdAt}|${newest.id}` } : {}) }
}
diff --git a/src/web/src/lib/community/read-contract.ts b/src/web/src/lib/community/read-contract.ts
index 407da1e78..c7d126f21 100644
--- a/src/web/src/lib/community/read-contract.ts
+++ b/src/web/src/lib/community/read-contract.ts
@@ -19,6 +19,7 @@ export function writeCommunityChannelRead(_request: Request, channelId: string,
}
export type MessagePage = Pick<CommunityMessagesRead["page"], "latestSeq"> & Partial<{ [Field in Exclude<keyof CommunityMessagesRead["page"], "latestSeq">]: NonNullable<CommunityMessagesRead["page"][Field]> }> & {
+ relatedMessages?: CommunityMessagesRead["relatedMessages"]
messages: unknown[]
profiles: CommunityMessagesRead["profiles"]
cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>
@@ -34,6 +35,7 @@ export function writeCommunityMessagesRead(_request: Request, channelId: string,
function messageReadPayload(channelId: string, page: MessagePage, contract: CommunityContract) {
return { contractVersion: contract, channelId,
profiles: page.profiles,
+ relatedMessages: page.relatedMessages,
messages: page.messages.map((message) => CommunityMessageResourceSchema.parse(message)),
page: { olderCursor: page.olderCursor ?? page.cursor ?? null, newerCursor: page.newerCursor ?? null,
hasMoreOlder: page.hasMoreOlder ?? page.hasMore ?? false, hasMoreNewer: page.hasMoreNewer ?? false,
diff --git a/src/web/src/lib/community/read-response.ts b/src/web/src/lib/community/read-response.ts
index c35b7ad10..4286d399e 100644
--- a/src/web/src/lib/community/read-response.ts
+++ b/src/web/src/lib/community/read-response.ts
@@ -49,13 +49,13 @@ export function decodeCommunityReadResponse(path: string, method: string | undef
if (target.resource === "posted") {
const data = CommunityMessagePostedSchema.parse(value)
assertScope(data.channelId); assertScope(data.message.channelId)
- return { profiles: data.profiles, message: data.message, deduped: data.deduped, ...(data.threadId ? { threadId: data.threadId } : {}) }
+ return { profiles: data.profiles, ...(data.relatedMessages ? { relatedMessages: data.relatedMessages } : {}), message: data.message, deduped: data.deduped, ...(data.threadId ? { threadId: data.threadId } : {}) }
}
if (target.resource === "messages") {
const data = schemas.messages.parse(value)
assertScope(data.channelId); assertScope(data.surfaceReceipt.channelId)
for (const message of data.messages) assertScope(message.channelId)
- return { profiles: data.profiles, messages: data.messages,
+ return { profiles: data.profiles, ...(data.relatedMessages ? { relatedMessages: data.relatedMessages } : {}), messages: data.messages,
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 }
diff --git a/src/web/src/lib/community/spoiler-syntax.ts b/src/web/src/lib/community/spoiler-syntax.ts
index 4f3e479bf..f0d72e8da 100644
--- a/src/web/src/lib/community/spoiler-syntax.ts
+++ b/src/web/src/lib/community/spoiler-syntax.ts
@@ -1,170 +1,2 @@
-import { splice } from "micromark-util-chunked"
-import { classifyCharacter } from "micromark-util-classify-character"
-import { resolveAll } from "micromark-util-resolve-all"
-import { codes } from "micromark-util-symbol"
-import type { Construct, Effects, Event, Extension, State, Token, TokenizeContext } from "micromark-util-types"
-import type { CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle } from "mdast-util-from-markdown"
-
-// Discord-style `||spoiler||` — a micromark inline tokenizer extension +
-// mdast-util-from-markdown extension, structurally mirroring
-// micromark-extension-gfm-strikethrough/mdast-util-gfm-strikethrough (`~~text~~`)
-// with `|` (code 124) in place of `~` (code 126). Recognizing the `||`
-// boundary during TOKENIZATION (the same phase that recognizes `**`/`*`/`` ` ``)
-// — rather than as a text-node find-and-replace pass after parsing — is what
-// lets `||I think **this** is neat||` correctly produce a `spoiler` node
-// containing a nested `strong` node. A text-node find-and-replace can't do
-// this: remark-parse would already have split that input into 3 sibling
-// nodes (text, strong, text) before any post-processing plugin runs, so the
-// two `|` markers never co-occur in one text node to match against.
-
-declare module "micromark-util-types" {
- interface TokenTypeMap {
- spoilerSequence: "spoilerSequence"
- spoilerSequenceTemporary: "spoilerSequenceTemporary"
- spoiler: "spoiler"
- spoilerText: "spoilerText"
- }
-}
-
-declare module "mdast" {
- interface RootContentMap {
- spoiler: SpoilerNode
- }
- interface PhrasingContentMap {
- spoiler: SpoilerNode
- }
-}
-
-/** mdast node produced by `||...||` — a phrasing-content parent, like `emphasis`/`strong`. */
-export interface SpoilerNode {
- type: "spoiler"
- children: import("mdast").PhrasingContent[]
-}
-
-/** Micromark extension enabling `||...||` spoiler syntax during tokenization. */
-export function spoilerSyntax(): Extension {
- const tokenizer: Construct = {
- name: "spoiler",
- tokenize: tokenizeSpoiler,
- resolveAll: resolveAllSpoiler,
- }
- return {
- text: { [codes.verticalBar]: tokenizer },
- insideSpan: { null: [tokenizer] },
- attentionMarkers: { null: [codes.verticalBar] },
- }
-
- function resolveAllSpoiler(events: Event[], context: TokenizeContext): Event[] {
- let index = -1
- while (++index < events.length) {
- if (
- events[index][0] === "enter" &&
- events[index][1].type === "spoilerSequenceTemporary" &&
- events[index][1]._close
- ) {
- let open = index
- while (open--) {
- if (
- events[open][0] === "exit" &&
- events[open][1].type === "spoilerSequenceTemporary" &&
- events[open][1]._open &&
- events[index][1].end.offset - events[index][1].start.offset ===
- events[open][1].end.offset - events[open][1].start.offset
- ) {
- events[index][1].type = "spoilerSequence"
- events[open][1].type = "spoilerSequence"
-
- const spoiler: Token = {
- type: "spoiler",
- start: Object.assign({}, events[open][1].start),
- end: Object.assign({}, events[index][1].end),
- }
- const text: Token = {
- type: "spoilerText",
- start: Object.assign({}, events[open][1].end),
- end: Object.assign({}, events[index][1].start),
- }
-
- const nextEvents: Event[] = [
- ["enter", spoiler, context],
- ["enter", events[open][1], context],
- ["exit", events[open][1], context],
- ["enter", text, context],
- ]
- const insideSpan = context.parser.constructs.insideSpan.null
- if (insideSpan) {
- splice(nextEvents, nextEvents.length, 0, resolveAll(insideSpan, events.slice(open + 1, index), context))
- }
- splice(nextEvents, nextEvents.length, 0, [
- ["exit", text, context],
- ["enter", events[index][1], context],
- ["exit", events[index][1], context],
- ["exit", spoiler, context],
- ])
- splice(events, open - 1, index - open + 3, nextEvents)
- index = open + nextEvents.length - 2
- break
- }
- }
- }
- }
- index = -1
- while (++index < events.length) {
- if (events[index][1].type === "spoilerSequenceTemporary") {
- events[index][1].type = "data"
- }
- }
- return events
- }
-
- function tokenizeSpoiler(this: TokenizeContext, effects: Effects, ok: State, nok: State): State {
- const previous = this.previous
- const events = this.events
- let size = 0
- return start
-
- function start(code: Parameters<State>[0]): State | undefined {
- if (previous === codes.verticalBar && events[events.length - 1][1].type !== "characterEscape") {
- return nok(code)
- }
- effects.enter("spoilerSequenceTemporary")
- return more(code)
- }
-
- function more(code: Parameters<State>[0]): State | undefined {
- const before = classifyCharacter(previous)
- if (code === codes.verticalBar) {
- if (size > 1) return nok(code)
- effects.consume(code)
- size++
- return more
- }
- // Only the doubled `||` marker forms a spoiler boundary — a lone `|`
- // (e.g. inside a table row, which this codebase's Streamdown/GFM
- // pipeline also parses) must fall through untouched.
- if (size < 2) return nok(code)
- const token = effects.exit("spoilerSequenceTemporary")
- const after = classifyCharacter(code)
- token._open = !after || (after === 2 && Boolean(before))
- token._close = !before || (before === 2 && Boolean(after))
- return ok(code)
- }
- }
-}
-
-/** mdast-util-from-markdown extension: turns the `spoiler` token into a `spoiler` mdast node. */
-export function spoilerFromMarkdown(): FromMarkdownExtension {
- return {
- canContainEols: ["spoiler"],
- enter: { spoiler: enterSpoiler },
- exit: { spoiler: exitSpoiler },
- }
-}
-
-const enterSpoiler: FromMarkdownHandle = function (this: CompileContext, token) {
- this.enter({ type: "spoiler", children: [] }, token)
-}
-
-const exitSpoiler: FromMarkdownHandle = function (this: CompileContext, token) {
- this.exit(token)
-}
+export { spoilerSyntax, spoilerFromMarkdown } from "@alook/shared/spoiler-syntax"
+export type { SpoilerNode } from "@alook/shared/spoiler-syntax"
diff --git a/src/web/src/lib/community/thread-read.test.ts b/src/web/src/lib/community/thread-read.test.ts
index 2751a8981..aa65ea6d0 100644
--- a/src/web/src/lib/community/thread-read.test.ts
+++ b/src/web/src/lib/community/thread-read.test.ts
@@ -29,8 +29,10 @@ beforeEach(() => {
describe("complete thread read resource", () => {
it("writes the scoped message, attachment, reaction, reply and participant identities", async () => {
- mocks.attachments.mockResolvedValue([{ id: "attachment", messageId: "reply", targetId: "thread", filename: "note.txt", r2Key: "owned-key", contentType: "text/plain", size: 42 }])
- mocks.reactions.mockResolvedValue([{ messageId: "reply", emoji: "👍", userId: "viewer" }])
+ mocks.attachments.mockResolvedValueOnce([{ id: "attachment", messageId: "reply", targetId: "thread", filename: "note.txt", r2Key: "owned-key", contentType: "text/plain", size: 42 }])
+ mocks.reactions.mockResolvedValueOnce([{ messageId: "reply", emoji: "👍", userId: "viewer" }])
+ mocks.attachments.mockResolvedValueOnce([])
+ mocks.reactions.mockResolvedValueOnce([])
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(String(BUSINESS_SCHEMA_VERSION))
@@ -39,7 +41,8 @@ describe("complete thread read resource", () => {
included: { tags: [{ messageId: "opener", tag: "bug" }], members: [{ channelId: "thread", userId: "viewer", relation: "notify", isCreator: true }],
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: [{ id: "attachment", name: "note.txt", contentType: "text/plain", sizeBytes: 42, thumbnailUrl: null, width: null, height: null }], reactions: [{ emoji: "👍", me: true, count: 1, userIds: ["viewer"] }] })
+ replyTo: { id: "previous", authorId: "viewer" }, attachments: [{ id: "attachment", name: "note.txt", contentType: "text/plain", sizeBytes: 42, thumbnailUrl: null, width: null, height: null }], reactions: [{ emoji: "👍", me: true, count: 1, userIds: ["viewer"] }] })
+ expect(body.included.messages.find(message => message.id === "previous")).toMatchObject({ content: "same-channel reply", channelId: "thread" })
expect(JSON.stringify(body)).not.toContain("foreign private body")
expect(mocks.attachments).toHaveBeenCalledWith(db, ["opener", "reply"])
expect(mocks.reactions).toHaveBeenCalledWith(db, ["opener", "reply"], "viewer")
@@ -50,7 +53,7 @@ describe("complete thread read resource", () => {
mocks.replies.mockResolvedValue([{ ...row("previous", "foreign"), content: "private" }])
const response = await writeCommunityThreadsRead(db, "viewer", parent, [child], included())
const body = communityReadSchemas().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(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", deleted: true })
})
it("does not disclose a reply from a legitimate sibling in the same included query", async () => {
@@ -58,7 +61,7 @@ describe("complete thread read resource", () => {
mocks.replies.mockResolvedValue([{ ...row("previous", "sibling"), content: "sibling private reply" }])
const response = await writeCommunityThreadsRead(db, "viewer", parent, [child, sibling], included())
const body = communityReadSchemas().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(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", deleted: true })
expect(JSON.stringify(body)).not.toContain("sibling private reply")
expect(mocks.replies).toHaveBeenCalledWith(db, ["previous"], ["forum", "thread", "sibling"])
})
diff --git a/src/web/src/lib/community/thread-read.ts b/src/web/src/lib/community/thread-read.ts
index 5f738bfdf..95e9cd030 100644
--- a/src/web/src/lib/community/thread-read.ts
+++ b/src/web/src/lib/community/thread-read.ts
@@ -31,6 +31,8 @@ export async function readCommunityThreadsResource(db: Database, userId: string,
const message = mapMessageForApi(item, contextForChannel(item.channelId), contract, item.channelId)
return message
})
+ const related = [...new Map(items.flatMap(item => contextForChannel(item.channelId).relatedMessages ?? []).map(message => [message.id, message])).values()]
+ messages.push(...related)
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,
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index b3fcb7b16..c9884554b 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -162,6 +162,7 @@ describe("communityKeys", () => {
"channel",
"d1",
"message-context",
+ "seq",
7,
])
expect(communityKeys.messageContexts("dm", "d1")).toEqual([
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 0878a268a..665e61b7f 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -113,8 +113,8 @@ export const communityKeys = {
[...communityKeys.all, "message", messageId] as const,
messageContexts: (_type: "channel" | "dm", channelId: string) =>
[...communityKeys.all, "channel", channelId, "message-context"] as const,
- messageContext: (type: "channel" | "dm", channelId: string, targetSeq: number | null) =>
- [...communityKeys.messageContexts(type, channelId), targetSeq] as const,
+ messageContext: (type: "channel" | "dm", channelId: string, target: number | string | null) =>
+ [...communityKeys.messageContexts(type, channelId), typeof target === "string" ? "id" : "seq", target] as const,
reactionDetailsAll: () =>
[...communityKeys.all, "reaction-details"] as const,
reactionDetails: (messageId: string) =>
diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.ts
index d09ec1b93..d0bfbfb62 100644
--- a/src/web/src/lib/query-persister.test.ts
+++ b/src/web/src/lib/query-persister.test.ts
@@ -378,7 +378,7 @@ describe("createIdbPersister — serialize filter", () => {
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: { id: "reply", authorId: "reply_author", authorName: "Reply", text: "Prior" },
+ replyTo: { id: "reply", authorId: "reply_author", authorName: "Reply", },
thread: { id: "thread", name: "Thread", messageCount: 0, participants: [{ id: "thread_participant", name: "Participant", avatar: "P", avatarVersion: 0 }] },
} : {}),
}))
diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
index 0d1f9eb71..9e6ae7285 100644
--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
@@ -343,6 +343,7 @@ async function uploadImage(args: {
mimeType,
buffer,
})
+ await expect(page.getByText(name, { exact: true })).toBeVisible()
await expect.poll(() => editable.evaluate((element) => document.activeElement === element)).toBe(true)
await page.keyboard.press("Enter")
diff --git a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
index 8fd9ffd0a..34dbdb98e 100644
--- a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
+++ b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
@@ -1,9 +1,11 @@
+import { CommunityConversationEntryReadSchema } from "@alook/shared"
import { communityFixtureFetch } from "./_fixtures/business-contract"
import type { Page, Route } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
import { WEB_URL } from "./_setup/paths"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors) {
@@ -25,6 +27,86 @@ async function prepareCase(actors: CaseActors) {
const VIEWPORT = { width: 1280, height: 800 }
+for (const kind of ["channel", "dm"] as const) {
+ test(`${kind} reply uses the current window or an independent ID context`, async ({ caseActors, caseResources }, testInfo) => {
+ const actors = await caseActors(["alice", "bob"])
+ const { seedServer, seedChannel, seedJoinServer, seedDm, seedMessage } = actors.seed
+ let serverId: string | undefined
+ let channelId: string
+ if (kind === "channel") {
+ serverId = await seedServer("alice", `Reply context ${Date.now()}`)
+ await seedJoinServer("alice", "bob", serverId)
+ channelId = await seedChannel("alice", serverId, "reply-context")
+ } else channelId = await seedDm("alice", actors.userId("bob"))
+ const olderId = await seedMessage("bob", channelId, "**Old target** ||hidden preview|| `file_name.ts`")
+ let nearbyId = ""
+ for (let index = 0; index < 51; index++) {
+ const id = await seedMessage("bob", channelId, `context filler ${index}`)
+ if (index === 28) nearbyId = id
+ }
+ const oldReplyId = await seedMessage("bob", channelId, "Reply to old target", { replyToId: olderId })
+ const nearbyReplyId = await seedMessage("bob", channelId, "Reply to nearby target", { replyToId: nearbyId })
+ await (await prepareCase(actors)).setReadCheckpoint(channelId, nearbyReplyId)
+ const { page } = await actors.asUser("alice")
+ await page.setViewportSize(VIEWPORT)
+ const requests: Array<{ url: string; method: string }> = []
+ page.on("request", request => requests.push({ url: request.url(), method: request.method() }))
+ const olderPage = await holdNextPage(page, channelId, "cursor", caseResources)
+ const entryResponsePromise = page.waitForResponse(response => {
+ const url = new URL(response.url())
+ return response.request().method() === "GET"
+ && url.pathname === `/api/community/channels/${channelId}/messages`
+ && url.searchParams.get("entry") === "1"
+ })
+ await gotoAfterUserWsAuth(page, kind === "dm" ? `/c/me/${channelId}` : `/c/channels/${serverId}/${channelId}`)
+ const entryResponse = await entryResponsePromise
+ expect(entryResponse.ok()).toBe(true)
+ const entry = CommunityConversationEntryReadSchema.parse(await entryResponse.json())
+ const rootIds = entry.messages.map(message => message.id)
+ const relatedIds = (entry.relatedMessages ?? []).map(message => message.id)
+ expect(rootIds).toEqual(expect.arrayContaining([nearbyId, oldReplyId, nearbyReplyId]))
+ expect(rootIds).not.toContain(olderId)
+ expect(relatedIds).toContain(olderId)
+ const scroller = page.getByTestId(tid.messageScroller)
+ const nearReply = scroller.getByTestId(tid.message(nearbyReplyId))
+ await expect(nearReply).toBeVisible()
+ await nearReply.getByRole("button", { name: "Show original message" }).click()
+ await expect(scroller.getByTestId(tid.message(nearbyId))).toBeInViewport()
+ await expect(page.getByRole("dialog")).toHaveCount(0)
+ expect(requests.filter(request => new URL(request.url).searchParams.has("anchor"))).toEqual([])
+ await scroller.evaluate(element => { element.scrollTop = element.scrollHeight })
+ const oldReply = scroller.getByTestId(tid.message(oldReplyId))
+ await expect(oldReply).toBeVisible()
+ const originalButton = oldReply.getByRole("button", { name: "Show original message" })
+ await expect(originalButton).toContainText("Old target [Spoiler] file_name.ts")
+ await expect(originalButton).not.toContainText("hidden preview")
+ await expect(scroller.getByTestId(tid.message(olderId))).toHaveCount(0)
+ const before = await waitForStableGeometry(page)
+ const newCount = await scroller.getByTestId(tid.newDivider).count()
+ const context = await holdNextPage(page, channelId, "anchor", caseResources)
+ const start = requests.length
+ await originalButton.click()
+ await context.matched
+ const dialog = page.getByRole("dialog")
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByText("Old target", { exact: true })).toBeVisible()
+ context.release()
+ await expect(dialog.locator('[data-anchor-row="1"]')).toBeVisible()
+ await expect(scroller.getByTestId(tid.message(olderId))).toHaveCount(0)
+ expect(await scroller.getByTestId(tid.newDivider).count()).toBe(newCount)
+ const after = await readGeometry(page)
+ expect(after.firstVisibleId).toBe(before.firstVisibleId)
+ expect(Math.abs(after.scrollTop - before.scrollTop)).toBeLessThanOrEqual(1)
+ const contextRequests = requests.slice(start)
+ expect(contextRequests.filter(request => new URL(request.url).pathname.includes("/messages/seq/"))).toEqual([])
+ expect(contextRequests.filter(request => request.method === "PUT" && new URL(request.url).pathname.endsWith("/read"))).toEqual([])
+ expect(contextRequests.filter(request => new URL(request.url).searchParams.get("anchor") === olderId)).toHaveLength(1)
+ await context.dispose()
+ await testInfo.attach("reply-context-window.json", { body: Buffer.from(JSON.stringify({ kind, channelId, olderId, nearbyId, oldReplyId, rootIds, relatedIds, olderCursorRequested: olderPage.wasMatched(), olderCursorHeldThroughAssertions: true, before, after, newCount, contextRequests }, null, 2)), contentType: "application/json" })
+ await olderPage.dispose()
+ })
+}
+
type Geometry = {
scrollTop: number
scrollHeight: number
@@ -76,7 +158,7 @@ async function readMessageOffset(page: Page, messageId: string): Promise<number
}, messageId)
}
-async function holdNextPage(page: Page, channelId: string, param: "cursor" | "since", caseResources: CaseResources) {
+async function holdNextPage(page: Page, channelId: string, param: "cursor" | "since" | "anchor", caseResources: CaseResources) {
let release!: () => void
let resolveMatched!: () => void
let consumed = false
@@ -92,12 +174,13 @@ async function holdNextPage(page: Page, channelId: string, param: "cursor" | "si
resolveMatched()
await gate
}
- await route.continue()
+ await route.fallback()
}
await page.route(pattern, handler)
return {
matched,
release,
+ wasMatched: () => consumed,
dispose: async () => {
release()
await page.unroute(pattern, handler)
diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.ts
index 3fad3be9c..fc01e3a2b 100644
--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts
@@ -361,9 +361,9 @@ export function createSeed(identity: SeedIdentity) {
// Post a message into a channel via API (persisted with a real server id).
// Use when a spec needs a pre-existing message as a precondition rather than
// exercising the send UI itself. Returns the message id.
- async function seedMessage(author: UserKey, channelId: string, content: string): Promise<string> {
+ async function seedMessage(author: UserKey, channelId: string, content: string, options?: { replyToId: string }): Promise<string> {
identity.assertResource?.("channel", channelId)
- const res = await post(author, `/api/community/channels/${channelId}/messages`, { content })
+ const res = await post(author, `/api/community/channels/${channelId}/messages`, { content, ...options })
const data = (await res.json()) as { message: { id: string } }
identity.onResourceCreated?.("message", data.message.id)
return data.message.id