From ce0df522f9d9d8fc9feb3b8ff4a10fec66498a01 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 15:20:03 -0500 Subject: [PATCH 01/21] feat(mentions): let saved teams mention people outside the channel A saved team's member list can hold people as well as agents (the Mention Groups plugin writes such teams). The team path passed only agents as its directory, so a person outside the channel had no candidate row and disabled the whole team. Now each team person is named from their profile and offered exactly as the individual chooser offers them; agents keep their own path. A key counts as a person only once agent choices are complete and it is no known agent here or elsewhere. Team rows say members instead of agents. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/buzz-help.md | 3 +- src/bundled/mentions/team-mentions.test.tsx | 67 +++++++++++++++++++ src/bundled/mentions/use-team-mentions.ts | 71 ++++++++++++++++++--- 3 files changed, 132 insertions(+), 9 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 274d252a41..d85150fc01 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1498,7 +1498,8 @@ available rather than silently discarding it. Saved teams from **Your teams** appear in the inline `@` suggestions and the mention picker. Select a team to insert its members as individual mentions. -Typing its name alone does not notify it. Empty teams, teams with more than 32 +A saved team can hold people as well as agents; a person outside the +conversation is offered the way the `@` picker offers them. Typing its name alone does not notify it. Empty teams, teams with more than 32 members, and teams with unavailable members cannot be selected; edit the team or refresh the choices. Adding people to a channel still requires the normal send confirmation. **Delete team** asks first; it doesn't delete the team's agents. diff --git a/src/bundled/mentions/team-mentions.test.tsx b/src/bundled/mentions/team-mentions.test.tsx index f6c64e4748..5cee12fb34 100644 --- a/src/bundled/mentions/team-mentions.test.tsx +++ b/src/bundled/mentions/team-mentions.test.tsx @@ -537,6 +537,73 @@ it.each([false, true])( }, ); +/** A team of the fixture's agent and one person, who is outside the channel. */ +function teamWithPerson(h: ReturnType) { + const person = h.people[1]; + if (!person) throw new Error("Fixture needs a person"); + h.update({ members: [h.agent.pubkey] }); + h.catalog({ + status: "ready", + entries: [ + { + eventId: "head", + createdAt: 1, + record: { + version: 1, + community: "fixture", + deleted: false, + value: { + type: "team", + id: "team", + name: "Team", + agents: [h.agent.pubkey, person.pubkey], + }, + }, + }, + ], + }); + return person; +} + +it("a team mentions a person outside the channel, as the individual chooser would", async () => { + const h = fixture({ count: 2, team: 1 }); + const person = teamWithPerson(h); + const menu = inline(h.session); + try { + await waitFor(() => expect(menu.team()?.canSelect?.("Enter")).toBe(true)); + expect(menu.team()?.edit.mentions).toEqual([h.agent, person]); + expect(menu.team()?.detail).toBe( + "Saved team · 2 members · 1 not in channel", + ); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); + +it("a team person without a known name stays unavailable while their profile is requested", async () => { + const h = fixture({ count: 2, team: 1 }); + const person = teamWithPerson(h); + const profiles = h.session.profiles as unknown as { + snapshot: () => Map; + ensure: (ids: readonly string[]) => Promise; + }; + profiles.snapshot().delete(person.pubkey); + const ensure = vi.spyOn(profiles, "ensure"); + const menu = inline(h.session); + try { + await waitFor(() => + expect(ensure).toHaveBeenCalledWith( + [h.agent.pubkey, person.pubkey].sort(), + ), + ); + expect(menu.team()?.disabled).toContain("unavailable"); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); + it("more members than the shown rows rank only the first rows", async () => { const h = fixture({ count: MENTION_ROWS + 1, team: 0 }); const view = renderHook(() => diff --git a/src/bundled/mentions/use-team-mentions.ts b/src/bundled/mentions/use-team-mentions.ts index 677d3335ed..a0748994ca 100644 --- a/src/bundled/mentions/use-team-mentions.ts +++ b/src/bundled/mentions/use-team-mentions.ts @@ -6,6 +6,7 @@ import { useCallback, useEffect, useMemo, + useRef, useState, useSyncExternalStore, } from "react"; @@ -152,6 +153,23 @@ export function useTeamMentions( ? installed.teams : undefined; if (installed && !rows) install(undefined); + // A team holds people as well as agents. Ask for the names of the people in + // shown rows: an unnamed key is never offered, as with a pasted link. + const memberKeys = [ + ...new Set(rows?.flatMap((team) => team.value.agents) ?? []), + ] + .sort() + .join(); + useEffect(() => { + if (open && memberKeys) + void session.profiles.ensure(memberKeys.split(",")).catch(() => {}); + }, [session, open, memberKeys]); + // mentionCandidates keeps rows per directory array, so reuse one array until + // its sources change. + const directory = useRef<{ + sources: readonly unknown[]; + people: readonly { pubkey: string; name: string }[]; + }>(undefined); if (open && !model.pending) { const members = new Set( roster?.map((person) => person.pubkey) ?? model.channel?.members ?? [], @@ -192,6 +210,44 @@ export function useTeamMentions( } return useMemo(() => { void model; // Source revisions invalidate eligibility, not the installed row order. + // The agents the chooser offers, and the team's people by profile name. A + // key is a person only once agent choices are complete and it is no known + // agent here or in the owner's other communities; agents keep their path. + const teamDirectory = () => { + const choices = session.agentChoices.snapshot(); + const profiles = session.profiles.snapshot(); + const elsewhere = owner?.joinable() ?? []; + const sources = [ + choices, + profiles, + memberKeys, + elsewhere.map((agent) => agent.pubkey).join(), + ]; + if ( + !directory.current?.sources.every((source, i) => source === sources[i]) + ) { + const agents = new Set([ + ...choices.identities.map((agent) => agent.pubkey), + ...elsewhere.map((agent) => agent.pubkey), + ]); + const people = + choices.complete && memberKeys + ? memberKeys.split(",").flatMap((pubkey) => { + const profile = profiles.get(pubkey); + return profile?.name && !profile.isAgent && !agents.has(pubkey) + ? [{ pubkey, name: profile.name }] + : []; + }) + : []; + directory.current = { + sources, + people: people.length + ? [...choices.identities, ...people] + : choices.identities, + }; + } + return directory.current.people; + }; // Parent chooser subscribes to roster, profiles, agent choices and archives. // Read those same owners again at acceptance; saved keys grant no eligibility. const candidates = () => @@ -200,11 +256,9 @@ export function useTeamMentions( channelId, inviteAgents, roster, - // A Solo chat already offers the agents it can add; any other agent - // would only be a reference, and a team addresses its agents. - model.channel?.channelType === "solo" - ? [] - : session.agentChoices.snapshot().identities, + // A Solo chat already offers the agents it can add; anyone else + // would only be a reference, and a team addresses its members. + model.channel?.channelType === "solo" ? [] : teamDirectory(), owner?.joinable(), ); // Only shown team rows read eligibility; a closed chooser builds none. @@ -221,9 +275,9 @@ export function useTeamMentions( : members.some((key) => !eligible.get(key)?.member) ? "Channel membership changed. Reopen to review adding this team." : !value.agents.length - ? "This team has no agents." + ? "This team has no members." : value.agents.length > 32 - ? "Teams can mention at most 32 agents." + ? "Teams can mention at most 32 members." : recipients.length !== value.agents.length ? "A team member is unavailable. Edit the team or refresh choices." : undefined; @@ -247,7 +301,7 @@ export function useTeamMentions( disabled, detail: disabled ?? - [`Saved team · ${recipients.length} agents`, consequence] + [`Saved team · ${recipients.length} members`, consequence] .filter(Boolean) .join(" · "), canSelect: () => { @@ -301,5 +355,6 @@ export function useTeamMentions( hasTeams, readSaved, owner, + memberKeys, ]); } From 2a11787f2ffaba393b8ac14e551333144cd4c276 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 15:27:21 -0500 Subject: [PATCH 02/21] fix(mentions): request team names in the background, skipping oversized teams Team rows ask for member names the way the chooser asks for owner names: background priority, and only for teams that can mention (at most 32). The unnamed-person test now delivers the profile and checks that the open team becomes selectable. Co-authored-by: Clod Co-authored-by: Sigil <06114f072cf21e50fcd4133ab21346cdb1f74ee16d853a9729995fa6c03a251c@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/bundled/mentions/team-mentions.test.tsx | 27 +++++++++++++++------ src/bundled/mentions/use-team-mentions.ts | 13 +++++++--- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/bundled/mentions/team-mentions.test.tsx b/src/bundled/mentions/team-mentions.test.tsx index 5cee12fb34..20ffb16a9c 100644 --- a/src/bundled/mentions/team-mentions.test.tsx +++ b/src/bundled/mentions/team-mentions.test.tsx @@ -581,23 +581,36 @@ it("a team mentions a person outside the channel, as the individual chooser woul } }); -it("a team person without a known name stays unavailable while their profile is requested", async () => { +it("a team person without a known name stays unavailable until their profile loads", async () => { const h = fixture({ count: 2, team: 1 }); const person = teamWithPerson(h); - const profiles = h.session.profiles as unknown as { - snapshot: () => Map; - ensure: (ids: readonly string[]) => Promise; - }; - profiles.snapshot().delete(person.pubkey); - const ensure = vi.spyOn(profiles, "ensure"); + let names = new Map(h.session.profiles.snapshot()); + names.delete(person.pubkey); + const listeners = new Set<() => void>(); + const ensure = vi.fn(async () => {}); + Object.assign(h.session.profiles, { + snapshot: () => names, + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + ensure, + }); const menu = inline(h.session); try { await waitFor(() => expect(ensure).toHaveBeenCalledWith( [h.agent.pubkey, person.pubkey].sort(), + "background", ), ); expect(menu.team()?.disabled).toContain("unavailable"); + act(() => { + names = new Map(names).set(person.pubkey, { name: person.name }); + for (const listener of listeners) listener(); + }); + await waitFor(() => expect(menu.team()?.canSelect?.("Enter")).toBe(true)); + expect(menu.team()?.edit.mentions).toEqual([h.agent, person]); } finally { menu.view.unmount(); h.library.dispose(); diff --git a/src/bundled/mentions/use-team-mentions.ts b/src/bundled/mentions/use-team-mentions.ts index a0748994ca..6872d2eb4b 100644 --- a/src/bundled/mentions/use-team-mentions.ts +++ b/src/bundled/mentions/use-team-mentions.ts @@ -154,15 +154,22 @@ export function useTeamMentions( : undefined; if (installed && !rows) install(undefined); // A team holds people as well as agents. Ask for the names of the people in - // shown rows: an unnamed key is never offered, as with a pasted link. + // shown rows that can mention: an unnamed key is never offered, as with a + // pasted link. const memberKeys = [ - ...new Set(rows?.flatMap((team) => team.value.agents) ?? []), + ...new Set( + rows?.flatMap(({ value }) => + value.agents.length > 32 ? [] : value.agents, + ) ?? [], + ), ] .sort() .join(); useEffect(() => { if (open && memberKeys) - void session.profiles.ensure(memberKeys.split(",")).catch(() => {}); + void session.profiles + .ensure(memberKeys.split(","), "background") + .catch(() => {}); }, [session, open, memberKeys]); // mentionCandidates keeps rows per directory array, so reuse one array until // its sources change. From 96737da9cf73fe6ec7b95ff09485b1581406bfeb Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 17:30:49 -0500 Subject: [PATCH 03/21] feat(mentions): a saved team inserts one group chip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Selecting a team inserted every member as its own chip, so a large team made an unreadable message. A team row now inserts one `@team` chip that notifies each member: - CompletionEdit gains `{ group: { name, mentions } }`; `insertMentions` takes an optional group name, so the toolbar picker does the same. - The token's `group: { label, members }` attr holds the members, with `recipient` null, so code, clipboard, open-as-text and Markdown see plain `@team`. Projection emits one labelled DraftRecipient per member. - Lifecycle: removing or replacing a member keeps the chip for the rest; the last member, a boundary edit, code, paste or a pick during a message edit leave plain text. Draft restore keeps only members on a span reading `@label`. - The 32-recipient cap counts distinct people; mentionTags dedupes first. - The row reads "Saved team · 1 person, 2 agents". Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/agents.md | 12 +- docs/buzz-help.md | 3 +- docs/plugin-architecture.md | 4 +- src/bundled/mentions/MentionCompletion.tsx | 2 +- src/bundled/mentions/MentionPicker.tsx | 2 +- src/bundled/mentions/solo-agents.test.tsx | 12 +- src/bundled/mentions/team-mentions.test.tsx | 37 ++++-- src/bundled/mentions/use-team-mentions.ts | 18 ++- src/features/conversation/ComposerTools.tsx | 4 +- src/features/conversation/completion.ts | 63 ++++++---- src/features/conversation/contracts.ts | 20 ++- src/features/messages/EditableInput.test.tsx | 80 +++++++++++- src/features/messages/EditableInput.tsx | 119 ++++++++++++++---- .../messages/MessageComposer.test.tsx | 58 ++++++++- src/features/messages/MessageComposer.tsx | 90 +++++++++++-- src/features/messages/RichComposerInput.tsx | 58 ++++++++- src/features/messages/composer-document.ts | 119 ++++++++++++++++-- src/features/messages/composer-dom.ts | 4 +- src/features/messages/mention-draft.test.ts | 43 +++++++ src/features/messages/mention-draft.ts | 57 +++++++-- src/features/relay/messages.ts | 8 +- 21 files changed, 697 insertions(+), 116 deletions(-) diff --git a/docs/agents.md b/docs/agents.md index 2dc3e48209..955fb0cdf2 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -1155,17 +1155,19 @@ in both mention choosers under the same community visibility rules. Legacy channel-kit teams (see [Channels](channels.md)) remain available independently; a legacy catalog failure does not block current teams. A team is a shortcut, not a group identity: explicit selection -inserts its saved agent keys as individual mentions in one undoable edit through -`insertMentions`. Names never resolve membership. Typing a team name or Space +inserts one `@team` chip in one undoable edit, which notifies each saved key as an +individual mention (a `group` completion edit). Its row counts people and agents. +Removing a member keeps the chip for the rest; typing into its name, code, opening +it as text or copying it leaves plain `@team`. Names never resolve membership. Typing a team name or Space alone does not select it. Team names also prevent Space from accidentally selecting a person with the same name or a prefix. Each query shows at most 20 matching teams, with up to four cached avatar thumbnails and a remainder count. Empty, oversized (more than 32 agents), changed or partially unavailable teams stay disabled; there is no partial expansion. Reopen or change the query to refresh changed team choices. The resulting draft must fit the existing 32-mention and message-length -limits. Selection never adds members: ordinary channels retain invite-on-send -consent, DMs retain reference-only outsiders, and Solo chats add only the -viewer's available agents. +limits; a person mentioned by several chips counts once. Selection never adds +members: ordinary channels retain invite-on-send consent, DMs retain +reference-only outsiders, and Solo chats add only the viewer's available agents. The picker supports Up/Down navigation, Enter selection and Escape dismissal. diff --git a/docs/buzz-help.md b/docs/buzz-help.md index d85150fc01..e96c6d7010 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1497,7 +1497,8 @@ available rather than silently discarding it. this device. Saved teams from **Your teams** appear in the inline `@` suggestions and the -mention picker. Select a team to insert its members as individual mentions. +mention picker. Select a team to insert one `@team` mention that notifies each +member; the suggestion shows how many people and agents it holds. A saved team can hold people as well as agents; a person outside the conversation is offered the way the `@` picker offers them. Typing its name alone does not notify it. Empty teams, teams with more than 32 members, and teams with unavailable members cannot be selected; edit the team or diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 62db444950..39011c363e 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3131,7 +3131,9 @@ Providers receive immutable observation/range evidence and `publish(result)`—n DOM, focus or replacement commands. Results contain stable IDs, labels, optional detail/decorative previews, an optional `agent` flag (marked and announced only for the bundled mention and channel providers) and either text, an exact `{ pubkey, name }` mention, -or a `mentions` array of up to 32 such recipients. Batch edit primitives are +a `mentions` array of up to 32 such recipients, or a `group` of `{ name, mentions }`: +one `@name` chip that notifies each of its up to 32 mentions. In a message edit a +group inserts only its name, since edits add no recipients. Batch edit primitives are copied and frozen before display, and accepted as a single editor transaction. The host copies edit/query primitives and caps publications at 50 choices. A publication returns its own withdrawal disposer (or `false` after revocation). diff --git a/src/bundled/mentions/MentionCompletion.tsx b/src/bundled/mentions/MentionCompletion.tsx index d2ed05c3f6..0da5838d35 100644 --- a/src/bundled/mentions/MentionCompletion.tsx +++ b/src/bundled/mentions/MentionCompletion.tsx @@ -290,7 +290,7 @@ export function MentionCompletion({ ), edit: team.disabled ? { text: `@${team.name}` } - : { mentions: team.recipients }, + : { group: { name: team.name, mentions: team.recipients } }, })), ]; const key = JSON.stringify([ diff --git a/src/bundled/mentions/MentionPicker.tsx b/src/bundled/mentions/MentionPicker.tsx index d7df3d8c57..bc299004ef 100644 --- a/src/bundled/mentions/MentionPicker.tsx +++ b/src/bundled/mentions/MentionPicker.tsx @@ -144,7 +144,7 @@ export function MentionPicker({ setOpen(false); return; } - if (team.canSelect() && selectTeam?.(team.recipients)) { + if (team.canSelect() && selectTeam?.(team.recipients, team.name)) { accepted.current = true; setOpen(false); } diff --git a/src/bundled/mentions/solo-agents.test.tsx b/src/bundled/mentions/solo-agents.test.tsx index 845d21d550..33267c1f4e 100644 --- a/src/bundled/mentions/solo-agents.test.tsx +++ b/src/bundled/mentions/solo-agents.test.tsx @@ -4319,7 +4319,7 @@ it("saved teams resolve exact keys, block automatic Space and revoke a changed c try { await waitFor(() => expect(h.choice()?.disabled).toBeUndefined()); await waitFor(() => - expect(h.choice()?.edit.mentions).toEqual([ + expect(h.choice()?.edit.group?.mentions).toEqual([ { pubkey: h.member, name: "Member" }, { pubkey: h.key, name: "Outside agent" }, ]), @@ -4356,7 +4356,7 @@ it.each([ try { await waitFor(() => expect(h.choice()?.disabled).toBeTruthy()); expect(h.choice()?.canSelect?.("Enter")).toBe(false); - expect(h.choice()?.edit.mentions).toBeUndefined(); + expect(h.choice()?.edit.group?.mentions).toBeUndefined(); } finally { h.view.unmount(); h.library.dispose(); @@ -4366,7 +4366,9 @@ it.each([ it("archive changes revoke previously published team acceptance", async () => { const h = teamFixture(); try { - await waitFor(() => expect(h.choice()?.edit.mentions).toHaveLength(2)); + await waitFor(() => + expect(h.choice()?.edit.group?.mentions).toHaveLength(2), + ); const selected = h.choice(); if (!selected) throw new Error("Team missing"); act(() => h.setArchived([h.key])); @@ -4409,7 +4411,9 @@ it("team loading has no Retry action and never replaces a people status", async it("a longer team name remains an admitted query after a person's exact name plus Space", async () => { const h = teamFixture(undefined, { query: "Member " }); try { - await waitFor(() => expect(h.choice()?.edit.mentions).toHaveLength(2)); + await waitFor(() => + expect(h.choice()?.edit.group?.mentions).toHaveLength(2), + ); expect(h.result()?.items[0]).toMatchObject({ id: h.member, label: "Member", diff --git a/src/bundled/mentions/team-mentions.test.tsx b/src/bundled/mentions/team-mentions.test.tsx index 20ffb16a9c..8d683c0d2f 100644 --- a/src/bundled/mentions/team-mentions.test.tsx +++ b/src/bundled/mentions/team-mentions.test.tsx @@ -379,7 +379,7 @@ it("teams retain installed membership through rerenders and stale acceptance unt h.notify(); expect(menu.team()?.disabled).toContain("membership changed"); expect(menu.team()?.canSelect?.("Enter")).toBe(false); - expect(menu.team()?.edit.mentions).toBeUndefined(); + expect(menu.team()?.edit.group?.mentions).toBeUndefined(); expect( menu.result().items.find((i) => i.id === h.agent.pubkey)?.disabled, ).toContain("membership changed"); @@ -466,7 +466,7 @@ it("the team picker disables a removed member until reopened", async () => { }); expect(reopened).toBeEnabled(); await user.click(reopened); - expect(selectTeam).toHaveBeenCalledWith([h.agent]); + expect(selectTeam).toHaveBeenCalledWith([h.agent], "Team"); } finally { view.unmount(); h.library.dispose(); @@ -488,7 +488,7 @@ it.each([false, true])( act(() => menu.result().retry?.()); await waitFor(() => expect(h.read).toHaveBeenCalledTimes(2)); await waitFor(() => expect(menu.team()?.canSelect?.("Enter")).toBe(true)); - expect(menu.team()?.edit.mentions).toEqual([h.agent]); + expect(menu.team()?.edit.group?.mentions).toEqual([h.agent]); } finally { menu.view.unmount(); h.library.dispose(); @@ -529,7 +529,7 @@ it.each([false, true])( }); expect(team).toBeEnabled(); await user.click(team); - expect(selectTeam).toHaveBeenCalledWith([h.agent]); + expect(selectTeam).toHaveBeenCalledWith([h.agent], "Team"); } finally { view.unmount(); h.library.dispose(); @@ -571,9 +571,9 @@ it("a team mentions a person outside the channel, as the individual chooser woul const menu = inline(h.session); try { await waitFor(() => expect(menu.team()?.canSelect?.("Enter")).toBe(true)); - expect(menu.team()?.edit.mentions).toEqual([h.agent, person]); + expect(menu.team()?.edit.group?.mentions).toEqual([h.agent, person]); expect(menu.team()?.detail).toBe( - "Saved team · 2 members · 1 not in channel", + "Saved team · 1 person, 1 agent · 1 not in channel", ); } finally { menu.view.unmount(); @@ -610,7 +610,7 @@ it("a team person without a known name stays unavailable until their profile loa for (const listener of listeners) listener(); }); await waitFor(() => expect(menu.team()?.canSelect?.("Enter")).toBe(true)); - expect(menu.team()?.edit.mentions).toEqual([h.agent, person]); + expect(menu.team()?.edit.group?.mentions).toEqual([h.agent, person]); } finally { menu.view.unmount(); h.library.dispose(); @@ -1040,12 +1040,14 @@ it("offers a team created through Your teams in both mention choosers", async () const choice = () => completion(publish)?.items.find((item) => item.label === "ReviewCrew"); await waitFor(() => expect(choice()?.canSelect?.("Enter")).toBe(true)); - expect(choice()?.edit).toEqual({ mentions: h.people }); + expect(choice()?.edit).toEqual({ + group: { name: "ReviewCrew", mentions: h.people }, + }); await user.click(screen.getByRole("button", { name: "Mention a member" })); await user.click( await screen.findByRole("button", { name: /ReviewCrew.*Saved team/ }), ); - expect(selectTeam).toHaveBeenCalledExactlyOnceWith(h.people); + expect(selectTeam).toHaveBeenCalledExactlyOnceWith(h.people, "ReviewCrew"); } finally { view.unmount(); h.library.dispose(); @@ -1099,7 +1101,9 @@ it.each(["loading", "error", "unavailable"] as const)( expect(choice()?.disabled).toContain("changed"); view.rerender(content({ start: 0, end: 10, query: "Review Cr" })); await waitFor(() => expect(choice()?.canSelect?.("Enter")).toBe(true)); - expect(choice()?.edit).toEqual({ mentions: h.people.slice(0, 1) }); + expect(choice()?.edit).toEqual({ + group: { name: expect.any(String), mentions: h.people.slice(0, 1) }, + }); const renamed = choice(); await act(() => h.service.saveTeam({ ...team, name: "Renamed Crew" })); expect(renamed?.canSelect?.("Enter")).toBe(false); @@ -1262,7 +1266,10 @@ it.each([true, false])( await waitFor(() => expect(completion(publish)?.items.length).toBe(1)); const choice = completion(publish).items[0]; expect(choice?.canSelect?.("Enter")).toBe(canAdd); - if (canAdd) expect(choice?.edit).toEqual({ mentions: h.people }); + if (canAdd) + expect(choice?.edit).toEqual({ + group: { name: expect.any(String), mentions: h.people }, + }); else expect(choice?.disabled).toContain("unavailable"); } finally { view.unmount(); @@ -1515,8 +1522,12 @@ it("projects confirmed synced teams through the real service without colliding w const choices = completion(publish).items; const synced = choices.find((item) => item.label === "Synced Crew"); const legacy = choices.find((item) => item.label === "Legacy Crew"); - expect(synced?.edit).toEqual({ mentions: h.people }); - expect(legacy?.edit).toEqual({ mentions: [h.agent] }); + expect(synced?.edit).toEqual({ + group: { name: "Synced Crew", mentions: h.people }, + }); + expect(legacy?.edit).toEqual({ + group: { name: "Legacy Crew", mentions: [h.agent] }, + }); expect(synced?.id).not.toBe(legacy?.id); expect(synced?.canSelect?.("Enter")).toBe(true); expect(legacy?.canSelect?.("Enter")).toBe(true); diff --git a/src/bundled/mentions/use-team-mentions.ts b/src/bundled/mentions/use-team-mentions.ts index 6872d2eb4b..ea8c503ba1 100644 --- a/src/bundled/mentions/use-team-mentions.ts +++ b/src/bundled/mentions/use-team-mentions.ts @@ -52,6 +52,22 @@ export function teamBlocksSpace( const subscribeNone = () => () => {}; const snapshotNone = () => empty; +/** "1 person, 2 agents": what a team row says it mentions. */ +function teamCount( + recipients: readonly { pubkey: string }[], + eligible: ReadonlyMap, +) { + const agents = recipients.filter( + (person) => eligible.get(person.pubkey)?.agent, + ).length; + const people = recipients.length - agents; + return [ + people ? `${people} ${people === 1 ? "person" : "people"}` : "", + agents ? `${agents} ${agents === 1 ? "agent" : "agents"}` : "", + ] + .filter(Boolean) + .join(", "); +} /** Saved teams are shortcuts to exact individual recipients, never new identities. */ export function useTeamMentions( session: ComposerSession, @@ -308,7 +324,7 @@ export function useTeamMentions( disabled, detail: disabled ?? - [`Saved team · ${recipients.length} members`, consequence] + [`Saved team · ${teamCount(recipients, eligible)}`, consequence] .filter(Boolean) .join(" · "), canSelect: () => { diff --git a/src/features/conversation/ComposerTools.tsx b/src/features/conversation/ComposerTools.tsx index 74e5c8eadb..0715edca9a 100644 --- a/src/features/conversation/ComposerTools.tsx +++ b/src/features/conversation/ComposerTools.tsx @@ -105,8 +105,8 @@ function OwnedTool({ active() ? current.current.insertText(text) : false, insertMention: (recipient) => active() ? current.current.insertMention(recipient) : false, - insertMentions: (recipients) => - active() ? current.current.insertMentions(recipients) : false, + insertMentions: (recipients, group) => + active() ? current.current.insertMentions(recipients, group) : false, replaceRecipients: (recipients) => active() ? current.current.replaceRecipients(recipients) : false, replaceRecipientsIfEmpty: (recipients) => diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 1d59ce7f6a..e9292f6323 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -89,6 +89,28 @@ function validQuery( typeof query.query === "string" ); } +/** 1 to 32 well-formed people, as a team or group edit names them. */ +function validPeople(people: unknown): people is readonly MentionRecipient[] { + return ( + Array.isArray(people) && + !!people.length && + people.length <= 32 && + people.every( + (person: MentionRecipient) => + !!person && + typeof person.pubkey === "string" && + /^[0-9a-f]{64}$/.test(person.pubkey) && + typeof person.name === "string" && + !!person.name.trim(), + ) + ); +} +const frozenPeople = (people: readonly MentionRecipient[]) => + Object.freeze( + people.map((person) => + Object.freeze({ pubkey: person.pubkey, name: person.name }), + ), + ); /** Copy edit primitives so later provider mutation cannot retarget a displayed choice. */ export function completionResult( result: HostCompletionResult, @@ -121,21 +143,16 @@ export function completionResult( // Host-made and frozen: kept as is. } else if ("token" in edit) { if (!token) continue; - } else if ("mentions" in edit) { + } else if ("group" in edit) { if ( - !Array.isArray(edit.mentions) || - !edit.mentions.length || - edit.mentions.length > 32 || - edit.mentions.some( - (person: MentionRecipient) => - !person || - typeof person.pubkey !== "string" || - !/^[0-9a-f]{64}$/.test(person.pubkey) || - typeof person.name !== "string" || - !person.name.trim(), - ) + !edit.group || + typeof edit.group.name !== "string" || + !edit.group.name.trim() || + !validPeople(edit.group.mentions) ) continue; + } else if ("mentions" in edit) { + if (!validPeople(edit.mentions)) continue; } else if ("mention" in edit) { if ( !edit.mention || @@ -171,20 +188,18 @@ export function completionResult( : Object.freeze( token ? { token } - : "mentions" in edit && edit.mentions + : "group" in edit && edit.group ? { - mentions: Object.freeze( - edit.mentions.map((person: MentionRecipient) => - Object.freeze({ - pubkey: person.pubkey, - name: person.name, - }), - ), - ), + group: Object.freeze({ + name: edit.group.name, + mentions: frozenPeople(edit.group.mentions), + }), } - : "mention" in edit - ? { mention: Object.freeze({ ...edit.mention }) } - : { text: edit.text }, + : "mentions" in edit && edit.mentions + ? { mentions: frozenPeople(edit.mentions) } + : "mention" in edit + ? { mention: Object.freeze({ ...edit.mention }) } + : { text: edit.text }, ), }), ); diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index e222ef091c..04457eece4 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -55,9 +55,11 @@ export type ComposerToolProps = Readonly<{ * Prose never resolves to identities. Membership is checked by session delivery. * Like insertText, this command is revoked with the tool/destination lifetime. */ insertMention(recipient: Readonly<{ pubkey: string; name: string }>): boolean; - /** All-or-nothing insertion of a saved selection as individual mentions. */ + /** All-or-nothing insertion of a saved selection as individual mentions, + * or with `group` as one `@group` chip that notifies each of them. */ insertMentions( recipients: readonly Readonly<{ pubkey: string; name: string }>[], + group?: string, ): boolean; /** Replace all selected mentions in one undoable edit, preserving prose and focus. * An empty selection clears mentions. Rejected while editing a sent message. */ @@ -382,18 +384,33 @@ export type CompletionEdit = text: string; mention?: never; mentions?: never; + group?: never; pending?: never; }> | Readonly<{ mention: Readonly<{ pubkey: string; name: string }>; text?: never; mentions?: never; + group?: never; pending?: never; }> | Readonly<{ mentions: readonly Readonly<{ pubkey: string; name: string }>[]; text?: never; mention?: never; + group?: never; + pending?: never; + }> + /** One `@name` chip that notifies every one of `mentions` (1 to 32). In a + * message edit it inserts only the name, as edits never add recipients. */ + | Readonly<{ + group: Readonly<{ + name: string; + mentions: readonly Readonly<{ pubkey: string; name: string }>[]; + }>; + text?: never; + mention?: never; + mentions?: never; pending?: never; }> /** Host-only: the terminator typed over an undecided name. Never a suggestion's edit. */ @@ -402,6 +419,7 @@ export type CompletionEdit = text?: never; mention?: never; mentions?: never; + group?: never; }>; export type CompletionSuggestion = Readonly<{ id: string; diff --git a/src/features/messages/EditableInput.test.tsx b/src/features/messages/EditableInput.test.tsx index faa3a5ab5a..03554df65b 100644 --- a/src/features/messages/EditableInput.test.tsx +++ b/src/features/messages/EditableInput.test.tsx @@ -4823,7 +4823,7 @@ it("keeps retained recipients in place while adding and removing others", () => expect(h.input).toHaveValue("ask @Honey about X"); }); -it("rejects adding a recipient when retained duplicate mentions fill the limit", () => { +it("counts a person mentioned many times once against the recipient limit", () => { const first = { pubkey: "a".repeat(64), name: "Honey" }; const text = "@Honey ".repeat(32); const h = mount({ @@ -4840,9 +4840,9 @@ it("rejects adding a recipient when retained duplicate mentions fill the limit", first, { pubkey: "b".repeat(64), name: "Mary Jane" }, ]), - ).toBe(false), + ).toBe(true), ); - expect(h.input).toHaveValue(text); + expect(h.input).toHaveValue(`@Mary Jane ${text}`); }); it("toggles inline code, quote and code block with Slack's chords as well as Buzz's", async () => { @@ -4972,3 +4972,77 @@ describe("quoting timeline content", () => { expect(h.markdown()).toBe("keep"); }); }); + +describe("group chip", () => { + const ann = { pubkey: "1".repeat(64), name: "Ann" }; + const bo = { pubkey: "2".repeat(64), name: "Bo" }; + const crew = { label: "crew", members: [ann, bo] }; + const on = (start: number, end: number, ...people: (typeof ann)[]) => + people.map((person) => ({ ...person, label: "crew", start, end })); + + it("inserts one chip whose span names every member", () => { + const h = mount(); + act(() => expect(h.input.insertText("", crew)).toBe(true)); + expect(h.input).toHaveValue("@crew "); + expect(h.input.querySelectorAll("[data-mention]")).toHaveLength(1); + expect(h.draft().recipients).toEqual(on(0, 5, ann, bo)); + }); + + it("keeps its members through prose edits and a draft restore", async () => { + const h = mount(); + act(() => void h.input.insertText("", crew)); + await h.user.keyboard("hi"); + expect(h.draft().recipients).toEqual(on(0, 5, ann, bo)); + const restored = mount(h.draft()); + expect(restored.draft().recipients).toEqual(on(0, 5, ann, bo)); + expect(restored.input).toHaveValue("@crew hi"); + }); + + it("drops a removed member, and returns to prose with the last", () => { + const h = mount(); + act(() => void h.input.insertText("", crew)); + act(() => h.input.removeRecipient(ann.pubkey)); + expect(h.draft().recipients).toEqual(on(0, 5, bo)); + act(() => h.input.removeRecipient(bo.pubkey)); + expect(h.draft().recipients).toEqual([]); + expect(h.input).toHaveValue("@crew "); + }); + + it("returns to prose when typed text joins its name", async () => { + const h = mount(); + act(() => void h.input.insertText("", crew)); + act(() => h.input.setSelectionRange(5, 6)); + await h.user.keyboard("s"); + expect(h.input).toHaveValue("@crews"); + expect(h.draft().recipients).toEqual([]); + }); + + it("replaces its members as a whole: the span goes only with the last", () => { + const h = mount(); + act(() => void h.input.insertText("", crew)); + act(() => expect(h.input.replaceRecipients([bo])).toBe(true)); + expect(h.draft().recipients).toEqual(on(0, 5, bo)); + act(() => expect(h.input.replaceRecipients([ann])).toBe(true)); + expect(h.draft().recipients.map(({ pubkey }) => pubkey)).toEqual([ + ann.pubkey, + ]); + expect(h.input).toHaveValue("@Ann "); + }); + + it("counts distinct people against the 32-recipient cap", () => { + const people = Array.from({ length: 32 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: `P${i}`, + })); + const h = mount(); + act(() => + expect(h.input.insertText("", { label: "all", members: people })).toBe( + true, + ), + ); + // The same people again add no one, so the cap still holds. + act(() => expect(h.input.insertText("", people[0])).toBe(true)); + act(() => expect(h.input.insertText("", ann)).toBe(false)); + expect(new Set(h.draft().recipients.map((r) => r.pubkey)).size).toBe(32); + }); +}); diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index a3015cad86..b2d3d9e8c5 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -47,6 +47,10 @@ import { composerResource, brokenResources, resourceBlockingMarks, + composerGroup, + groupMembers, + tokenRecipients, + type ComposerGroup, } from "./composer-document"; import { scanMarkdown } from "../relay/message-content"; import type { @@ -94,6 +98,8 @@ import { pastedFiles, } from "./composer-clipboard"; import { + distinctRecipients, + MAX_RECIPIENTS, mentionBoundary, mentionDraft, type MentionDraft, @@ -708,12 +714,11 @@ export function EditableInput({ { source: safe.text.slice(item.start, item.end), editAsText: !!item.editAsText, - recipient: - safe.recipients.find( - (recipient) => - recipient.start === item.start && - recipient.end === item.end, - ) ?? null, + ...tokenRecipients( + safe.recipients, + safe.text.slice(item.start, item.end), + item, + ), }, null, state.doc.resolve(from).marks(), @@ -725,8 +730,26 @@ export function EditableInput({ // is editable again. Mention-boundary edits also remove invalidated // recipient provenance, and return a pending mention to its typed query. for (const token of next.tokens) { + // A group chip keeps the members the draft still mentions on its + // span, and returns to prose once none are left. + const group = composerGroup( + token.node.attrs.group, + token.node.attrs.source, + ); + const members = group + ? groupMembers(group, safe.recipients, token.start, token.end) + : []; + if (group && members.length) { + if (members.length < group.members.length) + tr.setNodeMarkup(tr.mapping.map(token.from), undefined, { + ...token.node.attrs, + group: { label: group.label, members }, + }); + continue; + } if ( - token.node.attrs.recipient + !group && + (token.node.attrs.recipient ? safe.recipients.some( (item) => item.start === token.start && item.end === token.end, @@ -738,7 +761,7 @@ export function EditableInput({ decorations.some( // A larger decoration has already adopted any tokens inside it. (item) => item.start <= token.start && item.end >= token.end, - ) + )) ) continue; const from = tr.mapping.map(token.from), @@ -851,7 +874,10 @@ export function EditableInput({ }; const insert = ( text: string, - recipient?: MentionRecipient | readonly MentionRecipient[], + recipient?: + | MentionRecipient + | readonly MentionRecipient[] + | ComposerGroup, range?: { start: number; end: number }, terminator?: string, focus = true, @@ -899,7 +925,25 @@ export function EditableInput({ .filter((mark) => mark.type !== composerSchema.marks.recipient); text = text.replace(/\r\n?/g, "\n"); const tr = closeHistory(editor.state.tr); - if (recipient) { + if (recipient && "members" in recipient) { + const group = composerGroup(recipient, `@${recipient.label}`); + if (!group) return false; + // In code a group is only its name: code never carries recipients. + tr.replaceWith( + from, + to, + Fragment.fromArray([ + $from.parent.type.spec.code + ? composerSchema.text(`@${group.label}`) + : composerSchema.nodes.token.create( + { source: `@${group.label}`, group, editAsText: false }, + null, + marks, + ), + composerSchema.text(" ", marks), + ]), + ); + } else if (recipient) { const recipients: readonly MentionRecipient[] = Array.isArray(recipient) ? recipient : [recipient as MentionRecipient]; @@ -934,8 +978,9 @@ export function EditableInput({ : editor.state.selection.map(tr.doc, tr.mapping), ); if ( - Array.isArray(recipient) && - projectComposerDocument(tr.doc).draft.recipients.length > 32 + recipient && + distinctRecipients(projectComposerDocument(tr.doc).draft.recipients) > + MAX_RECIPIENTS ) return false; if ( @@ -1096,11 +1141,31 @@ export function EditableInput({ return true; const added = recipients.filter((person) => !existing.has(person.pubkey)); const tr = closeHistory(editor.state.tr); - for (const person of [...source.draft.recipients].reverse()) { - if (requested.has(person.pubkey)) continue; - const end = - person.end + (source.draft.text[person.end] === " " ? 1 : 0); - tr.delete(source.position(person.start), source.position(end, -1)); + // A group's members share one span: it goes only with its last member. + const spans = new Map(); + for (const person of source.draft.recipients) + spans.set(person.start, [...(spans.get(person.start) ?? []), person]); + for (const [start, people] of [...spans].reverse()) { + const span = people[0]; + if (!span) continue; + const kept = people.filter((person) => requested.has(person.pubkey)); + if (kept.length === people.length) continue; + const token = source.tokens.find((item) => item.start === start); + const group = + token && + composerGroup(token.node.attrs.group, token.node.attrs.source); + if (token && group && kept.length) { + tr.setNodeMarkup(token.from, undefined, { + ...token.node.attrs, + group: { + label: group.label, + members: group.members.filter((m) => requested.has(m.pubkey)), + }, + }); + continue; + } + const end = span.end + (source.draft.text[span.end] === " " ? 1 : 0); + tr.delete(source.position(start), source.position(end, -1)); } if (added.length) { const at = Selection.atStart(tr.doc).from; @@ -1125,7 +1190,7 @@ export function EditableInput({ } const next = projectComposerDocument(tr.doc).draft; if ( - next.recipients.length > 32 || + distinctRecipients(next.recipients) > MAX_RECIPIENTS || composerMarkdown(next).length > current.current.maxLength ) return false; @@ -1681,7 +1746,7 @@ export function EditableInput({ if (!accept) return; const { tokens, draft } = projection(); const tr = editor.state.tr; - let count = draft.recipients.length; + const counted = new Set(draft.recipients.map((item) => item.pubkey)); // Later tokens first: earlier positions stay valid, and each boundary // check sees the text that now follows the token. for (const token of [...tokens].reverse()) { @@ -1695,7 +1760,7 @@ export function EditableInput({ const identity = identityLink(token.node.attrs.source); if ( !identity || - count >= 32 || + (!counted.has(identity.pubkey) && counted.size >= MAX_RECIPIENTS) || !mentionBoundary( projectComposerDocument(tr.doc).draft.text, token.end, @@ -1713,7 +1778,7 @@ export function EditableInput({ token.node.marks, ), ); - count++; + counted.add(recipient.pubkey); } if (tr.docChanged) editor.dispatch(tr); }; @@ -2580,6 +2645,18 @@ export function EditableInput({ ...node.attrs, recipient: null, }); + // A group drops the member, and returns to prose with the last. + const group = + node.type.name === "token" + ? composerGroup(node.attrs.group, node.attrs.source) + : null; + if (group?.members.some((m) => m.pubkey === pubkey)) { + const members = group.members.filter((m) => m.pubkey !== pubkey); + tr.setNodeMarkup(pos, undefined, { + ...node.attrs, + group: members.length ? { label: group.label, members } : null, + }); + } const mark = composerSchema.marks.recipient.isInSet(node.marks); if (mark?.attrs.pubkey === pubkey) tr.removeMark(pos, pos + node.nodeSize, mark); diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 38c1ab098c..b837282b39 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -8181,9 +8181,15 @@ it("rejects overlong and over-limit tool edits without changing accepted intent" expect(h.input()).toHaveValue("x".repeat(15999)); expect(screen.getByRole("alert")).toHaveTextContent("too long"); h.fill(""); + const people = Array.from({ length: 32 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: `P${i}`, + })); act(() => { - for (let i = 0; i < 32; i++) - expect(h.commands().insertMention(first)).toBe(true); + for (const person of people) + expect(h.commands().insertMention(person)).toBe(true); + // Someone already mentioned adds no recipient. + expect(h.commands().insertMention(people[7] ?? first)).toBe(true); }); const before = h.input().value; act(() => { @@ -12606,6 +12612,49 @@ it("batch insertion rejects an unavailable member atomically and does not send o expect(h.messages.send).not.toHaveBeenCalled(); expect(screen.getByRole("alert")).toHaveTextContent("no longer available"); }); +it("a group edit inserts one chip and sends each member once", async () => { + const h = mount(); + h.fill("!Crew"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [ + { + id: "team", + label: "Crew", + edit: { group: { name: "Crew", mentions: [first, second, first] } }, + }, + ], + }); + }); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("@Crew "); + // A member also mentioned alone is still one recipient. + act(() => void h.commands().insertMention(first)); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(new Set(h.messages.send.mock.calls[0]?.[2])).toEqual( + new Set([first.pubkey, second.pubkey]), + ); +}); +it("a group edit with an unavailable member adds nothing", async () => { + const h = mount({ inviteAgents: true }); + const unavailable = { pubkey: "c".repeat(64), name: "Missing" }; + h.fill("!Crew"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [ + { + id: "team", + label: "Crew", + edit: { group: { name: "Crew", mentions: [first, unavailable] } }, + }, + ], + }); + }); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("!Crew"); + expect(screen.getByRole("alert")).toHaveTextContent("no longer available"); +}); it.each(["disabled", "retarget", "unmount"])( "revokes batch commands after %s", (transition) => { @@ -16669,7 +16718,10 @@ it.each([ act(() => { h.input().insertText( "", - Array.from({ length: 32 }, () => second), + Array.from({ length: 32 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: `P${i}`, + })), ); }), alert: diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index d7d0bbca7e..bb0cf0c891 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -141,11 +141,13 @@ import styles from "./Messages.module.css"; import { messageViewKey } from "./view-key"; import { isEmojiOnly, usesLargeEmojiPresentation } from "./emoji-size"; import { + distinctRecipients, legacyFollowupDraft, MAX_DRAFT_GIFS, mentionBoundary, mentionDraft, stageableGif, + withoutSpans, type MentionDraft, type MentionRecipient, } from "./mention-draft"; @@ -1799,7 +1801,10 @@ function Composer({ ); return false; } - if (recipient && valueRef.current.recipients.length >= 32) { + if ( + recipient && + distinctRecipients([...valueRef.current.recipients, recipient]) > 32 + ) { setError("Choose at most 32 recipients"); return false; } @@ -1899,7 +1904,7 @@ function Composer({ ? "unresolved" : !admits()(recipient.pubkey) ? "unavailable" - : valueRef.current.recipients.length >= 32 + : distinctRecipients([...valueRef.current.recipients, recipient]) > 32 ? "limit" : undefined; const accepted = @@ -2160,6 +2165,69 @@ function Composer({ setError(undefined); return true; } + /** One chip for the whole group, at `range` or, from a tool, the caret. */ + function insertGroup( + group: Readonly<{ name: string; mentions: readonly MentionRecipient[] }>, + range?: CompletionQuery, + ) { + if ( + !group || + typeof group.name !== "string" || + !group.name.trim() || + !Array.isArray(group.mentions) || + !group.mentions.length || + group.mentions.some( + (person) => + !person || + typeof person.pubkey !== "string" || + !/^[0-9a-f]{64}$/.test(person.pubkey) || + typeof person.name !== "string" || + !person.name.trim(), + ) + ) + return false; + // Message edits only add references, never new notification intent. + if (editing.target) return insert(`@${group.name} `, undefined, range); + if ( + !permitted.current || + editingDisabled || + !outbox?.supports(9) || + !input.current?.isConnected || + input.current.disabled || + input.current.readOnly + ) + return false; + const members = [ + ...new Map( + group.mentions.map(({ pubkey, name }) => [pubkey, { pubkey, name }]), + ).values(), + ]; + const admitted = admits(); + if (members.some((person) => !admitted(person.pubkey))) { + setError( + "A group member is no longer available. Refresh choices before trying again.", + ); + return false; + } + const chip = { label: group.name, members }; + if ( + !(solo && !range + ? keepProseCaret( + (at) => !!input.current?.insertText("", chip, at, undefined, false), + ) + : input.current.insertText("", chip, range)) + ) { + setError( + "The group would exceed the message length or 32-recipient limit. Nothing was added.", + ); + return false; + } + completion.invalidate(); + for (const person of members) + rememberMention(session, channelId, person.pubkey); + setError(undefined); + return true; + } function replaceRecipients(recipients: readonly MentionRecipient[]) { if ( !Array.isArray(recipients) || @@ -2193,13 +2261,10 @@ function Composer({ } function replaceRecipientsIfEmpty(recipients: readonly MentionRecipient[]) { const current = valueRef.current; - const prose = [...current.recipients] - .sort((a, b) => b.start - a.start) - .reduce( - (text, tag) => text.slice(0, tag.start) + text.slice(tag.end), - current.text, - ); - return !prose.trim() && replaceRecipients(recipients); + return ( + !withoutSpans(current.text, current.recipients).trim() && + replaceRecipients(recipients) + ); } function insertResource(resource: ComposerResource): true | string { if ( @@ -2258,6 +2323,7 @@ function Composer({ setError(undefined); return true; } + if ("group" in edit && edit.group) return insertGroup(edit.group, query); if ("mentions" in edit && edit.mentions) return insertMentions(edit.mentions, query); if ("mention" in edit && edit.mention) @@ -3883,7 +3949,11 @@ function Composer({ audience={audience} insertText={insertToolText} insertMention={insertMention} - insertMentions={insertMentions} + insertMentions={(people, group) => + group === undefined + ? insertMentions(people) + : insertGroup({ name: group, mentions: people }) + } replaceRecipients={replaceRecipients} replaceRecipientsIfEmpty={replaceRecipientsIfEmpty} insertResource={insertResource} diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index 03c9093468..a87f0e2d54 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -7,6 +7,7 @@ import { useLayoutEffect, useMemo, useRef } from "react"; import { useNamesRevision } from "../identity-names/react"; import { useListedChannel } from "../relay/listed-channel"; import { InlineChip } from "../../shared/design-system/ui/InlineChip"; +import { UsersIcon } from "../../shared/design-system/icons/index"; import type { ConversationExtensions } from "../conversation/contracts"; import type { Profile } from "../relay/contracts"; import type { CustomEmoji } from "../relay/emoji"; @@ -106,6 +107,34 @@ const TokenChip = memo(function TokenChip({ ); }); +/** One chip for a group mention: its `@label`, with the members it notifies + * in the accessible name and tooltip rather than in the message. */ +const GroupChip = memo(function GroupChip({ + label, + members, +}: { + label: string; + members: string; +}) { + return ( + + + ); +}); + /** Decorations never change source text or infer notification recipients from names. */ export function RichComposerInput({ draft, @@ -315,8 +344,20 @@ export function RichComposerInput({ ...(mention ? { mention } : {}), }); }; - for (const recipient of draft.recipients) + // A group's members share its span; the first claims it for the chip. + const groups = new Map(); + for (const recipient of draft.recipients) { + if (recipient.label !== undefined) { + const group = groups.get(recipient.start); + if (group) group.members.push(recipient.pubkey); + else + groups.set(recipient.start, { + label: recipient.label, + members: [recipient.pubkey], + }); + } add(recipient.start, recipient.end, recipient.pubkey); + } // Identity links are display references, not new notification recipients. // Keep their exact source token so editing surrounding prose preserves it. const profileLinks = new Map(); @@ -380,6 +421,21 @@ export function RichComposerInput({ const preview = gifPreviews.get(start); if (preview && preview.end === end && !mention) return { start, end, editAsText: false, content: preview.content }; + const group = mention ? groups.get(start) : undefined; + if (group) + return { + start, + end, + editAsText: false, + content: ( + labels.get(key) ?? key) + .join(", ")} + /> + ), + }; const profile = mention ? undefined : profileLinks.get(start); const identity = mention ?? profile?.pubkey; const label = profile?.label ?? draft.text.slice(start + 1, end); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 9575cc39b9..a2940cc2a6 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -9,6 +9,7 @@ import { composerLinkUrl } from "./composer-link"; import { scanMarkdown } from "../relay/message-content"; import type { MentionDraft, + MentionRecipient, DraftRecipient, PendingMention, } from "./mention-draft"; @@ -102,6 +103,10 @@ export const composerSchema = new Schema< attrs: { source: {}, recipient: { default: null }, + /** `{ label, members }` for one chip that mentions several people: + * `source` is `@label` and `recipient` stays null, so paths that read + * only `recipient` (code, clipboard, blocks) see plain `@label`. */ + group: { default: null }, /** Host-owned `{ uri, label }`; valid only while `source` is its link. */ resource: { default: null }, /** A `ComposerToken` whose label is `source`; never a recipient. */ @@ -212,6 +217,92 @@ export function markdownRanges(text: string) { return { literal }; } +export type ComposerGroup = Readonly<{ + label: string; + members: readonly MentionRecipient[]; +}>; +/** A group chip's attribute as the editor may trust it: a label its `source` + * shows, and 1 to 32 distinct, well-formed members. Anything else is prose. */ +export function composerGroup( + value: unknown, + source: unknown, +): ComposerGroup | null { + if (!value || typeof value !== "object") return null; + const { label, members } = value as Record; + if ( + typeof label !== "string" || + !label.trim() || + source !== `@${label}` || + !Array.isArray(members) || + !members.length || + members.length > 32 + ) + return null; + const keys = new Set(); + for (const member of members) { + if ( + !member || + typeof member.pubkey !== "string" || + !/^[0-9a-f]{64}$/.test(member.pubkey) || + typeof member.name !== "string" || + !member.name.trim() || + keys.has(member.pubkey) + ) + return null; + keys.add(member.pubkey); + } + return value as ComposerGroup; +} +/** The members of a group chip that the draft still mentions on its range. */ +export function groupMembers( + group: ComposerGroup, + recipients: readonly DraftRecipient[], + start: number, + end: number, +): MentionRecipient[] { + return group.members.flatMap((member) => + recipients.some( + (item) => + item.pubkey === member.pubkey && + item.name === member.name && + item.label === group.label && + item.start === start && + item.end === end, + ) + ? [{ pubkey: member.pubkey, name: member.name }] + : [], + ); +} +/** A source token's recipient attributes from the draft's recipients on its + * range: every labelled one as a group, else the one recipient. */ +export function tokenRecipients( + recipients: readonly DraftRecipient[], + source: string, + range: { start: number; end: number }, +): { recipient: MentionRecipient | null; group: ComposerGroup | null } { + const on = recipients.filter( + (item) => item.start === range.start && item.end === range.end, + ); + const label = on.find((item) => item.label !== undefined)?.label; + if (label !== undefined) { + const members = on + .filter((item) => item.label === label) + .map(({ pubkey, name }) => ({ pubkey, name })); + const group = composerGroup( + { + label, + members: [...new Map(members.map((m) => [m.pubkey, m])).values()], + }, + source, + ); + return { recipient: null, group }; + } + const one = on[0]; + return { + recipient: one ? { pubkey: one.pubkey, name: one.name } : null, + group: null, + }; +} /** Draft text stays the editing/completion coordinate space. Formatting metadata * is local authoring state; message publication serializes it separately. */ export function readComposerDocument( @@ -246,6 +337,10 @@ export function readComposerDocument( return composerSchema.text(node.attrs.source, marks); const resource = composerResource(node.attrs.resource); const semantic = composerToken(node.attrs.semantic); + const group = composerGroup(node.attrs.group, node.attrs.source); + const members = group + ? groupMembers(group, draft.recipients, start, end) + : []; return node.type.create( { ...node.attrs, @@ -254,9 +349,11 @@ export function readComposerDocument( ? semantic : null, recipient: - node.attrs.recipient && valid(node.attrs.recipient) + !group && node.attrs.recipient && valid(node.attrs.recipient) ? node.attrs.recipient : null, + group: + group && members.length ? { label: group.label, members } : null, resource: resource && resource.source === node.attrs.source && @@ -287,14 +384,12 @@ export function readComposerDocument( while (offset < draft.text.length) { const token = tokens.find((token) => token.start === offset); if (token) { + const source = draft.text.slice(token.start, token.end); nodes.push( composerSchema.nodes.token.create({ - source: draft.text.slice(token.start, token.end), + source, editAsText: !!token.editAsText, - recipient: - draft.recipients.find( - (item) => item.start === token.start && item.end === token.end, - ) ?? null, + ...tokenRecipients(draft.recipients, source, token), }), ); offset = token.end; @@ -483,7 +578,17 @@ function project(doc: EditorNode) { node, editAsText: node.attrs.editAsText, }); - if (node.attrs.recipient) + const group = composerGroup(node.attrs.group, node.attrs.source); + if (group) + for (const { pubkey, name } of group.members) + recipients.push({ + pubkey, + name, + label: group.label, + start, + end: text.length, + }); + else if (node.attrs.recipient) recipients.push({ ...node.attrs.recipient, start, end: text.length }); if (node.attrs.pending) pending.push({ ...node.attrs.pending, start, end: text.length }); diff --git a/src/features/messages/composer-dom.ts b/src/features/messages/composer-dom.ts index 0ff2e9b90d..3ebf5c42e1 100644 --- a/src/features/messages/composer-dom.ts +++ b/src/features/messages/composer-dom.ts @@ -1,4 +1,5 @@ import type { MentionDraft, MentionRecipient } from "./mention-draft"; +import type { ComposerGroup } from "./composer-document"; import type { ComposerResource } from "../conversation/contracts"; import type { ComposerToken } from "./composer-token"; import type { AnnotationMark } from "./composer-annotations"; @@ -104,7 +105,8 @@ export type ComposerInputElement = HTMLDivElement & { setSelectionRange(start: number, end: number, direction?: string): void; insertText( text: string, - recipient?: MentionRecipient | readonly MentionRecipient[], + /** One chip each, or one chip for a whole group. */ + recipient?: MentionRecipient | readonly MentionRecipient[] | ComposerGroup, range?: { start: number; end: number }, /** The key typed to end the query. A closing colon is recorded before * conversion for one-step undo; after recipients, it takes the place of diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 645ddb4e27..7e722f67ce 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -252,3 +252,46 @@ it("sends chips of different keys sharing a name as `@Name ()`, others bare ), ).toBe(`@Honey (${"a".repeat(64)}) \`@Honey\``); }); +it("a group's members are kept on a span that shows the group's label", () => { + const crew = (label: string, text = "@crew hi") => + mentionDraft({ + text, + recipients: [ + { ...first, label, start: 0, end: 5 }, + { ...second, label, start: 0, end: 5 }, + ], + }); + expect(crew("crew").recipients).toEqual([ + { ...first, label: "crew", start: 0, end: 5 }, + { ...second, label: "crew", start: 0, end: 5 }, + ]); + // A label the span does not show, or a name joined by text, is prose. + expect(crew("team").recipients).toEqual([]); + expect(crew("crew", "@crews hi").recipients).toEqual([]); + // The group's span is removed once, so prose after it still counts. + expect(addressingOnly(crew("crew", "@crew "))).toBe(true); + expect(addressingOnly(crew("crew"))).toBe(false); +}); +it("the recipient cap counts distinct people, keeping each one's spans", () => { + const people = Array.from({ length: 33 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: "x", + })); + const text = "@all @x"; + const restored = mentionDraft({ + text, + recipients: [ + ...people.map((person) => ({ + ...person, + label: "all", + start: 0, + end: 4, + })), + { ...people[0], start: 5, end: 7 }, + ], + }).recipients; + expect(new Set(restored.map((item) => item.pubkey)).size).toBe(32); + expect( + restored.filter((item) => item.pubkey === people[0]?.pubkey), + ).toHaveLength(2); +}); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 34260933ee..68bb886a10 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -5,8 +5,43 @@ import { } from "./composer-document"; export type MentionRecipient = Readonly<{ pubkey: string; name: string }>; +/** One recipient on a span. A group chip projects one per member, each with + * the group's `label`: then the span reads `@label` instead of `@name`. */ export type DraftRecipient = MentionRecipient & - Readonly<{ start: number; end: number }>; + Readonly<{ start: number; end: number; label?: string }>; +/** A message notifies at most this many distinct people. */ +export const MAX_RECIPIENTS = 32; +/** The distinct people `recipients` mention; a group shares a span with its + * members, and two chips can name the same person. */ +export function distinctRecipients( + recipients: readonly MentionRecipient[], +): number { + return new Set(recipients.map((item) => item.pubkey)).size; +} +/** `recipients` up to the first `MAX_RECIPIENTS` distinct people, keeping + * every span of each one it keeps. */ +function capRecipients(recipients: readonly T[]) { + const kept = new Set(); + return recipients.filter((item) => { + if (!kept.has(item.pubkey) && kept.size >= MAX_RECIPIENTS) return false; + kept.add(item.pubkey); + return true; + }); +} +/** `text` without the spans `recipients` cover; a group's span counts once. */ +export function withoutSpans( + text: string, + recipients: readonly Readonly<{ start: number; end: number }>[], +) { + const spans = [ + ...new Map( + recipients.map((item) => [`${item.start}:${item.end}`, item]), + ).values(), + ].sort((a, b) => b.start - a.start); + for (const { start, end } of spans) + text = text.slice(0, start) + text.slice(end); + return text; +} // Serializable draft metadata must not expose editor implementation types to plugins. export type ComposerSnapshot = { version: 1; content: unknown }; /** A name Space committed before the chooser could decide. The editor resolves @@ -71,11 +106,13 @@ export function mentionDraft(value: unknown): MentionDraft { /^[0-9a-f]{64}$/.test(item.pubkey) && typeof item.name === "string" && !!item.name.trim() && + (item.label === undefined || + (typeof item.label === "string" && !!item.label.trim())) && Number.isInteger(item.start) && Number.isInteger(item.end) && item.start >= 0 && item.end <= text.length && - text.slice(item.start, item.end) === `@${item.name}` && + text.slice(item.start, item.end) === `@${item.label ?? item.name}` && mentionBoundary(text, item.end), ) : []; @@ -102,9 +139,12 @@ export function mentionDraft(value: unknown): MentionDraft { } : {}), ...(doc ? { document: document as ComposerSnapshot } : {}), - recipients: safe - .slice(0, 32) - .map(({ pubkey, name, start, end }) => ({ pubkey, name, start, end })), + recipients: capRecipients(safe).map( + ({ pubkey, name, label, start, end }) => + label === undefined + ? { pubkey, name, start, end } + : { pubkey, name, label, start, end }, + ), }; } /** What counts as a draft everywhere: text, an attached chat or GIF, or `files`. @@ -129,12 +169,7 @@ export function legacyFollowupDraft(value: MentionDraft): boolean { export function addressingOnly(value: MentionDraft): boolean { if (!value.recipients.length || value.chatCards?.length || value.gifs?.length) return false; - let rest = value.text; - for (const { start, end } of [...value.recipients].sort( - (a, b) => b.start - a.start, - )) - rest = rest.slice(0, start) + rest.slice(end); - return !rest.trim(); + return !withoutSpans(value.text, value.recipients).trim(); } /** Prefill exact, already-selected identities; never infer recipients from prose. */ export function followupDraft( diff --git a/src/features/relay/messages.ts b/src/features/relay/messages.ts index feacda6b43..3bff96aa71 100644 --- a/src/features/relay/messages.ts +++ b/src/features/relay/messages.ts @@ -80,12 +80,10 @@ export function createMessages( return value; }; const mentionTags = (channelId: string, pubkeys: readonly string[]) => { - if ( - pubkeys.length > 32 || - pubkeys.some((key) => !/^[0-9a-f]{64}$/.test(key)) - ) - throw new Error("Choose at most 32 valid mention recipients"); + // Two chips can name one person, as a group and its member can. const unique = [...new Set(pubkeys)]; + if (unique.length > 32 || unique.some((key) => !/^[0-9a-f]{64}$/.test(key))) + throw new Error("Choose at most 32 valid mention recipients"); validateMentions(channelId, unique); return unique.map((key) => ["p", key]); }; From 125b6d02c687c7653fd0bede3a776016b27533ec Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 17:51:31 -0500 Subject: [PATCH 04/21] fix(mentions): group chips in chat titles, inline code and references - A new chat's title strips a leading group chip: its members share one `@label` span. - A group inserted inside inline code is only its name, as in a code block. - `referenceTags` dedupes before its 32 check, like `mentionTags`. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/EditableInput.test.tsx | 8 ++++++++ src/features/messages/EditableInput.tsx | 7 +++++-- src/features/relay/messages.ts | 8 +++----- src/features/solo/chat-title.test.ts | 20 ++++++++++++++++++++ src/features/solo/chat-title.ts | 4 +++- 5 files changed, 39 insertions(+), 8 deletions(-) diff --git a/src/features/messages/EditableInput.test.tsx b/src/features/messages/EditableInput.test.tsx index 03554df65b..6c7bf6b498 100644 --- a/src/features/messages/EditableInput.test.tsx +++ b/src/features/messages/EditableInput.test.tsx @@ -5029,6 +5029,14 @@ describe("group chip", () => { expect(h.input).toHaveValue("@Ann "); }); + it("is only its name in inline code", () => { + const h = mount(); + act(() => h.input.toggleFormat("code")); + act(() => expect(h.input.insertText("", crew)).toBe(true)); + expect(h.input).toHaveValue("@crew "); + expect(h.draft().recipients).toEqual([]); + }); + it("counts distinct people against the 32-recipient cap", () => { const people = Array.from({ length: 32 }, (_, i) => ({ pubkey: i.toString(16).padStart(64, "0"), diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index b2d3d9e8c5..4e53394024 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -929,12 +929,15 @@ export function EditableInput({ const group = composerGroup(recipient, `@${recipient.label}`); if (!group) return false; // In code a group is only its name: code never carries recipients. + const code = + $from.parent.type.spec.code || + marks.some((mark) => mark.type === composerSchema.marks.code); tr.replaceWith( from, to, Fragment.fromArray([ - $from.parent.type.spec.code - ? composerSchema.text(`@${group.label}`) + code + ? composerSchema.text(`@${group.label}`, marks) : composerSchema.nodes.token.create( { source: `@${group.label}`, group, editAsText: false }, null, diff --git a/src/features/relay/messages.ts b/src/features/relay/messages.ts index 3bff96aa71..bf18ef0685 100644 --- a/src/features/relay/messages.ts +++ b/src/features/relay/messages.ts @@ -104,12 +104,10 @@ export function createMessages( ]; }; const referenceTags = (pubkeys: readonly string[]) => { - if ( - pubkeys.length > 32 || - pubkeys.some((key) => !/^[0-9a-f]{64}$/.test(key)) - ) + const unique = [...new Set(pubkeys)]; + if (unique.length > 32 || unique.some((key) => !/^[0-9a-f]{64}$/.test(key))) throw new Error("Choose at most 32 valid mention references"); - return [...new Set(pubkeys)].map((key) => ["mention", key]); + return unique.map((key) => ["mention", key]); }; const pickTags = ( channelId: string, diff --git a/src/features/solo/chat-title.test.ts b/src/features/solo/chat-title.test.ts index a8009285c8..b5bd367b87 100644 --- a/src/features/solo/chat-title.test.ts +++ b/src/features/solo/chat-title.test.ts @@ -74,3 +74,23 @@ it("drops leading namesake tags with their full-key qualifiers", () => { ); expect(startingChatTitle(draft)).toBe("fix the build"); }); + +it("strips a leading group chip, whose members share its span", () => { + const member = (pubkey: string, name: string) => ({ + pubkey, + name, + label: "crew", + start: 0, + end: 5, + }); + expect( + startingChatTitle({ + text: "@crew @Ann plan the launch", + recipients: [ + member("1".repeat(64), "Ann"), + member("2".repeat(64), "Bo"), + { pubkey: "1".repeat(64), name: "Ann", start: 6, end: 10 }, + ], + }), + ).toBe("plan the launch"); +}); diff --git a/src/features/solo/chat-title.ts b/src/features/solo/chat-title.ts index 1ecb010d09..bdb84b18bf 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,13 +35,15 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { + // A group's members share its span; it was stripped with the first. + if (recipient.end === draftStart) continue; if ( recipient.start < draftStart || draft.text.slice(draftStart, recipient.start).trim() ) break; const leading = text.slice(start).match(/^\s*/)?.[0].length ?? 0; - const tag = `@${recipient.name}`; + const tag = `@${recipient.label ?? recipient.name}`; if (!text.startsWith(tag, start + leading)) break; start += leading + tag.length; // A namesake is sent with its full key; that qualifier is part of the tag. From 929434649f399b03697b4b6bf5baffb8ee793a45 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 18:09:10 -0500 Subject: [PATCH 05/21] fix(mentions): a group stays plain text in Markdown and inline code A team picked inside backticks inserts only `@name` with no recipients, and typing after a group name in inline code stays in code. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/EditableInput.test.tsx | 1 + src/features/messages/EditableInput.tsx | 3 ++- .../messages/MessageComposer.test.tsx | 18 +++++++++++++ src/features/messages/MessageComposer.tsx | 27 ++++++++++--------- 4 files changed, 36 insertions(+), 13 deletions(-) diff --git a/src/features/messages/EditableInput.test.tsx b/src/features/messages/EditableInput.test.tsx index 6c7bf6b498..3cb988ba71 100644 --- a/src/features/messages/EditableInput.test.tsx +++ b/src/features/messages/EditableInput.test.tsx @@ -5035,6 +5035,7 @@ describe("group chip", () => { act(() => expect(h.input.insertText("", crew)).toBe(true)); expect(h.input).toHaveValue("@crew "); expect(h.draft().recipients).toEqual([]); + expect(h.formats()).toContain("code"); }); it("counts distinct people against the 32-recipient cap", () => { diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index 4e53394024..a3ff7e0216 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -986,8 +986,9 @@ export function EditableInput({ MAX_RECIPIENTS ) return false; + // Typing on in inline code stays in code, after text or a group's name. if ( - text && + (text || (recipient && "members" in recipient)) && composerSchema.marks.code.isInSet(editor.state.storedMarks ?? []) ) tr.setStoredMarks(marks); diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index b837282b39..de5b205809 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -12636,6 +12636,24 @@ it("a group edit inserts one chip and sends each member once", async () => { new Set([first.pubkey, second.pubkey]), ); }); +it("a group picked inside Markdown code is only its name", async () => { + const h = mount(); + h.fill("!`Crew`"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [ + { + id: "team", + label: "Crew", + edit: { group: { name: "Crew", mentions: [first, second] } }, + }, + ], + }); + }); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("@Crew "); + expect(h.commands().recipients).toEqual([]); +}); it("a group edit with an unavailable member adds nothing", async () => { const h = mount({ inviteAgents: true }); const unavailable = { pubkey: "c".repeat(64), name: "Missing" }; diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index bb0cf0c891..88f7fa89ad 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -2288,21 +2288,20 @@ function Composer({ valueRef.current.text !== observation.text ) return false; - // A typed terminator (Space, closing punctuation after a name, the closing - // emoji colon) stays literal in code. Tab, Enter and a click are not typed. - const typed = key?.length === 1 ? key : undefined; - if (typed) { + const inCode = () => { const doc = readComposerSnapshot(valueRef.current.document); const context = doc ? composerMarkdownContext(doc) : { text: observation.text, protected: [] }; - if ( - [...context.protected, ...markdownRanges(context.text).literal].some( - (r) => query.start < r.end && query.end > r.start, - ) - ) - return false; - } + return [ + ...context.protected, + ...markdownRanges(context.text).literal, + ].some((r) => query.start < r.end && query.end > r.start); + }; + // A typed terminator (Space, closing punctuation after a name, the closing + // emoji colon) stays literal in code. Tab, Enter and a click are not typed. + const typed = key?.length === 1 ? key : undefined; + if (typed && inCode()) return false; const chosen = chosenWorkspace(edit); if (chosen !== undefined) { // The chat's workspace leaves no text behind; the control shows it. @@ -2323,7 +2322,11 @@ function Composer({ setError(undefined); return true; } - if ("group" in edit && edit.group) return insertGroup(edit.group, query); + // In code a group is only its name: code never carries recipients. + if ("group" in edit && edit.group) + return inCode() + ? insert(`@${edit.group.name} `, undefined, query) + : insertGroup(edit.group, query); if ("mentions" in edit && edit.mentions) return insertMentions(edit.mentions, query); if ("mention" in edit && edit.mention) From 81559c82f4bee569eae1b9e871c897f52a18c19e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 18:29:12 -0500 Subject: [PATCH 06/21] fix(mentions): send each person once, keep picked groups plain in code, send group labels literally A message's mention keys and its prompts now list each person once, so a group plus a member named alone cannot exceed the Huddle window's key check or ask twice. A group picked from the toolbar inside Markdown backticks inserts only its name, as one picked by completion does. A group's label after the @ is escaped like literal text, so a team named *core* reads as typed. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 21 +++++-- src/features/messages/MessageComposer.tsx | 55 +++++++++++-------- .../messages/composer-document.test.ts | 14 +++++ src/features/messages/composer-markdown.ts | 6 +- 4 files changed, 68 insertions(+), 28 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index de5b205809..273e6ed052 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -7631,7 +7631,7 @@ it("qualifies both namesakes retroactively without changing source and removes q expect(h.messages.send).toHaveBeenCalledWith( "channel", "@Honey @Honey ", - [first.pubkey, first.pubkey], + [first.pubkey], [], ); }); @@ -8734,10 +8734,10 @@ it.each([undefined, "root"])( h.submit(); expect(h.input()).toHaveValue("@Honey @Honey @Honey hello"); h.submit(); + // Two chips for one person notify once. expect(send.mock.calls.at(-1)?.[threadRootId ? 3 : 2]).toEqual([ first.pubkey, second.pubkey, - second.pubkey, ]); expect(h.input()).toHaveValue("@Honey "); const recipients = screen.getByRole("region", { @@ -12632,9 +12632,10 @@ it("a group edit inserts one chip and sends each member once", async () => { act(() => void h.commands().insertMention(first)); h.submit(); await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); - expect(new Set(h.messages.send.mock.calls[0]?.[2])).toEqual( - new Set([first.pubkey, second.pubkey]), - ); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([ + first.pubkey, + second.pubkey, + ]); }); it("a group picked inside Markdown code is only its name", async () => { const h = mount(); @@ -12654,6 +12655,16 @@ it("a group picked inside Markdown code is only its name", async () => { expect(h.input()).toHaveValue("@Crew "); expect(h.commands().recipients).toEqual([]); }); +it("a group from the picker inside Markdown code is only its name", () => { + const h = mount(); + h.fill("`ab`"); + act(() => h.input().setSelectionRange(2, 2)); + act(() => + expect(h.commands().insertMentions([first, second], "Crew")).toBe(true), + ); + expect(h.input()).toHaveValue("`a@Crew b`"); + expect(h.commands().recipients).toEqual([]); +}); it("a group edit with an unavailable member adds nothing", async () => { const h = mount({ inviteAgents: true }); const unavailable = { pubkey: "c".repeat(64), name: "Missing" }; diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 88f7fa89ad..f52c2b6839 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -2165,6 +2165,17 @@ function Composer({ setError(undefined); return true; } + /** Whether `range` overlaps code: a code block, inline code, or Markdown + * code the draft's text spells with backticks. */ + function inMarkdownCode(range: Readonly<{ start: number; end: number }>) { + const doc = readComposerSnapshot(valueRef.current.document); + const context = doc + ? composerMarkdownContext(doc) + : { text: valueRef.current.text, protected: [] }; + return [...context.protected, ...markdownRanges(context.text).literal].some( + (r) => range.start < r.end && range.end > r.start, + ); + } /** One chip for the whole group, at `range` or, from a tool, the caret. */ function insertGroup( group: Readonly<{ name: string; mentions: readonly MentionRecipient[] }>, @@ -2186,8 +2197,14 @@ function Composer({ ) ) return false; - // Message edits only add references, never new notification intent. - if (editing.target) return insert(`@${group.name} `, undefined, range); + // Message edits only add references, never new notification intent, and + // in code a group is only its name: code never carries recipients. + const at = range ?? { + start: input.current?.selectionStart ?? valueRef.current.text.length, + end: input.current?.selectionEnd ?? valueRef.current.text.length, + }; + if (editing.target || (!(solo && !range) && inMarkdownCode(at))) + return insert(`@${group.name} `, undefined, range); if ( !permitted.current || editingDisabled || @@ -2288,20 +2305,10 @@ function Composer({ valueRef.current.text !== observation.text ) return false; - const inCode = () => { - const doc = readComposerSnapshot(valueRef.current.document); - const context = doc - ? composerMarkdownContext(doc) - : { text: observation.text, protected: [] }; - return [ - ...context.protected, - ...markdownRanges(context.text).literal, - ].some((r) => query.start < r.end && query.end > r.start); - }; // A typed terminator (Space, closing punctuation after a name, the closing // emoji colon) stays literal in code. Tab, Enter and a click are not typed. const typed = key?.length === 1 ? key : undefined; - if (typed && inCode()) return false; + if (typed && inMarkdownCode(query)) return false; const chosen = chosenWorkspace(edit); if (chosen !== undefined) { // The chat's workspace leaves no text behind; the control shows it. @@ -2322,11 +2329,7 @@ function Composer({ setError(undefined); return true; } - // In code a group is only its name: code never carries recipients. - if ("group" in edit && edit.group) - return inCode() - ? insert(`@${edit.group.name} `, undefined, query) - : insertGroup(edit.group, query); + if ("group" in edit && edit.group) return insertGroup(edit.group, query); if ("mentions" in edit && edit.mentions) return insertMentions(edit.mentions, query); if ("mention" in edit && edit.mention) @@ -2863,6 +2866,12 @@ function Composer({ sendAttempt.current = attempt; const captured = valueRef.current; const capturedRecipients = routing ? recipientsNow : captured.recipients; + // A group and a member named alone are one person to notify or ask about. + const people = [ + ...new Map( + captured.recipients.map((person) => [person.pubkey, person]), + ).values(), + ]; const capturedAttachments = attachments.store.snapshot(); // Mention resolution can update recipients before their picker commits. // Capture only a snapshot validated for the saved choices being sent. @@ -2961,7 +2970,9 @@ function Composer({ return; } let references: readonly string[] = []; - let recipients = capturedRecipients.map((item) => item.pubkey); + let recipients = [ + ...new Set(capturedRecipients.map((item) => item.pubkey)), + ]; let declinedImports: readonly string[] = []; if (soloConversation || ownSoloConversation) { admission.current = true; @@ -2972,7 +2983,7 @@ function Composer({ )); } else if (recipients.length) { // An agent only an earlier Buzz runs would not answer; offer it here first. - const lookup = oldAgents.find(captured.recipients); + const lookup = oldAgents.find(people); const old = lookup instanceof Promise ? await lookup : lookup; if (old.length) { setSending(true); @@ -3007,7 +3018,7 @@ function Composer({ const elsewhere = new Map( (agents?.joinable() ?? []).map((agent) => [agent.pubkey, agent]), ); - const bring = captured.recipients.flatMap((person) => { + const bring = people.flatMap((person) => { const agent = elsewhere.get(person.pubkey); return agent && !channel.members?.includes(person.pubkey) ? [agent] @@ -3024,7 +3035,7 @@ function Composer({ if (brought === null) return; added = brought; } - const missing = captured.recipients.filter( + const missing = people.filter( (person) => !channel.members?.includes(person.pubkey) && !added.includes(person.pubkey), diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 31802c3c72..fbb358d52b 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -589,6 +589,20 @@ describe("composer Markdown boundary", () => { { text: "*b*\\*" }, ]); }); + it("sends a group's label as typed, not as Markdown", () => { + const member = { pubkey: "a".repeat(64), name: "Honey" }; + const group = (label: string) => + schema.nodes.token.create({ + source: `@${label}`, + group: { label, members: [member] }, + }); + expect(serialize(group("core"), schema.text(" hi"))).toBe("@core hi"); + const output = serialize(group("*core*"), schema.text(" hi")); + expect(fromMarkdown(output).children[0]).toMatchObject({ + type: "paragraph", + children: [{ type: "text", value: "@*core* hi" }], + }); + }); it("keeps generated strong delimiters distinct from literal asterisks", () => { const italic = (text: string) => schema.text(text, [schema.marks.italic.create()]); diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index 9e7d9528da..825a58caf1 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -251,7 +251,7 @@ function authoredLiteralRanges(doc: EditorNode) { ? "\n" : node.attrs.source; context.source += - node.marks.length || node.attrs.recipient + node.marks.length || node.attrs.recipient || node.attrs.group ? value.replace(/\S/g, "a") : value; }); @@ -317,6 +317,10 @@ function paragraphMarkdown( : node.attrs.source; if (composerSchema.marks.literal.isInSet(node.marks)) literals.push({ start, end: text.length }); + // Readers see a group chip as text, so its label after the @ is sent as + // typed rather than read as Markdown. + else if (node.attrs.group) + literals.push({ start: start + 1, end: text.length }); if ( node.attrs.recipient || composerSchema.marks.recipient.isInSet(node.marks) From dc092dd64522c0f1d7b17551d66d33b2ad6afed5 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 18:40:28 -0500 Subject: [PATCH 07/21] fix(solo): keep a leading group chip in a new chat's title The sent message carries a group only as text, and renaming derives the starting title from that message, so stripping the group left the title unrecognized and the agent's name never landed. A group now ends the leading-mention strip, which also stops a member whose name starts the label from cutting it short. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/solo/chat-title.test.ts | 24 ++++++++++++------------ src/features/solo/chat-title.ts | 7 ++++--- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/features/solo/chat-title.test.ts b/src/features/solo/chat-title.test.ts index b5bd367b87..7e657006ed 100644 --- a/src/features/solo/chat-title.test.ts +++ b/src/features/solo/chat-title.test.ts @@ -1,5 +1,5 @@ import { expect, it } from "vitest"; -import { startingChatTitle } from "./chat-title"; +import { isStartingChatTitle, startingChatTitle } from "./chat-title"; import { mentionDraft } from "../messages/mention-draft"; import { typedDraft } from "../messages/composer-testing"; @@ -75,7 +75,8 @@ it("drops leading namesake tags with their full-key qualifiers", () => { expect(startingChatTitle(draft)).toBe("fix the build"); }); -it("strips a leading group chip, whose members share its span", () => { +it("keeps a leading group chip, as renaming reads the sent message", () => { + // A member whose name starts the label must not strip part of it. const member = (pubkey: string, name: string) => ({ pubkey, name, @@ -83,14 +84,13 @@ it("strips a leading group chip, whose members share its span", () => { start: 0, end: 5, }); - expect( - startingChatTitle({ - text: "@crew @Ann plan the launch", - recipients: [ - member("1".repeat(64), "Ann"), - member("2".repeat(64), "Bo"), - { pubkey: "1".repeat(64), name: "Ann", start: 6, end: 10 }, - ], - }), - ).toBe("plan the launch"); + const ann = { pubkey: "1".repeat(64), name: "Ann", start: 6, end: 10 }; + const text = "@crew @Ann plan the launch"; + const title = startingChatTitle({ + text, + recipients: [member("2".repeat(64), "cr"), member(ann.pubkey, "Ann"), ann], + }); + expect(title).toBe("@crew @Ann plan the launch"); + // What the rename check derives from the sent text and its mentions. + expect(isStartingChatTitle(title, { text, recipients: [ann] })).toBe(true); }); diff --git a/src/features/solo/chat-title.ts b/src/features/solo/chat-title.ts index bdb84b18bf..1cbc5aa475 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,15 +35,16 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { - // A group's members share its span; it was stripped with the first. - if (recipient.end === draftStart) continue; + // A group chip is text in the sent message, so it stays in the title: + // renaming derives the starting title from that message. if ( + recipient.label !== undefined || recipient.start < draftStart || draft.text.slice(draftStart, recipient.start).trim() ) break; const leading = text.slice(start).match(/^\s*/)?.[0].length ?? 0; - const tag = `@${recipient.label ?? recipient.name}`; + const tag = `@${recipient.name}`; if (!text.startsWith(tag, start + leading)) break; start += leading + tag.length; // A namesake is sent with its full key; that qualifier is part of the tag. From 329b7dd5e2db68114f3f44203f3bb3c148a17cd5 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 19:02:34 -0500 Subject: [PATCH 08/21] fix(mentions): Solo tags after a group join in order; a group in literal text still notifies The Solo leading-tag scan counts each chip span once, so a group's shared span no longer ends it early and a later pick lands after earlier tags. A group picked from the toolbar falls back to its plain name only in Markdown backticks; the editor already keeps code marks and code blocks plain, and literal text such as a removed link's label is ordinary prose. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 28 +++++++++++++++++ src/features/messages/MessageComposer.tsx | 31 ++++++++++++------- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 273e6ed052..96f5332917 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -12665,6 +12665,24 @@ it("a group from the picker inside Markdown code is only its name", () => { expect(h.input()).toHaveValue("`a@Crew b`"); expect(h.commands().recipients).toEqual([]); }); +it("a group from the picker inside a removed link's label still notifies", () => { + const h = mount(); + h.fill("see label"); + act(() => { + h.input().setSelectionRange(4, 9); + const edit = h.input().editLink(); + if (!edit) throw new Error("Link editing unavailable"); + edit.remove(); + h.input().setSelectionRange(6, 6); + }); + act(() => + expect(h.commands().insertMentions([first, second], "Crew")).toBe(true), + ); + expect(h.commands().recipients.map(({ pubkey }) => pubkey)).toEqual([ + first.pubkey, + second.pubkey, + ]); +}); it("a group edit with an unavailable member adds nothing", async () => { const h = mount({ inviteAgents: true }); const unavailable = { pubkey: "c".repeat(64), name: "Missing" }; @@ -13788,6 +13806,16 @@ it("while a typed tag decides, a Solo menu toggle edits the tags, not a hidden l expect(sendingTo("Ada")).toBeInTheDocument(); }); +it("after a Solo group chip, each picked tag joins the leading tags in order", () => { + const { h, ada, bea } = mountSoloAgents({ main: first.pubkey }); + act(() => { + expect(h.commands().insertMentions([ada, bea], "Crew")).toBe(true); + h.commands().insertText("hello"); + }); + act(() => h.commands().insertMention(ada)); + act(() => h.commands().insertMention(bea)); + expect(h.input()).toHaveValue("@Crew @Ada @Bea hello"); +}); it("while a typed tag decides, a Solo team pick replaces the tags", () => { const { h, ada, bea, sendingTo } = mountSoloAgents({ main: first.pubkey }); act(() => { diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index f52c2b6839..0df8f403f1 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -2079,9 +2079,12 @@ function Composer({ function keepProseCaret(add: (at: CompletionQuery) => boolean, focus = true) { const before = valueRef.current; let start = 0; - for (const tag of [...before.recipients].sort( - (a, b) => a.start - b.start, - )) { + // A group's members share one span: each chip counts once. + for (const tag of [ + ...new Map( + before.recipients.map((tag) => [`${tag.start}:${tag.end}`, tag]), + ).values(), + ].sort((a, b) => a.start - b.start)) { if (tag.start !== start || !/[ \t]/.test(before.text[tag.end] ?? "")) break; start = tag.end; @@ -2165,16 +2168,21 @@ function Composer({ setError(undefined); return true; } - /** Whether `range` overlaps code: a code block, inline code, or Markdown - * code the draft's text spells with backticks. */ - function inMarkdownCode(range: Readonly<{ start: number; end: number }>) { + /** Whether `range` overlaps Markdown code the draft spells with backticks + * or, with `rich`, any rich span Markdown can't reach: code, a link or + * literal text such as a removed link's label. */ + function inMarkdownCode( + range: Readonly<{ start: number; end: number }>, + rich = false, + ) { const doc = readComposerSnapshot(valueRef.current.document); const context = doc ? composerMarkdownContext(doc) : { text: valueRef.current.text, protected: [] }; - return [...context.protected, ...markdownRanges(context.text).literal].some( - (r) => range.start < r.end && range.end > r.start, - ); + return [ + ...(rich ? context.protected : []), + ...markdownRanges(context.text).literal, + ].some((r) => range.start < r.end && range.end > r.start); } /** One chip for the whole group, at `range` or, from a tool, the caret. */ function insertGroup( @@ -2198,7 +2206,8 @@ function Composer({ ) return false; // Message edits only add references, never new notification intent, and - // in code a group is only its name: code never carries recipients. + // in code a group is only its name: code never carries recipients. The + // editor keeps code blocks and inline code plain; this catches backticks. const at = range ?? { start: input.current?.selectionStart ?? valueRef.current.text.length, end: input.current?.selectionEnd ?? valueRef.current.text.length, @@ -2308,7 +2317,7 @@ function Composer({ // A typed terminator (Space, closing punctuation after a name, the closing // emoji colon) stays literal in code. Tab, Enter and a click are not typed. const typed = key?.length === 1 ? key : undefined; - if (typed && inMarkdownCode(query)) return false; + if (typed && inMarkdownCode(query, true)) return false; const chosen = chosenWorkspace(edit); if (chosen !== undefined) { // The chat's workspace leaves no text behind; the control shows it. From 0ea915d78c7dbec3310c53055b71ab8ce563b247 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 6 Nov 2026 19:27:34 -0500 Subject: [PATCH 09/21] test(mentions): a repeated key doesn't count toward the 32-tag limit Two portable write fixtures send 33 occurrences of 32 distinct keys, one for recipients and one for references, and expect 32 tags. They fail if the writer checks the limit before removing duplicates. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../mentions/mention-rules.fixtures.json | 379 ++++++++++++++++++ 1 file changed, 379 insertions(+) diff --git a/src/bundled/mentions/mention-rules.fixtures.json b/src/bundled/mentions/mention-rules.fixtures.json index ae10c5c567..8a8b40bff3 100644 --- a/src/bundled/mentions/mention-rules.fixtures.json +++ b/src/bundled/mentions/mention-rules.fixtures.json @@ -1879,6 +1879,385 @@ "error": "invalid" } }, + { + "name": "at_most_32_distinct_recipients", + "members": [ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000002", + "0000000000000000000000000000000000000000000000000000000000000003", + "0000000000000000000000000000000000000000000000000000000000000004", + "0000000000000000000000000000000000000000000000000000000000000005", + "0000000000000000000000000000000000000000000000000000000000000006", + "0000000000000000000000000000000000000000000000000000000000000007", + "0000000000000000000000000000000000000000000000000000000000000008", + "0000000000000000000000000000000000000000000000000000000000000009", + "000000000000000000000000000000000000000000000000000000000000000a", + "000000000000000000000000000000000000000000000000000000000000000b", + "000000000000000000000000000000000000000000000000000000000000000c", + "000000000000000000000000000000000000000000000000000000000000000d", + "000000000000000000000000000000000000000000000000000000000000000e", + "000000000000000000000000000000000000000000000000000000000000000f", + "0000000000000000000000000000000000000000000000000000000000000010", + "0000000000000000000000000000000000000000000000000000000000000011", + "0000000000000000000000000000000000000000000000000000000000000012", + "0000000000000000000000000000000000000000000000000000000000000013", + "0000000000000000000000000000000000000000000000000000000000000014", + "0000000000000000000000000000000000000000000000000000000000000015", + "0000000000000000000000000000000000000000000000000000000000000016", + "0000000000000000000000000000000000000000000000000000000000000017", + "0000000000000000000000000000000000000000000000000000000000000018", + "0000000000000000000000000000000000000000000000000000000000000019", + "000000000000000000000000000000000000000000000000000000000000001a", + "000000000000000000000000000000000000000000000000000000000000001b", + "000000000000000000000000000000000000000000000000000000000000001c", + "000000000000000000000000000000000000000000000000000000000000001d", + "000000000000000000000000000000000000000000000000000000000000001e", + "000000000000000000000000000000000000000000000000000000000000001f", + "0000000000000000000000000000000000000000000000000000000000000020" + ], + "recipients": [ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000002", + "0000000000000000000000000000000000000000000000000000000000000003", + "0000000000000000000000000000000000000000000000000000000000000004", + "0000000000000000000000000000000000000000000000000000000000000005", + "0000000000000000000000000000000000000000000000000000000000000006", + "0000000000000000000000000000000000000000000000000000000000000007", + "0000000000000000000000000000000000000000000000000000000000000008", + "0000000000000000000000000000000000000000000000000000000000000009", + "000000000000000000000000000000000000000000000000000000000000000a", + "000000000000000000000000000000000000000000000000000000000000000b", + "000000000000000000000000000000000000000000000000000000000000000c", + "000000000000000000000000000000000000000000000000000000000000000d", + "000000000000000000000000000000000000000000000000000000000000000e", + "000000000000000000000000000000000000000000000000000000000000000f", + "0000000000000000000000000000000000000000000000000000000000000010", + "0000000000000000000000000000000000000000000000000000000000000011", + "0000000000000000000000000000000000000000000000000000000000000012", + "0000000000000000000000000000000000000000000000000000000000000013", + "0000000000000000000000000000000000000000000000000000000000000014", + "0000000000000000000000000000000000000000000000000000000000000015", + "0000000000000000000000000000000000000000000000000000000000000016", + "0000000000000000000000000000000000000000000000000000000000000017", + "0000000000000000000000000000000000000000000000000000000000000018", + "0000000000000000000000000000000000000000000000000000000000000019", + "000000000000000000000000000000000000000000000000000000000000001a", + "000000000000000000000000000000000000000000000000000000000000001b", + "000000000000000000000000000000000000000000000000000000000000001c", + "000000000000000000000000000000000000000000000000000000000000001d", + "000000000000000000000000000000000000000000000000000000000000001e", + "000000000000000000000000000000000000000000000000000000000000001f", + "0000000000000000000000000000000000000000000000000000000000000020", + "0000000000000000000000000000000000000000000000000000000000000001" + ], + "references": [], + "expected": { + "tags": [ + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000001" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000002" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000003" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000004" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000005" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000006" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000007" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000008" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000009" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000000a" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000000b" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000000c" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000000d" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000000e" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000000f" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000010" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000011" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000012" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000013" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000014" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000015" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000016" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000017" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000018" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000019" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000001a" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000001b" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000001c" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000001d" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000001e" + ], + [ + "p", + "000000000000000000000000000000000000000000000000000000000000001f" + ], + [ + "p", + "0000000000000000000000000000000000000000000000000000000000000020" + ] + ] + } + }, + { + "name": "at_most_32_distinct_references", + "members": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ], + "recipients": [], + "references": [ + "0000000000000000000000000000000000000000000000000000000000000001", + "0000000000000000000000000000000000000000000000000000000000000002", + "0000000000000000000000000000000000000000000000000000000000000003", + "0000000000000000000000000000000000000000000000000000000000000004", + "0000000000000000000000000000000000000000000000000000000000000005", + "0000000000000000000000000000000000000000000000000000000000000006", + "0000000000000000000000000000000000000000000000000000000000000007", + "0000000000000000000000000000000000000000000000000000000000000008", + "0000000000000000000000000000000000000000000000000000000000000009", + "000000000000000000000000000000000000000000000000000000000000000a", + "000000000000000000000000000000000000000000000000000000000000000b", + "000000000000000000000000000000000000000000000000000000000000000c", + "000000000000000000000000000000000000000000000000000000000000000d", + "000000000000000000000000000000000000000000000000000000000000000e", + "000000000000000000000000000000000000000000000000000000000000000f", + "0000000000000000000000000000000000000000000000000000000000000010", + "0000000000000000000000000000000000000000000000000000000000000011", + "0000000000000000000000000000000000000000000000000000000000000012", + "0000000000000000000000000000000000000000000000000000000000000013", + "0000000000000000000000000000000000000000000000000000000000000014", + "0000000000000000000000000000000000000000000000000000000000000015", + "0000000000000000000000000000000000000000000000000000000000000016", + "0000000000000000000000000000000000000000000000000000000000000017", + "0000000000000000000000000000000000000000000000000000000000000018", + "0000000000000000000000000000000000000000000000000000000000000019", + "000000000000000000000000000000000000000000000000000000000000001a", + "000000000000000000000000000000000000000000000000000000000000001b", + "000000000000000000000000000000000000000000000000000000000000001c", + "000000000000000000000000000000000000000000000000000000000000001d", + "000000000000000000000000000000000000000000000000000000000000001e", + "000000000000000000000000000000000000000000000000000000000000001f", + "0000000000000000000000000000000000000000000000000000000000000020", + "0000000000000000000000000000000000000000000000000000000000000001" + ], + "expected": { + "tags": [ + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000001" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000002" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000003" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000004" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000005" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000006" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000007" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000008" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000009" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000000a" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000000b" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000000c" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000000d" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000000e" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000000f" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000010" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000011" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000012" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000013" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000014" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000015" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000016" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000017" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000018" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000019" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000001a" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000001b" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000001c" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000001d" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000001e" + ], + [ + "mention", + "000000000000000000000000000000000000000000000000000000000000001f" + ], + [ + "mention", + "0000000000000000000000000000000000000000000000000000000000000020" + ] + ] + } + }, { "name": "at_most_32_references", "members": [ From 4b0afb8371c6a4a1d14ac679b6137012c8ef8eaf Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 17:28:36 -0500 Subject: [PATCH 10/21] Say which teams a Solo chat can mention A Solo chat adds only the viewer's agents, so a team with someone outside the chat stays unavailable there. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/buzz-help.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index e96c6d7010..406ad62eba 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1500,7 +1500,9 @@ Saved teams from **Your teams** appear in the inline `@` suggestions and the mention picker. Select a team to insert one `@team` mention that notifies each member; the suggestion shows how many people and agents it holds. A saved team can hold people as well as agents; a person outside the -conversation is offered the way the `@` picker offers them. Typing its name alone does not notify it. Empty teams, teams with more than 32 +conversation is offered the way the `@` picker offers them. In a Solo chat, a +team can be selected only when every member is in the chat or is one of your +available agents. Typing its name alone does not notify it. Empty teams, teams with more than 32 members, and teams with unavailable members cannot be selected; edit the team or refresh the choices. Adding people to a channel still requires the normal send confirmation. **Delete team** asks first; it doesn't delete the team's agents. From db3a301648070a04f6e2ef05db7cfceeefc2e77e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 13:58:53 -0500 Subject: [PATCH 11/21] feat(communities): sign community mention group commands Mention groups become community state the relay owns. The app signs three commands (47000 put, 47001 delete, 47002 set "who can manage groups") through one route, `mention-group`, on both the packaged signer and the browser broker. The relay checks authority and answers with typed reasons (conflict, duplicate, restricted, invalid), which come back verbatim so the caller can tell a version conflict from a taken name. The request carries `created_at`, so a retry after a lost receipt signs the same event and the relay's receipt answers it instead of applying it twice. The native signer accepts only the exact tag order the relay expects. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-broker-api.test.mjs | 97 ++++++++++++++++ browser-host/relay-broker.mjs | 26 +++-- src-tauri/src/relay.rs | 77 +++++++++++++ src-tauri/src/relay/tests.rs | 66 +++++++++++ src/features/communities/admin-protocol.ts | 120 ++++++++++++++++++++ src/features/communities/native-api.test.ts | 61 ++++++++++ src/features/communities/native-api.ts | 20 +++- 7 files changed, 459 insertions(+), 8 deletions(-) diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index 268db22ffb..f3fcbbf112 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -3089,6 +3089,103 @@ test("member change receipts must match the signed command", async () => { } }); +test("mention group changes sign the relay's exact command kinds and reject malformed changes locally", async () => { + let answer; + const { h, post } = await communityAdmin((call) => + answer + ? Response.json({ error: answer }, { status: 409 }) + : Response.json({ accepted: true, event_id: call.body.id, message: "" }), + ); + const id = "0659678f-fddb-40df-a285-35f6b41db019"; + const person = "a".repeat(64); + const agent = "b".repeat(64); + const created_at = Math.floor(Date.now() / 1000); + const put = { + action: "put", + id, + prev: "0", + name: "On call", + members: [person, agent], + channels: ["general"], + created_at, + }; + try { + for (const [change, kind, tags] of [ + [ + put, + 47000, + [ + ["d", id], + ["prev", "0"], + ["name", "On call"], + ["p", person], + ["p", agent], + ["channel", "general"], + ], + ], + [ + { action: "remove", id, prev: "4", created_at }, + 47001, + [ + ["d", id], + ["prev", "4"], + ], + ], + [ + { action: "manage", manage: "admins", prev: "0", created_at }, + 47002, + [ + ["manage", "admins"], + ["prev", "0"], + ], + ], + ]) { + const response = await post("mention-group", change); + expect(response.status).toBe(200); + const sent = h.calls.at(-1); + expect(sent.url).toBe(`${fixtureRelayUrl}/events`); + expect(verifyEvent(sent.body)).toBe(true); + expect(sent.body).toMatchObject({ + kind, + tags, + content: "", + pubkey: h.event.pubkey, + created_at, + }); + } + // A retry after an unknown outcome is the same event, so the relay's + // receipt answers it instead of applying the change twice. + const first = h.calls[0].body.id; + expect((await post("mention-group", put)).status).toBe(200); + expect(h.calls.at(-1).body.id).toBe(first); + answer = "conflict: mention group version is 3"; + const conflict = await post("mention-group", put); + expect(conflict.status).toBe(409); + expect((await conflict.json()).error).toBe(answer); + const sent = h.calls.length; + for (const change of [ + { ...put, created_at: created_at - 3600 }, + { ...put, created_at: undefined }, + { ...put, prev: "01" }, + { ...put, name: " On call" }, + { ...put, name: "" }, + { ...put, id: id.toUpperCase() }, + { ...put, members: [person, person] }, + { ...put, members: ["A".repeat(64)] }, + { ...put, channels: ["a/b"] }, + { ...put, action: "rename" }, + { action: "manage", manage: "owners", prev: "0", created_at }, + { kind: 47000, tags: [["d", id]], created_at }, + ]) + expect((await post("mention-group", change)).status).toBe(400); + // Unscoped requests name no community. + expect((await h.post("mention-group", put)).status).toBe(400); + expect(h.calls).toHaveLength(sent); + } finally { + await h.close(); + } +}); + test("leave requests sign the exact NIP-43 shape for the selected community only", async () => { const { h, post } = await communityAdmin((call) => Response.json({ accepted: true, event_id: call.body.id, message: "" }), diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index 4e6e20bd66..78d667c134 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -43,6 +43,8 @@ import { claimReason, inviteRequest, memberCommand, + mentionGroupCommand, + mentionGroupReason, } from "../src/features/communities/admin-protocol.ts"; import { leaveRefusal, @@ -2467,6 +2469,7 @@ export function relayBrokerPlugin({ "/api/relay/accept-policy", "/api/relay/invite", "/api/relay/member", + "/api/relay/mention-group", "/api/relay/leave", "/api/relay/gifs", "/api/relay/profile-search", @@ -2778,19 +2781,21 @@ export function relayBrokerPlugin({ const policy = route === "/api/relay/accept-policy"; const invite = route === "/api/relay/invite"; const member = route === "/api/relay/member"; + const group = route === "/api/relay/mention-group"; const leave = route === "/api/relay/leave"; const gifs = route === "/api/relay/gifs"; const profileSearch = route === "/api/relay/profile-search"; // Only these routes may surface an exact, allowed relay refusal. - const refusal = - invite || member + const refusal = group + ? mentionGroupReason + : invite || member ? adminReason : claim ? claimReason : leave ? leaveRefusal : undefined; - if (invite || member || leave) { + if (invite || member || group || leave) { // Community-bound only; the relay remains the authority for roles. if (!scoped) return json(res, 400, { error: "Select a community first" }); @@ -2799,7 +2804,11 @@ export function relayBrokerPlugin({ filters = invite ? inviteRequest(filters) : finalizeEvent( - leave ? leaveRequestTemplate() : memberCommand(filters), + leave + ? leaveRequestTemplate() + : group + ? mentionGroupCommand(filters) + : memberCommand(filters), key, ); } catch (error) { @@ -3142,6 +3151,7 @@ export function relayBrokerPlugin({ !policy && !invite && !member && + !group && !leave && !gifs && !profileSearch && @@ -3228,7 +3238,7 @@ export function relayBrokerPlugin({ ? gifSearchPath : profileSearch ? "/profiles/search" - : profile || directMessage || member || leave + : profile || directMessage || member || group || leave ? "/events" : claim ? "/api/invites/claim" @@ -3392,7 +3402,7 @@ export function relayBrokerPlugin({ }); } } - if (profile || member || leave) { + if (profile || member || group || leave) { const receipt = JSON.parse(text); if ( receipt.event_id !== filters.id || @@ -3403,7 +3413,9 @@ export function relayBrokerPlugin({ ? "Leave request could not be confirmed" : member ? "Member change could not be confirmed" - : "Profile publication could not be confirmed", + : group + ? "Group change could not be confirmed" + : "Profile publication could not be confirmed", }); } res.writeHead(200, { diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index b3bf2063e4..fe12f4c8b0 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -445,6 +445,10 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> { if !valid_member_command(event) { return Err("Invalid member change".into()); } + } else if matches!(event.kind, 47000..=47002) { + if !valid_mention_group_command(event) { + return Err("Invalid group change".into()); + } } else if !matches!( event.kind, 0 | 7 | 9 | 1984 | 9000 | 9001 | 20001 | 30030 | 30177 | 30315 | 40003 | 42000 | 45010 @@ -467,6 +471,79 @@ fn valid_member_command(event: &EventTemplate) -> bool { } } +/** Match the broker's mention group command shape (`mentionGroupCommand` in + * `src/features/communities/admin-protocol.ts`); the relay decides authority + * from the community's "who can manage groups" setting. */ +fn valid_mention_group_command(event: &EventTemplate) -> bool { + let tag = |tag: &[String], name: &str| tag.len() == 2 && tag[0] == name; + let uuid = |value: &str| { + let bytes = value.as_bytes(); + bytes.len() == 36 + && bytes.iter().enumerate().all(|(i, byte)| match i { + 8 | 13 | 18 | 23 => *byte == b'-', + _ => byte.is_ascii_digit() || (b'a'..=b'f').contains(byte), + }) + && (b'1'..=b'8').contains(&bytes[14]) + && matches!(bytes[19], b'8' | b'9' | b'a' | b'b') + }; + let version = |value: &str| { + !value.is_empty() + && value.len() <= 19 + && value.bytes().all(|byte| byte.is_ascii_digit()) + && (value == "0" || !value.starts_with('0')) + }; + let name = |value: &str| { + value == value.trim() + && !value.is_empty() + && value.chars().count() <= 120 + && !value.chars().any(|c| c.is_control()) + }; + let channel = |value: &str| { + (1..=128).contains(&value.len()) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + }; + if !event.content.is_empty() { + return false; + } + let tags = event.tags.as_slice(); + match event.kind { + 47002 => matches!(tags, [m, p] if tag(m, "manage") + && (m[1] == "admins" || m[1] == "everyone") + && tag(p, "prev") && version(&p[1])), + 47001 => matches!(tags, [d, p] if tag(d, "d") && uuid(&d[1]) + && tag(p, "prev") && version(&p[1])), + 47000 => { + let [d, p, n, rest @ ..] = tags else { + return false; + }; + if !(tag(d, "d") + && uuid(&d[1]) + && tag(p, "prev") + && version(&p[1]) + && tag(n, "name") + && name(&n[1])) + { + return false; + } + let split = rest.iter().position(|t| !tag(t, "p")).unwrap_or(rest.len()); + let (members, channels) = rest.split_at(split); + let distinct = |items: &[Vec]| { + let mut seen = std::collections::HashSet::new(); + items.iter().all(|t| seen.insert(t[1].as_str())) + }; + members.len() <= 1000 + && members.iter().all(|t| hex_key(&t[1])) + && distinct(members) + && channels.len() <= 32 + && channels.iter().all(|t| tag(t, "channel") && channel(&t[1])) + && distinct(channels) + } + _ => false, + } +} + // Match the broker's purpose-bound Canvas admission, including legacy untagged retries. fn valid_canvas(event: &EventTemplate) -> bool { event.content.len() <= LIVE_CANVAS_BYTES diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index e9ab7c2daf..8f2399ceb4 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -198,6 +198,72 @@ fn member_commands_sign_only_the_broker_shape() { } } +#[test] +fn mention_group_commands_sign_only_the_broker_shape() { + let command = |kind: u16, content: &str, tags: &[&[&str]]| EventTemplate { + kind, + created_at: 1, + content: content.into(), + tags: tags + .iter() + .map(|tag| tag.iter().map(|value| value.to_string()).collect()) + .collect(), + }; + let id = "0659678f-fddb-40df-a285-35f6b41db019"; + let key = "a".repeat(64); + let other = "b".repeat(64); + let d: &[&str] = &["d", id]; + let prev: &[&str] = &["prev", "3"]; + let name: &[&str] = &["name", "On call 🚨"]; + let p: &[&str] = &["p", &key]; + let q: &[&str] = &["p", &other]; + let channel: &[&str] = &["channel", "5a906a8f-7c87-41dc-8df5-06ea23ed5362"]; + for accepted in [ + command(47000, "", &[d, &["prev", "0"], name]), + command(47000, "", &[d, prev, name, p, q, channel]), + command(47000, "", &[d, prev, name, channel]), + command(47001, "", &[d, prev]), + command(47002, "", &[&["manage", "admins"], &["prev", "0"]]), + command(47002, "", &[&["manage", "everyone"], prev]), + ] { + assert!(validate_event("https://relay.test", &accepted).is_ok()); + } + for rejected in [ + // Put needs its id, version and name first, in that order. + command(47000, "", &[d, prev]), + command(47000, "", &[prev, d, name]), + command(47000, "", &[d, prev, &["name", " padded"]]), + command(47000, "", &[d, prev, &["name", ""]]), + command(47000, "", &[d, prev, &["name", "two\nlines"]]), + command(47000, "", &[d, prev, &["name", &"x".repeat(121)]]), + command(47000, "", &[d, &["prev", "01"], name]), + command(47000, "", &[d, &["prev", "-1"], name]), + command(47000, "", &[&["d", "not-a-uuid"], prev, name]), + command(47000, "", &[&["d", &id.to_uppercase()], prev, name]), + // Members come before channels, once each, as lowercase keys. + command(47000, "", &[d, prev, name, channel, p]), + command(47000, "", &[d, prev, name, p, p]), + command(47000, "", &[d, prev, name, &["p", &key.to_uppercase()]]), + command( + 47000, + "", + &[d, prev, name, &["p", &key, "wss://relay.test"]], + ), + command(47000, "", &[d, prev, name, channel, channel]), + command(47000, "", &[d, prev, name, &["channel", "a/b"]]), + command(47000, "", &[d, prev, name, &["h", "channel"]]), + command(47000, "note", &[d, prev, name]), + // Delete and the setting carry nothing else. + command(47001, "", &[d, prev, name]), + command(47001, "", &[d]), + command(47002, "", &[&["manage", "owners"], prev]), + command(47002, "", &[&["manage", "admins"], prev, d]), + command(47003, "", &[d, prev]), + ] { + assert!(validate_event("https://relay.test", &rejected).is_err()); + } +} + fn fixture_server(response: String) -> (Url, std::thread::JoinHandle<(String, String)>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let url = Url::parse(&format!("http://{}/query", listener.local_addr().unwrap())).unwrap(); diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 17471950bb..208837744d 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -106,3 +106,123 @@ export function claimReason(body: unknown): string | undefined { ? reason : undefined; } + +// Mention groups (relay NIP-MG): community-owned groups the relay stores and +// signs as kind 39010. The relay decides authority from the community's +// "who can manage groups" setting; this only bounds shape. +export const MENTION_GROUP_KINDS = Object.freeze({ + put: 47000, + remove: 47001, + manage: 47002, + state: 39010, +}); +const UUID = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const VERSION = /^(?:0|[1-9][0-9]{0,18})$/; +const KEY = /^[0-9a-f]{64}$/; +const CHANNEL = /^[a-zA-Z0-9_-]{1,128}$/; +const MAX_NAME = 120; +const MAX_CHANNELS = 32; +// The relay bounds the signed size; this only keeps a template sane. +const MAX_MEMBERS = 1000; +/** Commands outlive no more than this before the relay calls them stale. */ +const MAX_AGE = 15 * 60; + +/** Trimmed one-line name of 1 to 120 characters, or undefined. */ +export function mentionGroupName(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const name = value.trim(); + return name && [...name].length <= MAX_NAME && !/\p{Cc}/u.test(name) + ? name + : undefined; +} + +/** Unsigned put, delete or set-manage command. `created_at` is part of the + * request so a retry signs the same event (same ID) and the relay's receipt + * answers it instead of applying it twice. */ +export function mentionGroupCommand( + value: unknown, + now = Math.floor(Date.now() / 1000), +) { + const body = (value ?? {}) as Record; + const { action, prev, created_at: createdAt } = body; + if ( + typeof createdAt !== "number" || + !Number.isSafeInteger(createdAt) || + createdAt > now + 60 || + createdAt < now - MAX_AGE + ) + throw new Error("Invalid group change time"); + if (typeof prev !== "string" || !VERSION.test(prev)) + throw new Error("Invalid group version"); + const base = { content: "", created_at: createdAt }; + if (action === "manage") { + if (body.manage !== "admins" && body.manage !== "everyone") + throw new Error("Invalid group setting"); + return { + ...base, + kind: MENTION_GROUP_KINDS.manage, + tags: [ + ["manage", body.manage], + ["prev", prev], + ], + }; + } + if (typeof body.id !== "string" || !UUID.test(body.id)) + throw new Error("Invalid group"); + if (action === "remove") + return { + ...base, + kind: MENTION_GROUP_KINDS.remove, + tags: [ + ["d", body.id], + ["prev", prev], + ], + }; + if (action !== "put") throw new Error("Invalid group change"); + const name = mentionGroupName(body.name); + if (name === undefined || name !== body.name) + throw new Error("Invalid group name"); + const members = body.members ?? []; + const channels = body.channels ?? []; + if ( + !Array.isArray(members) || + members.length > MAX_MEMBERS || + !members.every((key) => typeof key === "string" && KEY.test(key)) || + new Set(members).size !== members.length + ) + throw new Error("Invalid group members"); + if ( + !Array.isArray(channels) || + channels.length > MAX_CHANNELS || + !channels.every((id) => typeof id === "string" && CHANNEL.test(id)) || + new Set(channels).size !== channels.length + ) + throw new Error("Invalid group channels"); + return { + ...base, + kind: MENTION_GROUP_KINDS.put, + tags: [ + ["d", body.id], + ["prev", prev], + ["name", name], + ...members.map((key) => ["p", key as string]), + ...channels.map((id) => ["channel", id as string]), + ], + }; +} + +/** The relay's typed mention group answers, kept verbatim so the caller can + * tell a version conflict from a taken name or a refusal. Anything else stays + * a generic failure. */ +export function mentionGroupReason(body: unknown): string | undefined { + const { error, message, reason } = (body ?? {}) as Record; + const text = [error, message, reason].find( + (item): item is string => typeof item === "string", + ); + return text && + /^(?:conflict|duplicate|restricted|invalid|blocked): /.test(text) && + text.length <= 300 + ? text + : undefined; +} diff --git a/src/features/communities/native-api.test.ts b/src/features/communities/native-api.test.ts index e9fe0fe5ec..f98f4206e7 100644 --- a/src/features/communities/native-api.test.ts +++ b/src/features/communities/native-api.test.ts @@ -175,6 +175,67 @@ it.each([ }, ); +it("resends the same signed group change, so a retry after a lost receipt is answered, not applied twice", async () => { + const change = { + action: "put", + id: "0659678f-fddb-40df-a285-35f6b41db019", + prev: "2", + name: "On call", + members: ["2".repeat(64)], + channels: ["general"], + created_at: Math.floor(Date.now() / 1000), + }; + respond = (_path, body) => ({ + body: { accepted: true, event_id: (body as { id: string }).id }, + }); + await communityRequest(community, "mention-group", change); + await communityRequest(community, "mention-group", change); + expect(requests).toMatchObject([ + { + path: "/events", + body: { + kind: 47000, + content: "", + tags: [ + ["d", change.id], + ["prev", "2"], + ["name", "On call"], + ["p", "2".repeat(64)], + ["channel", "general"], + ], + }, + }, + { path: "/events" }, + ]); + const [first, second] = requests.map((r) => (r.body as { id: string }).id); + expect(second).toBe(first); +}); + +it.each([ + [ + "conflict: mention group version is 3", + "conflict: mention group version is 3", + ], + [ + "duplicate: mention group name already exists", + "duplicate: mention group name already exists", + ], + [ + "restricted: only owners and admins manage groups", + "restricted: only owners and admins manage groups", + ], + ["database error: connection reset", "Community request failed (409)"], +])("keeps the relay's typed group answer %j", async (error, shown) => { + respond = () => ({ status: 409, body: { error } }); + const failure = await communityRequest(community, "mention-group", { + action: "remove", + id: "0659678f-fddb-40df-a285-35f6b41db019", + prev: "3", + created_at: Math.floor(Date.now() / 1000), + }).catch((reason: Error) => reason); + expect(failure).toEqual(new Error(shown)); +}); + it("mints only bounded invites on the captured community", async () => { respond = () => ({ body: { code: "invite", url: `${community}/invite/invite` }, diff --git a/src/features/communities/native-api.ts b/src/features/communities/native-api.ts index a42f5f9c7a..98bdb817f4 100644 --- a/src/features/communities/native-api.ts +++ b/src/features/communities/native-api.ts @@ -9,7 +9,12 @@ import { } from "../relay/native"; import { joinPolicy as readJoinPolicy } from "./join-policy"; import { leaveRefusal, leaveRequestTemplate } from "./leave-protocol"; -import { adminReason, memberCommand } from "./admin-protocol"; +import { + adminReason, + memberCommand, + mentionGroupCommand, + mentionGroupReason, +} from "./admin-protocol"; import { readRelayLibrary } from "../agents/relay-library"; import { eventDto } from "../relay/events"; import { readApiFailure } from "../relay/http-admission"; @@ -217,6 +222,19 @@ export async function nativeCommunityRequest( throw new Error("Member change could not be confirmed"); return result; } + if (route === "mention-group") { + // The relay decides each change; its typed answers come back verbatim. + const event = await nativeRelaySigner(community).signEvent( + mentionGroupCommand(body), + ); + const result = await readResponse( + await nativeRelayRequest(community, "/events", event, signal), + mentionGroupReason, + ); + if (result.event_id !== event.id || typeof result.accepted !== "boolean") + throw new Error("Group change could not be confirmed"); + return result; + } if (route === "leave") { // The membership refusals come back verbatim so the caller can tell an // already-absent membership from a failed request. From cca583dbf440979365c7ebc4aaee0b2ad2b4c305 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 14:58:15 -0500 Subject: [PATCH 12/21] feat(communities): a live community mention group directory Each relay session gets one mention group owner, `session.mentionGroups`, when the relay advertises NIP-MG v1. It reads every relay-signed 39010 head in pages, keeps them current from the global live route, and reads them all again after a reconnect. Newer versions win, a missing head never deletes a group, and a failed read never empties a directory that was shown. It is a recovery source, so failed reads retry with the session's other background reads. On a relay that enforces membership, a group lists only current roster members and owner-admitted agents, and waits while one is unknown. `canEdit` and `canManage` follow the viewer's role and the "Who can manage groups" setting. Commands keep their event id across retries, so a retry after a lost receipt is answered from the relay's receipt at any age. Accepted saves report the default-channel joins the relay made or skipped. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-authority.test.mjs | 21 + browser-host/relay-broker-api.test.mjs | 4 +- browser-host/relay-broker.mjs | 4 + src-tauri/src/relay/tests.rs | 2 + src/features/communities/admin-protocol.ts | 44 +- .../communities/mention-groups.test.ts | 449 ++++++++++++ src/features/communities/mention-groups.ts | 689 ++++++++++++++++++ src/features/communities/native-api.test.ts | 8 +- src/features/relay/live.test.ts | 6 + src/features/relay/live.ts | 6 + src/features/relay/native.test.ts | 38 + src/features/relay/native.ts | 3 + src/features/relay/session.ts | 41 ++ src/features/relay/transport.ts | 16 + 14 files changed, 1320 insertions(+), 11 deletions(-) create mode 100644 src/features/communities/mention-groups.test.ts create mode 100644 src/features/communities/mention-groups.ts diff --git a/browser-host/relay-authority.test.mjs b/browser-host/relay-authority.test.mjs index f2a1905fd0..32f22cf0dd 100644 --- a/browser-host/relay-authority.test.mjs +++ b/browser-host/relay-authority.test.mjs @@ -44,6 +44,27 @@ async function harness(info, identity = generateSecretKey()) { }, }; } +it.each([ + [{}, undefined], + [{ supported_extensions: ["nip-mg"] }, undefined], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "open" }, + }, + { membership: "open", defaultManage: "everyone" }, + ], +])( + "carries a v1 NIP-MG advertisement to the browser transport: %j", + async (advertised, support) => { + const h = await harness(() => Response.json({ self, ...advertised })); + try { + expect((await h.connect()).mentionGroups).toEqual(support); + } finally { + await h.close(); + } + }, +); it.each([ [undefined, false], [null, false], diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index f3fcbbf112..7c1ed24c4c 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -3158,13 +3158,13 @@ test("mention group changes sign the relay's exact command kinds and reject malf const first = h.calls[0].body.id; expect((await post("mention-group", put)).status).toBe(200); expect(h.calls.at(-1).body.id).toBe(first); - answer = "conflict: mention group version is 3"; + answer = "conflict: mention group version changed"; const conflict = await post("mention-group", put); expect(conflict.status).toBe(409); expect((await conflict.json()).error).toBe(answer); const sent = h.calls.length; for (const change of [ - { ...put, created_at: created_at - 3600 }, + { ...put, created_at: created_at + 3600 }, { ...put, created_at: undefined }, { ...put, prev: "01" }, { ...put, name: " On call" }, diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index 78d667c134..6091316099 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -45,6 +45,7 @@ import { memberCommand, mentionGroupCommand, mentionGroupReason, + mentionGroupSupport, } from "../src/features/communities/admin-protocol.ts"; import { leaveRefusal, @@ -342,6 +343,8 @@ async function relayAuthority(fetch, relay) { artifactSupport: Array.isArray(nip11.supported_extensions) && nip11.supported_extensions.includes("nip-ar"), + // NIP-MG: community mention groups and the membership rule they follow. + mentionGroups: mentionGroupSupport(nip11), // Bridge search accepts `search_sort: "newest"`. searchSort: Array.isArray(nip11.supported_extensions) && @@ -1700,6 +1703,7 @@ export function relayBrokerPlugin({ sidebarMuteWrites: true, channelKit: true, channelIdentity: (await getAuthority(relay)).channelIdentity, + mentionGroups: (await getAuthority(relay)).mentionGroups, readState: true, sidebarPreferenceWrites: true, sidebarSectionRemoval: true, diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index 8f2399ceb4..df8ead58ba 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -259,6 +259,8 @@ fn mention_group_commands_sign_only_the_broker_shape() { command(47002, "", &[&["manage", "owners"], prev]), command(47002, "", &[&["manage", "admins"], prev, d]), command(47003, "", &[d, prev]), + // Group state is relay-signed only. + command(39010, "", &[d, &["name", "On call"], &["version", "1"]]), ] { assert!(validate_event("https://relay.test", &rejected).is_err()); } diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 208837744d..2ca9f6a34f 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -125,8 +125,42 @@ const MAX_NAME = 120; const MAX_CHANNELS = 32; // The relay bounds the signed size; this only keeps a template sane. const MAX_MEMBERS = 1000; -/** Commands outlive no more than this before the relay calls them stale. */ -const MAX_AGE = 15 * 60; +/** The relay takes a new command within this many seconds of its clock; an + * exact resend of an accepted command is answered at any age. */ +const MAX_SKEW = 120; + +/** The relay serves mention groups (NIP-11 `nip-mg` with a v1 + * `mention_groups` object). `membership` is the predicate it enforces: + * `roster` relays admit roster members and owner-admitted agents; `open` + * relays admit every authenticated key. */ +export type MentionGroupSupport = Readonly<{ + membership: "open" | "roster"; + /** "Who can manage groups" before any setting command. */ + defaultManage: "admins" | "everyone"; +}>; +export function mentionGroupSupport( + nip11: unknown, +): MentionGroupSupport | undefined { + const info = (nip11 ?? {}) as { + supported_extensions?: unknown; + mention_groups?: { + version?: unknown; + membership?: unknown; + default_manage?: unknown; + }; + }; + const groups = info.mention_groups; + return Array.isArray(info.supported_extensions) && + info.supported_extensions.includes("nip-mg") && + groups?.version === 1 && + (groups.membership === "open" || groups.membership === "roster") + ? { + membership: groups.membership, + defaultManage: + groups.default_manage === "admins" ? "admins" : "everyone", + } + : undefined; +} /** Trimmed one-line name of 1 to 120 characters, or undefined. */ export function mentionGroupName(value: unknown): string | undefined { @@ -139,7 +173,7 @@ export function mentionGroupName(value: unknown): string | undefined { /** Unsigned put, delete or set-manage command. `created_at` is part of the * request so a retry signs the same event (same ID) and the relay's receipt - * answers it instead of applying it twice. */ + * answers it instead of applying it twice, however old it is. */ export function mentionGroupCommand( value: unknown, now = Math.floor(Date.now() / 1000), @@ -149,8 +183,8 @@ export function mentionGroupCommand( if ( typeof createdAt !== "number" || !Number.isSafeInteger(createdAt) || - createdAt > now + 60 || - createdAt < now - MAX_AGE + createdAt < 1 || + createdAt > now + MAX_SKEW ) throw new Error("Invalid group change time"); if (typeof prev !== "string" || !VERSION.test(prev)) diff --git a/src/features/communities/mention-groups.test.ts b/src/features/communities/mention-groups.test.ts new file mode 100644 index 0000000000..2eee54389d --- /dev/null +++ b/src/features/communities/mention-groups.test.ts @@ -0,0 +1,449 @@ +import { expect, it, vi } from "vitest"; +import type { EventData, ReadFilter } from "../relay/events"; +import { createMentionGroups } from "./mention-groups"; + +const author = "f".repeat(64); +const viewer = "1".repeat(64); +const admin = "2".repeat(64); +const person = "3".repeat(64); +const removed = "4".repeat(64); +const agent = "5".repeat(64); +const groupA = "0659678f-fddb-40df-a285-35f6b41db019"; +const groupB = "1b0e8c2a-3f4d-4c5e-9a6b-7c8d9e0f1a2b"; +let sequence = 0; +const id = () => (++sequence).toString(16).padStart(64, "0"); + +function head( + d: string, + version: number, + name: string, + members: string[], + extra: string[][] = [], + created_at = 1000 + version, +): EventData { + return { + id: id(), + pubkey: author, + kind: 39010, + created_at, + content: "", + tags: [ + ["-"], + ["d", d], + ["name", name], + ["version", String(version)], + ["command", "c".repeat(64)], + ...members.map((key) => ["p", key]), + ...extra, + ], + }; +} +const tombstone = (d: string, version: number): EventData => ({ + id: id(), + pubkey: author, + kind: 39010, + created_at: 2000 + version, + content: "", + tags: [ + ["-"], + ["d", d], + ["version", String(version)], + ["command", "c".repeat(64)], + ["deleted", "true"], + ], +}); +const settings = (manage: string, version: number): EventData => ({ + id: id(), + pubkey: author, + kind: 39010, + created_at: 3000 + version, + content: "", + tags: [ + ["-"], + ["d", "settings"], + ["manage", manage], + ["version", String(version)], + ["command", "c".repeat(64)], + ], +}); +const roster = (members: [string, string][]): EventData => ({ + id: id(), + pubkey: author, + kind: 13534, + created_at: 500, + content: "", + tags: members.map(([key, role]) => ["member", key, role]), +}); + +/** A relay holding `stored` events, answering reads like the relay's cursor. */ +function harness( + stored: EventData[], + options: { + membership?: "open" | "roster"; + send?: (body: Record) => Promise; + profiles?: EventData[]; + } = {}, +) { + const reads: ReadFilter[][] = []; + let fail: Error | undefined; + let gate: Promise | undefined; + const live = new Set<(batch: { events: readonly EventData[] }) => void>(); + const reconnect = new Set<() => void>(); + const sent: Record[] = []; + let clock = 10_000; + const owner = createMentionGroups({ + support: { + membership: options.membership ?? "open", + defaultManage: "everyone", + }, + viewer, + relayAuthor: author, + now: () => clock, + async read(filters) { + reads.push([...filters]); + await gate; + if (fail) throw fail; + return filters.flatMap((filter) => { + if (filter.kinds?.includes(0)) + return (options.profiles ?? []).filter((event) => + filter.authors?.includes(event.pubkey), + ); + const matches = stored + .filter( + (event) => + filter.kinds?.includes(event.kind) && + (!filter["#d"] || + filter["#d"].includes( + event.tags.find(([n]) => n === "d")?.[1] ?? "", + )) && + (filter.until === undefined || + event.created_at < filter.until || + (event.created_at === filter.until && + event.id > (filter.before_id ?? ""))), + ) + .sort( + (a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id), + ); + return matches.slice(0, Math.min(filter.limit, 2)); + }); + }, + async send(body) { + sent.push(body); + return (options.send?.(body) ?? { + accepted: true, + event_id: "x", + }) as never; + }, + subscribeLive(listener) { + live.add(listener); + return () => live.delete(listener); + }, + subscribeReconnect(listener) { + reconnect.add(listener); + return () => reconnect.delete(listener); + }, + }); + return { + owner, + reads, + sent, + stored, + snapshot: () => owner.directory.snapshot(), + deliver: (...events: EventData[]) => { + for (const listener of live) listener({ events }); + }, + reconnect: () => { + for (const listener of reconnect) listener(); + }, + failReads: (error?: Error) => { + fail = error; + }, + hold: () => { + let release = () => {}; + gate = new Promise((resolve) => { + release = () => { + gate = undefined; + resolve(); + }; + }); + return release; + }, + tick: (seconds: number) => { + clock += seconds; + }, + }; +} +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +it("pages every head before showing groups, newest version per group, and keeps a deleted group hidden", async () => { + // Pages of two: the relay's cursor walks five heads, ties included. + const h = harness([ + head(groupA, 1, "Old name", [person]), + head(groupA, 3, "On call", [person, admin]), + head(groupB, 1, "Design", [person], [], 1003), + tombstone("2e9b7c3d-1a2b-4c3d-8e4f-5a6b7c8d9e0f", 2), + // Malformed: one bad head is dropped and the rest stay. + { ...head(groupB, 9, "", [person]), tags: [["d", groupB]] }, + roster([[admin, "admin"]]), + ]); + expect(h.snapshot()).toMatchObject({ status: "loading", groups: [] }); + await settle(); + expect(h.reads.length).toBeGreaterThan(3); + expect(h.snapshot()).toMatchObject({ + status: "ready", + groups: [ + { id: groupB, name: "Design", members: [person] }, + { id: groupA, name: "On call", version: "3", members: [person, admin] }, + ], + }); + expect(h.owner.recovery.status()).toBe("settled"); +}); + +it("folds live heads by version, ignores older ones, and repairs an equal-version conflict once", async () => { + const h = harness([head(groupA, 2, "On call", [person])]); + await settle(); + const reads = h.reads.length; + h.deliver(head(groupA, 1, "Older", [person])); + expect(h.snapshot().groups[0]).toMatchObject({ name: "On call" }); + h.deliver(head(groupA, 3, "Renamed", [person, admin])); + expect(h.snapshot().groups[0]).toMatchObject({ + name: "Renamed", + version: "3", + }); + // The same version under another id is a protocol error: keep the current + // head and read the authoritative one, once per version. + h.deliver(head(groupA, 3, "Fork", [person])); + h.deliver(head(groupA, 3, "Fork again", [person])); + await settle(); + expect(h.snapshot().groups[0]).toMatchObject({ name: "Renamed" }); + expect(h.reads.length).toBeGreaterThan(reads); + const repaired = h.reads.length; + h.deliver(head(groupA, 3, "Third fork", [person])); + await settle(); + expect(h.reads.length).toBe(repaired); + // A tombstone removes the row; a missing head never does. + h.deliver(tombstone(groupA, 4)); + expect(h.snapshot().groups).toEqual([]); +}); + +it("never empties on a failed reconcile, retries through recovery, and runs one trailing read for overlapping reconnects", async () => { + const h = harness([head(groupA, 1, "On call", [person])]); + await settle(); + h.failReads(new Error("offline")); + h.reconnect(); + await settle(); + expect(h.snapshot()).toMatchObject({ + status: "ready", + error: "offline", + groups: [{ name: "On call" }], + }); + expect(h.owner.recovery.status()).toBe("failed"); + h.failReads(); + h.stored.push(head(groupB, 1, "Design", [person])); + h.owner.recovery.retry(); + await settle(); + expect(h.snapshot().groups.map((g) => g.name)).toEqual(["Design", "On call"]); + expect(h.owner.recovery.status()).toBe("settled"); + // Many reconnect signals during one read: that read, then one more. + const release = h.hold(); + const before = h.reads.length; + h.reconnect(); + h.reconnect(); + h.reconnect(); + expect(h.owner.recovery.status()).toBe("busy"); + release(); + await settle(); + await settle(); + const firstPages = h.reads + .slice(before) + .filter((filters) => filters.length === 2).length; + expect(firstPages).toBe(2); +}); + +it("shows nothing and reports unavailable when the first read fails", async () => { + const h = harness([head(groupA, 1, "On call", [person])]); + h.failReads(new Error("offline")); + await settle(); + // Live heads alone are not a complete directory. + h.deliver(head(groupA, 2, "On call", [person])); + expect(h.snapshot()).toMatchObject({ + status: "unavailable", + groups: [], + error: "offline", + }); +}); + +it("on a roster relay offers only current members and owner-admitted agents", async () => { + // NIP-OA test vector (owner secret 1, agent secret 2), as in + // owner-attestation.test.ts: the owner is a roster member. + const owner = + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + const admittedAgent = + "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; + const proof = [ + "auth", + owner, + "kind=1&created_at<1713957000", + "8b7df2575caf0a108374f8471722b233c53f9ff827a8b0f91861966c3b9dd5cb2e189eae9f49d72187674c2f5bd244145e10ff86c9f257ffe65a1ee5f108b369", + ]; + const profile = (pubkey: string, auth: string[]): EventData => ({ + id: id(), + pubkey, + kind: 0, + created_at: 1, + content: "{}", + tags: [auth], + }); + const h = harness( + [ + head(groupA, 1, "On call", [person, removed, admittedAgent, agent]), + roster([ + [person, "member"], + [owner, "member"], + [viewer, "member"], + ]), + ], + { + membership: "roster", + profiles: [ + profile(admittedAgent, proof), + // A forged proof names a member but is not signed by them. + profile(agent, ["auth", owner, "", "a".repeat(128)]), + ], + }, + ); + await settle(); + // While the profile lookup runs, the group waits rather than sending to a + // partial set. + expect(h.snapshot().groups[0]?.members).toBeNull(); + await vi.waitFor(() => + expect(h.snapshot().groups[0]?.members).toEqual([person, admittedAgent]), + ); + expect(h.snapshot().groups[0]?.stored).toEqual([ + person, + removed, + admittedAgent, + agent, + ]); + // An open relay never filters. + const open = harness([head(groupA, 1, "On call", [person, removed])]); + await settle(); + expect(open.snapshot().groups[0]?.members).toEqual([person, removed]); +}); + +it("lets any member edit under Everyone, only stewards under admins, and only stewards change the setting", async () => { + const stewards = roster([ + [admin, "admin"], + [person, "member"], + ]); + const h = harness([stewards]); + await settle(); + // No setting head yet: the default is Everyone at version 0. + expect(h.snapshot()).toMatchObject({ + manage: "everyone", + settingVersion: "0", + canEdit: true, + canManage: false, + }); + h.deliver(settings("admins", 1)); + expect(h.snapshot()).toMatchObject({ + manage: "admins", + settingVersion: "1", + canEdit: false, + canManage: false, + }); + h.deliver({ + ...stewards, + id: id(), + created_at: 600, + tags: [["member", viewer, "admin"]], + }); + expect(h.snapshot()).toMatchObject({ + role: "admin", + canEdit: true, + canManage: true, + }); + // A community with no steward lets any member change it. + const rosterless = harness([settings("admins", 2)]); + await settle(); + expect(rosterless.snapshot()).toMatchObject({ + canEdit: true, + canManage: true, + }); +}); + +it("resends the same event after an unknown outcome and types each relay answer", async () => { + let answer: () => Promise = () => + Promise.reject(new Error("Failed to fetch")); + const h = harness([], { send: () => answer() }); + await settle(); + const input = { + id: groupA, + prev: "0", + name: "On call", + members: [person], + channels: [], + }; + const lost = await h.owner.put(input); + expect(lost).toMatchObject({ outcome: "unknown" }); + answer = () => Promise.resolve({ accepted: true, event_id: lost.eventId }); + h.tick(30); + const retried = await lost.retry?.(); + expect(retried).toMatchObject({ outcome: "accepted", eventId: lost.eventId }); + expect(h.sent[1]).toEqual(h.sent[0]); + // After acceptance, the changed head is read in case live delivery lags. + expect(h.reads.at(-1)?.[0]).toMatchObject({ "#d": [groupA], limit: 1 }); + for (const [text, outcome] of [ + ["conflict: mention group version changed", "conflict"], + ["duplicate: mention group name already exists", "name-taken"], + [ + "restricted: community policy does not permit this mention group command", + "forbidden", + ], + ["invalid: name too long", "invalid"], + ["Community request failed (500)", "unknown"], + ] as const) { + answer = () => Promise.reject(new Error(text)); + const result = await h.owner.put(input); + expect(result.outcome).toBe(outcome); + expect(!!result.retry).toBe(outcome === "unknown"); + } + // Long after the relay's freshness window, a retry is still the same + // event: the relay answers an accepted one from its receipt. + answer = () => Promise.reject(new Error("Failed to fetch")); + const stale = await h.owner.setManage({ manage: "admins", prev: "0" }); + h.tick(60 * 60); + answer = () => + Promise.resolve({ + accepted: true, + message: 'duplicate: joins: {"joined":2,"skipped":{"channel_closed":1}}', + }); + const resent = await stale.retry?.(); + expect(resent).toMatchObject({ + outcome: "accepted", + eventId: stale.eventId, + joins: { joined: 2, skipped: { channel_closed: 1 } }, + }); + expect(h.sent.at(-1)).toEqual(h.sent.at(-2)); +}); + +it("reads and sends nothing when the relay has no mention groups", async () => { + const read = vi.fn(); + const owner = createMentionGroups({ + support: undefined, + viewer, + relayAuthor: author, + read, + send: vi.fn(), + subscribeLive: () => () => {}, + subscribeReconnect: () => () => {}, + }); + await settle(); + expect(read).not.toHaveBeenCalled(); + expect(owner.supported).toBe(false); + expect(owner.directory.snapshot()).toMatchObject({ + status: "unsupported", + groups: [], + }); + await expect(owner.remove({ id: groupA, prev: "1" })).rejects.toThrow(); +}); diff --git a/src/features/communities/mention-groups.ts b/src/features/communities/mention-groups.ts new file mode 100644 index 0000000000..e2dc370b8c --- /dev/null +++ b/src/features/communities/mention-groups.ts @@ -0,0 +1,689 @@ +// Community mention groups (relay NIP-MG): the relay owns every group and +// signs its current state as kind 39010. This module folds that state into one +// directory per relay session and sends the viewer's put, delete and setting +// commands. The relay decides authority; `canEdit` only shapes the UI. +import { getEventHash } from "nostr-tools"; +import { authTagOwner } from "../agents/owner-attestation"; +import type { EventData, ReadFilter } from "../relay/events"; +import type { RecoverySource, RecoveryStatus } from "../relay/recovery"; +import { + MENTION_GROUP_KINDS, + mentionGroupCommand, + mentionGroupName, + type MentionGroupSupport, +} from "./admin-protocol"; +import { MEMBERSHIP_KIND, membersFromSnapshot, type Role } from "./roster"; + +export type ManageSetting = "admins" | "everyone"; +type Head = Readonly<{ + id: string; + version: bigint; + eventId: string; + /** The accepted command that produced this head. */ + command: string; + name: string; + members: readonly string[]; + channels: readonly string[]; + deleted: boolean; +}>; +type Settings = Readonly<{ + manage: ManageSetting; + version: bigint; + eventId: string; +}>; +type Roster = Readonly<{ + eventId: string; + createdAt: number; + roles: ReadonlyMap; +}>; +/** Everything folded so far. Pages and live frames only ever add to it, so a + * missing head never deletes a group. */ +export type Folded = Readonly<{ + heads: ReadonlyMap; + settings?: Settings; + /** null: the relay publishes no roster; undefined: not read yet. */ + roster?: Roster | null; +}>; + +// The directory's lifecycle. Groups are shown only once a complete read has +// landed (`ready`, `reconciling`, `stale`); before that, rows wait. +export type DirectoryState = + | Readonly<{ status: "unsupported" }> + | Readonly<{ status: "loading"; data: Folded }> + | Readonly<{ status: "unavailable"; data: Folded; error: string }> + | Readonly<{ status: "ready"; data: Folded }> + | Readonly<{ status: "reconciling"; data: Folded }> + | Readonly<{ status: "stale"; data: Folded; error: string }>; +export type DirectoryAction = + | Readonly<{ type: "read" }> + | Readonly<{ type: "read-done" }> + | Readonly<{ type: "read-failed"; error: string }> + | Readonly<{ type: "fold"; data: Folded }>; + +const empty: Folded = Object.freeze({ heads: new Map() }); +export const initialDirectory = (supported: boolean): DirectoryState => + supported ? { status: "loading", data: empty } : { status: "unsupported" }; +const shown = (state: DirectoryState) => + state.status === "ready" || + state.status === "reconciling" || + state.status === "stale"; + +/** Pure transitions. A failure never empties a directory that has been ready. */ +export function reduceDirectory( + state: DirectoryState, + action: DirectoryAction, +): DirectoryState { + if (state.status === "unsupported") return state; + switch (action.type) { + case "fold": + return { ...state, data: action.data }; + case "read": + return shown(state) + ? { status: "reconciling", data: state.data } + : { status: "loading", data: state.data }; + case "read-done": + return { status: "ready", data: state.data }; + case "read-failed": + return shown(state) + ? { status: "stale", data: state.data, error: action.error } + : { status: "unavailable", data: state.data, error: action.error }; + } +} + +const UUID = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const VERSION = /^(?:0|[1-9][0-9]{0,18})$/; +const KEY = /^[0-9a-f]{64}$/; +const ID = /^[0-9a-f]{64}$/; +const single = (event: EventData, name: string) => { + const found = event.tags.filter((tag) => tag[0] === name); + return found.length === 1 && found[0]?.length === 2 ? found[0][1] : undefined; +}; + +/** A relay-signed group head or settings head, or undefined when malformed: + * one bad head is dropped and the rest stay. */ +export function parseState( + event: EventData, + author: string, +): Head | Settings | undefined { + if (event.kind !== MENTION_GROUP_KINDS.state || event.pubkey !== author) + return undefined; + const d = single(event, "d"); + const version = single(event, "version"); + if (!d || !version || !VERSION.test(version)) return undefined; + if (d === "settings") { + const manage = single(event, "manage"); + return manage === "admins" || manage === "everyone" + ? { manage, version: BigInt(version), eventId: event.id } + : undefined; + } + const command = single(event, "command"); + if (!UUID.test(d) || !command || !ID.test(command)) return undefined; + const deleted = event.tags.some( + ([name, value]) => name === "deleted" && value === "true", + ); + if (deleted) + return { + id: d, + version: BigInt(version), + eventId: event.id, + command, + name: "", + members: [], + channels: [], + deleted: true, + }; + const name = mentionGroupName(single(event, "name")); + if (!name) return undefined; + const list = (tag: string, valid: (value: string) => boolean) => [ + ...new Set( + event.tags.flatMap(([name, value]) => + name === tag && value && valid(value) ? [value] : [], + ), + ), + ]; + return { + id: d, + version: BigInt(version), + eventId: event.id, + command, + name, + members: list("p", (key) => KEY.test(key)), + channels: list("channel", (id) => /^[a-zA-Z0-9_-]{1,128}$/.test(id)), + deleted: false, + }; +} + +/** Folds events into the directory by version. An equal version under a + * different event id keeps the current head and asks for a repair read. */ +export function foldEvents( + data: Folded, + events: readonly EventData[], + author: string, + /** These events answer a roster read: none found means no roster. */ + rosterRead = false, +): { data: Folded; repair: readonly string[] } { + let heads: Map | undefined; + let { settings, roster } = data; + if ( + rosterRead && + roster === undefined && + !events.some((e) => e.kind === MEMBERSHIP_KIND && e.pubkey === author) + ) + roster = null; + const repair: string[] = []; + for (const event of events) { + if (event.kind === MEMBERSHIP_KIND && event.pubkey === author) { + if ( + roster && + (event.created_at < roster.createdAt || + (event.created_at === roster.createdAt && event.id >= roster.eventId)) + ) + continue; + try { + const members = membersFromSnapshot(event, author); + roster = { + eventId: event.id, + createdAt: event.created_at, + roles: new Map(members.map((member) => [member.pubkey, member.role])), + }; + } catch { + // Not this community's roster; ignore it. + } + continue; + } + const head = parseState(event, author); + if (!head) continue; + const current = + "id" in head ? (heads ?? data.heads).get(head.id) : settings; + if (current && current.version > head.version) continue; + if (current && current.version === head.version) { + if (current.eventId !== head.eventId) + repair.push(`${"id" in head ? head.id : "settings"}:${head.version}`); + continue; + } + if ("id" in head) { + heads ??= new Map(data.heads); + heads.set(head.id, head); + } else settings = head; + } + const changed = + heads !== undefined || settings !== data.settings || roster !== data.roster; + return { + data: changed + ? { + heads: heads ?? data.heads, + ...(settings ? { settings } : {}), + ...(roster !== undefined ? { roster } : {}), + } + : data, + repair, + }; +} + +export type MentionGroupView = Readonly<{ + id: string; + version: string; + name: string; + /** Current community members only. null while membership is still being + * established for this group: never offer or send to a partial set. */ + members: readonly string[] | null; + /** Every stored key, for the editor (removed members are pruned on save). */ + stored: readonly string[]; + channels: readonly string[]; + /** The accepted command that produced this version. */ + command: string; +}>; +export type MentionGroupDirectory = Readonly<{ + status: "unsupported" | "loading" | "unavailable" | "ready" | "reconciling"; + groups: readonly MentionGroupView[]; + membership?: MentionGroupSupport["membership"]; + manage: ManageSetting; + /** The setting's version, the `prev` for setManage. */ + settingVersion: string; + role?: Role; + /** May the viewer put or delete groups? */ + canEdit: boolean; + /** May the viewer change "Who can manage groups"? */ + canManage: boolean; + error?: string; +}>; + +/** Pure projection of the folded state. `admitted` answers whether a key + * outside the roster is an owner-admitted agent (undefined: not known yet). */ +export function projectDirectory( + state: DirectoryState, + support: MentionGroupSupport | undefined, + viewer: string, + admitted: (key: string) => boolean | undefined, +): MentionGroupDirectory { + const data = state.status === "unsupported" ? empty : state.data; + const manage = data.settings?.manage ?? support?.defaultManage ?? "everyone"; + const roles = data.roster?.roles; + const role = roles?.get(viewer); + const steward = !!roles && [...roles.values()].some((r) => r !== "member"); + const roster = support?.membership === "roster"; + // The predicate the relay enforces: on an open relay every authenticated + // key belongs; on a roster relay a roster entry or an owner-admitted agent. + const member = (key: string): boolean | undefined => + !roster || !data.roster || data.roster.roles.has(key) + ? true + : admitted(key); + const viewerMember = member(viewer) === true; + const ready = shown(state); + const groups = ready + ? [...data.heads.values()] + .filter((head) => !head.deleted) + .map((head) => { + const known = head.members.map((key) => [key, member(key)] as const); + return { + id: head.id, + version: head.version.toString(), + name: head.name, + members: known.some(([, value]) => value === undefined) + ? null + : known.flatMap(([key, value]) => (value ? [key] : [])), + stored: head.members, + channels: head.channels, + command: head.command, + }; + }) + .sort( + (a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id), + ) + : []; + const manager = role === "owner" || role === "admin"; + return { + status: state.status === "stale" ? "ready" : state.status, + groups, + ...(support ? { membership: support.membership } : {}), + manage, + settingVersion: (data.settings?.version ?? 0n).toString(), + ...(role ? { role } : {}), + canEdit: + ready && viewerMember && (manage === "everyone" || manager || !steward), + canManage: ready && viewerMember && (manager || !steward), + ...("error" in state ? { error: state.error } : {}), + }; +} + +export type MentionGroupOutcome = + | "accepted" + | "conflict" + | "name-taken" + | "forbidden" + | "invalid" + | "unknown"; +export type MentionGroupCommand = Readonly<{ + /** The event id of this attempt; the head's `command` tag equals it once + * the directory shows the result. Kept across retries. */ + eventId: string; + outcome: MentionGroupOutcome; + /** The relay's own answer, when it gave one. */ + message?: string; + /** Default-channel joins the accepted save made, and the ones it skipped + * by reason. A resend reports the original save's joins. */ + joins?: Readonly<{ + joined: number; + skipped: Readonly>; + }>; + /** Only an unknown outcome can be retried: it resends the same event. */ + retry?: () => Promise; +}>; +export type MentionGroupReceipt = Readonly<{ + accepted: boolean; + event_id?: string; + message?: string; +}>; + +/** The relay's `joins: {...}` report at the end of an accepted answer. */ +function joinReport(text: string | undefined) { + const json = /(?:^|\s)joins: (\{.*\})$/.exec(text ?? "")?.[1]; + try { + const report: unknown = json ? JSON.parse(json) : undefined; + const { joined, skipped } = (report ?? {}) as Record; + if ( + !Number.isSafeInteger(joined) || + !skipped || + typeof skipped !== "object" || + !Object.values(skipped).every((n) => Number.isSafeInteger(n)) + ) + return undefined; + return { + joined: joined as number, + skipped: { ...(skipped as Record) }, + }; + } catch { + return undefined; + } +} + +/** Typed outcome from the relay's answer. Only the relay's own prefixes are + * trusted; anything else is unknown and may be retried. */ +export function commandOutcome(text: string | undefined): MentionGroupOutcome { + if (!text) return "unknown"; + if (text.startsWith("conflict: ")) return "conflict"; + if (text.startsWith("duplicate: mention group name")) return "name-taken"; + if (text === "duplicate:" || text.startsWith("duplicate: ")) + return "accepted"; + if (text.startsWith("restricted: ") || text.startsWith("blocked: ")) + return "forbidden"; + if (text.startsWith("invalid: ")) return "invalid"; + return "unknown"; +} + +type Request = Readonly & { created_at: number }>; +export type MentionGroupDeps = Readonly<{ + support: MentionGroupSupport | undefined; + viewer: string; + relayAuthor: string; + read( + filters: readonly ReadFilter[], + signal: AbortSignal, + ): Promise; + send(body: Request, signal: AbortSignal): Promise; + /** Verified live delivery, including the batches a reconnect replays. */ + subscribeLive( + listener: (batch: { events: readonly EventData[] }) => void, + ): () => void; + /** Called on every reconnect after the first connection. */ + subscribeReconnect(listener: () => void): () => void; + now?: () => number; +}>; + +const PAGE = 500; +const MAX_PAGES = 40; +const message = (reason: unknown) => + reason instanceof Error ? reason.message : String(reason); +const newest = (a: EventData, b: EventData) => + b.created_at - a.created_at || a.id.localeCompare(b.id); + +/** One mention group owner per relay session: the live directory, its + * recovery source, and the viewer's commands. */ +export function createMentionGroups(deps: MentionGroupDeps) { + const { support, viewer, relayAuthor: author } = deps; + const now = deps.now ?? (() => Math.floor(Date.now() / 1000)); + const lifetime = new AbortController(); + const listeners = new Set<() => void>(); + let state = initialDirectory(!!support && !!author && !!viewer); + let view: MentionGroupDirectory | undefined; + // Owner-admitted agents outside the roster, by key: owner key or null. + const owners = new Map(); + const looking = new Set(); + let lookupFailed = false; + const repaired = new Set(); + let reading: Promise | undefined; + let again = false; + + const publish = () => { + view = undefined; + for (const listener of listeners) listener(); + }; + const dispatch = (action: DirectoryAction) => { + const next = reduceDirectory(state, action); + if (next === state) return; + state = next; + publish(); + }; + const fold = (events: readonly EventData[], rosterRead = false) => { + if (state.status === "unsupported") return; + const { data, repair } = foldEvents(state.data, events, author, rosterRead); + if (data !== state.data) dispatch({ type: "fold", data }); + // Repair an equal-version conflict once per head version. + if (repair.some((key) => !repaired.has(key))) { + for (const key of repair) repaired.add(key); + reconcile(); + } + admit(); + }; + + /** One paged read of every head, single-flight with one trailing rerun. */ + function reconcile() { + if (state.status === "unsupported" || lifetime.signal.aborted) return; + if (reading) { + again = true; + return; + } + dispatch({ type: "read" }); + reading = (async () => { + try { + let cursor: { until: number; before_id: string } | undefined; + for (let page = 0; ; page++) { + if (page >= MAX_PAGES) + throw new Error("Too many mention groups to read"); + const filters: ReadFilter[] = [ + { + kinds: [MENTION_GROUP_KINDS.state], + authors: [author], + limit: PAGE, + ...cursor, + }, + ]; + if (!page) + filters.push({ + kinds: [MEMBERSHIP_KIND], + authors: [author], + limit: 1, + }); + const events = [...(await deps.read(filters, lifetime.signal))]; + lifetime.signal.throwIfAborted(); + fold(events, !page); + const heads = events + .filter((event) => event.kind === MENTION_GROUP_KINDS.state) + .sort(newest); + const last = heads.at(-1); + if (!last) break; + const previous = cursor; + if ( + previous && + heads.some( + (event) => + event.created_at > previous.until || + (event.created_at === previous.until && + event.id <= previous.before_id), + ) + ) + throw new Error("Mention group pages did not advance"); + cursor = { until: last.created_at, before_id: last.id }; + } + dispatch({ type: "read-done" }); + } catch (reason) { + if (lifetime.signal.aborted) return; + dispatch({ type: "read-failed", error: message(reason) }); + } finally { + reading = undefined; + if (again && !lifetime.signal.aborted) { + again = false; + reconcile(); + } + } + })(); + } + + /** Looks up owner-admitted agents for stored keys outside a roster. */ + function admit() { + if (state.status === "unsupported" || support?.membership !== "roster") + return; + const roster = state.data.roster; + if (!roster) return; + const unknown = [ + ...new Set( + [...state.data.heads.values()].flatMap((head) => head.members), + ), + ].filter( + (key) => !roster.roles.has(key) && !owners.has(key) && !looking.has(key), + ); + if (!unknown.length) return; + for (const key of unknown) looking.add(key); + void (async () => { + try { + const events = await deps.read( + [{ kinds: [0], authors: unknown, limit: unknown.length }], + lifetime.signal, + ); + lifetime.signal.throwIfAborted(); + for (const key of unknown) { + const profile = events + .filter((event) => event.kind === 0 && event.pubkey === key) + .sort(newest)[0]; + const [tag, ...extra] = + profile?.tags.filter(([name]) => name === "auth") ?? []; + owners.set( + key, + tag && !extra.length + ? ((await authTagOwner(key, tag)) ?? null) + : null, + ); + } + lookupFailed = false; + } catch { + if (lifetime.signal.aborted) return; + lookupFailed = true; + } finally { + for (const key of unknown) looking.delete(key); + } + publish(); + })(); + } + const admitted = (key: string) => { + if (!owners.has(key)) return undefined; + const owner = owners.get(key); + const roles = + state.status === "unsupported" ? undefined : state.data.roster?.roles; + return !!owner && !!roles?.has(owner); + }; + + // A relay without mention groups gets no listeners and no reads. + const supported = state.status !== "unsupported"; + const stopLive = supported + ? deps.subscribeLive(({ events }) => { + const relevant = events.filter( + (event) => + event.pubkey === author && + (event.kind === MENTION_GROUP_KINDS.state || + event.kind === MEMBERSHIP_KIND), + ); + if (relevant.length) fold(relevant); + }) + : () => {}; + // A reconnect may have dropped frames the replay does not return. + const stopReconnect = supported + ? deps.subscribeReconnect(reconcile) + : () => {}; + reconcile(); + + async function command(body: Request): Promise { + if (state.status === "unsupported") + throw new Error("Mention groups are unavailable in this community"); + const template = mentionGroupCommand(body, now()); + const eventId = getEventHash({ ...template, pubkey: viewer }); + const attempt = async (): Promise => { + const result = (outcome: MentionGroupOutcome, text?: string) => { + const joins = outcome === "accepted" ? joinReport(text) : undefined; + return Object.freeze({ + eventId, + outcome, + ...(text ? { message: text } : {}), + ...(joins ? { joins } : {}), + ...(outcome === "unknown" && !lifetime.signal.aborted + ? { + // Always the same event: the relay answers an accepted one + // from its receipt at any age, and refuses a stale new one. + retry: attempt, + } + : {}), + }); + }; + if (lifetime.signal.aborted) return result("unknown"); + try { + const receipt = await deps.send(body, lifetime.signal); + const outcome = receipt.accepted + ? "accepted" + : commandOutcome(receipt.message); + if (outcome === "accepted") confirm(body); + return result(outcome, receipt.message); + } catch (reason) { + const text = message(reason); + const outcome = commandOutcome(text); + if (outcome === "accepted") confirm(body); + return result(outcome, outcome === "unknown" ? undefined : text); + } + }; + return attempt(); + } + /** After acceptance, read the changed head in case live delivery lags. */ + function confirm(body: Request) { + const d = body.action === "manage" ? "settings" : String(body.id); + void deps + .read( + [ + { + kinds: [MENTION_GROUP_KINDS.state], + authors: [author], + "#d": [d], + limit: 1, + }, + ], + lifetime.signal, + ) + .then(fold, () => {}); + } + + const recovery: RecoverySource = Object.freeze({ + status(): RecoveryStatus { + if (state.status === "loading" || state.status === "reconciling") + return "busy"; + return state.status === "unavailable" || + state.status === "stale" || + lookupFailed + ? "failed" + : "settled"; + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + retry() { + if (lookupFailed) { + lookupFailed = false; + admit(); + } + if (state.status === "unavailable" || state.status === "stale") + reconcile(); + }, + reauthorize: reconcile, + }); + + return Object.freeze({ + supported, + recovery, + directory: Object.freeze({ + snapshot(): MentionGroupDirectory { + view ??= Object.freeze( + projectDirectory(state, support, viewer, admitted), + ); + return view; + }, + subscribe: recovery.subscribe, + }), + put: (input: { + id: string; + prev: string; + name: string; + members: readonly string[]; + channels: readonly string[]; + }) => command({ action: "put", ...input, created_at: now() }), + remove: (input: { id: string; prev: string }) => + command({ action: "remove", ...input, created_at: now() }), + setManage: (input: { manage: ManageSetting; prev: string }) => + command({ action: "manage", ...input, created_at: now() }), + dispose() { + lifetime.abort(); + stopLive(); + stopReconnect(); + listeners.clear(); + }, + }); +} + +export type MentionGroups = ReturnType; diff --git a/src/features/communities/native-api.test.ts b/src/features/communities/native-api.test.ts index f98f4206e7..292fe05831 100644 --- a/src/features/communities/native-api.test.ts +++ b/src/features/communities/native-api.test.ts @@ -213,16 +213,16 @@ it("resends the same signed group change, so a retry after a lost receipt is ans it.each([ [ - "conflict: mention group version is 3", - "conflict: mention group version is 3", + "conflict: mention group version changed", + "conflict: mention group version changed", ], [ "duplicate: mention group name already exists", "duplicate: mention group name already exists", ], [ - "restricted: only owners and admins manage groups", - "restricted: only owners and admins manage groups", + "restricted: community policy does not permit this mention group command", + "restricted: community policy does not permit this mention group command", ], ["database error: connection reset", "Community request failed (409)"], ])("keeps the relay's typed group answer %j", async (error, shown) => { diff --git a/src/features/relay/live.test.ts b/src/features/relay/live.test.ts index e20d5d9d76..04fe843450 100644 --- a/src/features/relay/live.test.ts +++ b/src/features/relay/live.test.ts @@ -402,6 +402,12 @@ it("uses independent explicit channel routes and self-p globals; equal interests since: expect.any(Number), limit: 1, }); + // Community mention group heads ride the same global route. + expect(filtersOf(membershipRequest)).toContainEqual({ + kinds: [39010], + since: expect.any(Number), + limit: 500, + }); const before = h.first.sent.length; h.owner.update(["b", "a", "a"]); expect(h.first.sent).toHaveLength(before); diff --git a/src/features/relay/live.ts b/src/features/relay/live.ts index 323338812e..adcb715263 100644 --- a/src/features/relay/live.ts +++ b/src/features/relay/live.ts @@ -1364,6 +1364,12 @@ export function subscribeRelayTraffic( since: route.since, limit: 1, }, + // NIP-MG group and setting heads; the directory checks the author. + { + kinds: [39010], + since: route.since, + limit: LIVE_REPLAY_LIMIT, + }, { kinds: [30078], authors: [viewer], diff --git a/src/features/relay/native.test.ts b/src/features/relay/native.test.ts index 891c50e3c2..51fd471115 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -261,6 +261,44 @@ it.each([ ).toBeUndefined(); }, ); +it.each([ + [{}, undefined], + [{ supported_extensions: ["nip-mg"] }, undefined], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 2, membership: "open" }, + }, + undefined, + ], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "members" }, + }, + undefined, + ], + [{ mention_groups: { version: 1, membership: "open" } }, undefined], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { + version: 1, + membership: "roster", + default_manage: "admins", + }, + }, + { membership: "roster", defaultManage: "admins" }, + ], +])( + "offers mention groups only with a v1 NIP-MG advertisement: %o", + async (advertised, support) => { + discovery = advertised; + expect((await connectNativeTransport(community)).mentionGroups).toEqual( + support, + ); + }, +); it("publishes config artifacts straight to the relay, re-sending identical bytes and keeping typed refusals", async () => { discovery = { supported_extensions: ["nip-ar"] }; const transport = await connectNativeTransport(community); diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index 8e202c6ad4..854b7a2430 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -12,6 +12,7 @@ import { Channel, convertFileSrc, invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import type { EventTemplate } from "nostr-tools"; import { communityDestination, relayOrigin } from "../communities/destination"; +import { mentionGroupSupport } from "../communities/admin-protocol"; import { audioDemuxer, isHeic, @@ -460,6 +461,7 @@ export async function connectNativeTransport( const searchSort = Array.isArray(info.supported_extensions) && info.supported_extensions.includes("buzz-search-sort"); + const mentionGroups = mentionGroupSupport(info); const artifacts = info.artifacts as | { sync?: { version?: unknown } } | undefined; @@ -960,6 +962,7 @@ export async function connectNativeTransport( nativeAttachmentUpload(origin, file, signal, progress), ...(channelIdentity ? { channelIdentity: true as const } : {}), ...(searchSort ? { searchSort: true as const } : {}), + ...(mentionGroups ? { mentionGroups } : {}), ...(artifactSync ? { artifactSync: true as const } : {}), verifiedProfiles: verifiedProfileAuthority(info), async readVerifiedProfileAuthority(signal) { diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index fb53c9ca11..b3fa75b5fc 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -110,6 +110,8 @@ import { PRODUCT_FEEDBACK_KIND } from "./product-feedback"; import { attemptEnded } from "./withdraw"; import type { ReadTransport } from "./transport"; import type { LiveGlobal, LiveSnapshot, LiveSubscription } from "./live"; +import { communityRequest } from "../communities/api"; +import { createMentionGroups } from "../communities/mention-groups"; import { hasTag, type ReadFilter, @@ -2401,6 +2403,34 @@ export function createRelaySession( writes?.local, ), ); + // Community mention groups: one live directory per session, read fresh + // from the relay and kept current by the global live route. + const mentionGroups = createMentionGroups({ + support: + transport?.scope && !options.cachedOnly + ? transport.mentionGroups + : undefined, + viewer: transport?.viewer ?? "", + relayAuthor: transport?.relayAuthor ?? "", + read: (filters, signal) => + readVerified(filters, { signal, fresh: true }, false), + send: (body, signal) => + communityRequest(transport?.scope ?? "", "mention-group", body, signal), + subscribeLive(listener) { + replayListeners.add(listener); + return () => replayListeners.delete(listener); + }, + subscribeReconnect(listener) { + let connected = live.snapshot().status === "connected"; + let reconnect = connected; + return live.subscribe(() => { + const now = live.snapshot().status === "connected"; + if (now && !connected && reconnect) listener(); + reconnect ||= now; + connected = now; + }); + }, + }); const recoverable = ( subscribe: (listener: () => void) => () => void, status: () => RecoveryStatus, @@ -2431,6 +2461,7 @@ export function createRelaySession( // A ready catalog may be revalidating under the old credentials. () => void channelKit.capability.refresh({ after: true }), ), + mentionGroups.recovery, recoverable( soloPreferences.queries.subscribe, () => loadState(soloPreferences.queries.snapshot()), @@ -2462,6 +2493,15 @@ export function createRelaySession( const session = Object.freeze({ artifactIncremental: transport?.artifactIncremental, memberAdditions, + /** Community mention groups (NIP-MG): the live directory, and the + * viewer's put, delete and "Who can manage groups" commands. */ + mentionGroups: Object.freeze({ + supported: mentionGroups.supported, + directory: mentionGroups.directory, + put: mentionGroups.put, + remove: mentionGroups.remove, + setManage: mentionGroups.setManage, + }), presence, viewer: transport?.viewer, relayAuthor: transport?.relayAuthor, @@ -4117,6 +4157,7 @@ export function createRelaySession( lifecycle.dispose(); details.dispose(); memberAdministration.dispose(); + mentionGroups.dispose(); stopInterests(); stopHintGuard(); stopWarmPreferences(); diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index f7558cf6e4..306b6b873d 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -47,6 +47,7 @@ import { } from "./sidebar-preferences"; import { createHostAdmission } from "./host-admission"; import { relayOrigin } from "../communities/destination"; +import type { MentionGroupSupport } from "../communities/admin-protocol"; import { admittedApiRequest, ApiPaused, @@ -144,6 +145,8 @@ export interface ReadTransport { /** The relay advertises NIP-CL (`nip-cl` in NIP-11 `supported_extensions`): * it keeps channel labels and answers label lookups. */ readonly channelIdentity?: true; + /** The relay serves community mention groups (NIP-MG). */ + readonly mentionGroups?: MentionGroupSupport; /** The relay advertises `buzz-search-sort`: bridge search accepts * `search_sort: "newest"`. Older relays silently rank by relevance. */ readonly searchSort?: true; @@ -537,6 +540,7 @@ export async function connectBrokerTransport( channelKit?: boolean; channelIdentity?: boolean; searchSort?: boolean; + mentionGroups?: { membership?: unknown; defaultManage?: unknown }; artifactSync?: boolean; sidebarPreferenceWrites?: boolean; sidebarSectionRemoval?: boolean; @@ -873,6 +877,18 @@ export async function connectBrokerTransport( ? { channelIdentity: true as const } : {}), ...(session.searchSort === true ? { searchSort: true as const } : {}), + ...(session.mentionGroups?.membership === "open" || + session.mentionGroups?.membership === "roster" + ? { + mentionGroups: { + membership: session.mentionGroups.membership, + defaultManage: + session.mentionGroups.defaultManage === "admins" + ? ("admins" as const) + : ("everyone" as const), + }, + } + : {}), ...(session.artifactSync === true ? { artifactSync: true as const } : {}), ...(session.channelKit ? { From 83ef095783ec87644ff14afe7cdcd8c43c18eb72 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 15:06:46 -0500 Subject: [PATCH 13/21] feat(mentions): community mention groups in the @ chooser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Groups from the session's mention group directory join the @ team rows and the toolbar picker as "Group · N people, M agents" and insert one group chip. A group waits while its membership loads, shows disabled when empty, blocks Space auto-select like a team, and revalidates at acceptance. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/bundled/mentions/MentionPicker.tsx | 2 +- src/bundled/mentions/team-mentions.test.tsx | 163 ++++++++++++++++++++ src/bundled/mentions/use-team-mentions.ts | 83 ++++++++-- src/features/relay/session.ts | 1 + 4 files changed, 235 insertions(+), 14 deletions(-) diff --git a/src/bundled/mentions/MentionPicker.tsx b/src/bundled/mentions/MentionPicker.tsx index bc299004ef..2616603ab4 100644 --- a/src/bundled/mentions/MentionPicker.tsx +++ b/src/bundled/mentions/MentionPicker.tsx @@ -373,7 +373,7 @@ export function MentionPicker({

{teams.status}{" "} {teams.canRetry && ( - + )}

)} diff --git a/src/bundled/mentions/team-mentions.test.tsx b/src/bundled/mentions/team-mentions.test.tsx index 8d683c0d2f..2c156690fb 100644 --- a/src/bundled/mentions/team-mentions.test.tsx +++ b/src/bundled/mentions/team-mentions.test.tsx @@ -1548,3 +1548,166 @@ it("projects confirmed synced teams through the real service without colliding w await h.context.fiber.dispose(); } }); + +type GroupDirectory = ReturnType< + RelaySession["mentionGroups"]["directory"]["snapshot"] +>; +type GroupView = GroupDirectory["groups"][number]; + +/** A community mention group directory on the fixture's session. */ +function withGroups( + h: ReturnType, + groups: readonly GroupView[], + status: GroupDirectory["status"] = "ready", +) { + const directory = (next: readonly GroupView[], now = status) => + ({ + status: now, + groups: next, + membership: "open", + manage: "everyone", + settingVersion: "0", + canEdit: true, + canManage: true, + }) satisfies GroupDirectory; + let view: GroupDirectory = directory(groups); + const listeners = new Set<() => void>(); + const retry = vi.fn(); + Object.assign(h.session, { + mentionGroups: { + supported: true, + directory: { + snapshot: () => view, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }, + retry, + }, + }); + return { + retry, + set(next: readonly GroupView[], now = status) { + act(() => { + view = directory(next, now); + for (const listener of listeners) listener(); + }); + }, + }; +} +const groupView = ( + members: readonly string[] | null, + version = "1", + name = "Risk", +): GroupView => ({ + id: "6f1d6c1e-8a4b-4c55-9b0e-2f3a4b5c6d7e", + version, + name, + members, + stored: members ?? [], + channels: [], + command: "c".repeat(64), +}); +const groupRow = (menu: ReturnType) => + menu + .result() + ?.items.find( + (i) => i.id === "team:group:6f1d6c1e-8a4b-4c55-9b0e-2f3a4b5c6d7e", + ); + +it("a community group is one row that inserts one group chip and blocks Space", async () => { + const h = fixture({ count: 2, team: 1 }); + const person = h.people[1]; + if (!person) throw new Error("Fixture needs a person"); + const groups = withGroups(h, [groupView([h.agent.pubkey, person.pubkey])]); + const menu = inline(h.session); + try { + await waitFor(() => + expect(groupRow(menu)?.canSelect?.("Enter")).toBe(true), + ); + expect(groupRow(menu)?.detail).toBe("Group · 1 person, 1 agent"); + expect(groupRow(menu)?.edit).toEqual({ + group: { name: "Risk", mentions: [h.agent, person] }, + }); + // Space after a name that a group continues never auto-selects the person. + menu.view.rerender( + , + ); + const personRow = () => + menu.result()?.items.find((i) => i.id === person.pubkey); + await waitFor(() => expect(personRow()?.canSelect?.(" ")).toBe(true)); + groups.set([ + groupView([h.agent.pubkey, person.pubkey], "2", "Person 01 crew"), + ]); + await waitFor(() => expect(personRow()?.canSelect?.(" ")).toBe(false)); + expect(personRow()?.canSelect?.("Enter")).toBe(true); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); + +it("a group waits while its membership loads and is disabled once it has no members", async () => { + const h = fixture({ count: 2, team: 1 }); + const groups = withGroups(h, [groupView(null)]); + const menu = inline(h.session); + try { + await waitFor(() => expect(menu.team()).toBeDefined()); + expect(groupRow(menu)).toBeUndefined(); + groups.set([groupView([], "2")]); + await waitFor(() => + expect(groupRow(menu)?.disabled).toBe("This group has no members."), + ); + expect(groupRow(menu)?.edit).toEqual({ text: "@Risk" }); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); + +it("a group that changes after its row shows can't be picked until the chooser reopens", async () => { + const h = fixture({ count: 2, team: 1 }); + const person = h.people[1]; + if (!person) throw new Error("Fixture needs a person"); + const groups = withGroups(h, [groupView([h.agent.pubkey, person.pubkey])]); + const menu = inline(h.session); + try { + await waitFor(() => + expect(groupRow(menu)?.canSelect?.("Enter")).toBe(true), + ); + const shown = groupRow(menu); + // A member left the community: same version, fewer current members. + groups.set([groupView([h.agent.pubkey])]); + expect(shown?.canSelect?.("Enter")).toBe(false); + await waitFor(() => + expect(groupRow(menu)?.disabled).toBe( + "Group changed or unavailable. Reopen to refresh.", + ), + ); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); + +it("a failed group directory says so and Retry rereads it", async () => { + const h = fixture({ count: 2, team: 1 }); + const groups = withGroups(h, [], "unavailable"); + const menu = inline(h.session); + try { + await waitFor(() => + expect(menu.result()?.status).toBe( + "Could not load groups. Retry to refresh.", + ), + ); + act(() => menu.result()?.retry?.()); + expect(groups.retry).toHaveBeenCalledOnce(); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); diff --git a/src/bundled/mentions/use-team-mentions.ts b/src/bundled/mentions/use-team-mentions.ts index ea8c503ba1..288c8b5072 100644 --- a/src/bundled/mentions/use-team-mentions.ts +++ b/src/bundled/mentions/use-team-mentions.ts @@ -51,6 +51,11 @@ export function teamBlocksSpace( } const subscribeNone = () => () => {}; const snapshotNone = () => empty; +const snapshotNoGroups = () => undefined; +const sameKeys = ( + a: readonly string[] | null | undefined, + b: readonly string[] | null | undefined, +) => !!a && !!b && a.length === b.length && a.every((key, i) => key === b[i]); /** "1 person, 2 agents": what a team row says it mentions. */ function teamCount( @@ -68,7 +73,8 @@ function teamCount( .filter(Boolean) .join(", "); } -/** Saved teams are shortcuts to exact individual recipients, never new identities. */ +/** Saved teams and community mention groups are shortcuts to exact individual + * recipients, never new identities. */ export function useTeamMentions( session: ComposerSession, channelId: string, @@ -94,6 +100,14 @@ export function useTeamMentions( useEffect(() => { if (open) kit?.ensure(); }, [kit, open]); + // Community mention groups: the session's live directory, read only on a + // relay that serves them. + const groupSource = fullSession(session)?.mentionGroups; + const groupFeed = groupSource?.supported ? groupSource.directory : undefined; + const groupDirectory = useSyncExternalStore( + groupFeed?.subscribe ?? subscribeNone, + groupFeed?.snapshot ?? snapshotNoGroups, + ); // readSaved is a live read at acceptance, not another subscribed store. const teams = useMemo(() => { // The service owns local persistence and confirmed synced copies. Neither @@ -101,6 +115,7 @@ export function useTeamMentions( void snapshot; return [ ...readSaved().map((team) => ({ + kind: "team" as const, ready: true, value: { id: `saved:${team.id}`, @@ -122,6 +137,7 @@ export function useTeamMentions( !entry.record.deleted && entry.record.value.type === "team" ? [ { + kind: "team" as const, value: entry.record.value, ready: catalog.status === "ready", current: () => { @@ -141,8 +157,27 @@ export function useTeamMentions( ] : [], ), + // A group waits while its membership loads: never a partial set. + ...(groupDirectory?.groups ?? []).map((group) => ({ + kind: "group" as const, + ready: group.members !== null, + value: { + id: `group:${group.id}`, + name: group.name, + agents: group.members ?? [], + }, + current: () => { + const latest = groupFeed + ?.snapshot() + .groups.find((next) => next.id === group.id); + return ( + latest?.version === group.version && + sameKeys(latest.members, group.members) + ); + }, + })), ]; - }, [readSaved, snapshot, catalog, kit]); + }, [readSaved, snapshot, catalog, kit, groupDirectory, groupFeed]); const hasTeams = open && teams.length > 0; useEffect(() => { if (!hasTeams) return; @@ -288,21 +323,22 @@ export function useTeamMentions( const current = open && rows?.length ? candidates() : []; const eligible = new Map(current.map((c) => [c.recipient.pubkey, c])); const choices = (open ? (rows ?? []) : []).map( - ({ value, current, members }) => { + ({ kind, value, current, members }) => { + const noun = kind === "group" ? "group" : "team"; const recipients = value.agents.flatMap((key) => { const person = eligible.get(key)?.recipient; return person ? [{ pubkey: person.pubkey, name: person.name }] : []; }); const disabled = !current() - ? "Team changed or unavailable. Reopen to refresh." + ? `${kind === "group" ? "Group" : "Team"} changed or unavailable. Reopen to refresh.` : members.some((key) => !eligible.get(key)?.member) - ? "Channel membership changed. Reopen to review adding this team." + ? `Channel membership changed. Reopen to review adding this ${noun}.` : !value.agents.length - ? "This team has no members." + ? `This ${noun} has no members.` : value.agents.length > 32 - ? "Teams can mention at most 32 members." + ? `${kind === "group" ? "Groups" : "Teams"} can mention at most 32 members.` : recipients.length !== value.agents.length - ? "A team member is unavailable. Edit the team or refresh choices." + ? `A ${noun} member is unavailable. Edit the ${noun} or refresh choices.` : undefined; const outside = recipients.filter( (person) => !eligible.get(person.pubkey)?.member, @@ -324,7 +360,10 @@ export function useTeamMentions( disabled, detail: disabled ?? - [`Saved team · ${teamCount(recipients, eligible)}`, consequence] + [ + `${kind === "group" ? "Group" : "Saved team"} · ${teamCount(recipients, eligible)}`, + consequence, + ] .filter(Boolean) .join(" · "), canSelect: () => { @@ -348,20 +387,35 @@ export function useTeamMentions( const names = [ ...new Set([...teams, ...(rows ?? [])].map(({ value }) => value.name)), ]; + const groupsFailed = open && groupDirectory?.status === "unavailable"; return { choices, includeLegacy: hasTeams, names, blocksSpace: teamBlocksSpace(catalog, query, names), - readNames: () => readSaved().map((team) => team.name), + readNames: () => [ + ...readSaved().map((team) => team.name), + ...(groupFeed?.snapshot().groups.map((group) => group.name) ?? []), + ], status: open && (catalog.status === "idle" || catalog.status === "loading") ? "Loading legacy teams…" : open && catalog.status === "error" ? "Could not load legacy teams. Retry to refresh." - : undefined, - canRetry: open && catalog.status === "error", - retry: () => void kit?.refresh(), + : open && groupDirectory?.status === "loading" + ? "Loading groups…" + : groupsFailed + ? "Could not load groups. Retry to refresh." + : undefined, + canRetry: (open && catalog.status === "error") || groupsFailed, + retryLabel: + open && catalog.status === "error" + ? "Retry legacy teams" + : "Retry groups", + retry: () => { + void kit?.refresh(); + if (groupDirectory?.status === "unavailable") groupSource?.retry(); + }, }; }, [ session, @@ -379,5 +433,8 @@ export function useTeamMentions( readSaved, owner, memberKeys, + groupDirectory, + groupFeed, + groupSource, ]); } diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index b3fa75b5fc..50c706267c 100644 --- a/src/features/relay/session.ts +++ b/src/features/relay/session.ts @@ -2501,6 +2501,7 @@ export function createRelaySession( put: mentionGroups.put, remove: mentionGroups.remove, setManage: mentionGroups.setManage, + retry: mentionGroups.recovery.retry, }), presence, viewer: transport?.viewer, From af773e205220f6983fc823430c1425f9603352e6 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 15:21:29 -0500 Subject: [PATCH 14/21] feat(channels): add a community mention group to a channel Add people lists community mention groups that match the search. One button adds the group's current members who aren't in the channel yet through the existing add-member command; refusals keep the shared alert and Retry. A group still loading its members, or with everyone already here, isn't offered. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../channels/ChannelMembersDialog.test.tsx | 63 +++++++++++++++++ src/bundled/channels/ChannelMembersDialog.tsx | 67 +++++++++++++++++-- 2 files changed, 125 insertions(+), 5 deletions(-) diff --git a/src/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index d4a6043e0e..507a3dc62b 100644 --- a/src/bundled/channels/ChannelMembersDialog.test.tsx +++ b/src/bundled/channels/ChannelMembersDialog.test.tsx @@ -124,6 +124,11 @@ async function setup( verifiedProfiles?: VerifiedProfileAuthority; visibility?: "private" | "public"; joinRole?: "member" | "guest"; + /** Community mention groups the relay serves: name to member keys. */ + mentionGroups?: Record< + string, + (people: { person: string; viewer: string }) => string[] + >; } = {}, ) { const viewer = keypair(), @@ -196,6 +201,22 @@ async function setup( ], }), ...(options.memberProfiles ?? []), + ...Object.entries(options.mentionGroups ?? {}).map(([name, keys], index) => + signed(relay, { + kind: 39010, + content: "", + tags: [ + ["-"], + ["d", `6f1d6c1e-8a4b-4c55-9b0e-2f3a4b5c6d7${index}`], + ["version", "1"], + ["command", `${index}`.repeat(64)], + ["name", name], + ...keys({ person: person.pubkey, viewer: viewer.pubkey }).map( + (key) => ["p", key], + ), + ], + }), + ), profile(viewer, { name: "Carl" }), personProfile, ]; @@ -254,6 +275,14 @@ async function setup( ? { verifiedProfiles: options.verifiedProfiles } : {}), readAgentLibrary, + ...(options.mentionGroups + ? { + mentionGroups: { + membership: "open" as const, + defaultManage: "everyone" as const, + }, + } + : {}), writer: { kinds: [ 9, @@ -2700,6 +2729,40 @@ it("adds a team's members not in the channel with one button", async () => { ).not.toBeInTheDocument(); }); +it("adds a community group's members not in the channel with one button", async () => { + const t = await setup("stream", false, false, undefined, undefined, { + mentionGroups: { + Reviewers: ({ person, viewer }) => [viewer, person], + Everyone: ({ viewer }) => [viewer], + }, + }); + expect(screen.queryByRole("list", { name: "Groups" })).toBeNull(); + await t.user.type(screen.getByRole("searchbox"), "Rev"); + const groups = await screen.findByRole("list", { name: "Groups" }); + // Only the members not here yet are listed and added. + expect(within(groups).getByText("Morgan")).toBeInTheDocument(); + await t.user.click( + screen.getByRole("button", { name: "Add group Reviewers" }), + ); + await screen.findByText("Reviewers is in the channel."); + const added = t.publish.mock.calls + .map(([event]) => event) + .filter((event) => event.kind === 9000) + .map((event) => event.tags.find((tag) => tag[0] === "p")?.[1]); + expect(added).toEqual([t.person.pubkey]); + await vi.waitFor(() => + expect( + screen.queryByRole("list", { name: "Groups" }), + ).not.toBeInTheDocument(), + ); + // A group whose members are all here is never offered. + await t.user.clear(screen.getByRole("searchbox")); + await t.user.type(screen.getByRole("searchbox"), "Every"); + expect( + screen.queryByRole("button", { name: "Add group Everyone" }), + ).not.toBeInTheDocument(); +}); + async function teamSetup(names = ["Ada", "Cy"]) { const keys = names.map((_name, index) => `${index}${index}`.repeat(32)); const ada = keys[0] ?? ""; diff --git a/src/bundled/channels/ChannelMembersDialog.tsx b/src/bundled/channels/ChannelMembersDialog.tsx index 47e92aa62a..6ead288962 100644 --- a/src/bundled/channels/ChannelMembersDialog.tsx +++ b/src/bundled/channels/ChannelMembersDialog.tsx @@ -521,15 +521,18 @@ export function ChannelMembersButton({ const noTeams = () => () => {}; const noSnapshot = () => undefined; -/** A team of the owner's agents, added to the channel with one button. */ +/** A team of the owner's agents, or a community mention group, added to the + * channel with one button. */ function TeamRow({ team, + kind = "team", names, busy, disabled, onAdd, }: { - team: Team; + team: Pick; + kind?: "team" | "group"; /** The members not yet in the channel. */ names: readonly string[]; busy: boolean; @@ -540,7 +543,12 @@ function TeamRow({
  • - + {team.name} @@ -553,14 +561,14 @@ function TeamRow({
  • @@ -839,6 +847,14 @@ export function ChannelMembersDialog({ agents?.snapshot ?? noSnapshot, agents?.snapshot ?? noSnapshot, ); + const groupFeed = session.mentionGroups.supported + ? session.mentionGroups.directory + : undefined; + const groupDirectory = useSyncExternalStore( + groupFeed?.subscribe ?? noTeams, + groupFeed?.snapshot ?? noSnapshot, + groupFeed?.snapshot ?? noSnapshot, + ); const resolveName = useIdentityNames(session.names); const channel = list.channels.find((item) => item.id === channelId) ?? @@ -1613,6 +1629,27 @@ export function ChannelMembersDialog({ ? [{ team, missing }] : []; }); + // Community mention groups match by name too; each adds its current + // community members not here yet. A group still loading its members waits. + const mentionGroups = ( + solo || !text ? [] : (groupDirectory?.groups ?? []) + ).flatMap((group) => { + const missing = group.members?.filter((key) => !members.has(key)) ?? []; + return missing.length && matchPerson(group.name, query) + ? [{ group, missing }] + : []; + }); + const groupKeys = [ + ...new Set(mentionGroups.flatMap(({ missing }) => missing)), + ] + .sort() + .join(":"); + useEffect(() => { + if (groupKeys) + void session.profiles + .ensure(groupKeys.split(":"), "background") + .catch(() => {}); + }, [session, groupKeys]); // Names refused people in a stable order: up to three, then a count. const listNames = (keys: readonly string[]) => { const names = keys @@ -2466,6 +2503,26 @@ export function ChannelMembersDialog({ ))} )} + {mentionGroups.length > 0 && ( +
      + {mentionGroups.map(({ group, missing }) => ( + label(key))} + busy={missing.some((key) => busy.has(key))} + disabled={rosterBusy || !!rosterError} + onAdd={() => + void addAll( + missing, + `${group.name} is in the ${place}.`, + ) + } + /> + ))} +
    + )} {invitationGroups.map((group) => group.people.length > 0 ? (
    Date: Mon, 16 Nov 2026 15:31:52 -0500 Subject: [PATCH 15/21] fix(mentions): groups skip archived agents and block Space mid-read Add group skips archived or deleting agents, as the individual rows do. A group saved while a Space directory read is pending blocks its namesake. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../channels/ChannelMembersDialog.test.tsx | 4 +- src/bundled/channels/ChannelMembersDialog.tsx | 6 ++- src/bundled/mentions/team-mentions.test.tsx | 52 +++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/src/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index 507a3dc62b..948a310ea2 100644 --- a/src/bundled/channels/ChannelMembersDialog.test.tsx +++ b/src/bundled/channels/ChannelMembersDialog.test.tsx @@ -2731,8 +2731,10 @@ it("adds a team's members not in the channel with one button", async () => { it("adds a community group's members not in the channel with one button", async () => { const t = await setup("stream", false, false, undefined, undefined, { + archivedAgent: true, mentionGroups: { - Reviewers: ({ person, viewer }) => [viewer, person], + // The archived agent is skipped, as the individual rows skip it. + Reviewers: ({ person, viewer }) => [viewer, person, "ab".repeat(32)], Everyone: ({ viewer }) => [viewer], }, }); diff --git a/src/bundled/channels/ChannelMembersDialog.tsx b/src/bundled/channels/ChannelMembersDialog.tsx index 6ead288962..19ca803675 100644 --- a/src/bundled/channels/ChannelMembersDialog.tsx +++ b/src/bundled/channels/ChannelMembersDialog.tsx @@ -1634,7 +1634,11 @@ export function ChannelMembersDialog({ const mentionGroups = ( solo || !text ? [] : (groupDirectory?.groups ?? []) ).flatMap((group) => { - const missing = group.members?.filter((key) => !members.has(key)) ?? []; + // Members added in one turn share one batched write. + const missing = + group.members?.filter( + (key) => !members.has(key) && !agentUnavailable(session, key), + ) ?? []; return missing.length && matchPerson(group.name, query) ? [{ group, missing }] : []; diff --git a/src/bundled/mentions/team-mentions.test.tsx b/src/bundled/mentions/team-mentions.test.tsx index 2c156690fb..2e9caa1998 100644 --- a/src/bundled/mentions/team-mentions.test.tsx +++ b/src/bundled/mentions/team-mentions.test.tsx @@ -1711,3 +1711,55 @@ it("a failed group directory says so and Retry rereads it", async () => { h.library.dispose(); } }); + +it("a group created during a pending Space directory read blocks its namesake", async () => { + const h = fixture(); + const groups = withGroups(h, []); + let release!: (value: { + people: { pubkey: string; name: string }[]; + hasMore: boolean; + }) => void; + const started = vi.fn(); + vi.spyOn(h.session.directMessages, "people").mockImplementation(async () => { + started(); + return new Promise((resolve) => { + release = resolve; + }); + }); + const model = { + pending: false, + channel: h.session.channels.list().channels[0], + } as ReturnType; + const hook = renderHook(() => + useTeamMentions(h.session, "parent", false, "Review Crew", model), + ); + const resolve = async (name: string, during: () => void) => { + started.mockClear(); + const result = resolveSpaceMention( + h.session, + { + channelId: "parent", + selected: [], + teamNames: hook.result.current.readNames, + }, + name, + new AbortController().signal, + ); + await waitFor(() => expect(started).toHaveBeenCalledOnce()); + during(); + release({ people: [{ pubkey: "e".repeat(64), name }], hasMore: false }); + return result; + }; + try { + // Without a group the person resolves; a group saved mid-read blocks it. + expect(await resolve("Review Crew", () => {})).not.toBeNull(); + expect( + await resolve("Design Crew", () => + groups.set([groupView([h.agent.pubkey], "1", "Design Crew")]), + ), + ).toBeNull(); + } finally { + hook.unmount(); + h.library.dispose(); + } +}); From 820931c6c1ce15343a0b0a18e42073597c3146cc Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 15:48:34 -0500 Subject: [PATCH 16/21] feat(communities): read the relay's mention group size limit The relay may advertise mention_groups.max_members in NIP-11. Both transports carry it and the group directory exposes it as maxMembers, so the group editor can show the limit without a number in the app. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- browser-host/relay-authority.test.mjs | 7 +++++ src/features/communities/admin-protocol.ts | 7 +++++ .../communities/mention-groups.test.ts | 6 ++++ src/features/communities/mention-groups.ts | 3 ++ src/features/relay/native.test.ts | 28 +++++++++++++++++++ src/features/relay/transport.ts | 10 ++++++- 6 files changed, 60 insertions(+), 1 deletion(-) diff --git a/browser-host/relay-authority.test.mjs b/browser-host/relay-authority.test.mjs index 32f22cf0dd..1c6f9e43db 100644 --- a/browser-host/relay-authority.test.mjs +++ b/browser-host/relay-authority.test.mjs @@ -54,6 +54,13 @@ it.each([ }, { membership: "open", defaultManage: "everyone" }, ], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "roster", max_members: 20 }, + }, + { membership: "roster", defaultManage: "everyone", maxMembers: 20 }, + ], ])( "carries a v1 NIP-MG advertisement to the browser transport: %j", async (advertised, support) => { diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 2ca9f6a34f..feb89bcda5 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -137,6 +137,8 @@ export type MentionGroupSupport = Readonly<{ membership: "open" | "roster"; /** "Who can manage groups" before any setting command. */ defaultManage: "admins" | "everyone"; + /** Most members a group may have, when the relay advertises a limit. */ + maxMembers?: number; }>; export function mentionGroupSupport( nip11: unknown, @@ -147,6 +149,7 @@ export function mentionGroupSupport( version?: unknown; membership?: unknown; default_manage?: unknown; + max_members?: unknown; }; }; const groups = info.mention_groups; @@ -158,6 +161,10 @@ export function mentionGroupSupport( membership: groups.membership, defaultManage: groups.default_manage === "admins" ? "admins" : "everyone", + ...(Number.isSafeInteger(groups.max_members) && + (groups.max_members as number) > 0 + ? { maxMembers: groups.max_members as number } + : {}), } : undefined; } diff --git a/src/features/communities/mention-groups.test.ts b/src/features/communities/mention-groups.test.ts index 2eee54389d..aff0b3292c 100644 --- a/src/features/communities/mention-groups.test.ts +++ b/src/features/communities/mention-groups.test.ts @@ -80,6 +80,7 @@ function harness( stored: EventData[], options: { membership?: "open" | "roster"; + maxMembers?: number; send?: (body: Record) => Promise; profiles?: EventData[]; } = {}, @@ -95,6 +96,7 @@ function harness( support: { membership: options.membership ?? "open", defaultManage: "everyone", + ...(options.maxMembers ? { maxMembers: options.maxMembers } : {}), }, viewer, relayAuthor: author, @@ -305,6 +307,7 @@ it("on a roster relay offers only current members and owner-admitted agents", as ], { membership: "roster", + maxMembers: 20, profiles: [ profile(admittedAgent, proof), // A forged proof names a member but is not signed by them. @@ -328,6 +331,9 @@ it("on a roster relay offers only current members and owner-admitted agents", as // An open relay never filters. const open = harness([head(groupA, 1, "On call", [person, removed])]); await settle(); + // The relay's advertised group size limit reaches the editor; none here. + expect(h.snapshot().maxMembers).toBe(20); + expect(open.snapshot().maxMembers).toBeUndefined(); expect(open.snapshot().groups[0]?.members).toEqual([person, removed]); }); diff --git a/src/features/communities/mention-groups.ts b/src/features/communities/mention-groups.ts index e2dc370b8c..754871d10f 100644 --- a/src/features/communities/mention-groups.ts +++ b/src/features/communities/mention-groups.ts @@ -238,6 +238,8 @@ export type MentionGroupDirectory = Readonly<{ status: "unsupported" | "loading" | "unavailable" | "ready" | "reconciling"; groups: readonly MentionGroupView[]; membership?: MentionGroupSupport["membership"]; + /** Most members a group may have, when the relay advertises a limit. */ + maxMembers?: number; manage: ManageSetting; /** The setting's version, the `prev` for setManage. */ settingVersion: string; @@ -297,6 +299,7 @@ export function projectDirectory( status: state.status === "stale" ? "ready" : state.status, groups, ...(support ? { membership: support.membership } : {}), + ...(support?.maxMembers ? { maxMembers: support.maxMembers } : {}), manage, settingVersion: (data.settings?.version ?? 0n).toString(), ...(role ? { role } : {}), diff --git a/src/features/relay/native.test.ts b/src/features/relay/native.test.ts index 51fd471115..f9cc538944 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -290,6 +290,34 @@ it.each([ }, { membership: "roster", defaultManage: "admins" }, ], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "open", max_members: 20 }, + }, + { membership: "open", defaultManage: "everyone", maxMembers: 20 }, + ], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "open", max_members: 0 }, + }, + { membership: "open", defaultManage: "everyone" }, + ], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "open", max_members: "20" }, + }, + { membership: "open", defaultManage: "everyone" }, + ], + [ + { + supported_extensions: ["nip-mg"], + mention_groups: { version: 1, membership: "open", max_members: 2.5 }, + }, + { membership: "open", defaultManage: "everyone" }, + ], ])( "offers mention groups only with a v1 NIP-MG advertisement: %o", async (advertised, support) => { diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index 306b6b873d..d50f890549 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -540,7 +540,11 @@ export async function connectBrokerTransport( channelKit?: boolean; channelIdentity?: boolean; searchSort?: boolean; - mentionGroups?: { membership?: unknown; defaultManage?: unknown }; + mentionGroups?: { + membership?: unknown; + defaultManage?: unknown; + maxMembers?: unknown; + }; artifactSync?: boolean; sidebarPreferenceWrites?: boolean; sidebarSectionRemoval?: boolean; @@ -886,6 +890,10 @@ export async function connectBrokerTransport( session.mentionGroups.defaultManage === "admins" ? ("admins" as const) : ("everyone" as const), + ...(Number.isSafeInteger(session.mentionGroups.maxMembers) && + (session.mentionGroups.maxMembers as number) > 0 + ? { maxMembers: session.mentionGroups.maxMembers as number } + : {}), }, } : {}), From 43b60f5bc963632d5f9e106f9af2a75cef4d0c76 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 15:49:40 -0500 Subject: [PATCH 17/21] docs: community mention groups in the choosers and Add people Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/agents.md | 10 ++++++++++ docs/buzz-help.md | 7 +++++++ docs/communities.md | 26 ++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/docs/agents.md b/docs/agents.md index 955fb0cdf2..af2cc21b5c 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -1169,6 +1169,16 @@ limits; a person mentioned by several chips counts once. Selection never adds members: ordinary channels retain invite-on-send consent, DMs retain reference-only outsiders, and Solo chats add only the viewer's available agents. +Community mention groups (see [Communities](communities.md#community-mention-groups)) +appear in both choosers as **Group** rows beside the saved teams and follow the +same rules: one `@group` chip that notifies each current member, people and +agents counted in the row, Space and typed names never select it, and a group +that is empty, too large, changed or still loading its members stays disabled. +When the directory cannot be read the chooser says so and offers **Retry +groups**. In a channel's **Add people**, matching groups are listed with +**Add group**, which adds only the members not yet in the channel and skips +archived agents. + The picker supports Up/Down navigation, Enter selection and Escape dismissal. `session.messages.send/reply` accepts up to 32 exact notification pubkeys and emits diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 406ad62eba..179c5190eb 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1509,6 +1509,13 @@ confirmation. **Delete team** asks first; it doesn't delete the team's agents. Closing a team's editor with unsaved edits, by Escape, its Close or another tab, asks **Discard changes?** first; **Keep editing** keeps them. +A community can also have mention groups, which everyone in the community +shares. They appear in the `@` suggestions as **Group** with how many people +and agents they hold, and selecting one mentions every member. In a channel, +**Add people** lists matching groups; **Add group** adds the members who aren't +in the channel yet. A group can have only as many members as the community +allows; for a larger group, use a channel. + ## Optional features and limits - Plugins can add features. **Settings → Plugins → Manage plugins** controls diff --git a/docs/communities.md b/docs/communities.md index 3c5f831684..7071292632 100644 --- a/docs/communities.md +++ b/docs/communities.md @@ -161,6 +161,32 @@ empty state there. Try drafting in A, switching to B, then returning to A. Selected channels, drafts and reading offsets are partitioned by the canonical community origin and viewer; channel IDs alone are not sufficient keys. +## Community mention groups + +A relay that advertises NIP-MG (`nip-mg` in `supported_extensions` with a +version 1 `mention_groups` object) keeps the community's mention groups, like +Slack user groups: each has a name, members and optional default channels, and +everyone in the community sees the same groups. `session.mentionGroups` is the +host capability. Its `directory` is a live snapshot of the relay-signed kind +`39010` groups: it shows groups only after a complete paged read, takes the +newest version of each group from live updates, reads again after every +reconnect, and never empties on a failed read (`unavailable`, then **Retry**). +On a `roster` community a group's members are its current roster members and +owner-admitted agents, and a group waits while that membership is still being +read, so nothing sends to a partial set. + +`put`, `remove` and `setManage` sign one command (kind `47000` put, `47001` +delete, `47002` "Who can manage groups") with the group's current version as +its precondition: the broker signs it in development, and the native host signs +only those exact shapes and posts them to the relay's `/events`. The relay +alone decides authority from the community's **Who can manage groups** +setting (owners and admins, or everyone; NIP-11 `default_manage` applies until +the first setting is saved). A retry resends the same signed command, so the +relay answers it from its receipt rather than applying it twice. A stale +version, a taken name and a refusal come back as distinct answers. When the +relay advertises `max_members`, the directory exposes it as `maxMembers`, the +most members a group may have; larger groups belong in a channel. + ## Import from the previous desktop app After native startup, Buzz offers the previous desktop app's saved communities From 8cca1d0b802cc7231379e774c94fbb24c910a16e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 15:57:24 -0500 Subject: [PATCH 18/21] fix(mentions): a group's unavailable member isn't the viewer's to edit Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/bundled/mentions/use-team-mentions.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/bundled/mentions/use-team-mentions.ts b/src/bundled/mentions/use-team-mentions.ts index 288c8b5072..86eae11711 100644 --- a/src/bundled/mentions/use-team-mentions.ts +++ b/src/bundled/mentions/use-team-mentions.ts @@ -338,7 +338,9 @@ export function useTeamMentions( : value.agents.length > 32 ? `${kind === "group" ? "Groups" : "Teams"} can mention at most 32 members.` : recipients.length !== value.agents.length - ? `A ${noun} member is unavailable. Edit the ${noun} or refresh choices.` + ? kind === "group" + ? "A group member can't be mentioned here." + : "A team member is unavailable. Edit the team or refresh choices." : undefined; const outside = recipients.filter( (person) => !eligible.get(person.pubkey)?.member, From 9f3d012aed439cea71a22efa1e034b4c060e6800 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 16:42:31 -0500 Subject: [PATCH 19/21] fix(communities): match relay group edit authority under admins With no steward and the setting at admins, the relay refuses every put and delete (NIP-MG), so the directory no longer reports canEdit there. Any member can still change the setting back to Everyone. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/communities/mention-groups.test.ts | 5 +++-- src/features/communities/mention-groups.ts | 3 +-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/features/communities/mention-groups.test.ts b/src/features/communities/mention-groups.test.ts index aff0b3292c..e7051912ac 100644 --- a/src/features/communities/mention-groups.test.ts +++ b/src/features/communities/mention-groups.test.ts @@ -369,11 +369,12 @@ it("lets any member edit under Everyone, only stewards under admins, and only st canEdit: true, canManage: true, }); - // A community with no steward lets any member change it. + // With no steward, any member may change the setting, but under admins + // nobody may edit groups until it is set back to Everyone (NIP-MG). const rosterless = harness([settings("admins", 2)]); await settle(); expect(rosterless.snapshot()).toMatchObject({ - canEdit: true, + canEdit: false, canManage: true, }); }); diff --git a/src/features/communities/mention-groups.ts b/src/features/communities/mention-groups.ts index 754871d10f..4b47446973 100644 --- a/src/features/communities/mention-groups.ts +++ b/src/features/communities/mention-groups.ts @@ -303,8 +303,7 @@ export function projectDirectory( manage, settingVersion: (data.settings?.version ?? 0n).toString(), ...(role ? { role } : {}), - canEdit: - ready && viewerMember && (manage === "everyone" || manager || !steward), + canEdit: ready && viewerMember && (manage === "everyone" || manager), canManage: ready && viewerMember && (manager || !steward), ...("error" in state ? { error: state.error } : {}), }; From 5d2d2c802357807c50cc9d8e26f128f35e933621 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 16:54:33 -0500 Subject: [PATCH 20/21] fix(communities): match relay group ids, freeze retries, recheck agents - Group ids follow the relay's rule (any canonical lowercase non-nil UUID) in the directory, the shared command builder and the native signer. - put copies the member and channel arrays, so a caller's later edit can't change the event a retry sends. - Each reconcile rechecks agents with no owner proof, so one that publishes its proof later is admitted after a reconnect; the old answer stands until then, and an older lookup's answer is dropped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src-tauri/src/relay.rs | 3 +- src-tauri/src/relay/tests.rs | 11 ++++ src/features/communities/admin-protocol.ts | 9 ++- .../communities/mention-groups.test.ts | 57 ++++++++++++++++++- src/features/communities/mention-groups.ts | 44 ++++++++++---- 5 files changed, 106 insertions(+), 18 deletions(-) diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index fe12f4c8b0..c94b7edf75 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -483,8 +483,7 @@ fn valid_mention_group_command(event: &EventTemplate) -> bool { 8 | 13 | 18 | 23 => *byte == b'-', _ => byte.is_ascii_digit() || (b'a'..=b'f').contains(byte), }) - && (b'1'..=b'8').contains(&bytes[14]) - && matches!(bytes[19], b'8' | b'9' | b'a' | b'b') + && bytes.iter().any(|byte| !matches!(*byte, b'0' | b'-')) }; let version = |value: &str| { !value.is_empty() diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index df8ead58ba..886a29a4b6 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -225,6 +225,12 @@ fn mention_group_commands_sign_only_the_broker_shape() { command(47001, "", &[d, prev]), command(47002, "", &[&["manage", "admins"], &["prev", "0"]]), command(47002, "", &[&["manage", "everyone"], prev]), + // Any canonical non-nil UUID, as the relay accepts (NIP-MG). + command( + 47001, + "", + &[&["d", "00000000-0000-0000-0000-000000000001"], prev], + ), ] { assert!(validate_event("https://relay.test", &accepted).is_ok()); } @@ -240,6 +246,11 @@ fn mention_group_commands_sign_only_the_broker_shape() { command(47000, "", &[d, &["prev", "-1"], name]), command(47000, "", &[&["d", "not-a-uuid"], prev, name]), command(47000, "", &[&["d", &id.to_uppercase()], prev, name]), + command( + 47001, + "", + &[&["d", "00000000-0000-0000-0000-000000000000"], prev], + ), // Members come before channels, once each, as lowercase keys. command(47000, "", &[d, prev, name, channel, p]), command(47000, "", &[d, prev, name, p, p]), diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index feb89bcda5..e698dc29af 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -116,8 +116,11 @@ export const MENTION_GROUP_KINDS = Object.freeze({ manage: 47002, state: 39010, }); -const UUID = - /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +/** The relay's group id rule (NIP-MG): canonical lowercase UUID, not nil. */ +export const isMentionGroupId = (value: string) => + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test( + value, + ) && value !== "00000000-0000-0000-0000-000000000000"; const VERSION = /^(?:0|[1-9][0-9]{0,18})$/; const KEY = /^[0-9a-f]{64}$/; const CHANNEL = /^[a-zA-Z0-9_-]{1,128}$/; @@ -209,7 +212,7 @@ export function mentionGroupCommand( ], }; } - if (typeof body.id !== "string" || !UUID.test(body.id)) + if (typeof body.id !== "string" || !isMentionGroupId(body.id)) throw new Error("Invalid group"); if (action === "remove") return { diff --git a/src/features/communities/mention-groups.test.ts b/src/features/communities/mention-groups.test.ts index e7051912ac..3cae1cc703 100644 --- a/src/features/communities/mention-groups.test.ts +++ b/src/features/communities/mention-groups.test.ts @@ -10,6 +10,7 @@ const removed = "4".repeat(64); const agent = "5".repeat(64); const groupA = "0659678f-fddb-40df-a285-35f6b41db019"; const groupB = "1b0e8c2a-3f4d-4c5e-9a6b-7c8d9e0f1a2b"; +const plainId = "00000000-0000-0000-0000-000000000001"; let sequence = 0; const id = () => (++sequence).toString(16).padStart(64, "0"); @@ -130,7 +131,8 @@ function harness( }); }, async send(body) { - sent.push(body); + // A copy at dispatch, so a later change to the body would show. + sent.push(JSON.parse(JSON.stringify(body))); return (options.send?.(body) ?? { accepted: true, event_id: "x", @@ -183,6 +185,9 @@ it("pages every head before showing groups, newest version per group, and keeps head(groupA, 1, "Old name", [person]), head(groupA, 3, "On call", [person, admin]), head(groupB, 1, "Design", [person], [], 1003), + // Any canonical non-nil UUID is a group id, as on the relay. + head(plainId, 1, "Plain", [person], [], 1004), + head("00000000-0000-0000-0000-000000000000", 1, "Nil", [person], [], 1005), tombstone("2e9b7c3d-1a2b-4c3d-8e4f-5a6b7c8d9e0f", 2), // Malformed: one bad head is dropped and the rest stay. { ...head(groupB, 9, "", [person]), tags: [["d", groupB]] }, @@ -196,6 +201,7 @@ it("pages every head before showing groups, newest version per group, and keeps groups: [ { id: groupB, name: "Design", members: [person] }, { id: groupA, name: "On call", version: "3", members: [person, admin] }, + { id: plainId, name: "Plain" }, ], }); expect(h.owner.recovery.status()).toBe("settled"); @@ -337,6 +343,50 @@ it("on a roster relay offers only current members and owner-admitted agents", as expect(open.snapshot().groups[0]?.members).toEqual([person, removed]); }); +it("rechecks an agent with no owner proof on reconnect", async () => { + // NIP-OA test vector, as above: the owner is a roster member. + const owner = + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + const later = + "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; + const profiles: EventData[] = []; + const h = harness( + [ + head(groupA, 1, "On call", [person, later]), + roster([ + [person, "member"], + [owner, "member"], + ]), + ], + { membership: "roster", profiles }, + ); + await vi.waitFor(() => + expect(h.snapshot().groups[0]?.members).toEqual([person]), + ); + // The agent publishes its owner's proof after the first lookup. + profiles.push({ + id: id(), + pubkey: later, + kind: 0, + created_at: 1, + content: "{}", + tags: [ + [ + "auth", + owner, + "kind=1&created_at<1713957000", + "8b7df2575caf0a108374f8471722b233c53f9ff827a8b0f91861966c3b9dd5cb2e189eae9f49d72187674c2f5bd244145e10ff86c9f257ffe65a1ee5f108b369", + ], + ], + }); + h.reconnect(); + // The old answer stands while the recheck runs; the group never waits. + expect(h.snapshot().groups[0]?.members).toEqual([person]); + await vi.waitFor(() => + expect(h.snapshot().groups[0]?.members).toEqual([person, later]), + ); +}); + it("lets any member edit under Everyone, only stewards under admins, and only stewards change the setting", async () => { const stewards = roster([ [admin, "admin"], @@ -389,10 +439,13 @@ it("resends the same event after an unknown outcome and types each relay answer" prev: "0", name: "On call", members: [person], - channels: [], + channels: [] as string[], }; const lost = await h.owner.put(input); expect(lost).toMatchObject({ outcome: "unknown" }); + // The caller's later edits don't change the event a retry sends. + input.members.push(admin); + input.channels.push("general"); answer = () => Promise.resolve({ accepted: true, event_id: lost.eventId }); h.tick(30); const retried = await lost.retry?.(); diff --git a/src/features/communities/mention-groups.ts b/src/features/communities/mention-groups.ts index 4b47446973..dbaab45af2 100644 --- a/src/features/communities/mention-groups.ts +++ b/src/features/communities/mention-groups.ts @@ -11,6 +11,7 @@ import { mentionGroupCommand, mentionGroupName, type MentionGroupSupport, + isMentionGroupId, } from "./admin-protocol"; import { MEMBERSHIP_KIND, membersFromSnapshot, type Role } from "./roster"; @@ -90,8 +91,6 @@ export function reduceDirectory( } } -const UUID = - /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; const VERSION = /^(?:0|[1-9][0-9]{0,18})$/; const KEY = /^[0-9a-f]{64}$/; const ID = /^[0-9a-f]{64}$/; @@ -118,7 +117,7 @@ export function parseState( : undefined; } const command = single(event, "command"); - if (!UUID.test(d) || !command || !ID.test(command)) return undefined; + if (!isMentionGroupId(d) || !command || !ID.test(command)) return undefined; const deleted = event.tags.some( ([name, value]) => name === "deleted" && value === "true", ); @@ -412,6 +411,11 @@ export function createMentionGroups(deps: MentionGroupDeps) { // Owner-admitted agents outside the roster, by key: owner key or null. const owners = new Map(); const looking = new Set(); + // Every reconcile rechecks negative answers, so a key that later proves its + // owner is admitted; the old answer stands until then. A lookup from an + // earlier reconcile is dropped. + const recheck = new Set(); + let ownerGeneration = 0; let lookupFailed = false; const repaired = new Set(); let reading: Promise | undefined; @@ -446,6 +450,9 @@ export function createMentionGroups(deps: MentionGroupDeps) { again = true; return; } + ownerGeneration++; + looking.clear(); + for (const [key, owner] of owners) if (owner === null) recheck.add(key); dispatch({ type: "read" }); reading = (async () => { try { @@ -513,10 +520,14 @@ export function createMentionGroups(deps: MentionGroupDeps) { [...state.data.heads.values()].flatMap((head) => head.members), ), ].filter( - (key) => !roster.roles.has(key) && !owners.has(key) && !looking.has(key), + (key) => + !roster.roles.has(key) && + (!owners.has(key) || recheck.has(key)) && + !looking.has(key), ); if (!unknown.length) return; for (const key of unknown) looking.add(key); + const generation = ownerGeneration; void (async () => { try { const events = await deps.read( @@ -524,25 +535,28 @@ export function createMentionGroups(deps: MentionGroupDeps) { lifetime.signal, ); lifetime.signal.throwIfAborted(); + if (generation !== ownerGeneration) return; for (const key of unknown) { const profile = events .filter((event) => event.kind === 0 && event.pubkey === key) .sort(newest)[0]; const [tag, ...extra] = profile?.tags.filter(([name]) => name === "auth") ?? []; - owners.set( - key, + const owner = tag && !extra.length ? ((await authTagOwner(key, tag)) ?? null) - : null, - ); + : null; + if (generation !== ownerGeneration) return; + owners.set(key, owner); + recheck.delete(key); } lookupFailed = false; } catch { - if (lifetime.signal.aborted) return; + if (lifetime.signal.aborted || generation !== ownerGeneration) return; lookupFailed = true; } finally { - for (const key of unknown) looking.delete(key); + if (generation === ownerGeneration) + for (const key of unknown) looking.delete(key); } publish(); })(); @@ -674,7 +688,15 @@ export function createMentionGroups(deps: MentionGroupDeps) { name: string; members: readonly string[]; channels: readonly string[]; - }) => command({ action: "put", ...input, created_at: now() }), + }) => + // Copy the arrays so a later edit by the caller can't change a retry. + command({ + action: "put", + ...input, + members: [...input.members], + channels: [...input.channels], + created_at: now(), + }), remove: (input: { id: string; prev: string }) => command({ action: "remove", ...input, created_at: now() }), setManage: (input: { manage: ManageSetting; prev: string }) => From 5e81602f66838607fca3a60b5457f3e409b1b34e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 16 Nov 2026 17:54:49 -0500 Subject: [PATCH 21/21] fix(communities): notify nobody without a roster, batch owner lookups On a roster community whose relay publishes no roster, no member can be confirmed, so groups now notify nobody instead of everyone. Owner-proof profile lookups are split into reads of the profile directory's page size, so a large directory stays within a relay's authors limit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/communities.md | 3 +- .../communities/mention-groups.test.ts | 30 +++++++++++++++++++ src/features/communities/mention-groups.ts | 27 ++++++++++++----- src/features/relay/profile-directory.ts | 2 +- 4 files changed, 53 insertions(+), 9 deletions(-) diff --git a/docs/communities.md b/docs/communities.md index 7071292632..0fc8adeceb 100644 --- a/docs/communities.md +++ b/docs/communities.md @@ -173,7 +173,8 @@ newest version of each group from live updates, reads again after every reconnect, and never empties on a failed read (`unavailable`, then **Retry**). On a `roster` community a group's members are its current roster members and owner-admitted agents, and a group waits while that membership is still being -read, so nothing sends to a partial set. +read, so nothing sends to a partial set. If the relay publishes no roster, +groups notify nobody. `put`, `remove` and `setManage` sign one command (kind `47000` put, `47001` delete, `47002` "Who can manage groups") with the group's current version as diff --git a/src/features/communities/mention-groups.test.ts b/src/features/communities/mention-groups.test.ts index 3cae1cc703..015d362c69 100644 --- a/src/features/communities/mention-groups.test.ts +++ b/src/features/communities/mention-groups.test.ts @@ -387,6 +387,36 @@ it("rechecks an agent with no owner proof on reconnect", async () => { ); }); +it("on a roster relay that publishes no roster, notifies nobody", async () => { + const h = harness([head(groupA, 1, "On call", [person, viewer])], { + membership: "roster", + }); + await settle(); + expect(h.snapshot()).toMatchObject({ + status: "ready", + groups: [{ name: "On call", members: [], stored: [person, viewer] }], + canEdit: false, + }); +}); + +it("looks up owner proofs in reads the relay's authors limit accepts", async () => { + const outsiders = Array.from( + { length: 501 }, + (_, i) => `e${i.toString(16).padStart(63, "0")}`, + ); + const h = harness( + [head(groupA, 1, "Everyone", outsiders), roster([[viewer, "member"]])], + { membership: "roster" }, + ); + await vi.waitFor(() => expect(h.snapshot().groups[0]?.members).toEqual([])); + const profileReads = h.reads + .flat() + .filter((filter) => filter.kinds?.includes(0)); + expect(profileReads.map((filter) => filter.authors?.length)).toEqual([ + 500, 1, + ]); +}); + it("lets any member edit under Everyone, only stewards under admins, and only stewards change the setting", async () => { const stewards = roster([ [admin, "admin"], diff --git a/src/features/communities/mention-groups.ts b/src/features/communities/mention-groups.ts index dbaab45af2..fff6b39895 100644 --- a/src/features/communities/mention-groups.ts +++ b/src/features/communities/mention-groups.ts @@ -6,6 +6,7 @@ import { getEventHash } from "nostr-tools"; import { authTagOwner } from "../agents/owner-attestation"; import type { EventData, ReadFilter } from "../relay/events"; import type { RecoverySource, RecoveryStatus } from "../relay/recovery"; +import { PROFILE_PAGE } from "../relay/profile-directory"; import { MENTION_GROUP_KINDS, mentionGroupCommand, @@ -266,10 +267,15 @@ export function projectDirectory( const roster = support?.membership === "roster"; // The predicate the relay enforces: on an open relay every authenticated // key belongs; on a roster relay a roster entry or an owner-admitted agent. + // Without a roster nobody is known to belong, so nobody is notified. const member = (key: string): boolean | undefined => - !roster || !data.roster || data.roster.roles.has(key) + !roster ? true - : admitted(key); + : data.roster === undefined + ? undefined + : data.roster === null + ? false + : data.roster.roles.has(key) || admitted(key); const viewerMember = member(viewer) === true; const ready = shown(state); const groups = ready @@ -530,11 +536,18 @@ export function createMentionGroups(deps: MentionGroupDeps) { const generation = ownerGeneration; void (async () => { try { - const events = await deps.read( - [{ kinds: [0], authors: unknown, limit: unknown.length }], - lifetime.signal, - ); - lifetime.signal.throwIfAborted(); + // Batched like the profile directory, within a relay's authors limit. + const events: EventData[] = []; + for (let at = 0; at < unknown.length; at += PROFILE_PAGE) { + const authors = unknown.slice(at, at + PROFILE_PAGE); + events.push( + ...(await deps.read( + [{ kinds: [0], authors, limit: authors.length }], + lifetime.signal, + )), + ); + lifetime.signal.throwIfAborted(); + } if (generation !== ownerGeneration) return; for (const key of unknown) { const profile = events diff --git a/src/features/relay/profile-directory.ts b/src/features/relay/profile-directory.ts index 8f2add0299..35c0d6a0bf 100644 --- a/src/features/relay/profile-directory.ts +++ b/src/features/relay/profile-directory.ts @@ -78,7 +78,7 @@ export interface ProfileQueries { /** Authors per profile read, the reader's largest page. A page that fills it * may have left out authors who do have a profile. */ -const PROFILE_PAGE = 500; +export const PROFILE_PAGE = 500; /** How long a released reservation holds the limit up. */ const RELEASE_HOLD_MS = 30_000;