Skip to content

Commit 44d19f5

Browse files
loganjLarry
andauthored
fix(desktop): preserve spacing after multi-word mentions (#7128)
🤖 ## Summary In Buzz Desktop, choosing a multi-word name and immediately continuing a sentence could swallow the space after the mention: `Hey @alice Chenhello`. This keeps the separator, so the same action produces `Hey @alice Chen hello` without moving the caret or repairing the name by hand. The editor recognizes the complete selected label, including its internal spaces, and settles the autocomplete caret after the trailing separator. Deliberately moving left or clicking inside the label still lets you edit there; this is not a rule that forces every caret to the end of a mention. ### Related issue Independent base: `main`. Child: [#7133](#7133), whose disambiguated labels also contain spaces. Extracted from [#7114](#7114), retained as historical source (`98fe33ec`). [Behavior contract](https://github.com/block/buzz/blob/4fe451d9c251af59c34a0a890d38499912f7e3da/docs/mention-editor.md). Originating [Buzz discussion](buzz://message?channel=f7a9536a-1738-4bad-a888-b3ea25010ef1&id=7aa1f0ab23dce514bd8a0221441cf005bf428914621171472b79747c50820848) · channel `f7a9536a-1738-4bad-a888-b3ea25010ef1`. ### Testing Select an existing member named Alice Chen, then type `hello` immediately. Repeat after ArrowLeft or clicking inside the mention: typing should follow your chosen caret position. Mock-browser captures, not live remote-agent evidence: #### Immediate typing preserves the separator Choosing the complete label then typing produces `Hey @alice Chen hello`. ![separator](https://raw.githubusercontent.com/block/buzz/7258fe2d9f276b93f4d304ac2ac47c450f104157/pr-7128--separator.png) #### Deliberate caret movement is respected After ArrowLeft, typing edits at the chosen caret rather than forcing the caret back beyond the separator. ![intentional-caret](https://raw.githubusercontent.com/block/buzz/7258fe2d9f276b93f4d304ac2ac47c450f104157/pr-7128--intentional-caret.png) [Original screenshot publication](#7128 (comment)); immutable image URLs and captions retained here. #### Evidence and limitations **5,801 desktop tests**, **45 focused editor tests**, both new browser regressions, the browser-test build and static/type/size checks passed. [Applicable CI passed](https://github.com/block/buzz/actions/runs/33421534320). The broader browser run had **132 passes / 6 failures**: two clipboard-origin setup failures and four generic caret-formatting failures also reproduced on unchanged main. Full local `just ci` stopped at three native timing/probe failures; a same-head native rerun passed **3,005 tests** with 18 existing ignores. This is not a full local-CI pass. The change fixes insertion and caret behavior, not duplicate-name recipient selection, discovery or invitation. Signed-off-by: Logan Johnson <[email protected]> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
1 parent c328202 commit 44d19f5

6 files changed

Lines changed: 199 additions & 11 deletions

File tree

‎AGENTS.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -733,3 +733,10 @@ usage.
733733
- [ARCHITECTURE.md](ARCHITECTURE.md) — system design and component relationships
734734
- [RELEASING.md](RELEASING.md) — release process: `release-desktop`, `release-relay`, `scripts/mobile-release.sh`, candidate tags, internal builds
735735
- [README.md](README.md) — project overview and quick start
736+
737+
### Mention editor contract
738+
739+
Autocomplete inserts a literal full label and a separator, including multi-word
740+
names. Only autocomplete settlement may move the caret past that separator;
741+
internal label spaces and deliberate ArrowLeft/click movement must be respected.
742+
See `docs/mention-editor.md` and `desktop/tests/e2e/mention-spacing.spec.ts`.

‎desktop/playwright.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ export default defineConfig({
7777
"**/composer-selection-formatting.spec.ts",
7878
"**/composer-tooltip-dismiss.spec.ts",
7979
"**/mentions.spec.ts",
80+
"**/mention-spacing.spec.ts",
8081
"**/team-mentions.spec.ts",
8182
"**/persistent-agent-audience.spec.ts",
8283
"**/relay-reconnect.spec.ts",

‎desktop/src/features/messages/lib/mentionHighlightExtension.test.mjs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
positionAfterArrowLeftThroughMentionSpace,
1818
selectionAfterMentionTrailingSpace,
1919
shouldAdvanceMentionCaret,
20+
settleAutocompleteMentionInsert,
2021
} from "./mentionHighlightExtension.ts";
2122

2223
// ── buildHighlightPatterns ────────────────────────────────────────────
@@ -505,3 +506,60 @@ test("a whitespace-run rewrite after a mention pick keeps the draft space", () =
505506
assert.equal(typed.doc.textContent, "hello @bob a world", shape.name);
506507
}
507508
});
509+
510+
// Multi-word display names must use the same settlement as single-word names.
511+
// Simulate the browser remapping the DOM caret to the chip edge before typing.
512+
test("multi-word autocomplete keeps its separator after a chip-edge remap", () => {
513+
const storage = { names: ["Remote Scout"], agentNames: [], channelNames: [] };
514+
const plugins = MentionHighlightExtension.config.addProseMirrorPlugins.call({
515+
storage,
516+
});
517+
const state = EditorState.create({
518+
doc: document(paragraph(text("@Remote"))),
519+
schema,
520+
plugins,
521+
});
522+
const tr = state.tr.insertText("@Remote Scout ", 1, 8);
523+
tr.setSelection(TextSelection.create(tr.doc, 15));
524+
settleAutocompleteMentionInsert(
525+
{ storage: { mentionHighlight: storage } },
526+
tr,
527+
"@Remote Scout ",
528+
);
529+
const picked = state.apply(tr);
530+
const spacePos = 1 + "@Remote Scout".length;
531+
const typed = textInput(picked, spacePos, spacePos, "hello");
532+
assert.equal(typed.doc.textContent, "@Remote Scout hello");
533+
});
534+
535+
test("full-name boundaries preserve internal spaces and intentional caret moves", () => {
536+
const names = ["Remote Scout", "Scout (ed12)"];
537+
const doc = document(paragraph(text("@Remote Scout world")));
538+
const edge = 1 + "@Remote Scout".length;
539+
assert.equal(
540+
selectionAfterMentionTrailingSpace(doc, 1 + "@Remote".length, names),
541+
1 + "@Remote".length,
542+
);
543+
assert.equal(selectionAfterMentionTrailingSpace(doc, edge, names), edge + 1);
544+
assert.equal(
545+
positionAfterArrowLeftThroughMentionSpace(doc, edge + 1, names),
546+
edge,
547+
);
548+
assert.equal(
549+
mentionTextInputInsertion(doc, edge, edge, "x", false, names),
550+
null,
551+
);
552+
assert.deepEqual(
553+
insertionForMentionTextInput(doc, edge, edge + 2, "\u00a0x", names),
554+
{ insertAt: edge + 1, text: "x" },
555+
);
556+
const disambiguated = document(paragraph(text("@Scout (ed12) ")));
557+
assert.equal(
558+
selectionAfterMentionTrailingSpace(
559+
disambiguated,
560+
1 + "@Scout (ed12)".length,
561+
names,
562+
),
563+
1 + "@Scout (ed12) ".length,
564+
);
565+
});

