Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): track @mention selection by identity, not slot index (MUL-3607) (#4488)
Naiyuan Qing8a0934c7411c
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsxindex 291837f5fb..15ec6387a3 100644--- a/packages/views/editor/extensions/mention-suggestion.test.tsx+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from "@testing-library/react";+import { act, render, screen, waitFor } from "@testing-library/react";import { createRef, type ReactNode } from "react";import { describe, it, expect, vi, beforeEach } from "vitest";import { workspaceKeys } from "@multica/core/workspace/queries";@@ -209,6 +209,55 @@ describe("createMentionSuggestion", () => {).toBe(true);});+ // MUL-3607: groupItems() re-buckets the list (current → recent → search →+ // users → issues), so an item that sits LATER in the data array can render+ // NEAR THE TOP. Selection must follow the rendered order — otherwise the+ // highlighted row and the committed item drift apart and you mention the+ // neighbour of who you picked. (Issue rows are used because they render+ // without workspace/avatar context; the bug is type-agnostic.)+ it("commits the highlighted row, not its neighbour, when groups reorder the list", () => {+ const command = vi.fn<(item: MentionItem) => void>();+ const ref = createRef<MentionListRef>();++ // Data order is [MUL-2 (issues bucket), MUL-1 (search bucket)], but+ // groupItems hoists the search row, so the RENDERED order is [MUL-1, MUL-2].+ const items: MentionItem[] = [+ { id: "i-plain", label: "MUL-2", type: "issue" },+ { id: "i-search", label: "MUL-1", type: "issue", group: "search" },+ ];++ render(+ <I18nWrapper>+ <MentionList ref={ref} items={items} query="" command={command} includeProjectSearch />+ </I18nWrapper>,+ );++ const highlightedLabel = () => {+ const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>("button"));+ return buttons.find((b) => b.classList.contains("bg-accent"))?.textContent ?? "";+ };+ const press = (key: string) =>+ act(() => {+ ref.current?.onKeyDown({ event: new KeyboardEvent("keydown", { key }) });+ });++ // First rendered row is the hoisted search result. Enter commits it, not+ // the issue that sits first in the data array.+ expect(highlightedLabel()).toBe("MUL-1");+ press("Enter");+ expect(command).toHaveBeenCalledTimes(1);+ expect(command.mock.calls[0]?.[0]?.label).toBe("MUL-1");++ command.mockClear();++ // Arrow down one row, then Enter — still commits exactly the highlighted row.+ press("ArrowDown");+ expect(highlightedLabel()).toBe("MUL-2");+ press("Enter");+ expect(command).toHaveBeenCalledTimes(1);+ expect(command.mock.calls[0]?.[0]?.label).toBe("MUL-2");+ });+it("hides personal agents owned by someone else from a regular member", () => {const qc = fakeQc({members: [diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsxindex 54a0c00e49..b246bb0688 100644--- a/packages/views/editor/extensions/mention-suggestion.tsx+++ b/packages/views/editor/extensions/mention-suggestion.tsx@@ -146,7 +146,14 @@ function mergeMentionItems(export const MentionList = forwardRef<MentionListRef, MentionListProps>(function MentionList({ items, query, command, includeProjectSearch = false }, ref) {const { t } = useT("editor");- const [selectedIndex, setSelectedIndex] = useState(0);+ // Selection is tracked by item identity, NOT by a positional index. The+ // list is re-bucketed by groupItems() and grows asynchronously (server+ // search results), so a slot index is not a stable target — the row under+ // index N changes as the list reorders. selectedKey pins the highlight to+ // a specific item; the numeric index is derived from it against the SAME+ // order the popup renders (orderedItems). null means "no explicit pick yet"+ // → the first rendered row is highlighted by default.+ const [selectedKey, setSelectedKey] = useState<string | null>(null);const [serverItems, setServerItems] = useState<MentionItem[]>([]);const [isSearching, setIsSearching] = useState(false);const [searchedQuery, setSearchedQuery] = useState("");@@ -232,23 +239,36 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(return mergeMentionItems(items, currentServerItems).slice(0, MAX_ITEMS);}, [items, normalizedQuery, searchedQuery, serverItems]);- useEffect(() => {- setSelectedIndex(0);- }, [displayItems]);+ // The single index space for selection. groupItems() re-buckets displayItems+ // (current → recent → search → users → issues); orderedItems is exactly what+ // the popup renders, top to bottom. Keyboard nav, Enter, clicks, highlight,+ // and scroll all index THIS, so the highlighted row always equals the+ // committed item — there is no second "data order" to drift against.+ const groups = useMemo(() => groupItems(displayItems), [displayItems]);+ const orderedItems = useMemo(() => groups.flatMap((g) => g.items), [groups]);++ // Derive the numeric index from the pinned identity. If the selected item+ // is no longer in the list (query narrowed it away) or nothing is picked+ // yet, fall back to the first row. This self-heals across reorders and+ // async result arrival without ever force-resetting an active selection.+ const selectedIndex = useMemo(() => {+ if (selectedKey === null) return 0;+ const i = orderedItems.findIndex((it) => mentionItemKey(it) === selectedKey);+ return i === -1 ? 0 : i;+ }, [orderedItems, selectedKey]);useEffect(() => {itemRefs.current[selectedIndex]?.scrollIntoView({ block: "nearest" });}, [selectedIndex]);const selectItem = useCallback(- (index: number) => {- const item = displayItems[index];+ (item: MentionItem | undefined) => {if (!item) return;const wsId = getCurrentWsId();if (wsId) recordMentionUsage(wsId, item);command(item);},- [displayItems, command],+ [command],);useImperativeHandle(ref, () => ({@@ -257,27 +277,27 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(// those keys belong to the IME (Enter commits composition, etc).if (isImeComposing(event)) return false;if (event.key === "ArrowUp") {- if (displayItems.length === 0) return true;- setSelectedIndex(- (i) => (i + displayItems.length - 1) % displayItems.length,- );+ if (orderedItems.length === 0) return true;+ const next = (selectedIndex + orderedItems.length - 1) % orderedItems.length;+ setSelectedKey(mentionItemKey(orderedItems[next]!));return true;}if (event.key === "ArrowDown") {- if (displayItems.length === 0) return true;- setSelectedIndex((i) => (i + 1) % displayItems.length);+ if (orderedItems.length === 0) return true;+ const next = (selectedIndex + 1) % orderedItems.length;+ setSelectedKey(mentionItemKey(orderedItems[next]!));return true;}if (event.key === "Enter") {- if (displayItems.length === 0) return true;- selectItem(selectedIndex);+ if (orderedItems.length === 0) return true;+ selectItem(orderedItems[selectedIndex]);return true;}return false;},}));- if (displayItems.length === 0) {+ if (orderedItems.length === 0) {const isWaitingForServer =normalizedQuery !== "" &&(isSearching || searchedQuery !== normalizedQuery);@@ -291,8 +311,7 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>();}- const groups = groupItems(displayItems);- const hasContextGroups = displayItems.some((item) => item.group === "current" || item.group === "recent");+ const hasContextGroups = orderedItems.some((item) => item.group === "current" || item.group === "recent");const contextLayout = hasContextGroups;const groupLabel = (label: string): string => {if (label === "Current") return t(($) => $.mention.group_current);@@ -314,7 +333,7 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(key={`${item.type}-${item.id}`}item={item}selected={idx === selectedIndex}- onSelect={() => selectItem(idx)}+ onSelect={() => selectItem(item)}buttonRef={(el) => { itemRefs.current[idx] = el; }}/>);