Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): complete mention candidate pagination (#564)
Gener6938c5bd41ad
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex e88e2f2a5..79e510657 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -39,6 +39,7 @@ export const SPEC_SECONDS = {"29-community-bot-avatar-cleanup.spec.ts": 15,"29-multi-device-read-state.spec.ts": 45,"30-bot-profile-audit-preview.spec.ts": 35,+ "31-mention-candidate-pagination.spec.ts": 10,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 6801f0ab9..8ce624d6f 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -70,7 +70,7 @@ describe("planE2eShards", () => {expect(first).toHaveLength(E2E_SHARD_COUNT)expect([...assigned].sort()).toEqual(specs)expect(new Set(assigned).size).toBe(specs.length)- expect(totals.sort((left, right) => left - right)).toEqual([218, 219, 219, 219, 223])+ expect(totals.sort((left, right) => left - right)).toEqual([220, 220, 220, 224, 224])expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)})diff --git a/src/shared/src/db/queries/community/member.ts b/src/shared/src/db/queries/community/member.tsindex 4f2dfc24e..4bbc26888 100644--- a/src/shared/src/db/queries/community/member.ts+++ b/src/shared/src/db/queries/community/member.ts@@ -1,4 +1,4 @@-import { eq, and, ne, inArray, count, asc, or, gt, like, isNull, sql } from "drizzle-orm";+import { eq, and, ne, inArray, count, asc, or, gt, isNull, sql } from "drizzle-orm";import { communityServerMember, communityUserProfile } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -280,7 +280,7 @@ export async function searchMembers(db: Database,serverId: string,q: string,- opts?: { limit?: number }+ opts?: { limit?: number; cursor?: { name: string; id: string } }) {const rawLimit = opts?.limit ?? MAX_MEMBERS_PAGE_SIZE;const limit = Math.max(1, Math.min(rawLimit, MAX_MEMBERS_PAGE_SIZE));@@ -288,7 +288,26 @@ export async function searchMembers(// single "%" in the query matches every row.const pattern = `${escapeLikePattern(q)}%`;- return db+ const conditions = [+ eq(communityServerMember.serverId, serverId),+ or(+ sql`${user.name} LIKE ${pattern} ESCAPE '\\'`,+ sql`${user.email} LIKE ${pattern} ESCAPE '\\'`+ )!,+ ];+ if (opts?.cursor) {+ conditions.push(+ or(+ gt(user.name, opts.cursor.name),+ and(+ eq(user.name, opts.cursor.name),+ gt(communityServerMember.id, opts.cursor.id),+ ),+ )!,+ );+ }++ const rows = await db.select({id: communityServerMember.id,serverId: communityServerMember.serverId,@@ -305,17 +324,18 @@ export async function searchMembers(.from(communityServerMember).innerJoin(user, eq(communityServerMember.userId, user.id)).leftJoin(communityUserProfile, eq(communityUserProfile.userId, user.id))- .where(- and(- eq(communityServerMember.serverId, serverId),- or(- like(user.name, pattern),- like(user.email, pattern)- )- )- )+ .where(and(...conditions)).orderBy(asc(user.name), asc(communityServerMember.id))- .limit(limit);+ .limit(limit + 1);++ const hasMore = rows.length > limit;+ const members = hasMore ? rows.slice(0, limit) : rows;+ const last = members[members.length - 1];+ const cursor = hasMore && last+ ? { name: last.userName, id: last.id }+ : undefined;++ return { members, hasMore, cursor };}export async function getMember(db: Database, serverId: string, userId: string) {diff --git a/src/shared/test/queries/community-member-search-sqlite.test.ts b/src/shared/test/queries/community-member-search-sqlite.test.tsnew file mode 100644index 000000000..c6d63ee7f--- /dev/null+++ b/src/shared/test/queries/community-member-search-sqlite.test.ts@@ -0,0 +1,75 @@+import Sqlite from "better-sqlite3"+import { drizzle } from "drizzle-orm/better-sqlite3"+import { afterEach, beforeEach, describe, expect, it } from "vitest"++import type { Database } from "../../src/db"+import { searchMembers } from "../../src/db/queries/community/member"++describe("searchMembers literal prefixes against real SQLite", () => {+ let sqlite: Sqlite.Database+ let db: Database++ beforeEach(() => {+ sqlite = new Sqlite(":memory:")+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ email TEXT NOT NULL UNIQUE,+ image TEXT,+ isBot INTEGER NOT NULL DEFAULT 0,+ ownerUserId TEXT,+ discriminator TEXT NOT NULL DEFAULT '0000'+ );+ CREATE TABLE community_server_member (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ role TEXT DEFAULT 'member',+ joined_at TEXT NOT NULL+ );+ CREATE TABLE community_user_profile (+ user_id TEXT PRIMARY KEY,+ status_emoji TEXT,+ status_text TEXT DEFAULT ''+ );+ `)+ db = drizzle(sqlite) as unknown as Database++ const insertUser = sqlite.prepare(`+ INSERT INTO user (id, name, email, discriminator)+ VALUES (?, ?, ?, ?)+ `)+ const insertMember = sqlite.prepare(`+ INSERT INTO community_server_member+ (id, server_id, user_id, joined_at)+ VALUES (?, 'srv_1', ?, '2026-01-01T00:00:00.000Z')+ `)+ const names = [+ "Literal%Percent",+ "Literal_Underscore",+ "Literal\\Slash",+ "LiteralXDecoy",+ "PlainAlice",+ "PlainBob",+ "XPlain",+ ]+ names.forEach((name, index) => {+ const id = `u_${index}`+ insertUser.run(id, name, `${id}@example.com`, String(index).padStart(4, "0"))+ insertMember.run(`m_${index}`, id)+ })+ })++ afterEach(() => sqlite.close())++ it.each([+ ["Literal%", ["Literal%Percent"]],+ ["Literal_", ["Literal_Underscore"]],+ ["Literal\\", ["Literal\\Slash"]],+ ["Plain", ["PlainAlice", "PlainBob"]],+ ])("treats %s as a literal prefix", async (query, expected) => {+ const page = await searchMembers(db, "srv_1", query)+ expect(page.members.map((member) => member.userName)).toEqual(expected)+ })+})diff --git a/src/shared/test/queries/community-member.test.ts b/src/shared/test/queries/community-member.test.tsindex 23d7e4d3b..f180a8785 100644--- a/src/shared/test/queries/community-member.test.ts+++ b/src/shared/test/queries/community-member.test.ts@@ -238,18 +238,18 @@ describe("searchMembers", () => {const rowsForAli = [{ id: "m1", userName: "Alice" }, { id: "m2", userName: "Alicia" }];const dbAli = createSearchMock(rowsForAli);const resAli = await memberQueries.searchMembers(dbAli, "srv_1", "Ali");- expect(resAli.map((r) => r.userName)).toEqual(["Alice", "Alicia"]);+ expect(resAli.members.map((r) => r.userName)).toEqual(["Alice", "Alicia"]);const rowsForBob = [{ id: "m3", userName: "Bob" }];const dbBob = createSearchMock(rowsForBob);const resBob = await memberQueries.searchMembers(dbBob, "srv_1", "Bob");- expect(resBob.map((r) => r.userName)).toEqual(["Bob"]);+ expect(resBob.members.map((r) => r.userName)).toEqual(["Bob"]);- // Fixture with no prefix match — DB returns [], hook returns []. This+ // Fixture with no prefix match — DB returns an empty page. This// pins prefix semantics: "li" should NOT match "Alice"/"Alicia".const dbNone = createSearchMock([]);const resNone = await memberQueries.searchMembers(dbNone, "srv_1", "li");- expect(resNone).toEqual([]);+ expect(resNone).toEqual({ members: [], hasMore: false, cursor: undefined });});it("orders by user.name ASC then id ASC", async () => {@@ -263,13 +263,13 @@ describe("searchMembers", () => {it("clamps limit above MAX_MEMBERS_PAGE_SIZE down to the cap", async () => {const db = createSearchMock([]);await memberQueries.searchMembers(db, "srv_1", "A", { limit: MAX_MEMBERS_PAGE_SIZE + 5000 });- expect(db.limit).toHaveBeenCalledWith(MAX_MEMBERS_PAGE_SIZE);+ expect(db.limit).toHaveBeenCalledWith(MAX_MEMBERS_PAGE_SIZE + 1);});it("defaults to MAX_MEMBERS_PAGE_SIZE when limit omitted", async () => {const db = createSearchMock([]);await memberQueries.searchMembers(db, "srv_1", "A");- expect(db.limit).toHaveBeenCalledWith(MAX_MEMBERS_PAGE_SIZE);+ expect(db.limit).toHaveBeenCalledWith(MAX_MEMBERS_PAGE_SIZE + 1);});it("leftJoins communityUserProfile and passes through statusEmoji/statusText", async () => {@@ -278,7 +278,7 @@ describe("searchMembers", () => {]);const res = await memberQueries.searchMembers(db, "srv_1", "Ali");expect(db.leftJoin).toHaveBeenCalledTimes(1);- expect(res[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" });+ expect(res.members[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" });});it("escapes % and _ wildcards in the query string (LIKE escape)", async () => {@@ -300,7 +300,7 @@ describe("searchMembers", () => {{ id: "m2", userId: "u_blocked_by_caller", userName: "Alicia" },]);const res = await memberQueries.searchMembers(db, "srv_1", "Ali");- expect(res.map((r) => r.id)).toEqual(["m1", "m2"]);+ expect(res.members.map((r) => r.id)).toEqual(["m1", "m2"]);});it("rows carry the user's discriminator", async () => {@@ -309,7 +309,31 @@ describe("searchMembers", () => {{ id: "m2", userName: "Alex", discriminator: "0002" },]);const res = await memberQueries.searchMembers(db, "srv_1", "Alex");- expect(res.map((r) => r.discriminator)).toEqual(["0001", "0002"]);+ expect(res.members.map((r) => r.discriminator)).toEqual(["0001", "0002"]);+ });++ it("returns a stable name/id cursor and slices off the probe row", async () => {+ const db = createSearchMock([+ { id: "m1", userName: "Alex" },+ { id: "m2", userName: "Alex" },+ { id: "m3", userName: "Alicia" },+ ]);+ const res = await memberQueries.searchMembers(db, "srv_1", "Al", { limit: 2 });+ expect(db.limit).toHaveBeenCalledWith(3);+ expect(res.members.map((row) => row.id)).toEqual(["m1", "m2"]);+ expect(res).toMatchObject({+ hasMore: true,+ cursor: { name: "Alex", id: "m2" },+ });+ });++ it("adds the same-name cursor boundary to the scoped search", async () => {+ const db = createSearchMock([]);+ await memberQueries.searchMembers(db, "srv_1", "Alex", {+ cursor: { name: "Alex", id: "m200" },+ });+ expect(db.where).toHaveBeenCalledTimes(1);+ expect(db.orderBy).toHaveBeenCalledTimes(1);});});diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.test.tsindex 8aa8431b2..fccdb96bc 100644--- a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts@@ -40,6 +40,7 @@ vi.mock("@/lib/middleware/helpers", () => {import { GET } from "./route"import { MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"+import { encodeMemberSearchCursor } from "@/lib/community/member-search-cursor"function getReq(query: string) {return new NextRequest(`http://localhost/api/community/servers/srv_1/members/search${query}`, { method: "GET" })@@ -68,27 +69,44 @@ describe("GET /api/community/servers/[id]/members/search", () => {mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", serverId: "srv_1", role: "member" })})- it("returns matched members as display shape with { members, limit } envelope", async () => {- mockSearchMembers.mockResolvedValue([buildRow(1, "Alice"), buildRow(2, "Alicia")])+ it("returns matched members as a backward-compatible paginated envelope", async () => {+ mockSearchMembers.mockResolvedValue({+ members: [buildRow(1, "Alice"), buildRow(2, "Alicia")],+ hasMore: false,+ cursor: undefined,+ })const res = await GET(getReq("?q=Ali"), ctx)expect(res.status).toBe(200)- const body = await res.json() as { members: Array<{ id: string; name: string }>; limit: number }+ const body = await res.json() as {+ members: Array<{ id: string; name: string }>+ limit: number+ hasMore: boolean+ cursor?: string+ }expect(body.members.map((m) => m.name)).toEqual(["Alice", "Alicia"])expect(body.limit).toBe(MAX_MEMBERS_PAGE_SIZE)+ expect(body.hasMore).toBe(false)+ expect(body.cursor).toBeUndefined()})it("includes each member's discriminator in the response", async () => {- mockSearchMembers.mockResolvedValue([buildRow(1, "Alex"), buildRow(2, "Alex")])+ mockSearchMembers.mockResolvedValue({+ members: [buildRow(1, "Alex"), buildRow(2, "Alex")],+ hasMore: false,+ })const res = await GET(getReq("?q=Alex"), ctx)const body = await res.json() as { members: Array<{ discriminator?: string }> }expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])})it("includes statusEmoji/statusText, defaulting for a user with no profile row", async () => {- mockSearchMembers.mockResolvedValue([- { ...buildRow(1, "Alex"), statusEmoji: "🎮", statusText: "Gaming" },- { ...buildRow(2, "Alex"), statusEmoji: null, statusText: null },- ])+ mockSearchMembers.mockResolvedValue({+ members: [+ { ...buildRow(1, "Alex"), statusEmoji: "🎮", statusText: "Gaming" },+ { ...buildRow(2, "Alex"), statusEmoji: null, statusText: null },+ ],+ hasMore: false,+ })const res = await GET(getReq("?q=Alex"), ctx)const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string }> }expect(body.members[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" })@@ -97,9 +115,12 @@ describe("GET /api/community/servers/[id]/members/search", () => {it("never emits isBot/ownerUserId (no bot gating on search — byte-identical)", async () => {// Even if a row carried bot columns, search passes them through as humans.- mockSearchMembers.mockResolvedValue([- { ...buildRow(1, "Botty"), userId: "own_bot", userIsBot: true, userOwnerUserId: "u1" },- ])+ mockSearchMembers.mockResolvedValue({+ members: [+ { ...buildRow(1, "Botty"), userId: "own_bot", userIsBot: true, userOwnerUserId: "u1" },+ ],+ hasMore: false,+ })const res = await GET(getReq("?q=Bot"), ctx)const body = await res.json() as { members: Array<{ isBot?: boolean; ownerUserId?: string }> }expect(body.members[0].isBot).toBeUndefined()@@ -128,7 +149,7 @@ describe("GET /api/community/servers/[id]/members/search", () => {})it("clamps limit param to MAX_MEMBERS_PAGE_SIZE", async () => {- mockSearchMembers.mockResolvedValue([])+ mockSearchMembers.mockResolvedValue({ members: [], hasMore: false })const res = await GET(getReq(`?q=A&limit=9999`), ctx)expect(res.status).toBe(200)const body = await res.json() as { limit: number }@@ -138,9 +159,46 @@ describe("GET /api/community/servers/[id]/members/search", () => {})it("forwards q verbatim to the query (LIKE-escape happens inside the query)", async () => {- mockSearchMembers.mockResolvedValue([])+ mockSearchMembers.mockResolvedValue({ members: [], hasMore: false })await GET(getReq(`?q=${encodeURIComponent("50%_off")}`), ctx)const call = mockSearchMembers.mock.calls[0]expect(call[2]).toBe("50%_off")})++ it("encodes and forwards the stable same-name cursor", async () => {+ mockSearchMembers.mockResolvedValue({+ members: [buildRow(2, "Alex")],+ hasMore: true,+ cursor: { name: "Alex", id: "mem_2" },+ })+ const first = await GET(getReq("?q=Alex&limit=1"), ctx)+ const firstBody = await first.json() as { cursor: string; hasMore: boolean }+ expect(firstBody.hasMore).toBe(true)+ expect(firstBody.cursor).toBeTruthy()++ mockSearchMembers.mockResolvedValue({ members: [], hasMore: false })+ await GET(getReq(`?q=Alex&cursor=${encodeURIComponent(firstBody.cursor)}`), ctx)+ expect(mockSearchMembers.mock.calls[1][3]).toMatchObject({+ cursor: { name: "Alex", id: "mem_2" },+ })+ })++ it("rejects malformed and cross-query cursors before querying", async () => {+ const malformed = await GET(getReq("?q=Alex&cursor=invalid"), ctx)+ expect(malformed.status).toBe(400)+ expect(mockSearchMembers).not.toHaveBeenCalled()++ const crossQuery = encodeMemberSearchCursor({+ serverId: "srv_1",+ query: "Alice",+ name: "Alice",+ id: "mem_1",+ })+ const cross = await GET(+ getReq(`?q=Bob&cursor=${encodeURIComponent(crossQuery)}`),+ ctx,+ )+ expect(cross.status).toBe(400)+ expect(mockSearchMembers).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.tsindex f3f62abb1..c1fb10ca9 100644--- a/src/web/src/app/api/community/servers/[id]/members/search/route.ts+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.ts@@ -5,6 +5,10 @@ import { queries, MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"import { requireServerMember } from "@/lib/community/permissions"import { parseBoundedInt } from "@/lib/community/messages"import { mapMemberForApi } from "@/lib/community/member-payload"+import {+ encodeMemberSearchCursor,+ parseMemberSearchCursor,+} from "@/lib/community/member-search-cursor"export const GET = withAuth(async (req, ctx) => {const serverId = ctx.params?.id@@ -23,11 +27,27 @@ export const GET = withAuth(async (req, ctx) => {MAX_MEMBERS_PAGE_SIZE,MAX_MEMBERS_PAGE_SIZE,)+ const cursor = parseMemberSearchCursor(+ url.searchParams.get("cursor"),+ { serverId, query: q },+ )+ if (cursor === null) return writeError("invalid cursor", 400)- const rows = await queries.communityMember.searchMembers(db, serverId, q, { limit })+ const page = await queries.communityMember.searchMembers(db, serverId, q, {+ limit,+ cursor,+ })// No bot gating here — `searchMembers` never selected the bot columns and this// route never emitted `isBot`/`ownerUserId`. Byte-identical to before.- const members = rows.map((r) => mapMemberForApi(r, ctx.userId))+ const members = page.members.map((r) => mapMemberForApi(r, ctx.userId))+ const nextCursor = page.cursor+ ? encodeMemberSearchCursor({+ serverId,+ query: q,+ name: page.cursor.name,+ id: page.cursor.id,+ })+ : undefined- return writeJSON({ members, limit })+ return writeJSON({ members, limit, hasMore: page.hasMore, cursor: nextCursor })})diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.tsindex c5115577d..1b3d25645 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts@@ -43,7 +43,7 @@ const {},mockMemberViewModel: {composerMembers: [],- onSearchComposerMembers: vi.fn(),+ composerMentionCandidates: undefined,memberPanelProps: { members: [] },manageMembersDialog: null,resolveUserName: (userId: string) => userId,diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex cda1e77bc..12c8bc885 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -96,7 +96,7 @@ export function ChannelRoute({ serverParam, channelId }: {})const {composerMembers,- onSearchComposerMembers,+ composerMentionCandidates,memberPanelProps,manageMembersDialog,resolveUserName,@@ -213,7 +213,7 @@ export function ChannelRoute({ serverParam, channelId }: {onSetNotificationLevel={setNotificationLevel}onBack={bp === "mobile" ? goBack : undefined}composerMembers={composerMembers}- onSearchComposerMembers={onSearchComposerMembers}+ composerMentionCandidates={composerMentionCandidates}channelRefCandidates={channelRefCandidates}memberPanelProps={memberPanelProps}manageMembersDialog={manageMembersDialog}@@ -241,7 +241,7 @@ export function ChannelRoute({ serverParam, channelId }: {onSetNotificationLevel={setNotificationLevel}onBack={bp === "mobile" ? goBack : undefined}composerMembers={composerMembers}- onSearchComposerMembers={onSearchComposerMembers}+ composerMentionCandidates={composerMentionCandidates}memberPanelProps={memberPanelProps}manageMembersDialog={manageMembersDialog}onOpenPost={enterThread}@@ -266,7 +266,7 @@ export function ChannelRoute({ serverParam, channelId }: {onSetNotificationLevel={setNotificationLevel}onBack={bp === "mobile" ? goBack : undefined}composerMembers={composerMembers}- onSearchComposerMembers={onSearchComposerMembers}+ composerMentionCandidates={composerMentionCandidates}channelRefCandidates={channelRefCandidates}memberPanelProps={memberPanelProps}manageMembersDialog={manageMembersDialog}diff --git a/src/web/src/components/community/channels/forum-channel-surface.test.ts b/src/web/src/components/community/channels/forum-channel-surface.test.tsindex b51ee57d6..38a418fed 100644--- a/src/web/src/components/community/channels/forum-channel-surface.test.ts+++ b/src/web/src/components/community/channels/forum-channel-surface.test.ts@@ -66,7 +66,7 @@ function surfaceProps(overrides: Record<string, unknown> = {}) {notificationLevel: "Use Server Default" as const,onSetNotificationLevel: vi.fn(),composerMembers: [],- onSearchComposerMembers: vi.fn(),+ composerMentionCandidates: undefined,memberPanelProps: { members: [] },manageMembersDialog: React.createElement("span", { "data-manage-dialog": true }),onOpenPost: vi.fn(),@@ -96,7 +96,7 @@ describe("ForumChannelSurface ownership", () => {expect(forumProps).toEqual(expect.objectContaining({forumChannelId: "forum_1",members: props.composerMembers,- onSearchMembers: props.onSearchComposerMembers,+ mentionCandidates: props.composerMentionCandidates,onOpenPost: props.onOpenPost,savingTagsFor: "post_saving",deletingPost: "post_deleting",diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsxindex 9f65b6a4b..c25a9d12c 100644--- a/src/web/src/components/community/channels/forum-channel-surface.tsx+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx@@ -10,6 +10,7 @@ import { ChannelShell } from "@/components/community/channels/channel-shell"import type { ChannelMemberPanelProps } from "@/components/community/members/channel-member-view-model"import { CommunityPanel } from "@/components/community/shell/community-panel"import type { NewForumThread } from "@/components/community/messages/create-forum-thread"+import type { ComposerProps } from "@/components/community/messages/composer"import { ForumSurface } from "@/components/community/channels/forum-surface"import type { Member } from "@/lib/community/models/people"import {@@ -29,7 +30,7 @@ export function ForumChannelSurface({onSetNotificationLevel,onBack,composerMembers,- onSearchComposerMembers,+ composerMentionCandidates,memberPanelProps,manageMembersDialog,onOpenPost,@@ -45,7 +46,7 @@ export function ForumChannelSurface({onSetNotificationLevel: (level: ChannelNotifLevel) => voidonBack?: () => voidcomposerMembers: Member[]- onSearchComposerMembers?: (query: string) => void+ composerMentionCandidates?: ComposerProps["mentionCandidates"]memberPanelProps: ChannelMemberPanelPropsmanageMembersDialog: ReactNodeonOpenPost: (postId: string) => void@@ -108,7 +109,7 @@ export function ForumChannelSurface({serverId={serverId}forumChannelId={channelId}members={composerMembers}- onSearchMembers={onSearchComposerMembers}+ mentionCandidates={composerMentionCandidates}onOpenPost={onOpenPost}onCreatePost={createForumThread}canEditPostTags={(post) => canManage || post.authorId === viewer.id}diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsxindex d0f31492f..8f4002d9f 100644--- a/src/web/src/components/community/channels/forum-surface.tsx+++ b/src/web/src/components/community/channels/forum-surface.tsx@@ -2,6 +2,7 @@import { useState } from "react"import type { NewForumThread } from "../messages/create-forum-thread"+import type { ComposerProps } from "../messages/composer"import type { ForumThread } from "@/lib/community/models/message"import type { Member } from "@/lib/community/models/people"import { ForumView } from "./forum-view"@@ -13,7 +14,7 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {serverId: stringforumChannelId: stringmembers: Member[]- onSearchMembers?: (query: string) => void+ mentionCandidates?: ComposerProps["mentionCandidates"]onOpenPost: (id: string) => voidonCreatePost?: (post: NewForumThread) => Promise<void>onEditPostTags?: (post: ForumThread, tags: string[]) => voiddiff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsxindex a032a49da..c9a33194f 100644--- a/src/web/src/components/community/channels/forum-view.tsx+++ b/src/web/src/components/community/channels/forum-view.tsx@@ -12,6 +12,7 @@ import { AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"import { EmptyState } from "../empty-state"import { CreateForumThread, type NewForumThread } from "../messages/create-forum-thread"+import type { ComposerProps } from "../messages/composer"import { PostTagDialog } from "./post-tag-dialog"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { tid } from "@/lib/community/testids"@@ -183,7 +184,7 @@ function ForumPostTitle({ name, postId, seq }: { name: string; postId: string; sexport function ForumView({forumChannelId,members,- onSearchMembers,+ mentionCandidates,posts, loading, tag, availableTags = [], onTagChange, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,hasMore, loadingMore, onLoadMore,onDeletePost, canDeletePost, deletingPost,@@ -191,7 +192,7 @@ export function ForumView({}: {forumChannelId: stringmembers: Member[]- onSearchMembers?: (query: string) => void+ mentionCandidates?: ComposerProps["mentionCandidates"]posts: ForumThread[]loading?: booleantag: string@@ -302,7 +303,7 @@ export function ForumView({<CreateForumThreadforumChannelId={forumChannelId}members={members}- onSearchMembers={onSearchMembers}+ mentionCandidates={mentionCandidates}onCancel={closeCompose}onCreatePost={async (post) => {if (!onCreatePost) returndiff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex 3e721f3a9..7179c4378 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -30,7 +30,7 @@ export function TextChannelSurface({onSetNotificationLevel,onBack,composerMembers,- onSearchComposerMembers,+ composerMentionCandidates,channelRefCandidates,memberPanelProps,manageMembersDialog,@@ -50,7 +50,7 @@ export function TextChannelSurface({onSetNotificationLevel: (level: ChannelNotifLevel) => voidonBack?: () => voidcomposerMembers: ComponentProps<typeof Composer>["members"]- onSearchComposerMembers: ComponentProps<typeof Composer>["onSearchMembers"]+ composerMentionCandidates: ComponentProps<typeof Composer>["mentionCandidates"]channelRefCandidates: ComponentProps<typeof Composer>["channelRefCandidates"]memberPanelProps: ChannelMemberPanelPropsmanageMembersDialog: ReactNode@@ -145,7 +145,7 @@ export function TextChannelSurface({channel={channelName}context="channel"members={composerMembers}- onSearchMembers={onSearchComposerMembers}+ mentionCandidates={composerMentionCandidates}channelRefCandidates={channelRefCandidates}sendContract="accepted"onAcceptSend={controller.acceptMessage}diff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.tsindex e004e14f4..520e98bbb 100644--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts@@ -175,7 +175,7 @@ function surfaceProps(overrides: Record<string, unknown> = {}) {onSetNotificationLevel: vi.fn(),onBack: vi.fn(),composerMembers: [{ id: "member_1", userId: "member_1", name: "Alice" }],- onSearchComposerMembers: vi.fn(),+ composerMentionCandidates: undefined,channelRefCandidates: [{ id: "parent_1", name: "general", serverId: "server_1", serverName: "Server", serverDiscriminator: "0001" }],memberPanelProps: {members: [],@@ -257,7 +257,7 @@ describe("ThreadChannelSurface ownership", () => {channel: "Thread name",context: "thread",members: props.composerMembers,- onSearchMembers: props.onSearchComposerMembers,+ mentionCandidates: props.composerMentionCandidates,channelRefCandidates: props.channelRefCandidates,replyingTo: "Alice",autoFocus: true,diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 5390836e0..ab059c734 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -40,7 +40,7 @@ export function ThreadChannelSurface({onSetNotificationLevel,onBack,composerMembers,- onSearchComposerMembers,+ composerMentionCandidates,channelRefCandidates,memberPanelProps,manageMembersDialog,@@ -66,7 +66,7 @@ export function ThreadChannelSurface({onSetNotificationLevel: (level: ChannelNotifLevel) => voidonBack?: () => voidcomposerMembers: ComponentProps<typeof Composer>["members"]- onSearchComposerMembers: ComponentProps<typeof Composer>["onSearchMembers"]+ composerMentionCandidates: ComponentProps<typeof Composer>["mentionCandidates"]channelRefCandidates: ComponentProps<typeof Composer>["channelRefCandidates"]memberPanelProps: ChannelMemberPanelPropsmanageMembersDialog: ReactNode@@ -246,7 +246,7 @@ export function ThreadChannelSurface({channel={displayName}context="thread"members={composerMembers}- onSearchMembers={onSearchComposerMembers}+ mentionCandidates={composerMentionCandidates}channelRefCandidates={channelRefCandidates}sendContract="accepted"onAcceptSend={controller.acceptMessage}diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsxindex ce6ee90c3..31743c0f1 100644--- a/src/web/src/components/community/members/channel-member-view-model.tsx+++ b/src/web/src/components/community/members/channel-member-view-model.tsx@@ -6,6 +6,7 @@ import { isForum, type CommunityRole as Role } from "@alook/shared"import { AddMembersDialog } from "@/components/community/members/add-members-dialog"import type { CommunityPanel } from "@/components/community/shell/community-panel"import type { Member } from "@/lib/community/models/people"+import type { ComposerProps } from "@/components/community/messages/composer"import { toastApiError } from "@/lib/api/client"import { makeUserNameResolver } from "@/lib/community/display-name"import { resolveRowPresence } from "@/lib/community/presence"@@ -23,6 +24,8 @@ import {import { useKickMember, useSetMemberRole } from "@/hooks/community/mutations"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+type MentionCandidateSource = NonNullable<ComposerProps["mentionCandidates"]>+type PanelProps = ComponentProps<typeof CommunityPanel>export type ChannelMemberPanelProps = Pick<@@ -79,7 +82,7 @@ export function useChannelMemberViewModel({currentUser: { id: string }}): {composerMembers: Member[]- onSearchComposerMembers: (query: string) => void+ composerMentionCandidates?: MentionCandidateSourcememberPanelProps: ChannelMemberPanelPropsmanageMembersDialog: ReactNoderesolveUserName: (userId: string) => string@@ -236,6 +239,32 @@ export function useChannelMemberViewModel({userStatuses,])+ const composerMentionCandidates = useMemo<MentionCandidateSource | undefined>(+ () => currentChannelPrivate+ ? undefined+ : {+ loading: membersHook.loading,+ loadingMore: membersHook.loadingMore,+ hasMore: membersHook.hasMore,+ failed: membersHook.failed,+ searchQuery: membersHook.searchQuery,+ searchStatus: membersHook.searchStatus,+ loadMore: membersHook.loadMore,+ search: membersHook.searchMembers,+ },+ [+ currentChannelPrivate,+ membersHook.failed,+ membersHook.hasMore,+ membersHook.loadMore,+ membersHook.loading,+ membersHook.loadingMore,+ membersHook.searchMembers,+ membersHook.searchQuery,+ membersHook.searchStatus,+ ],+ )+const myRole = members.find((member) => member.userId === currentUser.id)?.roleconst unitCreatorId = isChildChannel? currentChannelMeta?.creatorId@@ -330,7 +359,7 @@ export function useChannelMemberViewModel({return {composerMembers,- onSearchComposerMembers: membersHook.searchMembers,+ composerMentionCandidates,memberPanelProps,manageMembersDialog,resolveUserName,diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts b/src/web/src/components/community/messages/composer-suggestion-popups.test.tsindex 206c6793a..9f6e9d347 100644--- a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts+++ b/src/web/src/components/community/messages/composer-suggestion-popups.test.ts@@ -85,7 +85,10 @@ describe("Composer suggestion popups", () => {let channel!: TestRenderer.ReactTestRendererawait act(async () => {mention = TestRenderer.create(- createElement(CommunityMentionList, { state: EMPTY_MENTION_STATE }),+ createElement(CommunityMentionList, {+ state: EMPTY_MENTION_STATE,+ presentation: { status: "ready" },+ }),)channel = TestRenderer.create(createElement(ChannelRefList, { state: EMPTY_CHANNEL_REF_STATE }),@@ -100,10 +103,12 @@ describe("Composer suggestion popups", () => {createElement(CommunityMentionList, {state: {items: [{ kind: "everyone", id: "everyone", label: "everyone" }],+ query: "",selectedIndex: 0,command: vi.fn(),getRect: () => rect(500),},+ presentation: { status: "ready" },}),)})@@ -131,6 +136,7 @@ describe("Composer suggestion popups", () => {status: "online",},],+ query: "",selectedIndex: 1,command,getRect: () => rect(500),@@ -138,7 +144,10 @@ describe("Composer suggestion popups", () => {let renderer!: TestRenderer.ReactTestRendererawait act(async () => {renderer = TestRenderer.create(- createElement(CommunityMentionList, { state }),+ createElement(CommunityMentionList, {+ state,+ presentation: { status: "ready" },+ }),{createNodeMock: (element) =>element.props.className?.includes("overflow-y-auto") ? listNode : {},@@ -218,6 +227,42 @@ describe("Composer suggestion popups", () => {expect(command).toHaveBeenCalledWith({ id: "member-1", label: "Ada#0001" })})+ it("keeps one anchored frame for loading, empty, error, and loading-more", async () => {+ const state: MentionPopupState = {+ items: [],+ query: "ada",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: () => rect(500),+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(CommunityMentionList, {+ state,+ presentation: { status: "loading" },+ }),+ )+ })+ expect(renderer.root.findByProps({ "data-state": "loading" }).children)+ .toEqual(["Loading members…"])++ for (const [status, label] of [+ ["empty", "No matching members"],+ ["error", "Couldn’t load members"],+ ["loading-more", "Loading members…"],+ ] as const) {+ await act(async () => {+ renderer.update(createElement(CommunityMentionList, {+ state,+ presentation: { status },+ }))+ })+ expect(renderer.root.findByProps({ "data-state": status }).children)+ .toEqual([label])+ }+ })+it("adds server prefixes only for cross-server channel results", async () => {const command = vi.fn()const state: ChannelRefPopupState = {diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.tsx b/src/web/src/components/community/messages/composer-suggestion-popups.tsxindex 558da0e81..26213fa0a 100644--- a/src/web/src/components/community/messages/composer-suggestion-popups.tsx+++ b/src/web/src/components/community/messages/composer-suggestion-popups.tsx@@ -15,6 +15,7 @@ import {type ChannelRefPopupState,} from "@/lib/community/channel-ref-extension"import type {+ MentionCandidatePresentation,MentionItem,MentionPopupState,} from "@/lib/community/mention-extension"@@ -36,25 +37,28 @@ function scrollSelectedRowIntoView(list: HTMLDivElement | null): void {export function CommunityMentionList({state,+ presentation,}: {state: MentionPopupState+ presentation: MentionCandidatePresentation}) {const listRef = useRef<HTMLDivElement>(null)const { items, selectedIndex, command, getRect } = stateconst geometry = useAnchoredPopover(getRect,- items.length > 0 && command !== null,+ command !== null,)useEffect(() => {scrollSelectedRowIntoView(listRef.current)}, [selectedIndex, geometry])- if (!geometry || items.length === 0 || !command) return null+ if (!geometry || !command) return nullconst firstMemberIndex = items.findIndex((item) => item.kind === "member")const hasVirtual = items.some((item) => item.kind !== "member")const showMembersHeader = hasVirtual && firstMemberIndex > 0return createPortal(<div+ data-testid={tid.mentionPopup}className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"style={anchoredPopoverStyle(geometry.rect,@@ -79,12 +83,40 @@ export function CommunityMentionList({onSelect={() => command({ id: item.id, label: item.label })}/>))}+ {presentation.status !== "ready" && (+ <MentionStatus status={presentation.status} hasItems={items.length > 0} />+ )}</div></div>,document.body,)}+function MentionStatus({+ status,+ hasItems,+}: {+ status: Exclude<MentionCandidatePresentation["status"], "ready">+ hasItems: boolean+}) {+ const label = status === "error"+ ? "Couldn’t load members"+ : status === "empty"+ ? "No matching members"+ : status === "loading-more" && hasItems+ ? "Loading more…"+ : "Loading members…"+ return (+ <div+ data-testid={tid.mentionStatus}+ data-state={status}+ className="px-2 py-2 text-xs text-muted-foreground"+ >+ {label}+ </div>+ )+}+export function ChannelRefList({ state }: { state: ChannelRefPopupState }) {const listRef = useRef<HTMLDivElement>(null)const { items, selectedIndex, command, getRect } = statediff --git a/src/web/src/components/community/messages/composer-types.ts b/src/web/src/components/community/messages/composer-types.tsindex f49ef60ef..0598fe558 100644--- a/src/web/src/components/community/messages/composer-types.ts+++ b/src/web/src/components/community/messages/composer-types.ts@@ -6,6 +6,23 @@ import type { Member } from "@/lib/community/models/people"type ComposerMode = "chat" | "forumThreadBody"+export type MentionCandidateSource = {+ loading: boolean+ loadingMore: boolean+ hasMore: boolean+ failed: boolean+ searchQuery: string+ searchStatus:+ | "idle"+ | "loading"+ | "loading-more"+ | "ready"+ | "empty"+ | "error"+ loadMore: () => void+ search: (query: string) => void+}+export type ComposerHandle = {focusEditor: () => voidsubmitNow: () => void@@ -18,7 +35,7 @@ type ComposerBaseProps = {channel: stringcontext: MentionContextmembers: Member[]- onSearchMembers?: (query: string) => void+ mentionCandidates?: MentionCandidateSourcechannelRefCandidates?: ChannelRefCandidate[]onChannelRefIntent?: () => voidonTyping?: () => voiddiff --git a/src/web/src/components/community/messages/composer-view.test.ts b/src/web/src/components/community/messages/composer-view.test.tsindex 422ac85eb..91ff127ae 100644--- a/src/web/src/components/community/messages/composer-view.test.ts+++ b/src/web/src/components/community/messages/composer-view.test.ts@@ -70,6 +70,7 @@ function baseProps(onDragOver: vi.fn(),onDrop: vi.fn(),mentionPopup: EMPTY_MENTION_STATE,+ mentionPresentation: { status: "ready" },channelRefPopup: EMPTY_CHANNEL_REF_STATE,pendingFiles: [],removePendingFile: vi.fn(),diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsxindex 9e3a1effe..de129dc83 100644--- a/src/web/src/components/community/messages/composer-view.tsx+++ b/src/web/src/components/community/messages/composer-view.tsx@@ -14,7 +14,10 @@ import {import { Skeleton } from "@/components/ui/skeleton"import type { PendingFile } from "@/hooks/use-file-attachments"import type { ChannelRefPopupState } from "@/lib/community/channel-ref-extension"-import type { MentionPopupState } from "@/lib/community/mention-extension"+import type {+ MentionCandidatePresentation,+ MentionPopupState,+} from "@/lib/community/mention-extension"import { tid } from "@/lib/community/testids"import { EmojiPickerPopover } from "./emoji-picker"import {@@ -30,6 +33,7 @@ export type ComposerViewProps = {onDragOver: DragEventHandler<HTMLDivElement>onDrop: DragEventHandler<HTMLDivElement>mentionPopup: MentionPopupState+ mentionPresentation: MentionCandidatePresentationchannelRefPopup: ChannelRefPopupStatereplyingTo?: stringonCancelReply?: () => void@@ -53,6 +57,7 @@ export function ComposerView({onDragOver,onDrop,mentionPopup,+ mentionPresentation,channelRefPopup,replyingTo,onCancelReply,@@ -77,7 +82,10 @@ export function ComposerView({onDragOver={onDragOver}onDrop={onDrop}>- <CommunityMentionList state={mentionPopup} />+ <CommunityMentionList+ state={mentionPopup}+ presentation={mentionPresentation}+ /><ChannelRefList state={channelRefPopup} />{replyingTo && (diff --git a/src/web/src/components/community/messages/create-forum-thread.tsx b/src/web/src/components/community/messages/create-forum-thread.tsxindex 6458e384d..83b6a6b0e 100644--- a/src/web/src/components/community/messages/create-forum-thread.tsx+++ b/src/web/src/components/community/messages/create-forum-thread.tsx@@ -13,7 +13,12 @@ import {import { onEnterSubmit } from "@/lib/ime"import { toastApiError } from "@/lib/api/client"import { MAX_CHANNEL_NAME_LENGTH, type MentionType } from "@alook/shared"-import { Composer, type ComposerHandle, type SendAttachment } from "./composer"+import {+ Composer,+ type ComposerHandle,+ type ComposerProps,+ type SendAttachment,+} from "./composer"import type { Member } from "@/lib/community/models/people"import {useUploadFile,@@ -35,7 +40,7 @@ export type NewForumThread = {export function CreateForumThread({forumChannelId,members,- onSearchMembers,+ mentionCandidates,onCancel,onCreatePost,}: {@@ -43,7 +48,7 @@ export function CreateForumThread({// live under the same access-scope as the post.forumChannelId: stringmembers: Member[]- onSearchMembers?: (query: string) => void+ mentionCandidates?: ComposerProps["mentionCandidates"]onCancel: () => void// Async — the page owns the mutation call + `enterThread` navigation. This// handler either resolves (success — child clears its state) or rejects@@ -173,7 +178,7 @@ export function CreateForumThread({channel=""context="channel"members={members}- onSearchMembers={onSearchMembers}+ mentionCandidates={mentionCandidates}channelRefCandidates={[]}placeholder="What do you want to discuss?"onDeferredSubmit={handleBodySubmit}diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.tsindex 91c5acb46..dd107cd94 100644--- a/src/web/src/components/community/messages/use-composer-controller.ts+++ b/src/web/src/components/community/messages/use-composer-controller.ts@@ -33,7 +33,7 @@ export function useComposerController(channel,context,members,- onSearchMembers,+ mentionCandidates,channelRefCandidates = [],onChannelRefIntent,sendContract,@@ -103,7 +103,7 @@ export function useComposerController(const suggestions = useComposerSuggestions({members,context,- onSearchMembers,+ mentionCandidates,channelRefCandidates,onChannelRefIntent,})@@ -348,6 +348,7 @@ export function useComposerController(onDragOver: handleDragOver,onDrop: handleDrop,mentionPopup: suggestions.mentionPopup,+ mentionPresentation: suggestions.mentionPresentation,channelRefPopup: suggestions.channelRefPopup,replyingTo,onCancelReply,diff --git a/src/web/src/components/community/messages/use-composer-suggestions.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.test.tsindex e6e34c433..7a8a67574 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.test.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.test.ts@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@/lib/community/mention-extension", () => ({EMPTY_MENTION_STATE: {items: [],+ query: "",selectedIndex: 0,command: null,getRect: null,@@ -73,6 +74,21 @@ const channel = (...overrides,})+const candidateSource = (+ search: (query: string) => void,+ overrides: Partial<NonNullable<Options["mentionCandidates"]>> = {},+) => ({+ loading: false,+ loadingMore: false,+ hasMore: false,+ failed: false,+ searchQuery: "",+ searchStatus: "idle" as const,+ loadMore: vi.fn(),+ search,+ ...overrides,+})+describe("useComposerSuggestions", () => {beforeEach(() => {mocks.buildMention.mockReset()@@ -114,7 +130,10 @@ describe("useComposerSuggestions", () => {createElement(Harness, {members: firstMembers,context: "channel",- onSearchMembers: firstSearch,+ mentionCandidates: candidateSource(firstSearch, {+ searchQuery: "ad",+ searchStatus: "ready",+ }),channelRefCandidates: firstChannels,onChannelRefIntent: vi.fn(),resultRef,@@ -135,7 +154,10 @@ describe("useComposerSuggestions", () => {createElement(Harness, {members: nextMembers,context: "thread",- onSearchMembers: nextSearch,+ mentionCandidates: candidateSource(nextSearch, {+ searchQuery: "ad",+ searchStatus: "ready",+ }),channelRefCandidates: nextChannels,onChannelRefIntent: nextIntent,resultRef,@@ -156,6 +178,7 @@ describe("useComposerSuggestions", () => {await act(async () => {mentionOptions.setPopup({items: [],+ query: "",selectedIndex: 0,command: vi.fn(),getRect: null,@@ -199,7 +222,10 @@ describe("useComposerSuggestions", () => {createElement(Harness, {members: thirdMembers,context: "thread",- onSearchMembers: nextSearch,+ mentionCandidates: candidateSource(nextSearch, {+ searchQuery: "ad",+ searchStatus: "ready",+ }),channelRefCandidates: thirdChannels,onChannelRefIntent: nextIntent,resultRef,@@ -242,6 +268,7 @@ describe("useComposerSuggestions", () => {await act(async () => {options.setPopup({items: [initialItem, secondItem],+ query: "",selectedIndex: 1,command: vi.fn(),getRect: null,@@ -295,6 +322,183 @@ describe("useComposerSuggestions", () => {expect(resultRef.current!.mentionPopup.selectedIndex).toBe(0)})+ it("loads bare-@ pages serially and exposes first search pages while loading more", async () => {+ const resultRef: { current: Result | null } = { current: null }+ const search = vi.fn()+ const loadMore = vi.fn()+ let source = candidateSource(search, { hasMore: true, loadMore })+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, {+ members: [member()],+ context: "channel",+ mentionCandidates: source,+ channelRefCandidates: [],+ resultRef,+ }))+ })+ const options = mocks.buildMention.mock.calls[0][0]+ await act(async () => {+ options.setPopup({+ items: [{ kind: "everyone", id: "everyone", label: "everyone" }],+ query: "",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ })+ expect(loadMore).toHaveBeenCalledOnce()+ expect(resultRef.current!.mentionPresentation.status).toBe("loading-more")++ const firstSearchItem = {+ kind: "member" as const,+ id: "member-1",+ userId: "user-1",+ label: "Ada#0001",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online" as const,+ }+ await act(async () => {+ options.setPopup({+ items: [],+ query: "ad",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ })+ expect(resultRef.current!.mentionPresentation.status).toBe("loading")++ mocks.rankMention.mockReturnValue([firstSearchItem])+ source = candidateSource(search, {+ searchQuery: "ad",+ searchStatus: "loading-more",+ loadMore,+ })+ await act(async () => {+ renderer.update(createElement(Harness, {+ members: [member()],+ context: "channel",+ mentionCandidates: source,+ channelRefCandidates: [],+ resultRef,+ }))+ })+ expect(resultRef.current!.mentionPopup.items).toEqual([firstSearchItem])+ expect(resultRef.current!.mentionPresentation.status).toBe("loading-more")++ await act(async () => {+ options.setPopup({+ items: [],+ query: "bob",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ })+ expect(resultRef.current!.mentionPresentation.status).toBe("loading")+ })++ it("maps matching search loading, loading-more, ready, and empty states to presentation", async () => {+ const resultRef: { current: Result | null } = { current: null }+ const search = vi.fn()+ const item = {+ kind: "member" as const,+ id: "member-1",+ userId: "user-1",+ label: "Ada#0001",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online" as const,+ }+ let renderer!: TestRenderer.ReactTestRenderer+ const renderWith = async (+ searchStatus: NonNullable<Options["mentionCandidates"]>["searchStatus"],+ items: typeof item[],+ ) => {+ mocks.rankMention.mockReturnValue(items)+ await act(async () => {+ renderer.update(createElement(Harness, {+ members: [member()],+ context: "channel",+ mentionCandidates: candidateSource(search, {+ searchQuery: "ad",+ searchStatus,+ }),+ channelRefCandidates: [],+ resultRef,+ }))+ })+ }++ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, {+ members: [member()],+ context: "channel",+ mentionCandidates: candidateSource(search, {+ searchQuery: "ad",+ searchStatus: "loading",+ }),+ channelRefCandidates: [],+ resultRef,+ }))+ })+ const options = mocks.buildMention.mock.calls[0][0]+ const runQuery = (+ resultRef.current!.mentionExtension as unknown as {+ runQuery: (query: string) => unknown+ }+ ).runQuery+ expect(runQuery("ad")).toEqual([])+ expect(search).toHaveBeenCalledWith("ad")+ expect(mocks.rankMention).toHaveBeenLastCalledWith(+ [member()],+ "channel",+ "ad",+ )+ await act(async () => {+ options.setPopup({+ items: [],+ query: "ad",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ })+ expect(resultRef.current!.mentionPresentation.status).toBe("loading")++ await renderWith("idle", [])+ expect(resultRef.current!.mentionPresentation.status).toBe("loading")++ await renderWith("loading-more", [item])+ expect(resultRef.current!.mentionPopup.items).toEqual([item])+ expect(resultRef.current!.mentionPresentation.status).toBe("loading-more")+ expect(mocks.rankMention).toHaveBeenLastCalledWith(+ [member()],+ "channel",+ "ad",+ )++ await renderWith("ready", [item])+ expect(resultRef.current!.mentionPresentation.status).toBe("ready")++ await renderWith("ready", [])+ expect(resultRef.current!.mentionPopup.items).toEqual([])+ expect(resultRef.current!.mentionPresentation.status).toBe("empty")++ await renderWith("empty", [])+ expect(mocks.rankMention).toHaveBeenLastCalledWith(+ [member()],+ "channel",+ "ad",+ )+ expect(resultRef.current!.mentionPopup.items).toEqual([])+ expect(resultRef.current!.mentionPresentation.status).toBe("empty")+ })+it("keeps channel state when only serverName changes and resets both popups", async () => {const resultRef: { current: Result | null } = { current: null }let renderer!: TestRenderer.ReactTestRenderer@@ -313,6 +517,7 @@ describe("useComposerSuggestions", () => {await act(async () => {mentionOptions.setPopup({items: [{ kind: "everyone", id: "everyone", label: "everyone" }],+ query: "",selectedIndex: 0,command: vi.fn(),getRect: null,diff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.tsindex a70e2bae4..f8ece48d9 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts@@ -3,6 +3,7 @@ import {buildCommunityMentionExtension,EMPTY_MENTION_STATE,rankMentionItems,+ type MentionCandidatePresentation,type MentionContext,type MentionItem,type MentionPopupState,@@ -15,11 +16,12 @@ import {type ChannelRefPopupState,} from "@/lib/community/channel-ref-extension"import type { Member } from "@/lib/community/models/people"+import type { MentionCandidateSource } from "./composer-types"type ComposerSuggestionsOptions = {members: Member[]context: MentionContext- onSearchMembers?: (query: string) => void+ mentionCandidates?: MentionCandidateSourcechannelRefCandidates: ChannelRefCandidate[]onChannelRefIntent?: () => void}@@ -66,7 +68,7 @@ function channelRefItemsEqual(export function useComposerSuggestions({members,context,- onSearchMembers,+ mentionCandidates,channelRefCandidates,onChannelRefIntent,}: ComposerSuggestionsOptions) {@@ -87,7 +89,7 @@ export function useComposerSuggestions({const membersRef = useRef(members)const contextRef = useRef(context)- const onSearchMembersRef = useRef(onSearchMembers)+ const onSearchMembersRef = useRef(mentionCandidates?.search)const mentionQueryRef = useRef("")useEffect(() => {membersRef.current = members@@ -96,8 +98,8 @@ export function useComposerSuggestions({contextRef.current = context}, [context])useEffect(() => {- onSearchMembersRef.current = onSearchMembers- }, [onSearchMembers])+ onSearchMembersRef.current = mentionCandidates?.search+ }, [mentionCandidates?.search])// eslint-disable-next-line react-hooks/refs -- runtime suggestion callbacks read these refsconst [mentionExtension] = useState(() =>@@ -135,7 +137,17 @@ export function useComposerSuggestions({useEffect(() => {const current = mentionPopupRef.currentif (!current.command) return- const items = rankMentionItems(members, context, mentionQueryRef.current)+ const query = mentionQueryRef.current+ const remoteSearchReady = !query || !mentionCandidates+ || (mentionCandidates.searchQuery === query+ && (mentionCandidates.searchStatus === "ready"+ || mentionCandidates.searchStatus === "loading-more"+ || mentionCandidates.searchStatus === "empty"))+ const items = rankMentionItems(+ remoteSearchReady ? members : [],+ context,+ query,+ )if (mentionItemsEqual(current.items, items)) returnsetMentionPopup({...current,@@ -143,7 +155,47 @@ export function useComposerSuggestions({selectedIndex:current.selectedIndex < items.length ? current.selectedIndex : 0,})- }, [members, context])+ }, [+ context,+ members,+ mentionCandidates,+ ])++ useEffect(() => {+ const current = mentionPopupRef.current+ if (!current.command || current.query.trim()) return+ if (!mentionCandidates?.hasMore) return+ if (mentionCandidates.loading || mentionCandidates.loadingMore) return+ if (mentionCandidates.failed) return+ mentionCandidates.loadMore()+ }, [mentionCandidates, mentionPopup.command, mentionPopup.query])++ const mentionPresentation: MentionCandidatePresentation = (() => {+ if (!mentionCandidates) {+ return { status: mentionPopup.items.length > 0 ? "ready" : "empty" }+ }+ const query = mentionPopup.query+ if (query) {+ if (mentionCandidates.searchQuery !== query) return { status: "loading" }+ if (mentionCandidates.searchStatus === "loading"+ || mentionCandidates.searchStatus === "idle") {+ return { status: "loading" }+ }+ if (mentionCandidates.searchStatus === "error") return { status: "error" }+ if (mentionCandidates.searchStatus === "loading-more") {+ return { status: "loading-more" }+ }+ return {+ status: mentionPopup.items.length > 0 ? "ready" : "empty",+ }+ }+ if (mentionCandidates.failed) return { status: "error" }+ if (mentionCandidates.loading) return { status: "loading" }+ if (mentionCandidates.loadingMore || mentionCandidates.hasMore) {+ return { status: "loading-more" }+ }+ return { status: mentionPopup.items.length > 0 ? "ready" : "empty" }+ })()useEffect(() => {const current = channelRefPopupRef.current@@ -162,12 +214,14 @@ export function useComposerSuggestions({}, [channelRefCandidates])const resetPopups = () => {+ mentionCandidates?.search("")setMentionPopup(EMPTY_MENTION_STATE)setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)}return {mentionPopup,+ mentionPresentation,mentionPopupRef,mentionExtension,channelRefPopup,diff --git a/src/web/src/hooks/community/use-server-members.test.ts b/src/web/src/hooks/community/use-server-members.test.tsindex 967c48024..c720e0da0 100644--- a/src/web/src/hooks/community/use-server-members.test.ts+++ b/src/web/src/hooks/community/use-server-members.test.ts@@ -1,13 +1,34 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { QueryClient, type InfiniteData } from "@tanstack/react-query"+import { createElement, useEffect, type MutableRefObject } from "react"+import TestRenderer, { act, type ReactTestRenderer } from "react-test-renderer"+import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from "vitest"+import { QueryClient, QueryClientProvider, type InfiniteData } from "@tanstack/react-query"const apiFetchMock = vi.fn()+const toastApiErrorMock = vi.fn()+const reactActEnvironment = globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT?: boolean+}+const previousReactActEnvironment = reactActEnvironment.IS_REACT_ACT_ENVIRONMENTvi.mock("@/lib/api/client", () => ({apiFetch: (...args: unknown[]) => apiFetchMock(...args),+ toastApiError: (...args: unknown[]) => toastApiErrorMock(...args),}))+beforeAll(() => {+ reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = true+})+beforeEach(() => {apiFetchMock.mockReset()+ toastApiErrorMock.mockReset()+})++afterEach(() => {+ vi.useRealTimers()+})++afterAll(() => {+ reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = previousReactActEnvironment})import {@@ -23,6 +44,8 @@ import {SEARCH_DEBOUNCE_MS,dispatchMemberOverlayEvent,subscribeMemberOverlayEvents,+ mergeMemberSearchPage,+ useServerMembers,type MembersEnvelope,type MemberOverlayEvent,} from "./use-server-members"@@ -52,12 +75,86 @@ function joinEvent(userId: string, id = userId): CommunityMemberJoin {}}+type ServerMembersResult = ReturnType<typeof useServerMembers>++type Deferred<T> = {+ promise: Promise<T>+ resolve: (value: T) => void+ reject: (reason?: unknown) => void+}++function deferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise+ reject = rejectPromise+ })+ return { promise, resolve, reject }+}++function HookProbe({ serverId, resultRef }: {+ serverId: string | null+ resultRef: MutableRefObject<ServerMembersResult | null>+}) {+ const result = useServerMembers(serverId)+ useEffect(() => {+ resultRef.current = result+ }, [result, resultRef])+ return null+}++async function mountServerMembers(serverId = "srv_1") {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false, gcTime: Infinity },+ },+ })+ const resultRef = { current: null } as MutableRefObject<ServerMembersResult | null>+ let renderer!: ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ createElement(+ QueryClientProvider,+ { client: queryClient },+ createElement(HookProbe, { serverId, resultRef }),+ ),+ )+ await Promise.resolve()+ })+ return { queryClient, renderer, resultRef }+}++async function flushEffects() {+ await act(async () => {+ await Promise.resolve()+ await Promise.resolve()+ })+}++function isSearchUrl(value: unknown): value is string {+ return typeof value === "string" && value.includes("/members/search?")+}+describe("SEARCH_DEBOUNCE_MS", () => {it("is 200ms (matches plan)", () => {expect(SEARCH_DEBOUNCE_MS).toBe(200)})})+describe("mergeMemberSearchPage", () => {+ it("appends serial search pages and drops duplicate boundary rows", () => {+ const first = [m("a"), m("b")]+ const merged = mergeMemberSearchPage(first, [m("b"), m("c")])+ expect(merged.map((member) => member.id)).toEqual(["a", "b", "c"])+ })++ it("preserves the accumulated reference when a page adds nothing", () => {+ const first = [m("a"), m("b")]+ expect(mergeMemberSearchPage(first, [m("a")])).toBe(first)+ })+})+describe("applyJoinEvent", () => {it("appends at tail when hasMore=false", () => {const prev = [m("a"), m("b")]@@ -350,3 +447,254 @@ describe("member overlay bus", () => {unsub()})})++describe("useServerMembers search lifecycle", () => {+ it("debounces the first page, serially appends continuation pages, and ignores duplicate search calls", async () => {+ vi.useFakeTimers()+ const first = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()+ const second = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()+ apiFetchMock.mockImplementation((url: unknown) => {+ if (!isSearchUrl(url)) return Promise.resolve(makeEnvelope([], false, 0))+ if (url.includes("q=none")) {+ return Promise.resolve({ members: [], hasMore: false, limit: 50 })+ }+ return url.includes("cursor=cur_2") ? second.promise : first.promise+ })+ const harness = await mountServerMembers()++ await act(async () => {+ harness.resultRef.current!.searchMembers(" ad ")+ harness.resultRef.current!.searchMembers("ad")+ })+ expect(harness.resultRef.current).toMatchObject({+ isSearching: true,+ searchQuery: "ad",+ searchStatus: "loading",+ members: [],+ })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ expect(apiFetchMock.mock.calls.filter(([url]) => isSearchUrl(url))).toEqual([+ ["/api/community/servers/srv_1/members/search?q=ad"],+ ])++ first.resolve({ members: [m("a"), m("b")], hasMore: true, cursor: "cur_2", limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ members: [m("a"), m("b")],+ searchStatus: "loading-more",+ })+ expect(apiFetchMock.mock.calls.filter(([url]) => isSearchUrl(url))).toEqual([+ ["/api/community/servers/srv_1/members/search?q=ad"],+ ["/api/community/servers/srv_1/members/search?q=ad&cursor=cur_2"],+ ])++ second.resolve({ members: [m("b"), m("c")], hasMore: false, limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ members: [m("a"), m("b"), m("c")],+ searchStatus: "ready",+ })++ await act(async () => {+ harness.resultRef.current!.searchMembers("none")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ members: [],+ searchStatus: "empty",+ searchQuery: "none",+ })++ await act(async () => harness.renderer.unmount())+ harness.queryClient.clear()+ })++ it("keeps the latest query when older success and error responses settle late", async () => {+ vi.useFakeTimers()+ const requests = new Map<string, Deferred<{ members: Member[]; hasMore: boolean; limit: number }>>()+ apiFetchMock.mockImplementation((url: unknown) => {+ if (!isSearchUrl(url)) return Promise.resolve(makeEnvelope([], false, 0))+ const query = new URL(url, "https://alook.local").searchParams.get("q")!+ const request = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()+ requests.set(query, request)+ return request.promise+ })+ const harness = await mountServerMembers()++ await act(async () => {+ harness.resultRef.current!.searchMembers("old-success")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ harness.resultRef.current!.searchMembers("new-success")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ requests.get("old-success")!.resolve({ members: [m("old")], hasMore: false, limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ searchQuery: "new-success",+ searchStatus: "loading",+ members: [],+ })+ requests.get("new-success")!.resolve({ members: [m("new")], hasMore: false, limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ searchQuery: "new-success",+ searchStatus: "ready",+ members: [m("new")],+ })++ await act(async () => {+ harness.resultRef.current!.searchMembers("old-error")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ harness.resultRef.current!.searchMembers("final")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ requests.get("old-error")!.reject(new Error("stale failure"))+ await flushEffects()+ expect(toastApiErrorMock).not.toHaveBeenCalled()+ expect(harness.resultRef.current).toMatchObject({+ searchQuery: "final",+ searchStatus: "loading",+ members: [],+ })+ requests.get("final")!.resolve({ members: [m("final")], hasMore: false, limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ searchQuery: "final",+ searchStatus: "ready",+ members: [m("final")],+ })++ await act(async () => harness.renderer.unmount())+ harness.queryClient.clear()+ })++ it("retains accumulated members on a current continuation error and refreshes the active query", async () => {+ vi.useFakeTimers()+ const first = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()+ const continuation = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()+ const refreshed = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()+ let searchCall = 0+ apiFetchMock.mockImplementation((url: unknown) => {+ if (!isSearchUrl(url)) return Promise.resolve(makeEnvelope([], false, 0))+ searchCall += 1+ if (searchCall === 1) return first.promise+ if (searchCall === 2) return continuation.promise+ return refreshed.promise+ })+ const harness = await mountServerMembers()++ await act(async () => {+ harness.resultRef.current!.searchMembers("ad")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ first.resolve({ members: [m("a")], hasMore: true, cursor: "next", limit: 50 })+ await flushEffects()+ continuation.reject(new Error("current failure"))+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ members: [m("a")],+ searchStatus: "error",+ })+ expect(toastApiErrorMock).toHaveBeenCalledOnce()+ expect(toastApiErrorMock).toHaveBeenCalledWith(expect.any(Error), "Search failed")++ await act(async () => {+ dispatchMemberOverlayEvent({ type: "refresh", serverId: "srv_1" })+ })+ expect(harness.resultRef.current).toMatchObject({+ members: [],+ searchStatus: "loading",+ searchQuery: "ad",+ })+ refreshed.resolve({ members: [m("refreshed")], hasMore: false, limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ members: [m("refreshed")],+ searchStatus: "ready",+ })++ await act(async () => {+ harness.resultRef.current!.searchMembers("")+ dispatchMemberOverlayEvent({ type: "refresh", serverId: "srv_1" })+ })+ expect(searchCall).toBe(3)+ expect(harness.resultRef.current).toMatchObject({ isSearching: false, searchStatus: "idle" })++ await act(async () => harness.renderer.unmount())+ harness.queryClient.clear()+ })++ it("clears pending searches and cancels the debounce on unmount", async () => {+ vi.useFakeTimers()+ apiFetchMock.mockImplementation((url: unknown) => {+ if (isSearchUrl(url)) return Promise.resolve({ members: [], hasMore: false, limit: 50 })+ return Promise.resolve(makeEnvelope([], false, 0))+ })+ const harness = await mountServerMembers()++ await act(async () => {+ harness.resultRef.current!.searchMembers("cancelled")+ harness.resultRef.current!.searchMembers("")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ expect(apiFetchMock.mock.calls.some(([url]) => isSearchUrl(url))).toBe(false)+ expect(harness.resultRef.current).toMatchObject({ isSearching: false, searchStatus: "idle" })++ await act(async () => {+ harness.resultRef.current!.searchMembers("unmounted")+ })+ await act(async () => harness.renderer.unmount())+ await act(async () => {+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ expect(apiFetchMock.mock.calls.some(([url]) => isSearchUrl(url))).toBe(false)+ harness.queryClient.clear()+ })++ it("drops the previous server overlay and ignores its late response", async () => {+ vi.useFakeTimers()+ const oldResponse = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()+ apiFetchMock.mockImplementation((url: unknown) => {+ if (isSearchUrl(url)) return oldResponse.promise+ return Promise.resolve(makeEnvelope([], false, 0))+ })+ const harness = await mountServerMembers()++ await act(async () => {+ harness.resultRef.current!.searchMembers("old")+ await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)+ })+ await act(async () => {+ harness.renderer.update(+ createElement(+ QueryClientProvider,+ { client: harness.queryClient },+ createElement(HookProbe, { serverId: "srv_2", resultRef: harness.resultRef }),+ ),+ )+ await Promise.resolve()+ })+ expect(harness.resultRef.current).toMatchObject({+ isSearching: false,+ searchQuery: "",+ searchStatus: "idle",+ })++ oldResponse.resolve({ members: [m("old")], hasMore: false, limit: 50 })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({+ isSearching: false,+ searchQuery: "",+ searchStatus: "idle",+ members: [],+ })+ expect(toastApiErrorMock).not.toHaveBeenCalled()++ await act(async () => harness.renderer.unmount())+ harness.queryClient.clear()+ })+})diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex 85e10f37c..82fa8d5ca 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -83,6 +83,34 @@ export type MembersEnvelope = {type SearchEnvelope = {members: Member[]limit: number+ hasMore: boolean+ cursor?: string+}++type MemberSearchStatus =+ | "idle"+ | "loading"+ | "loading-more"+ | "ready"+ | "empty"+ | "error"++type MemberSearchState = {+ serverId: string+ query: string+ members: Member[]+ status: Exclude<MemberSearchStatus, "idle">+ cursor?: string+}++export function mergeMemberSearchPage(+ current: Member[],+ incoming: Member[],+): Member[] {+ if (current.length === 0) return incoming+ const seen = new Set(current.map((member) => member.id))+ const additions = incoming.filter((member) => !seen.has(member.id))+ return additions.length === 0 ? current : [...current, ...additions]}// Exported so the tests can drive the query function against a mocked@@ -261,6 +289,9 @@ export type UseServerMembers = {hasMore: booleantotal: numberisSearching: boolean+ searchQuery: string+ searchStatus: MemberSearchStatus+ failed: booleanloadMore: () => voidreset: () => voidrefresh: () => void@@ -278,10 +309,9 @@ export type UseServerMembers = {* Two view modes:* - "paged": pages live in the TanStack Query cache keyed under* `communityKeys.members(serverId)`. `loadMore()` calls `fetchNextPage`.- * - "search": bypasses the cache — search results live in local state- * because the search endpoint is a different route with its own semantics- * (no pagination, no cursor) and we don't want to blow away cursor state- * when the user starts typing.+ * - "search": bypasses the cache — paginated search results and their cursor+ * live in local state because the search endpoint is a different route and+ * we don't want to overwrite the server-roster page cache while typing.** WS events patch the shared paged cache in `community-ws/membership-events`* and notify the overlay bus above. Optimistic mutations use the same cache@@ -326,15 +356,13 @@ export function useServerMembers(serverId: string | null): UseServerMembers {})// ── Search state ────────────────────────────────────────────────────────- const [searchOverlay, setSearchOverlay] = useState<{- serverId: string | null- members: Member[]- } | null>(null)+ const [searchOverlay, setSearchOverlay] = useState<MemberSearchState | null>(null)const activeSearchQuery = useRef("")const searchActive = useRef(false)const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null)// Monotonic sequence so out-of-order responses drop old results silently.const searchSeq = useRef(0)+ const searchPageInFlight = useRef<string | null>(null)// ── Derived paged state ─────────────────────────────────────────────────const pagedMembers = useMemo<Member[]>(() => {@@ -387,29 +415,66 @@ export function useServerMembers(serverId: string | null): UseServerMembers {}, [serverId])const runSearch = useCallback(- async (q: string, seq: number) => {+ async (q: string, seq: number, cursor?: string) => {if (!enabled) return+ const pageKey = `${seq}:${cursor ?? "__first__"}`+ if (searchPageInFlight.current === pageKey) return+ searchPageInFlight.current = pageKeytry {const params = new URLSearchParams({ q })+ if (cursor) params.set("cursor", cursor)const data = await apiFetch<SearchEnvelope>(`/api/community/servers/${serverId}/members/search?${params}`,)- // Guard against out-of-order responses.if (searchSeq.current !== seq) return- setSearchOverlay({ serverId, members: data.members })+ setSearchOverlay((current) => {+ const members = cursor+ ? mergeMemberSearchPage(current!.members, data.members)+ : data.members+ return {+ serverId: serverId!,+ query: q,+ members,+ status: data.hasMore && data.cursor+ ? "loading-more"+ : members.length === 0 ? "empty" : "ready",+ cursor: data.hasMore ? data.cursor : undefined,+ }+ })} catch (e) {if (searchSeq.current === seq) {- setSearchOverlay({ serverId, members: [] })+ setSearchOverlay((current) => ({+ serverId: serverId!,+ query: q,+ members: current!.members,+ status: "error",+ }))toastApiError(e, "Search failed")}+ } finally {+ if (searchPageInFlight.current === pageKey) {+ searchPageInFlight.current = null+ }}},[enabled, serverId],)+ useEffect(() => {+ if (!searchOverlay || searchOverlay.serverId !== serverId) return+ if (searchOverlay.status !== "loading-more" || !searchOverlay.cursor) return+ const seq = searchSeq.current+ void runSearch(searchOverlay.query, seq, searchOverlay.cursor)+ }, [runSearch, searchOverlay, serverId])+const searchMembers = useCallback((q: string) => {const trimmed = q.trim()+ if (+ trimmed.length > 0+ && searchActive.current+ && activeSearchQuery.current === trimmed+ ) returnif (searchTimer.current) {clearTimeout(searchTimer.current)searchTimer.current = null@@ -424,12 +489,18 @@ export function useServerMembers(serverId: string | null): UseServerMembers {activeSearchQuery.current = trimmedsearchActive.current = trueconst seq = searchSeq.current+ setSearchOverlay({+ serverId: serverId!,+ query: trimmed,+ members: [],+ status: "loading",+ })searchTimer.current = setTimeout(() => {searchTimer.current = nullvoid runSearch(trimmed, seq)}, SEARCH_DEBOUNCE_MS)},- [runSearch],+ [runSearch, serverId],)const applyRoleChange = useCallback(@@ -481,8 +552,14 @@ export function useServerMembers(serverId: string | null): UseServerMembers {if (!q) returnsearchSeq.current += 1const seq = searchSeq.current+ setSearchOverlay({+ serverId: serverId!,+ query: q,+ members: [],+ status: "loading",+ })void runSearch(q, seq)- }, [runSearch])+ }, [runSearch, serverId])// Mirror-patch the search overlay from mutation and WS events. Every event// carries serverId so a transitioning hook cannot patch results retained@@ -534,6 +611,9 @@ export function useServerMembers(serverId: string | null): UseServerMembers {hasMore,total,isSearching: isSearchingCurrentServer,+ searchQuery: isSearchingCurrentServer ? searchOverlay.query : "",+ searchStatus: isSearchingCurrentServer ? searchOverlay.status : "idle",+ failed: infinite.isError,loadMore,reset,refresh,diff --git a/src/web/src/lib/community/member-search-cursor.test.ts b/src/web/src/lib/community/member-search-cursor.test.tsnew file mode 100644index 000000000..8b0e6de5b--- /dev/null+++ b/src/web/src/lib/community/member-search-cursor.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest"+import {+ encodeMemberSearchCursor,+ parseMemberSearchCursor,+} from "./member-search-cursor"++describe("member search cursor", () => {+ const cursor = {+ serverId: "srv_1",+ query: "阿 li|ce",+ name: "Alice | 阿",+ id: "member_2",+ }++ it("round-trips names and queries that cannot use a delimiter cursor", () => {+ const encoded = encodeMemberSearchCursor(cursor)+ expect(encoded).not.toContain(cursor.name)+ expect(parseMemberSearchCursor(encoded, {+ serverId: cursor.serverId,+ query: cursor.query,+ })).toEqual({ name: cursor.name, id: cursor.id })+ })++ it("rejects malformed and cross-scope cursors", () => {+ const encoded = encodeMemberSearchCursor(cursor)+ expect(parseMemberSearchCursor("invalid", {+ serverId: cursor.serverId,+ query: cursor.query,+ })).toBeNull()+ expect(parseMemberSearchCursor(encoded, {+ serverId: "srv_2",+ query: cursor.query,+ })).toBeNull()+ expect(parseMemberSearchCursor(encoded, {+ serverId: cursor.serverId,+ query: "Bob",+ })).toBeNull()+ })++ it("treats an absent cursor as the first page", () => {+ expect(parseMemberSearchCursor(null, {+ serverId: cursor.serverId,+ query: cursor.query,+ })).toBeUndefined()+ })+})diff --git a/src/web/src/lib/community/member-search-cursor.ts b/src/web/src/lib/community/member-search-cursor.tsnew file mode 100644index 000000000..24554461e--- /dev/null+++ b/src/web/src/lib/community/member-search-cursor.ts@@ -0,0 +1,33 @@+export type MemberSearchCursor = {+ serverId: string+ query: string+ name: string+ id: string+}++export function encodeMemberSearchCursor(cursor: MemberSearchCursor): string {+ const ascii = encodeURIComponent(JSON.stringify(cursor))+ return btoa(ascii).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")+}++export function parseMemberSearchCursor(+ raw: string | null,+ scope: { serverId: string; query: string },+): { name: string; id: string } | null | undefined {+ if (!raw) return undefined+ try {+ const base64 = raw.replaceAll("-", "+").replaceAll("_", "/")+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")+ const value = JSON.parse(decodeURIComponent(atob(padded))) as Partial<MemberSearchCursor>+ if (+ value.serverId !== scope.serverId+ || value.query !== scope.query+ || typeof value.name !== "string"+ || typeof value.id !== "string"+ || value.id.length === 0+ ) return null+ return { name: value.name, id: value.id }+ } catch {+ return null+ }+}diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 811508ec5..9712c2773 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -72,9 +72,9 @@ describe("rankMentionItems", () => {expect(memberOrder.slice(0, 2).sort()).toEqual(["Albert#0000", "Alice#0000"])})- it("caps the list at 8 items", () => {+ it("returns the complete roster without the former 8-item cap", () => {const many = Array.from({ length: 50 }, (_, i) => member(`u${i}`, `User${i}`))- expect(rankMentionItems(many, "channel", "").length).toBe(8)+ expect(rankMentionItems(many, "channel", "").length).toBe(51)})it("accepts a full Member[] with role/userId fields — ranking invariants unchanged", () => {@@ -194,6 +194,42 @@ function getItemsCallback(return items}+type MentionRenderProps = {+ items?: MentionPopupState["items"]+ query?: string+ command: (props: { id: string; label: string }) => void+ clientRect?: (() => DOMRect | null) | null+}++type MentionRenderCallbacks = {+ onStart: (props: MentionRenderProps) => void+ onUpdate: (props: MentionRenderProps) => void+ onKeyDown: (props: { event: KeyboardEvent }) => boolean+ onExit: () => void+}++function getRenderCallbacks(+ ext: ReturnType<typeof buildCommunityMentionExtension>,+): MentionRenderCallbacks {+ const config = (ext as unknown as {+ config: { addOptions?: () => { suggestion?: { render?: unknown } } }+ }).config+ const opts =+ config.addOptions?.() ??+ (ext as unknown as { options?: { suggestion?: { render?: unknown } } }).options+ const render = opts?.suggestion?.render as (() => MentionRenderCallbacks) | undefined+ if (!render) throw new Error("suggestion.render not found")+ return render()+}++function keyboardEvent(key: string, isComposing = false) {+ return {+ key,+ isComposing,+ preventDefault: vi.fn(),+ } as unknown as KeyboardEvent+}+// Same access pattern as `getItemsCallback` above — reach into the configured// `renderText`/`renderHTML` options rather than the tag's declared defaults.type RenderNodeProps = {@@ -332,6 +368,193 @@ describe("buildCommunityMentionExtension — suggestion.items callback", () => {})})+describe("buildCommunityMentionExtension — suggestion.render callbacks", () => {+ function setup(queryRef?: { current: string }) {+ let popup: MentionPopupState = EMPTY_MENTION_STATE+ const popupRef = { current: popup }+ const search = vi.fn()+ const setPopup = (+ next: MentionPopupState | ((cur: MentionPopupState) => MentionPopupState),+ ) => {+ popup = typeof next === "function" ? next(popup) : next+ popupRef.current = popup+ }+ const ext = buildCommunityMentionExtension({+ membersRef: { current: [] as Member[] },+ contextRef: { current: "channel" as MentionContext },+ popupRef,+ setPopup,+ onSearchMembersRef: { current: search },+ queryRef,+ })+ return {+ callbacks: getRenderCallbacks(ext),+ popup: () => popup,+ popupRef,+ search,+ setPopup,+ }+ }++ const items = rankMentionItems(+ [member("m1", "Ada", "0001"), member("m2", "Adel", "0002")],+ "channel",+ "ad",+ )++ it("starts and updates popup state while preserving only an in-range selection", () => {+ const harness = setup()+ const firstCommand = vi.fn()+ const firstRect = vi.fn(() => null)+ harness.callbacks.onStart({+ items,+ query: "ad",+ command: firstCommand,+ clientRect: firstRect,+ })+ expect(harness.popup()).toEqual({+ items,+ query: "ad",+ selectedIndex: 0,+ command: firstCommand,+ getRect: firstRect,+ })++ harness.setPopup({ ...harness.popup(), selectedIndex: 1 })+ const nextCommand = vi.fn()+ const nextRect = vi.fn(() => null)+ harness.callbacks.onUpdate({+ items,+ query: "ade",+ command: nextCommand,+ clientRect: nextRect,+ })+ expect(harness.popup()).toEqual({+ items,+ query: "ade",+ selectedIndex: 1,+ command: nextCommand,+ getRect: nextRect,+ })++ harness.callbacks.onUpdate({+ items: items.slice(0, 1),+ query: "ada",+ command: nextCommand,+ clientRect: null,+ })+ expect(harness.popup()).toMatchObject({+ items: items.slice(0, 1),+ query: "ada",+ selectedIndex: 0,+ getRect: null,+ })+ })++ it("prefers the live query ref over callback query snapshots", () => {+ const queryRef = { current: "live-start" }+ const harness = setup(queryRef)+ const command = vi.fn()+ harness.callbacks.onStart({+ items,+ query: "stale-start",+ command,+ clientRect: null,+ })+ expect(harness.popup().query).toBe("live-start")++ queryRef.current = "live-update"+ harness.callbacks.onUpdate({+ items,+ query: "stale-update",+ command,+ clientRect: null,+ })+ expect(harness.popup().query).toBe("live-update")+ })++ it("selects with Enter and Tab, then clears search and popup state", () => {+ const harness = setup()+ const command = vi.fn()+ harness.setPopup({+ items,+ query: "ad",+ selectedIndex: 1,+ command,+ getRect: null,+ })+ const enter = keyboardEvent("Enter")+ expect(harness.callbacks.onKeyDown({ event: enter })).toBe(true)+ expect(enter.preventDefault).toHaveBeenCalledOnce()+ expect(command).toHaveBeenLastCalledWith({ id: items[1].id, label: items[1].label })+ expect(harness.search).toHaveBeenLastCalledWith("")+ expect(harness.popup()).toEqual(EMPTY_MENTION_STATE)++ harness.setPopup({+ items,+ query: "ad",+ selectedIndex: 0,+ command,+ getRect: null,+ })+ const tab = keyboardEvent("Tab")+ expect(harness.callbacks.onKeyDown({ event: tab })).toBe(true)+ expect(tab.preventDefault).toHaveBeenCalledOnce()+ expect(command).toHaveBeenLastCalledWith({ id: items[0].id, label: items[0].label })+ expect(harness.popup()).toEqual(EMPTY_MENTION_STATE)+ })++ it("dismisses on Escape and exit, and wraps arrow navigation", () => {+ const harness = setup()+ harness.setPopup({+ items,+ query: "ad",+ selectedIndex: items.length - 1,+ command: vi.fn(),+ getRect: null,+ })+ const down = keyboardEvent("ArrowDown")+ expect(harness.callbacks.onKeyDown({ event: down })).toBe(true)+ expect(down.preventDefault).toHaveBeenCalledOnce()+ expect(harness.popup().selectedIndex).toBe(0)++ const up = keyboardEvent("ArrowUp")+ expect(harness.callbacks.onKeyDown({ event: up })).toBe(true)+ expect(up.preventDefault).toHaveBeenCalledOnce()+ expect(harness.popup().selectedIndex).toBe(items.length - 1)++ expect(harness.callbacks.onKeyDown({ event: keyboardEvent("Escape") })).toBe(true)+ expect(harness.search).toHaveBeenLastCalledWith("")+ expect(harness.popup()).toEqual(EMPTY_MENTION_STATE)++ harness.setPopup({+ items,+ query: "ad",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ harness.callbacks.onExit()+ expect(harness.search).toHaveBeenLastCalledWith("")+ expect(harness.popup()).toEqual(EMPTY_MENTION_STATE)+ })++ it("does not consume composing, empty, or unrelated key events", () => {+ const harness = setup()+ harness.setPopup({+ items,+ query: "ad",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ expect(harness.callbacks.onKeyDown({ event: keyboardEvent("Enter", true) })).toBe(false)+ expect(harness.callbacks.onKeyDown({ event: keyboardEvent("Space") })).toBe(false)+ harness.setPopup(EMPTY_MENTION_STATE)+ expect(harness.callbacks.onKeyDown({ event: keyboardEvent("Enter") })).toBe(false)+ })+})+describe("detectMentionType", () => {it("finds @everyone as a standalone token", () => {expect(detectMentionType("hi @everyone")).toBe("everyone")diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex e4b7653c9..67e43d0bd 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -22,9 +22,11 @@ export type MentionItem =| { kind: MentionType; id: MentionType; label: MentionType }| MemberMentionItem-const VIRTUAL_ITEMS: MentionItem[] = MENTION_TYPES.map((t) => ({ kind: t, id: t, label: t }))+export type MentionCandidatePresentation = {+ status: "loading" | "loading-more" | "ready" | "empty" | "error"+}-const MENTION_LIMIT = 8+const VIRTUAL_ITEMS: MentionItem[] = MENTION_TYPES.map((t) => ({ kind: t, id: t, label: t }))// The disambiguated label (`Alex#0002`, set by `rankMentionItems` below) is// what gets serialized into the message text via `renderText` — the backend@@ -40,7 +42,8 @@ function mentionDisplayLabel(label: string): string {// members, ranked prefix-first then substring. Returns an empty list for DMs:// a 1:1 conversation has no roster to disambiguate against, and the backend// (message-handler.ts) explicitly skips mention extraction for DMs anyway, so-// the popover would be pure noise. Capped at MENTION_LIMIT.+// the popover would be pure noise. The popover owns viewport containment, so+// this ranker returns the complete candidate set it receives.export function rankMentionItems(members: Member[],context: MentionContext,@@ -84,7 +87,7 @@ export function rankMentionItems(else if (name.includes(q)) inc.push(item)}- return [...virtual, ...sw, ...inc].slice(0, MENTION_LIMIT)+ return [...virtual, ...sw, ...inc]}// Keep TipTap's live `clientRect` resolver rather than a one-time DOMRect.@@ -93,6 +96,7 @@ export function rankMentionItems(// and re-reads this resolver.export interface MentionPopupState {items: MentionItem[]+ query: stringselectedIndex: numbercommand: ((props: { id: string; label: string }) => void) | nullgetRect: (() => DOMRect | null) | null@@ -100,6 +104,7 @@ export interface MentionPopupState {export const EMPTY_MENTION_STATE: MentionPopupState = {items: [],+ query: "",selectedIndex: 0,command: null,getRect: null,@@ -107,6 +112,7 @@ export const EMPTY_MENTION_STATE: MentionPopupState = {type SuggestionProps = {items: MentionItem[]+ query?: stringcommand: (props: { id: string; label: string }) => voidclientRect?: (() => DOMRect | null) | null}@@ -152,12 +158,17 @@ export function buildCommunityMentionExtension(opts: {items: ({ query }: { query: string }) => {if (queryRef) queryRef.current = queryonSearchMembersRef?.current?.(query)- return rankMentionItems(membersRef.current, contextRef.current, query)+ return rankMentionItems(+ query && onSearchMembersRef?.current ? [] : membersRef.current,+ contextRef.current,+ query,+ )},render: () => ({onStart: (props: SuggestionProps) => {setPopup({items: props.items ?? [],+ query: queryRef?.current ?? props.query ?? "",selectedIndex: 0,command: props.command,getRect: props.clientRect ?? null,@@ -166,6 +177,7 @@ export function buildCommunityMentionExtension(opts: {onUpdate: (props: SuggestionProps) => {setPopup((cur) => ({items: props.items ?? [],+ query: queryRef?.current ?? props.query ?? "",selectedIndex:cur.selectedIndex < (props.items?.length ?? 0)? cur.selectedIndex@@ -199,16 +211,21 @@ export function buildCommunityMentionExtension(opts: {event.preventDefault()const item = cur.items[cur.selectedIndex]if (item && cur.command) cur.command({ id: item.id, label: item.label })+ onSearchMembersRef?.current?.("")setPopup(EMPTY_MENTION_STATE)return true}if (event.key === "Escape") {+ onSearchMembersRef?.current?.("")setPopup(EMPTY_MENTION_STATE)return true}return false},- onExit: () => setPopup(EMPTY_MENTION_STATE),+ onExit: () => {+ onSearchMembersRef?.current?.("")+ setPopup(EMPTY_MENTION_STATE)+ },}),},})diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.tsindex dab2c4088..aeb5c9511 100644--- a/src/web/src/lib/community/testids.test.ts+++ b/src/web/src/lib/community/testids.test.ts@@ -32,6 +32,7 @@ describe("community QA selectors", () => {it("exposes stable composer and message-list surfaces", () => {expect(tid.channelComposerShell).toBe("community-composer-shell")+ expect(tid.memberRow("member_1")).toBe("community-member-row-member_1")expect(tid.composerFileInput).toBe("community-composer-file-input")expect(tid.messageScroller).toBe("community-message-scroller")})diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 730ed63b6..bb31d74a4 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -97,6 +97,8 @@ export const tid = {dmRow: (id: string) => `community-dm-row-${id}`,memberRow: (id: string) => `community-member-row-${id}`,mentionOption: (id: string) => `community-mention-option-${id}`,+ mentionPopup: "community-mention-popup",+ mentionStatus: "community-mention-status",channelRefOption: (id: string) => `community-channel-ref-option-${id}`,reactionAdd: (msgId: string) => `community-reaction-add-${msgId}`,messageShare: (msgId: string) => `community-message-share-${msgId}`,diff --git a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.tsnew file mode 100644index 000000000..ce90559ca--- /dev/null+++ b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts@@ -0,0 +1,141 @@+import { test, expect } from "./_fixtures/community-fixture"+import { composerEditable } from "./_fixtures/actions"+import { seedChannel, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"++type Candidate = {+ id: string+ userId: string+ name: string+ discriminator: string+ avatar: string+ status: "offline"+ sub: string+ role: "member"+}++function candidate(prefix: string, index: number): Candidate {+ const tag = String(index).padStart(4, "0")+ return {+ id: `${prefix}-member-${tag}`,+ userId: `${prefix}-user-${tag}`,+ name: `${prefix}${tag}`,+ discriminator: tag,+ avatar: prefix[0] ?? "M",+ status: "offline",+ sub: "",+ role: "member",+ }+}++test("@ candidates page to completion, expose first search page, and keep status anchored on mobile", async ({ asUser }) => {+ const serverId = await seedServer("alice", `Mention pages ${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, "mention-pages")+ const { page } = await asUser("alice")+ await page.setViewportSize({ width: 390, height: 640 })++ const browse = Array.from({ length: 12 }, (_, index) => candidate("Browse", index + 1))+ const matches = Array.from({ length: 205 }, (_, index) => candidate("CapMatch", index + 1))+ let releaseSearchTail!: () => void+ const searchTailReleased = new Promise<void>((resolve) => {+ releaseSearchTail = resolve+ })+ let markSearchTailRequested!: () => void+ const searchTailRequested = new Promise<void>((resolve) => {+ markSearchTailRequested = resolve+ })++ await page.route(`**/api/community/servers/${serverId}/members**`, async (route) => {+ const url = new URL(route.request().url())+ if (url.pathname.endsWith("/members/search")) {+ const query = url.searchParams.get("q") ?? ""+ const cursor = url.searchParams.get("cursor")+ if (query === "Fail") {+ await route.fulfill({ status: 500, json: { error: "forced failure" } })+ return+ }+ if (query === "NoMatch") {+ await route.fulfill({ json: { members: [], limit: 200, hasMore: false } })+ return+ }+ if (query === "CapMatch" && cursor) {+ markSearchTailRequested()+ await searchTailReleased+ await route.fulfill({+ json: { members: matches.slice(200), limit: 200, hasMore: false },+ })+ return+ }+ if (query === "CapMatch") {+ await route.fulfill({+ json: {+ members: matches.slice(0, 200),+ limit: 200,+ hasMore: true,+ cursor: "search-page-2",+ },+ })+ return+ }+ }++ const cursor = url.searchParams.get("cursor")+ await route.fulfill({+ json: cursor+ ? { members: browse.slice(8), limit: 8, total: 12, hasMore: false }+ : {+ members: browse.slice(0, 8),+ limit: 8,+ total: 12,+ hasMore: true,+ cursor: "browse-page-2",+ },+ })+ })++ await page.goto(`/c/channels/${serverId}/${channelId}`)+ const editable = composerEditable(page)+ await expect(editable).toBeVisible({ timeout: 20_000 })+ await editable.click()+ await editable.pressSequentially("@")+ await expect(page.getByTestId(tid.mentionOption(browse[11]!.id))).toHaveCount(1)++ await editable.pressSequentially("CapMatch")+ await searchTailRequested+ await expect(page.getByTestId(tid.mentionOption(matches[0]!.id))).toBeVisible()+ const mentionOptions = page.getByTestId(tid.mentionPopup).getByRole("option")+ await expect(mentionOptions).toHaveCount(200)+ await expect(page.getByTestId(tid.mentionStatus)).toHaveAttribute("data-state", "loading-more")+ releaseSearchTail()+ await expect(page.getByTestId(tid.mentionOption(matches[204]!.id))).toHaveCount(1)+ await expect(mentionOptions).toHaveCount(205)++ const bounds = await page.getByTestId(tid.mentionPopup).evaluate((element) => {+ const rect = element.getBoundingClientRect()+ const viewport = window.visualViewport+ return {+ top: rect.top,+ bottom: rect.bottom,+ left: rect.left,+ right: rect.right,+ width: viewport?.width ?? window.innerWidth,+ height: viewport?.height ?? window.innerHeight,+ }+ })+ expect(bounds.top).toBeGreaterThanOrEqual(0)+ expect(bounds.left).toBeGreaterThanOrEqual(0)+ expect(bounds.bottom).toBeLessThanOrEqual(bounds.height)+ expect(bounds.right).toBeLessThanOrEqual(bounds.width)++ await page.keyboard.press("Escape")+ await editable.press("ControlOrMeta+A")+ await editable.press("Backspace")+ await editable.pressSequentially("@NoMatch")+ await expect(page.getByTestId(tid.mentionStatus)).toHaveAttribute("data-state", "empty")++ await page.keyboard.press("Escape")+ await editable.press("ControlOrMeta+A")+ await editable.press("Backspace")+ await editable.pressSequentially("@Fail")+ await expect(page.getByTestId(tid.mentionStatus)).toHaveAttribute("data-state", "error")+})