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): disable mention suggestions in DMs (#600)
Gener36bcf70f57d6
diff --git a/src/web/src/components/community/messages/use-composer-suggestions.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.test.tsindex a2103ce91..6f3eba23e 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.test.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.test.ts@@ -110,7 +110,9 @@ describe("useComposerSuggestions", () => {mocks.rankChannel.mockReset()mocks.buildMention.mockImplementation((options) => ({name: "mention-extension",+ allow: () => options.contextRef.current !== "dm",runQuery: (query: string) => {+ if (options.contextRef.current === "dm") return []options.queryRef.current = queryoptions.onSearchMembersRef.current?.(query)return mocks.rankMention(@@ -253,6 +255,112 @@ describe("useComposerSuggestions", () => {expect(mocks.rankChannel).toHaveBeenLastCalledWith(thirdChannels, "gen")})+ it("disables mentions across a live DM transition without rebuilding or disturbing channel refs", async () => {+ const resultRef: { current: Result | null } = { current: null }+ const search = vi.fn()+ const mentionItem = {+ kind: "member" as const,+ id: "member-1",+ userId: "user-1",+ label: "Ada#0001",+ name: "Ada",+ discriminator: "0001",+ avatar: "A",+ status: "online" as const,+ }+ const channelItem = channel()+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(Harness, {+ members: [member()],+ context: "channel",+ mentionCandidates: candidateSource(search),+ channelRefCandidates: [channelItem],+ resultRef,+ }))+ })+ const mentionOptions = mocks.buildMention.mock.calls[0][0]+ const channelOptions = mocks.buildChannel.mock.calls[0][0]+ const extension = resultRef.current!.mentionExtension as unknown as {+ allow: () => boolean+ runQuery: (query: string) => unknown+ }+ const channelCommand = vi.fn()+ await act(async () => {+ mentionOptions.setPopup({+ items: [mentionItem],+ query: "ad",+ selectedIndex: 0,+ command: vi.fn(),+ getRect: null,+ })+ channelOptions.setPopup({+ items: [channelItem],+ selectedIndex: 0,+ command: channelCommand,+ getRect: null,+ })+ })+ expect(extension.allow()).toBe(true)++ extension.runQuery("ad")+ search.mockClear()+ mocks.rankMention.mockClear()+ mocks.rankChannel.mockReturnValue([channelItem])+ await act(async () => {+ renderer.update(createElement(Harness, {+ members: [],+ context: "dm",+ mentionCandidates: candidateSource(search),+ channelRefCandidates: [channelItem],+ resultRef,+ }))+ })++ expect(mocks.buildMention).toHaveBeenCalledOnce()+ expect(resultRef.current!.mentionExtension).toBe(extension)+ expect(extension.allow()).toBe(false)+ expect(resultRef.current!.mentionPopup).toEqual({+ items: [],+ query: "",+ selectedIndex: 0,+ command: null,+ getRect: null,+ })+ expect(resultRef.current!.channelRefPopup).toEqual({+ items: [channelItem],+ selectedIndex: 0,+ command: channelCommand,+ getRect: null,+ })+ expect(search).toHaveBeenCalledOnce()+ expect(search).toHaveBeenLastCalledWith("")+ search.mockClear()+ expect(extension.runQuery("abc")).toEqual([])+ expect(search).not.toHaveBeenCalled()+ expect(mocks.rankMention).not.toHaveBeenCalled()++ mocks.rankMention.mockReturnValue([mentionItem])+ await act(async () => {+ renderer.update(createElement(Harness, {+ members: [member()],+ context: "thread",+ mentionCandidates: candidateSource(search),+ channelRefCandidates: [channelItem],+ resultRef,+ }))+ })+ expect(resultRef.current!.mentionExtension).toBe(extension)+ expect(extension.allow()).toBe(true)+ expect(extension.runQuery("ad")).toEqual([mentionItem])+ expect(search).toHaveBeenCalledWith("ad")+ expect(mocks.rankMention).toHaveBeenLastCalledWith(+ [member()],+ "thread",+ "ad",+ )+ })+it("reranks open mentions, preserves valid selection, and detects visual changes", async () => {const resultRef: { current: Result | null } = { current: null }const initialItem = {diff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.tsindex 607397e6a..3e357928e 100644--- a/src/web/src/components/community/messages/use-composer-suggestions.ts+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from "react"+import { useEffect, useLayoutEffect, useRef, useState } from "react"import {buildCommunityMentionExtension,EMPTY_MENTION_STATE,@@ -100,12 +100,22 @@ export function useComposerSuggestions({useEffect(() => {membersRef.current = members}, [members])- useEffect(() => {+ 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])- useEffect(() => {- onSearchMembersRef.current = mentionCandidates?.search- }, [mentionCandidates?.search])// eslint-disable-next-line react-hooks/refs -- runtime suggestion callbacks read these refsconst [mentionExtension] = useState(() =>@@ -160,6 +170,7 @@ export function useComposerSuggestions({)useEffect(() => {+ if (context === "dm") returnconst current = mentionPopupRef.currentif (!current.command) returnconst query = mentionQueryRef.currentdiff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.tsindex 9712c2773..074fcd3b0 100644--- a/src/web/src/lib/community/mention-extension.test.ts+++ b/src/web/src/lib/community/mention-extension.test.ts@@ -194,6 +194,16 @@ function getItemsCallback(return items}+function getAllowCallback(+ ext: ReturnType<typeof buildCommunityMentionExtension>,+): () => boolean {+ const config = (ext as unknown as { config: { addOptions?: () => { suggestion?: { allow?: unknown } } } }).config+ const opts = config.addOptions?.() ?? (ext as unknown as { options?: { suggestion?: { allow?: unknown } } }).options+ const allow = (opts?.suggestion as { allow: () => boolean } | undefined)?.allow+ if (!allow) throw new Error("suggestion.allow not found")+ return allow+}+type MentionRenderProps = {items?: MentionPopupState["items"]query?: string@@ -286,6 +296,27 @@ describe("buildCommunityMentionExtension — renderText/renderHTML", () => {})})+describe("buildCommunityMentionExtension — suggestion.allow callback", () => {+ it("reads the live context ref and disables the TipTap lifecycle only in DMs", () => {+ const contextRef = { current: "channel" as MentionContext }+ const ext = buildCommunityMentionExtension({+ membersRef: { current: [] as Member[] },+ contextRef,+ popupRef: { current: EMPTY_MENTION_STATE as MentionPopupState },+ setPopup: () => { },+ })+ const allow = getAllowCallback(ext)++ expect(allow()).toBe(true)+ contextRef.current = "thread"+ expect(allow()).toBe(true)+ contextRef.current = "dm"+ expect(allow()).toBe(false)+ contextRef.current = "channel"+ expect(allow()).toBe(true)+ })+})+describe("buildCommunityMentionExtension — suggestion.items callback", () => {it("fires onSearchMembersRef.current with the current query on each items() call", () => {const membersRef = { current: [] as Member[] }@@ -329,20 +360,24 @@ describe("buildCommunityMentionExtension — suggestion.items callback", () => {expect(queryRef.current).toBe("hello")})- it("is a no-op when onSearchMembersRef is undefined (DM composer)", () => {- const membersRef = { current: [] as Member[] }+ it("does not update query state, search remotely, or rank stale members in a DM", () => {+ const membersRef = { current: [member("m1", "Alice")] as Member[] }const contextRef = { current: "dm" as MentionContext }const popupRef = { current: EMPTY_MENTION_STATE as MentionPopupState }- // No onSearchMembersRef, no queryRef — the mention builder must still- // return the DM-context ranking ([]) without throwing.+ const search = vi.fn()+ const queryRef = { current: "channel-query" }const ext = buildCommunityMentionExtension({membersRef,contextRef,popupRef,setPopup: () => { },+ onSearchMembersRef: { current: search },+ queryRef,})const items = getItemsCallback(ext)expect(items({ query: "anything" })).toEqual([])+ expect(queryRef.current).toBe("channel-query")+ expect(search).not.toHaveBeenCalled()})it("returns the ranked items straight from rankMentionItems for the live refs", () => {@@ -372,6 +407,7 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>function setup(queryRef?: { current: string }) {let popup: MentionPopupState = EMPTY_MENTION_STATEconst popupRef = { current: popup }+ const contextRef = { current: "channel" as MentionContext }const search = vi.fn()const setPopup = (next: MentionPopupState | ((cur: MentionPopupState) => MentionPopupState),@@ -381,7 +417,7 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>}const ext = buildCommunityMentionExtension({membersRef: { current: [] as Member[] },- contextRef: { current: "channel" as MentionContext },+ contextRef,popupRef,setPopup,onSearchMembersRef: { current: search },@@ -389,6 +425,7 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>})return {callbacks: getRenderCallbacks(ext),+ contextRef,popup: () => popup,popupRef,search,@@ -553,6 +590,35 @@ describe("buildCommunityMentionExtension — suggestion.render callbacks", () =>harness.setPopup(EMPTY_MENTION_STATE)expect(harness.callbacks.onKeyDown({ event: keyboardEvent("Enter") })).toBe(false)})++ it("ignores stale lifecycle, key, insertion, and exit callbacks after a live transition to DM", () => {+ const harness = setup()+ const staleCommand = vi.fn()+ harness.setPopup({+ items,+ query: "ad",+ selectedIndex: 0,+ command: staleCommand,+ getRect: null,+ })+ const beforeTransition = harness.popup()+ harness.contextRef.current = "dm"++ harness.callbacks.onStart({ items, query: "new", command: vi.fn() })+ harness.callbacks.onUpdate({ items: items.slice(0, 1), query: "updated", command: vi.fn() })+ expect(harness.popup()).toBe(beforeTransition)++ for (const key of ["Enter", "Tab", "ArrowDown", "ArrowUp", "Escape"]) {+ const event = keyboardEvent(key)+ expect(harness.callbacks.onKeyDown({ event })).toBe(false)+ expect(event.preventDefault).not.toHaveBeenCalled()+ }+ expect(staleCommand).not.toHaveBeenCalled()++ harness.callbacks.onExit()+ expect(harness.search).not.toHaveBeenCalled()+ expect(harness.popup()).toBe(beforeTransition)+ })})describe("detectMentionType", () => {diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.tsindex 67e43d0bd..eb64aa7d3 100644--- a/src/web/src/lib/community/mention-extension.ts+++ b/src/web/src/lib/community/mention-extension.ts@@ -155,7 +155,16 @@ export function buildCommunityMentionExtension(opts: {["span", options.HTMLAttributes, `@${mentionDisplayLabel(node.attrs.label ?? node.attrs.id ?? "")}`],suggestion: {char: "@",+ // 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 }) => {+ // 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 (queryRef) queryRef.current = queryonSearchMembersRef?.current?.(query)return rankMentionItems(@@ -166,6 +175,7 @@ export function buildCommunityMentionExtension(opts: {},render: () => ({onStart: (props: SuggestionProps) => {+ if (contextRef.current === "dm") returnsetPopup({items: props.items ?? [],query: queryRef?.current ?? props.query ?? "",@@ -175,6 +185,7 @@ export function buildCommunityMentionExtension(opts: {})},onUpdate: (props: SuggestionProps) => {+ if (contextRef.current === "dm") returnsetPopup((cur) => ({items: props.items ?? [],query: queryRef?.current ?? props.query ?? "",@@ -187,6 +198,7 @@ export function buildCommunityMentionExtension(opts: {}))},onKeyDown: ({ event }: { event: KeyboardEvent }) => {+ if (contextRef.current === "dm") return falseif (event.isComposing) return falseconst cur = popupRef.currentif (cur.items.length === 0) return false@@ -223,6 +235,7 @@ export function buildCommunityMentionExtension(opts: {return false},onExit: () => {+ if (contextRef.current === "dm") returnonSearchMembersRef?.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 f07488c6d..2ebb6bd82 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@@ -192,18 +192,49 @@ test.describe.serial("mentions — candidate scope", () => {await expect(page.getByTestId(tid.mentionOption(bob.id))).toBeVisible({ timeout: 15_000 })})- test("1:1 DM composer has no @ popup at all (no members, no everyone/here)", async ({ asUser }) => {+ test("1:1 DM keeps @abc as plain text, never starts mention suggestions, and sends with Enter", async ({ asUser }) => {const dmId = await seedDm("alice", userId("bob"))const { page } = await asUser("alice")+ const memberSearchRequests: string[] = []+ const messagePosts: string[] = []+ page.on("request", (request) => {+ const url = new URL(request.url())+ if (url.pathname.endsWith("/members/search")) {+ memberSearchRequests.push(request.url())+ }+ if (+ request.method() === "POST"+ && url.pathname === `/api/community/channels/${dmId}/messages`+ ) {+ messagePosts.push(request.url())+ }+ })await page.goto(`/c/me/${dmId}`)await page.waitForURL(new RegExp(dmId), { timeout: 20_000, waitUntil: "commit" })const editable = composerEditable(page)await editable.click()- await editable.pressSequentially("@")- // DM context short-circuits the ranker → zero options, and no virtual rows.+ await editable.pressSequentially("@abc")+ await expect(editable).toHaveText("@abc")+ await expect(editable.locator('[data-type="mention"]')).toHaveCount(0)+ await expect(page.getByTestId(tid.mentionPopup)).toHaveCount(0)+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)await expect(page.getByTestId(tid.mentionOption(bob.id))).toHaveCount(0)await expect(page.getByTestId(tid.mentionOption("everyone"))).toHaveCount(0)await expect(page.getByTestId(tid.mentionOption("here"))).toHaveCount(0)++ const responsePromise = page.waitForResponse((response) => {+ const url = new URL(response.url())+ return response.request().method() === "POST"+ && url.pathname === `/api/community/channels/${dmId}/messages`+ })+ await page.keyboard.press("Enter")+ const response = await responsePromise+ expect(response.status()).toBe(201)+ const payload = await response.json() as { message: { id: string } }+ await expect(page.getByTestId(tid.message(payload.message.id))).toContainText("@abc")+ await expect(editable).toHaveText("")+ expect(memberSearchRequests).toHaveLength(0)+ expect(messagePosts).toHaveLength(1)})})