Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(community): preserve native markdown mention boundaries (#989)
Generd47cc8977199
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 157267435..7a8d486a3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -511,6 +511,9 @@ importers:remark-gfm:specifier: ^4.0.1version: 4.0.1+ remark-parse:+ specifier: ^11.0.0+ version: 11.0.0resend:specifier: 6.17.2version: 6.17.2@@ -535,6 +538,9 @@ importers:tw-animate-css:specifier: ^1.4.0version: 1.4.0+ unified:+ specifier: ^11.0.5+ version: 11.0.5unique-names-generator:specifier: ^4.7.1version: 4.7.1@@ -617,9 +623,6 @@ importers:react-scan:specifier: 0.5.7version: 0.5.7(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- remark-parse:- specifier: ^11.0.0- version: 11.0.0serwist:specifier: 9.5.13version: 9.5.13([email protected])([email protected])@@ -638,9 +641,6 @@ importers:typescript-eslint:specifier: 8.71.1- unified:- specifier: ^11.0.5- version: 11.0.5vitest:specifier: 4.1.11version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 10f26790f..bff85d317 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -822,7 +822,7 @@ export {export type { FriendshipStatus } from "./utils/friendship";export { isPublic, isPrivate } from "./utils/visibility";export type { AgentVisibility } from "./utils/visibility";-export { extractMentionedUserIds, MENTION_TYPES, isMentionType, MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary } from "./utils/community-mentions";+export { extractMentionedUserIds, MENTION_TYPES, isMentionType, MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary, isMentionEndBoundary } from "./utils/community-mentions";export type { MentionCandidate, MentionType } from "./utils/community-mentions";export { parseReleaseVersion, releaseVersionGte, semverGte } from "./semver";export type { ReleaseVersion } from "./semver";diff --git a/src/shared/src/utils/community-mentions.ts b/src/shared/src/utils/community-mentions.tsindex f17b96338..29de2322d 100644--- a/src/shared/src/utils/community-mentions.ts+++ b/src/shared/src/utils/community-mentions.ts@@ -41,10 +41,20 @@ export function isMentionType(value: unknown): value is MentionType {export const MENTION_IDENTIFIER_CHARACTERS = /[\p{L}\p{N}_-]/u.source;const ID_CHAR_RE = new RegExp(MENTION_IDENTIFIER_CHARACTERS, "u");-const MENTION_START_RE = new RegExp(`${MENTION_IDENTIFIER_CHARACTERS}$`, "u");export function isMentionStartBoundary(prefix: string): boolean {- return !MENTION_START_RE.test(prefix);+ const previous = [...prefix.slice(-2)].at(-1);+ return isBoundaryChar(previous);+}++export function isMentionEndBoundary(suffix: string): boolean {+ return isBoundaryChar(suffix[Symbol.iterator]().next().value);+}++function isEscapedStart(content: string, at: number): boolean {+ let start = at;+ while (start > 0 && content[start - 1] === "\\") start--;+ return (at - start) % 2 === 1;}function isBoundaryChar(ch: string | undefined): boolean {@@ -79,7 +89,7 @@ export function extractMentionedUserIds(const at = content.indexOf("@", i);if (at === -1) break;// The character before "@" must be a boundary (or start of string).- if (!isMentionStartBoundary(content.slice(0, at))) {+ if (!isMentionStartBoundary(content.slice(0, at)) || isEscapedStart(content, at)) {i = at + 1;continue;}@@ -88,8 +98,7 @@ export function extractMentionedUserIds(for (const { candidate, handle } of handled) {const slice = lower.slice(at + 1, at + 1 + handle.length);if (slice !== handle) continue;- const after = content[at + 1 + handle.length];- if (!isBoundaryChar(after)) continue;+ if (!isMentionEndBoundary(content.slice(at + 1 + handle.length))) continue;matched = candidate;matchedLen = handle.length;break;diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.tsindex b38b260ce..3b945de79 100644--- a/src/shared/test/utils/community-mentions.test.ts+++ b/src/shared/test/utils/community-mentions.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { extractMentionedUserIds } from "../../src/utils/community-mentions";+import { extractMentionedUserIds, isMentionStartBoundary, isMentionEndBoundary } from "../../src/utils/community-mentions";// Every mention now resolves ONLY via a fully-tagged `@Name#dddd` handle — a// hand-typed bare `@Alice` is not a mention. Rosters carry a discriminator.@@ -11,7 +11,40 @@ const ROSTER = [{ userId: "u5", name: "李雷", discriminator: "0005" },];+describe("isMentionStartBoundary — complete Unicode prefix", () => {+ it.each(["mail", "回复", "é", "𠮷", "𠀀", "𝟙", "_", "-", "9"])("rejects the final identifier code point in %s", (identifier) => {+ expect(isMentionStartBoundary(identifier)).toBe(false);+ expect(isMentionStartBoundary(`earlier text ${identifier}`)).toBe(false);+ });++ it.each(["", " ", "\n", "(", ".", "🎉", "\u0301", "\uD842", "\uDFB7"])("accepts a non-identifier final code point: %j", (boundary) => {+ expect(isMentionStartBoundary(boundary)).toBe(true);+ if (boundary) expect(isMentionStartBoundary(`𠮷𝟙${boundary}`)).toBe(true);+ });++ it("uses only the final code point after a supplementary pair or a lone surrogate", () => {+ expect(isMentionStartBoundary("𠮷a")).toBe(false);+ expect(isMentionStartBoundary("𠮷.")).toBe(true);+ expect(isMentionStartBoundary("\uD842a")).toBe(false);+ expect(isMentionStartBoundary("\uDFB7 ")).toBe(true);+ expect(isMentionStartBoundary("x".repeat(20_000) + "🎉")).toBe(true);+ });+});+describe("extractMentionedUserIds", () => {+ it.each(["x", "é", "𠮷", "𠀀", "𝟙", "_", "-"])("rejects the complete suffix identifier %s", (suffix) => {+ expect(isMentionEndBoundary(suffix)).toBe(false);+ expect(extractMentionedUserIds(`@Alice#0001${suffix} @Bob#0002`, ROSTER)).toEqual(["u2"]);+ });++ it.each(["", "🎉", "。", " ", "\uD842", "\uDFB7"])("accepts the complete suffix boundary %j", (suffix) => {+ expect(isMentionEndBoundary(suffix)).toBe(true);+ expect(extractMentionedUserIds(`@Alice#0001${suffix}`, ROSTER)).toEqual(["u1"]);+ });++ it.each([1, 2, 3, 4])("uses raw backslash parity for a run of %s", (count) => {+ expect(extractMentionedUserIds("\\".repeat(count) + "@Alice#0001", ROSTER)).toEqual(count % 2 ? [] : ["u1"]);+ });it("returns empty when content is empty", () => {expect(extractMentionedUserIds("", ROSTER)).toEqual([]);});@@ -50,8 +83,13 @@ describe("extractMentionedUserIds", () => {expect(extractMentionedUserIds("contact me@Alice#0001.com", ROSTER)).toEqual([]);});- it.each(["mail", "回复", "é", "𠮷", "_", "-", "9"])("rejects an identifier prefix before a tagged mention: %s", (prefix) => {+ it.each(["mail", "回复", "é", "𠮷", "𠀀", "𝟙", "_", "-", "9"])("rejects an identifier prefix before a tagged mention: %s", (prefix) => {expect(extractMentionedUserIds(`${prefix}@Alice#0001`, ROSTER)).toEqual([]);+ expect(extractMentionedUserIds(`earlier text ${prefix}@Alice#0001 then @Bob#0002`, ROSTER)).toEqual(["u2"]);+ });++ it.each([" ", "(", ".", "🎉", "\u0301", "\uD842", "\uDFB7"])("keeps an exact handle after the final boundary: %j", (boundary) => {+ expect(extractMentionedUserIds(`𠮷${boundary}@Alice#0001`, ROSTER)).toEqual(["u1"]);});it("handles unicode names via handle", () => {diff --git a/src/web/package.json b/src/web/package.jsonindex 279caf741..e092dbd40 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -124,6 +124,7 @@"rehype-slug": "^6.0.0","remark-breaks": "^4.0.0","remark-gfm": "^4.0.1",+ "remark-parse": "^11.0.0","resend": "6.17.2","shadcn": "^4.21.4","shiki": "^4.5.0",@@ -132,6 +133,7 @@"stripe": "22.6.2","tailwind-merge": "^3.7.0","tw-animate-css": "^1.4.0",+ "unified": "^11.0.5","unique-names-generator": "^4.7.1","zod": "^4.6.5"},@@ -161,14 +163,12 @@"jsdom": "29.1.1","knip": "^6.32.2","react-scan": "0.5.7",- "remark-parse": "^11.0.0","serwist": "9.5.13","sharp": "^0.35.5","tailwindcss": "^4","tsx": "^4.23.15","typescript": "^6.0.3","typescript-eslint": "8.71.1",- "unified": "^11.0.5","vitest": "4.1.11","wrangler": "4.149.0"}diff --git a/src/web/src/components/community/messages/message-body.dom.test.ts b/src/web/src/components/community/messages/message-body.dom.test.tsindex 51669e2b3..f26db2108 100644--- a/src/web/src/components/community/messages/message-body.dom.test.ts+++ b/src/web/src/components/community/messages/message-body.dom.test.ts@@ -136,6 +136,45 @@ describe("MessageBody — spoiler nested formatting (full Streamdown pipeline)",// sanitize pipeline — the mdast-only unit tests in message-markdown.test.ts// pass kebab props directly and can't catch this.describe("MessageBody — mention pill survives sanitize (full pipeline)", () => {+ it("updates the same body through partial supplementary-prefixed input and a genuine mention", () => {+ const onOpenProfile = vi.fn()+ const text = "𠮷@Alice#0001"+ let renderer: ReturnType<typeof render>+ act(() => { renderer = render(React.createElement(MessageBody, { text: "", onOpenProfile })) })+ for (let end = 1; end <= text.length; end++) {+ act(() => { renderer!.rerender(React.createElement(MessageBody, { text: text.slice(0, end), onOpenProfile })) })+ const body = renderer!.container.querySelector("[data-community-message-body]")!+ expect(body.textContent).toBe(text.slice(0, end))+ expect(body.querySelectorAll('[title="@Alice"]')).toHaveLength(0)+ }+ act(() => { renderer!.rerender(React.createElement(MessageBody, { text: "🎉@Alice#0001", onOpenProfile })) })+ fireEvent.click(renderer!.getByRole("button", { name: "@Alice" }))+ expect(onOpenProfile).toHaveBeenCalledWith("Alice", expect.anything(), "0001")+ act(() => { renderer!.rerender(React.createElement(MessageBody, { text, onOpenProfile })) })+ expect(renderer!.container.querySelectorAll('[title="@Alice"]')).toHaveLength(0)+ expect(renderer!.container.querySelector("[data-community-message-body]")!.textContent).toBe(text)+ })++ it.each([+ ["𠮷@Alice#0001", "𠮷@Alice#0001"],+ ["@Alice#0001𠀀", "@Alice#0001𠀀"],+ ["\\@Alice#0001", "@Alice#0001"],+ ["@Alice#0001", "@Alice#0001"],+ ["\\@everyone", "@everyone"],+ ["@everyone", "@everyone"],+ ["`@Alice#0001 @everyone`", "@Alice#0001 @everyone"],+ ["[@Alice#0001 @everyone](https://example.com)", "@Alice#0001 @everyone"],+ ["[@Alice#0001 @everyone][target]\n\n[target]: https://example.com", "@Alice#0001 @everyone"],+ ])("keeps protected/literal text through the actual pipeline: %s", (text, visible) => {+ let renderer: ReturnType<typeof render>+ act(() => {+ renderer = render(React.createElement(MessageBody, { text, onOpenProfile: vi.fn() }))+ })+ const body = renderer!.container.querySelector("[data-community-message-body]")!+ expect(body).toHaveTextContent(visible)+ expect(body.querySelectorAll('[title="@Alice"], [title="@everyone"]')).toHaveLength(0)+ })+it("renders an HTML-looking member name as one literal pill and opens the tagged profile", () => {const onOpenProfile = vi.fn()let renderer: ReturnType<typeof render>diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsxindex cdd9841f2..fccda2b69 100644--- a/src/web/src/components/community/messages/message-body.tsx+++ b/src/web/src/components/community/messages/message-body.tsx@@ -2,11 +2,10 @@ import { memo, useMemo } from "react"import { Streamdown } from "streamdown"import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"import { harden } from "rehype-harden"-import remarkGfm from "remark-gfm"-import remarkBreaks from "remark-breaks"import type { PluggableList } from "unified"import { mermaid, cjk, math } from "@/lib/streamdown-plugins"-import { chatSyntaxPlugin, chatSyntaxHandlers } from "@/lib/community/chat-syntax-plugin"+import { chatSyntaxHandlers } from "@/lib/community/chat-syntax-plugin"+import { CHAT_REMARK_PLUGINS } from "@/lib/community/chat-markdown"import {extractInviteTokens,MD_ALLOWED_TAGS,@@ -113,9 +112,10 @@ function MessageBodyImpl({><StreamdownclassName="message-markdown-blocks flex flex-col gap-2 space-y-0"+ mode="static"parseIncompleteMarkdown={false}plugins={{ mermaid, cjk, math }}- remarkPlugins={[remarkGfm, chatSyntaxPlugin, remarkBreaks]}+ remarkPlugins={CHAT_REMARK_PLUGINS}remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}rehypePlugins={REHYPE_PLUGINS}// Deliberately skips the AI-content confirm-before-navigating modaldiff --git a/src/web/src/lib/community/chat-markdown.test.ts b/src/web/src/lib/community/chat-markdown.test.tsnew file mode 100644index 000000000..8e68fabf5--- /dev/null+++ b/src/web/src/lib/community/chat-markdown.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest"+import { detectChatMentionType, extractChatMentionedUserIds } from "./chat-markdown"++const candidates = [+ { userId: "alice", name: "Alice", discriminator: "0001" },+ { userId: "bob", name: "Bob", discriminator: "0002" },+ { userId: "other-alice", name: "Alice", discriminator: "0003" },+]++describe("whole-body native Markdown mention consumption", () => {+ it.each([+ "`TOKEN`",+ "```txt\nTOKEN\n```",+ "```txt\nTOKEN",+ " TOKEN",+ "[TOKEN](https://example.com)",+ "[label](https://example.com/TOKEN)",+ "[TOKEN][target]\n\n[target]: https://example.com",+ "<https://example.com/TOKEN>",+ "https://example.com/TOKEN",+ "$TOKEN$",+ "$$\nTOKEN\n$$",+ "\\TOKEN",+ "@TOKEN",+ "@TOKEN",+ "𠮷TOKEN",+ "𠀀TOKEN",+ "𝟙TOKEN",+ "TOKEN𠮷",+ "TOKEN𠀀",+ "TOKEN𝟙",+ ])("does not consume protected or literal input: %s", (template) => {+ function body(token: string): string {+ return template.includes("64;") || template.includes("commat;")+ ? template.replace("TOKEN", token.slice(1))+ : template.replace("TOKEN", token)+ }+ expect(extractChatMentionedUserIds(body("@Alice#0001"), candidates)).toEqual([])+ expect(detectChatMentionType(body("@everyone"))).toBeUndefined()+ })++ it.each([+ "TOKEN",+ "🎉TOKEN!",+ "**TOKEN**",+ "中文**TOKEN**。",+ "||TOKEN||",+ "\\\\TOKEN",+ "`TOKEN",+ "[TOKEN](unfinished",+ ])("consumes native unprotected input: %s", (template) => {+ expect(extractChatMentionedUserIds(template.replaceAll("TOKEN", "@Alice#0001"), candidates)).toEqual(["alice"])+ expect(detectChatMentionType(template.replaceAll("TOKEN", "@everyone"))).toBe("everyone")+ })++ it("keeps protection local and resolves exact tagged identities once", () => {+ const content = "`@Alice#0001` \\@Alice#0001 [@everyone](https://example.com) @Bob#0002 @Alice#0003 @Bob#0002"+ expect(extractChatMentionedUserIds(content, candidates)).toEqual(["bob", "other-alice"])+ expect(detectChatMentionType(content)).toBeUndefined()+ expect(detectChatMentionType(`${content} @everyone`)).toBe("everyone")+ })+})diff --git a/src/web/src/lib/community/chat-markdown.ts b/src/web/src/lib/community/chat-markdown.tsnew file mode 100644index 000000000..c391aa315--- /dev/null+++ b/src/web/src/lib/community/chat-markdown.ts@@ -0,0 +1,52 @@+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, math } from "../streamdown-remark-plugins"+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([math.remarkPlugin])+ .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]+}diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.tsindex 1bebea208..64bb3e34a 100644--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts@@ -40,6 +40,26 @@ describe("CLI prompt ref examples — tokenizer contract", () => {})describe("chatSyntaxPlugin — mention", () => {+ it.each(["\uD800", "\uD800!tail"])("preserves a mention and unpaired high-surrogate suffix %j", (suffix) => {+ expect(paragraphChildren(parse(`@Alice#0001${suffix}`))).toEqual([+ expect.objectContaining({ type: "mention", value: "@Alice", discriminator: "0001" }),+ expect.objectContaining({ type: "text", value: suffix }),+ ])+ })++ it.each(["x", "é", "𠮷", "𠀀", "𝟙", "_", "-"])("keeps a handle with identifier suffix %s intact", (suffix) => {+ expect(paragraphChildren(parse(`@Alice#0001${suffix}`))).toEqual([+ expect.objectContaining({ type: "text", value: `@Alice#0001${suffix}` }),+ ])+ })++ it.each(["@Alice#0001", "@everyone", "/Alook#1234/general", "/Alook#1234/general#8", "/Alook#1234/general/#8", "/Alook#1234/general/#8#2", "/.dm/Alice#0001", "/Alook#1234"])("preserves literal syntax origin for %s", (syntax) => {+ for (const source of [`\\${syntax}`, `${syntax.startsWith("@") ? "@" : "/"}${syntax.slice(1)}`]) {+ const children = paragraphChildren(parse(source))+ expect(children.every((node) => node.type === "text")).toBe(true)+ expect(children.map((node) => "value" in node ? node.value : "").join("")).toBe(syntax)+ }+ })it("keeps a bare at-sign in prose from swallowing a following channel ref", () => {const children = paragraphChildren(parse("DM回复取消自动@已交 /Alook#5620/fix/#213"))expect(children.some((child) => child.type === "mention")).toBe(false)diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.tsindex d2a36f9f3..40348e54c 100644--- a/src/web/src/lib/community/chat-syntax-plugin.ts+++ b/src/web/src/lib/community/chat-syntax-plugin.ts@@ -1,4 +1,4 @@-import type { Root, PhrasingContent } from "mdast"+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"@@ -6,7 +6,7 @@ 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 } from "@alook/shared"+import { MENTION_IDENTIFIER_CHARACTERS, isMentionStartBoundary, isMentionEndBoundary } from "@alook/shared"import { spoilerSyntax, spoilerFromMarkdown } from "./spoiler-syntax"import type { SpoilerNode } from "./spoiler-syntax"@@ -127,7 +127,7 @@ const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}]// 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,})`,+ String.raw`(?<!/|${MENTION_IDENTIFIER_CHARACTERS})(?:@everyone(?!${MENTION_IDENTIFIER_CHARACTERS})|@[^@#\n\r]*[^@#\n\r\s]#\d{4,}(?!${MENTION_IDENTIFIER_CHARACTERS}))`,"gu",)@@ -155,11 +155,13 @@ export interface ServerRefNode {declare module "mdast" {interface RootContentMap {+ chatLiteral: ChatLiteralNodemention: MentionNodechannelRef: ChannelRefNodeserverRef: ServerRefNode}interface PhrasingContentMap {+ chatLiteral: ChatLiteralNodemention: MentionNodechannelRef: ChannelRefNodeserverRef: ServerRefNode@@ -169,6 +171,7 @@ declare module "mdast" {declare module "micromark-util-types" {interface TokenTypeMap {memberMention: "memberMention"+ memberMentionBoundary: "memberMentionBoundary"}}@@ -231,11 +234,80 @@ function tokenizeMemberMention(this: TokenizeContext, effects: Effects, ok: Statreturn 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 },@@ -327,7 +399,7 @@ export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(thisconst micromarkExtensions = (settings.micromarkExtensions ??= [])const fromMarkdownExtensions = (settings.fromMarkdownExtensions ??= [])micromarkExtensions.push(memberMentionSyntax())- fromMarkdownExtensions.push(memberMentionFromMarkdown())+ fromMarkdownExtensions.push(memberMentionFromMarkdown(), literalFromMarkdown())micromarkExtensions.push(spoilerSyntax())fromMarkdownExtensions.push(spoilerFromMarkdown())@@ -346,6 +418,7 @@ export const chatSyntaxPlugin: Plugin<[], Root> = function chatSyntaxPlugin(this],{ ignore: IGNORE_NODE_TYPES },)+ restoreLiteralNodes(tree)}}diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 8cb4b716d..be65a0f08 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -676,6 +676,15 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>})describe("detectMentionType", () => {+ it.each([+ "𠮷@everyone", "𠀀@everyone", "𝟙@everyone", "@everyone𠮷", "@everyone𠀀", "@everyone𝟙",+ "\\@everyone", "@everyone", "`@everyone`", "```\n@everyone\n```",+ "[@everyone](https://example.com)", "[label](https://example.com/@everyone)",+ ])("does not classify protected/literal input as a broadcast: %s", (text) => {+ expect(detectMentionType(text)).toBeUndefined()+ expect(detectMentionType(`${text}\n\n@everyone`)).toBe("everyone")+ })+it("finds @everyone as a standalone token", () => {expect(detectMentionType("hi @everyone")).toBe("everyone")})diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex 636eda87c..c1bba9c73 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -1,3 +1,4 @@+import { detectChatMentionType } from "./chat-markdown"import Mention from "@tiptap/extension-mention"import type { Editor } from "@tiptap/react"import { PluginKey } from "@tiptap/pm/state"@@ -267,30 +268,7 @@ export function buildCommunityMentionExtension(opts: {}/**- * Standalone-token scan for `@everyone`. Used at send time to set- * `mentionType` on the outgoing POST body so the server fans out to all- * members. Iterates `MENTION_TYPES`, now just `everyone`; `@here` was removed.+ * Automatic broadcasts use only genuine whole-body Markdown mention nodes.+ * Explicit API mentionType requests keep their separate broadcast contract.*/-export function detectMentionType(text: string): MentionType | undefined {- if (!text) return undefined- // Unicode-aware (`\p{L}\p{N}_-`) — must agree with the display-side regex- // in `chat-syntax-plugin.ts` and the server-side boundary check in- // `community-mentions.ts`'s `ID_CHAR_RE`, or a name like `@everyoneäx` would- // disagree across surfaces on whether the literal `@everyone` token is a- // genuine standalone mention vs. part of a longer word.- const ID = /[\p{L}\p{N}_-]/u- for (const name of MENTION_TYPES) {- let i = 0- while (i < text.length) {- const at = text.indexOf("@" + name, i)- if (at === -1) break- const before = at > 0 ? text[at - 1] : undefined- const after = text[at + 1 + name.length]- const beforeOk = before === undefined || !ID.test(before)- const afterOk = after === undefined || !ID.test(after)- if (beforeOk && afterOk) return name- i = at + 1- }- }- return undefined-}+export const detectMentionType = detectChatMentionTypediff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 6ab1fbadb..f28bb82ee 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -451,6 +451,23 @@ describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {])})+ it.each([+ "𠮷@Alex#0001", "@Alex#0001𠀀", "\\@Alex#0001", "@Alex#0001",+ "`@Alex#0001`", "```\n@Alex#0001\n```", "```\n@Alex#0001",+ "[@Alex#0001](https://example.com)", "[label](https://example.com/@Alex#0001)",+ ])("excludes protected/literal member tokens from committed targets: %s", async (content) => {+ mockGetMessage.mockResolvedValue(messageRow({ content }))+ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content },+ })+ const committed = mockCreateMessage.mock.calls.at(-1)?.[1]+ expect(committed.content).toBe(content)+ expect(committed.mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual([])+ })+it("disambiguates two same-named members via the @Name#0042 handle in the message body", async () => {mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Alex#0002, over here" }))@@ -494,6 +511,33 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-admockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])})+ it("does not enroll a protected mention, but a genuine sibling still enrolls", async () => {+ const content = "`@Bob#0001` [@Cara#0002](https://example.com) \\@Cara#0002 @Cara#0002"+ mockGetMessage.mockResolvedValue(messageRow({ content, channelId: "t1" }))+ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "srv_1" },+ body: { content },+ })+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].participants).toEqual([+ { userId: "author_1", source: "spoke" }, { userId: "cara_1", source: "mention" },+ ])+ })++ it("preserves an explicit API broadcast without a body token and clamps its audience", async () => {+ mockGetMessage.mockResolvedValue(messageRow({ content: "API broadcast", mentionType: "everyone" }))+ await createCommunityMessage({+ db: {} as never,+ authorId: "author_1",+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },+ body: { content: "API broadcast", mentionType: "everyone" },+ })+ expect(mockCreateMessage.mock.calls.at(-1)?.[1].mentions.filter((row: { kind: string }) => row.kind === "mention")).toEqual([+ { userId: "cara_1", kind: "mention" },+ ])+ })+it("drops an @mention of a non-member: no auto-add, no CHANNEL_MEMBER_ADD, no mention row", async () => {mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob" }))diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.tsindex 8b3687c80..0512f0d77 100644--- a/src/web/src/lib/community/message-handler.ts+++ b/src/web/src/lib/community/message-handler.ts@@ -1,6 +1,5 @@import {queries,- extractMentionedUserIds,isMentionType,MAX_MESSAGE_CONTENT_LENGTH,MAX_ATTACHMENTS_PER_MESSAGE,@@ -22,6 +21,7 @@ import { attachmentThumbnailUrl, attachmentUrl } from "./storage"import { broadcastToUserSafe, fanOutToChannel } from "./fanout"import { getCloudflareContext } from "@opennextjs/cloudflare"import { communityProducerContract } from "./producer-contract"+import { extractChatMentionedUserIds } from "./chat-markdown"const log = createLogger({ service: "community-message-handler" })@@ -411,7 +411,7 @@ export async function createCommunityMessage(params: {const candidates = members.filter((m) => m.userId !== authorId && m.userName).map((m) => ({ userId: m.userId, name: m.userName as string, discriminator: m.discriminator }))- for (const id of extractMentionedUserIds(content, candidates)) {+ for (const id of extractChatMentionedUserIds(content, candidates)) {mentionTargets.add(id)explicitMentionTargets.add(id)}diff --git a/src/web/src/lib/streamdown-plugins.ts b/src/web/src/lib/streamdown-plugins.tsindex 55e06a18c..3e0f00a1c 100644--- a/src/web/src/lib/streamdown-plugins.ts+++ b/src/web/src/lib/streamdown-plugins.ts@@ -1,6 +1,5 @@import { createMermaidPlugin } from "@streamdown/mermaid";-import { createMathPlugin } from "@streamdown/math";-export { cjk } from "@streamdown/cjk";+export { cjk, math } from "./streamdown-remark-plugins";export const mermaid = createMermaidPlugin({config: {@@ -26,7 +25,3 @@ export const mermaid = createMermaidPlugin({fontFamily: "ui-sans-serif, system-ui, sans-serif",},});--export const math = createMathPlugin({- singleDollarTextMath: true,-});diff --git a/src/web/src/lib/streamdown-remark-plugins.ts b/src/web/src/lib/streamdown-remark-plugins.tsnew file mode 100644index 000000000..245703641--- /dev/null+++ b/src/web/src/lib/streamdown-remark-plugins.ts@@ -0,0 +1,4 @@+import { createMathPlugin } from "@streamdown/math"+export { cjk } from "@streamdown/cjk"++export const math = createMathPlugin({ singleDollarTextMath: true })diff --git a/src/web/src/test/community-loading-geometry-lanes.test.ts b/src/web/src/test/community-loading-geometry-lanes.test.tsindex 4b0d7a07a..4610b4eee 100644--- a/src/web/src/test/community-loading-geometry-lanes.test.ts+++ b/src/web/src/test/community-loading-geometry-lanes.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vitest"import type { BrowserContext, Page } from "@playwright/test"import { runDesktopPersistedPendingGeometry } from "./e2e-ui/_fixtures/community-loading-geometry"+import { tid } from "./e2e-ui/_fixtures/testids"const steps = vi.hoisted(() => vi.fn())vi.mock("./e2e-ui/_fixtures/community-fixture", async () => {@@ -48,7 +49,7 @@ type Visit = {}type RequestRoute = { request: () => { url: () => string; method: () => string }; continue: () => Promise<void> }-function fixtureRun(failure?: "navigation" | "overflow" | "empty") {+function fixtureRun(failure?: "navigation" | "overflow" | "empty" | "ssr-duplicate" | "ssr-hidden" | "ssr-size" | "ssr-overflow") {const visits: Visit[] = [], active = new Set<string>()const originalFailure = new Error("original navigation failure")const asUser: Parameters<typeof runDesktopPersistedPendingGeometry>[1] = async (account, options) => {@@ -75,7 +76,6 @@ function fixtureRun(failure?: "navigation" | "overflow" | "empty") {fixtureLocator: true, visible: true, count,attributes: { "aria-busy": "true", "aria-label": "Loading community" },locator: () => locator(),- evaluate: async () => ({ overflow: 0, root: { x: 0, y: 0, width: visit.width, height: 900 } }),})const page = {on: (event: string, listener: (event: { url: () => string }) => void) => listeners.set(event, listener),@@ -94,7 +94,17 @@ function fixtureRun(failure?: "navigation" | "overflow" | "empty") {getByTestId: () => locator(),locator: (selector: string) => locator(selector.includes("restore-bootstrap") ? 0 : 1),waitForTimeout: async (time: number) => { visit.waits.push(time); visit.events.push("sample.wait") },- evaluate: async (callback: () => unknown) => {+ evaluate: async (callback: () => unknown, input?: unknown) => {+ if (input === tid.initialFrame) {+ const root = { visible: true, streamId: null, streamDisplay: null, display: "block", x: 0, y: 0, width: visit.width, height: 900 }+ const nodes = [root, { ...root, visible: false, streamId: "S:0", streamDisplay: "none", width: 0, height: 0 }]+ if (visits[0] === visit) {+ if (failure === "ssr-duplicate") nodes.push({ ...root })+ if (failure === "ssr-hidden") nodes.push({ ...root, visible: false, width: 0, height: 0 })+ if (failure === "ssr-size") root.width -= 1+ }+ return { nodes, overflow: failure === "ssr-overflow" && visits[0] === visit ? 3 : 0 }+ }if (!callback.toString().includes("__communityDesktopPendingFrameSamples")) return undefinedvisit.events.push("samples")if (failure === "empty" && visits[0] === visit) return []@@ -128,11 +138,14 @@ describe("geometry fixture account lanes and resource release", () => {expect(fixture.active.size).toBe(0)})- it.each(["navigation", "overflow", "empty"] as const)("releases gates and awaits the other lane before propagating %s failure", async failure => {+ it.each(["navigation", "overflow", "empty", "ssr-duplicate", "ssr-hidden", "ssr-size", "ssr-overflow"] as const)("releases gates and awaits the other lane before propagating %s failure", async failure => {const fixture = fixtureRun(failure)const error = await fixture.run().catch((error: unknown) => error)if (failure === "navigation") expect(error).toBe(fixture.originalFailure)else expect(error).toBeInstanceOf(Error)+ if (failure === "ssr-duplicate") expect(error.message).toContain("SSR must have exactly one visible initial frame")+ if (failure === "ssr-hidden") expect(error.message).toContain("Unexpected hidden SSR initial frame")+ if (failure === "ssr-size") expect(error.message).toContain("width")expect(fixture.visits.filter(v => v.account === "geometry")).toHaveLength(24)expect(fixture.visits.filter(v => v.account === "dave")).toHaveLength(1)expect(fixture.visits.every(v => v.closed && v.events.includes("script.continue") && v.events.includes("read.continue"))).toBe(true)diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.tsindex f404f6ae6..4426806fc 100644--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts@@ -60,6 +60,150 @@ test.describe("mentions — mandatory discriminator", () => {const identityKeys = ["alice", "bob", "carol"] as const+ test("whole-body Markdown keeps literal mentions inert through composer, display and consumption", async ({ caseActors }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const { serverId, channelId, bob } = await prepareCase1(actors)+ const opener = await actors.seed.seedMessage("alice", channelId, "native mention protection")+ const threadId = await actors.seed.seedThread("alice", opener, "native mention protection")+ const { page } = await actors.asUser("alice")+ await page.goto(`/c/channels/${serverId}/${threadId}`)+ const threadSurface = page.getByTestId(tid.threadSplitPanel)+ await expect(threadSurface).toHaveCount(1)+ await expect(threadSurface).toBeVisible()+ const handle = `@John Doe#${bob.discriminator}`+ const sent: Array<{ id: string; content: string; mentionType?: string }> = []++ async function participants(): Promise<string[]> {+ const response = await page.request.get(`/api/community/channels/${threadId}/members`)+ expect(response.status()).toBe(200)+ const payload = await response.json() as { members: Array<{ userId: string }> }+ return payload.members.map((member) => member.userId).sort()+ }++ async function attention(role: "bob" | "carol") {+ const response = await fetch(new URL("/api/community/users/me/attention?limit=200", page.url()), {+ headers: { Cookie: actors.sessionCookie(role) },+ })+ expect(response.status).toBe(200)+ const payload = await response.json() as {+ stale?: boolean+ truncated: boolean+ items: Array<{ kind: string; messageId?: string; scopeId?: string }>+ }+ expect(payload.stale).not.toBe(true)+ expect(payload.truncated).toBe(false)+ return payload.items.filter((item) => item.kind === "mention" && item.scopeId === threadId)+ .map((item) => item.messageId)+ }++ async function send(content: string, mentionType?: "everyone") {+ const editable = composerEditable(page, threadSurface)+ await expect(editable).toHaveCount(1)+ if (content.includes("\n")) {+ await editable.click()+ await editable.press("ControlOrMeta+A")+ await editable.press("Backspace")+ await editable.evaluate((element, text) => {+ const transfer = new DataTransfer()+ transfer.setData("text/plain", text)+ element.dispatchEvent(new ClipboardEvent("paste", {+ bubbles: true,+ cancelable: true,+ clipboardData: transfer,+ }))+ }, content)+ expect(await editable.evaluate((element) => Array.from(element.children).map((block) => ({+ tag: block.tagName,+ text: block.textContent,+ breaks: block.querySelectorAll("br").length,+ })))).toEqual(content.split("\n\n").map((block) => ({+ tag: "P",+ text: block.replaceAll("\n", ""),+ breaks: block.split("\n").length - 1,+ })))+ } else {+ await editable.fill(content)+ }+ if (content === "@everyone") {+ const popup = page.getByTestId(tid.mentionPopup)+ await expect(popup).toBeVisible()+ await editable.press("Escape")+ await expect(popup).toBeHidden()+ await expect(editable).toHaveText(content)+ await expect(editable.locator('[data-type="mention"]')).toHaveCount(0)+ }+ const [response] = await Promise.all([+ page.waitForResponse((response) => response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${threadId}/messages`),+ editable.press("Enter"),+ ])+ expect(response.status()).toBe(201)+ const outgoing = response.request().postDataJSON() as { content: string; mentionType?: string }+ expect(outgoing.content).toBe(content)+ expect(outgoing.mentionType).toBe(mentionType)+ const created = await response.json() as { message: { id: string; content: string } }+ expect(created.message.content).toBe(content)+ const persisted = await page.request.get(`/api/community/messages/${created.message.id}`)+ expect(persisted.status()).toBe(200)+ expect(await persisted.json()).toMatchObject({ id: created.message.id, content, channelId: threadId })+ const body = threadSurface.getByTestId(tid.message(created.message.id)).locator("[data-community-message-body]")+ await expect(body).toBeVisible()+ await expect(editable).toHaveText("")+ sent.push({ id: created.message.id, content, mentionType: outgoing.mentionType })+ return { id: created.message.id, body }+ }++ expect(await attention("bob")).toEqual([])+ expect(await attention("carol")).toEqual([])+ const negativeBodies = [+ `𠮷${handle} 𠀀${handle} 𝟙${handle} ${handle}𠮷 ${handle}𝟙`,+ `\\${handle} \\@everyone @John Doe#${bob.discriminator} @everyone`,+ `\`${handle} @everyone\``,+ `\`\`\`txt\n${handle} @everyone\n\`\`\``,+ `[${handle} @everyone][protected]\n\n[protected]: https://example.com/@everyone`,+ "[label](https://example.com/@everyone)",+ ]+ for (const content of negativeBodies) {+ const { body } = await send(content)+ await expect(body.locator('[title="@John Doe"], [title="@everyone"]')).toHaveCount(0)+ if (content === negativeBodies[0]) await expect(body).toHaveText(content)+ }+ expect(await participants()).toEqual([actors.userId("alice")])+ expect(await attention("bob")).toEqual([])+ expect(await attention("carol")).toEqual([])++ const positive = await send(`🎉${handle}`)+ await expect(positive.body.getByRole("button", { name: "@John Doe", exact: true })).toHaveCount(1)+ expect(await participants()).toEqual([actors.userId("alice"), actors.userId("bob")].sort())+ expect(await attention("bob")).toEqual([positive.id])+ expect(await attention("carol")).toEqual([])++ const broadcast = await send("@everyone", "everyone")+ await expect(broadcast.body.locator('[title="@everyone"]')).toHaveCount(1)+ expect(await attention("bob")).toEqual(expect.arrayContaining([positive.id, broadcast.id]))+ expect(await attention("carol")).toEqual([broadcast.id])+ expect(await participants()).toEqual([actors.userId("alice"), actors.userId("bob")].sort())++ const explicit = await page.request.post(`/api/community/channels/${threadId}/messages`, {+ data: { content: "explicit API broadcast without body token", mentionType: "everyone" },+ })+ expect(explicit.status()).toBe(201)+ const explicitBody = await explicit.json() as { message: { id: string } }+ expect(await attention("carol")).toEqual(expect.arrayContaining([broadcast.id, explicitBody.message.id]))+ expect(await participants()).toEqual([actors.userId("alice"), actors.userId("bob")].sort())+ const negativeIds = sent.slice(0, negativeBodies.length).map((message) => message.id)+ for (const role of ["bob", "carol"] as const) {+ const delivered = await attention(role)+ expect(delivered.filter((id) => negativeIds.includes(id!))).toEqual([])+ }+ await testInfo.attach("native-markdown-consumption.json", {+ body: JSON.stringify({ serverId, threadId, sent, explicitMessageId: explicitBody.message.id,+ participants: await participants(), bobMentions: await attention("bob"), carolMentions: await attention("carol") }, null, 2),+ contentType: "application/json",+ })+ })+// Types `@John`, waits for the popup, and picks the member whose row id is// `memberId` (the popup option testid keys off the row id — labels are// identical for two "John Doe"s, so text can't disambiguate). Verifies thediff --git a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.tsindex e15399263..44e8f721e 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts@@ -103,24 +103,36 @@ async function expectServerSeededRouteFrame(await expect(frame.locator('[data-slot="skeleton"], [data-community-unresolved-main]',)).not.toHaveCount(0)- const geometry = await frame.evaluate((root) => {- const rect = (element: Element) => {+ const geometry = await page.evaluate((testId) => {+ const nodes = Array.from(document.querySelectorAll(`[data-testid="${CSS.escape(testId)}"]`)).map((element) => {const box = element.getBoundingClientRect()+ const style = getComputedStyle(element)+ const stream = element.parentElement?.closest('[hidden][id^="S:"]')return {- display: getComputedStyle(element).display,+ visible: box.width > 0 && box.height > 0+ && style.visibility !== "hidden" && style.visibility !== "collapse",+ streamId: stream?.id ?? null,+ streamDisplay: stream ? getComputedStyle(stream).display : null,+ display: style.display,x: box.x,y: box.y,width: box.width,height: box.height,}- }+ })return {- root: rect(root),+ nodes,overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,}- })+ }, tid.initialFrame)+ const visibleFrames = geometry.nodes.filter((node) => node.visible)+ expect(visibleFrames, "SSR must have exactly one visible initial frame").toHaveLength(1)+ expect(+ geometry.nodes.filter((node) => !node.visible && (node.streamId === null || node.streamDisplay !== "none")),+ `Unexpected hidden SSR initial frame: ${JSON.stringify(geometry)}`,+ ).toEqual([])expect(geometry.overflow).toBe(0)- expect(geometry.root).toMatchObject({ x: 0, y: 0, width, height })+ expect(visibleFrames[0]).toMatchObject({ x: 0, y: 0, width, height })return frame}