Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7456 fix(editor): open the mention picker at any token boundary, not only after a half-width space (#8502)
HenrySu-sudo39ad969b0b14
diff --git a/apps/mobile/lib/mention-serialize.test.ts b/apps/mobile/lib/mention-serialize.test.tsnew file mode 100644index 0000000000..1e272019cd--- /dev/null+++ b/apps/mobile/lib/mention-serialize.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { tokenAtCursor } from "./mention-serialize";++// The mobile half of the shared boundary rule. The rule's own matrix lives in+// packages/core/markdown/mention-boundary.test.ts; this covers the wiring — that+// `tokenAtCursor` consults it, and that the sentinel guard still wins.++/** Cursor sits at the end of `text`. */+function at(text: string) {+ return tokenAtCursor(text, text.length);+}++describe("tokenAtCursor boundary", () => {+ it.each([+ ["an empty box", "@Mi"],+ ["after a half-width space", "hello @Mi"],+ ["a full-width space", "你好 @Mi"],+ ["after CJK with no separator", "你好@Mi"],+ ["after katakana", "テレビ@Mi"],+ ["after the prolonged sound mark", "コーヒー@Mi"],+ ["after punctuation", "hello(@Mi"],+ ])("opens %s", (_name, text) => {+ expect(at(text)).toEqual({ start: text.indexOf("@"), query: "Mi" });+ });++ it.each([+ ["an ASCII word", "hello@Mi"],+ ["a digit", "2024@Mi"],+ ["an address", "[email protected]"],+ ["an accented address", "josé@example.com"],+ ["a cyrillic address", "почта@mail.ru"],+ ["a greek address", "αλφα@example.com"],+ ])("stays shut inside %s", (_name, text) => {+ expect(at(text)).toBeNull();+ });++ it("stays shut over a completed mention", () => {+ // The bar inserts `@Name `; a cursor inside the inserted text, or at the+ // space after it, must not re-open the bar.+ expect(tokenAtCursor("@Mika", 6)).toBeNull();+ expect(tokenAtCursor("@Mika", 4)).toBeNull();+ expect(tokenAtCursor("@Mika ", 7)).toBeNull();+ });++ it("still returns the query when the cursor is mid-token", () => {+ expect(tokenAtCursor("你好@Mi", 5)).toEqual({ start: 2, query: "Mi" });+ });+});diff --git a/apps/mobile/lib/mention-serialize.ts b/apps/mobile/lib/mention-serialize.tsindex 1ea0ae6e73..2f844bb639 100644--- a/apps/mobile/lib/mention-serialize.ts+++ b/apps/mobile/lib/mention-serialize.ts@@ -18,6 +18,8 @@* lose user input, never claim a mention we can't prove.*/+import { isMentionBoundaryAfter } from "@multica/core/markdown";+const SENTINEL = "";export type MentionType = "member" | "agent" | "squad" | "all" | "issue";@@ -38,8 +40,10 @@ export interface MentionMarker {* Returns the start offset of the `@` and the query (text between `@` and* the cursor), or null when not in a mention token.*- * Word boundary uses `/\s/` so non-ASCII names (中文 / 日本語) work — the- * token ends at whitespace, not at ASCII word boundary.+ * The token ends at whitespace, not at an ASCII word boundary, so non-ASCII+ * names (中文 / 日本語) work. Whether the `@` itself starts a token is decided+ * by the rule shared with the web/desktop editor — see+ * `isMentionBoundaryAfter` in packages/core/markdown.** Skips runs that begin with the sentinel — those are completed mentions* inserted by the bar, not in-progress queries.@@ -63,12 +67,12 @@ export function tokenAtCursor(// Skip if the @ is preceded by the sentinel (= a completed mention chip).if (i > 0 && text[i - 1] === SENTINEL) return null;- // The character before @ must be whitespace or start-of-string. This- // prevents random in-word @ (e.g. "[email protected]") from triggering.- if (i > 0) {- const prev = text[i - 1];- if (prev !== undefined && !/\s/.test(prev)) return null;- }+ // The @ must start a token rather than continue the word before it. The rule+ // is shared with the web/desktop editor (packages/core/markdown), so both+ // clients offer the picker over the same text: an in-word @ such as+ // "[email protected]" stays inert, while CJK — written without a separator —+ // opens it.+ if (i > 0 && !isMentionBoundaryAfter(text.slice(Math.max(0, i - 2), i))) return null;const query = text.slice(i + 1, cursor);// If the query already contains whitespace, the user has moved past thediff --git a/apps/mobile/lib/use-mention-input.ts b/apps/mobile/lib/use-mention-input.tsindex 091ee1fb4f..ebf4169bed 100644--- a/apps/mobile/lib/use-mention-input.ts+++ b/apps/mobile/lib/use-mention-input.ts@@ -28,6 +28,7 @@ import {tokenAtCursor,type MentionMarker,} from "@/lib/mention-serialize";+import { isMentionBoundaryAfter } from "@multica/core/markdown";export interface MentioningState {start: number;@@ -139,10 +140,10 @@ export function useMentionInput(): UseMentionInputReturn {const s = selectionRef.current;const before = t.slice(0, s.start);const after = t.slice(s.end);- // Mention tokens require a word boundary before `@`. If the prior char- // isn't whitespace (or start-of-text), pad with a space — otherwise the- // suggestion bar won't trigger.- const needsPad = before.length > 0 && !/\s$/.test(before);+ // A mention token needs a token boundary before `@`. Pad with a space when+ // the character before the caret is one the `@` would glue onto; CJK text+ // needs no pad, because there the `@` already starts a token.+ const needsPad = !isMentionBoundaryAfter(before.slice(-2));const inserted = (needsPad ? " " : "") + "@";const next = before + inserted + after;const cursor = before.length + inserted.length;diff --git a/packages/core/markdown/index.ts b/packages/core/markdown/index.tsindex c33ceefbeb..c24cb09163 100644--- a/packages/core/markdown/index.ts+++ b/packages/core/markdown/index.ts@@ -1 +1,2 @@export { preprocessMentionShortcodes } from "./mention-shortcodes";+export { isMentionBoundaryAfter } from "./mention-boundary";diff --git a/packages/core/markdown/mention-boundary.test.ts b/packages/core/markdown/mention-boundary.test.tsnew file mode 100644index 0000000000..72c1612dae--- /dev/null+++ b/packages/core/markdown/mention-boundary.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "vitest";+import { isMentionBoundaryAfter } from "./mention-boundary";++// The character-level matrix for the shared mention boundary rule. The wiring —+// that the editor and the mobile composer actually consult it — is covered+// where each of them lives (mention-boundary.test.ts under packages/views and+// mention-serialize.test.ts under apps/mobile).++/** The `@` is placed directly after this text, so its last code point decides. */+const OPENS: Array<[string, string]> = [+ ["nothing at all", ""],+ ["a half-width space", "hello "],+ // A Chinese IME inserts U+3000 for the space key.+ ["a full-width space", "你好 "],+ ["a tab", "hello\t"],+ ["a newline", "hello\n"],+ ["punctuation", "hello("],+ ["a CJK word with no separator", "你好"],+ ["a hiragana word", "こんにちは"],+ ["a katakana word", "テレビ"],+ // U+30FC carries Katakana only as a Script_Extensions value, so it needs the+ // explicit listing in SPACELESS_SCRIPT to count as part of the word.+ ["a katakana word ending in the prolonged sound mark", "コーヒー"],+ ["half-width katakana", "コーヒー"],+ ["a hangul word", "안녕하세요"],+ ["a thai word", "สวัสดี"],+ ["a lao word", "ສະບາຍດີ"],+ ["a khmer word", "ជំរាបសួរ"],+ ["a myanmar word", "မင်္ဂလာပါ"],+ ["a tibetan word", "བཀྲ་ཤིས"],+ ["an emoji", "🎉"],+];++const SHUT: Array<[string, string]> = [+ ["an ASCII word", "hello"],+ ["an ASCII capital", "Hello"],+ ["a digit", "2024"],+ ["an underscore", "snake_case"],+ ["an accented latin word", "café"],+ ["a spanish word", "josé"],+ ["a cyrillic word", "почта"],+ ["a greek word", "αλφα"],+ ["a vietnamese word", "chà"],+ ["a dotted domain", "[email protected]"],+ ["a full ASCII address", "[email protected]"],+];++describe("isMentionBoundaryAfter", () => {+ it.each(OPENS)("opens after %s", (_name, before) => {+ expect(isMentionBoundaryAfter(before)).toBe(true);+ });++ it.each(SHUT)("stays shut after %s", (_name, before) => {+ expect(isMentionBoundaryAfter(before)).toBe(false);+ });++ it("reads only the last code point", () => {+ // The caller may hand over a two-unit tail; earlier characters are noise.+ expect(isMentionBoundaryAfter("café")).toBe(false);+ expect(isMentionBoundaryAfter("é")).toBe(false);+ });++ it("reads a code point outside the BMP whole", () => {+ // Deseret is a letter and not a spaceless script, so it stays shut — but+ // only if the two units arrive together. Read one unit at a time the+ // implementation would see a lone surrogate, fail both tests, and open.+ const astral = "𐐀";+ expect(astral.length).toBe(2);+ expect(isMentionBoundaryAfter(astral)).toBe(false);+ });+});diff --git a/packages/core/markdown/mention-boundary.ts b/packages/core/markdown/mention-boundary.tsnew file mode 100644index 0000000000..3794b0bfdd--- /dev/null+++ b/packages/core/markdown/mention-boundary.ts@@ -0,0 +1,66 @@+/**+ * Where an `@` starts a mention token rather than continuing the word before it.+ *+ * Single source of truth for both composers: the web/desktop editor+ * (packages/views/editor/extensions/mention-suggestion.tsx) and the mobile+ * comment composer (apps/mobile/lib/mention-serialize.ts). They have to agree —+ * the same text must offer the picker on every client.+ *+ * Tiptap's own rule is `allowedPrefixes`, defaulting to `[" "]`: a half-width+ * space and nothing else. That makes a mention unreachable in the two ways CJK+ * text is actually typed — with no separator at all, and after the full-width+ * space (U+3000) an IME inserts. The rule it means to protect is narrower than+ * "not a space": an `@` glued to the end of a word, as in `[email protected]`.+ * So the question is whether the character before the `@` is part of a word.+ *+ * Two things make that question non-obvious:+ *+ * - Word characters are Unicode letters, digits, marks and `_`. An ASCII-only+ * class makes every accented, Cyrillic or Greek letter look like a+ * boundary, which re-opens the address case for `josé@example.com`,+ * `почта@mail.ru` and `αλφα@example.com`.+ * - Scripts written without spaces between words are the exception: there is+ * no separator to type, so the `好` in `你好@Mi` is where the token starts.+ *+ * Known ambiguity, accepted rather than solved: `用户@example.com` cannot be+ * told apart from a mention typed with no separator, and opens the picker. No+ * character-level rule that keeps `你好@Mi` working can distinguish the two.+ *+ * Pure — no IO, no global state.+ */++/** Unicode word characters. An `@` glued to one of these continues a word. */+const WORD_CHARACTER = /[\p{L}\p{N}\p{M}_]/u;++/**+ * Scripts that do not separate words with spaces, where a word can therefore+ * end directly against the `@`. Latin, Cyrillic, Greek and friends are absent+ * on purpose: their writers type a space before `@`, and that absence is also+ * what keeps their email addresses from opening the picker.+ *+ * Written with `Script=`, not `Script_Extensions=`, because Hermes — the JS+ * engine the mobile app runs on — rejects `\p{Script_Extensions=Thai}` (also+ * Lao, Khmer and Tibetan) as an invalid property name and fails to parse the+ * module, which would take the app down with it. The escapes trailing the+ * scripts are the code points that carry one of these scripts only as an+ * extension *and* are word characters, so a `Script=` test alone would read+ * them as word continuations: U+3099/U+309A and U+FF9E/U+FF9F voiced sound+ * marks, and U+30FC/U+FF70 prolonged sound marks — the last character of+ * `コーヒー`, which would otherwise not open the picker.+ */+const SPACELESS_SCRIPT =+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}\p{Script=Tibetan}\u3099\u309A\u30FC\uFF70\uFF9E\uFF9F]/u;++/**+ * True when an `@` typed immediately after `before` starts a token.+ *+ * `before` is the text preceding the `@`; only its last code point is read, and+ * an empty string means the `@` opens the text. Callers pass at most two code+ * units so an astral-plane code point arrives whole.+ */+export function isMentionBoundaryAfter(before: string): boolean {+ const codePoints = [...before];+ const previous = codePoints[codePoints.length - 1];+ if (previous === undefined) return true;+ return SPACELESS_SCRIPT.test(previous) || !WORD_CHARACTER.test(previous);+}diff --git a/packages/views/editor/extensions/mention-boundary.test.ts b/packages/views/editor/extensions/mention-boundary.test.tsnew file mode 100644index 0000000000..ec8572c771--- /dev/null+++ b/packages/views/editor/extensions/mention-boundary.test.ts@@ -0,0 +1,216 @@+import { describe, it, expect, beforeAll, vi } from "vitest";+import { Editor, Extension } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import { Markdown } from "@tiptap/markdown";+import { Suggestion } from "@tiptap/suggestion";+import { EditorView } from "@tiptap/pm/view";+import type { QueryClient } from "@tanstack/react-query";+import { workspaceKeys } from "@multica/core/workspace/queries";+import { createMarkdownPasteExtension } from "./markdown-paste";+import { SuggestionTriggerArmingExtension } from "./suggestion-trigger-arming";++// The mention picker's boundary rule, end to end. It is driven through the real+// pipeline — the production `createMentionSuggestion()` config on a real editor,+// with typing routed through `handleTextInput` exactly the way+// prosemirror-view's readDOMChange does it — because the rule that decides+// whether the picker opens lives inside Tiptap's `findSuggestionMatch` and+// @tiptap/suggestion's `shouldShow` call, not in anything this package owns.++vi.mock("@multica/core/platform", () => ({+ getCurrentWsId: () => "ws-1",+}));++vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => ({ iconOf: () => null, colorOf: () => null }),+}));++vi.mock("@multica/core/api", () => ({+ api: {+ searchIssues: vi.fn().mockResolvedValue({ issues: [] }),+ searchProjects: vi.fn().mockResolvedValue({ projects: [] }),+ },+}));++vi.mock("@multica/core/auth", () => ({+ useAuthStore: { getState: () => ({ user: { id: "u1" } }) },+}));++vi.mock("../../common/actor-avatar", () => ({+ ActorAvatar: () => null,+}));++import { createMentionSuggestion, type MentionItem } from "./mention-suggestion";++function fakeQc(): QueryClient {+ return {+ getQueryData: (key: unknown) => {+ if (JSON.stringify(key) === JSON.stringify(workspaceKeys.members("ws-1"))) {+ return [{ user_id: "u1", name: "Henry", role: "owner" }];+ }+ if (JSON.stringify(key) === JSON.stringify(workspaceKeys.agents("ws-1"))) {+ return [+ {+ id: "agent-1",+ name: "Mika",+ archived_at: null,+ runtime_id: "rt-1",+ runtime_bound: true,+ owner_id: null,+ permission_mode: "public_to",+ invocation_targets: [{ target_type: "workspace", target_id: null }],+ },+ ];+ }+ return undefined;+ },+ getQueriesData: () => [],+ } as unknown as QueryClient;+}++function makeEditor() {+ const element = document.createElement("div");+ document.body.appendChild(element);+ const config = createMentionSuggestion(fakeQc());+ const probe = Extension.create({+ name: "mentionBoundaryProbe",+ addProseMirrorPlugins() {+ return [Suggestion({ ...config, editor: this.editor, render: () => ({}) })];+ },+ });+ const editor = new Editor({+ element,+ extensions: [+ StarterKit,+ Markdown,+ createMarkdownPasteExtension(),+ SuggestionTriggerArmingExtension,+ probe,+ ],+ content: { type: "doc", content: [{ type: "paragraph" }] },+ });+ return { editor, config };+}++/** Types text the way ProseMirror does: through `handleTextInput`. */+function type(editor: Editor, text: string): void {+ for (const ch of text) {+ if (ch === "\n") {+ editor.view.dispatch(editor.state.tr.split(editor.state.selection.from));+ continue;+ }+ const { from, to } = editor.state.selection;+ const handled = editor.view.someProp("handleTextInput", (fn) =>+ fn(editor.view, from, to, ch, () => editor.state.tr.insertText(ch, from, to)),+ );+ if (!handled) editor.view.dispatch(editor.state.tr.insertText(ch, from, to));+ }+}++function paste(editor: Editor, text: string): void {+ const event = new Event("paste", { bubbles: false, cancelable: true });+ Object.defineProperty(event, "clipboardData", {+ value: {+ files: [],+ getData: (type: string) =>+ type === "text/plain" ? text : type === "text/html" ? "" : "",+ },+ });+ editor.view.dom.dispatchEvent(event);+}++function picker(editor: Editor, config: ReturnType<typeof createMentionSuggestion>) {+ const key = config.pluginKey;+ if (!key) throw new Error("mention suggestion config has no plugin key");+ const state = key.getState(editor.state) as+ | { active?: boolean; query?: string | null }+ | undefined;+ return { active: state?.active ?? false, query: state?.query ?? null };+}++beforeAll(() => {+ // jsdom has no layout, so ProseMirror's post-dispatch scroll walks+ // coordsAtPos into getClientRects() on nodes jsdom does not implement.+ (EditorView.prototype as unknown as { scrollToSelection: () => void }).scrollToSelection =+ () => {};+ Element.prototype.scrollIntoView = () => {};+});++describe("mention picker boundary", () => {+ describe("opens where an @ starts a token", () => {+ const cases: Array<[string, string]> = [+ ["empty comment box", "@Mi"],+ ["after a half-width space", "hello @Mi"],+ // A Chinese IME inserts U+3000 for the space key. Tiptap's default+ // allowedPrefixes ([" "]) rejected it, so the picker never opened.+ ["after a full-width space", "你好 @Mi"],+ ["after a tab", "hello\t@Mi"],+ // CJK text is written without a separator before @, so requiring a space+ // made the picker unreachable for the most common way to address someone.+ ["after CJK text with no separator", "你好@Mi"],+ ["after katakana", "テレビ@Mi"],+ // U+30FC carries Katakana only as a Script_Extensions value; the shared+ // rule lists it by hand so the word still ends here.+ ["after a prolonged sound mark", "コーヒー@Mi"],+ ["after hangul with no separator", "안녕하세요@Mi"],+ ["after thai with no separator", "สวัสดี@Mi"],+ ["after punctuation", "hello(@Mi"],+ ["on a new line", "hello\n@Mi"],+ ];++ it.each(cases)("%s", (_name, typed) => {+ const { editor, config } = makeEditor();+ editor.commands.focus("end");++ type(editor, typed);++ expect(picker(editor, config)).toEqual({ active: true, query: "Mi" });+ });++ it("lists the agent the query names", () => {+ const { editor, config } = makeEditor();+ editor.commands.focus("end");++ type(editor, "你好@Mi");++ const items = config.items!({ query: "Mi" } as never) as MentionItem[];+ expect(items.map((i) => i.label)).toContain("Mika");+ expect(picker(editor, config).active).toBe(true);+ });+ });++ describe("stays shut where an @ continues a token", () => {+ const cases: Array<[string, string]> = [+ ["after an ASCII word", "hello@Mi"],+ ["after a digit", "2024@Mi"],+ ["after an underscore", "snake_case@Mi"],+ ["inside an address", "[email protected]"],+ // Non-ASCII word characters count too. An ASCII-only class made every one+ // of these a boundary, re-opening the address case the rule exists to+ // keep shut.+ ["inside an accented address", "josé@example.com"],+ ["inside a cyrillic address", "почта@mail.ru"],+ ["inside a greek address", "αλφα@example.com"],+ ["after an accented word", "café@Mi"],+ ];++ it.each(cases)("%s", (_name, typed) => {+ const { editor, config } = makeEditor();+ editor.commands.focus("end");++ type(editor, typed);++ expect(picker(editor, config)).toEqual({ active: false, query: null });+ });++ it("over an @ the user did not type", () => {+ // MUL-5429: provenance still comes from the arming extension, so widening+ // the boundary rule does not re-open the picker over pasted text.+ const { editor, config } = makeEditor();+ editor.commands.focus("end");++ paste(editor, "npx @aiforui/install --token=abc");++ expect(picker(editor, config)).toEqual({ active: false, query: null });+ });+ });+});diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsxindex 5236a4d147..186733409f 100644--- a/packages/views/editor/extensions/mention-suggestion.tsx+++ b/packages/views/editor/extensions/mention-suggestion.tsx@@ -25,6 +25,7 @@ import {isProjectDirectHit,} from "@multica/core/search/cancelled-rank";import { isImeComposing } from "@multica/core/utils";+import { isMentionBoundaryAfter } from "@multica/core/markdown";import type {Issue,ListIssuesCache,@@ -47,6 +48,7 @@ import { cn } from "@multica/ui/lib/utils";import type { IssueStatus, IssueStatusCategory, ProjectStatus } from "@multica/core/types";import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";import type { SuggestionOptions } from "@tiptap/suggestion";+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";import { PluginKey } from "@tiptap/pm/state";import {getRecencyMap,@@ -700,6 +702,21 @@ function projectToMention(p: { id: string; title: string; description?: string |};}+/**+ * True when the `@` at `pos` starts a token instead of continuing one.+ *+ * The rule itself — which characters make an `@` part of the word it follows,+ * and why CJK needs the exception — lives in @multica/core/markdown, shared+ * with the mobile composer so the two clients cannot drift apart.+ */+function isMentionBoundary(doc: ProseMirrorNode, pos: number): boolean {+ if (pos <= 0) return true;+ // Two units wide, so a code point outside the BMP arrives whole; one would+ // hand back a lone surrogate. Across a block boundary this is the separator,+ // which is not a word character either.+ return isMentionBoundaryAfter(doc.textBetween(Math.max(0, pos - 2), pos, "\n", "\n"));+}+function matchesMentionQuery(item: MentionItem, query: string): boolean {const q = query.trim().toLowerCase();if (!q) return true;@@ -827,10 +844,15 @@ export function createMentionSuggestion(return {pluginKey,allowSpaces: true,+ // The boundary rule is isMentionBoundary's, not Tiptap's default of "a+ // half-width space and nothing else" (see the note there).+ allowedPrefixes: null,// Only open over an `@` the user actually typed. Tiptap matches on document// content alone, so without this a pasted, dropped, undone or server-loaded// `@` opens the picker just as readily (MUL-5429).- shouldShow: ({ editor, range }) => isTriggerArmedAt(editor, range.from),+ shouldShow: ({ editor, range, transaction }) =>+ isTriggerArmedAt(editor, range.from) &&+ isMentionBoundary(transaction.doc, range.from),items: ({ query }) => {if (options.mode === "context") {const normalizedQuery = query.trim();