diff --git a/browser-host/relay-authority.test.mjs b/browser-host/relay-authority.test.mjs index f2a1905fd0..1c6f9e43db 100644 --- a/browser-host/relay-authority.test.mjs +++ b/browser-host/relay-authority.test.mjs @@ -44,6 +44,34 @@ 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" }, + ], + [ + { + 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) => { + 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 268db22ffb..7c1ed24c4c 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 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: 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..6091316099 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -43,6 +43,9 @@ import { claimReason, inviteRequest, memberCommand, + mentionGroupCommand, + mentionGroupReason, + mentionGroupSupport, } from "../src/features/communities/admin-protocol.ts"; import { leaveRefusal, @@ -340,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) && @@ -1698,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, @@ -2467,6 +2473,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 +2785,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 +2808,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 +3155,7 @@ export function relayBrokerPlugin({ !policy && !invite && !member && + !group && !leave && !gifs && !profileSearch && @@ -3228,7 +3242,7 @@ export function relayBrokerPlugin({ ? gifSearchPath : profileSearch ? "/profiles/search" - : profile || directMessage || member || leave + : profile || directMessage || member || group || leave ? "/events" : claim ? "/api/invites/claim" @@ -3392,7 +3406,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 +3417,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/docs/agents.md b/docs/agents.md index 2dc3e48209..af2cc21b5c 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -1155,17 +1155,29 @@ 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. + +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. diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 274d252a41..179c5190eb 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1497,14 +1497,25 @@ 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. -Typing its name alone does not notify it. Empty teams, teams with more than 32 +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. 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. 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..0fc8adeceb 100644 --- a/docs/communities.md +++ b/docs/communities.md @@ -161,6 +161,33 @@ 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. 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 +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 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-tauri/src/relay.rs b/src-tauri/src/relay.rs index b3bf2063e4..c94b7edf75 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,78 @@ 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), + }) + && bytes.iter().any(|byte| !matches!(*byte, b'0' | 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..886a29a4b6 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -198,6 +198,85 @@ 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]), + // 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()); + } + 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]), + 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]), + 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]), + // Group state is relay-signed only. + command(39010, "", &[d, &["name", "On call"], &["version", "1"]]), + ] { + 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/bundled/channels/ChannelMembersDialog.test.tsx b/src/bundled/channels/ChannelMembersDialog.test.tsx index d4a6043e0e..948a310ea2 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,42 @@ 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, { + archivedAgent: true, + mentionGroups: { + // The archived agent is skipped, as the individual rows skip it. + Reviewers: ({ person, viewer }) => [viewer, person, "ab".repeat(32)], + 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..19ca803675 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,31 @@ 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) => { + // 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 }] + : []; + }); + 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 +2507,26 @@ export function ChannelMembersDialog({ ))} )} + {mentionGroups.length > 0 && ( + + )} {invitationGroups.map((group) => group.people.length > 0 ? (
    {teams.status}{" "} {teams.canRetry && ( - + )}

    )} 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": [ 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 f6c64e4748..2e9caa1998 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(); @@ -537,6 +537,86 @@ 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.group?.mentions).toEqual([h.agent, person]); + expect(menu.team()?.detail).toBe( + "Saved team · 1 person, 1 agent · 1 not in channel", + ); + } finally { + menu.view.unmount(); + h.library.dispose(); + } +}); + +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); + 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.group?.mentions).toEqual([h.agent, person]); + } 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(() => @@ -960,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(); @@ -1019,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); @@ -1182,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(); @@ -1435,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); @@ -1457,3 +1548,218 @@ 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(); + } +}); + +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(); + } +}); diff --git a/src/bundled/mentions/use-team-mentions.ts b/src/bundled/mentions/use-team-mentions.ts index 677d3335ed..86eae11711 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"; @@ -50,8 +51,30 @@ 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]); -/** Saved teams are shortcuts to exact individual recipients, never new identities. */ +/** "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 and community mention groups are shortcuts to exact individual + * recipients, never new identities. */ export function useTeamMentions( session: ComposerSession, channelId: string, @@ -77,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 @@ -84,6 +115,7 @@ export function useTeamMentions( void snapshot; return [ ...readSaved().map((team) => ({ + kind: "team" as const, ready: true, value: { id: `saved:${team.id}`, @@ -105,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: () => { @@ -124,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; @@ -152,6 +204,30 @@ 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 that can mention: an unnamed key is never offered, as with a + // pasted link. + const memberKeys = [ + ...new Set( + rows?.flatMap(({ value }) => + value.agents.length > 32 ? [] : value.agents, + ) ?? [], + ), + ] + .sort() + .join(); + useEffect(() => { + if (open && memberKeys) + 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. + 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 +268,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,32 +314,33 @@ 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. 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 agents." + ? `This ${noun} has no members.` : value.agents.length > 32 - ? "Teams can mention at most 32 agents." + ? `${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." + ? 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, @@ -247,7 +362,10 @@ export function useTeamMentions( disabled, detail: disabled ?? - [`Saved team · ${recipients.length} agents`, consequence] + [ + `${kind === "group" ? "Group" : "Saved team"} · ${teamCount(recipients, eligible)}`, + consequence, + ] .filter(Boolean) .join(" · "), canSelect: () => { @@ -271,20 +389,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, @@ -301,5 +434,9 @@ export function useTeamMentions( hasTeams, readSaved, owner, + memberKeys, + groupDirectory, + groupFeed, + groupSource, ]); } diff --git a/src/features/communities/admin-protocol.ts b/src/features/communities/admin-protocol.ts index 17471950bb..e698dc29af 100644 --- a/src/features/communities/admin-protocol.ts +++ b/src/features/communities/admin-protocol.ts @@ -106,3 +106,167 @@ 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, +}); +/** 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}$/; +const MAX_NAME = 120; +const MAX_CHANNELS = 32; +// The relay bounds the signed size; this only keeps a template sane. +const MAX_MEMBERS = 1000; +/** 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"; + /** Most members a group may have, when the relay advertises a limit. */ + maxMembers?: number; +}>; +export function mentionGroupSupport( + nip11: unknown, +): MentionGroupSupport | undefined { + const info = (nip11 ?? {}) as { + supported_extensions?: unknown; + mention_groups?: { + version?: unknown; + membership?: unknown; + default_manage?: unknown; + max_members?: 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", + ...(Number.isSafeInteger(groups.max_members) && + (groups.max_members as number) > 0 + ? { maxMembers: groups.max_members as number } + : {}), + } + : undefined; +} + +/** 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, however old it is. */ +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 < 1 || + createdAt > now + MAX_SKEW + ) + 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" || !isMentionGroupId(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/mention-groups.test.ts b/src/features/communities/mention-groups.test.ts new file mode 100644 index 0000000000..015d362c69 --- /dev/null +++ b/src/features/communities/mention-groups.test.ts @@ -0,0 +1,539 @@ +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"; +const plainId = "00000000-0000-0000-0000-000000000001"; +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"; + maxMembers?: number; + 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", + ...(options.maxMembers ? { maxMembers: options.maxMembers } : {}), + }, + 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) { + // 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", + }) 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), + // 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]] }, + 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] }, + { id: plainId, name: "Plain" }, + ], + }); + 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", + maxMembers: 20, + 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(); + // 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]); +}); + +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("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"], + [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, + }); + // 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: false, + 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: [] 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?.(); + 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..fff6b39895 --- /dev/null +++ b/src/features/communities/mention-groups.ts @@ -0,0 +1,726 @@ +// 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 { PROFILE_PAGE } from "../relay/profile-directory"; +import { + MENTION_GROUP_KINDS, + mentionGroupCommand, + mentionGroupName, + type MentionGroupSupport, + isMentionGroupId, +} 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 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 (!isMentionGroupId(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"]; + /** 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; + 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. + // Without a roster nobody is known to belong, so nobody is notified. + const member = (key: string): boolean | undefined => + !roster + ? true + : 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 + ? [...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 } : {}), + ...(support?.maxMembers ? { maxMembers: support.maxMembers } : {}), + manage, + settingVersion: (data.settings?.version ?? 0n).toString(), + ...(role ? { role } : {}), + canEdit: ready && viewerMember && (manage === "everyone" || manager), + 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(); + // 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; + 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; + } + ownerGeneration++; + looking.clear(); + for (const [key, owner] of owners) if (owner === null) recheck.add(key); + 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) || recheck.has(key)) && + !looking.has(key), + ); + if (!unknown.length) return; + for (const key of unknown) looking.add(key); + const generation = ownerGeneration; + void (async () => { + try { + // 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 + .filter((event) => event.kind === 0 && event.pubkey === key) + .sort(newest)[0]; + const [tag, ...extra] = + profile?.tags.filter(([name]) => name === "auth") ?? []; + const owner = + tag && !extra.length + ? ((await authTagOwner(key, tag)) ?? null) + : null; + if (generation !== ownerGeneration) return; + owners.set(key, owner); + recheck.delete(key); + } + lookupFailed = false; + } catch { + if (lifetime.signal.aborted || generation !== ownerGeneration) return; + lookupFailed = true; + } finally { + if (generation === ownerGeneration) + 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[]; + }) => + // 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 }) => + 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 e9fe0fe5ec..292fe05831 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 changed", + "conflict: mention group version changed", + ], + [ + "duplicate: mention group name already exists", + "duplicate: mention group name already exists", + ], + [ + "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) => { + 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. 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..3cb988ba71 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,86 @@ 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("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([]); + expect(h.formats()).toContain("code"); + }); + + 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..a3ff7e0216 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,28 @@ 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. + const code = + $from.parent.type.spec.code || + marks.some((mark) => mark.type === composerSchema.marks.code); + tr.replaceWith( + from, + to, + Fragment.fromArray([ + code + ? composerSchema.text(`@${group.label}`, marks) + : 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,12 +981,14 @@ 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; + // 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); @@ -1096,11 +1145,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 +1194,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 +1750,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 +1764,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 +1782,7 @@ export function EditableInput({ token.node.marks, ), ); - count++; + counted.add(recipient.pubkey); } if (tr.docChanged) editor.dispatch(tr); }; @@ -2580,6 +2649,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..96f5332917 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], [], ); }); @@ -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(() => { @@ -8728,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", { @@ -12606,6 +12612,96 @@ 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(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(); + 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 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 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" }; + 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) => { @@ -13710,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(() => { @@ -16669,7 +16775,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..0df8f403f1 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 = @@ -2074,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; @@ -2160,6 +2168,92 @@ function Composer({ setError(undefined); return true; } + /** 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 [ + ...(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( + 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, and + // 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, + }; + if (editing.target || (!(solo && !range) && inMarkdownCode(at))) + 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 +2287,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 ( @@ -2226,18 +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) { - 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; - } + 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. @@ -2258,6 +2338,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) @@ -2794,6 +2875,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. @@ -2892,7 +2979,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; @@ -2903,7 +2992,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); @@ -2938,7 +3027,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] @@ -2955,7 +3044,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), @@ -3883,7 +3972,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.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-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/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) 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/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/messages.ts b/src/features/relay/messages.ts index feacda6b43..bf18ef0685 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]); }; @@ -106,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/relay/native.test.ts b/src/features/relay/native.test.ts index 891c50e3c2..f9cc538944 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -261,6 +261,72 @@ 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" }, + ], + [ + { + 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) => { + 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/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; diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts index fb53c9ca11..50c706267c 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,16 @@ 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, + retry: mentionGroups.recovery.retry, + }), presence, viewer: transport?.viewer, relayAuthor: transport?.relayAuthor, @@ -4117,6 +4158,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..d50f890549 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,11 @@ export async function connectBrokerTransport( channelKit?: boolean; channelIdentity?: boolean; searchSort?: boolean; + mentionGroups?: { + membership?: unknown; + defaultManage?: unknown; + maxMembers?: unknown; + }; artifactSync?: boolean; sidebarPreferenceWrites?: boolean; sidebarSectionRemoval?: boolean; @@ -873,6 +881,22 @@ 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), + ...(Number.isSafeInteger(session.mentionGroups.maxMembers) && + (session.mentionGroups.maxMembers as number) > 0 + ? { maxMembers: session.mentionGroups.maxMembers as number } + : {}), + }, + } + : {}), ...(session.artifactSync === true ? { artifactSync: true as const } : {}), ...(session.channelKit ? { diff --git a/src/features/solo/chat-title.test.ts b/src/features/solo/chat-title.test.ts index a8009285c8..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"; @@ -74,3 +74,23 @@ it("drops leading namesake tags with their full-key qualifiers", () => { ); expect(startingChatTitle(draft)).toBe("fix the build"); }); + +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, + label: "crew", + start: 0, + end: 5, + }); + 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 1ecb010d09..1cbc5aa475 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,7 +35,10 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { + // 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() )