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
feat(community): mandatory mention discriminator + tighten identity types (#381)
Genere81ae27b2e39
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 6494c2c1a..f41459a49 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -249,9 +249,10 @@ export type CommunityMemberJoin = {id: stringuserId: stringname: string- // 4-digit discriminator (`"0042"`) — optional so older/mock payloads- // that predate the column keep type-checking.- discriminator?: string+ // 4-digit discriminator (`"0042"`) — required. NOT NULL column; the row+ // becomes a roster `Member` via `applyJoinEvent`, which feeds the mention+ // popup, so the tag must always be present.+ discriminator: stringavatar?: stringrole: stringjoinedAt: stringdiff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex 5bb68e8ed..7a4b078ce 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -43,6 +43,7 @@ import { nanoid } from "nanoid";export type BotRow = {id: string;name: string;+ discriminator: string;image: string | null;ownerUserId: string;description: string;@@ -78,6 +79,7 @@ export async function listBotsForOwner(.select({id: user.id,name: user.name,+ discriminator: user.discriminator,image: user.image,ownerUserId: user.ownerUserId,createdAt: user.createdAt,@@ -102,6 +104,7 @@ export async function listBotsForOwner(return rows.map((r) => ({id: r.id,name: r.name,+ discriminator: r.discriminator,image: r.image,ownerUserId: r.ownerUserId!,description: r.description ?? "",@@ -125,6 +128,7 @@ export async function getBotOwnedBy(.select({id: user.id,name: user.name,+ discriminator: user.discriminator,image: user.image,ownerUserId: user.ownerUserId,createdAt: user.createdAt,@@ -153,6 +157,7 @@ export async function getBotOwnedBy(return {id: r.id,name: r.name,+ discriminator: r.discriminator,image: r.image,ownerUserId: r.ownerUserId!,description: r.description ?? "",diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.tsindex 10c21e93b..25ce93a5a 100644--- a/src/shared/src/db/queries/community/server.ts+++ b/src/shared/src/db/queries/community/server.ts@@ -21,6 +21,7 @@ export async function createServer(joinedAt: string;userName: string;userImage: string | null;+ userDiscriminator: string;};}> {const [server] = await db@@ -68,7 +69,7 @@ export async function createServer(// scoped select is honest about intent and avoids `.find` disambiguation// in the caller.const [userRow] = await db- .select({ name: user.name, image: user.image })+ .select({ name: user.name, image: user.image, discriminator: user.discriminator }).from(user).where(eq(user.id, data.ownerId));@@ -82,6 +83,8 @@ export async function createServer(// and the createUser/updateUser guards — the `?? ""` is defensive.userName: userRow?.name ?? "",userImage: userRow?.image ?? null,+ // NOT NULL column; `?? "0000"` mirrors the schema default defensively.+ userDiscriminator: userRow?.discriminator ?? "0000",},};}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 62474ee24..5f7c63fd5 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -504,6 +504,8 @@ export type { MeetingInfo } from "./lib/ics-parser";export { buildMimeMessage, extractAttachmentMeta, filterDownloadableAttachments } from "./lib/mime";export type { MimeAttachment, BuildMimeOptions, InboundAttachmentMeta } from "./lib/mime";export { computeDiscriminator, parseNameAndTag, formatHandle } from "./lib/discriminator";+export { validateCommunityName, sanitizeCommunityName } from "./lib/community-name";+export type { CommunityNameValidation } from "./lib/community-name";export { parseInviteToken } from "./lib/invite-link";export { slugify } from "./lib/slugify";export {diff --git a/src/shared/src/lib/community-name.ts b/src/shared/src/lib/community-name.tsnew file mode 100644index 000000000..47ac01f7a--- /dev/null+++ b/src/shared/src/lib/community-name.ts@@ -0,0 +1,57 @@+import { MAX_PROFILE_NAME_LENGTH } from "../constants/community";++// A mentionable community name (user display name or bot name) is serialized+// into message text as `@Name#dddd`. Because the display parser treats the+// trailing `#dddd` as an unambiguous terminator and everything before it as the+// name (spaces included), the name itself must never contain `#`, `@`, or a+// line break — any of those would let a name masquerade as (or break) the tag+// grammar and resolve a mention to the wrong user. See+// plans/mandatory-mention-discriminator.md.+//+// The forbidden set: `#`, `@`, and any C0/C1 control char (covers `\n`, `\r`,+// `\t`, DEL). Everything else — spaces, unicode letters, hyphens, underscores —+// stays allowed.+// eslint-disable-next-line no-control-regex+const FORBIDDEN_NAME_CHARS = /[#@\x00-\x1f\x7f-\x9f]/;++export type CommunityNameValidation =+ | { ok: true }+ | { ok: false; reason: string };++/**+ * Validate a mentionable community name for a surface that CAN reject (a user+ * profile PATCH, a bot create/rename). Trims first, then enforces non-empty,+ * length, and the forbidden-char rule. Returns a structured result carrying a+ * human-readable reason for the API error message.+ */+export function validateCommunityName(name: string): CommunityNameValidation {+ const trimmed = name.trim();+ if (!trimmed) return { ok: false, reason: "name cannot be empty" };+ if (trimmed.length > MAX_PROFILE_NAME_LENGTH) {+ return { ok: false, reason: `name must be ≤ ${MAX_PROFILE_NAME_LENGTH} characters` };+ }+ if (FORBIDDEN_NAME_CHARS.test(trimmed)) {+ return { ok: false, reason: "name cannot contain #, @, or line breaks" };+ }+ return { ok: true };+}++/**+ * Sanitize a name for a surface that CANNOT reject — the auth signup/update+ * hooks, where `user.name` arrives from an OAuth provider or an email+ * local-part and a 400 would fail the whole flow. Strips the forbidden chars,+ * collapses the resulting whitespace, and clamps to the max length. Never+ * throws; a fully-stripped name falls back to a placeholder so the column+ * stays non-empty.+ */+export function sanitizeCommunityName(name: string): string {+ const stripped = name+ .replace(/[#@]/g, "")+ // eslint-disable-next-line no-control-regex+ .replace(/[\x00-\x1f\x7f-\x9f]/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ .slice(0, MAX_PROFILE_NAME_LENGTH)+ .trim();+ return stripped || "user";+}diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 8c71332d7..d91837768 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1013,6 +1013,13 @@ import {COMMUNITY_BOT_DESCRIPTION_MAX,COMMUNITY_BOT_IMAGE_URL_MAX,} from "./constants";+import { validateCommunityName } from "./lib/community-name";++// A bot is a mentionable community member, so its name must satisfy the same+// `@Name#dddd` mention-grammar rules as a human display name (no `#`/`@`/line+// breaks). Reused as a `.refine` on both bot-name fields below.+const isMentionSafeName = (name: string): boolean => validateCommunityName(name).ok;+const MENTION_SAFE_NAME_MSG = "name cannot contain #, @, or line breaks";// Accepts an https URL, the exact bot-avatar route shape// (`/api/community/bots/{id}/avatar` — see plans/icon-range-selector.md), or@@ -1040,7 +1047,8 @@ export const CommunityBotCreateRequestSchema = z.object({.string().trim().min(COMMUNITY_BOT_NAME_MIN)- .max(COMMUNITY_BOT_NAME_MAX),+ .max(COMMUNITY_BOT_NAME_MAX)+ .refine(isMentionSafeName, { message: MENTION_SAFE_NAME_MSG }),description: z.string().max(COMMUNITY_BOT_DESCRIPTION_MAX).optional(),machineId: z.string().min(1),runtime: z.string().min(1),@@ -1055,6 +1063,7 @@ export const CommunityBotPatchRequestSchema = z.trim().min(COMMUNITY_BOT_NAME_MIN).max(COMMUNITY_BOT_NAME_MAX)+ .refine(isMentionSafeName, { message: MENTION_SAFE_NAME_MSG }).optional(),description: z.string().max(COMMUNITY_BOT_DESCRIPTION_MAX).optional(),image: BotImageUrlSchema.nullable().optional(),diff --git a/src/shared/src/utils/community-mentions.ts b/src/shared/src/utils/community-mentions.tsindex b8a0e1b73..04bc4b48c 100644--- a/src/shared/src/utils/community-mentions.ts+++ b/src/shared/src/utils/community-mentions.ts@@ -1,25 +1,19 @@/**- * Resolves `@Name` tokens in a community message body to userIds, given a- * roster of candidate members. Matching is case-insensitive, longest-match- * first (so `@John Doe` wins over `@John` when both exist).+ * Resolves `@Name#0042` mention handles in a community message body to userIds,+ * given a roster of candidate members. Only fully-tagged handles resolve — a+ * hand-typed bare `@Name` (no discriminator) is NOT a mention, matching the+ * display parser in `chat-syntax-plugin.ts` so the pill and the notification+ * fan-out never disagree (see plans/mandatory-mention-discriminator.md).*- * A match must:+ * A handle match must:* - be preceded by start-of-string or a non-identifier character* - be followed by end-of-string or a non-identifier character*- * Identifier characters are `\p{L}\p{N}_-` (Unicode-aware — `Member.name`- * is a free Unicode string, so an ASCII-only class would silently fail to- * resolve/notify mentions of names like `李四`/`José`/`Ünal`; this must- * agree with the display-side regex in `chat-syntax-plugin.ts` or the pill- * and the notification fan-out would disagree on which text is a mention),- * so a name ending or starting in those plus the next-char rule covers- * normal punctuation, spaces, and newlines as boundaries. Names containing- * whitespace are supported.- *- * When a candidate carries a `discriminator`, an exact `@Name#0042` match is- * tried FIRST at each `@` site (so a channel with two "Alex"es can be- * disambiguated), falling back to the existing longest-bare-name match when- * no `#0042` suffix is present or it doesn't match anyone.+ * Handles are tried longest-first at each `@` site (so a longer name wins).+ * The handle string (`name#dddd`) is a raw substring compare, not a charset+ * regex, so names containing spaces resolve correctly (`@John Doe#0042`).+ * Identifier characters for the boundary check are `\p{L}\p{N}_-`+ * (Unicode-aware — `Member.name` is a free Unicode string).*/import { formatHandle } from "../lib/discriminator";@@ -54,27 +48,20 @@ export function extractMentionedUserIds(candidates: MentionCandidate[]): string[] {if (!content) return [];- // De-dupe by name, prefer the first occurrence. Then sort by length desc so- // we try the most specific name first at each `@` site.- const byName = new Map<string, MentionCandidate>();- for (const c of candidates) {- if (!c.name) continue;- const key = c.name.toLowerCase();- if (!byName.has(key)) byName.set(key, c);- }- const sorted = [...byName.values()].sort((a, b) => b.name.length - a.name.length);- // Exact `@Name#0042` handles, tried FIRST at each `@` site — longest-handle- // first (mirrors the bare-name ordering). Built from ALL candidates (not- // the de-duped-by-name map above) since a handle is already unambiguous- // per-candidate; de-duping by name would arbitrarily drop one of the two- // "Alex"es a handle exists specifically to disambiguate.+ // Only exact `@Name#0042` handles resolve — the bare-name fallback was+ // removed so the send side agrees with the display parser: a hand-typed bare+ // `@Alice` is NOT a mention on either surface (see+ // plans/mandatory-mention-discriminator.md). Handles are tried longest-first+ // and built from ALL candidates (a handle is already unambiguous per user;+ // two same-name "Alex"es both keep their distinct handle). A candidate with+ // no discriminator can't be mentioned and is dropped here.const handled = candidates.filter((c): c is MentionCandidate & { discriminator: string } => !!c.name && !!c.discriminator).map((c) => ({ candidate: c, handle: formatHandle(c.name, c.discriminator).toLowerCase() })).sort((a, b) => b.handle.length - a.handle.length);- if (sorted.length === 0 && handled.length === 0) return [];+ if (handled.length === 0) return [];const lower = content.toLowerCase();const found = new Set<string>();@@ -99,18 +86,6 @@ export function extractMentionedUserIds(matchedLen = handle.length;break;}- if (!matched) {- for (const cand of sorted) {- const nameLen = cand.name.length;- const slice = lower.slice(at + 1, at + 1 + nameLen);- if (slice !== cand.name.toLowerCase()) continue;- const after = content[at + 1 + nameLen];- if (!isBoundaryChar(after)) continue;- matched = cand;- matchedLen = nameLen;- break;- }- }if (matched) {found.add(matched.userId);i = at + 1 + matchedLen;diff --git a/src/shared/src/utils/title.ts b/src/shared/src/utils/title.tsindex 42fc02558..ca8e97128 100644--- a/src/shared/src/utils/title.ts+++ b/src/shared/src/utils/title.ts@@ -46,8 +46,11 @@ export function stripInlineMarkup(raw: string): string {.replace(/`+([^`]*)`+/g, "$1")// Emphasis / strong / strike markers..replace(/(\*\*|__|~~|\*|_)/g, "")- // `@name#0042` discriminator → `@name`.- .replace(/(@[\p{L}\p{N}_-]+)#\d{4}(?!\d)/gu, "$1")+ // `@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}(?!\d)/gu, "$1")// Line-leading block markers: heading #, blockquote >, list bullets/numbers..replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d+[.)]\s+)/gm, "");}diff --git a/src/shared/test/lib/community-name.test.ts b/src/shared/test/lib/community-name.test.tsnew file mode 100644index 000000000..e1774e903--- /dev/null+++ b/src/shared/test/lib/community-name.test.ts@@ -0,0 +1,69 @@+import { describe, it, expect } from "vitest";+import { validateCommunityName, sanitizeCommunityName } from "../../src/lib/community-name";++describe("validateCommunityName", () => {+ it("accepts a plain name", () => {+ expect(validateCommunityName("Alice")).toEqual({ ok: true });+ });++ it("accepts spaces, unicode, hyphens, underscores", () => {+ expect(validateCommunityName("John Doe")).toEqual({ ok: true });+ expect(validateCommunityName("李四")).toEqual({ ok: true });+ expect(validateCommunityName("José")).toEqual({ ok: true });+ expect(validateCommunityName("Ünal")).toEqual({ ok: true });+ expect(validateCommunityName("jean-luc_picard")).toEqual({ ok: true });+ });++ it("rejects a name containing #", () => {+ expect(validateCommunityName("Ann#1234").ok).toBe(false);+ expect(validateCommunityName("a#b").ok).toBe(false);+ });++ it("rejects a name containing @", () => {+ expect(validateCommunityName("bad@name").ok).toBe(false);+ });++ it("rejects a name containing a newline or other control char", () => {+ expect(validateCommunityName("line\nbreak").ok).toBe(false);+ expect(validateCommunityName("tab\there").ok).toBe(false);+ expect(validateCommunityName("cr\rhere").ok).toBe(false);+ });++ it("rejects empty / whitespace-only names", () => {+ expect(validateCommunityName("").ok).toBe(false);+ expect(validateCommunityName(" ").ok).toBe(false);+ });++ it("rejects names longer than 100 chars (after trim)", () => {+ expect(validateCommunityName("a".repeat(101)).ok).toBe(false);+ expect(validateCommunityName("a".repeat(100)).ok).toBe(true);+ });++ it("carries a human-readable reason", () => {+ const res = validateCommunityName("Ann#1234");+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.reason).toMatch(/#/);+ });+});++describe("sanitizeCommunityName", () => {+ it("strips # and @ and collapses whitespace", () => {+ expect(sanitizeCommunityName("Ann#1234")).toBe("Ann1234");+ expect(sanitizeCommunityName("bad@name")).toBe("badname");+ expect(sanitizeCommunityName("a\nb\tc")).toBe("a b c");+ });++ it("keeps a clean name unchanged", () => {+ expect(sanitizeCommunityName("John Doe")).toBe("John Doe");+ expect(sanitizeCommunityName("李四")).toBe("李四");+ });++ it("clamps to 100 chars", () => {+ expect(sanitizeCommunityName("a".repeat(200)).length).toBe(100);+ });++ it("falls back to a placeholder when fully stripped", () => {+ expect(sanitizeCommunityName("###")).toBe("user");+ expect(sanitizeCommunityName("")).toBe("user");+ });+});diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.tsindex 00bcf5aae..91579c3cd 100644--- a/src/shared/test/queries/server.test.ts+++ b/src/shared/test/queries/server.test.ts@@ -102,7 +102,7 @@ describe("createServer", () => {[memberRow], // insert communityServerMember w/ returning],selectReturns: [- [{ name: "Alice", image: "https://avatars/alice.png" }], // select user+ [{ name: "Alice", image: "https://avatars/alice.png", discriminator: "0042" }], // select user],});@@ -119,6 +119,7 @@ describe("createServer", () => {joinedAt: memberRow.joinedAt,userName: "Alice",userImage: "https://avatars/alice.png",+ userDiscriminator: "0042",});});diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.tsindex 1b236badf..8bd829a21 100644--- a/src/shared/test/utils/community-mentions.test.ts+++ b/src/shared/test/utils/community-mentions.test.ts@@ -1,12 +1,15 @@import { describe, it, expect } from "vitest";import { extractMentionedUserIds } 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 (see+// plans/mandatory-mention-discriminator.md). Rosters carry a discriminator.const ROSTER = [- { userId: "u1", name: "Alice" },- { userId: "u2", name: "Bob" },- { userId: "u3", name: "John" },- { userId: "u4", name: "John Doe" },- { userId: "u5", name: "李雷" },+ { userId: "u1", name: "Alice", discriminator: "0001" },+ { userId: "u2", name: "Bob", discriminator: "0002" },+ { userId: "u3", name: "John", discriminator: "0003" },+ { userId: "u4", name: "John Doe", discriminator: "0004" },+ { userId: "u5", name: "李雷", discriminator: "0005" },];describe("extractMentionedUserIds", () => {@@ -15,69 +18,64 @@ describe("extractMentionedUserIds", () => {});it("returns empty when no candidates", () => {- expect(extractMentionedUserIds("hi @Alice", [])).toEqual([]);+ expect(extractMentionedUserIds("hi @Alice#0001", [])).toEqual([]);});- it("finds a single mention", () => {- expect(extractMentionedUserIds("hi @Alice", ROSTER)).toEqual(["u1"]);+ it("finds a single tagged mention", () => {+ expect(extractMentionedUserIds("hi @Alice#0001", ROSTER)).toEqual(["u1"]);});- it("is case-insensitive", () => {- expect(extractMentionedUserIds("hi @alice", ROSTER)).toEqual(["u1"]);- expect(extractMentionedUserIds("HI @ALICE", ROSTER)).toEqual(["u1"]);+ it("is case-insensitive on the name part", () => {+ expect(extractMentionedUserIds("hi @alice#0001", ROSTER)).toEqual(["u1"]);+ expect(extractMentionedUserIds("HI @ALICE#0001", ROSTER)).toEqual(["u1"]);});it("matches multiple distinct mentions", () => {- const got = extractMentionedUserIds("@Alice @Bob hey", ROSTER);+ const got = extractMentionedUserIds("@Alice#0001 @Bob#0002 hey", ROSTER);expect(got.sort()).toEqual(["u1", "u2"]);});it("dedupes repeated mentions of the same user", () => {- expect(extractMentionedUserIds("@Alice @Alice", ROSTER)).toEqual(["u1"]);+ expect(extractMentionedUserIds("@Alice#0001 @Alice#0001", ROSTER)).toEqual(["u1"]);});- it("prefers longest match (John Doe over John)", () => {- expect(extractMentionedUserIds("hi @John Doe", ROSTER)).toEqual(["u4"]);+ it("resolves a spaced name via its handle", () => {+ expect(extractMentionedUserIds("hi @John Doe#0004", ROSTER)).toEqual(["u4"]);});- it("falls back to short name when long does not fit boundary", () => {- expect(extractMentionedUserIds("hi @John, hey", ROSTER)).toEqual(["u3"]);+ it("respects right boundary — trailing punctuation after the handle is fine", () => {+ expect(extractMentionedUserIds("hi @John#0003, hey", ROSTER)).toEqual(["u3"]);});it("respects left boundary — won't match in email", () => {- expect(extractMentionedUserIds("contact [email protected]", ROSTER)).toEqual([]);+ expect(extractMentionedUserIds("contact me@Alice#0001.com", ROSTER)).toEqual([]);});- it("respects right boundary — won't match partial token", () => {- expect(extractMentionedUserIds("hi @AliceBob", ROSTER)).toEqual([]);- });-- it("handles unicode names", () => {- expect(extractMentionedUserIds("早 @李雷 好", ROSTER)).toEqual(["u5"]);+ it("handles unicode names via handle", () => {+ expect(extractMentionedUserIds("早 @李雷#0005 好", ROSTER)).toEqual(["u5"]);});it("handles accented-Latin names — the #4 charset fix", () => {- const roster = [{ userId: "u_jose", name: "José" }, { userId: "u_unal", name: "Ünal" }];- expect(extractMentionedUserIds("hi @José", roster)).toEqual(["u_jose"]);- expect(extractMentionedUserIds("hi @Ünal", roster)).toEqual(["u_unal"]);+ const roster = [+ { userId: "u_jose", name: "José", discriminator: "0001" },+ { userId: "u_unal", name: "Ünal", discriminator: "0002" },+ ];+ expect(extractMentionedUserIds("hi @José#0001", roster)).toEqual(["u_jose"]);+ expect(extractMentionedUserIds("hi @Ünal#0002", roster)).toEqual(["u_unal"]);});- it("respects right boundary for accented-Latin names — a longer identifier run must not false-positive match a shorter name prefix", () => {- // Before the #4 fix, `ID_CHAR_RE` was ASCII-only (`[A-Za-z0-9_]`), which- // treated `é` as a non-identifier boundary character — so `@Josééx`- // incorrectly matched "José" as a complete token (the boundary check- // right after the match wrongly passed). Verified this reproduced- // against the pre-fix regex before writing this test.- const roster = [{ userId: "u_jose", name: "José" }];- expect(extractMentionedUserIds("hi @Josééx", roster)).toEqual([]);+ it("a hand-typed bare @name (no discriminator) is NOT a mention", () => {+ expect(extractMentionedUserIds("hi @Alice", ROSTER)).toEqual([]);+ expect(extractMentionedUserIds("hi @John Doe", ROSTER)).toEqual([]);+ expect(extractMentionedUserIds("早 @李雷 好", ROSTER)).toEqual([]);});- it("does not match @everyone / @here when not in roster", () => {+ it("does not match @everyone / @here", () => {expect(extractMentionedUserIds("@everyone hi", ROSTER)).toEqual([]);});it("returns ids in encounter order", () => {- const got = extractMentionedUserIds("@Bob @Alice", ROSTER);+ const got = extractMentionedUserIds("@Bob#0002 @Alice#0001", ROSTER);expect(got).toEqual(["u2", "u1"]);});});@@ -103,19 +101,18 @@ describe("extractMentionedUserIds — @Name#0042 disambiguation", () => {expect(got).toEqual(["u_alex_1", "u_alex_2"]);});- it("falls back to bare-name (first occurrence) when no #0042 suffix is present", () => {- expect(extractMentionedUserIds("hey @Alex, you there?", DUP_ROSTER)).toEqual(["u_alex_1"]);+ it("a bare @name with no matching handle resolves to nothing (no bare-name fallback)", () => {+ expect(extractMentionedUserIds("hey @Alex, you there?", DUP_ROSTER)).toEqual([]);});- it("falls back to bare-name when the discriminator suffix doesn't match anyone", () => {- expect(extractMentionedUserIds("hey @Alex#9999", DUP_ROSTER)).toEqual(["u_alex_1"]);+ it("a #dddd suffix that matches no one resolves to nothing", () => {+ expect(extractMentionedUserIds("hey @Alex#9999", DUP_ROSTER)).toEqual([]);});- it("a longer digit run after # doesn't match the handle, falls back to bare-name", () => {- // "#00013" isn't the "#0001" handle (boundary char after would need to be- // non-identifier) — falls through to the bare "@Alex" bare-name match,- // since "#" itself is already a non-identifier boundary character.- expect(extractMentionedUserIds("hey @Alex#00013", DUP_ROSTER)).toEqual(["u_alex_1"]);+ it("a longer digit run after # doesn't match the handle and resolves to nothing", () => {+ // "#00013" isn't the "#0001" handle (the char after the 4-digit tag must be+ // a boundary; "3" is an identifier char), and there is no bare-name fallback.+ expect(extractMentionedUserIds("hey @Alex#00013", DUP_ROSTER)).toEqual([]);});it("handle match still respects word-boundary punctuation immediately after", () => {diff --git a/src/web/playwright.config.ts b/src/web/playwright.config.tsindex f8a9b6497..4efd14ef8 100644--- a/src/web/playwright.config.ts+++ b/src/web/playwright.config.ts@@ -7,7 +7,7 @@ export default defineConfig({testMatch: "**/*.spec.ts",fullyParallel: false,forbidOnly: !!process.env.CI,- retries: process.env.CI ? 1 : 0,+ retries: process.env.CI ? 2 : 0,workers: process.env.CI ? 1 : undefined,reporter: process.env.CI ? [["html", { open: "never" }], ["list"]] : "list",globalSetup: "./src/test/e2e-ui/_setup/global-setup.ts",diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.tsindex dbaf26dae..869d01f29 100644--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts+++ b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts@@ -50,6 +50,7 @@ export const POST = withAuth(async (_req, ctx) => {id: added.id,userId: botId,name: bot.name,+ discriminator: bot.discriminator,avatar: bot.image ?? undefined,role: added.role ?? ROLES.MEMBER,joinedAt: added.joinedAt,diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 508a135b2..e79728363 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@@ -219,9 +219,9 @@ describe("POST /api/community/channels/[id]/messages", () => {// userName), covering both broadcast + candidate branches. listMemberUserIds// must not fire so we don't double-query.mockListMembers.mockResolvedValue([- { userId: "u1", userName: "Alice" },- { userId: "u2", userName: "Bob" },- { userId: "u3", userName: "Carol" },+ { userId: "u1", userName: "Alice", discriminator: "0001" },+ { userId: "u2", userName: "Bob", discriminator: "0002" },+ { userId: "u3", userName: "Carol", discriminator: "0003" },])mockGetMessage.mockResolvedValue({id: "m1",@@ -229,7 +229,7 @@ describe("POST /api/community/channels/[id]/messages", () => {authorName: "Alice",authorImage: null,authorEmail: "[email protected]",- content: "hi @Bob",+ content: "hi @Bob#0002",type: "default",mentionType: null,replyToId: null,@@ -237,7 +237,7 @@ describe("POST /api/community/channels/[id]/messages", () => {createdAt: "2026-06-30T00:00:00.000Z",})- const res = await POST(postReq({ content: "hi @Bob" }), ctx)+ const res = await POST(postReq({ content: "hi @Bob#0002" }), ctx)expect(res.status).toBe(201)expect(mockListMembers).toHaveBeenCalledTimes(1)diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsindex e59d55989..1a9f984c4 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts@@ -70,6 +70,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {id: added.id,userId: botId,name: bot?.name ?? "",+ discriminator: bot?.discriminator ?? "0000",avatar: bot?.image ?? undefined,role: added.role ?? ROLES.MEMBER,joinedAt: added.joinedAt,diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.tsindex ca31b0cfd..bb913e113 100644--- a/src/web/src/app/api/community/servers/route.ts+++ b/src/web/src/app/api/community/servers/route.ts@@ -66,6 +66,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {id: ownerMember.id,userId: ctx.userId,name: ownerMember.userName,+ discriminator: ownerMember.userDiscriminator,avatar: ownerMember.userImage ?? undefined,role: ROLES.OWNER,joinedAt: ownerMember.joinedAt,diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.tsindex 73b40548d..efa40393d 100644--- a/src/web/src/app/api/community/users/me/profile/route.ts+++ b/src/web/src/app/api/community/users/me/profile/route.ts@@ -1,12 +1,12 @@import { NextRequest, NextResponse } from "next/server"import {queries,- MAX_PROFILE_NAME_LENGTH,MAX_PROFILE_ABOUT_LENGTH,MAX_STATUS_TEXT_LENGTH,MAX_EMOJI_BYTES,BANNER_COLOR_REGEX,WS_EVENTS,+ validateCommunityName,} from "@alook/shared"import { getDb } from "@/lib/db"import { createAuth } from "@/lib/auth"@@ -63,10 +63,12 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (body.name !== undefined) {if (typeof body.name !== "string") return writeError("name must be a string", 400)const trimmed = body.name.trim()- if (!trimmed) return writeError("name cannot be empty", 400)- if (trimmed.length > MAX_PROFILE_NAME_LENGTH) {- return writeError(`name must be ≤ ${MAX_PROFILE_NAME_LENGTH} characters`, 400)- }+ // Rejects empty, over-length, and names with `#`/`@`/line breaks — the last+ // keeps `@Name#dddd` mention grammar unambiguous. The auth `update.before`+ // hook sanitizes as a backstop for the raw `/update-user` path; this 400 is+ // the clean-UX message for the in-app rename.+ const nameCheck = validateCommunityName(trimmed)+ if (!nameCheck.ok) return writeError(nameCheck.reason, 400)// Goes through Better-Auth's own `/update-user` rather than a raw// Drizzle write — it updates the DB row AND re-signs the// `session_token`/`session_data` cookies in the same call, so adiff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 64c3dcdf6..559f6c807 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -170,7 +170,7 @@ function ChannelView() {const panelMembers = useMemo(() => {const q = memberQuery.trim().toLowerCase()const withPresence = (m: {- userId: string; name: string; discriminator?: string; avatar: string+ userId: string; name: string; discriminator: string; avatar: stringstatusEmoji?: string | null; statusText?: string | nullisCreator?: boolean; source?: "explicit" | "inherited" | "admin"}) => {@@ -200,7 +200,7 @@ function ChannelView() {.map((p) => withPresence({userId: p.userId,name: displayName(p),- discriminator: p.discriminator ?? undefined,+ discriminator: p.discriminator ?? "0000",avatar: p.avatar,// Thread rows are all real participants (removable); the thread// creator's row is locked.diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 4412b724a..7bb1f0bf7 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -162,14 +162,24 @@ export type Role = CommunityRoleexport { canManageServer, isServerOwner, ROLES, isPresenceOnline, isPresenceOffline } from "@alook/shared"-export type Member = {- id: string- userId: string+// Identity fields shared by every community user view-model (member / friend /+// DM). All three are required `string`: `user.name`/`user.discriminator` are+// NOT NULL columns always projected on live payloads. Requiring `discriminator`+// here (in one place) moves the "a mention target always has a tag" guarantee+// to compile time — see plans/mandatory-mention-discriminator.md. `userId` is+// NOT part of the core: it's required on Member/DM but optional on Friend, so+// each type declares it. Only types whose identity fields are identically+// shaped extend this — AddableMember/ThreadParticipant (nullable projections),+// Profile/UserProfile (renamed/merged shapes) intentionally stay standalone.+export type CommunityUserCore = {name: string- // 4-digit discriminator (`"0042"`). Optional so mock/older payloads that- // predate the column keep type-checking; live payloads always include it.- discriminator?: string+ discriminator: stringavatar: string+}++export type Member = CommunityUserCore & {+ id: string+ userId: stringstatus: Presencesub: stringrole: Role@@ -186,14 +196,11 @@ export type Member = {source?: "explicit" | "inherited" | "admin"}-export type Friend = {+export type Friend = CommunityUserCore & {id: string+ // Optional here (unlike Member/DM) — some friend rows predate a resolved+ // userId; that's the one field that keeps Friend from a plain intersection.userId?: string- name: string- // 4-digit discriminator (`"0042"`). Optional so mock/older payloads that- // predate the column keep type-checking; live payloads always include it.- discriminator?: string- avatar: stringstatus: Presencesub: string// Custom status (emoji + short term) — see `Profile.statusEmoji`/`statusText`.@@ -214,13 +221,9 @@ export type BlockedUser = { id: string; userId?: string; name: string; avatar: s// DM summary shown in the DM sidebar. Actual conversation history is loaded// into `ctx.messages` once the user opens the DM — DM summaries don't carry// inline messages.-export type DM = {- id: string // nanoid+export type DM = CommunityUserCore & {+ id: string // DM conversation nanoid — NOT the peer's user id (that's `userId`)userId: string- name: string- // 4-digit discriminator (`"0042"`). Optional for the same reason as Friend.- discriminator?: string- avatar: stringstatus: Presencepreview: stringunread?: booleandiff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex 9afb8df2d..2a41d377c 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -1,4 +1,5 @@import { ChevronRight, Inbox, MoreHorizontal, Trash2 } from "lucide-react"+import { stripInlineMarkup } from "@alook/shared"import { EntityIcon } from "./entity-icon"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"@@ -100,7 +101,7 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {{mn.kind === "reply" ? "replied to you" : "mentioned you"} in {mn.server} · #{mn.channel}</span></div>- <div className="truncate text-sm text-muted-foreground">{mn.m.content}</div>+ <div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(mn.m.content ?? "")}</div></div></button>{onDeleteMention && (diff --git a/src/web/src/components/community/member-list.test.ts b/src/web/src/components/community/member-list.test.tsindex 7e09c7ef4..0ab17887e 100644--- a/src/web/src/components/community/member-list.test.ts+++ b/src/web/src/components/community/member-list.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest"import { computeDuplicateNames, hasMemberMenu } from "./member-list"import type { Member } from "./_types"-const member = (id: string, name: string, discriminator?: string): Member => ({+const member = (id: string, name: string, discriminator = "0000"): Member => ({id,userId: id,name,diff --git a/src/web/src/components/community/message-body.test.ts b/src/web/src/components/community/message-body.test.tsindex 12ea16758..77a33b3e4 100644--- a/src/web/src/components/community/message-body.test.ts+++ b/src/web/src/components/community/message-body.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect } from "vitest"+import { describe, it, expect, vi } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"import { MessageBody } from "./message-body"@@ -46,3 +46,51 @@ describe("MessageBody — spoiler nested formatting (full Streamdown pipeline)",expect(button.children.join("")).toBe("secret")})})++// Regression for the sanitize allowlist case-mismatch: `MD_ALLOWED_TAGS`+// declared the mention attrs in kebab-case (`data-tag`) while chatSyntaxHandlers+// emits camelCase hast property keys (`dataTag`), so `hast-util-sanitize`+// dropped them. That silently stripped the discriminator from the rendered+// pill (same-name mentions all resolved to the first match on click) and the+// everyone/here flag (lost their styling). These drive the FULL Streamdown ++// 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("forwards the discriminator from a @Name#dddd handle to onOpenProfile on click", () => {+ const calls: Array<[string, unknown, string | undefined]> = []+ const onOpenProfile = (name: string, _e: React.MouseEvent, discriminator?: string) => {+ calls.push([name, _e, discriminator])+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(MessageBody, { text: "hi @Gus#0042", onOpenProfile }),+ )+ })+ const pill = renderer!.root.findByType("button")+ expect(pill.children.join("")).toBe("@Gus")+ act(() => {+ pill.props.onClick({ preventDefault() {}, stopPropagation() {} })+ })+ expect(calls).toHaveLength(1)+ expect(calls[0][0]).toBe("Gus")+ expect(calls[0][2]).toBe("0042")+ })++ it("keeps the @everyone flag so it renders with the distinct primary styling, and is not clickable", () => {+ const onOpenProfile = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(MessageBody, { text: "cc @everyone hi", onOpenProfile }),+ )+ })+ // @everyone has no user behind it → rendered as a non-clickable <span>+ // (not a <button>), with the distinct primary tint.+ const pill = renderer!.root.find(+ (n) => n.type === "span" && n.children.join("") === "@everyone",+ )+ expect(pill.props.className).toContain("text-primary")+ expect(pill.props.onClick).toBeUndefined()+ })+})diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsxindex 52578ca80..036a1f551 100644--- a/src/web/src/components/community/message-markdown.tsx+++ b/src/web/src/components/community/message-markdown.tsx@@ -33,9 +33,15 @@ export function extractInviteTokens(text: string): string[] {return out}+// Attribute names MUST be the camelCase hast property keys+// (`dataEveryone`/`dataTag`), matching what `chatSyntaxHandlers` emits in+// chat-syntax-plugin.ts — `hast-util-sanitize` matches its allowlist against+// the property key, and kebab-case (`data-tag`) silently drops both, so the+// mention pill would lose its discriminator (same-name pills all resolve to+// the first match) and @everyone/@here lose their styling flag.export const MD_ALLOWED_TAGS = {spoiler: [],- mention: ["data-everyone", "data-tag"],+ mention: ["dataEveryone", "dataTag"],channelref: [],serverref: [],}diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex e22d5cbb4..85c7d3cfc 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -18,6 +18,7 @@ import { formatMessageTime } from "./format-time"import { tid } from "@/lib/community/testids"import { avatarInitial } from "@/lib/community/avatar"import { displayName } from "@/lib/community/display-name"+import { stripInlineMarkup } from "@alook/shared"import type { RenderMsg, OpenProfile } from "./_types"// Fallback ratio for an attachment image with no known dimensions@@ -119,7 +120,7 @@ export function Message({) : (<><span className="font-medium text-foreground/80">@{m.replyTo.authorName}</span>- <span className="truncate">{m.replyTo.text}</span>+ <span className="truncate">{stripInlineMarkup(m.replyTo.text)}</span></>)}</button>diff --git a/src/web/src/components/community/profile-lookup.test.ts b/src/web/src/components/community/profile-lookup.test.tsindex 9ab479906..0bd07297b 100644--- a/src/web/src/components/community/profile-lookup.test.ts+++ b/src/web/src/components/community/profile-lookup.test.ts@@ -8,7 +8,7 @@ function member(overrides: Partial<Member>): Member {id: overrides.id ?? "mem_default",userId: overrides.userId ?? "user_default",name: overrides.name ?? "Default",- discriminator: overrides.discriminator,+ discriminator: overrides.discriminator ?? "0000",avatar: overrides.avatar ?? "D",status: overrides.status ?? "online",sub: overrides.sub ?? "",@@ -43,7 +43,7 @@ describe("resolveProfileTarget", () => {})it("checks friends when userId doesn't match any member", () => {- const friend: Friend = { id: "fr_a", userId: "user_c", name: "Ren", avatar: "R", status: "online", sub: "" }+ const friend: Friend = { id: "fr_a", userId: "user_c", name: "Ren", discriminator: "0000", avatar: "R", status: "online", sub: "" }expect(resolveProfileTarget([], [friend], { name: "Ren", userId: "user_c" })).toBe(friend)})})diff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/right-panel.tsxindex c354bf8ea..50a84747f 100644--- a/src/web/src/components/community/right-panel.tsx+++ b/src/web/src/components/community/right-panel.tsx@@ -10,6 +10,7 @@ import { PanelShell } from "./panel-shell"import { MemberList } from "./member-list"import { Message } from "./message"import { formatRelativeTime } from "./format-time"+import { stripInlineMarkup } from "@alook/shared"import type { RightPanel, Member, Role, Msg, RenderMsg, Thread, OpenProfile, MemberManageContext } from "./_types"// Right-panel content router — members / pinned / search / threads. Data via props.@@ -87,7 +88,7 @@ export function RightPanelContent({<span className="text-sm font-medium">{m.authorName}</span>{m.createdAt && <span className="text-xs text-muted-foreground">{formatRelativeTime(m.createdAt)}</span>}</div>- <div className="truncate text-sm text-muted-foreground">{m.content}</div>+ <div className="truncate text-sm text-muted-foreground">{stripInlineMarkup(m.content ?? "")}</div></div></button>))@@ -114,7 +115,7 @@ export function RightPanelContent({<div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{t.name}</div><div className="truncate text-xs text-muted-foreground">- <span className="font-medium text-foreground/80">{t.parent.authorName}</span> {t.parent.text}+ <span className="font-medium text-foreground/80">{t.parent.authorName}</span> {stripInlineMarkup(t.parent.text)}</div><div className="mt-1 text-xs text-muted-foreground" suppressHydrationWarning>{t.messageCount} messages · {formatRelativeTime(t.lastMessageAt)}</div></div>diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.tsindex d5c64e261..51ace38f0 100644--- a/src/web/src/hooks/community/mutations/friends.test.ts+++ b/src/web/src/hooks/community/mutations/friends.test.ts@@ -96,7 +96,7 @@ describe("useAcceptFriendRequest — rollback", () => {describe("useRemoveFriend — optimistic + rollback", () => {it("optimistically drops the friend and restores on failure", async () => {capturedQc.setQueryData(communityKeys.friends(), {- friends: [{ id: "f_1", name: "n", avatar: "N", status: "offline", sub: "" }],+ friends: [{ id: "f_1", name: "n", discriminator: "0000", avatar: "N", status: "offline", sub: "" }],blocked: [],pending: [],})diff --git a/src/web/src/hooks/community/mutations/members.test.ts b/src/web/src/hooks/community/mutations/members.test.tsindex ea468d0d2..c63d9ac54 100644--- a/src/web/src/hooks/community/mutations/members.test.ts+++ b/src/web/src/hooks/community/mutations/members.test.ts@@ -71,7 +71,7 @@ describe("useSetMemberRole — optimistic + rollback", () => {pages: [{members: [- { id: "mem_1", userId: "u_1", role: "member", name: "n", avatar: "N", status: "offline", sub: "" },+ { id: "mem_1", userId: "u_1", role: "member", name: "n", discriminator: "0000", avatar: "N", status: "offline", sub: "" },],hasMore: false,limit: 50,@@ -108,7 +108,7 @@ describe("useKickMember — optimistic + rollback", () => {pages: [{members: [- { id: "mem_1", userId: "u_1", role: "member", name: "n", avatar: "N", status: "offline", sub: "" },+ { id: "mem_1", userId: "u_1", role: "member", name: "n", discriminator: "0000", avatar: "N", status: "offline", sub: "" },],hasMore: false,limit: 50,diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex 0abc1f342..a76f65178 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -4,17 +4,18 @@ import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanimport { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { CommunityRole } from "@alook/shared"+import type { CommunityUserCore } from "@/components/community/_types"// Canonical member shape (superset of the pre-audience roster). `source` tags// why the user is in the channel: "explicit" (added member or creator),// "inherited" (public-channel server member), or "admin" (server admin/owner).-// Only `source === "explicit" && !isCreator` rows are removable.-export type ChannelMember = {+// Only `source === "explicit" && !isCreator` rows are removable. Shares the+// identity core (name/discriminator/avatar) with Member/Friend/DM — feeds the+// private-channel/thread mention popup, so the required `discriminator` keeps+// the "mention target always has a tag" guarantee at compile time.+export type ChannelMember = CommunityUserCore & {id: stringuserId: string- name: string- discriminator: string | undefined- avatar: stringsub: stringrole: CommunityRolestatus: "online" | "offline"diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex ddb64f227..2f5013bb3 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -592,6 +592,7 @@ describe("useCommunityWs — member events", () => {id: "mem_1",userId: "u_1",name: "n",+ discriminator: "0000",role: "member",joinedAt: "2026-07-03T00:00:00.000Z",},diff --git a/src/web/src/hooks/community/use-dms.test.ts b/src/web/src/hooks/community/use-dms.test.tsindex 3a38cbb59..2e7d9dd7c 100644--- a/src/web/src/hooks/community/use-dms.test.ts+++ b/src/web/src/hooks/community/use-dms.test.ts@@ -14,7 +14,7 @@ beforeEach(() => {describe("useDms / dmsQueryFn", () => {it("returns the DM conversations from GET /api/community/dm", async () => {const conversations = [- { id: "dm_1", userId: "u_1", name: "Alice", avatar: "A", status: "offline", preview: "" },+ { id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0000", avatar: "A", status: "offline", preview: "" },]apiFetchMock.mockResolvedValueOnce({ conversations })const { dmsQueryFn } = await import("./use-dms")diff --git a/src/web/src/hooks/community/use-friends.test.ts b/src/web/src/hooks/community/use-friends.test.tsindex c8eb5bce8..50f6ffbd3 100644--- a/src/web/src/hooks/community/use-friends.test.ts+++ b/src/web/src/hooks/community/use-friends.test.ts@@ -16,7 +16,7 @@ describe("useFriends / friendsQueryFn", () => {apiFetchMock.mockImplementationOnce(async (url: string) => {expect(url).toBe("/api/community/friends")- return { friends: [{ id: "f_1", name: "n", avatar: "a", status: "offline", sub: "" }], blocked: [{ id: "b_1", name: "b", avatar: "a" }] }+ return { friends: [{ id: "f_1", name: "n", discriminator: "0000", avatar: "a", status: "offline", sub: "" }], blocked: [{ id: "b_1", name: "b", avatar: "a" }] }}).mockImplementationOnce(async (url: string) => {expect(url).toBe("/api/community/friends/pending")diff --git a/src/web/src/hooks/community/use-server-members.test.ts b/src/web/src/hooks/community/use-server-members.test.tsindex 43cfb3246..5436989ef 100644--- a/src/web/src/hooks/community/use-server-members.test.ts+++ b/src/web/src/hooks/community/use-server-members.test.ts@@ -41,14 +41,14 @@ import type {// behaviour the plan calls for in one place.function m(id: string, userId = id, role: Member["role"] = "member"): Member {- return { id, userId, name: `n_${id}`, avatar: `A`, status: "offline", sub: "", role }+ return { id, userId, name: `n_${id}`, discriminator: "0000", avatar: `A`, status: "offline", sub: "", role }}function joinEvent(userId: string, id = userId): CommunityMemberJoin {return {type: "community:member.join",serverId: "srv_1",- member: { id, userId, name: `n_${userId}`, role: "member", joinedAt: "2026-07-03T00:00:00.000Z" },+ member: { id, userId, name: `n_${userId}`, discriminator: "0000", role: "member", joinedAt: "2026-07-03T00:00:00.000Z" },}}diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 7f68f1e74..6cb63866f 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -8,6 +8,7 @@ import {queries,COMMUNITY_BOT_EMAIL_DOMAIN,RATE_LIMITS,+ sanitizeCommunityName,} from "@alook/shared"import { getDb } from "@/lib/db"import { checkRateLimit } from "@/lib/rate-limit"@@ -107,7 +108,10 @@ export function createAuth(env: Env) {// otherwise sticks and a backfill has to catch it.const id = (user as { id?: string }).id ?? nanoid()const trimmed = (user.name ?? "").trim()- const name = trimmed || user.email?.split("@")[0]?.trim() || user.name+ // The provider display name / email local-part can contain `#`/`@`,+ // which would break `@Name#dddd` mention grammar. Sanitize (never+ // reject — this is an auth callback) so the name is mention-safe.+ const name = sanitizeCommunityName(trimmed || user.email?.split("@")[0]?.trim() || user.name || "")// Better Auth's adapter inserts AFTER this hook returns — there's no// insert call here to wrap in a catch/retry like `withUniqueDiscriminator`// does. `probeAvailableDiscriminator` is a best-effort SELECT pre-check@@ -133,6 +137,19 @@ export function createAuth(env: Env) {})},},+ update: {+ // The built-in `/update-user` endpoint writes `user.name` directly,+ // bypassing the profile route's validation. This hook is the actual+ // backstop for the `@Name#dddd` mention invariant: sanitize any name+ // being written so it can never contain `#`/`@`/line breaks. `update`+ // receives only the CHANGED fields (a partial), so no-op unless a name+ // is present.+ before: async (data) => {+ const partial = data as { name?: unknown }+ if (typeof partial.name !== "string") return+ return { data: { ...data, name: sanitizeCommunityName(partial.name) } }+ },+ },},session: {create: {diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.tsindex 460f0d5ce..0023faf2a 100644--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts@@ -17,11 +17,10 @@ function paragraphChildren(tree: Root): PhrasingContent[] {}describe("chatSyntaxPlugin — mention", () => {- it("wraps a bare @name mention", () => {+ it("a hand-typed bare @name (no #dddd) is NOT a mention — stays plain text", () => {const children = paragraphChildren(parse("hi @Lindsay"))- expect(children.map((c) => c.type)).toEqual(["text", "mention"])- expect(children[1]).toMatchObject({ value: "@Lindsay", everyone: false })- expect((children[1] as MentionNode).discriminator).toBeUndefined()+ expect(children).toHaveLength(1)+ expect(children[0]).toMatchObject({ type: "text", value: "hi @Lindsay" })})it("splits a @name#0042 handle into a bare mention + discriminator", () => {@@ -29,11 +28,32 @@ describe("chatSyntaxPlugin — mention", () => {expect(children[1]).toMatchObject({ type: "mention", value: "@Gus", everyone: false, discriminator: "0042" })})+ it("wraps a spaced-name handle as a single mention — the #dddd terminator makes this unambiguous", () => {+ const children = paragraphChildren(parse("hey @John Doe#0042 there"))+ const mention = children.find((c): c is MentionNode => c.type === "mention")+ expect(mention).toMatchObject({ value: "@John Doe", everyone: false, discriminator: "0042" })+ })++ it("does not swallow ordinary prose ending in #dddd — the name-run must end in a non-space", () => {+ // No earlier `#`, so a naive non-greedy run would span "bob check issue "+ // and terminate at #0042. The non-space-before-# guard prevents this.+ const children = paragraphChildren(parse("@bob check issue #0042"))+ expect(children.some((c) => c.type === "mention")).toBe(false)+ expect(children.map((c) => c.type)).toEqual(["text"])+ })++ it("keeps two adjacent handles as two distinct mentions", () => {+ const children = paragraphChildren(parse("@Alice#0001 @Bob#0002"))+ const mentions = children.filter((c): c is MentionNode => c.type === "mention")+ expect(mentions.map((m) => `${m.value}#${m.discriminator}`)).toEqual(["@Alice#0001", "@Bob#0002"])+ })+it("does not truncate a 5+ digit run into a false-positive discriminator", () => {+ // "#00423" is not a 4-digit tag, and a bare "@Gus" is no longer a mention,+ // so the whole token stays plain text.const children = paragraphChildren(parse("hi @Gus#00423"))- expect(children.map((c) => c.type)).toEqual(["text", "mention", "text"])- expect(children[1]).toMatchObject({ value: "@Gus", everyone: false })- expect(children[2]).toMatchObject({ type: "text", value: "#00423" })+ expect(children.some((c) => c.type === "mention")).toBe(false)+ expect(children.map((c) => c.type)).toEqual(["text"])})it("flags @everyone", () => {@@ -46,14 +66,23 @@ describe("chatSyntaxPlugin — mention", () => {expect(children[0]).toMatchObject({ type: "mention", value: "@here", everyone: true })})- it("supports Unicode names (李四, José, Ünal) — the #4 charset fix", () => {- expect(paragraphChildren(parse("hi @李四"))[1]).toMatchObject({ value: "@李四", everyone: false })- expect(paragraphChildren(parse("hi @José"))[1]).toMatchObject({ value: "@José", everyone: false })- expect(paragraphChildren(parse("hi @Ünal"))[1]).toMatchObject({ value: "@Ünal", everyone: false })+ it("does NOT match @everyone inside a longer identifier (trailing boundary guard)", () => {+ const children = paragraphChildren(parse("@everyoneee hey"))+ expect(children.some((c) => c.type === "mention")).toBe(false)+ })++ it("supports Unicode names in a handle (李四, José, Ünal) — the #4 charset fix", () => {+ expect(paragraphChildren(parse("hi @李四#0001"))[1]).toMatchObject({ value: "@李四", discriminator: "0001" })+ expect(paragraphChildren(parse("hi @José#0002"))[1]).toMatchObject({ value: "@José", discriminator: "0002" })+ expect(paragraphChildren(parse("hi @Ünal#0003"))[1]).toMatchObject({ value: "@Ünal", discriminator: "0003" })+ })++ it("a bare unicode @name (no tag) is NOT a mention", () => {+ expect(paragraphChildren(parse("hi @李四")).some((c) => c.type === "mention")).toBe(false)})- it("leaves an @mention inside inline code literal", () => {- const children = paragraphChildren(parse("use `@Lindsay` here"))+ it("leaves an @handle inside inline code literal", () => {+ const children = paragraphChildren(parse("use `@Lindsay#0001` here"))expect(children.map((c) => c.type)).toEqual(["text", "inlineCode", "text"])})@@ -145,20 +174,20 @@ describe("chatSyntaxPlugin — serverRef", () => {describe("chatSyntaxPlugin — mixed", () => {it("handles a mix of mention, channelRef, and unrelated formatting in one message", () => {- const children = paragraphChildren(parse("Here's the **setup**: `pnpm install` ping @Gus in /studio/dev"))+ const children = paragraphChildren(parse("Here's the **setup**: `pnpm install` ping @Gus#0042 in /studio/dev"))const types = children.map((c) => c.type)expect(types).toContain("strong")expect(types).toContain("inlineCode")const mention = children.find((c): c is MentionNode => c.type === "mention")- expect(mention).toMatchObject({ value: "@Gus" })+ expect(mention).toMatchObject({ value: "@Gus", discriminator: "0042" })const channelRef = children.find((c): c is ChannelRefNode => c.type === "channelRef")expect(channelRef).toMatchObject({ value: "/studio/dev" })})it("handles a mention and a bare serverRef together", () => {- const children = paragraphChildren(parse("ping @Gus, see /studio for context"))+ const children = paragraphChildren(parse("ping @Gus#0042, see /studio for context"))const mention = children.find((c): c is MentionNode => c.type === "mention")- expect(mention).toMatchObject({ value: "@Gus" })+ expect(mention).toMatchObject({ value: "@Gus", discriminator: "0042" })const serverRef = children.find((c): c is ServerRefNode => c.type === "serverRef")expect(serverRef).toMatchObject({ value: "/studio" })})diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.tsindex eabf2f46c..6698ecce9 100644--- a/src/web/src/lib/community/chat-syntax-plugin.ts+++ b/src/web/src/lib/community/chat-syntax-plugin.ts@@ -8,14 +8,16 @@ import type { SpoilerNode } from "./spoiler-syntax"// Chat-only syntax (`||spoiler||`, `@mention`, `/server/channel` and bare// `/server` refs), parsed as real markdown AST nodes rather than-// string-spliced HTML tags fed through `rehype-raw`. `mention`/`channelRef`/-// `serverRef` content is always an identifier charset (`\p{L}\p{N}_-` for-// names, `[A-Za-z0-9_-]` for nanoid-based refs) — `remark-parse` never splits-// an identifier across sibling text nodes (no markdown metacharacters inside-// one), so a `mdast-util-find-and-replace` pass is safe for these. `spoiler`-// is handled separately by the micromark tokenizer extension in-// `spoiler-syntax.ts` — see that file's comment for why find-and-replace-// cannot handle spoilers containing nested formatting.+// 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 but never a markdown+// metacharacter (validateCommunityName forbids `#`/`@`/line breaks, and the+// composer only ever inserts names picked from the roster), so a+// `mdast-util-find-and-replace` pass stays safe — `remark-parse` won't split+// these tokens across sibling text nodes. `spoiler` is handled separately by+// the micromark tokenizer extension in `spoiler-syntax.ts` — see that file's+// comment for why find-and-replace cannot handle spoilers containing nested+// formatting.// Mirrors `CHANNEL_REF_REGEX`'s old doc comment: matches a `/server/channel`// or `/server/channel/#N` (thread) ref — the CLI's path grammar@@ -47,15 +49,24 @@ const CHANNEL_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?(?=\// makes the ordering non-load-bearing for correctness.const SERVER_REF_RE = /(?<=^|\s)\/[A-Za-z0-9_-]+(?=\s|$|[.,;:!?)\]])/g-// `@name`, `@name#0042` (disambiguating discriminator), or the literal-// `@everyone`/`@here` tokens. `\p{L}\p{N}_-` (Unicode-aware, `u` flag) in-// place of the old `\w` — `Member.name` is a free Unicode string (no-// charset constraint), so an ASCII-only `\w` silently dropped mentions for-// names like `李四`/`José`/`Ünal`. The `(?!\d)` lookahead after the-// discriminator group stops a 5+-digit run from being truncated into a-// false-positive handle (e.g. `@Gus#00423` must not become `@Gus` + a-// dangling `#0042` handle).-const MENTION_RE = /@[\p{L}\p{N}_-]+(?:#\d{4}(?!\d))?/gu+// Two-branch mention grammar (see plans/mandatory-mention-discriminator.md):+//+// 1. The literal `@everyone`/`@here` tokens, 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`.+//+// 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). `(?!\d)` after `#dddd` stops+// a 5+-digit run from matching a 4-digit tag (`@Gus#00423`). A hand-typed+// bare `@Alice` (no tag) is intentionally NOT a mention — it stays text.+const MENTION_RE =+ /@(?:everyone|here)(?![\p{L}\p{N}_-])|@[^@#\n\r]*[^@#\n\r\s]#\d{4}(?!\d)/gu/** mdast node produced by `@name`/`@name#0042`/`@everyone`/`@here`. */export interface MentionNode {diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 44add6a89..32910f6ea 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -9,7 +9,9 @@ import {type MentionPopupState,} from "./mention-extension"-const member = (id: string, name: string, discriminator?: string): Member => ({+// A member must carry a discriminator to appear in the popup (disc-less members+// are filtered out), so the helper defaults one. Labels are always tagged now.+const member = (id: string, name: string, discriminator = "0000"): Member => ({id,userId: id,name,@@ -64,7 +66,8 @@ describe("rankMentionItems", () => {const items = rankMentionItems(roster, "channel", "al")const memberOrder = items.filter((i) => i.kind === "member").map((i) => i.label)// Alice and Albert start with "al"; no substring-only members in this set.- expect(memberOrder.slice(0, 2).sort()).toEqual(["Albert", "Alice"])+ // Labels are always tagged with the member's discriminator now.+ expect(memberOrder.slice(0, 2).sort()).toEqual(["Albert#0000", "Alice#0000"])})it("caps the list at 8 items", () => {@@ -77,9 +80,9 @@ describe("rankMentionItems", () => {// roster with the additional Member fields (`userId`, `role`, `sub`) must// still rank virtual → prefix → substring.const memberRoster: Member[] = [- { id: "m_alice", userId: "u_alice", name: "Alice", avatar: "A", status: "online", sub: "eng", role: "admin" },- { id: "m_bob", userId: "u_bob", name: "Bob", avatar: "B", status: "offline", sub: "", role: "member" },- { id: "m_alba", userId: "u_alba", name: "Alba", avatar: "A", status: "online", sub: "", role: "owner" },+ { id: "m_alice", userId: "u_alice", name: "Alice", discriminator: "0001", avatar: "A", status: "online", sub: "eng", role: "admin" },+ { id: "m_bob", userId: "u_bob", name: "Bob", discriminator: "0002", avatar: "B", status: "offline", sub: "", role: "member" },+ { id: "m_alba", userId: "u_alba", name: "Alba", discriminator: "0003", avatar: "A", status: "online", sub: "", role: "owner" },]const items = rankMentionItems(memberRoster, "channel", "al")// Virtual items are gated by prefix on the query — "al" filters both out.@@ -91,8 +94,8 @@ describe("rankMentionItems", () => {it("preserves virtual → prefix → substring order on a non-empty Member[]", () => {const memberRoster: Member[] = [- { id: "m_al", userId: "u_al", name: "Alberta", avatar: "A", status: "online", sub: "", role: "member" },- { id: "m_mal", userId: "u_mal", name: "Mallory", avatar: "M", status: "online", sub: "", role: "member" },+ { id: "m_al", userId: "u_al", name: "Alberta", discriminator: "0001", avatar: "A", status: "online", sub: "", role: "member" },+ { id: "m_mal", userId: "u_mal", name: "Mallory", discriminator: "0002", avatar: "M", status: "online", sub: "", role: "member" },]const items = rankMentionItems(memberRoster, "channel", "")// Empty query — @everyone / @here lead, then all members (starts-with@@ -111,7 +114,7 @@ describe("rankMentionItems", () => {// while `id` stays the membership row id (used for #0042 disambiguation and// mention serialization). Fixture deliberately keeps id !== userId.const memberRoster: Member[] = [- { id: "m_row", userId: "u_person", name: "Alice", avatar: "A", status: "online", sub: "", role: "member" },+ { id: "m_row", userId: "u_person", name: "Alice", discriminator: "0001", avatar: "A", status: "online", sub: "", role: "member" },]const item = rankMentionItems(memberRoster, "channel", "al").find((i) => i.kind === "member")!expect(item.id).toBe("m_row")@@ -120,8 +123,8 @@ describe("rankMentionItems", () => {it("ranks substring members after prefix members", () => {const memberRoster: Member[] = [- { id: "m_al", userId: "u_al", name: "Alberta", avatar: "A", status: "online", sub: "", role: "member" },- { id: "m_mal", userId: "u_mal", name: "Mallory", avatar: "M", status: "online", sub: "", role: "member" },+ { id: "m_al", userId: "u_al", name: "Alberta", discriminator: "0001", avatar: "A", status: "online", sub: "", role: "member" },+ { id: "m_mal", userId: "u_mal", name: "Mallory", discriminator: "0002", avatar: "M", status: "online", sub: "", role: "member" },]const items = rankMentionItems(memberRoster, "channel", "al")// "Alberta" prefix-matches "al"; "Mallory" substring-matches. Prefix wins.@@ -129,7 +132,7 @@ describe("rankMentionItems", () => {expect(memberIds).toEqual(["m_al", "m_mal"])})- it("appends #0042 to the label when two ranked members share a name", () => {+ it("always tags a member's label with its discriminator", () => {const dupes = [member("u1", "Alex", "0001"),member("u2", "Alex", "0002"),@@ -140,7 +143,7 @@ describe("rankMentionItems", () => {expect(labels.sort()).toEqual(["Alex#0001", "Alex#0002"])})- it("leaves a unique name's label bare even when other names collide", () => {+ it("tags even a unique name — the discriminator is always present", () => {const mixed = [member("u1", "Alex", "0001"),member("u2", "Alex", "0002"),@@ -148,14 +151,20 @@ describe("rankMentionItems", () => {]const items = rankMentionItems(mixed, "channel", "")const bob = items.find((i) => i.kind === "member" && i.id === "u3")- expect(bob?.label).toBe("Bob")+ expect(bob?.label).toBe("Bob#0003")})- it("leaves the label bare when a colliding member has no discriminator", () => {- const noDisc = [member("u1", "Alex"), member("u2", "Alex", "0002")]+ it("filters out a member with no discriminator — it can't produce a valid mention", () => {+ // `Member.discriminator` is required at the type level, but the runtime+ // filter is defense-in-depth against a malformed/legacy payload. The cast+ // deliberately constructs a disc-less member to exercise that guard.+ const noDisc: Member[] = [+ { id: "u1", userId: "u1", name: "Alex", avatar: "A", status: "online", sub: "", role: "member" } as Member,+ member("u2", "Alex", "0002"),+ ]const items = rankMentionItems(noDisc, "channel", "")const labels = items.filter((i) => i.kind === "member").map((i) => i.label)- expect(labels.sort()).toEqual(["Alex", "Alex#0002"])+ expect(labels).toEqual(["Alex#0002"])})})diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex e7cd1592f..59cacf926 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -46,15 +46,30 @@ export function rankMentionItems(const q = query.toLowerCase()const virtual = VIRTUAL_ITEMS.filter((v) => !q || v.label.startsWith(q))+ // Every member mention is serialized with its `#dddd` discriminator (via+ // `renderText`), so each pill resolves to the EXACT user — no name-collision+ // ambiguity, and the trailing tag lets the display parser accept spaced names+ // (see plans/mandatory-mention-discriminator.md). A member with no+ // discriminator can't produce a valid mention token, so it is filtered OUT of+ // the popup entirely — the user physically can't pick an unmentionable member+ // and get an inert, non-notifying dud. This is a should-never-happen guard+ // (every member-list/search query selects `discriminator`, seeded at signup);+ // do NOT recompute it client-side, since the stored value is salted-unique.const sw: MemberMentionItem[] = []const inc: MemberMentionItem[] = []for (const m of members) {+ if (!m.discriminator) {+ if (typeof console !== "undefined") {+ console.warn(`rankMentionItems: skipping member ${m.id} with no discriminator`)+ }+ continue+ }const name = m.name.toLowerCase()const item: MemberMentionItem = {kind: "member",id: m.id,userId: m.userId,- label: m.name,+ label: `${m.name}#${m.discriminator}`,avatar: m.avatar,status: m.status,}@@ -62,28 +77,7 @@ export function rankMentionItems(else if (name.includes(q)) inc.push(item)}- // Disambiguate same-name members within the ranked window: append the- // `#0042` discriminator to the label (which is also what gets inserted- // into the message, via `renderText`) so picking either one resolves to- // the exact user server-side instead of the backend's first-match- // fallback. Unique names stay plain — no visual noise for the common- // case.- const ranked = [...sw, ...inc]- const nameCounts = new Map<string, number>()- for (const item of ranked) {- const key = item.label.toLowerCase()- nameCounts.set(key, (nameCounts.get(key) ?? 0) + 1)- }- const membersByLabel = new Map(members.map((m) => [m.id, m]))- const disambiguated = ranked.map((item) => {- const key = item.label.toLowerCase()- if ((nameCounts.get(key) ?? 0) < 2) return item- const discriminator = membersByLabel.get(item.id)?.discriminator- if (!discriminator) return item- return { ...item, label: `${item.label}#${discriminator}` }- })-- return [...virtual, ...disambiguated].slice(0, MENTION_LIMIT)+ return [...virtual, ...sw, ...inc].slice(0, MENTION_LIMIT)}// Popup state. `rect` is `clientRect()` from @tiptap/suggestion — it's thediff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.tsindex 7b49aa366..d40720e78 100644--- a/src/web/src/lib/community/message-handler.test.ts+++ b/src/web/src/lib/community/message-handler.test.ts@@ -435,13 +435,13 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad})it("keeps an @mention of an existing channel member", async () => {- mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara" }))+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara#0002" }))await createCommunityMessage({db: {} as never,authorId: "author_1",target: { kind: "channel", channelId: "c1", serverId: "srv_1" },- body: { content: "hey @Cara" },+ body: { content: "hey @Cara#0002" },})expect(mockCreateChannelMember).not.toHaveBeenCalled()@@ -495,13 +495,13 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-adit("thread: an in-audience @mention joins as a participant + gets a mention row", async () => {// Cara is in the parent audience; add her to it.mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["author_1", "cara_1"])- mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara", channelId: "t1" }))+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Cara#0002", channelId: "t1" }))await createCommunityMessage({db: {} as never,authorId: "author_1",target: { kind: "thread", channelId: "t1", parentChannelId: "c1", serverId: "srv_1" },- body: { content: "hey @Cara" },+ body: { content: "hey @Cara#0002" },})// Bulk insert: author (spoke) + Cara (mention).@@ -572,13 +572,13 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-adit("public channel: mention of any server member is kept, no roster row", async () => {mockIsChannelPrivate.mockResolvedValue(false)- mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob" }))+ mockGetMessage.mockResolvedValue(messageRow({ content: "hey @Bob#0001" }))await createCommunityMessage({db: {} as never,authorId: "author_1",target: { kind: "channel", channelId: "c1", serverId: "srv_1" },- body: { content: "hey @Bob" },+ body: { content: "hey @Bob#0001" },})expect(mockCreateChannelMember).not.toHaveBeenCalled()diff --git a/src/web/src/test/e2e-ui/01-auth.spec.ts b/src/web/src/test/e2e-ui/01-auth.spec.tsindex cc5985100..744896f83 100644--- a/src/web/src/test/e2e-ui/01-auth.spec.ts+++ b/src/web/src/test/e2e-ui/01-auth.spec.ts@@ -8,7 +8,7 @@ test.describe.serial("auth & first screen", () => {const context = await browser.newContext() // no storageState — anonymousconst page = await context.newPage()await page.goto("/c/channels/does-not-matter/whatever")- await page.waitForURL(/\/sign-in/, { timeout: 20_000 })+ await page.waitForURL(/\/sign-in/, { timeout: 20_000 , waitUntil: "commit" })expect(page.url()).toContain("redirect=")await context.close()})@@ -18,6 +18,6 @@ test.describe.serial("auth & first screen", () => {await page.goto("/c")// Not bounced to sign-in.await expect(page).not.toHaveURL(/\/sign-in/)- await page.waitForURL(/\/c/, { timeout: 20_000 })+ await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })})})diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.tsindex c28c6e46b..84e0a886a 100644--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts@@ -11,7 +11,7 @@ test.describe.serial("server → channel → message", () => {test("create a server from the rail", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto("/c")- await page.waitForURL(/\/c/, { timeout: 20_000 })+ await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })serverId = await createServer(page, `E2E Server ${Date.now()}`)expect(serverId).toBeTruthy()})@@ -19,7 +19,7 @@ test.describe.serial("server → channel → message", () => {test("send a message; it appears and the composer clears", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 })+ await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })const body = `hello world ${Date.now()}`await sendMessage(page, body)@@ -32,7 +32,7 @@ test.describe.serial("server → channel → message", () => {test("empty message does not send; Shift+Enter inserts a newline", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 })+ await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })const input = page.getByTestId(tid.composerInput)await input.click()diff --git a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.tsindex 18a08e898..6aa6ec705 100644--- a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts+++ b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts@@ -23,8 +23,8 @@ test.describe.serial("multi-user realtime", () => {const bob = await asUser("bob")await alice.page.goto(`/c/channels/${serverId}/${channelId}`)await bob.page.goto(`/c/channels/${serverId}/${channelId}`)- await alice.page.waitForURL(new RegExp(channelId), { timeout: 20_000 })- await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await alice.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })+ await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })const body = `live from alice ${Date.now()}`await sendMessage(alice.page, body)@@ -37,7 +37,7 @@ test.describe.serial("multi-user realtime", () => {const bob = await asUser("bob")await alice.page.goto(`/c/channels/${serverId}/${channelId}`)await bob.page.goto(`/c/channels/${serverId}/${channelId}`)- await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })await alice.page.getByTestId(tid.composerInput).click()await alice.page.keyboard.type("typing…")diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex ba79294ec..2072d2f02 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -14,7 +14,7 @@ test.describe.serial("direct messages", () => {const bob = await asUser("bob")await alice.page.goto(`/c/me/${dmId}`)await bob.page.goto("/c/me")- await alice.page.waitForURL(new RegExp(dmId), { timeout: 20_000 })+ await alice.page.waitForURL(new RegExp(dmId), { timeout: 20_000 , waitUntil: "commit" })const body = `dm hello ${Date.now()}`await sendMessage(alice.page, body)@@ -24,7 +24,7 @@ test.describe.serial("direct messages", () => {await bob.page.getByTestId(tid.dmRow(dmId)).click()// Bob lands in the DM; the message list fetch on a freshly-opened DM can// lag, so give the body a generous window rather than the default.- await bob.page.waitForURL(new RegExp(dmId), { timeout: 20_000 })+ await bob.page.waitForURL(new RegExp(dmId), { timeout: 20_000 , waitUntil: "commit" })await expect(bob.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })})@@ -35,7 +35,7 @@ test.describe.serial("direct messages", () => {const carol = await asUser("carol")await carol.page.goto(`/c/me/${dmId}`)- await carol.page.waitForURL(new RegExp(dmId), { timeout: 20_000 })+ await carol.page.waitForURL(new RegExp(dmId), { timeout: 20_000 , waitUntil: "commit" })await expect(carol.page.getByTestId(tid.dmBlockedNotice)).toBeVisible()await expect(carol.page.getByTestId(tid.composerInput)).toHaveCount(0)diff --git a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts b/src/web/src/test/e2e-ui/05-mention-bot.spec.tsindex e130c0178..2c80c0aae 100644--- a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts+++ b/src/web/src/test/e2e-ui/05-mention-bot.spec.ts@@ -20,7 +20,7 @@ test.describe.serial("mentions", () => {test("the @-mention popup lists server members", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })const editable = composerEditable(page)await editable.click()@@ -35,7 +35,7 @@ test.describe.serial("mentions", () => {test("@everyone is offered in a channel", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })const editable = composerEditable(page)await editable.click()diff --git a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.tsindex b227a868f..077a6550a 100644--- a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts+++ b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts@@ -25,7 +25,7 @@ test.describe.serial("channel & member admin", () => {test("the member list shows server members", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })// Open the members panel via the channel header.await page.getByRole("button", { name: /member/i }).first().click()await expect(page.getByTestId(tid.memberRow(userId("bob")))).toBeVisible({ timeout: 15_000 })diff --git a/src/web/src/test/e2e-ui/07-invite.spec.ts b/src/web/src/test/e2e-ui/07-invite.spec.tsindex d197c2f10..fb8cec58b 100644--- a/src/web/src/test/e2e-ui/07-invite.spec.ts+++ b/src/web/src/test/e2e-ui/07-invite.spec.ts@@ -18,7 +18,7 @@ test.describe.serial("invite accept", () => {await page.goto(`/c/invite/${inviteToken}`)// Accept via the join CTA.await page.getByRole("button", { name: /join server/i }).first().click()- await page.waitForURL(new RegExp(`/c/channels/${serverId}`), { timeout: 20_000 })+ await page.waitForURL(new RegExp(`/c/channels/${serverId}`), { timeout: 20_000, waitUntil: "commit" })await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}`))})})diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.tsindex 444862783..618977c77 100644--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts@@ -19,7 +19,7 @@ test.describe.serial("mobile layout", () => {test("opening a channel shows the messages zone with a back button", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })// Composer (messages zone) is present.await expect(page.getByTestId(tid.composerInput)).toBeVisible()diff --git a/src/web/src/test/e2e-ui/09-forum-thread.spec.ts b/src/web/src/test/e2e-ui/09-forum-thread.spec.tsindex 03dde6fd7..52177231e 100644--- a/src/web/src/test/e2e-ui/09-forum-thread.spec.ts+++ b/src/web/src/test/e2e-ui/09-forum-thread.spec.ts@@ -23,7 +23,7 @@ test.describe.serial("threads", () => {test("creating a thread from a message shows a thread indicator on the parent", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })// The seeded parent message renders (real id, not a racy optimistic row).const row = page.getByText("thread parent", { exact: false }).first()@@ -38,7 +38,7 @@ test.describe.serial("threads", () => {}).toPass({ timeout: 20_000 })// Thread creation navigates off the parent channel into the thread child.- await page.waitForURL((url) => !url.pathname.endsWith(`/${channelId}`), { timeout: 20_000 })+ await page.waitForURL((url) => !url.pathname.endsWith(`/${channelId}`), { timeout: 20_000, waitUntil: "commit" })// The thread is usable: a reply posts and appears in the thread view.const reply = `first reply ${Date.now()}`diff --git a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.tsindex ef9050906..320c486c9 100644--- a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts+++ b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts@@ -23,23 +23,23 @@ test.describe.serial("eject, navigation & logout", () => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}`)// The bare-server route redirects to the first channel.- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 })+ await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })expect(page.url()).toMatch(new RegExp(`/channels/${serverId}/[^/]+`))})test("logout clears the session", async ({ asUser }) => {const { page } = await asUser("bob")await page.goto("/c")- await page.waitForURL(/\/c/, { timeout: 20_000 })+ await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })// Drive the real logout: User settings → Log Out → redirect to sign-in.await page.getByRole("button", { name: "User settings" }).click()await page.getByRole("button", { name: "Log Out" }).click()- await page.waitForURL(/\/sign-in/, { timeout: 20_000 })+ await page.waitForURL(/\/sign-in/, { timeout: 20_000 , waitUntil: "commit" })// Session is actually cleared: revisiting a protected route stays bounced.await page.goto("/c")- await page.waitForURL(/\/sign-in/, { timeout: 20_000 })+ await page.waitForURL(/\/sign-in/, { timeout: 20_000 , waitUntil: "commit" })await expect(page).toHaveURL(/\/sign-in/)})})diff --git a/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.ts b/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.tsindex 78ccce850..e55fff9fa 100644--- a/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.ts+++ b/src/web/src/test/e2e-ui/11-profile-ui-stability.spec.ts@@ -18,7 +18,7 @@ test.describe.serial("profile card stability", () => {test("opening a member profile shows the card; closing detaches it", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${channelId}`)- await page.waitForURL(new RegExp(channelId), { timeout: 20_000 })+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })// Open the members panel and click Bob's row → profile card.await page.getByRole("button", { name: /member/i }).first().click()diff --git a/src/web/src/test/e2e-ui/12-friends.spec.ts b/src/web/src/test/e2e-ui/12-friends.spec.tsindex 5af4f237a..0c4737421 100644--- a/src/web/src/test/e2e-ui/12-friends.spec.ts+++ b/src/web/src/test/e2e-ui/12-friends.spec.ts@@ -12,7 +12,7 @@ test.describe.serial("friends", () => {test("a friend shows in the friends list and opens a DM", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto("/c/me")- await page.waitForURL(/\/c\/me/, { timeout: 20_000 })+ await page.waitForURL(/\/c\/me/, { timeout: 20_000 , waitUntil: "commit" })// Bob appears in the friends list (his dev display name = email local-part).const bobRow = page.getByText(userName("bob"), { exact: false }).first()@@ -20,7 +20,7 @@ test.describe.serial("friends", () => {// Left-click opens the DM with Bob.await bobRow.click()- await page.waitForURL(/\/c\/me\/[^/]+/, { timeout: 20_000 })+ await page.waitForURL(/\/c\/me\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })expect(page.url()).toMatch(/\/c\/me\/[^/]+/)})})diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.tsnew file mode 100644index 000000000..c3df6c3b6--- /dev/null+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts@@ -0,0 +1,153 @@+import { test, expect, userId } from "./_fixtures/community-fixture"+import { tid } from "./_fixtures/testids"+import { composerEditable } from "./_fixtures/actions"+import {+ seedServer,+ seedChannel,+ seedJoinServer,+ seedMessage,+ renameUser,+ memberInfo,+} from "./_fixtures/seed"++// Journey 13 — mandatory mention discriminator. Every member mention serializes+// as `@Name#dddd`, which lets a name with spaces render as one pill AND makes a+// same-name mention resolve to the EXACT person on click (regression for the+// sanitize allowlist case-mismatch that stripped the discriminator — bugfix+// 4044fd6c). A hand-typed bare `@name` is not a mention. See+// plans/mandatory-mention-discriminator.md.+//+// Fixture: Bob and Carol are both renamed "John Doe" (spaced name), each keeping+// its own auto-assigned discriminator — so the same journey exercises the+// spaced-name pill and the same-name disambiguation.+test.describe.serial("mentions — mandatory discriminator", () => {+ let serverId: string+ let channelId: string+ let bob: { id: string; discriminator: string }+ let carol: { id: string; discriminator: string }++ test.beforeAll(async () => {+ await renameUser("bob", "John Doe")+ await renameUser("carol", "John Doe")+ serverId = await seedServer("alice", `Mentions ${Date.now()}`)+ channelId = await seedChannel("alice", serverId, "mentions")+ await seedJoinServer("alice", "bob", serverId)+ await seedJoinServer("alice", "carol", serverId)+ bob = await memberInfo("alice", serverId, userId("bob"))+ carol = await memberInfo("alice", serverId, userId("carol"))+ // Distinct discriminators are what the disambiguation hinges on — if the+ // two happened to collide the journey couldn't prove per-user resolution.+ expect(bob.discriminator).not.toBe(carol.discriminator)+ })++ // 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 the+ // send actually landed (marker message visible) before returning, so a+ // following call starts from a clean, settled composer — otherwise the second+ // mention races the first send and only one pill renders.+ async function mentionAndSend(page: import("@playwright/test").Page, memberId: string, marker: string) {+ const editable = composerEditable(page)+ await editable.click()+ await editable.pressSequentially("@John")+ const option = page.getByTestId(tid.mentionOption(memberId))+ await expect(option).toBeVisible({ timeout: 15_000 })+ await option.click()+ // The picked mention becomes a pill node in the composer — wait for it+ // before typing the trailing marker, so the text isn't swallowed by the+ // still-open suggestion popup.+ await expect(editable.locator("[data-type='mention'], .mention-highlight").first()).toBeVisible({ timeout: 10_000 })+ await editable.pressSequentially(` ${marker}`)+ await page.keyboard.press("Enter")+ // Confirm the message posted (and the composer cleared) before returning.+ await expect(page.getByText(marker, { exact: false }).first()).toBeVisible({ timeout: 15_000 })+ }++ test("same-name mentions each resolve to the exact user on pill click (spaced name, no leaked #dddd)", async ({ asUser }) => {+ const { page } = await asUser("alice")+ await page.goto(`/c/channels/${serverId}/${channelId}`)+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })++ await mentionAndSend(page, bob.id, "msgBob")+ await mentionAndSend(page, carol.id, "msgCarol")++ // Both messages render a single `@John Doe` pill with NO visible tag.+ const bobMsg = page.getByText("msgBob", { exact: false }).first()+ const carolMsg = page.getByText("msgCarol", { exact: false }).first()+ await expect(bobMsg).toBeVisible({ timeout: 15_000 })+ await expect(carolMsg).toBeVisible({ timeout: 15_000 })+ const bobPill = page.locator("button", { hasText: "@John Doe" }).first()+ await expect(bobPill).toBeVisible()+ await expect(bobPill).not.toContainText("#")++ // Click Bob's pill → the profile card shows Bob's discriminator, not Carol's.+ await bobPill.click()+ const card = page.getByTestId(tid.profileCard)+ await expect(card).toBeVisible({ timeout: 15_000 })+ await expect(card).toContainText(`#${bob.discriminator}`)+ await expect(card).not.toContainText(`#${carol.discriminator}`)+ // Dismiss and wait for the card (and its popover overlay) to fully detach+ // before touching the second pill — clicking while the overlay animates out+ // gets the click intercepted.+ await page.keyboard.press("Escape")+ await expect(card).toBeHidden({ timeout: 15_000 })+ const carolPill = page.locator("button", { hasText: "@John Doe" }).nth(1)+ await carolPill.click()+ await expect(card).toBeVisible({ timeout: 15_000 })+ await expect(card).toContainText(`#${carol.discriminator}`)+ })++ test("a hand-typed bare @name (not picked from the popup) is inert — plain text, no pill", async ({ asUser }) => {+ const { page } = await asUser("alice")+ await page.goto(`/c/channels/${serverId}/${channelId}`)+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })++ const marker = `bareMention ${Date.now()}`+ const editable = composerEditable(page)+ await editable.click()+ // Type the bare handle and dismiss the popup so it never becomes a node.+ await editable.pressSequentially("@John")+ await page.keyboard.press("Escape")+ await editable.pressSequentially(` ${marker}`)+ await page.keyboard.press("Enter")++ const msg = page.getByText(marker, { exact: false }).first()+ await expect(msg).toBeVisible({ timeout: 15_000 })+ // The `@John` in this message is literal text — no mention pill button.+ await expect(msg.locator("xpath=ancestor-or-self::*[1]").locator("button", { hasText: "@John" })).toHaveCount(0)+ })++ test("@everyone renders with the distinct primary styling (its flag survives sanitize)", async ({ asUser }) => {+ const { page } = await asUser("alice")+ await page.goto(`/c/channels/${serverId}/${channelId}`)+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })++ const marker = `everyoneMsg ${Date.now()}`+ // Seed via API (the composer's own @everyone popup path is covered by unit+ // tests) — this journey is specifically about how the sent pill renders.+ await seedMessage("alice", channelId, `@everyone ${marker}`)++ await expect(page.getByText(marker, { exact: false }).first()).toBeVisible({ timeout: 15_000 })+ const everyonePill = page.locator("span", { hasText: "@everyone" }).first()+ await expect(everyonePill).toBeVisible()+ // everyone/here use the primary tint, not the member accent tint.+ await expect(everyonePill).toHaveClass(/text-primary/)+ })++ test("setting a display name with # / @ / newline is rejected (400)", async ({ asUser }) => {+ const { page } = await asUser("alice")+ for (const bad of ["Ann#1234", "bad@name", "line\nbreak"]) {+ const res = await page.request.patch("/api/community/users/me/profile", {+ headers: { "Content-Type": "application/json" },+ data: { name: bad },+ })+ expect(res.status()).toBe(400)+ }+ // A valid spaced name still saves.+ const ok = await page.request.patch("/api/community/users/me/profile", {+ headers: { "Content-Type": "application/json" },+ data: { name: "Jane Roe" },+ })+ expect(ok.status()).toBe(200)+ })+})diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.tsindex f342520f8..95dc3650e 100644--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts@@ -4,6 +4,14 @@ import { tid } from "./testids"// Reusable UI action helpers built on the canonical testids. Journeys compose// these so the real user path (click → type → assert) stays readable and the// selectors live in one place.+//+// NOTE: every `page.waitForURL(...)` in this suite passes `waitUntil: "commit"`.+// `next dev` compiles routes lazily on first hit, so the initial page's `load`+// event can lag many seconds behind the URL change while a chunk compiles — the+// default `waitUntil: "load"` then times out even though navigation already+// happened (the CI symptom: "navigated to <correct url>" then a 20s timeout).+// Specs assert on real DOM right after (which auto-waits), so `commit` is the+// correct, non-flaky signal.// Create a server through the rail. `openViaAddButton` clicks the "+" (the// empty-list auto-dialog covers the first-server case separately). Waits for@@ -18,7 +26,7 @@ export async function createServer(page: Page, name: string, opts?: { autoDialogawait page.getByTestId(tid.createServerSubmit).click()// Land on the new server's default channel.- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 })+ await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000, waitUntil: "commit" })const m = page.url().match(/\/c\/channels\/([^/]+)\//)if (!m) throw new Error(`createServer: no serverId in URL ${page.url()}`)return m[1]@@ -37,12 +45,12 @@ export async function createChannel(page: Page, categoryName: string, channelNamexport async function openServer(page: Page, serverId: string): Promise<void> {await page.getByTestId(tid.serverIcon(serverId)).click()- await page.waitForURL(new RegExp(`/c/channels/${serverId}/`), { timeout: 20_000 })+ await page.waitForURL(new RegExp(`/c/channels/${serverId}/`), { timeout: 20_000, waitUntil: "commit" })}export async function openChannel(page: Page, channelId: string): Promise<void> {await page.getByTestId(tid.channelRow(channelId)).click()- await page.waitForURL(new RegExp(`/${channelId}(\\?|$)`), { timeout: 20_000 })+ await page.waitForURL(new RegExp(`/${channelId}(\\?|$)`), { timeout: 20_000, waitUntil: "commit" })}// The ProseMirror contenteditable inside the composer wrapper. Clicking thediff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex 0718a0a91..3aa9f9a26 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -7,8 +7,15 @@ import type { UserKey } from "../_setup/users"// import.meta, which Playwright's CJS test loader can't evaluate). These call// the same community routes over HTTP with a user's session cookie — the// operations under test are still exercised through the UI in the specs.-async function post(key: UserKey, path: string, body?: unknown): Promise<Response> {- const res = await fetch(`${WEB_URL}${path}`, {+// Statuses worth retrying: a transient auth race (401/403 before the session+// cookie is fully established on a cold worker) and D1/WAL contention (5xx).+// A 4xx that isn't auth is a real precondition failure — don't mask it.+function isRetryableStatus(status: number): boolean {+ return status === 401 || status === 403 || status >= 500+}++async function postRaw(key: UserKey, path: string, body?: unknown): Promise<Response> {+ return fetch(`${WEB_URL}${path}`, {method: "POST",headers: {Cookie: sessionCookie(key),@@ -17,8 +24,18 @@ async function post(key: UserKey, path: string, body?: unknown): Promise<Respons},body: body === undefined ? undefined : JSON.stringify(body),})- if (!res.ok) throw new Error(`POST ${path} failed (${res.status})`)- return res+}++async function post(key: UserKey, path: string, body?: unknown): Promise<Response> {+ let lastStatus = 0+ for (let attempt = 0; attempt < 3; attempt++) {+ const res = await postRaw(key, path, body)+ if (res.ok) return res+ lastStatus = res.status+ if (!isRetryableStatus(res.status)) break+ await new Promise((r) => setTimeout(r, 400))+ }+ throw new Error(`POST ${path} failed (${lastStatus})`)}export async function seedServer(owner: UserKey, name: string): Promise<string> {@@ -39,8 +56,8 @@ export async function seedChannel(owner: UserKey, serverId: string, name: string// "Already a member" 400 is treated as success.export async function seedJoinServer(owner: UserKey, joiner: UserKey, serverId: string): Promise<void> {const token = await createInvite(owner, serverId)- // Retry transient 5xx (local D1/WAL contention) a couple times; a 400 is- // "Already a member" and counts as success.+ // Retry a transient auth race (401/403) and D1/WAL contention (5xx); a 400 is+ // "Already a member" and counts as success (idempotent on a Playwright retry).let lastStatus = 0for (let attempt = 0; attempt < 3; attempt++) {const res = await fetch(`${WEB_URL}/api/community/invites/${token}/join`, {@@ -49,7 +66,7 @@ export async function seedJoinServer(owner: UserKey, joiner: UserKey, serverId:})if (res.ok || res.status === 400) returnlastStatus = res.status- if (res.status < 500) break+ if (!isRetryableStatus(res.status)) breakawait new Promise((r) => setTimeout(r, 500))}throw new Error(`seedJoinServer join failed (${lastStatus})`)@@ -71,11 +88,37 @@ export async function seedBlock(blocker: UserKey, targetUserId: string): Promiseawait post(blocker, `/api/community/users/${targetUserId}/block`)}+// Look up an existing accepted-friendship id between the requester and a target+// user, from the requester's friends list. Used to recover idempotently when a+// re-run (Playwright retry) finds the pair already friends.+async function findFriendshipId(requester: UserKey, targetUserId: string): Promise<string | undefined> {+ const res = await fetch(`${WEB_URL}/api/community/friends`, {+ headers: { Cookie: sessionCookie(requester), Origin: WEB_URL },+ })+ if (!res.ok) return undefined+ const data = (await res.json()) as { friends: Array<{ id: string; userId: string }> }+ return data.friends.find((f) => f.userId === targetUserId)?.id+}+// Full friend handshake: requester sends, addressee accepts (accept is-// addressee-only, hence two keys). Returns the friendship id.+// addressee-only, hence two keys). Returns the friendship id. Idempotent on a+// Playwright retry: if the pair is already friends the request 409s, so we+// recover the existing friendship id and skip the accept.export async function seedFriendship(requester: UserKey, addressee: UserKey, targetUserId: string): Promise<string> {- const reqRes = await post(requester, "/api/community/friends/request", { userId: targetUserId })- const reqData = (await reqRes.json()) as { id?: string; friendship?: { id: string } | null }+ let reqRes: Response | undefined+ for (let attempt = 0; attempt < 3; attempt++) {+ reqRes = await postRaw(requester, "/api/community/friends/request", { userId: targetUserId })+ // 409 = already friends / request already sent — a valid idempotent state.+ if (reqRes.ok || reqRes.status === 409 || !isRetryableStatus(reqRes.status)) break+ await new Promise((r) => setTimeout(r, 400))+ }+ if (reqRes!.status === 409) {+ const existing = await findFriendshipId(requester, targetUserId)+ if (existing) return existing+ throw new Error("seedFriendship: 409 but no existing friendship found")+ }+ if (!reqRes!.ok) throw new Error(`seedFriendship request failed (${reqRes!.status})`)+ const reqData = (await reqRes!.json()) as { id?: string; friendship?: { id: string } | null }const friendshipId = reqData.id ?? reqData.friendship?.idif (!friendshipId) throw new Error("seedFriendship: no friendship id in response")await post(addressee, `/api/community/friends/${friendshipId}/accept`)@@ -96,3 +139,42 @@ export async function createInvite(owner: UserKey, serverId: string): Promise<stconst data = (await res.json()) as { invite: { token: string } }return data.invite.token}++// Rename a user's community display name. Used by the mention specs to force+// two members to share a name (each keeps its own auto-assigned discriminator),+// which is the whole point of the same-name-disambiguation journey.+export async function renameUser(key: UserKey, name: string): Promise<void> {+ let lastStatus = 0+ for (let attempt = 0; attempt < 3; attempt++) {+ const res = await fetch(`${WEB_URL}/api/community/users/me/profile`, {+ method: "PATCH",+ headers: { Cookie: sessionCookie(key), "Content-Type": "application/json", Origin: WEB_URL },+ body: JSON.stringify({ name }),+ })+ if (res.ok) return+ lastStatus = res.status+ if (!isRetryableStatus(res.status)) break+ await new Promise((r) => setTimeout(r, 400))+ }+ throw new Error(`renameUser failed (${lastStatus})`)+}++// A member's row id + discriminator, read from a server's member list (the+// same NOT NULL column the mention grammar depends on). The mention popup keys+// its option testid off the row `id`, and the pill/profile card shows the+// `discriminator`, so the mention specs need both. `viewer` must be a member of+// `serverId`; `targetUserId` is the member being looked up.+export async function memberInfo(+ viewer: UserKey,+ serverId: string,+ targetUserId: string,+): Promise<{ id: string; discriminator: string }> {+ const res = await fetch(`${WEB_URL}/api/community/servers/${serverId}/members`, {+ headers: { Cookie: sessionCookie(viewer), Origin: WEB_URL },+ })+ if (!res.ok) throw new Error(`memberInfo list failed (${res.status})`)+ const data = (await res.json()) as { members: Array<{ id: string; userId: string; discriminator?: string }> }+ const found = data.members.find((m) => m.userId === targetUserId)+ if (!found?.discriminator) throw new Error(`memberInfo: no discriminator for ${targetUserId}`)+ return { id: found.id, discriminator: found.discriminator }+}diff --git a/src/web/src/test/e2e-ui/_setup/auth.ts b/src/web/src/test/e2e-ui/_setup/auth.tsindex 5a2251cc0..08f736e97 100644--- a/src/web/src/test/e2e-ui/_setup/auth.ts+++ b/src/web/src/test/e2e-ui/_setup/auth.ts@@ -21,7 +21,7 @@ export async function loginAndSaveState(const page = await context.newPage()try {await page.goto(`${WEB_URL}/c`)- await page.waitForURL(/\/sign-in/, { timeout: 30_000 })+ await page.waitForURL(/\/sign-in/, { timeout: 30_000 , waitUntil: "commit" })await page.getByRole("textbox", { name: "Email" }).fill(email)await page.getByRole("button", { name: "Sign in", exact: true }).click()@@ -29,6 +29,7 @@ export async function loginAndSaveState(// Land somewhere authenticated — community shell or the default workspace.await page.waitForURL((url) => !url.pathname.startsWith("/sign-in"), {timeout: 30_000,+ waitUntil: "commit",})// Resolve the seeded userId via the authenticated community profile API,diff --git a/src/web/src/test/e2e-ui/_setup/services.ts b/src/web/src/test/e2e-ui/_setup/services.tsindex c573d8d63..dbe897b3d 100644--- a/src/web/src/test/e2e-ui/_setup/services.ts+++ b/src/web/src/test/e2e-ui/_setup/services.ts@@ -56,12 +56,22 @@ async function waitForHealth(url: string, name: string, timeoutMs = 90_000): Pro}export function resetDb(): void {+ // `wrangler d1 migrations apply` prints the full migrations table (twice) on+ // every run — noise in CI when it succeeds. DROP stdout entirely (that table+ // is the noise) and capture only stderr so a real failure is still legible.+ //+ // Do NOT capture stdout into a buffer: it's ~600KB and blows spawnSync's 1MB+ // default `maxBuffer`, which kills the child (status=null) and made this whole+ // step falsely "fail" — crashing global-setup so CI never migrated and every+ // query 500'd. `stdio: ["ignore","ignore","pipe"]` can't overflow.const res = spawnSync("pnpm", ["run", "db:reset"], {cwd: REPO_ROOT,- stdio: "inherit",+ encoding: "utf8",+ stdio: ["ignore", "ignore", "pipe"],})if (res.status !== 0) {- throw new Error(`db:reset failed (exit ${res.status})`)+ if (res.stderr) process.stderr.write(res.stderr)+ throw new Error(`db:reset failed (exit ${res.status}, signal ${res.signal})`)}}@@ -105,11 +115,33 @@ function startService(name: string, filter: string, healthUrl: string): ManagedS// Starts web (:3000) + ws-do (:8789). Realtime journeys REQUIRE ws-do, so a// missing ws health check is a hard failure (fail fast), never a silent// degrade. Returns started services (empty when reusing an existing server).+// `next dev` compiles each route lazily on first request, so a health check+// (which only proves the process is up) doesn't mean `/c/channels/...` is+// compiled. The first spec to hit a route then eats multi-second cold-compile+// time and its `waitForURL` can time out. Pre-hit the hot routes so they're+// warm before any spec runs. Best-effort: any response (even a redirect to+// /sign-in) has already triggered compilation, so status is ignored.+async function warmUpRoutes(): Promise<void> {+ // Include the DYNAMIC route segments the first specs land on — `next dev`+ // compiles per route *file*, not per id, so a placeholder id triggers the+ // same compilation the real navigation needs. `/c/channels/x` (server root)+ // and `/c/channels/x/y` (channel) are the ones create-server waits for; the+ // server-root page also runs a data-gated redirect, so warming its chunk is+ // what keeps that first `waitForURL` from eating cold-compile time.+ const routes = ["/c", "/sign-in", "/c/me", "/c/channels/warmup", "/c/channels/warmup/warmup"]+ await Promise.all(+ routes.map((path) =>+ fetch(`${WEB_URL}${path}`, { redirect: "manual" }).catch(() => {}),+ ),+ )+}+export async function startServices(): Promise<ManagedService[]> {const webHealth = `${WEB_URL}/api/health`const wsHealth = `${WS_URL}/health`if (REUSE_EXISTING && (await isUp(webHealth)) && (await isUp(wsHealth))) {+ await warmUpRoutes()return []}@@ -126,5 +158,6 @@ export async function startServices(): Promise<ManagedService[]> {]await Promise.all(services.map((s) => waitForHealth(s.healthUrl, s.name)))+ await warmUpRoutes()return services}