diff --git a/src/features/conversation/completion.test.ts b/src/features/conversation/completion.test.ts index 25f6651245..26e2a67f39 100644 --- a/src/features/conversation/completion.test.ts +++ b/src/features/conversation/completion.test.ts @@ -188,6 +188,30 @@ it("copies and freezes batch recipients without allowing malformed or oversized ).toEqual([]); } }); +it("keeps a group's label and drops one that is blank, not a string or not one plain line", () => { + const mentions = [{ pubkey: "a".repeat(64), name: "Carl" }]; + const edit = (extra: object) => + completionResult({ + items: [ + { + id: "crew", + label: "crew", + edit: { mentions, ...extra } as unknown as CompletionEdit, + }, + ], + }).items[0]?.edit; + expect(edit({ label: "crew" })).toEqual({ mentions, label: "crew" }); + for (const label of [ + "", + " ", + 7, + null, + "crew\n\n# Title", + "\u202ecrew", + "x".repeat(257), + ]) + expect(edit({ label })).toBeUndefined(); +}); it("keeps a host workspace edit and drops a provider's look-alike", () => { const host = workspaceEdit("design"); const result = completionResult({ diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 485f43a87f..9a373a59cc 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -1,5 +1,9 @@ import type { MentionRecipient } from "../messages/mention-draft"; -import { composerToken, type ComposerToken } from "../messages/composer-token"; +import { + chipLabel, + composerToken, + type ComposerToken, +} from "../messages/composer-token"; import type { Contribution } from "../../plugins/contributions"; import { isBundledContribution } from "../../plugins/provenance"; import type { @@ -149,7 +153,8 @@ export function completionResult( !/^[0-9a-f]{64}$/.test(person.pubkey) || typeof person.name !== "string" || !person.name.trim(), - ) + ) || + (edit.label !== undefined && !chipLabel(edit.label)) ) continue; } else if ("mention" in edit) { @@ -203,6 +208,9 @@ export function completionResult( }), ), ), + ...(edit.label !== undefined + ? { label: edit.label } + : {}), } : "mention" in edit ? { mention: Object.freeze({ ...edit.mention }) } diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index ea9eeac4b8..09d78782e0 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -420,6 +420,12 @@ export type CompletionEdit = }> | Readonly<{ mentions: readonly Readonly<{ pubkey: string; name: string }>[]; + /** One chip `@label` that notifies each of `mentions`, sent as the text + * `@label`. Kept only when it is letters, digits and spaces (a hyphen may + * sit between two letters or digits) and no name in the draft reads as a + * mention inside it; otherwise each of `mentions` is its own chip. In + * code only the text goes in, and a message edit adds no recipients. */ + label?: string; text?: never; mention?: never; pending?: never; diff --git a/src/features/direct-messages/NewMessage.test.tsx b/src/features/direct-messages/NewMessage.test.tsx index f09beb92d8..1885a2476b 100644 --- a/src/features/direct-messages/NewMessage.test.tsx +++ b/src/features/direct-messages/NewMessage.test.tsx @@ -2,7 +2,7 @@ import { SEARCH_DEBOUNCE_MS } from "../../shared/search-debounce"; import type { ConversationHostServices } from "../conversation/ConversationHost"; // @vitest-environment jsdom import "@testing-library/jest-dom/vitest"; -import { composerDOMFixture } from "../messages/composer-testing"; +import { composerDOMFixture, typedDraft } from "../messages/composer-testing"; import { afterEach, @@ -39,6 +39,7 @@ import { publicKeyLabels, } from "../../shared/identity/public-key"; import type { RelaySession } from "../relay/session"; +import { writeView } from "../../shared/view-state"; import { NewMessage } from "./NewMessage"; import { createAgentChoices } from "../agents/choices"; import type { LocalAgentsSnapshot } from "../agents/local"; @@ -1490,6 +1491,36 @@ it("locks during opening and delivery, waits for confirmation, and retries the s expect(t.directMessages.delivered).toHaveBeenCalledTimes(2); }); +it("sends a saved group whose label no longer holds as its members", async () => { + const crew = [ + { pubkey: people[2]?.pubkey ?? "", name: "Mary Jane" }, + { pubkey: people[3]?.pubkey ?? "", name: "Wes" }, + ]; + writeView( + scope, + "direct-message:new-draft", + typedDraft({ + text: "@*ops* hi", + recipients: crew.map((person) => ({ + ...person, + start: 0, + end: 6, + label: "*ops*", + })), + }), + ); + const t = setup(); + t.mount(); + await t.user.click(await screen.findByRole("option", { name: "Person 1" })); + await t.user.click(send()); + await waitFor(() => expect(t.onStarted).toHaveBeenCalledOnce()); + expect(t.messages.send).toHaveBeenCalledOnce(); + expect(t.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@Mary Jane @Wes hi", + crew.map((person) => person.pubkey), + ]); +}); + it("preserves recipients and draft after opening fails and across remount", async () => { const t = setup(); const view = t.mount(); diff --git a/src/features/direct-messages/NewMessage.tsx b/src/features/direct-messages/NewMessage.tsx index cf667384a1..81bf82dd52 100644 --- a/src/features/direct-messages/NewMessage.tsx +++ b/src/features/direct-messages/NewMessage.tsx @@ -32,7 +32,11 @@ import { type AttachmentDraft, } from "../messages/attachment-draft"; import { MessageComposer } from "../messages/MessageComposer"; -import { mentionDraft, type MentionDraft } from "../messages/mention-draft"; +import { + distinctRecipients, + mentionDraft, + type MentionDraft, +} from "../messages/mention-draft"; import { clearView, readView, writeView } from "../../shared/view-state"; import type { MessageIntent } from "../channel-navigation/routes"; import { Button } from "../../shared/design-system/ui/Button"; @@ -459,7 +463,9 @@ export function NewMessage({ session.messages.send( id, content, - draft.recipients.map((person) => person.pubkey), + distinctRecipients(draft.recipients).map( + (person) => person.pubkey, + ), uploaded, { key: recoveryKey, diff --git a/src/features/messages/EditableInput.test.tsx b/src/features/messages/EditableInput.test.tsx index 2820af3478..cedfe03d03 100644 --- a/src/features/messages/EditableInput.test.tsx +++ b/src/features/messages/EditableInput.test.tsx @@ -4840,7 +4840,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({ @@ -4857,9 +4857,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 () => { @@ -5025,3 +5025,113 @@ 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, ...people: (typeof ann)[]) => + people.map((person) => ({ + ...person, + label: "crew", + start, + end: start + "@crew".length, + })); + const add = (h: ReturnType, group = crew) => { + let result: boolean | "typed" = false; + act(() => { + result = h.input.insertText("", group); + }); + return result; + }; + + it("inserts one chip, sent as `@label`, whose span names every member", () => { + const h = mount(); + expect(add(h)).toBe(true); + expect(h.markdown()).toBe("@crew "); + expect(h.input.querySelectorAll("[data-mention]")).toHaveLength(1); + expect(h.draft().recipients).toEqual(on(0, ann, bo)); + }); + + it("is only its text in a code block", () => { + const h = mount(); + act(() => h.input.toggleFormat("code_block")); + expect(add(h)).toBe(true); + expect(h.input).toHaveValue("@crew "); + expect(h.draft().recipients).toEqual([]); + }); + + it("keeps its members through edits and restores, and is text without them", async () => { + const h = mount(); + add(h); + await h.user.keyboard("hi"); + expect(h.markdown()).toBe("@crew hi"); + expect(h.draft().recipients).toEqual(on(0, ann, bo)); + const { text, recipients } = h.draft(); + for (const saved of [h.draft(), mentionDraft({ text, recipients })]) { + const restored = mount(saved); + expect(restored.draft().recipients).toEqual(on(0, ann, bo)); + expect(restored.markdown()).toBe("@crew hi"); + expect(restored.input.querySelectorAll("[data-mention]")).toHaveLength(1); + act(() => restored.input.replaceRecipients([])); + expect(restored.draft().recipients).toEqual([]); + expect(restored.markdown()).toBe("@crew hi"); + expect(restored.input.querySelector("[data-mention]")).toBeNull(); + } + }); + + it("drops a removed member, and is text after the last", () => { + const h = mount(); + add(h); + act(() => h.input.removeRecipient(ann.pubkey)); + expect(h.draft().recipients).toEqual(on(0, bo)); + act(() => h.input.removeRecipient(bo.pubkey)); + expect(h.draft().recipients).toEqual([]); + expect(h.markdown()).toBe("@crew "); + expect(h.input.querySelector("[data-mention]")).toBeNull(); + }); + + it("keeps the requested members when recipients are replaced", () => { + const h = mount(); + add(h); + act(() => expect(h.input.replaceRecipients([bo])).toBe(true)); + expect(h.draft().recipients).toEqual(on(0, bo)); + act(() => expect(h.input.replaceRecipients([ann])).toBe(true)); + expect(h.draft().recipients).toEqual([{ ...ann, start: 0, end: 4 }]); + expect(h.markdown()).toBe("@Ann @crew "); + }); + + it("keeps its members inside a new link, as a person's chip does", () => { + const url = "https://example.com/notes"; + const h = mount("Check the "); + add(h); + act(() => h.input.insertText("notes")); + act(() => h.input.setSelectionRange(10, 21)); + paste(h.input, url); + expect(h.markdown()).toBe(`Check the [@crew notes](${url})`); + expect(h.draft().recipients).toEqual(on(10, ann, bo)); + }); + + it("notifies no one once a letter joins its label", async () => { + const h = mount(); + add(h); + act(() => h.input.setSelectionRange(5, 6)); + await h.user.keyboard("s"); + expect(h.markdown()).toBe("@crews"); + expect(h.draft().recipients).toEqual([]); + }); + + it("counts distinct people against the 32-recipient cap", () => { + const people = Array.from({ length: 32 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: `P${i}`, + })); + const h = mount(); + expect(add(h, { label: "crew", members: people })).toBe(true); + act(() => expect(h.input.insertText("", people[0])).toBe(true)); + expect(add(h, { label: "crew", members: [people[1] ?? ann] })).toBe(true); + act(() => expect(h.input.insertText("", [ann])).toBe(false)); + expect(add(h, { label: "crew", members: [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 53014f2bd7..38e460b0c0 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -53,6 +53,10 @@ import { composerResource, brokenResources, resourceBlockingMarks, + composerGroup, + groupKeeping, + tokenRecipients, + type ComposerGroup, } from "./composer-document"; import { scanMarkdown } from "../relay/message-content"; import type { @@ -118,6 +122,7 @@ import { pastedFiles, } from "./composer-clipboard"; import { + distinctRecipients, mentionBoundary, mentionDraft, type MentionDraft, @@ -896,12 +901,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(), @@ -914,7 +918,7 @@ export function EditableInput({ // recipient provenance, and return a pending mention to its typed query. for (const token of next.tokens) { if ( - token.node.attrs.recipient + token.node.attrs.recipient || token.node.attrs.group ? safe.recipients.some( (item) => item.start === token.start && item.end === token.end, @@ -1084,8 +1088,9 @@ export function EditableInput({ const source = projection(); const inside = source.tokens.filter( (token) => - (start > token.start && start < token.end) || - (end > token.start && end < token.end), + !token.node.attrs.group && + ((start > token.start && start < token.end) || + (end > token.start && end < token.end)), ); if (!inside.length) return; const tr = editor.state.tr; @@ -1113,13 +1118,21 @@ 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, onTooLong?: () => void, ) => { if (!editable() || composing.current || editor.composing) return false; + const group = + recipient && "members" in recipient + ? composerGroup(recipient, `@${recipient.label}`) + : undefined; + if (group === null) return false; flushTokens(); // The key that ended a name follows its mention in place of the space; // only text records its terminator before converting. @@ -1162,7 +1175,23 @@ 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 (group) { + const source = `@${group.label}`; + tr.replaceWith( + from, + to, + Fragment.fromArray([ + $from.parent.type.spec.code + ? composerSchema.text(source, marks) + : composerSchema.nodes.token.create( + { source, group, editAsText: false }, + null, + marks, + ), + composerSchema.text(after, marks), + ]), + ); + } else if (recipient) { const recipients: readonly MentionRecipient[] = Array.isArray(recipient) ? recipient : [recipient as MentionRecipient]; @@ -1197,8 +1226,9 @@ export function EditableInput({ : editor.state.selection.map(tr.doc, tr.mapping), ); if ( - Array.isArray(recipient) && - projectComposerDocument(tr.doc).draft.recipients.length > 32 + (Array.isArray(recipient) || group) && + distinctRecipients(projectComposerDocument(tr.doc).draft.recipients) + .length > 32 ) return false; if ( @@ -1372,8 +1402,22 @@ export function EditableInput({ return true; const added = recipients.filter((person) => !existing.has(person.pubkey)); const tr = closeHistory(editor.state.tr); + for (const token of source.tokens) { + const group = composerGroup( + token.node.attrs.group, + token.node.attrs.source, + ); + const kept = + group && groupKeeping(group, (pubkey) => requested.has(pubkey)); + if (kept !== group) + tr.setNodeMarkup(token.from, undefined, { + ...token.node.attrs, + group: kept, + }); + } for (const person of [...source.draft.recipients].reverse()) { - if (requested.has(person.pubkey)) continue; + if (requested.has(person.pubkey) || person.label !== undefined) + continue; const end = person.end + (source.draft.text[person.end] === " " ? 1 : 0); tr.delete(source.position(person.start), source.position(end, -1)); @@ -1401,7 +1445,7 @@ export function EditableInput({ } const next = projectComposerDocument(tr.doc).draft; if ( - next.recipients.length > 32 || + distinctRecipients(next.recipients).length > 32 || current.current.serializeDraft(next).length > current.current.maxLength ) return false; @@ -1978,7 +2022,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()) { @@ -1992,7 +2036,7 @@ export function EditableInput({ const identity = identityLink(token.node.attrs.source); if ( !identity || - count >= 32 || + (!counted.has(identity.pubkey) && counted.size >= 32) || !mentionBoundary( projectComposerDocument(tr.doc).draft.text, token.end, @@ -2010,7 +2054,7 @@ export function EditableInput({ token.node.marks, ), ); - count++; + counted.add(recipient.pubkey); } if (tr.docChanged) editor.dispatch(tr); }; @@ -3048,6 +3092,11 @@ export function EditableInput({ ...node.attrs, recipient: null, }); + const group = composerGroup(node.attrs.group, node.attrs.source); + const kept = + group && groupKeeping(group, (member) => member !== pubkey); + if (kept !== group) + tr.setNodeMarkup(pos, undefined, { ...node.attrs, group: kept }); 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 8356023c7d..47c545f366 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -64,7 +64,7 @@ import { MENTION_RESOLVE_TIMEOUT_MS } from "../conversation/completion"; import { bundledContribution } from "../../plugins/provenance"; import { mentionQuery } from "../../bundled/mentions/mention-query"; import { MentionCompletion } from "../../bundled/mentions/MentionCompletion"; -import type { MentionRecipient } from "./mention-draft"; +import type { MentionDraft, MentionRecipient } from "./mention-draft"; import type { AgentLibrarySnapshot } from "../agents/library"; import { createAgentChoices } from "../agents/choices"; import type { LocalAgents } from "../agents/local"; @@ -105,6 +105,7 @@ import { } from "../../shared/view-state"; import { clearDraft } from "../drafts-sent/drafts"; import { followupDraft } from "./mention-draft"; +import { followUpStorage } from "./follow-up-storage"; import { emojiMatches, type CustomEmoji } from "../relay/emoji"; import { CustomEmoji as CustomEmojiImage } from "../../bundled/emoji/CustomEmoji"; import { EmojiCompletion } from "../../bundled/emoji/EmojiCompletion"; @@ -113,6 +114,7 @@ import type { EmojiSnapshot } from "../relay/emoji-directory"; import { emojiQuery } from "../../bundled/emoji/emoji-query"; import type { ComposerInputElement } from "./composer-dom"; import { profileTarget } from "../profiles/target"; +import { profileMentionParts } from "./profile-mentions"; import { fromMarkdown } from "mdast-util-from-markdown"; import { setRememberAgentsPreference } from "./mention-preferences"; import * as modelStorage from "./solo-model-picks-storage"; @@ -249,6 +251,10 @@ function mount( viewer?: string, agents?: Agents, task?: ChannelMessage, + match: ComposerCompletion["match"] = ({ text, start }) => + text.startsWith("!") && start > 0 + ? { start: 0, end: start, query: text.slice(1, start) } + : null, ) { let commands: ComposerToolProps; const completionRequests: ComposerCompletionProps["publish"][] = []; @@ -265,10 +271,7 @@ function mount( pluginId: "test", revision, title: "Delayed", - match: ({ text, start }) => - text.startsWith("!") && start > 0 - ? { start: 0, end: start, query: text.slice(1, start) } - : null, + match, component: Completion, }); let completions: readonly Contribution[] = [ @@ -8132,7 +8135,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], [], ); }); @@ -8738,9 +8741,14 @@ 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); + expect(h.commands().insertMention(people[7] ?? first)).toBe(true); }); const before = h.input().value; act(() => { @@ -9291,7 +9299,6 @@ it.each([undefined, "root"])( 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", { @@ -14069,6 +14076,204 @@ 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"); }); +const bangAnywhere: ComposerCompletion["match"] = ({ text, start }) => { + const at = text.lastIndexOf("!", start - 1); + return at >= 0 && /^$|[\s`]$/.test(text.slice(0, at).slice(-1)) + ? { start: at, end: start, query: text.slice(at + 1, start) } + : null; +}; +function offerCrew( + h: ReturnType, + mentions: readonly MentionRecipient[], + label = "Crew", +) { + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "crew", label, edit: { mentions, label } }], + }); + }); +} +it("a labelled mentions edit is one chip, sent as `@label` with each member once", async () => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [first, second, first]); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("@Crew "); + expect( + screen.getByRole("img", { + name: "Group Crew, 2 recipients: Honey · rcaj, Honey · 04hu", + }), + ).toHaveTextContent("@Crew · 2"); + act(() => void h.commands().insertMention(first)); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe( + `@Crew @Honey (${first.pubkey}) `, + ); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([ + first.pubkey, + second.pubkey, + ]); +}); +it("a selection offset inside a group chip keeps it one chip that notifies every member", async () => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [first, second]); + await h.user.keyboard("{Enter}"); + act(() => h.input().setSelectionRange(2, 2)); + fireEvent(document, new Event("selectionchange")); + expect( + screen.getByRole("img", { + name: "Group Crew, 2 recipients: Honey · rcaj, Honey · 04hu", + }), + ).toBeVisible(); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe("@Crew "); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([ + first.pubkey, + second.pubkey, + ]); +}); +it("deleting a group chip removes every member from who is notified", async () => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [first, second]); + await h.user.keyboard("{Enter}"); + act(() => h.input().setSelectionRange(0, 5)); + await h.user.keyboard("{Backspace}"); + expect(h.commands().recipients).toEqual([]); + expect(screen.queryByRole("img", { name: /^Group Crew/ })).toBeNull(); +}); +it.each([ + [ + "a group", + { mentions: [first, second], label: "Crew" }, + [first.pubkey, second.pubkey], + ], + ["a person", { mention: first }, [first.pubkey]], +])( + "picking %s inside link text keeps its recipients", + async (_, edit, notified) => { + const h = mount( + {}, + undefined, + undefined, + undefined, + undefined, + bangAnywhere, + ); + const label = "go !Crew now"; + await h.user.type(h.input(), label); + act(() => h.input().setSelectionRange(0, label.length)); + act(() => void h.input().editLink()?.save(label, "https://example.test/")); + act(() => h.input().setSelectionRange(8, 8)); + fireEvent(document, new Event("selectionchange")); + expect(h.input().querySelector("a")).not.toBeNull(); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "pick", label: "Pick", edit }], + }); + }); + await h.user.keyboard("{Enter}"); + expect(h.input().querySelector("a [data-source]")).not.toBeNull(); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual(notified); + }, +); +it.each([ + ["a code span", "Crew", "see `run !Crew` now", "see `run @Crew ` now"], + ["a fenced block", "Crew", "```\nrun !Crew\n```", "```\nrun @Crew \n```"], + [ + "a code span", + "Honey team", + "see `run !Crew` now", + "see `run @Honey team ` now", + ], +])( + "a labelled mentions edit inside %s is only its name (%s)", + async (_, label, text, sent) => { + const h = mount( + {}, + undefined, + undefined, + undefined, + undefined, + bangAnywhere, + ); + h.fill(text); + const caret = text.indexOf("!Crew") + "!Crew".length; + act(() => h.input().setSelectionRange(caret, caret)); + fireEvent(document, new Event("selectionchange")); + offerCrew(h, [first, second], label); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue(sent); + expect(h.commands().recipients).toEqual([]); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe(sent); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([]); + }, +); +it.each([ + ["Crew", "@Crew "], + [ + "*ops*", + "[@Honey](nostr:npub1424242424242424242424242424242424242424242424242424qamrcaj) [@Honey](nostr:npub1hwamhwamhwamhwamhwamhwamhwamhwamhwamhwamhwamhwamhwasxw04hu) ", + ], +])( + "a labelled mentions edit while editing a sent message adds text and no recipients (%s)", + async (label, text) => { + const h = mount({}, undefined, first.pubkey); + h.setRows([editableMessage()]); + fireEvent.keyDown(h.input(), { key: "ArrowUp" }); + h.fill("!Crew"); + offerCrew(h, [first, second], label); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue(text); + expect(h.commands().recipients).toEqual([]); + h.submit(); + expect(h.messages.edit.mock.calls[0]?.[1]).toBe(text); + expect(h.messages.send).not.toHaveBeenCalled(); + }, +); +it("a labelled mentions edit with an unavailable member adds nothing", async () => { + const h = mount({ inviteAgents: true }); + h.fill("!Crew"); + offerCrew(h, [first, { pubkey: "c".repeat(64), name: "Missing" }]); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("!Crew"); + expect(screen.getByRole("alert")).toHaveTextContent("no longer available"); +}); +it("a person in a chip and also mentioned alone is one reference outside a DM", async () => { + const h = mount(); + const list = { + status: "ready", + channels: [ + { + id: "channel", + channelType: "dm", + members: ["d".repeat(64), second.pubkey], + participants: [second.pubkey], + }, + ], + }; + Object.assign(h.session, { + channels: { list: () => list, subscribeList: () => () => {} }, + memberAdditions: { add: vi.fn() }, + outbox: { ...h.session.outbox, supports: () => true }, + }); + h.fill("!Crew"); + offerCrew(h, [first, second]); + await h.user.keyboard("{Enter}"); + act(() => void h.commands().insertMention(first)); + fireEvent.submit(screen.getByRole("form")); + await act(async () => {}); + expect(h.messages.send).toHaveBeenCalledOnce(); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([second.pubkey]); + expect(h.messages.send.mock.calls[0]?.at(-1)).toEqual([first.pubkey]); +}); it.each(["disabled", "retarget", "unmount"])( "revokes batch commands after %s", (transition) => { @@ -15556,6 +15761,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", async () => { + const { h, ada, bea } = mountSoloAgents({ main: first.pubkey }); + h.fill("!Crew"); + offerCrew(h, [ada, bea]); + await h.user.keyboard("{Enter}"); + act(() => void h.commands().insertText("hello")); + act(() => void h.commands().insertMention(ada)); + act(() => void 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(() => { @@ -18550,7 +18765,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: @@ -19506,6 +19724,861 @@ it("pastes a copied forward literally inside a code block", async () => { ).not.toBeInTheDocument(); }); +async function pickSent(edit: { + mentions: MentionRecipient[]; + label?: string; +}) { + const h = mount(); + h.fill("!Crew"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "crew", label: "Crew", edit }], + }); + }); + await h.user.keyboard("{Enter}"); + const chips = screen + .queryAllByRole("img") + .map((node) => node.getAttribute("aria-label")); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + const [, content, tags] = h.messages.send.mock.calls[0] ?? []; + cleanup(); + return { chips, content, tags }; +} +const maryJane = { ...first, name: "Mary Jane" }; +const wes = { ...second, name: "Wes" }; +it.each([ + ["eng-oncall", [first, second], true], + ["eng_ios", [first, second], false], + ["Mary crew", [maryJane, wes], false], +])( + "a group picked with the label %s is one chip only when its label holds for every reader", + async (label, members, holds) => { + const group = await pickSent({ mentions: members, label }); + expect(group.tags).toEqual(members.map((person) => person.pubkey)); + if (holds) { + expect(group.content).toBe(`@${label} `); + expect(group.chips).toEqual([ + `Group ${label}, 2 recipients: Honey · rcaj, Honey · 04hu`, + ]); + } else { + expect(group).toEqual(await pickSent({ mentions: members })); + expect(group.chips.some((name) => name?.startsWith("Group"))).toBe(false); + } + }, +); +it.each(["eng-oncall", "a-b-c"])( + "a group labelled %s is still one chip after its saved draft is restored", + async (label) => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [first, second], label); + await h.user.keyboard("{Enter}"); + act(() => h.input().blur()); + h.remount(); + expect( + screen + .queryAllByRole("img") + .map((node) => node.getAttribute("aria-label")), + ).toEqual([`Group ${label}, 2 recipients: Honey · rcaj, Honey · 04hu`]); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe(`@${label} `); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([ + first.pubkey, + second.pubkey, + ]); + }, +); + +it.each([true, false])( + "a group label that starts with the name of a person already in the draft is its members (person in the draft: %s)", + async (withPerson) => { + const h = mount( + {}, + undefined, + undefined, + undefined, + undefined, + bangAnywhere, + ); + if (withPerson) { + h.fill("!H"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "honey", label: "Honey", edit: { mention: first } }], + }); + }); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("!Crew"); + } else h.fill("!Crew"); + offerCrew(h, [{ ...second, name: "Wes" }], "Honey crew"); + await h.user.keyboard("{Enter}"); + expect( + screen.queryAllByRole("img", { name: /^Group Honey crew/ }), + ).toHaveLength(withPerson ? 0 : 1); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe( + withPerson ? "@Honey @Wes " : "@Honey crew ", + ); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual( + withPerson ? [first.pubkey, second.pubkey] : [second.pubkey], + ); + }, +); + +const savedCrew = ( + text: string, + label: string, + crew: readonly MentionRecipient[], + before: readonly MentionRecipient[] = [], +) => { + const start = text.indexOf(`@${label}`); + return { + text, + recipients: [ + ...before.map((person) => ({ ...person, start: 0, end: start - 1 })), + ...crew.map((person) => ({ + ...person, + start, + end: start + label.length + 1, + label, + })), + ], + }; +}; +const opsCrew = savedCrew("@*ops* hi", "*ops*", [maryJane, wes]); +async function sentGroups(h: ReturnType) { + const groups = screen.queryAllByRole("img", { name: /^Group / }).length; + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + const [, content, tags] = h.messages.send.mock.calls[0] ?? []; + return { groups, content, tags }; +} +it.each([ + ["*ops*", opsCrew], + [ + "Mary crew", + savedCrew("@Mary Jane @Mary crew hi", "Mary crew", [wes], [maryJane]), + ], +])( + "a saved group labelled %s comes back as typed and is sent as its members", + async (_label, saved) => { + writeView("scope", "draft:channel", typedDraft(saved)); + expect(await sentGroups(mount())).toEqual({ + groups: 1, + content: "@Mary Jane @Wes hi", + tags: [maryJane.pubkey, wes.pubkey], + }); + }, +); +it("a group whose label no longer holds is sent as its members from a draft saved without a document", async () => { + writeView("scope", "draft:channel", opsCrew); + expect(await sentGroups(mount())).toEqual({ + groups: 1, + content: "@Mary Jane @Wes hi", + tags: [maryJane.pubkey, wes.pubkey], + }); +}); +it("a group whose label no longer holds is sent as its members from a draft another window saves", async () => { + const h = mount(); + act(() => writeView("scope", "draft:channel", typedDraft(opsCrew))); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Mary Jane @Wes hi", + tags: [maryJane.pubkey, wes.pubkey], + }); +}); +it("a group whose label a person added after it binds is sent as its members when the draft reopens over a conflict", async () => { + const h = mount({}, undefined, undefined, undefined, undefined, bangAnywhere); + h.fill("!Crew"); + offerCrew(h, [wes], "Mary crew"); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("!M"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "mary", label: "Mary Jane", edit: { mention: maryJane } }], + }); + }); + await h.user.keyboard("{Enter}"); + act(() => writeView("scope", "draft:channel", "Saved elsewhere")); + h.remount(); + expect(screen.getByRole("alert")).toHaveTextContent(/changed elsewhere/); + fireEvent.click(screen.getByRole("button", { name: "Keep my draft" })); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Wes @Mary Jane ", + tags: [wes.pubkey, maryJane.pubkey], + }); +}); +it("a group picked before a member whose name starts its label is sent as its members, with the text after it in place", async () => { + const h = mount({}, undefined, undefined, undefined, undefined, bangAnywhere); + h.fill("!Crew"); + offerCrew(h, [wes], "Mary crew"); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("!M"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "mary", label: "Mary Jane", edit: { mention: maryJane } }], + }); + }); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("see you"); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Wes @Mary Jane see you", + tags: [wes.pubkey, maryJane.pubkey], + }); +}); +it("in a Solo chat with agents only, a group of people outside it whose label starts with the toolbar agent's name is sent as its members", async () => { + const { h } = mountSoloAgents({ main: first.pubkey }); + const outside = [ + { pubkey: "d".repeat(64), name: "Cy" }, + { pubkey: "e".repeat(64), name: "Di" }, + ]; + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, outside, "Ada crew"); + await h.user.keyboard("{Enter}"); + act(() => void h.commands().insertText("hi")); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Cy @Di hi", + tags: [first.pubkey], + }); +}); +it("in a Solo chat with agents only, a group further in the draft joins the toolbar's agent", async () => { + const cam = { pubkey: "f".repeat(64), name: "Cam" }; + writeView( + "scope", + "draft:channel", + typedDraft( + savedCrew("Plan this, then ask @Crew", "Crew", [ + { pubkey: second.pubkey, name: "Bea" }, + cam, + ]), + ), + ); + const { h, ada, sendingTo } = mountSoloAgents({ + members: [first.pubkey, second.pubkey, cam.pubkey], + unpicked: true, + }); + h.setLibrary([first, second, cam]); + h.setProfiles( + new Map([ + [first.pubkey, { name: "Ada", isAgent: true }], + [second.pubkey, { name: "Bea", isAgent: true }], + [cam.pubkey, { name: "Cam", isAgent: true }], + ]), + ); + await choicesLoaded(); + act(() => h.commands().audience?.only([ada])); + expect(sendingTo("Ada, Bea, Cam")).toBeInTheDocument(); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "Plan this, then ask @Crew", + tags: [first.pubkey, second.pubkey, cam.pubkey], + }); +}); +it("in a Solo chat with agents only, a group that opens the draft is for its members alone when the first is outside the chat", async () => { + const { h, sendingTo } = mountSoloAgents(); + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, [ + { pubkey: "d".repeat(64), name: "Cy" }, + { pubkey: second.pubkey, name: "Bea" }, + ]); + await h.user.keyboard("{Enter}"); + act(() => void h.commands().insertText("hi")); + expect(sendingTo("Bea")).toBeInTheDocument(); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Crew hi", + tags: [second.pubkey], + }); +}); +it.each([ + ["picked", 0], + ["saved in a draft", 1], +])( + "in a one-to-one DM with an agent, a group whose label starts with the agent's name is %s and sent as its members", + async (_how, groups) => { + const viewer = "d".repeat(64); + const ops = "c".repeat(64); + if (groups) + writeView( + "scope", + "draft:channel", + typedDraft(savedCrew("@Ops crew hi", "Ops crew", [maryJane, wes])), + ); + const h = mount({}, undefined, viewer); + h.setProfiles(new Map([[ops, { name: "Ops", isAgent: true }]])); + const dm = { + status: "ready" as const, + channels: [ + { id: "channel", channelType: "dm" as const, members: [viewer, ops] }, + ], + }; + Object.assign(h.session.channels, { + list: () => dm, + get: () => dm.channels[0], + }); + h.remount(); + if (!groups) { + h.fill("!Crew"); + offerCrew(h, [maryJane, wes], "Ops crew"); + await h.user.keyboard("{Enter}hi"); + } + expect(await sentGroups(h)).toEqual({ + groups, + content: "@Mary Jane @Wes hi", + tags: [], + }); + }, +); +it.each([ + ["picked", 0], + ["saved in a draft", 1], +])( + "a group whose label starts with a member's verified name is %s and sent as its members", + async (_how, groups) => { + const mj = { ...first, name: "MJ" }; + const label = "Mary Jane Jones crew"; + const verified = { + displayName: "MJ", + username: "mj", + fullName: "Mary Jane Jones", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }; + if (groups) + writeView( + "scope", + "draft:channel", + typedDraft(savedCrew(`@${label} hi`, label, [mj, wes])), + ); + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ", verified }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + if (!groups) { + h.fill("!Crew"); + offerCrew(h, [mj, wes], label); + await h.user.keyboard("{Enter}hi"); + } + const sent = await sentGroups(h); + const reader = new Map([ + [mj.pubkey, { name: "Mary Jane Jones", verified }], + [wes.pubkey, { name: "Wes" }], + ]); + expect({ + ...sent, + parts: profileMentionParts( + { content: sent.content ?? "", mentions: sent.tags ?? [] }, + reader, + ), + }).toEqual({ + groups, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + parts: [ + { text: "@MJ", target: profileTarget(mj.pubkey) }, + { text: " " }, + { text: "@Wes", target: profileTarget(wes.pubkey) }, + { text: " hi" }, + ], + }); + }, +); +it("a group whose label a member's new verified name breaks while link sharing checks a linked chat is not sent, and the next Send sends it as its members", async () => { + const mj = { ...first, name: "MJ" }; + const link = "[Session: Work](buzz://channel/session-id)"; + const list = { + status: "ready" as const, + channels: [ + { + id: "channel", + name: "general", + channelType: "stream", + members: [mj.pubkey, wes.pubkey], + }, + { + id: "session-id", + name: "Work", + channelType: "solo", + creator: "viewer", + members: ["viewer"], + }, + ], + }; + const details = { visibility: "public", joinRole: "member" }; + const held = deferred(); + const asked = deferred(); + let loads = 0; + const load = () => { + asked.resolve(); + return loads++ ? Promise.resolve(details) : held.promise; + }; + const h = mount({}, undefined, "viewer"); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ" }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + h.retarget({ + session: { + ...h.session, + channels: { + ...h.session.channels, + list: () => list, + get: (id: string) => list.channels.find((channel) => channel.id === id), + }, + channelDetails: { snapshot: () => undefined, load }, + } as unknown as RelaySession, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mary crew"); + await h.user.keyboard("{Enter}hi "); + act(() => h.input().insertText(link)); + h.submit(); + await act(() => asked.promise); + h.setProfiles( + new Map([ + [ + mj.pubkey, + { + name: "MJ", + verified: { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }, + }, + ], + [wes.pubkey, { name: "Wes" }], + ]), + ); + await act(async () => held.resolve(details)); + await waitFor(() => + expect({ + sent: h.messages.send.mock.calls.map(([, content]) => content), + draft: h.input().value, + line: + screen.queryAllByText( + "A member's name changed while sending. Send again.", + ).length > 0, + }).toEqual({ sent: [], draft: `@Mary crew hi ${link}`, line: true }), + ); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: `@MJ @Wes hi ${link}`, + tags: [mj.pubkey, wes.pubkey], + }); +}); +it("a group whose label a member's new verified name breaks while a detached window uploads its file is not sent, and the next Send sends it as its members", async () => { + const mj = { ...first, name: "MJ" }; + const result = deferred>(); + const started = deferred(); + const upload = () => { + started.resolve(); + return result.promise; + }; + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ" }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + const { unread: _full, ...detached } = h.session; + h.retarget({ + session: { + ...detached, + attachments: { upload }, + } as unknown as RelaySession, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mary crew"); + await h.user.keyboard("{Enter}hi"); + attachByPaste(h.input(), attachmentFile()); + await act(() => started.promise); + h.submit(); + await waitFor(() => + expect(screen.getByRole("button", { name: "Send message" })).toBeDisabled(), + ); + h.setProfiles( + new Map([ + [ + mj.pubkey, + { + name: "MJ", + verified: { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }, + }, + ], + [wes.pubkey, { name: "Wes" }], + ]), + ); + await act(async () => result.resolve(uploadDescriptor())); + await waitFor(() => + expect({ + sent: h.messages.send.mock.calls.map(([, content]) => content), + draft: h.input().value, + file: screen.queryAllByText("notes.txt").length > 0, + line: + screen.queryAllByText( + "A member's name changed while sending. Send again.", + ).length > 0, + }).toEqual({ sent: [], draft: "@Mary crew hi", file: true, line: true }), + ); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + }); +}); +it("a group whose label a member's new verified name breaks while the main window uploads its file is not sent, and the next Send sends it as its members", async () => { + const mj = { ...first, name: "MJ" }; + const result = deferred>(); + const started = deferred(); + const upload = () => { + started.resolve(); + return result.promise; + }; + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ" }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + h.retarget({ + session: { + ...h.session, + attachments: { upload }, + } as unknown as RelaySession, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mary crew"); + await h.user.keyboard("{Enter}hi"); + attachByPaste(h.input(), attachmentFile()); + await act(() => started.promise); + h.submit(); + await waitFor(() => expect(h.input().value).toBe("")); + h.setProfiles( + new Map([ + [ + mj.pubkey, + { + name: "MJ", + verified: { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }, + }, + ], + [wes.pubkey, { name: "Wes" }], + ]), + ); + await act(async () => result.resolve(uploadDescriptor())); + const form = within(h.container).getByRole("form"); + await waitFor(() => + expect({ + sent: h.messages.send.mock.calls.map(([, content]) => content), + draft: h.input().value, + file: within(form).queryAllByText("notes.txt").length > 0, + line: + within(form).queryAllByText( + "A member's name changed while sending. Send again.", + ).length > 0, + }).toEqual({ sent: [], draft: "@Mary crew hi", file: true, line: true }), + ); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + }); + expect(h.messages.send.mock.calls[0]?.[3]).toEqual([uploadDescriptor()]); +}); +const maryVerified = { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, +}; +function queueChat( + agents: readonly MentionRecipient[], + people: readonly MentionRecipient[] = [], +) { + localStorage.setItem("buzz-follow-up-behavior.v1", "queue"); + const h = mount(); + h.setLibrary(agents.map(({ pubkey, name }) => ({ pubkey, name }))); + const rename = (verified?: typeof maryVerified) => + h.setProfiles( + new Map([ + ...agents.map(({ pubkey, name }, index) => [ + pubkey, + { + name, + isAgent: true, + ...(index === 0 && verified ? { verified } : {}), + }, + ]), + ...people.map(({ pubkey, name }) => [pubkey, { name }]), + ] as [string, Profile][]), + ); + rename(); + const listeners = new Set<() => void>(); + let activity = { + status: "unavailable", + records: [], + turns: [], + typing: [], + local: agents.slice(0, 1).map(({ pubkey }) => ({ + agent: pubkey, + channelId: "channel", + messageId: "previous", + state: "working", + scope: "scope", + threadRootId: "", + startedAt: 1, + })), + }; + const chat = { + id: "channel", + channelType: "solo", + creator: "viewer", + members: ["viewer", ...[...agents, ...people].map(({ pubkey }) => pubkey)], + }; + const channelList = { status: "ready", channels: [chat] }; + h.retarget({ + ownSoloConversation: true, + requireMention: true, + session: { + ...h.session, + viewer: "viewer", + channels: { + ...h.session.channels, + list: () => channelList, + }, + channelWrites: { + refreshMembership: async () => chat, + addAgents: vi.fn(), + }, + agentActivity: { + activate: () => () => {}, + snapshot: () => activity, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }, + } as unknown as RelaySession, + }); + return { + h, + rename, + finish() { + activity = { + ...activity, + local: activity.local.map((row) => ({ ...row, state: "done" })), + }; + act(() => { + for (const listener of listeners) listener(); + }); + }, + }; +} +async function sendCrew( + h: ReturnType, + members: readonly MentionRecipient[], + label: string, +) { + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, members, label); + await h.user.keyboard("{Enter}hi"); + h.submit(); +} +it("a group in a Solo follow-up that waits in the queue is sent as its members, as named when it was sent", async () => { + const mj = { ...first, name: "MJ" }; + const chat = queueChat([mj, wes]); + await sendCrew(chat.h, [mj, wes], "Mary crew"); + await screen.findByRole("region", { name: "Queued follow-ups" }); + expect(chat.h.messages.send).not.toHaveBeenCalled(); + chat.rename(maryVerified); + chat.finish(); + await waitFor(() => expect(chat.h.messages.send).toHaveBeenCalledOnce()); + expect(chat.h.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@MJ @Wes hi", + [mj.pubkey, wes.pubkey], + ]); +}); +it("a group in a queued Solo follow-up is saved as its members and sent as its members after a restart", async () => { + const mj = { ...first, name: "MJ" }; + const before = queueChat([mj, wes]); + await sendCrew(before.h, [mj, wes], "Mary crew"); + await screen.findByRole("region", { name: "Queued follow-ups" }); + expect( + followUpStorage("scope") + .load() + .map(({ text, recipients }) => ({ text, recipients })), + ).toEqual([{ text: "@MJ @Wes hi", recipients: [mj.pubkey, wes.pubkey] }]); + cleanup(); + const after = queueChat([mj, wes]); + after.rename(maryVerified); + const queued = await screen.findByRole("region", { + name: "Queued follow-ups", + }); + await within(queued).findByText("Saved before restart. Send when ready."); + await after.h.user.click( + within(queued).getByRole("button", { name: "Send" }), + ); + await waitFor(() => expect(after.h.messages.send).toHaveBeenCalledOnce()); + expect(after.h.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@MJ @Wes hi", + [mj.pubkey, wes.pubkey], + ]); + expect(before.h.messages.send).not.toHaveBeenCalled(); +}); +it("a group in a Solo send that goes out at once with the follow-up setting on queue is also sent as its members", async () => { + const guest = { pubkey: "d".repeat(64), name: "Guest" }; + const chat = queueChat([first], [guest]); + await sendCrew(chat.h, [first, guest], "Crew"); + await waitFor(() => expect(chat.h.messages.send).toHaveBeenCalledOnce()); + expect(chat.h.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@Honey @Guest hi", + [first.pubkey, guest.pubkey], + ]); + expect( + screen.queryByRole("region", { name: "Queued follow-ups" }), + ).toBeNull(); +}); +it("a new Solo chat's first send with the follow-up setting on queue keeps a group as one chip", async () => { + localStorage.setItem("buzz-follow-up-behavior.v1", "queue"); + const submit = vi.fn(); + const h = mount({ + ownSoloConversation: true, + submission: { + draftKey: "new-draft", + locked: false, + disabled: false, + submit, + }, + }); + h.setLibrary([first, second].map(({ pubkey, name }) => ({ pubkey, name }))); + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, [first, second], "Crew"); + await h.user.keyboard("{Enter}hi"); + h.submit(); + await waitFor(() => expect(submit).toHaveBeenCalledOnce()); + const sent = submit.mock.calls[0]?.[0] as MentionDraft; + expect([sent.text, sent.recipients.map(({ label }) => label)]).toEqual([ + "@Crew hi", + ["Crew", "Crew"], + ]); +}); +it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { + const mj = { ...first, name: "MJ" }; + const h = mount(); + Object.assign(h.session.profiles, { + event: (pubkey: string) => + pubkey === mj.pubkey + ? { + id: "e".repeat(64), + pubkey, + created_at: 1, + kind: 0, + content: JSON.stringify({ name: "Mo Jones" }), + tags: [], + } + : undefined, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mo crew"); + await h.user.keyboard("{Enter}hi"); + expect(await sentGroups(h)).toEqual({ + groups: 0, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + }); +}); +it.each([ + ["the composer's own send", false], + ["a submission", true], +])( + "a group sent as its members past the length limit is refused through %s, and the draft stays", + async (_path, submitted) => { + const submit = vi.fn(); + const draftKey = submitted ? "new-draft" : "draft:channel"; + const text = `@*ops* ${"x".repeat(15990)}`; + writeView( + "scope", + draftKey, + typedDraft(savedCrew(text, "*ops*", [maryJane, wes])), + ); + const h = mount( + submitted + ? { submission: { draftKey, locked: false, disabled: false, submit } } + : {}, + ); + h.submit(); + expect(await screen.findByRole("alert")).toHaveTextContent( + "@*ops* could not be tagged: the message would be too long.", + ); + expect(submit).not.toHaveBeenCalled(); + expect(h.messages.send).not.toHaveBeenCalled(); + expect(screen.queryAllByRole("img", { name: /^Group / })).toHaveLength(1); + expect(h.input()).toHaveValue(text); + }, +); +it("undoing and redoing a group pick brings back one chip with the same members", async () => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [maryJane, wes]); + await h.user.keyboard("{Enter}"); + const chips = () => + screen.queryAllByRole("img").map((node) => node.getAttribute("aria-label")); + const picked = chips(); + expect(picked).toEqual(["Group Crew, 2 recipients: Mary Jane, Wes"]); + act(() => h.input().undo(false)); + expect(chips()).toEqual([]); + act(() => h.input().undo(true)); + expect(chips()).toEqual(picked); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Crew ", + tags: [maryJane.pubkey, wes.pubkey], + }); +}); + it("lets a send gate keep or refuse a message the composer would publish, and publishes when a gate throws", async () => { const kept: OutgoingMessage[] = []; let session: RelaySession | undefined; diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index ae373b785b..c22ee93116 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -52,6 +52,8 @@ import { readComposerSnapshot, composerMarkdownContext, markdownRanges, + groupLabelHolds, + readerNames, } from "./composer-document"; import { useMessageEdit, lastEditableMessage } from "./useMessageEdit"; import { editMentionText } from "./message-edit"; @@ -153,6 +155,7 @@ import styles from "./Messages.module.css"; import { messageViewKey } from "./view-key"; import { isEmojiOnly, usesLargeEmojiPresentation } from "./emoji-size"; import { + distinctRecipients, legacyFollowupDraft, MAX_DRAFT_GIFS, mentionBoundary, @@ -160,7 +163,9 @@ import { editorMention, hasHumanMentionSelection, hostComposerProvenance, + sentDraft, stageableGif, + withoutSpans, type MentionDraft, type MentionRecipient, } from "./mention-draft"; @@ -1155,6 +1160,14 @@ function Composer({ ]), ] : pubkeys; + const boundNames = (people: readonly MentionRecipient[]) => + readerNames( + people, + session.profiles.snapshot(), + (pubkey) => session.profiles.event?.(pubkey), + session.viewer, + dmMembers, + ); // Read at send time, as `addressed` is rendered. A reference addresses // nobody, so it goes along with whoever the message is for. const sendRecipients = () => { @@ -2273,7 +2286,11 @@ function Composer({ ); return false; } - if (recipient && valueRef.current.recipients.length >= 32) { + if ( + recipient && + distinctRecipients([...valueRef.current.recipients, recipient]).length > + 32 + ) { setError("Choose at most 32 recipients"); return false; } @@ -2387,7 +2404,8 @@ function Composer({ ? "unresolved" : !admits()(recipient.pubkey) ? "unavailable" - : valueRef.current.recipients.length >= 32 + : distinctRecipients([...valueRef.current.recipients, recipient]) + .length > 32 ? "limit" : undefined; const accepted = @@ -2566,9 +2584,11 @@ 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, - )) { + 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; @@ -2588,6 +2608,7 @@ function Composer({ function insertMentions( recipients: readonly MentionRecipient[], range?: CompletionQuery, + requested?: string, ) { if ( !Array.isArray(recipients) || @@ -2602,6 +2623,14 @@ function Composer({ ) ) return false; + const label = + requested !== undefined && + groupLabelHolds( + requested, + boundNames([...recipients, ...valueRef.current.recipients]), + ) + ? requested + : undefined; const unique = [ ...new Map( recipients.map((person) => [person.pubkey, editorMention(person)]), @@ -2620,31 +2649,45 @@ function Composer({ input.current.readOnly ) return false; + if (requested !== undefined && range && inMarkdownCode(range, false)) + return insert(`@${requested} `, undefined, range); // Message edits only add references, never new notification intent. if (editing.target) return insert( - unique.map((person) => editMentionText(person)).join(""), + label === undefined + ? unique.map((person) => editMentionText(person)).join("") + : `@${label} `, undefined, range, ); const admitted = admits(); + const noun = label === undefined ? "team" : "group"; if (unique.some((person) => !admitted(person.pubkey))) { setError( - "A team member is no longer available. Refresh choices before trying again.", + label === undefined + ? "A team member is no longer available. Refresh choices before trying again." + : "A recipient is no longer available. Refresh choices before trying again.", ); return false; } - const text = unique.map((person) => `@${person.name} `).join(""); + const text = + label === undefined + ? unique.map((person) => `@${person.name} `).join("") + : `@${label} `; if ( !(solo && !range ? keepProseCaret( (at) => !!input.current?.insertText(text, unique, at, undefined, false), ) - : input.current.insertText(text, unique, range)) + : input.current.insertText( + text, + label === undefined ? unique : { label, members: unique }, + range, + )) ) { setError( - "The team would exceed the message length or 32-recipient limit. Nothing was added.", + `The ${noun} would exceed the message length or 32-recipient limit. Nothing was added.`, ); return false; } @@ -2654,6 +2697,18 @@ function Composer({ setError(undefined); return true; } + function inMarkdownCode( + range: Readonly<{ start: number; end: number }>, + links = true, + ) { + const doc = readComposerSnapshot(valueRef.current.document); + const context = doc + ? composerMarkdownContext(doc, undefined, links) + : { text: valueRef.current.text, protected: [] }; + return [...context.protected, ...markdownRanges(context.text).literal].some( + (r) => range.start < r.end && range.end > r.start, + ); + } function replaceRecipients(recipients: readonly MentionRecipient[]) { if ( !Array.isArray(recipients) || @@ -2688,13 +2743,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 ( @@ -2721,18 +2773,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)) return false; const chosen = chosenWorkspace(edit); if (chosen !== undefined) { // The chat's workspace leaves no text behind; the control shows it. @@ -2757,7 +2798,7 @@ function Composer({ return true; } if ("mentions" in edit && edit.mentions) - return insertMentions(edit.mentions, query); + return insertMentions(edit.mentions, query, edit.label); if ("mention" in edit && edit.mention) return insert(`@${edit.mention.name} `, edit.mention, query, typed); if ("token" in edit && edit.token) { @@ -3320,9 +3361,24 @@ function Composer({ const savedRevision = revision.current; const retirementCursor = draftRetirementCursor(scope, draftKey); let retiredByOwner = false; - const attempt = new AbortController(); - sendAttempt.current = attempt; - const captured = valueRef.current; + const typed = valueRef.current; + const queueable = + !!host && + ownSoloConversation && + !submission && + !threadRootId && + followUpBehaviorPreference() === "queue"; + const bind = () => + sentDraft( + typed, + boundNames(routing ? recipientsNow : typed.recipients), + queueable, + ); + const captured = bind(); + const recheckLabels = () => { + if (composerMarkdown(bind()) !== composerMarkdown(captured)) + throw new Error("A member's name changed while sending. Send again."); + }; const explicit = human && ownerProvenance ? captured.recipients @@ -3356,12 +3412,17 @@ function Composer({ (person) => !captured.recipients.some((item) => item.pubkey === person.pubkey), ); - const queueable = - !!host && - ownSoloConversation && - !threadRootId && - followUpBehaviorPreference() === "queue"; + const attempt = new AbortController(); + sendAttempt.current = attempt; try { + if (captured !== typed && composerMarkdown(captured).length > 16000) { + const groups = new Set(typed.recipients.map((item) => item.label)); + for (const item of captured.recipients) groups.delete(item.label); + groups.delete(undefined); + throw new Error( + `${[...groups].map((label) => `@${label}`).join(", ")} ${pendingRefusals.length}.`, + ); + } const tokens = draftTokens(captured); messageTokenTags(tokens); if (command && onCommand) { @@ -3370,7 +3431,7 @@ function Composer({ setSending(true); if (await handled) { attempt.signal.throwIfAborted(); - if (valueRef.current !== captured) return; + if (valueRef.current !== typed) return; const current = viewRevision(scope, draftKey); if (current !== savedRevision) { diagnose("send-upload-conflict", savedRevision, current); @@ -3433,7 +3494,9 @@ function Composer({ return; } let references: readonly string[] = []; - let recipients = capturedRecipients.map((item) => item.pubkey); + let recipients = distinctRecipients(capturedRecipients).map( + (item) => item.pubkey, + ); let declinedImports: readonly string[] = []; if (soloConversation || ownSoloConversation) { admission.current = true; @@ -3443,8 +3506,9 @@ function Composer({ fromPill, )); } else if (recipients.length) { + const people = distinctRecipients(captured.recipients); // 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); @@ -3453,7 +3517,7 @@ function Composer({ old, attempt.signal, () => - valueRef.current === captured && + valueRef.current === typed && sameAttachmentSelection( attachments.store.snapshot(), capturedAttachments, @@ -3468,7 +3532,7 @@ function Composer({ .channels.find((item) => item.id === channelId); if (channel?.members && allowsOutsideMentions(channel)) { const current = () => - valueRef.current === captured && + valueRef.current === typed && sameAttachmentSelection( attachments.store.snapshot(), capturedAttachments, @@ -3479,7 +3543,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] @@ -3496,7 +3560,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), @@ -3524,7 +3588,7 @@ function Composer({ if (attachments.store.snapshot().some((item) => item.status === "error")) return; if ( - valueRef.current !== captured || + valueRef.current !== typed || !sameAttachmentSelection( attachments.store.snapshot(), capturedAttachments, @@ -3562,7 +3626,7 @@ function Composer({ setError(undefined); const current = () => permitted.current && - valueRef.current === captured && + valueRef.current === typed && viewRevision(scope, draftKey) === savedRevision && sameAttachmentSelection( attachments.store.snapshot(), @@ -3579,6 +3643,7 @@ function Composer({ } if (!current()) return; } + recheckLabels(); // Every prompt passed, so this message goes out to who was declined. oldAgents.decline(declinedImports); // Destination and content are fixed here; a background send never retargets. @@ -3794,6 +3859,7 @@ function Composer({ reportConflict(); return; } + recheckLabels(); id = await publish(uploaded); } else if (capturedAttachments.length) { // The revision acceptance saves; remembered agents are not a draft. @@ -3814,6 +3880,7 @@ function Composer({ }, capturedAttachments, async (uploaded) => { + recheckLabels(); // Report a synchronous publication before the new row can render. const result = publish(uploaded); const sent = typeof result === "string" ? result : await result; @@ -3824,7 +3891,7 @@ function Composer({ // restored. A later edit belongs to its author, not this job. if (!flushPendingDraft(scope, draftKey)) return "conflict"; const current = viewRevision(scope, draftKey); - const capturedRevision = JSON.stringify(captured); + const capturedRevision = JSON.stringify(typed); const cleared = (raw: string | null | undefined) => { if (!raw) return false; try { @@ -3887,7 +3954,7 @@ function Composer({ if (target.snapshot().length) return "conflict"; if ( current !== capturedRevision && - replaceView(scope, draftKey, current, captured) !== "saved" + replaceView(scope, draftKey, current, typed) !== "saved" ) return false; if (!target.adopt(files)) return false; @@ -3895,7 +3962,7 @@ function Composer({ // The whole captured pick set returns with the whole draft; the // recipient filter above applies again on the next send. notifyRecovered(session, recoveryKey, { - draft: captured, + draft: typed, picks: capturedPicks, preparationError, }); diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index 000321d198..d481e4f499 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -19,6 +19,7 @@ import { useReferenceDirectory } from "./ReferenceText"; import { readComposerSnapshot, composerMarkdownContext, + tokenRecipients, } from "./composer-document"; import { messageLinkParts } from "./message-link-parts"; import { parseBuzzLink } from "../navigation/buzz-links"; @@ -106,6 +107,29 @@ const TokenChip = memo(function TokenChip({ ); }); +const GroupChip = memo(function GroupChip({ + label, + names, + count, +}: { + label: string; + names: string; + count: number; +}) { + return ( + + ); +}); + /** Decorations never change source text or infer notification recipients from names. */ export function RichComposerInput({ draft, @@ -378,6 +402,26 @@ export function RichComposerInput({ const preview = gifPreviews.get(start); if (preview && preview.end === end && !mention) return { start, end, editAsText: false, content: preview.content }; + const { group } = tokenRecipients( + draft.recipients, + draft.text.slice(start, end), + { start, end }, + ); + if (group) + return { + start, + end, + editAsText: false, + content: ( + labels.get(item.pubkey) ?? item.name) + .join(", ")} + count={group.members.length} + /> + ), + }; 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 81e1abed1b..d27a67d7a9 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from "vitest"; import { + composerGroup, + groupKeeping, + groupLabelHolds, + readerNames, + tokenRecipients, composerSchema as schema, projectComposerDocument, readComposerDocument, @@ -8,12 +13,13 @@ import { import { composerMarkdown } from "./composer-markdown"; import { profileMentionParts } from "./profile-mentions"; import { profileTarget } from "../profiles/target"; -import { mentionDraft } from "./mention-draft"; +import { mentionDraft, type DraftRecipient } from "./mention-draft"; import { fromMarkdown } from "mdast-util-from-markdown"; import { gfmStrikethroughFromMarkdown } from "mdast-util-gfm-strikethrough"; import { gfmStrikethrough } from "micromark-extension-gfm-strikethrough"; import type { Nodes, RootContent } from "mdast"; import type { InlineFormat } from "./composer-dom"; +import type { Profile } from "../relay/contracts"; const paragraph = (...children: ReturnType[]) => schema.nodes.paragraph.create(null, children); @@ -735,6 +741,14 @@ describe("inline formatting batch", () => { ), ).toBe("_@Honey_"); }); + it("trusts a group chip only with a one-line label", () => { + const members = [{ pubkey: "a".repeat(64), name: "Honey" }]; + const group = (label: string) => + composerGroup({ label, members }, `@${label}`); + expect(group("crew")).not.toBeNull(); + for (const label of ["crew\n\n# Title", "\u202ecrew", "x".repeat(257)]) + expect(group(label)).toBeNull(); + }); it("escapes literal punctuation in each generated format", () => { for (const mark of ["bold", "italic", "strike"] as const) for (const character of ["*", "_", "~", "!"]) { @@ -779,3 +793,295 @@ it.each(["chat", "document"] as const)( expect(readComposerDocument(draft, []).eq(original)).toBe(true); }, ); + +it("a group chip's members keep `explicit` through a saved draft, as a person chip does", () => { + const ann = { pubkey: "a".repeat(64), name: "Ann", explicit: true as const }; + const bo = { pubkey: "b".repeat(64), name: "Bo", explicit: true as const }; + const saved = mentionDraft( + projectComposerDocument( + doc( + paragraph( + schema.nodes.token.create({ + source: "@Crew", + group: { label: "Crew", members: [ann, bo] }, + }), + schema.text(" "), + schema.nodes.token.create({ source: "@Ann", recipient: ann }), + ), + ), + ).draft, + ); + expect( + projectComposerDocument( + readComposerDocument(saved, []), + ).draft.recipients.map(({ pubkey, label, explicit }) => [ + pubkey, + label, + explicit, + ]), + ).toEqual([ + [ann.pubkey, "Crew", true], + [bo.pubkey, "Crew", true], + [ann.pubkey, undefined, true], + ]); +}); + +it("a person chip keeps `explicit` when it is rebuilt from the draft text", () => { + const ann = { pubkey: "a".repeat(64), name: "Ann", explicit: true as const }; + const draft = mentionDraft({ + text: "@Ann ", + recipients: [{ ...ann, start: 0, end: 4 }], + }); + expect( + projectComposerDocument( + readComposerDocument(draft, [{ start: 0, end: 4 }]), + ).draft.recipients.map(({ pubkey, explicit }) => [pubkey, explicit]), + ).toEqual([[ann.pubkey, true]]); +}); + +const honeyA = { pubkey: "a".repeat(64), name: "Honey" }; +const honeyB = { pubkey: "b".repeat(64), name: "Honey" }; +const honey = [honeyA, honeyB]; +const maryJaneAndWes = [ + { pubkey: "a".repeat(64), name: "Mary Jane" }, + { pubkey: "b".repeat(64), name: "Wes" }, +]; +it.each([ + ["Team 42", honey, true], + ["24-7", honey, true], + ["eng-oncall", honey, true], + ["a-b-c", honey, true], + ["हिंदी टीम", honey, true], + ["हिंदी-टीम", honey, true], + ["ทีมไทย", honey, true], + ["Cafe\u0301 crew", honey, true], + ["eng_ios", honey, false], + ["-ops", honey, false], + ["ops-", honey, false], + ["a--b", honey, false], + ["a - b", honey, false], + ["Honey team", honey, false], + ["Honey-crew", honey, false], + ["Mary crew", maryJaneAndWes, false], + ["mary crew", maryJaneAndWes, false], + ["MARY CREW", maryJaneAndWes, false], + ["Mary-crew", maryJaneAndWes, false], + ["Marys crew", maryJaneAndWes, true], + ["Crew Mary", maryJaneAndWes, true], + ["Wesley team", maryJaneAndWes, true], + ["ÉMILE crew", [{ pubkey: "a".repeat(64), name: "Émile Durand" }], false], + ["ſam crew", [{ pubkey: "a".repeat(64), name: "Sam Lee" }], false], + ["Ann team", [{ pubkey: "a".repeat(64), name: "Ann\tLee" }], false], + ["Ann crew", [{ pubkey: "a".repeat(64), name: " Ann Lee" }], false], + ["Ann squad", [{ pubkey: "a".repeat(64), name: "Ann\u0085" }], false], + [" ann pals", [{ pubkey: "a".repeat(64), name: " Ann" }], false], + ["Rene\u0301 fans", [{ pubkey: "a".repeat(64), name: "Rene" }], false], + ["Crew", [{ pubkey: "a".repeat(64), name: "C++" }], true], +])( + "the group label %s holds only when it is plain text and no reader binds a member's name or first word at its start", + (label, people, holds) => { + expect(groupLabelHolds(label, people)).toBe(holds); + }, +); + +const crew = { label: "Crew", members: honey }; +it.each<[string, string[], ReturnType]>([ + [ + "some members left", + ["a".repeat(64)], + { label: "Crew", members: honey.slice(0, 1) }, + ], + ["none left", [], null], + ["nothing removed", ["a".repeat(64), "b".repeat(64)], crew], +])("a group keeping its members: %s", (_case, keep, expected) => { + const kept = groupKeeping(crew, (pubkey) => keep.includes(pubkey)); + expect(kept).toEqual(expected); + expect(kept === crew).toBe(expected === crew); +}); + +const onCrew = (person: typeof honeyA, label = "Crew") => ({ + ...person, + label, + start: 0, + end: label.length + 1, +}); +it.each<[string, DraftRecipient[], string, ReturnType]>( + [ + [ + "one recipient", + [{ ...honeyA, start: 0, end: 6 }], + "@Honey", + { recipient: { ...honeyA, start: 0, end: 6 }, group: null }, + ], + [ + "a labelled group", + [onCrew(honeyA), onCrew(honeyB)], + "@Crew", + { recipient: null, group: { label: "Crew", members: honey } }, + ], + [ + "the same person twice counts once", + [onCrew(honeyA), onCrew(honeyA), onCrew(honeyB)], + "@Crew", + { recipient: null, group: { label: "Crew", members: honey } }, + ], + [ + "a label that fails composerGroup gives neither", + [onCrew(honeyA, "Crew\u0007"), onCrew(honeyB, "Crew\u0007")], + "@Crew\u0007", + { recipient: null, group: null }, + ], + [ + "a recipient with another start or end is not on the range", + [ + { ...honeyA, start: 0, end: 11 }, + { ...honeyB, start: 1, end: 6 }, + ], + "@Honey", + { recipient: null, group: null }, + ], + ], +)("a source token's recipients: %s", (_case, recipients, source, expected) => { + expect( + tokenRecipients(recipients, source, { start: 0, end: source.length }), + ).toStrictEqual(expected); +}); + +const viewer = "c".repeat(64); +const [mary, ops] = ["a".repeat(64), "b".repeat(64)]; +const verified = { + displayName: "MJ", + username: "mj", + fullName: "Mary Jane Jones", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, +}; +it.each< + [ + string, + Record, + object | undefined, + { viewer?: string; members?: string[] }, + string[][], + ] +>([ + ["the shown name", {}, undefined, {}, [[mary, "Mary"]]], + [ + "both verified names", + { [mary]: { name: "Mary", verified } }, + undefined, + {}, + [ + [mary, "Mary"], + [mary, "MJ"], + [mary, "Mary Jane Jones"], + ], + ], + [ + "the self-set name", + {}, + { name: "Mo Jones" }, + {}, + [ + [mary, "Mary"], + [mary, "Mo Jones"], + ], + ], + [ + "the fallback name", + {}, + { about: "no name" }, + {}, + [ + [mary, "Mary"], + [mary, "aaaaaaaaaa"], + ], + ], + [ + "the raw name mobile reads", + {}, + { display_name: "Ann Lee\u200e", name: "alee" }, + {}, + [ + [mary, "Mary"], + [mary, "alee"], + [mary, "Ann Lee\u200e"], + ], + ], + [ + "the raw name mobile reads with no display name", + {}, + { name: "Ann Lee\u200e" }, + {}, + [ + [mary, "Mary"], + [mary, "aaaaaaaaaa"], + [mary, "Ann Lee\u200e"], + ], + ], + [ + "each name once", + { + [mary]: { name: "Mary", verified: { ...verified, displayName: "Mary" } }, + }, + { display_name: "Mary" }, + {}, + [ + [mary, "Mary"], + [mary, "Mary Jane Jones"], + ], + ], + [ + "a one-to-one DM's agent partner", + { [ops]: { name: "Ops", isAgent: true } }, + undefined, + { viewer, members: [viewer, ops] }, + [ + [mary, "Mary"], + [ops, "Ops"], + ], + ], + [ + "no human partner", + { [ops]: { name: "Wes" } }, + undefined, + { viewer, members: [viewer, ops] }, + [[mary, "Mary"]], + ], + [ + "no partner in a DM without the viewer", + { [ops]: { name: "Ops", isAgent: true } }, + undefined, + { viewer, members: [mary, ops] }, + [[mary, "Mary"]], + ], + [ + "no partner in a group DM", + { [ops]: { name: "Ops", isAgent: true } }, + undefined, + { viewer, members: [viewer, ops, "d".repeat(64)] }, + [[mary, "Mary"]], + ], +])("a reader may bind %s", (_case, profiles, own, dm, entries) => { + expect( + readerNames( + [{ pubkey: mary, name: "Mary" }], + new Map(Object.entries(profiles)), + (pubkey) => + own && pubkey === mary + ? { + id: "e".repeat(64), + pubkey, + created_at: 1, + kind: 0, + content: JSON.stringify(own), + tags: [], + } + : undefined, + dm.viewer, + dm.members, + ).map(({ pubkey, name }) => [pubkey, name]), + ).toEqual(entries); +}); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index b860c5bea2..6e36ce4d26 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -9,11 +9,17 @@ import { composerLinkUrl } from "./composer-link"; import { MAX_MARKDOWN_LENGTH, scanMarkdown } from "../relay/message-content"; import type { MentionDraft, + MentionRecipient, DraftRecipient, PendingMention, } from "./mention-draft"; import type { ComposerResource } from "../conversation/contracts"; +import { profileMentionNames, profileMentionParts } from "./profile-mentions"; +import { foldProfiles } from "../relay/profiles"; +import type { Profile } from "../relay/contracts"; +import type { EventData } from "../relay/events"; import { + chipLabel, composerToken, composerTokenText, type ComposerToken, @@ -153,6 +159,9 @@ 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. */ + 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. */ @@ -263,6 +272,150 @@ 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` + * is `@label` of, and 1 to 32 distinct, well-formed members. Anything else is + * prose. */ +export function composerGroup(value: unknown, source: unknown) { + if (!value || typeof value !== "object") return null; + const { label, members } = value as Record; + if ( + !chipLabel(label) || + source !== `@${label}` || + !Array.isArray(members) || + !members.length || + members.length > 32 || + members.some( + (member) => + !member || + typeof member.pubkey !== "string" || + !/^[0-9a-f]{64}$/.test(member.pubkey) || + typeof member.name !== "string" || + !member.name.trim(), + ) || + new Set(members.map((member) => member.pubkey)).size < members.length + ) + return null; + return value as ComposerGroup; +} +/** `group` with only the members `keep` admits: itself when it loses none, + * `null` when none are left. */ +export function groupKeeping( + group: ComposerGroup, + keep: (pubkey: string) => boolean, +) { + const members = group.members.filter((member) => keep(member.pubkey)); + if (members.length === group.members.length) return group; + return members.length ? { label: group.label, members } : null; +} +/** Whether `@label` reads as one group to whoever gets it: letters, digits + * and spaces, a hyphen only between two of them, in which no reader binds + * any of `people`. This app's reader matches a whole name; mobile's matches + * a name or its first word, as written or trimmed, at the start, in any + * case, where a word ends. */ +export function groupLabelHolds( + label: string, + people: readonly MentionRecipient[], +) { + return ( + /^(?:[\p{L}\p{M}\p{N} ]|(?<=[\p{L}\p{M}\p{N}])-(?=[\p{L}\p{N}]))+$/u.test( + label, + ) && + !people.some((person) => + profileMentionParts( + { + content: `@${label}`, + mentions: [person.pubkey], + mentionLabels: [{ id: person.pubkey, names: [person.name] }], + }, + undefined, + ).some((part) => part.target), + ) && + !people.some((person) => + [person.name, person.name.replace(/^[\s\u0085]+|[\s\u0085]+$/g, "")] + .flatMap((name) => [name, name.split(/\s+/)[0]]) + .some( + (name) => + !!name && + new RegExp( + `^${name.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&")}(?![\\p{L}\\p{M}\\p{N}])`, + "iu", + ).test(label), + ), + ) + ); +} +function mobileName(content: string) { + try { + const body = JSON.parse(content) as Record | null; + const name = + typeof body?.display_name === "string" ? body.display_name : body?.name; + return typeof name === "string" ? name : undefined; + } catch { + return undefined; + } +} +/** Every name a reader may bind to each of `people`, and to a 1:1 DM's agent + * partner, whom the relay tags: the shown name, the verified names, the name + * set on their own profile or the key prefix shown when it sets none and, as + * mobile reads it, that profile's raw `display_name` or else `name`. */ +export function readerNames( + people: readonly MentionRecipient[], + profiles: ReadonlyMap, + ownProfile: (pubkey: string) => EventData | undefined, + viewer?: string, + dmMembers: readonly string[] = [], +) { + const partners = + viewer && dmMembers.length === 2 && dmMembers.includes(viewer) + ? dmMembers.flatMap((pubkey) => { + const profile = profiles.get(pubkey); + return pubkey !== viewer && profile?.isAgent + ? [{ pubkey, name: profile.name }] + : []; + }) + : []; + return [...people, ...partners].flatMap(({ pubkey, name }) => { + const event = ownProfile(pubkey); + const own = event && foldProfiles([event]).get(pubkey); + return [ + ...new Set([ + name, + ...profileMentionNames(profiles.get(pubkey)), + own?.name, + event && mobileName(event.content), + ]), + ].flatMap((each) => (each ? [{ pubkey, name: each }] : [])); + }); +} +/** 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 }, +) { + 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) return { recipient: on[0] ?? null, group: null }; + const members = new Map( + on + .filter((item) => item.label === label) + .map(({ pubkey, name, explicit }) => [ + pubkey, + { pubkey, name, ...(explicit ? { explicit } : {}) }, + ]), + ); + return { + recipient: null, + group: composerGroup({ label, members: [...members.values()] }, source), + }; +} /** Draft text stays the editing/completion coordinate space. Formatting metadata * is local authoring state; message publication serializes it separately. */ export function readComposerDocument( @@ -298,6 +451,7 @@ 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); return node.type.create( { ...node.attrs, @@ -306,9 +460,15 @@ 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 && + tokenRecipients(draft.recipients, node.attrs.source, { + start, + end, + }).group, resource: resource && resource.source === node.attrs.source && @@ -339,14 +499,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; @@ -557,7 +715,18 @@ 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, explicit } of group.members) + recipients.push({ + pubkey, + name, + label: group.label, + ...(explicit ? { explicit } : {}), + 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 }); @@ -610,6 +779,7 @@ function project(doc: EditorNode) { export function composerMarkdownContext( doc: EditorNode, source = projectComposerDocument(doc), + links = true, ) { let text = source.draft.text; const protectedRanges: SourceRange[] = []; @@ -622,6 +792,7 @@ export function composerMarkdownContext( text.slice(start, end).replace(/[^\r\n]/g, "x") + text.slice(end); }; + const { code, link, literal } = composerSchema.marks; doc.descendants((node, position) => { if (node.type.name === "markdown_table") { mask(position, position + node.nodeSize); @@ -633,9 +804,8 @@ export function composerMarkdownContext( } if ( node.isInline && - (["code", "link", "literal"] as const).some((name) => - composerSchema.marks[name].isInSet(node.marks), - ) + (code.isInSet(node.marks) || + (link.isInSet(node.marks) ? links : literal.isInSet(node.marks))) ) mask(position, position + node.nodeSize); }); @@ -715,6 +885,7 @@ function read( !token || composerTokenText(token) !== node.attrs.source || ("recipient" in node.attrs && node.attrs.recipient) || + ("group" in node.attrs && node.attrs.group) || ("resource" in node.attrs && node.attrs.resource) || ("pending" in node.attrs && node.attrs.pending) ) diff --git a/src/features/messages/composer-dom.ts b/src/features/messages/composer-dom.ts index a04c26dca8..687dce14b7 100644 --- a/src/features/messages/composer-dom.ts +++ b/src/features/messages/composer-dom.ts @@ -1,5 +1,6 @@ import type { MentionDraft, MentionRecipient } from "./mention-draft"; import type { ComposerResource } from "../conversation/contracts"; +import type { ComposerGroup } from "./composer-document"; import type { ComposerToken } from "./composer-token"; import type { AnnotationMark } from "./composer-annotations"; import type { AnnotationObservation } from "../conversation/contracts"; @@ -105,7 +106,7 @@ export type ComposerInputElement = HTMLDivElement & { /** `"typed"`: only the terminator landed; the text did not fit. */ insertText( text: string, - recipient?: MentionRecipient | readonly MentionRecipient[], + 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 be88a6d144..904183e6f8 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -141,14 +141,16 @@ function qualifyNamesakes( composerSchema.marks.recipient.isInSet(node?.marks ?? [])?.attrs; const keys = new Map>(); doc.descendants((node) => { - const found = person(node); + const members: readonly { pubkey: string; name: string }[] = + node.attrs.group?.members ?? []; // Mobile readers match names case-insensitively, so case-only namesakes // collide too; each occurrence keeps its own spelling. - if (found) - keys.set( - found.name.toLowerCase(), - (keys.get(found.name.toLowerCase()) ?? new Set()).add(found.pubkey), - ); + for (const found of [person(node), ...members]) + if (found) + keys.set( + found.name.toLowerCase(), + (keys.get(found.name.toLowerCase()) ?? new Set()).add(found.pubkey), + ); }); if (![...keys.values()].some((set) => set.size > 1)) return doc; const { code, link } = composerSchema.marks; @@ -345,7 +347,7 @@ function authoredLiteralRanges(doc: EditorNode, mode: ComposerMarkdownMode) { ? "\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; }); @@ -437,6 +439,7 @@ function paragraphMarkdown( literals.push({ start, end: text.length }); if ( node.attrs.recipient || + node.attrs.group || composerSchema.marks.recipient.isInSet(node.marks) ) recipients.push({ start, end: text.length }); diff --git a/src/features/messages/composer-token.ts b/src/features/messages/composer-token.ts index 2e369c9e17..baa4842da7 100644 --- a/src/features/messages/composer-token.ts +++ b/src/features/messages/composer-token.ts @@ -10,6 +10,14 @@ export type ComposerToken = Readonly< ) & { readonly [key: string]: JsonValue | undefined } >; +/** A chip's label: one line, at most 256 characters, with no control or + * bidirectional override characters. */ +export const chipLabel = (label: unknown): label is string => + typeof label === "string" && + !!label.trim() && + label.length <= 256 && + !/[\p{Cc}\u202a-\u202e\u2066-\u2069]/u.test(label); + /** Copy only bounded JSON. A provider cannot retain mutable editor metadata or * turn a token into a recipient through a label, prototype or callback. */ export function composerToken(value: unknown): ComposerToken | undefined { @@ -25,10 +33,7 @@ export function composerToken(value: unknown): ComposerToken | undefined { !token.id || token.id.length > 4096 || /\p{Cc}/u.test(token.id) || - typeof token.label !== "string" || - !token.label.trim() || - token.label.length > 256 || - /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u.test(token.label) + !chipLabel(token.label) ) return; if (token.kind === "skill") { diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 645ddb4e27..47e963ac33 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -5,6 +5,7 @@ import { legacyFollowupDraft, mentionDraft, followupDraft, + sentDraft, } from "./mention-draft"; import { typedDraft } from "./composer-testing"; import { composerMarkdown } from "./composer-markdown"; @@ -252,3 +253,115 @@ it("sends chips of different keys sharing a name as `@Name ()`, others bare ), ).toBe(`@Honey (${"a".repeat(64)}) \`@Honey\``); }); +it("keeps a group's members only on the exact text `@label`", () => { + const crew = (label: string, text = "@crew hi", end = 5) => + mentionDraft({ + text, + recipients: [ + { ...first, label, start: 0, end }, + { ...second, label, start: 0, end }, + ], + }); + expect(crew("crew").recipients).toEqual([ + { ...first, label: "crew", start: 0, end: 5 }, + { ...second, label: "crew", start: 0, end: 5 }, + ]); + expect(crew("team").recipients).toEqual([]); + expect(crew("crew", "@crews hi").recipients).toEqual([]); + 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 restored = mentionDraft({ + text: "@all @x", + 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); +}); +it("a sent group whose label no longer holds is one chip per member, each keeping its explicit pick", () => { + const mary = { + pubkey: "5".repeat(64), + name: "Mary", + explicit: true as const, + }; + const wes = { pubkey: "6".repeat(64), name: "Wes" }; + const saved = typedDraft({ + text: "@*ops* hi", + recipients: [mary, wes].map((person) => ({ + ...person, + label: "*ops*", + start: 0, + end: 6, + })), + }); + expect(sentDraft(saved, saved.recipients).recipients).toEqual([ + { ...mary, start: 0, end: 5 }, + { ...wes, start: 6, end: 10 }, + ]); +}); +const crewMary = { pubkey: "5".repeat(64), name: "Mary" }; +const crewWes = { pubkey: "6".repeat(64), name: "Wes" }; +it.each([ + [ + false, + "@crew hi", + [crewMary, crewWes].map((person) => ({ + ...person, + label: "crew", + start: 0, + end: 5, + })), + ], + [ + true, + "@Mary @Wes hi", + [ + { ...crewMary, start: 0, end: 5 }, + { ...crewWes, start: 6, end: 10 }, + ], + ], +])( + "a sent group whose label holds is one chip, or one chip per member when every group is split (every: %s)", + (every, text, recipients) => { + const saved = typedDraft({ + text: "@crew hi", + recipients: [crewMary, crewWes].map((person) => ({ + ...person, + label: "crew", + start: 0, + end: 5, + })), + }); + const sent = sentDraft(saved, saved.recipients, every); + expect([sent.text, sent.recipients]).toEqual([text, recipients]); + }, +); +it("a saved group whose label has a control character, which no chip holds, is sent as text that tags nobody", () => { + const text = "@crew\u0007 hi"; + const saved = mentionDraft({ + text, + recipients: [first, second].map((person) => ({ + ...person, + label: "crew\u0007", + start: 0, + end: 6, + })), + }); + const sent = sentDraft(saved, saved.recipients); + expect([sent.text, sent.recipients]).toEqual([text, []]); +}); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 573706ea2e..000aa5405d 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -1,7 +1,12 @@ +import { Fragment, Slice } from "prosemirror-model"; import { forwardReference, type ForwardReference } from "./forward-clipboard"; import { canonicalChatCard } from "./chat-cards"; +import { chipLabel } from "./composer-token"; import { + composerSchema, + groupLabelHolds, projectComposerDocument, + readComposerDocument, readComposerSnapshot, } from "./composer-document"; @@ -11,8 +16,10 @@ export type MentionRecipient = Readonly<{ /** A recipient selected in the editor. Automatic and legacy spans omit it. */ explicit?: true; }>; +/** One recipient on a span. A group chip projects one per member, each with + * the group's `label`: then the span is `@label`, not `@name`. */ export type DraftRecipient = MentionRecipient & - Readonly<{ start: number; end: number }>; + Readonly<{ start: number; end: number; label?: string }>; let humanMentionSelection = false; /** The host's own composer entry points can collect local send evidence. */ @@ -37,6 +44,33 @@ export function editorMention({ } export const hasHumanMentionSelection = () => humanMentionSelection; +/** One entry per person: a group shares a span with its members, and two + * chips can name the same person. */ +export const distinctRecipients = ( + recipients: readonly T[], +) => [...new Map(recipients.map((item) => [item.pubkey, item])).values()]; +function capRecipients(recipients: readonly T[]) { + const kept = new Set(); + return recipients.filter((item) => { + if (!kept.has(item.pubkey) && kept.size >= 32) 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 @@ -102,11 +136,12 @@ export function mentionDraft(value: unknown): MentionDraft { /^[0-9a-f]{64}$/.test(item.pubkey) && typeof item.name === "string" && !!item.name.trim() && + (item.label === undefined || chipLabel(item.label)) && 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), ) : []; @@ -136,17 +171,55 @@ export function mentionDraft(value: unknown): MentionDraft { } : {}), ...(doc ? { document: document as ComposerSnapshot } : {}), - recipients: safe - .slice(0, 32) - .map(({ pubkey, name, start, end, explicit }) => ({ + recipients: capRecipients(safe).map( + ({ pubkey, name, label, start, end, explicit }) => ({ pubkey, name, + ...(label === undefined ? {} : { label }), start, end, ...(explicit === true ? { explicit } : {}), - })), + }), + ), }; } +/** `draft` as a send gives it: a group chip whose label no longer holds + * against the `people` the send tags is one chip per member, each keeping its + * explicit pick. With nothing to split it returns `draft` itself; the draft + * in the box is left as typed. With `every`, every group chip is split. */ +export function sentDraft( + draft: MentionDraft, + people: readonly MentionRecipient[], + every = false, +) { + if (!draft.recipients.some((item) => item.label !== undefined)) return draft; + const doc = readComposerDocument(draft, draft.recipients); + const stale = projectComposerDocument(doc).tokens.filter( + ({ node }) => + node.attrs.group && + (every || !groupLabelHolds(node.attrs.group.label, people)), + ); + if (!stale.length) return draft; + const split = stale.reduceRight((next, { from, to, node }) => { + const members: readonly MentionRecipient[] = node.attrs.group.members; + const chips = members.flatMap((person, index) => [ + ...(index ? [composerSchema.text(" ", node.marks)] : []), + composerSchema.nodes.token.create( + { source: `@${person.name}`, recipient: person, editAsText: false }, + null, + node.marks, + ), + ]); + return next.replace(from, to, new Slice(Fragment.from(chips), 0, 0)); + }, doc); + const { text, recipients, document } = projectComposerDocument(split).draft; + return mentionDraft({ + ...draft, + text, + recipients, + ...(draft.document ? { document } : {}), + }); +} /** What counts as a draft everywhere: text, an attached chat or GIF, or `files`. * A typed tag is text the person put there; the composer no longer saves * tags of its own, and the ones earlier releases saved are not content. */ @@ -175,12 +248,7 @@ export function addressingOnly(value: MentionDraft): boolean { 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/solo/chat-title.test.ts b/src/features/solo/chat-title.test.ts index a8009285c8..a141e889af 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,30 @@ it("drops leading namesake tags with their full-key qualifiers", () => { ); expect(startingChatTitle(draft)).toBe("fix the build"); }); + +it("keeps a leading group tag, so Solo naming matches the sent text", () => { + const member = (pubkey: string, name: string, label: string) => ({ + pubkey: pubkey.repeat(64), + name, + label, + start: 0, + end: label.length + 1, + }); + const title = (text: string, label: string) => + startingChatTitle( + typedDraft( + mentionDraft({ + text, + recipients: [member("a", "Ann", label), member("b", "Bo", label)], + }), + ), + ); + expect(title("@crew do X", "crew")).toBe("@crew do X"); + expect( + isStartingChatTitle(title("@crew do X", "crew"), { + text: "@crew do X", + recipients: [], + }), + ).toBe(true); + expect(title("@Ann's team do X", "Ann's team")).toBe("@Ann's team do X"); +}); diff --git a/src/features/solo/chat-title.ts b/src/features/solo/chat-title.ts index 1ecb010d09..519732402a 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,6 +35,7 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { + if (recipient.label !== undefined) break; if ( recipient.start < draftStart || draft.text.slice(draftStart, recipient.start).trim() diff --git a/src/features/solo/recipients.test.ts b/src/features/solo/recipients.test.ts index 29619d919d..97ee2e5952 100644 --- a/src/features/solo/recipients.test.ts +++ b/src/features/solo/recipients.test.ts @@ -137,4 +137,15 @@ it("a draft that opens with a tag is for its tags; a later tag joins the toolbar }); // No tags: the toolbar's agents. expect(soloAudience("hi", [], [ada], named).recipients).toEqual([ada]); + expect( + soloAudience( + "@Crew hi", + [{ ...reference, end: 5 }, tag(bea, 0)], + [ada], + named, + ), + ).toEqual({ + opensWithTag: true, + recipients: [{ ...reference, end: 5 }, tag(bea, 0)], + }); }); diff --git a/src/features/solo/recipients.ts b/src/features/solo/recipients.ts index 5f40787376..5b4d346bf6 100644 --- a/src/features/solo/recipients.ts +++ b/src/features/solo/recipients.ts @@ -43,20 +43,19 @@ export function soloRecipients( /** Solo, alone with agents: who a draft addresses. A draft that opens with a * tag is for the agents it tags; a tag further in joins the toolbar's agents. - * `named` tells a notifying tag from a reference, which never opens one. */ + * `named` tells a notifying tag from a reference, which never opens one. A + * group chip tags each member at one place, so it opens the draft when any + * member is named. */ export function soloAudience>( text: string, typed: readonly (T & Readonly<{ start: number }>)[], toolbar: readonly T[], named: (pubkey: string) => boolean, ): { opensWithTag: boolean; recipients: readonly T[] } { - const first = typed.reduce<(typeof typed)[number] | undefined>( - (earliest, item) => - !earliest || item.start < earliest.start ? item : earliest, - undefined, - ); + const start = Math.min(...typed.map((item) => item.start)); const opensWithTag = - !!first && named(first.pubkey) && !text.slice(0, first.start).trim(); + typed.some((item) => item.start === start && named(item.pubkey)) && + !text.slice(0, start).trim(); const recipients = opensWithTag ? typed : [...toolbar, ...typed]; return { opensWithTag, diff --git a/src/shared/design-system/ui/InlineChip.tsx b/src/shared/design-system/ui/InlineChip.tsx index a728ed25e1..09d18b50b1 100644 --- a/src/shared/design-system/ui/InlineChip.tsx +++ b/src/shared/design-system/ui/InlineChip.tsx @@ -36,6 +36,7 @@ export function InlineChip({ qualifier, interactive = true, onActivate, + kindName, }: { address: ChipAddress; /** Scoped display data supplied by a host that already owns identity lookup. */ @@ -51,11 +52,13 @@ export function InlineChip({ interactive?: boolean; /** An explicit owner-provided action; previews never imply a deep-open. */ onActivate?: (address: ChipAddress) => void; + /** The kind it is announced as, when its address kind's name doesn't fit. */ + kindName?: string; }) { const face = useChipFace(address, suppliedFace); const Icon = KIND_ICON[address.kind]; const trigger = CHIP_KIND_TRIGGER[address.kind]; - const kind = accessibleKind(address.kind); + const kind = kindName ?? accessibleKind(address.kind); const content = ( <> diff --git a/tests/browser/completion-work.spec.mjs b/tests/browser/completion-work.spec.mjs index b9515d9181..de31a79694 100644 --- a/tests/browser/completion-work.spec.mjs +++ b/tests/browser/completion-work.spec.mjs @@ -315,14 +315,16 @@ test("completed, dismissed and refuted mention searches stay closed while fresh expect(await searches()).not.toContainEqual(expect.stringContaining("Zed ")); }); -for (const row of ["people", "supplement"]) { +for (const row of ["people", "supplement", "group"]) { test(`a ${row} row proves the owner's mention only from a person's pick`, async ({ page, }) => { await page.addInitScript(() => { localStorage.setItem("buzz-remember-mentioned-agents.v1", "off"); }); - await page.goto("/tests/fixtures/mentions.html?supplement"); + await page.goto( + `/tests/fixtures/mentions.html?supplement=${row === "group" ? "group" : ""}`, + ); const input = page.getByRole("textbox", { name: "Message #General" }); await expect .poll(() => page.evaluate(() => window.mentionFixture.list().status)) @@ -340,7 +342,7 @@ for (const row of ["people", "supplement"]) { if (trusted) await pick.click(); else await pick.dispatchEvent("click"); await expect(input.locator(".inline-chip")).toHaveCount( - row === "people" ? 1 : 2, + row === "supplement" ? 2 : 1, ); const count = await page.evaluate( () => window.mentionFixture.publications.length, diff --git a/tests/fixtures/mentions.tsx b/tests/fixtures/mentions.tsx index fdf0ab8793..fdeac731cb 100644 --- a/tests/fixtures/mentions.tsx +++ b/tests/fixtures/mentions.tsx @@ -376,6 +376,9 @@ const plugins = createPluginManager(context, { { pubkey: first.pubkey, name: "Honey" }, { pubkey: second.pubkey, name: "Honey" }, ], + ...(supplement === "group" + ? { label: "Crew" } + : {}), }, }, ],