Skip to content

Commit 8dbc65d

Browse files
tellahoCarlRizzmorgmart
authored
fix(composer): polish automatic mentions (#6956)
**Category:** improvement **User Impact:** Automatic mentions are easier to turn off and now behave consistently across conversations, settings, drafts, and repeated agent mentions. **Problem:** People found the new automatic mention behavior hard to control: turning it off in Settings did not reliably affect the composer, removing a mention could require also disabling the feature, and root/thread composers could inherit or restore surprising state. Other reported rough edges included only one of several mentioned agents becoming automatic, synthetic mentions leaking into drafts, restored mentions corrupting adjacent text, controls remaining visible in archived channels, and unclear picker feedback. See the [original feedback thread](buzz://message?channel=e62570dd-33ad-42c5-b92b-75f2689f9694&id=c949ec399274fbb0d6633da3f95712e843a67dcada214f63d72f6975b406604b). **Solution:** Polish the existing feature around the problems people encountered, keeping automatic mentions controllable and scoped to the active conversation. | Reported issue | UX fix | | --- | --- | | Turning automatic mentions off in Settings did not reliably update the composer. | The global setting and composer control stay synchronized, and disabling the feature does not clear typed text. | | Removing an automatic mention could require both deleting the mention and turning off the feature. | Removing or unchecking an agent excludes that agent for the current conversation, while explicitly re-adding the agent can restore automatic mention behavior. | | Root and thread composers could share or restore surprising selections. | Each root or thread composer keeps its own automatic audience and restores it when the user returns. A request to enable automatic mentions only in agent threads was considered; this PR keeps them available at the channel root but prevents state from leaking between the two. | | Mentioning multiple agents could leave only one saved as automatic. | Multi-agent selections remain represented in the automatic audience and restored mention chips. | | Automatic mention prefixes could be saved as if the user typed them. | Synthetic prefixes stay out of persisted drafts while authored text is preserved. | | Restored mentions could lose their separator and corrupt continued typing. | Restored multi-word mentions retain their trailing space and place the caret after it. | | Archived channels showed automatic-mention state beside a disabled composer. | Disabled composers hide automatic-mention controls while preserving the draft and restoring state when re-enabled. | | Confirmation and picker behavior made the feature feel difficult to inspect or adjust. | Confirmations dismiss with removed agents, remain open while hovered, and expose the setting before it changes; pin icons, contrast, scope copy, animation, and keyboard toggling are also clarified. | | Agent suggestions and membership state could shift during directory refreshes. | Suggestions and membership labels stay stable during refreshes, while send-time authorization still revalidates access. | ## Changes <details> <summary>File changes</summary> **desktop/src/features/agents/lib/agentAutocompleteEligibility.test.mjs** Adds coverage for the channel-roster eligibility rules used by agent mention autocomplete. **desktop/src/features/agents/lib/agentAutocompleteEligibility.ts** Aligns agent autocomplete eligibility with channel membership so available agents and their labels stay trustworthy. **desktop/src/features/channels/ui/MembersSidebar.tsx** Uses the shared member-pubkey logic when presenting and acting on channel members. **desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.test.mjs** Covers preference changes that must remain stable while composer controls are toggled. **desktop/src/features/messages/lib/autoPinMentionedAgentsPreference.ts** Keeps the automatic-mention preference as durable user intent rather than transient composer state. **desktop/src/features/messages/lib/mentionMemberPubkeys.ts** Centralizes which member identities count as mentionable in the current channel. **desktop/src/features/messages/lib/persistentAgentAudience.test.mjs** Expands lifecycle coverage for persistent agent audiences, explicit exclusions, and restored mentions. **desktop/src/features/messages/lib/persistentAgentAudience.ts** Models automatic, explicit, and excluded agent audiences separately so user choices survive updates without leaking across composers. **desktop/src/features/messages/lib/stripImplicitAgentMentions.test.mjs** Verifies implicit automatic mentions are removed without damaging surrounding separators or authored content. **desktop/src/features/messages/lib/stripImplicitAgentMentions.ts** Strips presentation-only automatic mentions before draft persistence while preserving whitespace and authored text. **desktop/src/features/messages/lib/useMentions.ts** Routes mention insertion and removal through the composer-local audience lifecycle. **desktop/src/features/messages/lib/useRichTextEditor.ts** Preserves mention-chip structure and caret placement when automatic mentions are restored. **desktop/src/features/messages/ui/ComposerAddressControls.test.mjs** Updates control-state expectations for disabled automatic mentions and restored pin affordances. **desktop/src/features/messages/ui/ComposerAddressControls.tsx** Makes automatic-mention state, disabled presentation, and pin controls visually explicit. **desktop/src/features/messages/ui/MentionAutocomplete.test.mjs** Adds coverage for roster labels, pin state, and picker behavior after mention selection. **desktop/src/features/messages/ui/MentionAutocomplete.tsx** Keeps the shortcut picker open for repeated selection and restores visible automatic-mention pin indicators. **desktop/src/features/messages/ui/MessageComposer.tsx** Scopes automatic mention state to each root or thread composer and coordinates restoration, draft persistence, and sending. **desktop/src/features/messages/ui/MessageComposerToolbar.tsx** Passes the effective automatic-mention state into the toolbar presentation. **desktop/src/features/messages/ui/composerAgentKeyboard.test.mjs** Updates keyboard interaction coverage for toggling agents in place. **desktop/src/features/messages/ui/useAddressedAgentMentionRestore.ts** Restores automatic mention chips after lifecycle changes without moving or duplicating authored content. **desktop/src/features/messages/ui/useAgentAddressLockPicker.test.mjs** Substantially expands coverage for toggles, exclusions, synchronization, and picker dismissal rules. **desktop/src/features/messages/ui/useAgentAddressLockPicker.ts** Keeps the picker usable across repeated choices and preserves explicit per-agent intent while settings change. **desktop/src/features/messages/ui/useAlwaysAddressShortcut.ts** Makes the keyboard shortcut toggle the highlighted automatic audience choice without replacing unrelated selections. **desktop/src/features/messages/ui/useAutoPinMentionedAgents.ts** Owns composer-local automatic-mention lifecycle behavior, including restoration, exclusions, deletion, and disabled-state handling. **desktop/src/features/messages/ui/useComposerMentionPicker.test.mjs** Adds focused picker lifecycle coverage for selection, hover, and dismissal behavior. **desktop/src/features/messages/ui/useComposerMentionPicker.ts** Prevents premature picker dismissal while the user is interacting with its controls. **desktop/src/features/messages/ui/useDraftPersistSnapshot.ts** Persists only user-authored draft content rather than implicit automatic mention decorations. **desktop/src/shared/lib/keyboard-shortcuts.ts** Updates the automatic-mention shortcut description to match its toggle behavior. **desktop/src/testing/e2eBridge.ts** Extends the desktop test bridge with the state needed to exercise roster and automatic-mention transitions. **desktop/tests/e2e/mentions.spec.ts** Covers roster-based labels, managed-agent invitation, revocation, and recovery behavior in the complete mention flow. **desktop/tests/e2e/persistent-agent-audience.spec.ts** Adds end-to-end coverage for root/thread isolation, preference synchronization, manual exclusions, draft hygiene, restored chips, separators, hover behavior, and disabled presentation. </details> ## Reproduction Steps 1. Open a channel with at least two available agents and enable automatic mentions from the composer mention control. 2. Select multiple agents, remove or uncheck one, and confirm subsequent composer updates keep that agent excluded while the others remain automatic. 3. Open a thread, choose a different automatic audience there, and switch between the thread and root composer; confirm each composer retains only its own choices. 4. Disable automatic mentions and confirm the draft text remains unchanged while automatic chips and controls show the disabled state; re-enable the setting and confirm eligible automatic chips return. 5. Delete an automatic mention chip, then explicitly add the agent again; confirm it immediately returns as an automatic mention without disturbing spaces or the caret, including for a multi-word name. 6. Reload with a saved draft and confirm implicit automatic mentions were not persisted as authored draft text. 7. Use the automatic-mention keyboard shortcut and picker repeatedly; confirm the picker remains open for additional choices and the highlighted agent toggles in place. ## Validation Validated at `34d208b47d64a9816f88e10a46bcfd479e917d75` after rebasing onto `origin/main` (`69096c9a8`): - Desktop unit tests: 5,731 passed, 0 failed. - Desktop TypeScript typecheck: passed. - Desktop E2E build: passed; emitted only existing chunk and dynamic-import warnings. - `pnpm check`: exited successfully; 4 warnings and 5 informational findings are in unrelated files introduced by current main. ## Screenshots/Demos The behavioral changes are covered by the focused desktop E2E scenarios above. Screenshots can be attached from the screenshot-producing automatic-mention E2E after the PR is created. --------- Signed-off-by: Taylor Ho <[email protected]> Signed-off-by: morgmart <[email protected]> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz> Co-authored-by: Rizz <302abe414ca6e3134763d2539bfcf145aea2a63fe5f8455204ed602fd40cf381@buzz.block.builderlab.xyz> Co-authored-by: morgmart <[email protected]>
1 parent 2c99ee7 commit 8dbc65d

35 files changed

Lines changed: 1921 additions & 241 deletions

‎desktop/src/features/agents/lib/agentAutocompleteEligibility.test.mjs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
getAgentMentionAdmission,
99
getMentionableAgentPubkeys,
1010
getSharedChannelIds,
11+
isAgentDirectoryReady,
1112
isAgentIdentityInAllowedList,
1213
isAgentMentionChannelType,
1314
relayAgentCanRespondInChannel,
@@ -42,6 +43,15 @@ function makeAgent(overrides = {}) {
4243
};
4344
}
4445

46+
test("isAgentDirectoryReady: requires successful cached directory evidence", () => {
47+
assert.equal(isAgentDirectoryReady({ data: [], error: null }), true);
48+
assert.equal(isAgentDirectoryReady({ data: undefined, error: null }), false);
49+
assert.equal(
50+
isAgentDirectoryReady({ data: [], error: new Error("offline") }),
51+
false,
52+
);
53+
});
54+
4555
test("getSharedChannelIds: includes only active joined channels", () => {
4656
assert.deepEqual(
4757
getSharedChannelIds([

‎desktop/src/features/agents/lib/agentAutocompleteEligibility.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
11
import type { Channel, RelayAgent } from "@/shared/api/types";
22
import { normalizePubkey } from "@/shared/lib/pubkey";
33

4+
export function isAgentDirectoryReady({
5+
data,
6+
error,
7+
}: {
8+
data: unknown;
9+
error: unknown;
10+
}) {
11+
// A successful cached directory remains suitable for autocomplete during a
12+
// refetch. Sending still re-fetches and fails closed at its authorization
13+
// boundary, so suggestions are hints rather than permission to send.
14+
return data !== undefined && error === null;
15+
}
16+
417
export function getSharedChannelIds(channels: readonly Channel[] | undefined) {
518
return new Set(
619
(channels ?? [])

‎desktop/src/features/channels/ui/MembersSidebar.tsx‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
coalesceAgentAutocompleteCandidates,
1313
getMentionableAgentPubkeys,
1414
getSharedChannelIds,
15+
isAgentDirectoryReady,
1516
isAgentIdentityInAllowedList,
1617
} from "@/features/agents/lib/agentAutocompleteEligibility";
1718
import { isOtherSetupAgent } from "@/features/agents/lib/otherSetupAgent";
@@ -184,12 +185,8 @@ export function MembersSidebar({
184185
relayAgentsQuery,
185186
} = useClassifiedMembers(rawMembers, currentPubkey);
186187
const agentDirectoriesReady =
187-
managedAgentsQuery.data !== undefined &&
188-
managedAgentsQuery.error === null &&
189-
!managedAgentsQuery.isFetching &&
190-
relayAgentsQuery.data !== undefined &&
191-
relayAgentsQuery.error === null &&
192-
!relayAgentsQuery.isFetching;
188+
isAgentDirectoryReady(managedAgentsQuery) &&
189+
isAgentDirectoryReady(relayAgentsQuery);
193190
const activeMembers = React.useMemo(
194191
() =>
195192
[...people, ...bots].sort((left, right) =>

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ globalThis.localStorage = {
88
};
99

1010
const preference = await import("./autoPinMentionedAgentsPreference.ts");
11+
const persistentAudience = await import("./persistentAgentAudience.ts");
1112

1213
test("defaults missing and invalid values to one-time agent mentions", () => {
1314
assert.equal(preference.parseKeepMentionedAgentsPinned(null), false);
@@ -31,3 +32,16 @@ test("persists changes to the post-mention pinning preference", () => {
3132
"false",
3233
);
3334
});
35+
36+
test("turning off automatic mentions clears active conversation audiences", () => {
37+
const scope = `${"1".repeat(64)}:channel-a:channel`;
38+
persistentAudience.setPersistentAgentAudience(scope, ["a".repeat(64)]);
39+
preference.setKeepMentionedAgentsPinned(true);
40+
41+
preference.setKeepMentionedAgentsPinned(false);
42+
43+
assert.deepEqual(
44+
persistentAudience.getPersistentAgentAudienceSnapshot().audiences,
45+
{},
46+
);
47+
});

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import * as React from "react";
22

3+
import { resetPersistentAgentAudienceStore } from "./persistentAgentAudience";
4+
35
export const KEEP_MENTIONED_AGENTS_PINNED_STORAGE_KEY =
46
"buzz.messages.keepMentionedAgentsPinned";
57
export const DEFAULT_KEEP_MENTIONED_AGENTS_PINNED = false;
@@ -37,6 +39,7 @@ export function getKeepMentionedAgentsPinned(): boolean {
3739
}
3840

3941
export function setKeepMentionedAgentsPinned(value: boolean): void {
42+
if (!value) resetPersistentAgentAudienceStore();
4043
if (value === keepMentionedAgentsPinned) return;
4144
keepMentionedAgentsPinned = value;
4245
try {

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ function input(overrides = {}) {
2323
managedAgents: [],
2424
memberPubkeys: new Set(),
2525
members: [],
26+
mentionChannelId: null,
2627
mentionableAgentPubkeys: new Set(),
2728
personaNameByPubkey: new Map(),
2829
profiles: undefined,

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ export type BuildMentionCandidatesInput = {
3636
managedAgents: readonly ManagedAgent[] | undefined;
3737
memberPubkeys: ReadonlySet<string>;
3838
members: readonly ChannelMember[] | undefined;
39+
mentionChannelId: string | null;
3940
mentionableAgentPubkeys: ReadonlySet<string>;
4041
personaNameByPubkey: ReadonlyMap<string, string>;
4142
profiles: UserProfileLookup | undefined;
@@ -66,6 +67,7 @@ export function buildMentionCandidates({
6667
managedAgents,
6768
memberPubkeys,
6869
members,
70+
mentionChannelId,
6971
mentionableAgentPubkeys,
7072
personaNameByPubkey,
7173
profiles,
@@ -167,7 +169,13 @@ export function buildMentionCandidates({
167169
kind: "identity",
168170
pubkey,
169171
displayName: agent.name,
170-
isMember: false,
172+
// Prefer the active channel's signed roster. The relay-agent directory
173+
// is filtered by access policy, so its channel ids can legitimately omit
174+
// a room where this identity is already a member.
175+
isMember:
176+
memberPubkeys.has(pubkey) ||
177+
(mentionChannelId !== null &&
178+
agent.channelIds.includes(mentionChannelId)),
171179
personaId:
172180
managedAgentPersonaIdsByPubkey.get(pubkey) ??
173181
(activePersonaById.has(pubkey) ? pubkey : undefined),
@@ -177,11 +185,12 @@ export function buildMentionCandidates({
177185
});
178186
}
179187
for (const agent of managedAgents ?? []) {
188+
const pubkey = normalizePubkey(agent.pubkey);
180189
addCandidate({
181190
kind: "identity",
182-
pubkey: agent.pubkey,
191+
pubkey,
183192
displayName: agent.name,
184-
isMember: false,
193+
isMember: memberPubkeys.has(pubkey),
185194
isAgent: true,
186195
isActiveAgent: agent.status === "running" || agent.status === "deployed",
187196
isManagedAgent: true,

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,12 @@ export const MentionHighlightExtension = Extension.create({
431431
applying = false;
432432
}
433433
}
434-
setDomCaretAtPos(view, view.state.selection.from);
434+
// Highlight refreshes can land after the user has moved focus to
435+
// a popover. Keep settlement armed for the next keystroke, but
436+
// never drag DOM selection back into an unfocused composer.
437+
if (view.hasFocus()) {
438+
setDomCaretAtPos(view, view.state.selection.from);
439+
}
435440
},
436441
destroy() {
437442
settlement.cancel();
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import type { Channel, ChannelMember } from "@/shared/api/types";
2+
import { normalizePubkey } from "@/shared/lib/pubkey";
3+
import { channelMemberPubkeySet } from "@/shared/lib/rosterDerivations";
4+
5+
/** Merge the dedicated roster with the active channel's signed projection. */
6+
export function getMentionMemberPubkeys(
7+
channelId: string | null,
8+
channels: readonly Channel[] | undefined,
9+
members: ChannelMember[] | undefined,
10+
): Set<string> {
11+
const pubkeys = new Set(
12+
members ? channelMemberPubkeySet(members) : undefined,
13+
);
14+
const activeChannel = channels?.find((channel) => channel.id === channelId);
15+
for (const pubkey of activeChannel?.memberPubkeys ?? []) {
16+
pubkeys.add(normalizePubkey(pubkey));
17+
}
18+
return pubkeys;
19+
}

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

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,20 +134,29 @@ test("reset clears every audience for refresh and community boundaries", async (
134134
assert.deepEqual(currentAudiences(store), {});
135135
});
136136

137-
test("channel and thread composers share the channel audience scope", async () => {
137+
test("channel and thread composers have independent audience scopes", async () => {
138138
const store = await loadStore(8);
139139
const channelScope = store.getPersistentAgentAudienceScope({
140140
ownerPubkey: ownerA,
141141
channelId: "channel-a",
142+
composerKey: "channel-a",
142143
});
143144
const threadScope = store.getPersistentAgentAudienceScope({
144145
ownerPubkey: ownerA,
145146
channelId: "channel-a",
146-
threadRootId: "root",
147+
composerKey: "thread:root",
148+
});
149+
const otherThreadScope = store.getPersistentAgentAudienceScope({
150+
ownerPubkey: ownerA,
151+
channelId: "channel-a",
152+
composerKey: "thread:other-root",
147153
});
148154

149155
assert.equal(channelScope, `${ownerA}:channel-a:channel`);
150-
assert.equal(threadScope, channelScope);
156+
assert.equal(threadScope, `${ownerA}:channel-a:thread:root`);
157+
assert.equal(otherThreadScope, `${ownerA}:channel-a:thread:other-root`);
158+
assert.notEqual(threadScope, channelScope);
159+
assert.notEqual(otherThreadScope, threadScope);
151160
});
152161

153162
test("delayed promotion cannot overwrite a newer audience choice", async () => {
@@ -191,6 +200,42 @@ test("stale auto-pin Undo cannot remove a newer explicit choice", async () => {
191200
assert.deepEqual(currentAudiences(store), { [scope]: [agentA] });
192201
});
193202

203+
test("explicitly excluded agents are not auto-promoted again", async () => {
204+
const store = await loadStore(12);
205+
const scope = `${ownerA}:channel-a:channel`;
206+
store.setPersistentAgentAudience(scope, [agentA]);
207+
store.excludePersistentAgentAudienceMember(scope, agentA);
208+
209+
const promotion = store.promotePersistentAgentAudienceIfUnchanged({
210+
expectedRevision: store.getPersistentAgentAudienceRevision(scope),
211+
pubkeys: [agentA],
212+
scope,
213+
});
214+
215+
assert.equal(promotion, null);
216+
assert.deepEqual(currentAudiences(store), { [scope]: [] });
217+
218+
store.addPersistentAgentAudienceMember(scope, agentA);
219+
assert.deepEqual(currentAudiences(store), { [scope]: [agentA] });
220+
});
221+
222+
test("explicit re-selection reinstates an excluded agent", async () => {
223+
const store = await loadStore(13);
224+
const scope = `${ownerA}:channel-a:channel`;
225+
store.setPersistentAgentAudience(scope, [agentA]);
226+
store.excludePersistentAgentAudienceMember(scope, agentA);
227+
228+
const promotion = store.promotePersistentAgentAudienceIfUnchanged({
229+
expectedRevision: store.getPersistentAgentAudienceRevision(scope),
230+
reinstateExcluded: true,
231+
pubkeys: [agentA],
232+
scope,
233+
});
234+
235+
assert.deepEqual(promotion?.promotedPubkeys, [agentA]);
236+
assert.deepEqual(currentAudiences(store), { [scope]: [agentA] });
237+
});
238+
194239
test("promotion reports only newly added agents for transactional Undo", async () => {
195240
const store = await loadStore(11);
196241
const scope = `${ownerA}:channel-a:channel`;

0 commit comments

Comments
 (0)