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): unify mention member readiness (#909)
Generf13f2f91a17a
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f0f2002ee..77d44074e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -388,6 +388,9 @@ importers:'@tiptap/starter-kit':specifier: ^3.31.4version: 3.31.4+ '@tiptap/suggestion':+ specifier: 3.31.4+ version: 3.31.4(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])'@types/mdx':specifier: ^2.0.14version: 2.0.14diff --git a/src/web/package.json b/src/web/package.jsonindex 7f18259ab..8137a3ea5 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -83,6 +83,7 @@"@tiptap/pm": "^3.31.4","@tiptap/react": "^3.31.4","@tiptap/starter-kit": "^3.31.4",+ "@tiptap/suggestion": "3.31.4","@types/mdx": "^2.0.14","@typesafe-ai/sdk": "0.6.0","better-auth": "1.7.7",diff --git a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts b/src/web/src/components/community/members/channel-member-view-model.dom.test.tsindex 33ad3193b..7e6973dd9 100644--- a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts+++ b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts@@ -11,11 +11,14 @@ const mocks = vi.hoisted(() => ({viewerRole: "admin" as "owner" | "admin" | "member" | undefined,serverMemberArgs: [] as Array<string | null>,channelMembers: new Map<string, Array<Record<string, unknown>>>(),+ channelProfiles: new Map<string, Map<string, Record<string, unknown>>>(),channelQueryState: new Map<string, {resolved?: booleanisLoading?: booleanisError?: booleanisFetching?: boolean+ loading?: boolean+ failed?: boolean}>(),channelRefetches: new Map<string, ReturnType<typeof vi.fn>>(),addableMembers: [] as Array<Record<string, unknown>>,@@ -47,6 +50,9 @@ vi.mock("@/hooks/community/use-server-members", () => ({return {members: mocks.serverMembers,loading: false,+ failed: false,+ searchQuery: "",+ searchStatus: "idle",loadingMore: false,hasMore: true,loadMore: mocks.loadMore,@@ -73,6 +79,9 @@ vi.mock("@/hooks/community/use-channel-members", () => ({isLoading: state?.isLoading ?? (enabled && !resolved && !state?.isError),isError: state?.isError ?? false,isFetching: state?.isFetching ?? false,+ loading: state?.loading ?? (enabled && !resolved && !state?.isError),+ failed: state?.failed ?? state?.isError ?? false,+ profiles: mocks.channelProfiles.get(channelId) ?? profileRows(members),refetch,}}),@@ -108,23 +117,7 @@ vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await...[...mocks.channelMembers.values()].flat(),...mocks.addableMembers,]- const profilesByUserId = new Map(rows.flatMap((row) => {- const userId = row.userId as string | undefined- if (!userId) return []- const status = mocks.userStatuses.get(userId)- return [[userId, {- id: userId,- name: row.name,- discriminator: row.discriminator,- avatar: row.avatar,- avatarVersion: row.avatarVersion ?? 0,- aboutMe: mocks.profileAboutMe.get(userId) ?? "",- presence: mocks.onlineUserIds.has(userId) ? "online" : "offline",- statusEmoji: status?.emoji,- statusText: status?.text,- }]]- }))- return profilesByUserId+ return profileRows(rows)},}))vi.mock("@/components/community/members/add-members-dialog", () => ({@@ -138,6 +131,25 @@ const mockedAddMembersDialog = vi.mocked(AddMembersDialog)const mockedUseAddableMembers = vi.mocked(useAddableMembers)const mockedUseChannelMembers = vi.mocked(useChannelMembers)+function profileRows(rows: Array<Record<string, unknown>>) {+ return new Map(rows.flatMap((row) => {+ const userId = row.userId as string | undefined+ if (!userId) return []+ const status = mocks.userStatuses.get(userId)+ return [[userId, {+ id: userId,+ name: row.name,+ discriminator: row.discriminator,+ avatar: row.avatar,+ avatarVersion: row.avatarVersion ?? 0,+ aboutMe: mocks.profileAboutMe.get(userId) ?? "",+ presence: mocks.onlineUserIds.has(userId) ? "online" : "offline",+ statusEmoji: status?.emoji,+ statusText: status?.text,+ }]]+ }))+}+function member(userId: string, name: string, overrides: Record<string, unknown> = {}) {return {id: `member_${userId}`,@@ -200,6 +212,7 @@ describe("useChannelMemberViewModel", () => {]mocks.serverMemberArgs = []mocks.channelMembers = new Map()+ mocks.channelProfiles = new Map()mocks.channelQueryState = new Map()mocks.channelRefetches = new Map()mocks.addableMembers = []@@ -394,6 +407,7 @@ describe("useChannelMemberViewModel", () => {expect(latestModel().memberPanelProps.members.map((row) => row.userId)).toEqual(["viewer_1", "alice_1"])expect(latestModel().memberPanelProps.members.every((row) => row.source === undefined)).toBe(true)expect(latestModel().composerMembers.map((row) => row.userId)).toEqual(["alice_1", "bob_1"])+ expect(latestModel().composerMentionCandidates).toMatchObject({ loading: false, failed: false })act(() => {latestModel().memberPanelProps.onAddMember?.()@@ -416,6 +430,27 @@ describe("useChannelMemberViewModel", () => {expect(mocks.removeChannelMember).not.toHaveBeenCalled()})+ it("keeps private mentions on the parent access read and its own profile snapshot through notify failure and revocation", () => {+ mocks.channelMembers.set("parent_1", [member("peer", "Nickname")])+ mocks.channelProfiles.set("parent_1", new Map([["peer", { id: "peer", name: "Canonical", discriminator: "0042", avatar: "C", avatarVersion: 2, presence: "online" }]]))+ mocks.channelQueryState.set("parent_1", { resolved: true, loading: true, failed: false })+ mocks.channelQueryState.set("thread_1", { resolved: false, isError: true, failed: true })+ const modelProps = props({ channelId: "thread_1", currentServer: { categories: [{ private: true, channels: [{ id: "parent_1" }] }] }, channelInServer: null, currentChannelMeta: { parentChannelId: "parent_1" }, isChildChannel: true, isNotifyUnit: true })+ let renderer!: ReturnType<typeof rtlRender>+ act(() => { renderer = rtlRender(renderHarness(modelProps)) })+ expect(latestModel().composerMentionCandidates).toEqual({ loading: true, failed: false })+ expect(latestModel().composerMembers).toEqual([expect.objectContaining({ userId: "peer", name: "Canonical", discriminator: "0042", avatar: "C", status: "online" })])+ mocks.channelQueryState.set("parent_1", { resolved: true, loading: false, failed: true })+ act(() => renderer.rerender(renderHarness(modelProps)))+ expect(latestModel().composerMentionCandidates).toEqual({ loading: false, failed: true })+ expect(latestModel().composerMembers).toHaveLength(1)+ mocks.channelQueryState.set("parent_1", { resolved: true, loading: false, failed: false })+ act(() => renderer.rerender(renderHarness(modelProps)))+ expect(latestModel().composerMentionCandidates).toEqual({ loading: false, failed: false })+ act(() => renderer.rerender(renderHarness({ ...modelProps, accessAllowed: false })))+ expect(latestModel().composerMembers).toEqual([])+ })+it("gates thread candidates on both query sources and retries only unresolved sources", () => {mocks.channelMembers.set("thread_1", [member("viewer_1", "Viewer", { isCreator: true }),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 d3f748297..909416464 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@@ -247,17 +247,18 @@ export function useChannelMemberViewModel({profilesByUserId,])+ const composerMemberSource = isNotifyUnit ? parentChannelMembersHook : channelMembersHookconst composerMembers = useMemo(() => {+ if (!accessAllowed) return []if (!currentChannelPrivate) {return members.filter((member) => member.userId !== currentUser.id)}- const roster = isNotifyUnit ? parentChannelMembersHook.members : channelMembersHook.members- return roster+ return composerMemberSource.members.filter((member): member is typeof member & { role: Role } => member.role !== null).filter((member) => member.userId !== currentUser.id).map((member) => {const profile = readCommunityProfile(- profilesByUserId.get(member.userId),+ composerMemberSource.profiles.get(member.userId),member.userId,)return {@@ -272,18 +273,17 @@ export function useChannelMemberViewModel({}})}, [- channelMembersHook.members,+ accessAllowed,+ composerMemberSource.members,+ composerMemberSource.profiles,currentChannelPrivate,currentUser.id,- isNotifyUnit,members,- parentChannelMembersHook.members,- profilesByUserId,])const composerMentionCandidates = useMemo<MentionCandidateSource | undefined>(() => currentChannelPrivate- ? undefined+ ? { loading: composerMemberSource.loading, failed: composerMemberSource.failed }: {loading: membersHook.loading,loadingMore: membersHook.loadingMore,@@ -296,6 +296,8 @@ export function useChannelMemberViewModel({},[currentChannelPrivate,+ composerMemberSource.loading,+ composerMemberSource.failed,membersHook.failed,membersHook.hasMore,membersHook.loadMore,diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsxnew file mode 100644index 000000000..98af022fe--- /dev/null+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx@@ -0,0 +1,251 @@+import { createRef, useLayoutEffect } from "react"+import { EditorContent, type Editor } from "@tiptap/react"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { act, fireEvent, screen, waitFor } from "@/test/react-dom-harness"+import { renderCommunity as render } from "@/test/community-owner-harness"+import { readComposerDraft, writeComposerDraft } from "@/lib/community/composer-draft"+import type { Member } from "@/lib/community/models/people"+import { CommunityMentionList, ChannelRefList } from "./composer-suggestion-popups"+import type { ComposerHandle, ComposerProps } from "./composer-types"+import { useComposerController } from "./use-composer-controller"++const files = vi.hoisted(() => ({+ pendingFiles: [], readPendingFiles: () => [], setPendingFiles: vi.fn(),+ transferPendingFiles: vi.fn(), awaitPendingFiles: async () => [], addPendingFiles: vi.fn(),+ fileInputRef: { current: null }, handleFileSelect: vi.fn(), removePendingFile: vi.fn(),+ dragging: false, handleDragEnter: vi.fn(), handleDragLeave: vi.fn(),+ handleDragOver: vi.fn(), handleDrop: vi.fn(),+}))+vi.mock("@/hooks/use-file-attachments", () => ({ useFileAttachments: () => files }))+vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))++type View = ReturnType<typeof useComposerController>+type Probe = { current: View | null }+const ada: Member = { id: "member-ada", userId: "user-ada", name: "Ada", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "online", sub: "", role: "member" }+const general = { id: "channel-general", name: "general", serverId: "server-one", serverName: "One", serverDiscriminator: "0001" }+const props: ComposerProps = {+ channel: "general", context: "channel", members: [ada], channelRefCandidates: [general],+ sendContract: "accepted", onAcceptSend: () => true, hideAttach: true, hideEmoji: true,+}++function Harness({ probeRef, handle, ...options }: ComposerProps & { probeRef: Probe; handle?: React.Ref<ComposerHandle> }) {+ const view = useComposerController(options, handle ?? null)+ useLayoutEffect(() => { probeRef.current = view }, [probeRef, view])+ return <>+ <EditorContent editor={view.editor} />+ <CommunityMentionList state={view.mentionPopup} presentation={view.mentionPresentation} />+ <ChannelRefList state={view.channelRefPopup} presentation={view.channelRefPresentation} />+ </>+}++async function editorOf(probeRef: Probe): Promise<Editor> {+ await waitFor(() => expect(probeRef.current?.editor).toBeTruthy())+ return probeRef.current!.editor!+}++async function type(editor: Editor, value: string) {+ await act(async () => {+ editor.view.dom.focus()+ editor.commands.insertContent(value)+ })+}++describe("composer suggestion focus with installed TipTap", () => {+ beforeEach(() => {+ localStorage.clear()+ const rect = new DOMRect(10, 20, 1, 18)+ Object.defineProperty(Range.prototype, "getBoundingClientRect", { configurable: true, value: () => rect })+ Object.defineProperty(Range.prototype, "getClientRects", { configurable: true, value: () => [rect] })+ })+ afterEach(() => {+ delete (Range.prototype as Partial<Range>).getBoundingClientRect+ delete (Range.prototype as Partial<Range>).getClientRects+ })++ it.each(["@", "@a", "/"])("restores %s without opening; focus alone stays quiet and an edit opens", async (trigger) => {+ const probeRef: Probe = { current: null }+ const draft = { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: trigger }] }] }+ writeComposerDraft("viewer:focus-draft", draft)+ render(<Harness {...props} probeRef={probeRef} draftKey="focus-draft" autoFocus />)+ const editor = await editorOf(probeRef)+ await waitFor(() => expect(editor.isFocused).toBe(true))+ expect(editor.getText()).toBe(trigger)+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(probeRef.current!.channelRefPopup.command).toBeNull()+ expect(screen.queryByTestId("community-mention-popup")).toBeNull()+ expect(screen.queryByTestId("community-channel-ref-popup")).toBeNull()+ expect(readComposerDraft("viewer:focus-draft")).toEqual(draft)+ const suffix = trigger.startsWith("@") ? trigger === "@" ? "a" : "d" : "g"+ await type(editor, suffix)+ await waitFor(() => expect(trigger.startsWith("@") ? probeRef.current!.mentionPopup.command : probeRef.current!.channelRefPopup.command).toBeTypeOf("function"))+ expect(editor.getText()).toBe(`${trigger}${suffix}`)+ })++ it.each(["@", "/"])("keeps the active %s candidate and caret when automatic focus turns on", async (trigger) => {+ const probeRef: Probe = { current: null }+ const options = { ...props, probeRef, draftKey: "autofocus-boundary" }+ const renderer = render(<Harness {...options} autoFocus={false} />)+ const editor = await editorOf(probeRef)+ await type(editor, trigger === "@" ? "@a" : "/g")+ const rowId = trigger === "@" ? "community-mention-option-member-ada" : "community-channel-ref-option-channel-general"+ await screen.findByTestId(rowId)+ const selection = editor.state.selection.toJSON()+ const draft = editor.getJSON()++ for (const autoFocus of [true, false, true]) {+ await act(async () => { renderer.rerender(<Harness {...options} autoFocus={autoFocus} />) })+ expect(document.activeElement).toBe(editor.view.dom)+ expect(editor.isFocused).toBe(true)+ expect(editor.state.selection.toJSON()).toEqual(selection)+ expect(editor.getJSON()).toEqual(draft)+ expect(readComposerDraft("viewer:autofocus-boundary")).toEqual(draft)+ expect(screen.getByTestId(rowId)).toBeVisible()+ }++ await act(async () => { fireEvent.mouseDown(screen.getByTestId(rowId)) })+ const nodeType = trigger === "@" ? "mention" : "channelRef"+ expect(editor.getJSON().content?.[0].content?.filter((node) => node.type === nodeType)).toEqual([+ expect.objectContaining({ attrs: expect.objectContaining({ id: trigger === "@" ? ada.id : general.id }) }),+ ])+ expect(screen.queryByTestId(rowId)).toBeNull()+ expect(readComposerDraft("viewer:autofocus-boundary")).toEqual(editor.getJSON())+ })++ it.each(["@", "/"])("moves focus between composers with only one %s popup and inert old insertion", async (trigger) => {+ const parent: Probe = { current: null }, thread: Probe = { current: null }+ render(<><Harness {...props} probeRef={parent} draftKey="parent" /><Harness {...props} context="thread" channel="thread" probeRef={thread} draftKey="thread" /></>)+ const first = await editorOf(parent), second = await editorOf(thread)+ await type(first, trigger)+ await waitFor(() => expect(trigger === "@" ? parent.current!.mentionPopup.command : parent.current!.channelRefPopup.command).toBeTypeOf("function"))+ const stale = trigger === "@" ? parent.current!.mentionPopup.command! : parent.current!.channelRefPopup.command!+ await type(second, trigger)+ await waitFor(() => expect(trigger === "@" ? thread.current!.mentionPopup.command : thread.current!.channelRefPopup.command).toBeTypeOf("function"))+ expect(parent.current!.mentionPopup.command).toBeNull()+ expect(parent.current!.channelRefPopup.command).toBeNull()+ expect(screen.getAllByTestId(trigger === "@" ? "community-mention-popup" : "community-channel-ref-popup")).toHaveLength(1)+ await act(async () => { stale({ id: "stale", label: "stale", serverId: "server-one", serverName: "One", serverDiscriminator: "0001" }) })+ expect(first.getText()).toBe(trigger)+ expect(second.getText()).toBe(trigger)+ expect(readComposerDraft("viewer:parent")).toEqual(first.getJSON())+ })++ it("preserves focus on candidate mousedown and inserts one canonical mention", async () => {+ const probeRef: Probe = { current: null }+ render(<Harness {...props} probeRef={probeRef} draftKey="clicked" />)+ const editor = await editorOf(probeRef)+ await type(editor, "@a")+ const row = await screen.findByTestId("community-mention-option-member-ada")+ await act(async () => { fireEvent.mouseDown(row) })+ expect(editor.isFocused).toBe(true)+ expect(editor.getJSON().content?.[0].content?.filter((node) => node.type === "mention")).toEqual([+ expect.objectContaining({ attrs: expect.objectContaining({ id: ada.id, label: "Ada#0001" }) }),+ ])+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(readComposerDraft("viewer:clicked")).toEqual(editor.getJSON())+ })++ it.each(["Enter", "Tab"])("keeps IME confirmation inert, then %s inserts once", async (key) => {+ const probeRef: Probe = { current: null }+ render(<Harness {...props} probeRef={probeRef} />)+ const editor = await editorOf(probeRef)+ await type(editor, "@a")+ await screen.findByTestId("community-mention-option-member-ada")+ await act(async () => {+ fireEvent.compositionStart(editor.view.dom)+ fireEvent.keyDown(editor.view.dom, { key, isComposing: true })+ })+ expect(editor.getText()).toBe("@a")+ expect(probeRef.current!.mentionPopup.command).toBeTypeOf("function")+ await act(async () => { fireEvent.compositionEnd(editor.view.dom) })+ await waitFor(() => expect(editor.view.composing).toBe(false))+ expect(probeRef.current!.mentionPopup.items.map((item) => item.id)).toEqual([ada.id])+ await act(async () => { fireEvent.keyDown(editor.view.dom, { key }) })+ expect(editor.getText()).toBe("@a")+ expect(probeRef.current!.mentionPopup.command).toBeTypeOf("function")+ await act(async () => { fireEvent.keyDown(editor.view.dom, { key }) })+ expect(editor.getJSON().content?.[0].content?.filter((node) => node.type === "mention")).toHaveLength(1)+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ })++ it.each(["@", "/"])("Escape closes empty/loading %s and canonical data cannot reopen it", async (trigger) => {+ const probeRef: Probe = { current: null }+ const search = vi.fn(), intent = vi.fn()+ const loading = { loading: true, failed: false }+ const renderer = render(<Harness {...props} probeRef={probeRef} members={[]} channelRefCandidates={[]} mentionCandidates={{ ...loading, search, searchQuery: "missing", searchStatus: "loading" }} channelRefCandidateSource={loading} onChannelRefIntent={intent} />)+ const editor = await editorOf(probeRef)+ await type(editor, `${trigger}missing`)+ await waitFor(() => expect(trigger === "@" ? probeRef.current!.mentionPopup.command : probeRef.current!.channelRefPopup.command).toBeTypeOf("function"))+ await act(async () => { fireEvent.keyDown(editor.view.dom, { key: "Escape" }) })+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(probeRef.current!.channelRefPopup.command).toBeNull()+ await act(async () => { renderer.rerender(<Harness {...props} probeRef={probeRef} members={[{ ...ada, name: "missing" }]} channelRefCandidates={[{ ...general, name: "missing" }]} mentionCandidates={{ loading: false, failed: false, search, searchQuery: "missing", searchStatus: "ready" }} channelRefCandidateSource={{ loading: false, failed: false }} onChannelRefIntent={intent} />) })+ await act(async () => { editor.view.dispatch(editor.state.tr) })+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(probeRef.current!.channelRefPopup.command).toBeNull()+ expect(editor.getText()).toBe(`${trigger}missing`)+ })++ it("ends old scope before rebinding search, preserves draft and allows a new DM slash", async () => {+ const probeRef: Probe = { current: null }+ const oldSearch = vi.fn(), nextSearch = vi.fn()+ const renderer = render(<Harness {...props} probeRef={probeRef} draftKey="channel" mentionCandidates={{ loading: false, failed: false, search: oldSearch }} />)+ const editor = await editorOf(probeRef)+ await type(editor, "@")+ await waitFor(() => expect(probeRef.current!.mentionPopup.command).toBeTypeOf("function"))+ const stale = probeRef.current!.mentionPopup.command!+ oldSearch.mockClear()+ await act(async () => { renderer.rerender(<Harness {...props} probeRef={probeRef} context="dm" channel="Ada" draftKey="dm" mentionCandidates={{ loading: false, failed: false, search: nextSearch }} />) })+ expect(oldSearch).toHaveBeenCalledExactlyOnceWith("")+ expect(nextSearch).not.toHaveBeenCalled()+ await act(async () => { stale({ id: ada.id, label: "Ada#0001" }); editor.commands.clearContent(); editor.commands.insertContent("/") })+ await waitFor(() => expect(probeRef.current!.channelRefPopup.command).toBeTypeOf("function"))+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(editor.getText()).toBe("/")+ })++ it.each(["@", "/"])("a new scope restores %s quietly, then accepts its current edit", async (trigger) => {+ const probeRef: Probe = { current: null }+ writeComposerDraft("viewer:next", { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: trigger }] }] })+ const renderer = render(<Harness {...props} probeRef={probeRef} draftKey="previous" />)+ const editor = await editorOf(probeRef)+ await type(editor, trigger)+ await waitFor(() => expect(trigger === "@" ? probeRef.current!.mentionPopup.command : probeRef.current!.channelRefPopup.command).toBeTypeOf("function"))+ await act(async () => { renderer.rerender(<Harness {...props} probeRef={probeRef} channel="next" draftKey="next" autoFocus />) })+ expect(editor.getText()).toBe(trigger)+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(probeRef.current!.channelRefPopup.command).toBeNull()+ await type(editor, trigger === "@" ? "a" : "g")+ await waitFor(() => expect(trigger === "@" ? probeRef.current!.mentionPopup.command : probeRef.current!.channelRefPopup.command).toBeTypeOf("function"))+ expect(readComposerDraft("viewer:next")).toEqual(editor.getJSON())+ })++ it("clear then one @ stays one @ and persists current JSON", async () => {+ const probeRef: Probe = { current: null }, handle = createRef<ComposerHandle>()+ writeComposerDraft("viewer:clear", { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "@" }] }] })+ render(<Harness {...props} probeRef={probeRef} handle={handle} draftKey="clear" />)+ const editor = await editorOf(probeRef)+ await act(async () => { handle.current!.focusEditor() })+ await waitFor(() => expect(editor.isFocused).toBe(true))+ await act(async () => { editor.commands.clearContent() })+ expect(editor.isEmpty).toBe(true)+ expect(readComposerDraft("viewer:clear")).toBeNull()+ await type(editor, "@")+ await waitFor(() => expect(probeRef.current!.mentionPopup.command).toBeTypeOf("function"))+ expect(editor.getText()).toBe("@")+ expect(readComposerDraft("viewer:clear")).toEqual(editor.getJSON())+ })++ it("destroy clears the visible suggestion without dispatch to the dying view", async () => {+ const probeRef: Probe = { current: null }+ const renderer = render(<Harness {...props} probeRef={probeRef} />)+ const editor = await editorOf(probeRef)+ await type(editor, "@")+ await waitFor(() => expect(probeRef.current!.mentionPopup.command).toBeTypeOf("function"))+ const dispatch = vi.spyOn(editor.view, "dispatch")+ await act(async () => { editor.destroy() })+ expect(dispatch).not.toHaveBeenCalled()+ expect(probeRef.current!.mentionPopup.command).toBeNull()+ expect(probeRef.current!.channelRefPopup.command).toBeNull()+ renderer.unmount()+ })+})diff --git a/src/web/src/components/community/messages/composer-types.ts b/src/web/src/components/community/messages/composer-types.tsindex 90c81e394..f1b645e13 100644--- a/src/web/src/components/community/messages/composer-types.ts+++ b/src/web/src/components/community/messages/composer-types.ts@@ -18,19 +18,19 @@ export type ComposerMention = {export type MentionCandidateSource = {loading: boolean- loadingMore: boolean- hasMore: boolean+ loadingMore?: boolean+ hasMore?: booleanfailed: boolean- searchQuery: string- searchStatus:+ searchQuery?: string+ searchStatus?:| "idle"| "loading"| "loading-more"| "ready"| "empty"| "error"- loadMore: () => void- search: (query: string) => void+ loadMore?: () => void+ search?: (query: string) => void}export type ChannelRefCandidateSource = {diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.tsindex 1098762f5..e3610f7c6 100644--- a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts+++ b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts@@ -31,14 +31,14 @@ vi.mock("@tiptap/pm/model", () => ({}))vi.mock("@/lib/community/mention-extension", () => ({- buildCommunityMentionExtension: vi.fn(() => ({})),+ buildCommunityMentionExtension: vi.fn(() => ({ options: { suggestion: { pluginKey: {} } } })),detectMentionType: vi.fn(() => undefined),EMPTY_MENTION_STATE: { items: [], selectedIndex: 0, command: null, getRect: null },rankMentionItems: vi.fn(() => []),}))vi.mock("@/lib/community/channel-ref-extension", () => ({- buildCommunityChannelRefExtension: vi.fn(() => ({})),+ buildCommunityChannelRefExtension: vi.fn(() => ({ options: { suggestion: { pluginKey: {} } } })),EMPTY_CHANNEL_REF_STATE: { items: [], selectedIndex: 0, command: null, getRect: null },rankChannelRefItems: vi.fn(() => []),toChannelRefCommandProps: vi.fn(),@@ -65,6 +65,8 @@ vi.mock("@/hooks/community/mutations/messages", async (importOriginal) => ({sendNonce: () => "nonce_collision",}))+vi.mock("@tiptap/suggestion", () => ({ exitSuggestion: vi.fn() }))+import { Composer, type ComposerProps } from "./composer"import type { PendingFile } from "@/hooks/use-file-attachments"@@ -92,6 +94,11 @@ describe("Composer committed send lifecycle", () => {awaitPendingFiles = vi.fn(async () => pendingFiles)const editor = {+ on: vi.fn(), off: vi.fn(),+ state: { tr: {} },+ isFocused: true,+ isDestroyed: false,+ view: { dispatch: vi.fn() },isEmpty: false,getText: vi.fn(() => "latest draft"),getJSON: vi.fn(() => ({})),diff --git a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts b/src/web/src/components/community/messages/use-composer-controller.dom.test.tsindex 4d832e0a4..59fb61367 100644--- a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts+++ b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts@@ -114,9 +114,14 @@ type EditorOptions = {clipboardTextParser: (text: string, context: never) => unknown}onUpdate: (props: { editor: TestEditor }) => void+ onBlur: (props: { editor: TestEditor }) => void}type TestEditor = {+ on: ReturnType<typeof vi.fn>+ off: ReturnType<typeof vi.fn>+ isFocused: boolean+ isDestroyed: booleanisEmpty: booleangetText: ReturnType<typeof vi.fn>getJSON: ReturnType<typeof vi.fn>@@ -155,6 +160,7 @@ const Harness = forwardRef<ComposerHandle, ComposerProps>(describe("useComposerController", () => {let editorOptions: EditorOptions+ let destroyCallback: () => voidlet pendingFiles: PendingFile[]let editor: TestEditorlet clearContent: ReturnType<typeof vi.fn>@@ -196,6 +202,10 @@ describe("useComposerController", () => {mentionPopupRef = { current: { items: [], command: null } }channelRefPopupRef = { current: { items: [], command: null } }editor = {+ on: vi.fn((_event, callback) => { destroyCallback = callback }),+ off: vi.fn(),+ isFocused: true,+ isDestroyed: false,isEmpty: false,getText: vi.fn(() => " hello @everyone "),getJSON: vi.fn(() => ({ type: "doc" })),@@ -268,6 +278,7 @@ describe("useComposerController", () => {})afterEach(() => {+ vi.unstubAllGlobals()vi.useRealTimers()})@@ -962,6 +973,7 @@ describe("useComposerController", () => {})it("leaves a focused persistent rail item in charge when a conversation mounts", async () => {+ editor.isFocused = falseconst rail = document.createElement("div")rail.setAttribute("data-testid", "community-server-rail-scroll")const button = document.createElement("button")@@ -993,6 +1005,7 @@ describe("useComposerController", () => {})it("preserves autofocus, reply edge, drop, dropdown, upload, and emoji timing", async () => {+ editor.isFocused = falseconst accept = vi.fn(() => true)let renderer!: ReturnType<typeof render>await act(async () => {@@ -1273,6 +1286,58 @@ describe("useComposerController", () => {})})+ it("uses live editor focus and retires suggestions on public blur/destroy", () => {+ render(createElement(Harness, acceptedProps(vi.fn(() => true))))+ const eligible = () => mocks.useSuggestions.mock.lastCall![0].canSuggest(editor)+ expect(eligible()).toBe(true)+ editor.isFocused = false+ expect(eligible()).toBe(false)+ act(() => editorOptions.onBlur({ editor }))+ expect(resetPopups).toHaveBeenLastCalledWith(editor)+ editor.isFocused = true+ expect(eligible()).toBe(true)+ act(() => destroyCallback())+ expect(resetPopups).toHaveBeenLastCalledWith(editor, false)+ expect(eligible()).toBe(false)+ })++ it("restores suppression through nested focus calls and thrown commands", () => {+ const handle = createRef<ComposerHandle>()+ render(createElement(Harness, { ...acceptedProps(vi.fn(() => true)), ref: handle }))+ const eligible = () => mocks.useSuggestions.mock.lastCall![0].canSuggest(editor)+ focus.mockImplementationOnce(() => {+ expect(eligible()).toBe(false)+ expect(() => handle.current!.focusEditor()).toThrow("focus failure")+ expect(eligible()).toBe(false)+ }).mockImplementationOnce(() => {+ expect(eligible()).toBe(false)+ throw new Error("focus failure")+ })+ act(() => handle.current!.focusEditor())+ expect(eligible()).toBe(true)+ })++ it("suppresses suggestion eligibility while restoring draft without suppressing later edits", () => {+ mocks.readDraft.mockReturnValue({ type: "doc" })+ setContent.mockImplementation(() => expect(mocks.useSuggestions.mock.lastCall![0].canSuggest(editor)).toBe(false))+ render(createElement(Harness, acceptedProps(vi.fn(() => true))))+ expect(setContent).toHaveBeenCalledOnce()+ expect(resetPopups).toHaveBeenCalledWith(editor)+ expect(mocks.useSuggestions.mock.lastCall![0].canSuggest(editor)).toBe(true)+ })++ it("ignores a delayed destroy callback from the previous editor", () => {+ const options = acceptedProps(vi.fn(() => true))+ const renderer = render(createElement(Harness, options))+ const oldDestroy = destroyCallback+ editor = { ...editor, view: { ...editor.view } }+ renderer.rerender(createElement(Harness, options))+ resetPopups.mockClear()+ act(() => oldDestroy())+ expect(resetPopups).not.toHaveBeenCalled()+ expect(mocks.useSuggestions.mock.lastCall![0].canSuggest(editor)).toBe(true)+ })+it("pins the layout/draft/typing ordering boundaries in source", () => {const source = readFileSync(resolve(diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.tsindex f4788a39f..c4da46ca7 100644--- a/src/web/src/components/community/messages/use-composer-controller.ts+++ b/src/web/src/components/community/messages/use-composer-controller.ts@@ -95,18 +95,24 @@ export function useComposerController(const typingTimer = useRef<NodeJS.Timeout | null>(null)const sendRef = useRef<() => void>(() => {})const editorRef = useRef<Editor | null>(null)- useLayoutEffect(() => {- const nextScope = `${context}\u0000${channel}\u0000${draftKey ?? ""}`- protocol.setState((state) => ({ ...state, draftKey, scope: nextScope, ...(state.scope !== nextScope ? { scopeVersion: state.scopeVersion + 1, nextLongPasteIndex: 1 } : {}) }))- }, [channel, context, draftKey, protocol])- useLayoutEffect(() => {- protocol.setState((state) => ({ ...state, active: true }))- return () => protocol.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))+ const scope = `${context}\u0000${channel}\u0000${draftKey ?? ""}`+ const canSuggest = useCallback((candidate: Editor) => {+ const current = protocol.get()+ return candidate === editorRef.current && current.active && current.scope === scope &&+ !current.suppress && !candidate.isDestroyed && candidate.isFocused+ }, [protocol, scope])+ const suppressSuggestions = useCallback((operation: () => void) => {+ const previous = protocol.get().suppress+ protocol.setState((state) => ({ ...state, suppress: true }))+ try { operation() } finally { protocol.setState((state) => ({ ...state, suppress: previous })) }}, [protocol])const resolvedPlaceholder = placeholder ?? (context === "channel" ? `Message /${channel}` : `Message ${channel}`)const placeholderRef = useRef(resolvedPlaceholder)const resolvePlaceholder = useCallback(() => placeholderRef.current, [])const suggestions = useComposerSuggestions({+ editorRef,+ canSuggest,+ scope,members,context,mentionCandidates,@@ -114,6 +120,10 @@ export function useComposerController(channelRefCandidateSource,onChannelRefIntent,})+ const { resetPopups } = suggestions+ useLayoutEffect(() => {+ protocol.setState((state) => ({ ...state, draftKey, scope, ...(state.scope !== scope ? { scopeVersion: state.scopeVersion + 1, nextLongPasteIndex: 1 } : {}) }))+ }, [scope, draftKey, protocol])const fireTyping = () => {if (!onTyping || typingTimer.current) returnonTyping()@@ -202,7 +212,22 @@ export function useComposerController()}},+ onBlur: ({ editor: blurredEditor }) => resetPopups(blurredEditor),})+ useLayoutEffect(() => {+ protocol.setState((state) => ({ ...state, active: true }))+ const onDestroy = () => {+ if (editorRef.current !== editor) return+ protocol.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))+ resetPopups(editor, false)+ }+ editor?.on("destroy", onDestroy)+ return () => {+ protocol.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))+ editor?.off("destroy", onDestroy)+ resetPopups(editor)+ }+ }, [editor, protocol, resetPopups])useLayoutEffect(() => {editorRef.current = editorreturn () => { if (editorRef.current === editor) editorRef.current = null }@@ -221,16 +246,18 @@ export function useComposerController(if (!editor || isForumThreadBody || !draftKey) returnconst doc = readComposerDraft(draftKey)if (!doc) return- protocol.setState((state) => ({ ...state, suppress: true }))- try {- editor.commands.setContent(doc as JSONContent, {- emitUpdate: false,- errorOnInvalidContent: true,- })- setEditorHasContent(!editor.isEmpty)- } catch {- clearComposerDraft(draftKey)- } finally { protocol.setState((state) => ({ ...state, suppress: false })) }+ resetPopups(editor)+ suppressSuggestions(() => {+ try {+ editor.commands.setContent(doc as JSONContent, {+ emitUpdate: false,+ errorOnInvalidContent: true,+ })+ setEditorHasContent(!editor.isEmpty)+ } catch {+ clearComposerDraft(draftKey)+ }+ })// eslint-disable-next-line react-hooks/exhaustive-deps}, [editor, draftKey])const onDirtyRef = useRef(onDirty)@@ -271,7 +298,7 @@ export function useComposerController(if (protocol.get().draftKey) clearComposerDraft(protocol.get().draftKey!)transferPendingFiles()protocol.setState((state) => ({ ...state, nextLongPasteIndex: 1 }))- suggestions.resetPopups()+ resetPopups()},})const send = () => {@@ -287,7 +314,7 @@ export function useComposerController(useImperativeHandle(ref, () => ({focusEditor: () => {- editor?.commands.focus("end")+ suppressSuggestions(() => editor?.commands.focus("end"))},insertTextAtCaret: (text) => {if (!editor || !text) return@@ -306,7 +333,7 @@ export function useComposerController(setEditorHasContent(false)setPendingFiles([])protocol.setState((state) => ({ ...state, nextLongPasteIndex: 1 }))- suggestions.resetPopups()+ resetPopups()},isEmpty: () => !editor || (editor.isEmpty && pendingFiles.length === 0),openFilePicker: () => {@@ -315,23 +342,23 @@ export function useComposerController(}))useEffect(() => {- if (!autoFocus || !editor || isForumThreadBody) return+ if (!autoFocus || !editor || isForumThreadBody || editor.isFocused) returnif (document.activeElement?.closest(`[data-testid="${tid.serverRailScroll}"]`)) return- editor.commands.focus("end")- }, [autoFocus, editor, channel, isForumThreadBody])+ suppressSuggestions(() => editor.commands.focus("end"))+ }, [autoFocus, editor, channel, isForumThreadBody, suppressSuggestions])const previousReplyingToRef = useRef(replyingTo)useEffect(() => {const targetChanged = previousReplyingToRef.current !== replyingTopreviousReplyingToRef.current = replyingToif (targetChanged && replyingTo && editor && !isForumThreadBody) {- editor.commands.focus("end")+ suppressSuggestions(() => editor.commands.focus("end"))}- }, [replyingTo, editor, isForumThreadBody])+ }, [replyingTo, editor, isForumThreadBody, suppressSuggestions])const handleDrop = (event: DragEvent<HTMLDivElement>) => {handleDropRaw(event)- editor?.commands.focus()+ suppressSuggestions(() => editor?.commands.focus())}return {diff --git a/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.dom.test.tsindex a5a9c38ac..0ee0f2e0d 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts@@ -34,12 +34,18 @@ vi.mock("@/lib/community/channel-ref-extension", () => ({rankChannelRefItems: (...args: unknown[]) => mocks.rankChannel(...args),}))+vi.mock("@tiptap/suggestion", () => ({ exitSuggestion: vi.fn() }))+import { useComposerSuggestions } from "./use-composer-suggestions"+import { exitSuggestion } from "@tiptap/suggestion"import type { ChannelRefCandidate } from "@/lib/community/channel-ref-extension"import type { Member } from "@/lib/community/models/people"-type Options = Parameters<typeof useComposerSuggestions>[0]+type Options = Omit<Parameters<typeof useComposerSuggestions>[0], "editorRef" | "canSuggest" | "scope">type Result = ReturnType<typeof useComposerSuggestions>+const editor = { isFocused: true, isDestroyed: false } as import("@tiptap/react").Editor+const editorRef = { current: editor }+const canSuggest = (candidate: import("@tiptap/react").Editor) => candidate === editor && candidate.isFocusedfunction Harness({resultRef,@@ -49,7 +55,7 @@ function Harness({resultRef: { current: Result | null }presentationHistory?: Array<Result["channelRefPresentation"]>}) {- const result = useComposerSuggestions(options)+ const result = useComposerSuggestions({ ...options, editorRef, canSuggest, scope: options.context })presentationHistory?.push(result.channelRefPresentation)useEffect(() => {resultRef.current = result@@ -104,12 +110,15 @@ const channelRefSource = (describe("useComposerSuggestions", () => {beforeEach(() => {+ editor.isFocused = true+ vi.mocked(exitSuggestion).mockClear()mocks.buildMention.mockReset()mocks.buildChannel.mockReset()mocks.rankMention.mockReset()mocks.rankChannel.mockReset()mocks.buildMention.mockImplementation((options) => ({name: "mention-extension",+ options: { suggestion: { pluginKey: {} } },allow: () => options.contextRef.current !== "dm",runQuery: (query: string) => {if (options.contextRef.current === "dm") return []@@ -124,6 +133,7 @@ describe("useComposerSuggestions", () => {}))mocks.buildChannel.mockImplementation((options) => ({name: "channel-extension",+ options: { suggestion: { pluginKey: {} } },runQuery: (query: string) => {options.queryRef.current = queryoptions.onIntentRef.current?.()@@ -134,6 +144,33 @@ describe("useComposerSuggestions", () => {mocks.rankChannel.mockReturnValue([])})+ it("clears refs synchronously, exits actual keys, and rejects old editor reset", () => {+ const resultRef: { current: Result | null } = { current: null }+ rtlRender(createElement(Harness, { members: [], context: "channel", channelRefCandidates: [], resultRef }))+ const mention = mocks.buildMention.mock.calls[0][0]+ act(() => mention.setPopup({ items: [], query: "a", selectedIndex: 0, command: vi.fn(), getRect: null }))+ vi.mocked(exitSuggestion).mockClear()+ const current = resultRef.current!+ act(() => {+ current.resetPopups(editor)+ expect(current.mentionPopupRef.current.command).toBeNull()+ expect(current.channelRefPopupRef.current.command).toBeNull()+ })+ expect(vi.mocked(exitSuggestion).mock.calls).toEqual([+ [editor.view, current.mentionExtension.options.suggestion.pluginKey],+ [editor.view, current.channelRefExtension.options.suggestion.pluginKey],+ ])+ vi.mocked(exitSuggestion).mockClear()+ act(() => {+ mention.setPopup({ items: [], query: "a", selectedIndex: 0, command: vi.fn(), getRect: null })+ current.resetPopups({} as typeof editor)+ expect(current.mentionPopupRef.current.command).toBeTypeOf("function")+ current.resetPopups(editor, false)+ expect(current.mentionPopupRef.current.command).toBeNull()+ })+ expect(exitSuggestion).not.toHaveBeenCalled()+ })+it("builds only the two custom extensions once and refreshes live refs", async () => {const resultRef: { current: Result | null } = { current: null }const firstMembers = [member()]@@ -256,7 +293,7 @@ describe("useComposerSuggestions", () => {expect(mocks.rankChannel).toHaveBeenLastCalledWith(thirdChannels, "gen")})- it("disables mentions across a live DM transition without rebuilding or disturbing channel refs", async () => {+ it("ends both old suggestions across a live DM transition without rebuilding extensions", async () => {const resultRef: { current: Result | null } = { current: null }const search = vi.fn()const mentionItem = {@@ -329,9 +366,9 @@ describe("useComposerSuggestions", () => {getRect: null,})expect(resultRef.current!.channelRefPopup).toEqual({- items: [channelItem],+ items: [],selectedIndex: 0,- command: channelCommand,+ command: null,getRect: null,})expect(search).toHaveBeenCalledOnce()@@ -621,6 +658,39 @@ describe("useComposerSuggestions", () => {expect(resultRef.current!.mentionPresentation.status).toBe("empty")})+ it("uses common read state for local private search and retains matching cache on remote errors", async () => {+ const resultRef: { current: Result | null } = { current: null }+ 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 }+ mocks.rankMention.mockImplementation((rows: Member[]) => rows.length ? [item] : [])+ const local = (loading: boolean, failed: boolean) => ({ loading, failed })+ let renderer!: ReturnType<typeof rtlRender>+ const show = async (source: Options["mentionCandidates"], members = [member()]) => {+ await act(async () => renderer.rerender(createElement(Harness, { members, context: "channel", mentionCandidates: source, channelRefCandidates: [], resultRef })))+ }+ await act(async () => { renderer = rtlRender(createElement(Harness, { members: [member()], context: "channel", mentionCandidates: local(true, false), channelRefCandidates: [], resultRef })) })+ const options = mocks.buildMention.mock.calls[0][0]+ const query = (resultRef.current!.mentionExtension as unknown as { runQuery: (query: string) => unknown }).runQuery+ await act(async () => { options.setPopup({ items: query("ad"), query: "ad", selectedIndex: 0, command: vi.fn(), getRect: null }) })+ expect(resultRef.current!.mentionPresentation.status).toBe("loading")+ expect(resultRef.current!.mentionPopup.items).toEqual([item])+ await show(local(false, true))+ expect(resultRef.current!.mentionPresentation.status).toBe("error")+ expect(resultRef.current!.mentionPopup.items).toEqual([item])+ await show(local(false, false))+ expect(resultRef.current!.mentionPresentation.status).toBe("ready")+ await show(local(false, false), [])+ expect(resultRef.current!.mentionPresentation.status).toBe("empty")+ await show(candidateSource(vi.fn(), { searchQuery: "ad", searchStatus: "error", failed: true }))+ expect(resultRef.current!.mentionPresentation.status).toBe("error")+ expect(resultRef.current!.mentionPopup.items).toEqual([item])+ await show(candidateSource(vi.fn(), { searchQuery: "older", searchStatus: "ready" }))+ expect(resultRef.current!.mentionPresentation.status).toBe("loading")+ expect(resultRef.current!.mentionPopup.items).toEqual([])+ await show(local(false, false))+ await act(async () => resultRef.current!.resetPopups())+ expect(resultRef.current!.mentionPopup.items).toEqual([])+ })+it("keeps channel state when only serverName changes and resets both popups", async () => {const resultRef: { current: Result | null } = { current: null }let renderer!: ReturnType<typeof rtlRender>diff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.tsindex 5894a16c4..e2b9b0306 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts@@ -1,5 +1,7 @@import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"+import type { Editor } from "@tiptap/react"+import { exitSuggestion } from "@tiptap/suggestion"import {buildCommunityMentionExtension,EMPTY_MENTION_STATE,@@ -24,6 +26,9 @@ import type {} from "./composer-types"type ComposerSuggestionsOptions = {+ editorRef: { current: Editor | null }+ canSuggest: (editor: Editor) => boolean+ scope: stringmembers: Member[]context: MentionContextmentionCandidates?: MentionCandidateSource@@ -72,6 +77,9 @@ function channelRefItemsEqual(}export function useComposerSuggestions({+ editorRef,+ canSuggest,+ scope,members,context,mentionCandidates,@@ -81,9 +89,20 @@ export function useComposerSuggestions({}: ComposerSuggestionsOptions) {const [mentionPopup, setMentionPopup] = useAtom(useCreateAtom<MentionPopupState>(EMPTY_MENTION_STATE))const mentionPopupRef = useRef(mentionPopup)- useEffect(() => {- mentionPopupRef.current = mentionPopup- }, [mentionPopup])+ const mentionQueryRef = useRef("")+ const canSuggestRef = useRef(canSuggest)+ useLayoutEffect(() => { canSuggestRef.current = canSuggest }, [canSuggest])+ const eligible = useCallback((editor: Editor) => canSuggestRef.current(editor), [])+ const isOpenEditor = useCallback(() => {+ const editor = editorRef.current+ return Boolean(editor && eligible(editor))+ }, [editorRef, eligible])+ const publishMention = useCallback((next: MentionPopupState | ((current: MentionPopupState) => MentionPopupState)) => {+ const resolved = typeof next === "function" ? next(mentionPopupRef.current) : next+ mentionPopupRef.current = resolved+ mentionQueryRef.current = resolved.query+ setMentionPopup(resolved)+ }, [setMentionPopup])const [channelRefPopupState, setChannelRefPopup] =useAtom(useCreateAtom<ChannelRefPopupState>(EMPTY_CHANNEL_REF_STATE))@@ -99,45 +118,35 @@ export function useComposerSuggestions({: 0,}}, [channelRefCandidates, channelRefPopupState])- useLayoutEffect(() => {- if (channelRefPopup !== channelRefPopupState) setChannelRefPopup(channelRefPopup)- }, [channelRefPopup, channelRefPopupState, setChannelRefPopup])const channelRefPopupRef = useRef(channelRefPopup)+ const channelRefQueryRef = useRef("")+ const publishChannelRef = useCallback((next: ChannelRefPopupState | ((current: ChannelRefPopupState) => ChannelRefPopupState)) => {+ const resolved = typeof next === "function" ? next(channelRefPopupRef.current) : next+ channelRefPopupRef.current = resolved+ channelRefQueryRef.current = resolved.query ?? ""+ setChannelRefPopup(resolved)+ }, [setChannelRefPopup])useLayoutEffect(() => {- channelRefPopupRef.current = channelRefPopup- }, [channelRefPopup])+ if (!isOpenEditor() || channelRefPopup.command !== channelRefPopupRef.current.command) return+ if (channelRefPopup !== channelRefPopupState) publishChannelRef(channelRefPopup)+ }, [channelRefPopup, channelRefPopupState, isOpenEditor, publishChannelRef])const membersRef = useRef(members)const contextRef = useRef(context)const onSearchMembersRef = useRef(mentionCandidates?.search)- const mentionQueryRef = useRef("")useEffect(() => {membersRef.current = members}, [members])- useLayoutEffect(() => {- const previousSearch = onSearchMembersRef.current- if (context === "dm" && mentionQueryRef.current) previousSearch?.("")- onSearchMembersRef.current = mentionCandidates?.search- }, [context, mentionCandidates?.search])- useLayoutEffect(() => {- contextRef.current = context- if (context !== "dm") return-- // The mention extension is initialized once, so close any channel/thread- // lifecycle before the reused editor can handle input in a DM. Keep the- // channel-ref popup untouched: slash references remain supported in DMs.- mentionQueryRef.current = ""- mentionPopupRef.current = EMPTY_MENTION_STATE- setMentionPopup(EMPTY_MENTION_STATE)- }, [context, setMentionPopup])// eslint-disable-next-line react-hooks/refs -- runtime suggestion callbacks read these refsconst [mentionExtension] = useState(() =>buildCommunityMentionExtension({+ editorRef,+ canSuggest: eligible,membersRef,contextRef,popupRef: mentionPopupRef,- setPopup: (next) => setMentionPopup((current) => typeof next === "function" ? next(current) : next),+ setPopup: publishMention,onSearchMembersRef,queryRef: mentionQueryRef,}),@@ -145,7 +154,6 @@ export function useComposerSuggestions({const channelRefCandidatesRef = useRef(channelRefCandidates)const onChannelRefIntentRef = useRef(onChannelRefIntent)- const channelRefQueryRef = useRef("")useEffect(() => {channelRefCandidatesRef.current = channelRefCandidates}, [channelRefCandidates])@@ -169,80 +177,78 @@ export function useComposerSuggestions({// eslint-disable-next-line react-hooks/refs -- runtime suggestion callbacks read these refsconst [channelRefExtension] = useState(() =>buildCommunityChannelRefExtension({+ editorRef,+ canSuggest: eligible,candidatesRef: channelRefCandidatesRef,popupRef: channelRefPopupRef,onIntentRef: onChannelRefIntentRef,- setPopup: (next) => setChannelRefPopup((current) => typeof next === "function" ? next(current) : next),+ setPopup: publishChannelRef,queryRef: channelRefQueryRef,}),)+ const resetPopups = useCallback((editor = editorRef.current, exit = true) => {+ if (editor && editorRef.current !== editor) return+ if (mentionQueryRef.current || mentionPopupRef.current.command) onSearchMembersRef.current?.("")+ publishMention(EMPTY_MENTION_STATE)+ publishChannelRef(EMPTY_CHANNEL_REF_STATE)+ if (!exit || !editor || editor.isDestroyed) return+ exitSuggestion(editor.view, mentionExtension.options.suggestion.pluginKey)+ exitSuggestion(editor.view, channelRefExtension.options.suggestion.pluginKey)+ }, [editorRef, mentionExtension, channelRefExtension, publishMention, publishChannelRef])+ useLayoutEffect(() => { resetPopups() }, [scope, resetPopups])+ useLayoutEffect(() => {+ contextRef.current = context+ onSearchMembersRef.current = mentionCandidates?.search+ }, [context, mentionCandidates?.search])+useEffect(() => {- if (context === "dm") return+ if (context === "dm" || !isOpenEditor()) returnconst current = mentionPopupRef.currentif (!current.command) returnconst query = mentionQueryRef.current- const remoteSearchReady = !query || !mentionCandidates- || (mentionCandidates.searchQuery === query- && (mentionCandidates.searchStatus === "ready"- || mentionCandidates.searchStatus === "loading-more"- || mentionCandidates.searchStatus === "empty"))+ const remoteSearchReady = !query || !mentionCandidates?.search || mentionCandidates.searchQuery === queryconst items = rankMentionItems(remoteSearchReady ? members : [],context,query,)if (mentionItemsEqual(current.items, items)) return- setMentionPopup({+ publishMention({...current,items,selectedIndex:current.selectedIndex < items.length ? current.selectedIndex : 0,})- }, [context, members, mentionCandidates, setMentionPopup])+ }, [context, members, mentionCandidates, isOpenEditor, publishMention])useEffect(() => {const current = mentionPopupRef.current+ if (!isOpenEditor()) returnif (!current.command || current.query.trim()) returnif (!mentionCandidates?.hasMore) returnif (mentionCandidates.loading || mentionCandidates.loadingMore) returnif (mentionCandidates.failed) return- mentionCandidates.loadMore()- }, [mentionCandidates, mentionPopup.command, mentionPopup.query])+ mentionCandidates.loadMore?.()+ }, [mentionCandidates, mentionPopup.command, mentionPopup.query, isOpenEditor])const mentionPresentation: MentionCandidatePresentation = (() => {if (!mentionCandidates) {return { status: mentionPopup.items.length > 0 ? "ready" : "empty" }}const query = mentionPopup.query- if (query) {+ if (query && mentionCandidates.search) {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) {+ const searchStatus = query && mentionCandidates.search ? mentionCandidates.searchStatus : undefined+ if (mentionCandidates.failed || searchStatus === "error") return { status: "error" }+ if (mentionCandidates.loading || searchStatus === "loading" || searchStatus === "idle") return { status: "loading" }+ if (mentionCandidates.loadingMore || mentionCandidates.hasMore || searchStatus === "loading-more") {return { status: "loading-more" }}return { status: mentionPopup.items.length > 0 ? "ready" : "empty" }})()- const resetPopups = () => {- mentionCandidates?.search("")- setMentionPopup(EMPTY_MENTION_STATE)- setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)- }-return {mentionPopup,mentionPresentation,diff --git a/src/web/src/hooks/community/use-channel-members.dom.test.ts b/src/web/src/hooks/community/use-channel-members.dom.test.tsindex e37b36462..3f04c91c0 100644--- a/src/web/src/hooks/community/use-channel-members.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-members.dom.test.ts@@ -4,7 +4,7 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"import { beforeEach, describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"-import { channelMembershipKey } from "@/lib/community-db/schema"+import { channelMembershipKey, profileSchema, serverMembershipKey } from "@/lib/community-db/schema"const apiFetchMock = vi.fn()@@ -17,6 +17,39 @@ beforeEach(() => {})describe("useChannelMembers", () => {+ it("retains authorized canonical access members on transport failure and recovers through the same refetch", async () => {+ const { useChannelMembers } = await import("./use-channel-members")+ const { publishCommunityChannelMembersSnapshot, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")+ const owner = await createCommunityQueryOwner()+ const peer = { id: "m-peer", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, sub: "", role: "member", status: "offline", source: "explicit", isCreator: false }+ publishCommunityChannelMembersSnapshot(owner.client, "server", "private", "access", [{ channelId: "private", userId: "peer", relation: "access", memberId: "m-peer", role: "member", source: "explicit", isCreator: false }], { token: captureCommunityLiveSnapshotToken(owner.client) }, [{ id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 }])+ apiFetchMock.mockRejectedValue(new Error("controlled first read failure"))+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)+ const rendered = renderHook(() => useChannelMembers("private", true, "server", "access"), { wrapper })+ await waitFor(() => expect(rendered.result.current).toMatchObject({ isError: true, failed: true, members: [expect.objectContaining({ userId: "peer", discriminator: "0042" })] }))+ expect(rendered.result.current.data).toBeUndefined()+ apiFetchMock.mockResolvedValue({ members: [peer] })+ await act(async () => { await rendered.result.current.refetch() })+ await waitFor(() => expect(rendered.result.current).toMatchObject({ isSuccess: true, loading: false, failed: false, members: [expect.objectContaining({ userId: "peer" })] }))+ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ })+ it("separates missing usable profiles from true empty and withdraws disabled access candidates", async () => {+ const { useChannelMembers } = await import("./use-channel-members")+ const owner = await createCommunityQueryOwner()+ apiFetchMock.mockResolvedValue({ members: [{ id: "m-peer", userId: "peer", name: "Peer", discriminator: "", avatar: "P", avatarVersion: 0, sub: "", role: "member", status: "offline", source: "explicit", isCreator: false }] })+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)+ const rendered = renderHook(({ enabled }) => useChannelMembers("private", enabled, "server", "access"), { wrapper, initialProps: { enabled: true } })+ await waitFor(() => expect(rendered.result.current).toMatchObject({ isSuccess: true, loading: false, failed: true }))+ await act(async () => owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 })))+ await waitFor(() => expect(rendered.result.current).toMatchObject({ loading: false, failed: false, members: [expect.objectContaining({ userId: "peer", discriminator: "0042" })] }))+ expect(rendered.result.current.profiles.get("peer")?.discriminator).toBe("0042")+ await act(async () => owner.registry.collections.serverMemberships.utils.writeDelete(serverMembershipKey("server", "peer")))+ await waitFor(() => expect(rendered.result.current).toMatchObject({ loading: false, failed: false, members: [] }))+ rendered.rerender({ enabled: false })+ expect(rendered.result.current).toMatchObject({ loading: false, failed: false, members: [] })+ expect(rendered.result.current.data).toBeUndefined()+ expect(apiFetchMock).toHaveBeenCalledOnce()+ })it("fetches the roster through the identity-aware query function", async () => {apiFetchMock.mockResolvedValue({members: [{diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.tsindex 709cfb719..c224859d6 100644--- a/src/web/src/hooks/community/use-channel-members.ts+++ b/src/web/src/hooks/community/use-channel-members.ts@@ -7,10 +7,10 @@ import { QueryObserver,useMutation,useQuery,useQueryClient,type QueryClient,typeimport { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { COMMUNITY_CONTRACT_VERSION, CommunityMembersReadSchema, CommunityResourceProfileSchema, type CommunityMembersRead, type CommunityRole, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"-import type { CommunityUserCore, Presence } from "@/lib/community/models/people"+import type { CommunityProfile, CommunityUserCore, Presence } from "@/lib/community/models/people"import { fetchAllServerMembers } from "./fetch-all-server-members"-import { useCanonicalProfilesByUserId,useServerMemberRows,useChannelRosterRows } from "@/lib/community-db/projections"+import { getMemberReadState, useCanonicalProfilesByUserId, useCanonicalProfilesProjection, useServerMemberRows, useServerMemberProjection, useChannelRosterRows, useChannelRosterProjection } from "@/lib/community-db/projections"import { captureCommunityLiveSnapshotToken,assertCommunityLiveSnapshotTokenCurrent,publishCommunityChannelMembersSnapshot,setCanonicalCommunityChannelMember } from "@/lib/community-db/sync"import { channelMembershipKey, type ChannelMembershipRow } from "@/lib/community-db/schema"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"@@ -95,24 +95,27 @@ async function addableMembersQueryFn(serverId: string, channelId: string, contexreturn { serverId, relation: roster.relation, members: serverMembers.map(({ id, userId }) => ({ id, userId })) }}-export function useChannelMembers(channelId: string, enabled = true, serverId?: string, relation?: "access" | "notify"): UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[] } {+export function useChannelMembers(channelId: string, enabled = true, serverId?: string, relation?: "access" | "notify"): UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[]; profiles: ReadonlyMap<string, CommunityProfile>; loading: boolean; failed: boolean } {const client = useQueryClient()const active = enabled && !!channelIdconst query = useQuery({ ...channelMembersOptions(client, channelId, serverId, relation), enabled: active, subscribed: active })- const roster = useChannelRosterRows(channelId, query.data?.relation ?? relation ?? "access")- const profiles = useCanonicalProfilesByUserId(roster.map((member) => member.userId))- const memberships = useServerMemberRows(query.data?.serverId ?? null, roster.map((member) => member.userId))+ const rosterProjection = useChannelRosterProjection(active ? channelId : "", query.data?.relation ?? relation ?? "access")+ const roster = rosterProjection.data+ const profileProjection = useCanonicalProfilesProjection(roster?.map((member) => member.userId) ?? [])+ const profiles = profileProjection.data+ const membershipProjection = useServerMemberProjection(query.data?.serverId === null ? null : query.data?.serverId ?? serverId ?? null, roster?.map((member) => member.userId) ?? [])const members = useMemo<ChannelMember[]>(() => {- const byUser = new Map(memberships.map((member) => [member.userId, member]))- return roster.flatMap((participant) => {+ const byUser = new Map((membershipProjection.data ?? []).map((member) => [member.userId, member]))+ return (roster ?? []).flatMap((participant) => {const member = byUser.get(participant.userId)if (query.data?.serverId !== null && !member?.memberId) return []const profile = readCommunityProfile(profiles.get(participant.userId), participant.userId)return [{ id: member?.memberId ?? participant.userId, userId: participant.userId, name: member?.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member ? member.role as CommunityRole : null, sub: "", status: member?.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source ?? "explicit", isCreator: participant.isCreator ?? false }]})- }, [profiles, memberships, roster, query.data?.serverId])- const data = useMemo(() => query.data ? { members } : undefined, [query.data, members])- return { ...query, data, members } as UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[] }+ }, [profiles, membershipProjection.data, roster, query.data?.serverId])+ const readState = getMemberReadState(active, { pending: !query.data || query.isRefetching, failed: query.isError && !query.isFetching }, query.data?.serverId === null ? [rosterProjection, profileProjection] : [rosterProjection, membershipProjection, profileProjection], members.filter((member) => member.userId !== rosterProjection.registry?.accountId).map((member) => member.userId), profiles)+ const data = useMemo(() => active && query.data ? { members } : undefined, [active, query.data, members])+ return { ...query, data, members, profiles, ...readState } as UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[]; profiles: typeof profiles; loading: boolean; failed: boolean }}export function useAddableMembers(serverId: string, channelId: string, enabled = true): UseQueryResult<{ members: AddableMember[] }> & { members: AddableMember[] } {diff --git a/src/web/src/hooks/community/use-server-members.dom.test.ts b/src/web/src/hooks/community/use-server-members.dom.test.tsindex c560ff979..358a9e98b 100644--- a/src/web/src/hooks/community/use-server-members.dom.test.ts+++ b/src/web/src/hooks/community/use-server-members.dom.test.ts@@ -1,7 +1,7 @@import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"import { createElement, useEffect, type RefObject } from "react"import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"-import { type InfiniteData } from "@tanstack/react-query"+import { QueryClient, type InfiniteData } from "@tanstack/react-query"import { act, render } from "@/test/react-dom-harness"const apiFetchMock = vi.fn()@@ -36,7 +36,8 @@ import {type MembersEnvelope,} from "./use-server-members"import { createCommunityQueryOwner } from "@/test/community-query-owner"-import { serverMembershipKey, serverMembershipSchema } from "@/lib/community-db/schema"+import { profileSchema, serverMembershipKey, serverMembershipSchema } from "@/lib/community-db/schema"+import { createCommunityDbRegistry } from "@/lib/community-db/collections"import { captureCommunityLiveSnapshotToken, publishCommunityMemberRemoval } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"import type { Member } from "@/lib/community/models/people"@@ -76,11 +77,13 @@ function deferred<T>(): Deferred<T> {return { promise, resolve, reject }}-function HookProbe({ serverId, resultRef }: {+function HookProbe({ serverId, resultRef, observations }: {serverId: string | nullresultRef: RefObject<ServerMembersResult | null>+ observations?: ServerMembersResult[]}) {const result = useServerMembers(serverId)+ observations?.push(result)useEffect(() => {resultRef.current = result}, [result, resultRef])@@ -428,6 +431,41 @@ describe("native member subscriptions", () => {})describe("useServerMembers search lifecycle", () => {+ it("does not carry an earlier query failure into the next query debounce", async () => {+ vi.useFakeTimers()+ apiFetchMock.mockImplementation((url: unknown) => isSearchUrl(url) ? Promise.reject(new Error("controlled search error")) : Promise.resolve(makeEnvelope([], false, 0)))+ const harness = await mountServerMembers()+ await act(async () => { harness.resultRef.current!.searchMembers("failed"); await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS + 1) })+ await flushEffects()+ expect(harness.resultRef.current).toMatchObject({ searchStatus: "error", failed: true })+ await act(async () => harness.resultRef.current!.searchMembers("next"))+ expect(harness.resultRef.current).toMatchObject({ searchQuery: "next", searchStatus: "loading", failed: false, members: [] })+ harness.renderer.unmount()+ harness.queryClient.clear()+ })+ it("does not complete a cached transport window while its native profile projection is pending", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const restore = deferred<void>()+ const registry = createCommunityDbRegistry(queryClient, "viewer", { waitForRestore: restore.promise })+ const person = m("a")+ queryClient.setQueryData(communityKeys.members("srv_1"), { pages: [{ members: [{ id: person.id, userId: person.userId }], hasMore: false, limit: 50, total: 1, liveRevision: 0 }], pageParams: [null] })+ queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "serverMemberships"), [serverMembershipSchema.parse({ id: serverMembershipKey("srv_1", person.userId), serverId: "srv_1", userId: person.userId, memberId: person.id, role: "member", viewer: false })])+ const resultRef = { current: null } as RefObject<ServerMembersResult | null>+ const observations: ServerMembersResult[] = []+ const renderer = render(createElement(QueryClientProvider, { client: queryClient, registry }, createElement(HookProbe, { serverId: "srv_1", resultRef, observations })))+ try {+ await flushEffects()+ expect(queryClient.getQueryState(communityKeys.members("srv_1"))?.status).toBe("success")+ expect(resultRef.current).toMatchObject({ loading: true, failed: false })+ expect(observations.every((value) => value.loading || value.failed)).toBe(true)+ await act(async () => {+ queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ userId: person.userId, name: person.name, discriminator: person.discriminator, avatar: person.avatar, avatarVersion: 0 })])+ restore.resolve(); await registry.preload()+ })+ await vi.waitFor(() => expect(resultRef.current).toMatchObject({ loading: false, failed: false, members: [expect.objectContaining({ id: "a", discriminator: "0000" })] }))+ expect(apiFetchMock).not.toHaveBeenCalled()+ } finally { restore.resolve(); renderer.unmount(); await registry.cleanup(); queryClient.clear() }+ })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 }>()@@ -551,7 +589,7 @@ describe("useServerMembers search lifecycle", () => {harness.queryClient.clear()})- it("retains accumulated members on a current continuation error and refreshes the active query", async () => {+ it("retains accumulated members on a current continuation error and same-term refresh", async () => {vi.useFakeTimers()const first = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()const continuation = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()@@ -588,7 +626,7 @@ describe("useServerMembers search lifecycle", () => {})await flushEffects()expect(harness.resultRef.current).toMatchObject({- members: [],+ members: [m("a")],searchStatus: "loading",searchQuery: "ad",})diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.tsindex d7d434aed..57a843c80 100644--- a/src/web/src/hooks/community/use-server-members.ts+++ b/src/web/src/hooks/community/use-server-members.ts@@ -8,7 +8,7 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent, publishCommunityMembersSnapshot } from "@/lib/community-db/sync"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { beginCommunityProfileSeed, writeCommunityProfilePatches, communityUserProfilePatch } from "@/lib/community/profile-seed"-import { useCanonicalProfilesByUserId, useServerMemberRows } from "@/lib/community-db/projections"+import { getMemberReadState, useCanonicalProfilesProjection, useServerMemberProjection } from "@/lib/community-db/projections"import { readCommunityProfile } from "@/lib/community/profile-read"import { serverMembershipKey } from "@/lib/community-db/schema"import { useCommunityViewSource } from "./use-community-view-source"@@ -421,18 +421,20 @@ export function useServerMembers(serverId: string | null): UseServerMembers {return true}) ?? []}, [data])- const memberships = useServerMemberRows(serverId, identities.map((member) => member.userId))- const profiles = useCanonicalProfilesByUserId(identities.map((member) => member.userId))+ const membershipProjection = useServerMemberProjection(serverId, identities.map((member) => member.userId))+ const profileProjection = useCanonicalProfilesProjection(identities.map((member) => member.userId))+ const profiles = profileProjection.dataconst members = useMemo(() => {- const byUser = new Map(memberships.map((row) => [row.userId, row]))+ const byUser = new Map((membershipProjection.data ?? []).map((row) => [row.userId, row]))return identities.flatMap((identity) => {const row = byUser.get(identity.userId)if (!row || row.memberId !== identity.id) return []const profile = readCommunityProfile(profiles.get(identity.userId), identity.userId)return [{ id: identity.id, userId: identity.userId, name: row.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: row.role as CommunityRole, status: row.viewer ? "online" as const : profile.presence, sub: "", statusEmoji: profile.statusEmoji, statusText: profile.statusText }]})- }, [identities, memberships, profiles])+ }, [identities, membershipProjection.data, profiles])const active = searching ? search : infinite+ const readState = getMemberReadState(!!serverId, { pending: !data || active.isRefetching, failed: (!searching || searchReady) && active.isError && !active.isFetching }, [membershipProjection, profileProjection], members.filter((member) => member.userId !== membershipProjection.registry?.accountId).map((member) => member.userId), profiles)const pendingKicks = useMutationState({ filters: { mutationKey: ["community", "member-command"], status: "pending" }, select: (mutation) => {const variables = mutation.state.variables as { kind: string; input: { serverId: string; memberId: string } }const current = queryClient.getQueryData<MembersWindowCache>(key)@@ -440,12 +442,12 @@ export function useServerMembers(serverId: string | null): UseServerMembers {} })const assertView = () => source.capture()()return {- members: searching && search.isRefetching ? [] : members, loading: searching ? searchReady ? search.isPending || search.isRefetching : true : !!serverId && infinite.isPending,+ members: serverId ? members : [], loading: readState.loading,loadingMore: active.isFetchingNextPage, hasMore: active.hasNextPage,total: Math.max(0, (infinite.data?.pages.at(-1)?.total ?? 0) - pendingKicks.reduce<number>((sum, value) => sum + value, 0)), isSearching: searching,searchQuery: searching ? searchIntent.query : "",- searchStatus: !searching ? "idle" : !searchReady || search.isPending || search.isRefetching ? "loading" : search.isError ? "error" : search.isFetchingNextPage || search.hasNextPage ? "loading-more" : members.length ? "ready" : "empty",- failed: active.isError,+ searchStatus: !searching ? "idle" : readState.failed ? "error" : readState.loading ? "loading" : search.isFetchingNextPage || search.hasNextPage ? "loading-more" : members.length ? "ready" : "empty",+ failed: readState.failed,loadMore: () => { assertView(); if (active.hasNextPage && !active.isFetchingNextPage) void active.fetchNextPage({ cancelRefetch: false }) },reset: () => { assertView(); intent.setState((state) => ({ ...state, query: "", debounced: "" })) },refresh: () => { assertView(); void queryClient.invalidateQueries({ queryKey: key }, { cancelRefetch: false }) },diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.tsindex fb2c12113..d95d91c69 100644--- a/src/web/src/lib/community-db/projections.dom.test.ts+++ b/src/web/src/lib/community-db/projections.dom.test.ts@@ -11,6 +11,9 @@ import {useCanonicalCommunityProfile,useCanonicalMessagesById,useCanonicalProfilesByUserId,+ useCanonicalProfilesProjection,+ useServerMemberProjection,+ getMemberReadState,useChannelRefDirectoryProjection,useDmProjection,useMessageProjection,@@ -21,8 +24,49 @@ import {useTrustedRestoredPrimary,} from "./projections"import { ingestMessages, ingestServerDetail, ingestServers } from "./sync"+import { profileSchema } from "./schema"describe("community DB projections", () => {+ it("carries native preparation and failure through member reads and recovers from actual canonical data", async () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let reject!: (error: Error) => void+ const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>((_resolve, rejectPromise) => { reject = rejectPromise }) })+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children))+ const rendered = renderHook(() => {+ const profiles = useCanonicalProfilesProjection(["peer"])+ const disabled = useServerMemberProjection(null, [])+ return { profiles, disabled, state: getMemberReadState(true, { pending: false, failed: false }, [profiles], ["peer"], profiles.data) }+ }, { wrapper })+ try {+ await waitFor(() => expect(rendered.result.current.profiles.isLoading).toBe(true))+ expect(rendered.result.current.state).toEqual({ loading: true, failed: false })+ expect(rendered.result.current.disabled).toMatchObject({ isEnabled: false, isReady: true })+ await act(async () => reject(new Error("controlled profile restore failure")))+ await waitFor(() => expect(rendered.result.current.profiles.isError).toBe(true))+ expect(rendered.result.current.state).toEqual({ loading: false, failed: true })+ await act(async () => client.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 1 })]))+ await waitFor(() => expect(rendered.result.current.state).toEqual({ loading: false, failed: false }))+ expect(rendered.result.current.profiles.data.get("peer")?.discriminator).toBe("0042")+ } finally { rendered.unmount(); await registry.cleanup(); client.clear() }+ })++ it("does not turn presence-only or disabled snapshots into complete member handles", async () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const registry = createCommunityDbRegistry(client, "viewer")+ await registry.preload()+ registry.runtime.ws.setState((state) => ({ ...state, presenceByUserId: new Map([["peer", "online"]]) }))+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children))+ const rendered = renderHook(() => ({ profiles: useCanonicalProfilesProjection(["peer"]), disabled: useServerMemberProjection(null, []) }), { wrapper })+ try {+ await waitFor(() => expect(rendered.result.current.profiles.isReady).toBe(true))+ const { profiles, disabled } = rendered.result.current+ expect(profiles.data.get("peer")).toMatchObject({ id: "peer", presence: "online" })+ expect(getMemberReadState(true, { pending: false, failed: false }, [profiles], ["peer"], profiles.data)).toEqual({ loading: false, failed: true })+ expect(getMemberReadState(true, { pending: false, failed: false }, [profiles], [], profiles.data)).toEqual({ loading: false, failed: false })+ expect(getMemberReadState(true, { pending: false, failed: false }, [disabled], [], profiles.data)).toEqual({ loading: true, failed: false })+ expect(getMemberReadState(false, { pending: true, failed: true }, [disabled], ["peer"], profiles.data)).toEqual({ loading: false, failed: false })+ } finally { rendered.unmount(); await registry.cleanup(); client.clear() }+ })it("keeps disabled channel arrays unresolved and active empty selections empty while restore is pending", async () => {const client = new QueryClient()let release!: () => voiddiff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.tsindex 733ad70ff..2734b8459 100644--- a/src/web/src/lib/community-db/projections.ts+++ b/src/web/src/lib/community-db/projections.ts@@ -94,14 +94,14 @@ type CollectionWhere<N extends CommunityCollectionName> = WhereCallback<ContextFfunction useCollectionQuery<N extends CommunityCollectionName>(name: N, where?: CollectionWhere<N>, enabled = true) {const registry = useOptionalCommunityDbRegistry()- const data = useLiveQuery({+ const result = useLiveQuery({query: (q) => {if (!registry || !enabled) return undefinedconst query = q.from({ row: registry.collections[name] })return where ? query.where(where) : query},- }).data as CommunityCollectionRows[N][] | undefined- return { registry, data }+ })+ return { ...result, registry, data: result.data as CommunityCollectionRows[N][] | undefined }}function useCollectionRows<N extends CommunityCollectionName>(name: N, where?: CollectionWhere<N>) {@@ -418,23 +418,16 @@ export function useNotificationSettingsProjection() {}, [rows.notificationSettings])}-function useProfileProjectionMap(userIds?: readonly string[]) {- const result = useCollectionQuery("profiles", ({ row }) => userIds === undefined ? eq(1, 1) : inArray(row.userId, [...userIds]))- return useMemo(() => new Map(- (result.data ?? []).map((profile) => [profile.userId, profile]),- ), [result.data])-}--export function useCanonicalProfilesByUserId(userIds?: readonly string[]): ReadonlyMap<string, CommunityProfile> {+export function useCanonicalProfilesProjection(userIds?: readonly string[]) {const previewProfiles = useCommunityPreviewProfiles()- const canonicalProfiles = useProfileProjectionMap(userIds)- const registry = useOptionalCommunityDbRegistry()+ const projection = useCollectionQuery("profiles", ({ row }) => userIds === undefined ? eq(1, 1) : inArray(row.userId, [...userIds]))+ const { registry } = projectionconst livePresence = useSelector(registry?.runtime.ws ?? absentPresence, (state) => previewProfiles ? null : userIds === undefined ? [...state.presenceByUserId] : userIds.map((id) => [id, state.presenceByUserId.get(id)] as const), { compare: (left, right) => left === right || (!!left && !!right && left.length === right.length && left.every(([id, presence], index) => id === right[index]?.[0] && presence === right[index]?.[1])) })- return useMemo(() => {+ const data: ReadonlyMap<string, CommunityProfile> = useMemo(() => {if (previewProfiles) return previewProfilesconst merged = new Map<string, CommunityProfile>()- for (const [userId, profile] of canonicalProfiles) {- merged.set(userId, { ...profile, id: userId })+ for (const profile of projection.data ?? []) {+ merged.set(profile.userId, { ...profile, id: profile.userId })}for (const [userId, presence] of livePresence ?? []) {if (presence === undefined) continue@@ -443,16 +436,43 @@ export function useCanonicalProfilesByUserId(userIds?: readonly string[]): Readomerged.set(userId, value)}return merged- }, [canonicalProfiles, livePresence, previewProfiles])+ }, [projection.data, livePresence, previewProfiles])+ return { ...projection, data, isReady: !!previewProfiles || projection.isReady, isError: !previewProfiles && projection.isError, isEnabled: !!previewProfiles || projection.isEnabled }+}++export function useCanonicalProfilesByUserId(userIds?: readonly string[]): ReadonlyMap<string, CommunityProfile> {+ return useCanonicalProfilesProjection(userIds).data+}++export function getMemberReadState(+ enabled: boolean,+ transport: { pending: boolean; failed: boolean },+ projections: readonly { isReady: boolean; isError: boolean; isEnabled: boolean }[],+ userIds: readonly string[],+ profiles: ReadonlyMap<string, CommunityProfile>,+) {+ if (!enabled) return { loading: false, failed: false }+ const failed = transport.failed || projections.some((projection) => projection.isError)+ const loading = !failed && (transport.pending || projections.some((projection) => !projection.isEnabled || !projection.isReady))+ const missingProfile = !loading && userIds.some((id) => !profiles.get(id)?.name || !profiles.get(id)?.discriminator)+ return { loading, failed: failed || missingProfile }+}++export function useServerMemberProjection(serverId: string | null, userIds: readonly string[]) {+ return useCollectionQuery("serverMemberships", ({ row }) => and(eq(row.serverId, serverId), inArray(row.userId, [...userIds])), !!serverId)}export function useServerMemberRows(serverId: string | null, userIds: readonly string[]) {- const { data } = useCollectionQuery("serverMemberships", ({ row }) => and(eq(row.serverId, serverId), inArray(row.userId, [...userIds])), !!serverId)+ const { data } = useServerMemberProjection(serverId, userIds)return data ?? []}+export function useChannelRosterProjection(channelId: string, relation: "access" | "notify") {+ return useCollectionQuery("channelMemberships", ({ row }) => and(eq(row.channelId, channelId), eq(row.relation, relation)), !!channelId)+}+export function useChannelRosterRows(channelId: string, relation: "access" | "notify") {- const { data } = useCollectionQuery("channelMemberships", ({ row }) => and(eq(row.channelId, channelId), eq(row.relation, relation)), !!channelId)+ const { data } = useChannelRosterProjection(channelId, relation)return data ?? []}diff --git a/src/web/src/lib/community/channel-ref-extension.test.ts b/src/web/src/lib/community/channel-ref-extension.test.tsindex ef4775091..929ff5c1f 100644--- a/src/web/src/lib/community/channel-ref-extension.test.ts+++ b/src/web/src/lib/community/channel-ref-extension.test.ts@@ -1,6 +1,6 @@-import { describe, it, expect, vi } from "vitest"+import { beforeEach, describe, it, expect, vi } from "vitest"import {- buildCommunityChannelRefExtension,+ buildCommunityChannelRefExtension as buildChannelRef,rankChannelRefItems,toChannelRefCandidate,toChannelRefCommandProps,@@ -9,6 +9,15 @@ import {type ChannelRefPopupState,} from "./channel-ref-extension"+import type { Editor } from "@tiptap/react"++const editor = { isFocused: true, isDestroyed: false } as Editor+const editorRef: { current: Editor | null } = { current: editor }+const canSuggest = (candidate: Editor) => candidate === editorRef.current && candidate.isFocused && !candidate.isDestroyed+const buildCommunityChannelRefExtension = (options: Omit<Parameters<typeof buildChannelRef>[0], "editorRef" | "canSuggest">) =>+ buildChannelRef({ ...options, editorRef, canSuggest })+beforeEach(() => { editorRef.current = editor; editor.isFocused = true })+const candidate = (id: string,name: string,@@ -64,7 +73,7 @@ function getItemsCallback(const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { items?: unknown } } }).optionsconst items = (opts?.suggestion as { items: (props: { query: string }) => unknown[] } | undefined)?.itemsif (!items) throw new Error("suggestion.items not found")- return items+ return (props) => items({ ...props, editor } as never)}type RenderNodeProps = {@@ -105,7 +114,7 @@ function getKeyDownCallback(const handlers = render()const onKeyDown = handlers.onKeyDown as ((props: { event: KeyboardEvent }) => boolean) | undefinedif (!onKeyDown) throw new Error("onKeyDown not found")- return onKeyDown+ return (props) => onKeyDown({ ...props, view: editor.view } as never)}function getExitCallback(@@ -117,7 +126,7 @@ function getExitCallback(if (!render) throw new Error("suggestion.render not found")const onExit = render().onExit as (() => void) | undefinedif (!onExit) throw new Error("suggestion.onExit not found")- return onExit+ return () => onExit({ editor } as never)}function getPopupLifecycleCallbacks(@@ -147,7 +156,11 @@ function getPopupLifecycleCallbacks(if (!render) throw new Error("suggestion.render not found")const { onStart, onUpdate } = render()if (!onStart || !onUpdate) throw new Error("suggestion popup lifecycle not found")- return { onStart, onUpdate } as ReturnType<typeof getPopupLifecycleCallbacks>+ const callbacks = { onStart, onUpdate } as ReturnType<typeof getPopupLifecycleCallbacks>+ return {+ onStart: (props) => callbacks.onStart({ ...props, editor } as never),+ onUpdate: (props) => callbacks.onUpdate({ ...props, editor } as never),+ }}function build(@@ -158,7 +171,9 @@ function build(const candidatesRef = { current: candidates }const popupRef = { current: popup }const onIntentRef = { current: onIntent }- const setPopup = vi.fn()+ const setPopup = vi.fn((next: ChannelRefPopupState | ((current: ChannelRefPopupState) => ChannelRefPopupState)) => {+ popupRef.current = typeof next === "function" ? next(popupRef.current) : next+ })const queryRef = { current: "" }const ext = buildCommunityChannelRefExtension({ candidatesRef, popupRef, onIntentRef, setPopup, queryRef })return { ext, candidatesRef, popupRef, onIntentRef, setPopup, queryRef }@@ -236,6 +251,36 @@ describe("buildCommunityChannelRefExtension — suggestion.items callback", () =})describe("buildCommunityChannelRefExtension — popup lifecycle", () => {+ it("rejects unfocused intent/publication and late updates; an old command stays inert", () => {+ const items = [candidate("c1", "general")], raw = vi.fn(), intent = vi.fn()+ const { ext, popupRef } = build(items, EMPTY_CHANNEL_REF_STATE, intent)+ const callbacks = getPopupLifecycleCallbacks(ext)+ editor.isFocused = false+ expect(getItemsCallback(ext)({ query: "gen" })).toEqual([])+ callbacks.onStart({ items, query: "gen", command: raw })+ expect(intent).not.toHaveBeenCalled()+ expect(popupRef.current.command).toBeNull()+ editor.isFocused = true+ callbacks.onStart({ items, query: "gen", command: raw })+ const stale = popupRef.current.command!+ getExitCallback(ext)()+ callbacks.onUpdate({ items, query: "gen", command: raw })+ expect(popupRef.current.command).toBeNull()+ callbacks.onStart({ items, query: "gen", command: raw })+ stale(toChannelRefCommandProps(items[0]))+ expect(raw).not.toHaveBeenCalled()+ popupRef.current.command!(toChannelRefCommandProps(items[0]))+ expect(raw).toHaveBeenCalledExactlyOnceWith(toChannelRefCommandProps(items[0]))+ })++ it("old editor exit cannot clear a replacement editor popup", () => {+ const items = [candidate("c1", "general")], { ext, popupRef } = build(items)+ getPopupLifecycleCallbacks(ext).onStart({ items, command: vi.fn() })+ const current = popupRef.current+ editorRef.current = { isFocused: true, isDestroyed: false } as Editor+ getExitCallback(ext)()+ expect(popupRef.current).toBe(current)+ })it("passes the live query through onStart/onUpdate and defaults a missing query", () => {const items = [candidate("c1", "general")]const command = vi.fn()diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.tsindex 6223758ac..bc13a774e 100644--- a/src/web/src/lib/community/channel-ref-extension.ts+++ b/src/web/src/lib/community/channel-ref-extension.ts@@ -1,4 +1,5 @@import Mention from "@tiptap/extension-mention"+import type { Editor } from "@tiptap/react"import { PluginKey } from "@tiptap/pm/state"import { formatHandle } from "@alook/shared"import {@@ -104,7 +105,8 @@ export function rankChannelRefItems(return [...prefix, ...substr].slice(0, CHANNEL_REF_LIMIT)}-type SuggestionProps = SuggestionCaretAnchorProps & {+type SuggestionProps = Omit<SuggestionCaretAnchorProps, "editor"> & {+ editor: Editoritems: ChannelRefCandidate[]query?: stringcommand: (props: ChannelRefCommandProps) => void@@ -137,11 +139,7 @@ const ChannelRefNode = Mention.extend({** `suggestion.char = "/"`, `allowedPrefixes` left at the library default* (`[' ']`, start-of-line included) — exactly the "must follow a space"- * rule from the spec, no custom `allow` callback needed. The explicit- * `pluginKey` below is good practice for debugging/introspection but isn't- * itself load-bearing (anonymous `new PluginKey()` calls already get an- * auto-incrementing unique suffix in `prosemirror-state`) — the node- * **name** rename above is what actually avoids the schema collision.+ * rule from the spec.** `renderText` inserts by display name, not id — server/channel names are* now guaranteed ref-safe at creation/rename time (`slugify()`, applied by@@ -155,6 +153,8 @@ const ChannelRefNode = Mention.extend({* only, not the full path — keeping the compose box readable.*/export function buildCommunityChannelRefExtension(opts: {+ editorRef: { current: Editor | null }+ canSuggest: (editor: Editor) => booleancandidatesRef: { current: ChannelRefCandidate[] }popupRef: { current: ChannelRefPopupState }onIntentRef?: { current: (() => void) | undefined }@@ -167,8 +167,15 @@ export function buildCommunityChannelRefExtension(opts: {// extension's `queryRef`.queryRef?: { current: string }}) {- const { candidatesRef, popupRef, onIntentRef, setPopup, queryRef } = opts+ const { editorRef, canSuggest, candidatesRef, popupRef, onIntentRef, setPopup, queryRef } = optslet intentSessionActive = false+ const commandFor = (props: SuggestionProps) => {+ const command: NonNullable<ChannelRefPopupState["command"]> = (value) => {+ if (!canSuggest(props.editor) || popupRef.current.command !== command) return+ props.command(value)+ }+ return command+ }return ChannelRefNode.configure({HTMLAttributes: { class: "channel-ref-highlight" },@@ -200,7 +207,10 @@ export function buildCommunityChannelRefExtension(opts: {suggestion: {char: "/",pluginKey: new PluginKey("channelRefSuggestion"),- items: ({ query }: { query: string }) => {+ allow: ({ editor }) => canSuggest(editor),+ shouldShow: ({ transaction }) => Boolean(popupRef.current.command) || transaction.docChanged || transaction.selectionSet,+ items: ({ query, editor }: { query: string; editor: Editor }) => {+ if (!canSuggest(editor)) return []if (!intentSessionActive) {intentSessionActive = trueonIntentRef?.current?.()@@ -210,15 +220,17 @@ export function buildCommunityChannelRefExtension(opts: {},render: () => ({onStart: (props: SuggestionProps) => {+ if (!canSuggest(props.editor)) returnsetPopup({items: props.items ?? [],query: props.query ?? "",selectedIndex: 0,- command: props.command,+ command: commandFor(props),getRect: createSuggestionCaretRectResolver(props),})},onUpdate: (props: SuggestionProps) => {+ if (!canSuggest(props.editor) || !popupRef.current.command) returnsetPopup((cur) => ({items: props.items ?? [],query: props.query ?? "",@@ -226,11 +238,13 @@ export function buildCommunityChannelRefExtension(opts: {cur.selectedIndex < (props.items?.length ?? 0)? cur.selectedIndex: 0,- command: props.command,+ command: commandFor(props),getRect: createSuggestionCaretRectResolver(props),}))},- onKeyDown: ({ event }: { event: KeyboardEvent }) => {+ onKeyDown: ({ event, view }) => {+ const editor = editorRef.current+ if (!editor || !canSuggest(editor) || editor.view !== view) return falseif (event.isComposing) return falseconst cur = popupRef.currentif (cur.items.length === 0) return false@@ -273,8 +287,10 @@ export function buildCommunityChannelRefExtension(opts: {}return false},- onExit: () => {+ onExit: ({ editor }) => {+ if (editorRef.current !== editor) returnintentSessionActive = false+ if (queryRef) queryRef.current = ""setPopup(EMPTY_CHANNEL_REF_STATE)},}),diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 4ec347ebe..5f75b28b6 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -1,7 +1,7 @@-import { describe, it, expect, vi } from "vitest"+import { beforeEach, describe, it, expect, vi } from "vitest"import type { Member } from "@/lib/community/models/people"import {- buildCommunityMentionExtension,+ buildCommunityMentionExtension as buildMention,rankMentionItems,detectMentionType,EMPTY_MENTION_STATE,@@ -9,6 +9,15 @@ import {type MentionPopupState,} from "./mention-extension"+import type { Editor } from "@tiptap/react"++const editor = { isFocused: true, isDestroyed: false } as Editor+const editorRef: { current: Editor | null } = { current: editor }+const canSuggest = (candidate: Editor) => candidate === editorRef.current && candidate.isFocused && !candidate.isDestroyed+const buildCommunityMentionExtension = (options: Omit<Parameters<typeof buildMention>[0], "editorRef" | "canSuggest">) =>+ buildMention({ ...options, editorRef, canSuggest })+beforeEach(() => { editorRef.current = editor; editor.isFocused = true })+// A member must carry a discriminator to appear in the popup (disc-less members// are filtered out), so the helper defaults one. Labels are always tagged now.const member = (id: string, name: string, discriminator = "0000"): Member => ({@@ -191,7 +200,7 @@ function getItemsCallback(const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { items?: unknown } } }).optionsconst items = (opts?.suggestion as { items: (props: { query: string }) => unknown[] } | undefined)?.itemsif (!items) throw new Error("suggestion.items not found")- return items+ return (props) => items({ ...props, editor } as never)}function getAllowCallback(@@ -201,7 +210,7 @@ function getAllowCallback(const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { allow?: unknown } } }).optionsconst allow = (opts?.suggestion as { allow: () => boolean } | undefined)?.allowif (!allow) throw new Error("suggestion.allow not found")- return allow+ return () => allow({ editor } as never)}type MentionRenderProps = {@@ -229,7 +238,13 @@ function getRenderCallbacks((ext as unknown as { options?: { suggestion?: { render?: unknown } } }).optionsconst render = opts?.suggestion?.render as (() => MentionRenderCallbacks) | undefinedif (!render) throw new Error("suggestion.render not found")- return render()+ const callbacks = render()+ return {+ onStart: (props) => callbacks.onStart({ ...props, editor } as never),+ onUpdate: (props) => callbacks.onUpdate({ ...props, editor } as never),+ onKeyDown: (props) => callbacks.onKeyDown({ ...props, view: editor.view } as never),+ onExit: () => callbacks.onExit({ editor } as never),+ }}function keyboardEvent(key: string, isComposing = false) {@@ -439,6 +454,34 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>"ad",)+ it("rejects unfocused publication and late updates; a retired command cannot insert", () => {+ const harness = setup(), raw = vi.fn()+ editor.isFocused = false+ harness.callbacks.onStart({ items, query: "ad", command: raw })+ expect(harness.popup().command).toBeNull()+ editor.isFocused = true+ harness.callbacks.onStart({ items, query: "ad", command: raw })+ const stale = harness.popup().command!+ harness.callbacks.onExit()+ harness.callbacks.onUpdate({ items, query: "ad", command: raw })+ expect(harness.popup().command).toBeNull()+ harness.callbacks.onStart({ items, query: "ad", command: raw })+ stale({ id: "m1", label: "Ada#0001" })+ expect(raw).not.toHaveBeenCalled()+ harness.popup().command!({ id: "m1", label: "Ada#0001" })+ expect(raw).toHaveBeenCalledExactlyOnceWith({ id: "m1", label: "Ada#0001" })+ })++ it("old editor exit cannot clear a replacement editor popup or its search", () => {+ const harness = setup()+ harness.callbacks.onStart({ items, query: "ad", command: vi.fn() })+ const current = harness.popup()+ editorRef.current = { isFocused: true, isDestroyed: false } as Editor+ harness.callbacks.onExit()+ expect(harness.popup()).toBe(current)+ expect(harness.search).not.toHaveBeenCalled()+ })+it("starts and updates popup state while preserving only an in-range selection", () => {const harness = setup()const firstCommand = vi.fn()@@ -453,7 +496,7 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>items,query: "ad",selectedIndex: 0,- command: firstCommand,+ command: expect.any(Function),getRect: firstRect,})@@ -470,7 +513,7 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>items,query: "ade",selectedIndex: 1,- command: nextCommand,+ command: expect.any(Function),getRect: nextRect,})@@ -591,7 +634,7 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>expect(harness.callbacks.onKeyDown({ event: keyboardEvent("Enter") })).toBe(false)})- it("ignores stale lifecycle, key, insertion, and exit callbacks after a live transition to DM", () => {+ it("ignores stale publication and insertion in DM but still cleans up on exit", () => {const harness = setup()const staleCommand = vi.fn()harness.setPopup({@@ -616,8 +659,8 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>expect(staleCommand).not.toHaveBeenCalled()harness.callbacks.onExit()- expect(harness.search).not.toHaveBeenCalled()- expect(harness.popup()).toBe(beforeTransition)+ expect(harness.search).toHaveBeenLastCalledWith("")+ expect(harness.popup()).toEqual(EMPTY_MENTION_STATE)})})diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex 63af21a33..6ca25de86 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -1,4 +1,6 @@import Mention from "@tiptap/extension-mention"+import type { Editor } from "@tiptap/react"+import { PluginKey } from "@tiptap/pm/state"import { MENTION_TYPES, type MentionType } from "@alook/shared"import type { Member } from "@/lib/community/models/people"import {@@ -114,7 +116,8 @@ export const EMPTY_MENTION_STATE: MentionPopupState = {getRect: null,}-type SuggestionProps = SuggestionCaretAnchorProps & {+type SuggestionProps = Omit<SuggestionCaretAnchorProps, "editor"> & {+ editor: Editoritems: MentionItem[]query?: stringcommand: (props: { id: string; label: string }) => void@@ -133,6 +136,8 @@ type SuggestionProps = SuggestionCaretAnchorProps & {* the mention.*/export function buildCommunityMentionExtension(opts: {+ editorRef: { current: Editor | null }+ canSuggest: (editor: Editor) => booleanmembersRef: { current: Member[] }contextRef: { current: MentionContext }popupRef: { current: MentionPopupState }@@ -150,7 +155,15 @@ export function buildCommunityMentionExtension(opts: {// two paths in agreement.queryRef?: { current: string }}) {- const { membersRef, contextRef, popupRef, setPopup, onSearchMembersRef, queryRef } = opts+ const { editorRef, canSuggest, membersRef, contextRef, popupRef, setPopup, onSearchMembersRef, queryRef } = opts+ const eligible = (editor: Editor) => contextRef.current !== "dm" && canSuggest(editor)+ const commandFor = (props: SuggestionProps) => {+ const command: NonNullable<MentionPopupState["command"]> = (value) => {+ if (!eligible(props.editor) || popupRef.current.command !== command) return+ props.command(value)+ }+ return command+ }return Mention.configure({HTMLAttributes: { class: "mention-highlight" },@@ -159,16 +172,18 @@ export function buildCommunityMentionExtension(opts: {["span", options.HTMLAttributes, `@${mentionDisplayLabel(node.attrs.label ?? node.attrs.id ?? "")}`],suggestion: {char: "@",+ pluginKey: new PluginKey("communityMentionSuggestion"),// The extension is intentionally built once by the Composer, so this// boundary must read the live context ref. Returning no ranked items is// not enough: TipTap would still start the suggestion lifecycle and// capture keys for an empty popup in DMs.- allow: () => contextRef.current !== "dm",- items: ({ query }: { query: string }) => {+ allow: ({ editor }) => eligible(editor),+ shouldShow: ({ transaction }) => Boolean(popupRef.current.command) || transaction.docChanged || transaction.selectionSet,+ items: ({ query, editor }: { query: string; editor: Editor }) => {// Defense-in-depth for an already-scheduled items callback during a// channel -> DM transition. A DM must not update query state or start// a remote member search even if TipTap invokes this stale callback.- if (contextRef.current === "dm") return []+ if (!eligible(editor)) return []if (queryRef) queryRef.current = queryonSearchMembersRef?.current?.(query)return rankMentionItems(@@ -179,17 +194,17 @@ export function buildCommunityMentionExtension(opts: {},render: () => ({onStart: (props: SuggestionProps) => {- if (contextRef.current === "dm") return+ if (!eligible(props.editor)) returnsetPopup({items: props.items ?? [],query: queryRef?.current ?? props.query ?? "",selectedIndex: 0,- command: props.command,+ command: commandFor(props),getRect: createSuggestionCaretRectResolver(props),})},onUpdate: (props: SuggestionProps) => {- if (contextRef.current === "dm") return+ if (!eligible(props.editor) || !popupRef.current.command) returnsetPopup((cur) => ({items: props.items ?? [],query: queryRef?.current ?? props.query ?? "",@@ -197,12 +212,13 @@ export function buildCommunityMentionExtension(opts: {cur.selectedIndex < (props.items?.length ?? 0)? cur.selectedIndex: 0,- command: props.command,+ command: commandFor(props),getRect: createSuggestionCaretRectResolver(props),}))},- onKeyDown: ({ event }: { event: KeyboardEvent }) => {- if (contextRef.current === "dm") return false+ onKeyDown: ({ event, view }) => {+ const editor = editorRef.current+ if (!editor || !eligible(editor) || editor.view !== view) return falseif (event.isComposing) return falseconst cur = popupRef.currentif (cur.items.length === 0) return false@@ -238,9 +254,10 @@ export function buildCommunityMentionExtension(opts: {}return false},- onExit: () => {- if (contextRef.current === "dm") return- onSearchMembersRef?.current?.("")+ onExit: ({ editor }) => {+ if (editorRef.current !== editor) return+ if (queryRef?.current || popupRef.current.command) onSearchMembersRef?.current?.("")+ if (queryRef) queryRef.current = ""setPopup(EMPTY_MENTION_STATE)},}),diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex 552ff4738..c5f45a026 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -1,7 +1,7 @@import type { Locator, Page } from "@playwright/test"import { test, expect, userId } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"-import { composerEditable } from "./_fixtures/actions"+import { composerEditable, openChannel } from "./_fixtures/actions"import {seedServer,seedChannel,@@ -157,6 +157,44 @@ test.describe.serial("mentions — candidate scope", () => {await expect(opt.carol).toHaveCount(0)})+ test("private local search reports a failed access read and recovers on warm channel re-entry", async ({ asUser }) => {+ const { page } = await asUser("alice")+ let failAccess = true+ let accessReads = 0+ await page.route(`**/api/community/channels/${privateChannelId}/members?*`, async (route) => {+ if (new URL(route.request().url()).searchParams.get("relation") !== "access") return route.continue()+ accessReads += 1+ if (failAccess) return route.fulfill({ status: 500, json: { error: "controlled access read failure" } })+ return route.continue()+ })+ await page.goto(`/c/channels/${serverId}/${privateChannelId}`)+ await openMentionPopup(page)+ await expect(page.getByTestId(tid.mentionStatus)).toHaveAttribute("data-state", "error")+ await expect(page.getByTestId(tid.mentionOption(carol.id))).toHaveCount(0)+ expect(accessReads).toBeGreaterThan(0)+ const failedReads = accessReads+ failAccess = false+ await page.keyboard.press("Escape")+ await openChannel(page, publicChannelId)+ const recovered = page.waitForResponse((response) => response.status() === 200 && new URL(response.url()).pathname === `/api/community/channels/${privateChannelId}/members`)+ await openChannel(page, privateChannelId)+ await recovered+ const editable = composerEditable(page)+ await editable.fill("")+ const opt = await openMentionPopup(page)+ await expect(opt.bob).toBeVisible()+ await expect(opt.carol).toHaveCount(0)+ await expect(page.getByTestId(tid.mentionOption(alice.id))).toHaveCount(0)+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)+ expect(accessReads).toBeGreaterThan(failedReads)+ await page.keyboard.press("Escape")+ await page.keyboard.press("Backspace")+ await editable.pressSequentially(`@${bob.name.slice(0, 3)}`)+ await expect(page.getByTestId(tid.mentionOption(bob.id))).toBeVisible()+ await expect(page.getByTestId(tid.mentionOption(carol.id))).toHaveCount(0)+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)+ })+test("forum post reply → post audience (bob present, carol absent)", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${privatePostId}`)diff --git a/src/web/src/test/e2e-ui/19-marketing-seo.spec.ts b/src/web/src/test/e2e-ui/19-marketing-seo.spec.tsindex 49fdb4769..183fa7ea2 100644--- a/src/web/src/test/e2e-ui/19-marketing-seo.spec.ts+++ b/src/web/src/test/e2e-ui/19-marketing-seo.spec.ts@@ -246,12 +246,12 @@ for (const width of [1440, 390]) {await page.goto("/pricing")const contact = page.getByRole("link", { name: "Contact us", exact: true })await expect(contact).toBeInViewport()+ await expect(page.getByRole("heading", { name: "Free", exact: true }).locator("..").getByRole("button")).not.toHaveText("Loading…")const box = await contact.boundingBox()const plans = await page.getByRole("region", { name: "Alook plans" }).boundingBox()expect(box!.height).toBeGreaterThanOrEqual(44)expect(box!.y + box!.height).toBeLessThan(plans!.y)expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width)- await expect(page.getByRole("heading", { name: "Free", exact: true }).locator("..").getByRole("button")).not.toHaveText("Loading…")await page.screenshot({ path: testInfo.outputPath("pricing-contact.png") })await contact.focus()await page.keyboard.press("Enter")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.tsindex 4342ba58e..dd06a4752 100644--- 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.ts@@ -64,6 +64,7 @@ test("@ candidates page to completion and shared popups stay anchored through viconst browse = Array.from({ length: 12 }, (_, index) => candidate("Browse", index + 1))const matches = Array.from({ length: 205 }, (_, index) => candidate("CapMatch", index + 1))+ const searchReads = new Map<string, number>()let releaseSearchTail!: () => voidconst searchTailReleased = new Promise<void>((resolve) => {releaseSearchTail = resolve@@ -77,6 +78,7 @@ test("@ candidates page to completion and shared popups stay anchored through viconst url = new URL(route.request().url())if (url.pathname.endsWith("/members/search")) {const query = url.searchParams.get("q") ?? ""+ searchReads.set(query, (searchReads.get(query) ?? 0) + 1)const cursor = url.searchParams.get("cursor")if (query === "Fail") {await route.fulfill({ status: 500, json: { error: "forced failure" } })@@ -216,6 +218,14 @@ test("@ candidates page to completion and shared popups stay anchored through vi}))expectAnchoredToCaret(await readBounds(tid.channelRefPopup))+ await page.keyboard.press("Escape")+ await editable.press("ControlOrMeta+A")+ await editable.press("Backspace")+ await editable.pressSequentially("@CapMatch")+ await expect(page.getByTestId(tid.mentionOption(matches[204]!.id))).toHaveCount(1)+ await expect(page.getByTestId(tid.mentionPopup).getByRole("option")).toHaveCount(205)+ expect(searchReads.get("CapMatch")).toBe(2)+await page.keyboard.press("Escape")await editable.press("ControlOrMeta+A")await editable.press("Backspace")@@ -227,4 +237,13 @@ test("@ candidates page to completion and shared popups stay anchored through viawait editable.press("Backspace")await editable.pressSequentially("@Fail")await expect(page.getByTestId(tid.mentionStatus)).toHaveAttribute("data-state", "error")++ await page.keyboard.press("Escape")+ await editable.press("ControlOrMeta+A")+ await editable.press("Backspace")+ await editable.pressSequentially("@CapMatch")+ await expect(page.getByTestId(tid.mentionOption(matches[204]!.id))).toHaveCount(1)+ await expect(page.getByTestId(tid.mentionPopup).getByRole("option")).toHaveCount(205)+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)+ expect(searchReads.get("CapMatch")).toBe(2)})