Skip to content

Commit cae3922

Browse files
matt2eclaude
andauthored
fix(mentions): keep @mentions tagged when punctuation or quotes follow the name (#2713)
## Summary Typing `@SomeAgent's`, `@SomeAgent"` or `@SomeAgent,` sent the message without a `p` tag, so the agent was never woken and nothing warned the user. Two independent composer causes were responsible; both are fixed here. 1. **Only Space selected a fully typed name.** Every other key, including closing punctuation, was typed into the search text. `SomeAgent,` matched no one, so nothing was tagged. 2. **Quotes weren't in the boundary allowlist.** After a mention was picked from the list, `mentionBoundary` accepted `, . ! ? : ; )` as the character following a name but not `'` `’` `"` `”`, so a quote right after a chip turned it back into plain text and dropped the recipient. Nothing on the relay or Rust side reads `@names` from text; agents wake only on `p` tags, so both fixes are in the frontend composer. ## Changes - **Where a name ends** (`mention-draft.ts`): a mention now ends at the first character that isn't a letter, combining mark, digit or `_`, matching how the timeline renders mentions. The check runs on every edit, so it also covers macOS smart-quote substitution. `codePointAt` avoids treating half a surrogate pair as a boundary. - **Closing punctuation selects** (`ComposerCompletions.tsx`, `MentionCompletion.tsx`, `MessageComposer.tsx`, `EditableInput.tsx`, `composer-dom.ts`): `, . ! ? ; : )` and `' ’ " ”` typed straight after an exact, unique name select it the way Space does, and the character stays after the mention (`@Name,` rather than `@Name ,`). They also hold a pending mention while names are still loading. - **Same guards as Space:** a longer known name that continues the query (`Pat O` while `Pat O'Brien` is known; `Wes` while `Wes Smith` is known) blocks every one of these keys; team and evidence rules that block Space block them too; Ctrl/Cmd stay shortcuts; the typed key stays literal inside code spans. Option/Alt is allowed only for mentions so Mac curly quotes work, and emoji completion is unchanged from `main`. - **Docs:** mentions README §5 now says closing punctuation SHOULD select under the same rule as Space (no contract version bump; §5 changes haven't bumped it before, and no fixture covers which key commits). Pointer sentences in `docs/agents.md`, `docs/plugin-architecture.md` and `docs/buzz-help.md`. ## Before / after Left: `main` (`fe3dd19`). Right: this branch. The same keystrokes go to both panes in lockstep. Each pane shows a chip badge under the composer and a log of sent events with their `p`-tag count (green = agent tagged, red = not tagged). On `main` the agent is tagged in 1 of 6 sends (only the Space control); with the fix, 6 of 6. https://github.com/user-attachments/assets/aa5b9043-d489-45bd-a9ab-389b13d2b894 | Step | Keys | `main` | this branch | |---|---|---|---| | Control | `@Other Honey`, Space, `please look` | tagged | tagged | | Typed `'s` | `@Other Honey's turn` | **not tagged** | tagged | | Typed `’s` | `@Other Honey` + Option+Shift+`]`, `s turn` | **not tagged** | tagged | | Typed `,` | `@Other Honey, please look` | **not tagged** | tagged | | Typed `"` | `@Other Honey" said hi` | **not tagged** | tagged | | Picked, then `'` | click the row, Backspace, `'s turn` | **not tagged** | tagged | Recorded in headless Chromium against `tests/fixtures/mentions.html?identity-names`; the native app, WebKit and IME were not recorded. ## Test plan - [x] New regression tests for both causes (fail with the fix reverted): `mention-draft.test.ts`, `EditableInput.test.tsx`, `MessageComposer.test.tsx`, `src/bundled/mentions` - [x] Longer-name guard (`Pat O` / `Pat O'Brien`, `Wes` / `Wes Smith`), loading-race case where `'` holds a pending mention and the directory later reports `Pat O'Brien` - [x] Option+`:` after an emoji shortcode no longer converts (matches `main`) - [x] macOS smart-quote substitution after a picked chip keeps the recipient - [x] 1,336 tests across the composer, mention and conversation suites; `tsc --noEmit` and Biome clean - [x] Browser repro against the real composer passes on this branch ## Known gaps (unchanged) - A quote before the `@` (`"@Name`) still doesn't open the mention list; that's part of the portable mention contract (README §2 / `query` fixtures) and needs sign-off. - `@Wes,` still doesn't select while `Wes Smith` is known, the same as Space. - Keys that arrive without a normal keydown (dead-key layouts such as US-International, IME, the character viewer) don't select a typed name. A picked chip keeps its tag in all of these cases. - With smart quotes on, the selecting apostrophe is inserted straight (`'`) rather than curly; both are treated the same. - The composer counts combining marks as part of a name; the timeline doesn't. Follow-up: have `profileMentionParts` call `mentionBoundary`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: mtoohey <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent bb98864 commit cae3922

15 files changed

Lines changed: 411 additions & 82 deletions

‎docs/agents.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -814,8 +814,9 @@ The host retains recipient intent, inline editing and avatar removal even if the
814814
chooser is unavailable because activation failed.
815815
The picker shows keys alongside names (namesakes remain separate), reads optional
816816
profiles only on demand, and keeps selected identity spans in scoped drafts.
817-
Typing a name alone does not notify anyone. Plain Space after a unique exact name
818-
selects its recipient; ambiguous names require Tab, Enter or click. While the
817+
Typing a name alone does not notify anyone. Plain Space or closing punctuation
818+
after a unique exact name selects its recipient; ambiguous names require Tab,
819+
Enter or click. While the
819820
chooser is still waiting on members, names, agents or a directory search, Space
820821
holds the name as a pending chip (a spinner in place of its `@`) and applies the
821822
same rule once the evidence arrives, within 8 s, or returns it to prose; sending
@@ -910,8 +911,11 @@ recipients among the destination's members plus the draft recipients.
910911

911912
Plain Space selects only a unique exact name/alias/label across the full uncapped
912913
candidate set, and only if that identity is displayed and still eligible. A known
913-
longer name beginning with that name plus a space prevents selection, unless it is
914-
another name of that same identity. Partial names, ambiguous names, modified Space,
914+
longer name that continues the query, with any separator, prevents selection,
915+
unless it is another name of that same identity. Closing punctuation (`, . ! ? ; : )`
916+
and `' ’ " ”`) selects under the same rule and stays after the mention
917+
([mentions README §5](../src/bundled/mentions/README.md#5-space-or-closing-punctuation-selects-only-an-exact-unique-name)).
918+
Partial names, ambiguous names, modified Space,
915919
IME composition, code and protected literal ranges keep ordinary editing behavior. Selection rechecks available evidence and
916920
stores only `{pubkey, name}`; qualifiers are presentation, not wire data. A Space
917921
the chooser cannot decide yet, because its evidence is still loading, holds the

‎docs/buzz-help.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,10 @@ revokes all of them, and a pairing unused for 30 days expires.
249249
Solo chats can also be shared with other people; do not describe every Solo
250250
chat as visible only to its creator.
251251
- **Team** contains community channels and their threads. Use the **@** picker
252-
to address a channel member. Typing a name alone does not guarantee a
252+
to address a channel member. A full name typed after **@** and followed by
253+
Space or closing punctuation, such as `,`, `.` or `'`, selects that person or
254+
agent unless a namesake or a longer name that begins the same way could be
255+
meant; then pick from the list. Typing a name alone does not guarantee a
253256
notification. Selecting someone outside the channel does not grant access;
254257
inviting them requires an explicit decision from someone with permission.
255258
- **Workspaces** group Solo chats and provide starting folders and instructions.

‎docs/plugin-architecture.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2466,14 +2466,18 @@ intent survives optional plugin removal and remains subject to session validatio
24662466
One host-owned, viewport-bounded portal renders the active listbox. Focus stays on
24672467
the textarea with `aria-controls`/`aria-activedescendant`; arrows follow stable IDs,
24682468
plain Enter/forward Tab accept, and Escape dismisses pending results. A typed
2469-
terminator accepts the provider-verified unique exact match: plain Space for a
2470-
mention, the closing colon for an emoji shortcode. Emoji publishes an exact-match ID
2469+
terminator accepts the provider-verified unique exact match: plain Space or closing
2470+
punctuation for a mention
2471+
([mentions README §5](../src/bundled/mentions/README.md#5-space-or-closing-punctuation-selects-only-an-exact-unique-name)),
2472+
the closing colon for an emoji shortcode. Emoji publishes an exact-match ID
24712473
only after both Unicode and community catalogs successfully settle. The editor refuses
24722474
typed terminators in rich or raw Markdown literal ranges; colon conversion records the
24732475
typed source first so undo restores the closing colon and collapsed caret. A rejected
24742476
displayed choice must not fall through to sending. Retry is a selectable menu action
24752477
using the same arrow/Enter/Tab path, including when there are no results. Modified
2476-
keys, Shift+Enter/Shift+Tab and IME events retain ordinary editing behavior.
2478+
keys, Shift+Enter/Shift+Tab and IME events retain ordinary editing behavior, except
2479+
that Shift may type any terminator but Space, and Option a mention's closing
2480+
punctuation.
24772481

24782482
Emoji lazily copies native-only records (including aliases and keywords) from the
24792483
pinned data package; it does not use Emoji Mart's mutable global search singleton.

‎src/bundled/mentions/MentionCompletion.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { continuedMention, matchingMentions } from "./mention-ranking";
2222
import { resolveSpaceMention } from "./resolve-space-mention";
2323
import { SelectedMentionContext } from "../../features/messages/selected-mention-context";
2424
import { DraftMentionRoster } from "../../features/messages/draft-mention-roster";
25+
import { mentionTerminator } from "../../features/messages/mention-draft";
2526
import { AgentsContext } from "../../features/agents/react";
2627
import { avatarMedia } from "../../shared/avatar-source";
2728
import {
@@ -241,9 +242,10 @@ export function MentionCompletion({
241242
undefined);
242243
return {
243244
disabled,
245+
// Every key that ends a typed name selects only the exact name.
244246
canSelect: (key: string) =>
245-
(key !== " " || !teams.blocksSpace) &&
246-
model.canSelect(recipient.pubkey, key === " "),
247+
(!mentionTerminator(key) || !teams.blocksSpace) &&
248+
model.canSelect(recipient.pubkey, mentionTerminator(key)),
247249
id: recipient.pubkey,
248250
label,
249251
agent,

‎src/bundled/mentions/README.md‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@ Find and mention people, agents, and teams while you write.
1717
## Abstract
1818

1919
This contract says who a user can mention in a channel message, how a client
20-
orders the choices, when Space completes a mention, and what a client sends when
21-
the user mentions someone outside the channel. Clients that follow it give the
22-
same search the same list and send the same tags.
20+
orders the choices, when Space or closing punctuation completes a mention, and
21+
what a client sends when the user mentions someone outside the channel. Clients
22+
that follow it give the same search the same list and send the same tags.
2323

2424
The built-in Mentions feature implements the chooser: the choice set, matching,
25-
order, and Space. The composer decides which keys a draft may address and asks
26-
before sending to people outside the channel. The relay message writer and
27-
message fold implement the tags. This directory owns the spec and the
28-
[portable fixtures](mention-rules.fixtures.json).
25+
order, and selection by Space or closing punctuation. The composer decides which
26+
keys a draft may address and asks before sending to people outside the channel.
27+
The relay message writer and message fold implement the tags. This directory
28+
owns the spec and the [portable fixtures](mention-rules.fixtures.json).
2929

3030
This is an extraction of the behavior in
3131
[buzz-app #257](https://github.com/block/buzz-app/pull/257) and
@@ -197,7 +197,7 @@ and recency never override membership or match. Recency is the
197197
client's memory of explicit selections in this channel. The desktop keeps it in
198198
memory for 100 channels and 100 keys each.
199199

200-
## 5. Space selects only an exact, unique name
200+
## 5. Space or closing punctuation selects only an exact, unique name
201201

202202
When the user types Space after a query, a choice is the **exact name** among a
203203
set of choices when all of these are true:
@@ -245,6 +245,19 @@ directory result has could still gain a namesake from a pending search, so Space
245245
MUST NOT select it before the search finishes. Otherwise Space is a normal
246246
space. Tab, Enter, and a click select the highlighted row.
247247

248+
Closing punctuation typed straight after the query (`,` `.` `!` `?` `;` `:` `)`
249+
or a closing quote `'` `’` `"` `”`) SHOULD select exactly as Space does, and the
250+
client keeps the character after the mention in place of the space, so
251+
`@Honey's` mentions Honey. Where Space would not select, the character is typed
252+
into the query instead. A longer known name that continues the query blocks
253+
every one of these characters, as it blocks Space, whichever character comes
254+
next in that name: `'` after `Pat O` while `Pat O'Brien` is known stays in the
255+
query, and so does `,` after `Wes` while `Wes Smith` is known. A saved team with
256+
the same or a longer name blocks them too. Where Space may hold a pending
257+
mention, so may this character, kept after the chip. A selected or pending
258+
mention ends at a name boundary: the next character that is not a letter, mark,
259+
digit or underscore.
260+
248261
While the client cannot yet decide — the member list, member names or agent
249262
list is still loading, or a directory search for the query is waiting or
250263
running — it MAY instead mark the query as a **pending mention**: a chip with

‎src/bundled/mentions/solo-agents.test.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -804,7 +804,8 @@ it("offers a known member for Tab while agents load, then appends late agents",
804804
expect(completionLabels(publish)).toEqual(["Member"]);
805805
expect(result().items[0]?.canSelect?.("Tab")).toBe(true);
806806
expect(result().spaceId).toBeUndefined();
807-
expect(result().items[0]?.canSelect?.(" ")).toBe(false);
807+
for (const key of [" ", ",", "’"])
808+
expect(result().items[0]?.canSelect?.(key), key).toBe(false);
808809
view.rerender(<MentionCompletion {...props} />);
809810
await act(async () => release());
810811
await waitFor(() =>
@@ -3480,6 +3481,11 @@ it("saved teams resolve exact keys, block automatic Space and revoke a changed c
34803481
]),
34813482
);
34823483
expect(h.result()?.spaceId).toBeUndefined();
3484+
// The team's longer name blocks every key that ends the typed name.
3485+
const member = h.result()?.items.find((item) => item.id === h.member);
3486+
expect(member?.canSelect?.("Enter")).toBe(true);
3487+
for (const key of [" ", ",", "'", "’", ")"])
3488+
expect(member?.canSelect?.(key), key).toBe(false);
34833489
const selected = h.choice();
34843490
if (!selected) throw new Error("Team missing");
34853491
expect(selected.canSelect?.("Enter")).toBe(true);

‎src/features/conversation/ComposerCompletions.tsx‎

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import {
22
readComposerSnapshot,
33
composerMarkdownContext,
44
} from "../messages/composer-document";
5-
import type { ComposerSnapshot } from "../messages/mention-draft";
5+
import {
6+
mentionTerminator,
7+
type ComposerSnapshot,
8+
} from "../messages/mention-draft";
69
import { scanMarkdown } from "../relay/message-content";
710
import type { ComposerInputElement } from "../messages/composer-dom";
811
import { createPortal } from "react-dom";
@@ -285,9 +288,11 @@ function OwnedCompletion({
285288
const mention = provider.pluginId === "buzz.mentions";
286289
const channel = provider.pluginId === "buzz.channels";
287290
const named = mention || channel;
288-
// Typing the terminator accepts the provider-verified exact match (spaceId):
289-
// plain Space after a name, the closing colon after an emoji shortcode.
290-
const terminator = provider.pluginId === "buzz.emoji" ? ":" : " ";
291+
// Typing a terminator accepts the provider-verified exact match (spaceId):
292+
// plain Space after a name, closing punctuation after a mention too, and the
293+
// closing colon after an emoji shortcode.
294+
const terminates = (key: string) =>
295+
compact ? key === ":" : mention ? mentionTerminator(key) : key === " ";
291296
const popup = useCompletionPosition(
292297
input,
293298
compact ? 0.375 : 1,
@@ -400,7 +405,7 @@ function OwnedCompletion({
400405
// Publication is synchronous; React may still be displaying the previous
401406
// result. Keep the user's chosen ID, but use only its current evidence/edit.
402407
// The terminator names its own item, which that display may not have yet.
403-
const id = key === terminator ? published.spaceId : items[index]?.id;
408+
const id = terminates(key) ? published.spaceId : items[index]?.id;
404409
const item = published.items.find((item) => item.id === id);
405410
if (!item || item.disabled || item.canSelect?.(key) === false) return false;
406411
const accepted = current.current.replace(
@@ -437,9 +442,17 @@ function OwnedCompletion({
437442
current.current.editor.invalidate();
438443
return true;
439444
}
440-
if (event.altKey || event.ctrlKey || event.metaKey) return false;
441-
// Shift types ":" on common layouts; other shifted keys keep editing.
442-
if (event.shiftKey && event.key !== ":") return false;
445+
// Option types curly quotes and, on some Mac layouts, other closing
446+
// punctuation, so it may close a mention; elsewhere it keeps editing.
447+
if (event.ctrlKey || event.metaKey || (event.altKey && !mention))
448+
return false;
449+
// Shift types ":" and closing punctuation on common layouts; other
450+
// modified keys, Space included, keep editing.
451+
if (
452+
(event.shiftKey || event.altKey) &&
453+
(event.key === " " || !terminates(event.key))
454+
)
455+
return false;
443456
if (!active()) {
444457
// A displayed choice owns plain acceptance even when its final evidence
445458
// was revoked. Never turn a rejected edit into an unintended send.
@@ -458,12 +471,12 @@ function OwnedCompletion({
458471
// is never accepted on its own; only the publication selects.
459472
const published = latest.current;
460473
if (
461-
event.key === terminator &&
474+
terminates(event.key) &&
462475
published?.spaceId &&
463476
(!result?.spaceId || result.spaceId === published.spaceId)
464477
) {
465478
// Selected by ID, so no displayed row is needed.
466-
if (accept(-1, terminator)) {
479+
if (accept(-1, event.key)) {
467480
event.preventDefault();
468481
event.stopPropagation();
469482
return true;
@@ -476,14 +489,14 @@ function OwnedCompletion({
476489
// as undecided: no other recipient overrules what the user saw, the
477490
// decision is deferred to the resolver under the full rule.
478491
if (
479-
event.key === terminator &&
492+
terminates(event.key) &&
480493
published?.spacePending &&
481494
!published.spaceId &&
482495
current.current.replace(
483496
{ pending: published.spacePending },
484497
query,
485498
observation,
486-
terminator,
499+
event.key,
487500
)
488501
) {
489502
event.preventDefault();

‎src/features/messages/EditableInput.test.tsx‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3624,14 +3624,40 @@ it("returns a pending chip to its typed query when a name character is typed rig
36243624
expect(h.draft().recipients).toEqual([]);
36253625
act(() => h.input.undo(false));
36263626
expect(h.draft().pending?.map((item) => item.id)).toEqual([id]);
3627-
// Punctuation is a name boundary and keeps the chip, as for a recipient.
3628-
const p = mount("@mira");
3629-
act(() => {
3630-
p.input.insertPendingMention("mira", { start: 0, end: 5 });
3631-
});
3632-
await p.user.keyboard("{Backspace},");
3633-
expect(p.input).toHaveValue("@mira,");
3634-
expect(p.draft().pending).toHaveLength(1);
3627+
// Punctuation and quotes are name boundaries and keep the chip, as for a
3628+
// recipient.
3629+
for (const character of [",", "'", "’"]) {
3630+
const p = mount("@mira");
3631+
act(() => {
3632+
p.input.insertPendingMention("mira", { start: 0, end: 5 });
3633+
});
3634+
await p.user.keyboard(`{Backspace}${character}`);
3635+
expect(p.input).toHaveValue(`@mira${character}`);
3636+
expect(p.draft().pending).toHaveLength(1);
3637+
}
3638+
});
3639+
it("keeps a recipient when a quote or apostrophe follows its chip, however the character arrives", async () => {
3640+
for (const character of ["'", "’", '"', "”"]) {
3641+
const h = mount();
3642+
act(() => h.input.insertText("", miraExample));
3643+
await h.user.keyboard(`{Backspace}${character}s`);
3644+
expect(h.input).toHaveValue(`@Mira Example${character}s`);
3645+
expect(h.draft().recipients).toEqual([
3646+
{ ...miraExample, start: 0, end: 13 },
3647+
]);
3648+
}
3649+
// macOS smart quotes after a picked chip: with no chooser open, the `'`
3650+
// keystroke is typed natively, then the system substitutes `’` for it with
3651+
// no keydown of its own.
3652+
const h = mount();
3653+
act(() => h.input.insertText("", honey));
3654+
await h.user.keyboard("{Backspace}'");
3655+
expect(h.input).toHaveValue("@Honey'");
3656+
const after = h.input.querySelector("[data-source]")?.nextSibling;
3657+
if (!(after instanceof Text)) throw new Error("No text after the chip");
3658+
await act(async () => after.replaceData(0, 1, "’"));
3659+
expect(h.input).toHaveValue("@Honey’");
3660+
expect(h.draft().recipients).toEqual([{ ...honey, start: 0, end: 6 }]);
36353661
});
36363662
it("leaves a pending chip to the identity link that adopts it, without restoring its typed query", async () => {
36373663
const h = mount("[@honey", { links: true });

‎src/features/messages/EditableInput.tsx‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -747,16 +747,19 @@ export function EditableInput({
747747
text: string,
748748
recipient?: MentionRecipient | readonly MentionRecipient[],
749749
range?: { start: number; end: number },
750-
terminator?: ":",
750+
terminator?: string,
751751
focus = true,
752752
onTooLong?: () => void,
753753
) => {
754754
if (!editable() || composing.current || editor.composing) return false;
755+
// The key that ended a name follows its mention in place of the space;
756+
// only text records its terminator before converting.
757+
const after = (recipient && terminator) || " ";
758+
if (recipient) terminator = undefined;
755759
if (terminator) {
756760
const source = projection();
757761
if (
758762
!range ||
759-
recipient ||
760763
!editor.state.selection.empty ||
761764
source.source(editor.state.selection.from) !== range.end
762765
)
@@ -811,7 +814,7 @@ export function EditableInput({
811814
null,
812815
marks,
813816
),
814-
composerSchema.text(" ", marks),
817+
composerSchema.text(after, marks),
815818
]),
816819
),
817820
);
@@ -985,10 +988,12 @@ export function EditableInput({
985988
return editor.state !== before;
986989
};
987990
/** The typed `@name` becomes one atom the host resolves later: one undo
988-
* step, like a selected mention, and the caret moves past its space. */
991+
* step, like a selected mention, and the caret moves past the key that
992+
* ended it. */
989993
const insertPendingMention = (
990994
name: string,
991995
range: { start: number; end: number },
996+
terminator = " ",
992997
): string | false => {
993998
if (!editable() || composing.current || editor.composing) return false;
994999
const source = projection();
@@ -1015,7 +1020,7 @@ export function EditableInput({
10151020
null,
10161021
marks,
10171022
),
1018-
composerSchema.text(" ", marks),
1023+
composerSchema.text(terminator, marks),
10191024
]),
10201025
);
10211026
tr.setSelection(

0 commit comments

Comments
 (0)