‎desktop/src/features/messages/lib/mentionHighlightExtension.ts‎

Lines changed: 81 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,14 @@ const OUTER_SPACES = /^[ \u00A0]+|[ \u00A0]+$/g;
7777
function mentionTrailingSpaceBoundary(
7878
doc: ProseMirrorNode,
7979
pos: number,
80+
names: readonly string[] = [],
8081
): number | null {
81-
const afterSpace = selectionAfterMentionTrailingSpace(doc, pos);
82+
const afterSpace = selectionAfterMentionTrailingSpace(doc, pos, names);
8283
if (afterSpace !== pos) return afterSpace;
83-
if (pos > 0 && selectionAfterMentionTrailingSpace(doc, pos - 1) === pos) {
84+
if (
85+
pos > 0 &&
86+
selectionAfterMentionTrailingSpace(doc, pos - 1, names) === pos
87+
) {
8488
return pos;
8589
}
8690
return null;
@@ -114,12 +118,13 @@ export function insertionForMentionTextInput(
114118
from: number,
115119
to: number,
116120
text: string,
121+
names: readonly string[] = [],
117122
): MentionTextInsertion | null {
118123
if (from === to) {
119-
const next = selectionAfterMentionTrailingSpace(doc, from);
124+
const next = selectionAfterMentionTrailingSpace(doc, from, names);
120125
return next === from ? null : { insertAt: next, text };
121126
}
122-
const boundary = mentionTrailingSpaceBoundary(doc, from);
127+
const boundary = mentionTrailingSpaceBoundary(doc, from, names);
123128
if (boundary === null) return null;
124129
if (!SPACE_RUN.test(doc.textBetween(from, to, "\n", "\0"))) return null;
125130
return { insertAt: boundary, text: text.replace(OUTER_SPACES, "") };
@@ -136,19 +141,21 @@ export function mentionTextInputInsertion(
136141
to: number,
137142
text: string,
138143
settling: boolean,
144+
names: readonly string[] = [],
139145
): MentionTextInsertion | null {
140146
if (!settling) return null;
141-
return insertionForMentionTextInput(doc, from, to, text);
147+
return insertionForMentionTextInput(doc, from, to, text, names);
142148
}
143149

144150
/** Caret just after a mention trailing space: ArrowLeft lands on the token end. */
145151
export function positionAfterArrowLeftThroughMentionSpace(
146152
doc: ProseMirrorNode,
147153
from: number,
154+
names: readonly string[] = [],
148155
): number | null {
149156
if (from <= 0) return null;
150157
const chipEnd = from - 1;
151-
if (selectionAfterMentionTrailingSpace(doc, chipEnd) === from) {
158+
if (selectionAfterMentionTrailingSpace(doc, chipEnd, names) === from) {
152159
return chipEnd;
153160
}
154161
return null;
@@ -252,7 +259,8 @@ export function settleAutocompleteMentionInsert(
252259
settleCaret = true,
253260
): void {
254261
const storage = mentionHighlightStorage(editor);
255-
const mentionInsert = /(?:^|[\s(])([@#])([^\s]+) $/.exec(text);
262+
// Autocomplete provides a literal label, including spaces and disambiguators.
263+
const mentionInsert = /(?:^|[\s(])([@#])([^@#\r\n]+) $/.exec(text);
256264
if (!mentionInsert) return;
257265
const prefix = mentionInsert[1];
258266
const label = mentionInsert[2];
@@ -319,6 +327,11 @@ export const MentionHighlightExtension = Extension.create({
319327
addProseMirrorPlugins() {
320328
const extension = this;
321329
const settlement = createMentionCaretSettlement();
330+
const knownNames = () => [
331+
...extension.storage.names,
332+
...extension.storage.agentNames,
333+
...extension.storage.channelNames,
334+
];
322335

323336
return [
324337
new Plugin({
@@ -339,7 +352,11 @@ export const MentionHighlightExtension = Extension.create({
339352
(tr.docChanged || settlement.peek() !== null)
340353
) {
341354
settlement.arm(
342-
selectionAfterMentionTrailingSpace(tr.doc, tr.selection.from),
355+
selectionAfterMentionTrailingSpace(
356+
tr.doc,
357+
tr.selection.from,
358+
knownNames(),
359+
),
343360
);
344361
}
345362

@@ -391,7 +408,11 @@ export const MentionHighlightExtension = Extension.create({
391408
return null;
392409
}
393410
const from = newState.selection.from;
394-
const next = selectionAfterMentionTrailingSpace(newState.doc, from);
411+
const next = selectionAfterMentionTrailingSpace(
412+
newState.doc,
413+
from,
414+
knownNames(),
415+
);
395416
if (
396417
!shouldAdvanceMentionCaret({
397418
from,
@@ -418,6 +439,7 @@ export const MentionHighlightExtension = Extension.create({
418439
const next = selectionAfterMentionTrailingSpace(
419440
view.state.doc,
420441
from,
442+
knownNames(),
421443
);
422444
if (next !== from) {
423445
applying = true;
@@ -454,6 +476,7 @@ export const MentionHighlightExtension = Extension.create({
454476
to,
455477
text,
456478
settlement.peek() !== null,
479+
knownNames(),
457480
);
458481
if (insertion == null) {
459482
settlement.cancel();
@@ -488,6 +511,7 @@ export const MentionHighlightExtension = Extension.create({
488511
const chipEnd = positionAfterArrowLeftThroughMentionSpace(
489512
view.state.doc,
490513
view.state.selection.from,
514+
knownNames(),
491515
);
492516
if (chipEnd == null) return false;
493517
view.dispatch(
@@ -508,6 +532,7 @@ export const MentionHighlightExtension = Extension.create({
508532
const chipEnd = positionAfterArrowLeftThroughMentionSpace(
509533
view.state.doc,
510534
pos,
535+
knownNames(),
511536
);
512537
if (chipEnd == null) return false;
513538
view.dispatch(
@@ -577,13 +602,58 @@ export function buildHighlightPatterns(
577602
export function selectionAfterMentionTrailingSpace(
578603
doc: ProseMirrorNode,
579604
pos: number,
605+
names: readonly string[] = [],
580606
): number {
581607
if (pos < 0 || pos >= doc.content.size) return pos;
582608
const nextChar = doc.textBetween(pos, pos + 1, "\n", "\0");
583609
if (nextChar !== " ") return pos;
584-
const lookbehind = Math.min(pos, 80);
610+
// Use registered full labels as well as the legacy single-token fallback.
611+
// A multi-word name's internal spaces are not trailing separators.
612+
const lookbehind = Math.min(
613+
pos,
614+
names.reduce((max, name) => Math.max(max, name.length + 2), 80),
615+
);
585616
const before = doc.textBetween(pos - lookbehind, pos, "\n", "\0");
586-
if (!/(?:^|[\s(])[@#][^\s]+$/.test(before)) return pos;
617+
const lower = before.toLowerCase();
618+
// Don't treat the space inside a registered multi-word label as the end of
619+
// a single-word token, even when the browser maps the caret there.
620+
const internalSpace = names.some((name) => {
621+
const token = name.toLowerCase();
622+
for (
623+
let space = token.indexOf(" ");
624+
space >= 0;
625+
space = token.indexOf(" ", space + 1)
626+
) {
627+
const start = before.length - space - 1;
628+
if (start < 0 || (start > 0 && !/[\s(]/.test(before[start - 1])))
629+
continue;
630+
if (before[start] !== "@" && before[start] !== "#") continue;
631+
if (lower.slice(start + 1) !== token.slice(0, space)) continue;
632+
if (
633+
doc
634+
.textBetween(
635+
pos,
636+
Math.min(doc.content.size, pos + name.length - space),
637+
"\n",
638+
"\0",
639+
)
640+
.toLowerCase() === token.slice(space)
641+
)
642+
return true;
643+
}
644+
return false;
645+
});
646+
if (internalSpace) return pos;
647+
const knownBoundary = names.some((name) => {
648+
const start = before.length - name.length - 1;
649+
return (
650+
start >= 0 &&
651+
(start === 0 || /[\s(]/.test(before[start - 1])) &&
652+
(before[start] === "@" || before[start] === "#") &&
653+
lower.slice(start + 1) === name.toLowerCase()
654+
);
655+
});
656+
if (!knownBoundary && !/(?:^|[\s(])[@#][^\s]+$/.test(before)) return pos;
587657
return pos + 1;
588658
}
589659

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { expect, test } from "@playwright/test";
2+
import { waitForAnimations } from "../helpers/animations";
3+
import { installMockBridge, TEST_IDENTITIES } from "../helpers/bridge";
4+
5+
// An ordinary existing channel member: no discovery, invitation or runtime needed.
6+
test.beforeEach(async ({ page }) => {
7+
await installMockBridge(page, {
8+
searchProfiles: [
9+
{ pubkey: TEST_IDENTITIES.alice.pubkey, displayName: "Alice Chen" },
10+
],
11+
});
12+
await page.goto("/");
13+
await page.getByTestId("channel-general").click();
14+
await expect(page.getByTestId("chat-title")).toHaveText("general");
15+
});
16+
17+
for (const deliberateMove of [false, true]) {
18+
test(`multi-word mention ${deliberateMove ? "respects intentional ArrowLeft" : "preserves separator when typing immediately"}`, async ({
19+
page,
20+
}) => {
21+
const input = page.getByTestId("message-input");
22+
await input.fill("Hey @Ali");
23+
await page
24+
.getByTestId("message-composer")
25+
.getByTestId("mention-autocomplete")
26+
.getByText("Alice Chen", { exact: true })
27+
.click();
28+
if (deliberateMove) await page.keyboard.press("ArrowLeft");
29+
await page.keyboard.type("hello");
30+
expect((await input.innerText()).trimEnd()).toBe(
31+
deliberateMove ? "Hey @Alice Chenhello" : "Hey @Alice Chen hello",
32+
);
33+
await waitForAnimations(page);
34+
await page.getByTestId("message-composer").screenshot({
35+
path: `test-results/mention-spacing/${deliberateMove ? "intentional-caret" : "separator"}.png`,
36+
});
37+
});
38+
}

‎docs/mention-editor.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Mention editor contract
2+
3+
Autocomplete inserts a full literal label followed by a separator. Full labels
4+
may contain spaces; internal spaces must not be mistaken for the final boundary.
5+
The immediate next typed character goes after the separator even if the browser
6+
remaps the DOM caret to the highlight edge. Explicit ArrowLeft or click cancels
7+
that settlement so users can intentionally edit a mention. Plain typed tokens
8+
retain their existing behavior; this does not change recipient resolution.
9+
10+
Regression coverage: `mentionHighlightExtension.test.mjs` simulates chip-edge and
11+
whitespace-run rewrites, internal spaces, and deliberate motion. The ordinary
12+
member browser cases in `mention-spacing.spec.ts` test immediate typing and
13+
ArrowLeft without requiring remote discovery or invitation; `mentions.spec.ts`
14+
also covers clicking chip edges and insertion before existing text.

0 commit comments

Comments
 (0)