From 3c3191c967dfa1494cdde6cdd64a3977060eb85b Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 12:10:47 -0500 Subject: [PATCH 1/5] feat(composer): let completion providers add rows beside the caret owner A provider registered with `supplement: true` mounts beside the provider that owns the caret when its own match has the same start, with its own query. It never owns the caret, so it never opens a popup alone. Each provider's rows form a section, in `order` then contribution key, with the winner among them. A supplement's section sits under a heading with its `title`, and so does the winner's when another section comes first. Rows are keyed by provider and id, so ids may repeat across providers; acceptance, retry, status and failure stay per provider. Terminator evidence still comes only from the winner. A supplement's `holdAutoSelect: true`, or a supplement that has not published yet, withholds the winner's `spaceId` and `spacePending`, so a typed terminator stays text. A supplement that throws drops only its section and releases its hold. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 19 + .../conversation/ComposerCompletions.test.tsx | 335 ++++++++++- .../conversation/ComposerCompletions.tsx | 528 +++++++++++------- src/features/conversation/completion.test.ts | 16 + src/features/conversation/completion.ts | 68 ++- src/features/conversation/contracts.ts | 10 + 6 files changed, 758 insertions(+), 218 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index e3a484d6a3..63f2147db6 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3137,6 +3137,25 @@ Before the first publication the menu is also hidden: syntax matching is not evi of loading. Providers must publish an explicit status for actual pending work. Escape still revokes unpublished work, without exposing ARIA controls for a missing listbox. +A provider registered with `supplement: true` never owns the caret. It mounts +beside the winner when its own match has the same start, with its own query, and +it never opens a menu alone. Each provider's rows form a section, and sections +follow `order`, then the contribution key, with the winner among them. A +supplement's section sits under a host-drawn heading with its `title`, and so +does the winner's when another section comes first and the winner draws no +heading of its own. The first row is selected by default, so Enter and Tab take a +supplement row ordered above the winner's; a terminator still accepts only the +winner's exact match. Each row keeps its provider: a row is identified by +provider and ID, and acceptance, `canSelect`, `disabled`, retry and status go to +the provider that published it. Each provider keeps its own 50-row cap. A +supplement decides no exact match. The host ignores its `spaceId`, `spacePending`, +`agent` and `group`. Its `holdAutoSelect: true` says that its whole source, not only its +shown rows, has or extends the typed name, or is still loading. Then a typed +terminator never accepts the winner's exact match and types as text. A supplement +that has not published yet for this query holds the same way, so supplements +publish on mount, even with no rows. One that fails drops only its own section +and holds nothing. + Providers receive immutable observation/range evidence and `publish(result)`—not DOM, focus or replacement commands. Results contain stable IDs, labels, optional detail/decorative previews, an optional `agent` flag (marked and announced only diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index bdb1192892..d3bb82fa6a 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -1,12 +1,19 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; -import { useEffect, useRef } from "react"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { useEffect, useRef, useState } from "react"; import { afterEach, expect, it, vi } from "vitest"; import { ComposerCompletions } from "./ComposerCompletions"; import type { CompletionEditor } from "./useCompletionEditor"; import type { CompletionResult, ComposerCompletion, + ComposerCompletionProps, IdentityMark, } from "./contracts"; import type { Contribution } from "../../plugins/contributions"; @@ -315,3 +322,327 @@ it("opens no query at a trigger inside a resolved chip", () => { expect(screen.queryByRole("listbox")).toBeNull(); expect(screen.queryByRole("option")).toBeNull(); }); + +const ENG_BOT = { pubkey: "e".repeat(64), name: "Eng Bot" }; +const BOB = { pubkey: "b".repeat(64), name: "Bob" }; +type Source = Readonly<{ + id: string; + order?: number; + supplement?: true; + title?: string; + /** Undefined publishes nothing; a function throws while rendering. */ + result?: CompletionResult | (() => never) | undefined; + /** Publishes `result` without keeping its withdrawal, then throws. */ + crashAfterPublish?: true; +}>; +function mountSources( + sources: readonly Source[], + replace = vi.fn((..._: unknown[]) => true), +) { + Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { + configurable: true, + value: () => {}, + }); + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + const publishes = new Map(); + const registered = sources.map((source) => { + const contribution = { + id: source.id, + key: `test.${source.id}/${source.id}`, + pluginId: source.id === "people" ? "buzz.mentions" : `test.${source.id}`, + revision: "1", + title: source.title ?? source.id, + ...(source.order !== undefined ? { order: source.order } : {}), + ...(source.supplement ? { supplement: true as const } : {}), + match: ({ text, start }) => + text.startsWith("@") ? { start: 0, end: start, query: "eng" } : null, + component: function Source({ publish }) { + const result = source.result; + if (typeof result === "function") result(); + publishes.set(source.id, publish); + const [crashed, setCrashed] = useState(false); + if (crashed) throw new Error("broken supplement"); + const published = useRef(publish); + useEffect(() => { + if (!result || typeof result === "function") return; + const withdraw = published.current(result); + if (!source.crashAfterPublish) return withdraw || undefined; + setCrashed(true); + }, []); + return null; + }, + } satisfies Contribution; + if (source.id === "people") bundledContribution(contribution); + return contribution; + }); + const input = document.createElement( + "div", + ) as unknown as ComposerInputElement; + document.body.append(input); + const editor = { + observation: { revision: 1, text: "@eng", start: 4, end: 4 }, + valid: () => true, + observe: () => {}, + invalidate: () => {}, + keys: { current: undefined }, + composing: { current: false }, + } as CompletionEditor; + render( + registered, subscribe: () => () => {} }} + editor={editor} + input={{ current: input }} + replace={replace} + resolved={{ text: "@eng", recipients: [] }} + session={{ profiles: {} } as unknown as RelaySession} + scope="test" + channelId="c" + />, + ); + const press = (key: string) => + editor.keys.current?.({ + key, + nativeEvent: { isComposing: false, keyCode: 0 }, + shiftKey: false, + altKey: false, + ctrlKey: false, + metaKey: false, + preventDefault: () => {}, + stopPropagation: () => {}, + } as unknown as Parameters< + NonNullable + >[0]) ?? false; + return { replace, press, publishes }; +} +const people = (result: Partial = {}): Source => ({ + id: "people", + title: "Mention", + order: -10, + result: { + items: [ + { + id: "x", + label: "Eng Bot", + edit: { mention: ENG_BOT }, + }, + ], + spaceId: "x", + ...result, + }, +}); +const groups = ( + result: CompletionResult | (() => never) | undefined, + order = -20, +): Source => ({ + id: "groups", + title: "Groups", + order, + supplement: true, + result, +}); +const groupRow = { + id: "x", + label: "eng", + edit: { mentions: [BOB] }, +} as const; + +// Headings and rows as the listbox lays them out. +const listed = () => + [...screen.getByRole("listbox").children].map((node) => node.textContent); +it("shows a supplement's rows under its title beside the winner, in provider order", async () => { + mountSources([people(), groups({ items: [groupRow] })]); + await screen.findByRole("option", { name: /^eng$/ }); + // The winner's rows never read as part of the section above them. + expect(listed()).toEqual(["Groups", "eng", "Mention", "Eng Bot"]); + cleanup(); + mountSources([people(), groups({ items: [groupRow] }, 10)]); + await screen.findByRole("option", { name: /^eng$/ }); + // First, the winner looks as it does alone. + expect(listed()).toEqual(["Eng Bot", "Groups", "eng"]); +}); +it("opens with a supplement's rows when the winner has none", async () => { + const { replace, press } = mountSources([ + people({ items: [], spaceId: undefined }), + groups({ items: [groupRow] }), + ]); + await screen.findByRole("option", { name: /^eng$/ }); + expect(listed()).toEqual(["Groups", "eng"]); + press("Enter"); + expect(replace).toHaveBeenCalledWith( + { mentions: [BOB] }, + expect.anything(), + expect.anything(), + "Enter", + ); +}); +it("never opens for a supplement alone", () => { + mountSources([groups({ items: [groupRow] })]); + expect(screen.queryByRole("listbox")).toBeNull(); +}); +it("accepts each row through its own provider when their ids collide", async () => { + const { replace, press } = mountSources([ + people(), + groups({ items: [groupRow] }, 10), + ]); + fireEvent.click(await screen.findByRole("option", { name: /^eng$/ })); + expect(replace).toHaveBeenLastCalledWith( + { mentions: [BOB] }, + { start: 0, end: 4, query: "eng" }, + expect.anything(), + "click", + ); + expect( + screen + .getAllByRole("option") + .map((row) => row.getAttribute("aria-selected")), + ).toEqual(["true", "false"]); + press("ArrowDown"); + await screen.findByRole("option", { name: /^eng$/, selected: true }); + press("Enter"); + expect(replace).toHaveBeenLastCalledWith( + { mentions: [BOB] }, + expect.anything(), + expect.anything(), + "Enter", + ); +}); +it("keeps Space from picking the winner's exact match while a supplement holds it", async () => { + const { replace, press } = mountSources([ + people(), + groups({ items: [groupRow], holdAutoSelect: true }), + ]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + expect(press(" ")).toBe(false); + expect(replace).not.toHaveBeenCalled(); +}); +it.each([ + ["publishes no rows", { items: [] }], + [ + "fails", + () => { + throw new Error("broken supplement"); + }, + ], +] as const)( + "leaves Space to the winner when a supplement %s", + async (_, result) => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const { replace, press } = mountSources([people(), groups(result)]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); + error.mockRestore(); + }, +); +it("drops a failed supplement's rows and refuses its later publications", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const { replace, press, publishes } = mountSources([ + people(), + { + ...groups({ items: [groupRow], holdAutoSelect: true }), + crashAfterPublish: true, + }, + ]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + expect(listed()).toEqual(["Eng Bot"]); + let late: ReturnType | undefined; + act(() => { + late = publishes.get("groups")?.({ items: [groupRow] }); + }); + expect(late).toBe(false); + expect(listed()).toEqual(["Eng Bot"]); + // Its hold went with it. + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); + error.mockRestore(); +}); +it("keeps the winner's rows when a supplement's preview throws", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + function Broken(): never { + throw new Error("broken preview"); + } + mountSources([ + people(), + groups({ items: [{ ...groupRow, preview: }] }), + ]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + expect(listed()).toEqual(["Eng Bot"]); + error.mockRestore(); +}); +it("lets Escape dismiss a supplement that has not answered beside an empty winner", () => { + const empty = people({ items: [], spaceId: undefined }); + expect(mountSources([empty, groups(undefined)]).press("Escape")).toBe(true); + cleanup(); + // A settled, empty popup leaves Escape to the composer. + expect(mountSources([empty, groups({ items: [] })]).press("Escape")).toBe( + false, + ); +}); +it("holds a pending exact match too while a supplement holds it", async () => { + const resolve = vi.fn(); + const pending = { + items: [], + spaceId: undefined, + spacePending: { name: "eng", resolve }, + }; + const held = mountSources([ + people(pending), + groups({ items: [groupRow], holdAutoSelect: true }), + ]); + await screen.findByRole("option", { name: /^eng$/ }); + expect(held.press(" ")).toBe(false); + expect(held.replace).not.toHaveBeenCalled(); + cleanup(); + const free = mountSources([people(pending), groups({ items: [groupRow] })]); + await screen.findByRole("option", { name: /^eng$/ }); + expect(free.press(" ")).toBe(true); + expect(free.replace).toHaveBeenCalledWith( + { pending: { name: "eng", resolve } }, + expect.anything(), + expect.anything(), + " ", + ); +}); +it("holds Space until a supplement has answered", async () => { + const { replace, press } = mountSources([people(), groups(undefined)]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + expect(press(" ")).toBe(false); + expect(replace).not.toHaveBeenCalled(); +}); +it("ignores a supplement's own exact match and agent mark, and retries it alone", async () => { + const retry = vi.fn(); + const peopleRetry = vi.fn(); + const { replace, press } = mountSources([ + people({ spaceId: undefined, retry: peopleRetry }), + groups({ + items: [{ ...groupRow, agent: true }], + spaceId: "x", + retry, + }), + ]); + expect(await screen.findByRole("option", { name: /^eng$/ })).not.toBeNull(); + expect(press(" ")).toBe(false); + expect(replace).not.toHaveBeenCalled(); + fireEvent.click( + screen.getByRole("option", { name: "Retry Groups suggestions" }), + ); + expect(retry).toHaveBeenCalledOnce(); + expect(peopleRetry).not.toHaveBeenCalled(); +}); diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index dcfc37fead..2bc826ffee 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -12,6 +12,7 @@ import { createPortal } from "react-dom"; import { RobotIcon } from "../../shared/design-system/icons/index"; import { useCompletionPosition } from "./useCompletionPosition"; import { + Fragment, useId, useCallback, useEffect, @@ -19,6 +20,7 @@ import { useRef, useState, useSyncExternalStore, + type ReactNode, type RefObject, } from "react"; import type { Contribution } from "../../plugins/contributions"; @@ -35,17 +37,18 @@ import type { import { ContributionBoundary, contributionKey } from "./ContributionBoundary"; import { IdentityMarks } from "./IdentityMarks"; import { + byOrder, completionResult, matchCompletion, + type CompletionMatch, type HostCompletionEdit, type HostCompletionResult, + type HostCompletionSuggestion, } from "./completion"; import type { CompletionEditor } from "./useCompletionEditor"; import styles from "./Completions.module.css"; import { Tooltip } from "../../shared/design-system/ui/Tooltip"; -const RETRY = Symbol("retry-completion"); - /** The editor retains focus, so keyboard selection must open its own hint. */ function EmojiCompletionName({ label, @@ -93,17 +96,25 @@ function EmojiCompletionName({ * owner whose provider has not published by the end of its mount effects * clears it. A query opened elsewhere, by another provider, or after the * popup closed starts empty: `ComposerCompletions` evicts the store in its - * closed render, so a carried result means only a continuing open query. */ + * closed render, so a carried result means only a continuing open query. + * Results are kept per provider: the winner and each supplement beside it. */ +type Shown = Readonly>; function createDisplay() { - let shown: { key: string; result: HostCompletionResult | undefined } = { + let shown: { key: string; results: Shown | undefined } = { key: "", - result: undefined, + results: undefined, }; const listeners = new Set<() => void>(); return { - read: (key: string) => (shown.key === key ? shown.result : undefined), - set(key: string, result: HostCompletionResult | undefined) { - shown = { key, result }; + read: (key: string) => (shown.key === key ? shown.results : undefined), + set(key: string, source?: number, result?: HostCompletionResult) { + const results: Record = + shown.key === key ? { ...shown.results } : {}; + if (source !== undefined) { + if (result) results[source] = result; + else delete results[source]; + } + shown = { key, results: key ? results : undefined }; for (const listener of listeners) listener(); }, subscribe(listener: () => void) { @@ -231,7 +242,7 @@ export function ComposerCompletions({ // that returned to text, starts empty as a first query does; its provider's // first publication fills it in the same task. useEffect(() => { - if (!open) display.set("", undefined); + if (!open) display.set(""); }, [open, display]); if (!open || !match || !observation) return null; return ( @@ -242,6 +253,11 @@ export function ComposerCompletions({ match.query.start, match.query.end, match.query.query, + match.supplements.map(({ provider, query }) => [ + contributionKey(provider), + query.end, + query.query, + ]), ])} fallback={ @@ -255,6 +271,7 @@ export function ComposerCompletions({ identityMarks={identityMarks} display={display} provider={match.provider} + supplements={match.supplements} query={match.query} observation={observation} editor={editor} @@ -265,8 +282,20 @@ export function ComposerCompletions({ ); } +type Source = CompletionMatch; +type Row = Readonly<{ + source: Source; + key: string; + item?: HostCompletionSuggestion; + heading?: string; +}>; +// A row's identity is its provider and its id: two providers may share ids. +const rowKey = (source: Source, id?: string) => + JSON.stringify([contributionKey(source.provider), id ?? null]); + function OwnedCompletion({ provider, + supplements: matched, registry, identityMarks, display, @@ -279,6 +308,7 @@ function OwnedCompletion({ ...context }: CompletionContext & { provider: Contribution; + supplements: readonly Source[]; registry: ContributionReader; identityMarks?: ContributionReader | undefined; display: ReturnType; @@ -315,15 +345,30 @@ function OwnedCompletion({ ); const list = useRef(null); const trigger = `${contributionKey(provider)}:${query.start}`; - const result = useSyncExternalStore( + // Fixed for this lifetime: a changed set of supplements remounts it. + const [{ winner, supplements, sources }] = useState(() => { + const winner: Source = { provider, query }; + return { + winner, + supplements: matched, + sources: [winner, ...matched].sort((a, b) => + byOrder(a.provider, b.provider), + ), + }; + }); + const results = useSyncExternalStore( display.subscribe, () => display.read(trigger), () => display.read(trigger), ); - // This lifetime's own publication; a carried display is never acted on. - const latest = useRef(undefined); - // Only user navigation pins an ID; automatic selection follows the first result. - const [selected, setSelected] = useState(); + const result = results?.[contributionKey(provider)]; + // This lifetime's own publications; a carried display is never acted on. + const latest = useRef(new Map()); + // A failed supplement is done for this lifetime: its section goes, it holds + // nothing back, and it can no longer publish or accept. + const failed = useRef(new Set()); + // Only user navigation pins a row; automatic selection follows the first result. + const [selected, setSelected] = useState(); const [keyboardSelection, setKeyboardSelection] = useState(); const pointerMoved = useCallback( (event: Pick) => { @@ -354,63 +399,132 @@ function OwnedCompletion({ current.current = { editor, replace }; }); const active = useCallback( - () => + (source: Source) => live.current && - registry.snapshot().includes(provider) && + !failed.current.has(source) && + registry.snapshot().includes(source.provider) && current.current.editor.valid(observation), - [provider, registry, observation], + [registry, observation], ); - const [publish, setPublish] = useState(); + const [publishers, setPublishers] = + useState>(); useLayoutEffect(() => { live.current = true; let owned = true; - setPublish(() => (incoming: CompletionResult) => { - if (!owned || !active()) return false; - const next = completionResult(incoming, provider); - latest.current = next; - revealSelection.current = true; - display.set(trigger, next); - setSelected((previous) => - next.items.some((item) => item.id === previous) - ? previous - : previous === RETRY && next.retry - ? RETRY - : undefined, - ); - return () => { - if (latest.current !== next) return; - latest.current = undefined; - if (live.current) display.set(trigger, undefined); - }; - }); + const published = latest.current; + setPublishers( + new Map( + sources.map((source) => [ + source, + (incoming: CompletionResult) => { + if (!owned || !active(source)) return false; + const next = completionResult(incoming, source.provider); + const slot = contributionKey(source.provider); + published.set(source, next); + revealSelection.current = true; + display.set(trigger, slot, next); + // A pinned row of this provider stays only while it still exists. + setSelected((previous) => { + if (!previous?.startsWith(`[${slot},`)) return previous; + const kept = + previous === rowKey(source) + ? !!next.retry + : next.items.some( + (item) => previous === rowKey(source, item.id), + ); + return kept ? previous : undefined; + }); + return () => { + if (published.get(source) !== next) return; + published.delete(source); + if (live.current) display.set(trigger, slot); + }; + }, + ]), + ), + ); return () => { owned = false; live.current = false; - latest.current = undefined; + published.clear(); }; - }, [active, display, provider, trigger]); - // A carried result stands only until this query's provider has run its + }, [active, display, sources, trigger]); + // A carried result stands only until this query's providers have run their // mount effects, which precede this one; a provider that has not published - // by then leaves the popup closed, as for a first query, so a stale display - // is never painted. + // by then shows nothing, as for a first query, so a stale display is never + // painted. A provider no longer beside this query keeps nothing either. useEffect(() => { - if (publish && !latest.current) display.set(trigger, undefined); - }, [publish, display, trigger]); - const items = result?.items ?? []; + if (!publishers) return; + const published = new Set( + [...latest.current.keys()].map(({ provider }) => + contributionKey(provider), + ), + ); + for (const slot of Object.keys(display.read(trigger) ?? {})) + if (!published.has(Number(slot))) display.set(trigger, Number(slot)); + }, [publishers, display, trigger]); + // The winner's exact match waits while a supplement has, or may have, a + // name the typed one is, or begins. + const held = () => + supplements.some((source) => { + const published = latest.current.get(source); + return ( + !failed.current.has(source) && + (!published || published.holdAutoSelect === true) + ); + }); + // The winner's failure closes the popup; a supplement's drops only its own + // section, whether its provider or one of its previews throws. + const isolate = (source: Source, node: ReactNode) => + source === winner ? ( + node + ) : ( + { + if (!failure) return; + failed.current.add(source); + display.set(trigger, contributionKey(source.provider)); + }} + > + {node} + + ); + const rows: Row[] = []; + for (const source of sources) { + const shown = results?.[contributionKey(source.provider)]; + const own: Row[] = [ + ...(shown?.items ?? []).map((item) => ({ + source, + key: rowKey(source, item.id), + item, + })), + ...(shown?.retry ? [{ source, key: rowKey(source) }] : []), + ]; + // A supplement's rows sit under its title; the winner's too when rows + // precede them and the provider draws no heading of its own. + const first = own[0]; + if (first && (source !== winner || (rows.length > 0 && !first.item?.group))) + own[0] = { ...first, heading: source.provider.title }; + rows.push(...own); + } + const statuses = sources.flatMap((source) => { + const status = results?.[contributionKey(source.provider)]?.status; + return status ? [{ source, status }] : []; + }); // Matching syntax is not evidence of pending work. Providers publish their // own status when needed; an empty/unpublished result must not flash a portal. - const visible = !!(items.length || result?.status || result?.retry); - const count = items.length + (result?.retry ? 1 : 0); - const index = - selected === RETRY && result?.retry - ? items.length - : items.findIndex((item) => item.id === selected); + const visible = !!(rows.length || statuses.length); + const count = rows.length; + const index = rows.findIndex((row) => row.key === selected); const selectedIndex = index < 0 ? 0 : index; - const status = result?.status; function accept(index: number, key = "click") { - const published = latest.current; - if (!active() || !published) return false; - if (index === items.length && result?.retry) { + const terminator = terminates(key); + const row = terminator ? undefined : rows[index]; + const source = row?.source ?? winner; + const published = latest.current.get(source); + if (!active(source) || !published) return false; + if (row && !row.item) { if (!published.retry) return false; published.retry(); return true; @@ -418,12 +532,12 @@ function OwnedCompletion({ // Publication is synchronous; React may still be displaying the previous // result. Keep the user's chosen ID, but use only its current evidence/edit. // The terminator names its own item, which that display may not have yet. - const id = terminates(key) ? published.spaceId : items[index]?.id; + const id = terminator ? published.spaceId : row?.item?.id; const item = published.items.find((item) => item.id === id); if (!item || item.disabled || item.canSelect?.(key) === false) return false; const accepted = current.current.replace( item.edit, - query, + source.query, observation, key, ); @@ -432,10 +546,12 @@ function OwnedCompletion({ } useLayoutEffect(() => { const element = input.current; - // Escape must still dismiss an unpublished provider without advertising a - // nonexistent listbox. A settled empty result leaves ordinary keys alone; - // an undecided one still owns the terminator, with nothing to show yet. - if (!element || (!visible && result && !result.spacePending)) return; + // Escape must still dismiss an unpublished provider, or a supplement that + // still holds, without advertising a nonexistent listbox. A settled empty + // result leaves ordinary keys alone; an undecided one still owns the + // terminator, with nothing to show yet. + if (!element || (!visible && result && !result.spacePending && !held())) + return; if (visible) { element.setAttribute("aria-autocomplete", "list"); element.setAttribute("aria-haspopup", "listbox"); @@ -466,7 +582,7 @@ function OwnedCompletion({ (event.key === " " || !terminates(event.key)) ) return false; - if (!active()) { + if (!active(winner)) { // A displayed choice owns plain acceptance even when its final evidence // was revoked. Never turn a rejected edit into an unintended send. if ((event.key === "Enter" || event.key === "Tab") && count) { @@ -481,10 +597,13 @@ function OwnedCompletion({ // yet, so both terminator branches read the publication. Space is not // redirected away from an exact match the display showed: a publication // that moves it to another id leaves Space literal. The displayed row - // is never accepted on its own; only the publication selects. - const published = latest.current; + // is never accepted on its own; only the publication selects. A + // supplement holding the terminator leaves it literal too. + const published = latest.current.get(winner); + const waiting = terminates(event.key) && held(); if ( terminates(event.key) && + !waiting && published?.spaceId && (!result?.spaceId || result.spaceId === published.spaceId) ) { @@ -503,6 +622,7 @@ function OwnedCompletion({ // decision is deferred to the resolver under the full rule. if ( terminates(event.key) && + !waiting && published?.spacePending && !published.spaceId && current.current.replace( @@ -523,8 +643,8 @@ function OwnedCompletion({ const next = (selectedIndex + (event.key === "ArrowDown" ? 1 : count - 1)) % count; revealSelection.current = true; - if (compact) setKeyboardSelection(items[next]?.id); - setSelected(next === items.length ? RETRY : items[next]?.id); + if (compact) setKeyboardSelection(rows[next]?.key); + setSelected(rows[next]?.key); return true; } if ((event.key === "Enter" || event.key === "Tab") && count) { @@ -550,17 +670,27 @@ function OwnedCompletion({ element.removeAttribute("aria-activedescendant"); }; }); - const Provider = provider.component; return ( <> - {publish && ( - - )} + {publishers && + sources.map((source) => { + const Provider = source.provider.component; + const publish = publishers.get(source); + if (!publish) return null; + return ( + + {isolate( + source, + , + )} + + ); + })} {visible && input.current && createPortal( @@ -579,131 +709,143 @@ function OwnedCompletion({ ref={list} className={styles.list} > - {items.flatMap((item, i) => [ - item.group && item.group !== items[i - 1]?.group && ( - // Read as the description of each row it heads. + {rows.flatMap((row, i) => { + const { item, source } = row; + const previous = rows[i - 1]; + const group = + item?.group && + (previous?.source !== source || + item.group !== previous.item?.group) && + item.group; + const heading = row.heading ?? group; + const lead = rows.findIndex((other) => other.source === source); + const describedBy = item?.group + ? `${id}-group-${rows.findIndex((other) => other.source === source && other.item?.group === item.group)}` + : rows[lead]?.heading + ? `${id}-group-${lead}` + : undefined; + const option = ( + // The textarea owns keyboard focus/selection via aria-activedescendant. + // biome-ignore lint/a11y/useKeyWithClickEvents: Keyboard acceptance belongs to the focused textarea. - ), - // The textarea owns keyboard focus/selection via aria-activedescendant. - // biome-ignore lint/a11y/useKeyWithClickEvents: Keyboard acceptance belongs to the focused textarea. -
row.group === item.group)}` - } - onPointerDown={(event) => { - if (event.button === 0) event.preventDefault(); - }} - onPointerMove={ - compact || named - ? (event) => { - // WebKit can report a pointermove when keyboard - // scrolling moves another row under a resting pointer. - if (compact && !pointerMoved(event)) return; - revealSelection.current = false; - setKeyboardSelection(undefined); - setSelected(item.id); - } - : undefined - } - onClick={() => accept(i)} - className={styles.option} - > - {item.preview && ( - - )} - - {compact ? ( - - ) : named ? ( - // Only the name ellipsizes; the agent mark stays visible. - - {item.label} - {mention && item.edit.mention && ( - + {!item ? ( + source === winner ? ( + "Retry suggestions" + ) : ( + `Retry ${source.provider.title} suggestions` + ) + ) : ( + <> + {item.preview && ( + )} - {item.agent && ( - - ) : ( - item.label + )} - {item.detail && ( - - {item.detail} - - )} - - {channel && i === selectedIndex && ( - - )} -
, - ])} - {result?.retry && ( - // biome-ignore lint/a11y/useKeyWithClickEvents: Keyboard acceptance belongs to the focused textarea. -
{ - if (event.button === 0) event.preventDefault(); - }} - onPointerMove={ - compact || named - ? (event) => { - if (compact && !pointerMoved(event)) return; - revealSelection.current = false; - setSelected(RETRY); - } - : undefined - } - onClick={() => accept(items.length)} - > - Retry suggestions -
- )} + + ); + return [ + heading && ( + // Read as the description of each row it heads. + + ), + option, + ]; + })} - {status &&

{status}

} + {statuses.map(({ source, status }) => ( +

+ {status} +

+ ))} , // A body sibling would sit behind a fullscreen modal and outside its // accessibility boundary. Ordinary composers keep the body portal. diff --git a/src/features/conversation/completion.test.ts b/src/features/conversation/completion.test.ts index 6e89baea69..25f6651245 100644 --- a/src/features/conversation/completion.test.ts +++ b/src/features/conversation/completion.test.ts @@ -51,6 +51,22 @@ it("validates and deterministically arbitrates optional provider ranges", () => matchCompletion([provider("a", 0, 3)], { ...observation, end: 4 }, context), ).toBeUndefined(); }); +it("keeps a supplement beside the winner only at the winner's start", () => { + const beside = (start: number, order = -20) => ({ + ...provider(`beside-${start}`, start, 3, order), + supplement: true as const, + }); + const match = matchCompletion( + [provider("people", 1, 3), beside(1), beside(0)], + observation, + context, + ); + expect(match?.provider.id).toBe("people"); + expect(match?.supplements.map(({ provider }) => provider.id)).toEqual([ + "beside-1", + ]); + expect(matchCompletion([beside(1)], observation, context)).toBeUndefined(); +}); it("snapshots valid edit primitives, rejects malformed/duplicate candidates and bounds output", () => { const recipient = { pubkey: "a".repeat(64), name: "Honey" }; const input = { diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 1d59ce7f6a..299ea116fa 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -33,45 +33,60 @@ export type HostCompletionSuggestion = Omit & export type HostCompletionResult = Omit & Readonly<{ items: readonly HostCompletionSuggestion[] }>; +export type CompletionMatch = Readonly<{ + provider: Contribution; + query: CompletionQuery; +}>; +const order = (value: ComposerCompletion) => + Number.isFinite(value.order) ? (value.order ?? 0) : 0; +/** Provider precedence: `order`, then contribution key. */ +export const byOrder = ( + a: Contribution, + b: Contribution, +) => order(a) - order(b) || a.key.localeCompare(b.key); export function matchCompletion( providers: readonly Contribution[], observation: ComposerObservation, context: CompletionContext, resolved: readonly Readonly<{ start: number; end: number }>[] = [], -) { - const order = (value: ComposerCompletion) => - Number.isFinite(value.order) ? (value.order ?? 0) : 0; - let winner: - | { provider: Contribution; query: CompletionQuery } - | undefined; - for (const provider of [...providers].sort( - (a, b) => order(a) - order(b) || a.key.localeCompare(b.key), - )) { +): (CompletionMatch & { supplements: readonly CompletionMatch[] }) | undefined { + let winner: CompletionMatch | undefined; + const supplements: CompletionMatch[] = []; + for (const provider of [...providers].sort(byOrder)) { try { const query = provider.match(observation, context); // A later trigger owns the caret over a broad earlier query (e.g. // @Mary Jane :smile). Order/key resolve providers claiming the same start. // A trigger inside a resolved chip is not an open query. if ( - validQuery(query, observation) && - !resolved.some( + !validQuery(query, observation) || + resolved.some( (span) => span.start <= query.start && query.start < span.end, - ) && - (!winner || query.start > winner.query.start) + ) ) - winner = { - provider, - query: Object.freeze({ - start: query.start, - end: query.end, - query: query.query, - }), - }; + continue; + const match = Object.freeze({ + provider, + query: Object.freeze({ + start: query.start, + end: query.end, + query: query.query, + }), + }); + if (provider.supplement === true) supplements.push(match); + else if (!winner || query.start > winner.query.start) winner = match; } catch { /* A broken optional matcher cannot break editing. */ } } - return winner; + return ( + winner && { + ...winner, + supplements: supplements.filter( + (match) => match.query.start === winner.query.start, + ), + } + ); } function validQuery( query: CompletionQuery | null, @@ -96,6 +111,9 @@ export function completionResult( ): HostCompletionResult { const ids = new Set(); const items: HostCompletionSuggestion[] = []; + // A supplement's rows sit under the host's heading for it and carry no + // agent mark; only its hold bears on the winner's exact match. + const supplement = provider?.supplement === true; for (const item of (Array.isArray(result?.items) ? result.items : []).slice( 0, 50, @@ -153,9 +171,10 @@ export function completionResult( label: item.label, ...(typeof item.detail === "string" ? { detail: item.detail } : {}), preview: item.preview, - ...(item.agent === true ? { agent: true } : {}), + ...(item.agent === true && !supplement ? { agent: true } : {}), ...(typeof item.group === "string" && item.group && + !supplement && provider && isBundledContribution(provider) ? { group: item.group } @@ -194,6 +213,9 @@ export function completionResult( ...(typeof result.spaceId === "string" && ids.has(result.spaceId) ? { spaceId: result.spaceId } : {}), + ...(supplement && result.holdAutoSelect === true + ? { holdAutoSelect: true } + : {}), ...(result.spacePending && typeof result.spacePending.name === "string" && result.spacePending.name && diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index e222ef091c..f8a18f0247 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -430,6 +430,10 @@ export type CompletionResult = Readonly<{ status?: string; /** Optional explicit recovery. A new query or disposal revokes this action. */ retry?: () => void; + /** Supplements only: something in the provider's whole source, not only its + * shown rows, has or extends the typed name, or that source is still + * loading. A terminator then never accepts the winner's exact match. */ + holdAutoSelect?: boolean; }>; export type ComposerCompletionProps = CompletionContext & Readonly<{ @@ -443,6 +447,12 @@ export type ComposerCompletion = Readonly<{ id: string; title: string; order?: number; + /** Adds rows beside the provider that owns the caret when this one's match + * has the same `start`; never owns it, so never opens alone. Its rows sit + * under a host-drawn `title`, sections in `order` then key. Publish on + * mount, even with no rows: until then the winner's exact match waits. Its + * `spaceId`, `spacePending`, `agent` and `group` are ignored. */ + supplement?: true; /** Pure syntax matcher. Host prefers the closest trigger; order/key break ties. */ match( observation: ComposerObservation, From 4ccb32df1208a5b30f8038c6b830f09202e5ccd9 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 16:33:56 -0500 Subject: [PATCH 2/5] test(completions): a supplement removed mid-menu; docs on default and hold A supplement whose plugin is removed while the menu is open loses its rows and its hold, and a publish from its old owner is refused. Nothing covered that before. The docs now say that a supplement publishing later with a lower order moves the default row until the user moves the selection, and that a hold has no time limit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 6 ++- .../conversation/ComposerCompletions.test.tsx | 43 +++++++++++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 63f2147db6..6e5ab26f56 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3145,7 +3145,9 @@ supplement's section sits under a host-drawn heading with its `title`, and so does the winner's when another section comes first and the winner draws no heading of its own. The first row is selected by default, so Enter and Tab take a supplement row ordered above the winner's; a terminator still accepts only the -winner's exact match. Each row keeps its provider: a row is identified by +winner's exact match. A supplement that publishes later with a lower `order` +moves the default row until the user moves the selection, which then stays on +its row while that row exists. Each row keeps its provider: a row is identified by provider and ID, and acceptance, `canSelect`, `disabled`, retry and status go to the provider that published it. Each provider keeps its own 50-row cap. A supplement decides no exact match. The host ignores its `spaceId`, `spacePending`, @@ -3154,7 +3156,7 @@ shown rows, has or extends the typed name, or is still loading. Then a typed terminator never accepts the winner's exact match and types as text. A supplement that has not published yet for this query holds the same way, so supplements publish on mount, even with no rows. One that fails drops only its own section -and holds nothing. +and holds nothing. A hold has no time limit. Providers receive immutable observation/range evidence and `publish(result)`—not DOM, focus or replacement commands. Results contain stable IDs, labels, optional diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index d3bb82fa6a..8e898d4a6c 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -352,7 +352,7 @@ function mountSources( }, ); const publishes = new Map(); - const registered = sources.map((source) => { + let registered = sources.map((source) => { const contribution = { id: source.id, key: `test.${source.id}/${source.id}`, @@ -394,9 +394,18 @@ function mountSources( keys: { current: undefined }, composing: { current: false }, } as CompletionEditor; + const listeners = new Set<() => void>(); render( registered, subscribe: () => () => {} }} + registry={{ + snapshot: () => registered, + subscribe: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }} editor={editor} input={{ current: input }} replace={replace} @@ -419,7 +428,12 @@ function mountSources( } as unknown as Parameters< NonNullable >[0]) ?? false; - return { replace, press, publishes }; + const unregister = (id: string) => + act(() => { + registered = registered.filter((contribution) => contribution.id !== id); + for (const listener of listeners) listener(); + }); + return { replace, press, publishes, unregister }; } const people = (result: Partial = {}): Source => ({ id: "people", @@ -573,6 +587,29 @@ it("drops a failed supplement's rows and refuses its later publications", async ); error.mockRestore(); }); +it("drops a supplement removed while the menu is open, with its hold", async () => { + const { replace, press, publishes, unregister } = mountSources([ + people(), + groups({ items: [groupRow], holdAutoSelect: true }), + ]); + await screen.findByRole("option", { name: /^eng$/ }); + const stale = publishes.get("groups"); + unregister("groups"); + expect(listed()).toEqual(["Eng Bot"]); + let late: ReturnType | undefined; + act(() => { + late = stale?.({ items: [groupRow] }); + }); + expect(late).toBe(false); + expect(listed()).toEqual(["Eng Bot"]); + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); +}); it("keeps the winner's rows when a supplement's preview throws", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); function Broken(): never { From 4f31f7798c600528c8ea335b262e673e56a676f2 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 16:53:54 -0500 Subject: [PATCH 3/5] test(completions): a late supplement with a lower order moves only an untouched default Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 8e898d4a6c..a71259d450 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -610,6 +610,31 @@ it("drops a supplement removed while the menu is open, with its hold", async () " ", ); }); +it.each([ + ["moves an untouched default to it", [], { mentions: [BOB] }], + ["keeps a row the user moved to", ["ArrowDown"], { mention: ENG_BOT }], +])( + "for a late supplement with a lower order, %s", + async (_, keys, accepted) => { + const { replace, press, publishes } = mountSources([ + people(), + groups(undefined), + ]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + for (const key of keys) press(key); + act(() => { + publishes.get("groups")?.({ items: [groupRow] }); + }); + expect(listed()).toEqual(["Groups", "eng", "Mention", "Eng Bot"]); + press("Enter"); + expect(replace).toHaveBeenCalledWith( + accepted, + expect.anything(), + expect.anything(), + "Enter", + ); + }, +); it("keeps the winner's rows when a supplement's preview throws", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); function Broken(): never { From 4e108350d87e655eb3712d3d1216abe2fb83f6e4 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 13:23:29 -0500 Subject: [PATCH 4/5] feat(composer): one chip for several recipients, sent as @label A `mentions` completion edit may carry a `label`. The composer inserts one `@label` chip over the query. It notifies each person in `mentions` once and is sent as the plain text `@label`, with one `p` tag per person. A blank or non-string label drops the row before it is shown. - In code, and in a message edit, only the text `@label` goes in, since edits add no recipients. - Removing or replacing recipients keeps the members still wanted; with none left the chip is plain text. A letter typed onto the label turns it into text, as for a person's chip, and marks such as a link keep it. - Saved drafts keep each member on the label's span, checked against the exact text `@label` and a mention boundary when restored. - The chip shows the recipient count beside the label and their names in its accessible name. - The 32-recipient cap counts distinct people, and a send names each person once. A chip's members count as namesakes, so a mention that shares a name with one of them is sent qualified. - A Solo chat's title drops a leading chip whole, as it drops a leading person tag. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 6 +- src/features/conversation/completion.test.ts | 16 +++ src/features/conversation/completion.ts | 7 +- src/features/conversation/contracts.ts | 10 ++ src/features/direct-messages/NewMessage.tsx | 2 +- src/features/messages/EditableInput.test.tsx | 118 +++++++++++++++- src/features/messages/EditableInput.tsx | 100 +++++++++++--- .../messages/MessageComposer.test.tsx | 129 +++++++++++++++++- src/features/messages/MessageComposer.tsx | 123 +++++++++++++---- src/features/messages/RichComposerInput.tsx | 53 ++++++- src/features/messages/composer-document.ts | 119 +++++++++++++++- src/features/messages/composer-dom.ts | 4 +- src/features/messages/composer-markdown.ts | 15 +- src/features/messages/mention-draft.test.ts | 42 ++++++ src/features/messages/mention-draft.ts | 57 ++++++-- src/features/solo/chat-title.test.ts | 14 ++ src/features/solo/chat-title.ts | 4 +- 17 files changed, 732 insertions(+), 87 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 6e5ab26f56..b48b7e575b 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3162,7 +3162,11 @@ Providers receive immutable observation/range evidence and `publish(result)`—n DOM, focus or replacement commands. Results contain stable IDs, labels, optional detail/decorative previews, an optional `agent` flag (marked and announced only for the bundled mention and channel providers) and either text, an exact `{ pubkey, name }` mention, -or a `mentions` array of up to 32 such recipients. Batch edit primitives are +or a `mentions` array of up to 32 such recipients. A `mentions` edit may add a +`label`: one `@label` chip that notifies each mention and is sent as the plain +text `@label`, with one `p` tag per mention. In code, and in a message edit, it +inserts only the text `@label`, since edits add no recipients. Removing every +recipient leaves the text. Batch edit primitives are copied and frozen before display, and accepted as a single editor transaction. The host copies edit/query primitives and caps publications at 50 choices. A publication returns its own withdrawal disposer (or `false` after revocation). diff --git a/src/features/conversation/completion.test.ts b/src/features/conversation/completion.test.ts index 25f6651245..a8b1eb91bd 100644 --- a/src/features/conversation/completion.test.ts +++ b/src/features/conversation/completion.test.ts @@ -188,6 +188,22 @@ it("copies and freezes batch recipients without allowing malformed or oversized ).toEqual([]); } }); +it("keeps a group's label and drops a blank or non-string one", () => { + 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]) + 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 299ea116fa..eb48448fa6 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -151,7 +151,9 @@ export function completionResult( !/^[0-9a-f]{64}$/.test(person.pubkey) || typeof person.name !== "string" || !person.name.trim(), - ) + ) || + (edit.label !== undefined && + (typeof edit.label !== "string" || !edit.label.trim())) ) continue; } else if ("mention" in edit) { @@ -200,6 +202,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 f8a18f0247..512b7714ba 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -392,6 +392,16 @@ export type CompletionEdit = }> | Readonly<{ mentions: readonly Readonly<{ pubkey: string; name: string }>[]; + label?: never; + text?: never; + mention?: never; + pending?: never; + }> + /** One chip `@label` that notifies each of `mentions`, sent as the text + * `@label`. In code, and in a message edit, only the text goes in. */ + | Readonly<{ + mentions: readonly Readonly<{ pubkey: string; name: string }>[]; + label: string; text?: never; mention?: never; pending?: never; diff --git a/src/features/direct-messages/NewMessage.tsx b/src/features/direct-messages/NewMessage.tsx index 80cd621cca..3a2826c9da 100644 --- a/src/features/direct-messages/NewMessage.tsx +++ b/src/features/direct-messages/NewMessage.tsx @@ -403,7 +403,7 @@ export function NewMessage({ const messageId = session.messages.send( id, content, - draft.recipients.map((person) => person.pubkey), + [...new Set(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 d3edac4b46..716c37fa50 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 () => { @@ -4989,3 +4989,115 @@ 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 = 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)); + // From the saved document, and from text and recipients alone. + 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); + // The same people again add no one, so the cap still holds. + 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 0f772f13a3..35491b11f1 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -47,6 +47,9 @@ import { composerResource, brokenResources, resourceBlockingMarks, + composerGroup, + tokenRecipients, + type ComposerGroup, } from "./composer-document"; import { scanMarkdown } from "../relay/message-content"; import type { @@ -94,6 +97,8 @@ import { pastedFiles, } from "./composer-clipboard"; import { + distinctRecipients, + MAX_RECIPIENTS, mentionBoundary, mentionDraft, type MentionDraft, @@ -708,12 +713,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(), @@ -726,7 +730,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, @@ -851,13 +855,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. @@ -899,7 +911,24 @@ 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) { + // One chip for every member; in code, the text alone. + 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]; @@ -934,8 +963,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) > + MAX_RECIPIENTS ) return false; if ( @@ -1096,11 +1126,29 @@ export function EditableInput({ return true; const added = recipients.filter((person) => !existing.has(person.pubkey)); const tr = closeHistory(editor.state.tr); - for (const person of [...source.draft.recipients].reverse()) { - if (requested.has(person.pubkey)) continue; - const end = - person.end + (source.draft.text[person.end] === " " ? 1 : 0); - tr.delete(source.position(person.start), source.position(end, -1)); + // A group's members share its chip: the chip keeps the members still + // requested, and is plain text without them. + const spans = new Map(); + for (const person of source.draft.recipients) + spans.set(person.start, [...(spans.get(person.start) ?? []), person]); + for (const [start, people] of [...spans].reverse()) { + const span = people[0]; + if (!span || people.every((person) => requested.has(person.pubkey))) + continue; + const token = source.tokens.find((item) => item.start === start); + const group = + token && + composerGroup(token.node.attrs.group, token.node.attrs.source); + if (token && group) { + const members = group.members.filter((m) => requested.has(m.pubkey)); + tr.setNodeMarkup(token.from, undefined, { + ...token.node.attrs, + group: members.length ? { label: group.label, members } : null, + }); + continue; + } + const end = span.end + (source.draft.text[span.end] === " " ? 1 : 0); + tr.delete(source.position(start), source.position(end, -1)); } if (added.length) { const at = Selection.atStart(tr.doc).from; @@ -1125,7 +1173,7 @@ export function EditableInput({ } const next = projectComposerDocument(tr.doc).draft; if ( - next.recipients.length > 32 || + distinctRecipients(next.recipients) > MAX_RECIPIENTS || composerMarkdown(next).length > current.current.maxLength ) return false; @@ -1681,7 +1729,7 @@ export function EditableInput({ if (!accept) return; const { tokens, draft } = projection(); const tr = editor.state.tr; - let count = draft.recipients.length; + const counted = new Set(draft.recipients.map((item) => item.pubkey)); // Later tokens first: earlier positions stay valid, and each boundary // check sees the text that now follows the token. for (const token of [...tokens].reverse()) { @@ -1695,7 +1743,7 @@ export function EditableInput({ const identity = identityLink(token.node.attrs.source); if ( !identity || - count >= 32 || + (!counted.has(identity.pubkey) && counted.size >= MAX_RECIPIENTS) || !mentionBoundary( projectComposerDocument(tr.doc).draft.text, token.end, @@ -1713,7 +1761,7 @@ export function EditableInput({ token.node.marks, ), ); - count++; + counted.add(recipient.pubkey); } if (tr.docChanged) editor.dispatch(tr); }; @@ -2581,6 +2629,18 @@ export function EditableInput({ ...node.attrs, recipient: null, }); + // A group drops the member; without members it is plain text. + const group = + node.type.name === "token" + ? composerGroup(node.attrs.group, node.attrs.source) + : null; + if (group?.members.some((m) => m.pubkey === pubkey)) { + const members = group.members.filter((m) => m.pubkey !== pubkey); + tr.setNodeMarkup(pos, undefined, { + ...node.attrs, + group: members.length ? { label: group.label, members } : null, + }); + } const mark = composerSchema.marks.recipient.isInSet(node.marks); if (mark?.attrs.pubkey === pubkey) tr.removeMark(pos, pos + node.nodeSize, mark); diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 38c1ab098c..c98f58af6d 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -7631,7 +7631,7 @@ it("qualifies both namesakes retroactively without changing source and removes q expect(h.messages.send).toHaveBeenCalledWith( "channel", "@Honey @Honey ", - [first.pubkey, first.pubkey], + [first.pubkey], [], ); }); @@ -8181,9 +8181,15 @@ it("rejects overlong and over-limit tool edits without changing accepted intent" expect(h.input()).toHaveValue("x".repeat(15999)); expect(screen.getByRole("alert")).toHaveTextContent("too long"); h.fill(""); + const people = Array.from({ length: 32 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: `P${i}`, + })); act(() => { - for (let i = 0; i < 32; i++) - expect(h.commands().insertMention(first)).toBe(true); + for (const person of people) + expect(h.commands().insertMention(person)).toBe(true); + // Someone already mentioned adds no recipient. + expect(h.commands().insertMention(people[7] ?? first)).toBe(true); }); const before = h.input().value; act(() => { @@ -8728,10 +8734,10 @@ it.each([undefined, "root"])( h.submit(); expect(h.input()).toHaveValue("@Honey @Honey @Honey hello"); h.submit(); + // Two chips for one person notify once. expect(send.mock.calls.at(-1)?.[threadRootId ? 3 : 2]).toEqual([ first.pubkey, second.pubkey, - second.pubkey, ]); expect(h.input()).toHaveValue("@Honey "); const recipients = screen.getByRole("region", { @@ -12606,6 +12612,106 @@ 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"); }); +/** The provider publishes one row whose edit is a labelled group. */ +function offerCrew( + h: ReturnType, + mentions: readonly MentionRecipient[], +) { + act(() => { + h.completionRequests.at(-1)?.({ + items: [ + { + id: "crew", + label: "Crew", + edit: { mentions, label: "Crew" }, + }, + ], + }); + }); +} +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( + // The namesakes' names say which key each one is. + screen.getByRole("img", { + name: "Person Crew, 2 recipients: Honey · rcaj, Honey · 04hu", + }), + ).toHaveTextContent("@Crew · 2"); + // A member also mentioned alone is still one recipient. + act(() => void h.commands().insertMention(first)); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + // The label, then the member named alone, qualified: a namesake is tagged. + 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 labelled mentions edit inside Markdown code is only its name", async () => { + const h = mount(); + h.fill("!`Crew`"); + offerCrew(h, [first, second]); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("@Crew "); + expect(h.commands().recipients).toEqual([]); +}); +it("a labelled mentions edit while editing a sent message adds only its text", async () => { + const h = mount({}, undefined, first.pubkey); + h.setRows([editableMessage()]); + fireEvent.keyDown(h.input(), { key: "ArrowUp" }); + h.fill("!Crew"); + offerCrew(h, [first, second]); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue("@Crew "); + expect(h.commands().recipients).toEqual([]); + h.submit(); + expect(h.messages.edit.mock.calls[0]?.[1]).toBe("@Crew "); + 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]); + // Once, though two spans name her: the relay takes at most 32 references. + expect(h.messages.send.mock.calls[0]?.at(-1)).toEqual([first.pubkey]); +}); it.each(["disabled", "retarget", "unmount"])( "revokes batch commands after %s", (transition) => { @@ -13710,6 +13816,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(() => { @@ -16669,7 +16785,10 @@ it.each([ act(() => { h.input().insertText( "", - Array.from({ length: 32 }, () => second), + Array.from({ length: 32 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: `P${i}`, + })), ); }), alert: diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index d7d0bbca7e..04bf091919 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -141,11 +141,13 @@ import styles from "./Messages.module.css"; import { messageViewKey } from "./view-key"; import { isEmojiOnly, usesLargeEmojiPresentation } from "./emoji-size"; import { + distinctRecipients, legacyFollowupDraft, MAX_DRAFT_GIFS, mentionBoundary, mentionDraft, stageableGif, + withoutSpans, type MentionDraft, type MentionRecipient, } from "./mention-draft"; @@ -1799,7 +1801,10 @@ function Composer({ ); return false; } - if (recipient && valueRef.current.recipients.length >= 32) { + if ( + recipient && + distinctRecipients([...valueRef.current.recipients, recipient]) > 32 + ) { setError("Choose at most 32 recipients"); return false; } @@ -1899,7 +1904,7 @@ function Composer({ ? "unresolved" : !admits()(recipient.pubkey) ? "unavailable" - : valueRef.current.recipients.length >= 32 + : distinctRecipients([...valueRef.current.recipients, recipient]) > 32 ? "limit" : undefined; const accepted = @@ -2074,9 +2079,12 @@ function Composer({ function keepProseCaret(add: (at: CompletionQuery) => boolean, focus = true) { const before = valueRef.current; let start = 0; - for (const tag of [...before.recipients].sort( - (a, b) => a.start - b.start, - )) { + // A group's members share one span: each chip counts once. + for (const tag of [ + ...new Map( + before.recipients.map((tag) => [`${tag.start}:${tag.end}`, tag]), + ).values(), + ].sort((a, b) => a.start - b.start)) { if (tag.start !== start || !/[ \t]/.test(before.text[tag.end] ?? "")) break; start = tag.end; @@ -2160,6 +2168,67 @@ function Composer({ setError(undefined); return true; } + /** Whether `range` overlaps Markdown code the draft spells with backticks, + * or a rich span Markdown can't reach: code, a link or literal text such as + * a removed link's label. */ + function inMarkdownCode(range: Readonly<{ start: number; end: number }>) { + const doc = readComposerSnapshot(valueRef.current.document); + const context = doc + ? composerMarkdownContext(doc) + : { text: valueRef.current.text, protected: [] }; + return [...context.protected, ...markdownRanges(context.text).literal].some( + (r) => range.start < r.end && range.end > r.start, + ); + } + /** One chip `@label` over `range` that notifies each of `mentions`, sent + * as the text `@label`. In code, and in a message edit, only the text goes + * in, since edits never add notification intent. */ + function insertGroup( + edit: Readonly<{ mentions: readonly MentionRecipient[]; label: string }>, + range: CompletionQuery, + ) { + if ( + !permitted.current || + editingDisabled || + !outbox?.supports(9) || + !input.current?.isConnected || + input.current.disabled || + input.current.readOnly + ) + return false; + const text = `@${edit.label} `; + if (editing.target || inMarkdownCode(range)) + return insert(text, undefined, range); + const members = [ + ...new Map( + edit.mentions.map(({ pubkey, name }) => [pubkey, { pubkey, name }]), + ).values(), + ]; + if (members.length > 32) { + setError("Choose at most 32 recipients"); + return false; + } + const admitted = admits(); + if (members.some((person) => !admitted(person.pubkey))) { + setError( + "A recipient is no longer available. Refresh choices before trying again.", + ); + return false; + } + if ( + !input.current.insertText(text, { label: edit.label, members }, range) + ) { + setError( + "The group would exceed the message length or 32-recipient limit. Nothing was added.", + ); + return false; + } + completion.invalidate(); + for (const person of members) + rememberMention(session, channelId, person.pubkey); + setError(undefined); + return true; + } function replaceRecipients(recipients: readonly MentionRecipient[]) { if ( !Array.isArray(recipients) || @@ -2193,13 +2262,10 @@ function Composer({ } function replaceRecipientsIfEmpty(recipients: readonly MentionRecipient[]) { const current = valueRef.current; - const prose = [...current.recipients] - .sort((a, b) => b.start - a.start) - .reduce( - (text, tag) => text.slice(0, tag.start) + text.slice(tag.end), - current.text, - ); - return !prose.trim() && replaceRecipients(recipients); + return ( + !withoutSpans(current.text, current.recipients).trim() && + replaceRecipients(recipients) + ); } function insertResource(resource: ComposerResource): true | string { if ( @@ -2226,18 +2292,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. @@ -2259,7 +2314,9 @@ function Composer({ return true; } if ("mentions" in edit && edit.mentions) - return insertMentions(edit.mentions, query); + return edit.label !== undefined + ? insertGroup(edit, query) + : insertMentions(edit.mentions, query); if ("mention" in edit && edit.mention) return insert(`@${edit.mention.name} `, edit.mention, query, typed); if ("token" in edit && edit.token) { @@ -2892,7 +2949,9 @@ function Composer({ return; } let references: readonly string[] = []; - let recipients = capturedRecipients.map((item) => item.pubkey); + let recipients = [ + ...new Set(capturedRecipients.map((item) => item.pubkey)), + ]; let declinedImports: readonly string[] = []; if (soloConversation || ownSoloConversation) { admission.current = true; @@ -2902,8 +2961,14 @@ function Composer({ fromPill, )); } else if (recipients.length) { + // A person in several chips, or also mentioned alone, is offered once. + const people = [ + ...new Map( + captured.recipients.map((person) => [person.pubkey, person]), + ).values(), + ]; // An agent only an earlier Buzz runs would not answer; offer it here first. - const lookup = oldAgents.find(captured.recipients); + const lookup = oldAgents.find(people); const old = lookup instanceof Promise ? await lookup : lookup; if (old.length) { setSending(true); @@ -2938,7 +3003,7 @@ function Composer({ const elsewhere = new Map( (agents?.joinable() ?? []).map((agent) => [agent.pubkey, agent]), ); - const bring = captured.recipients.flatMap((person) => { + const bring = people.flatMap((person) => { const agent = elsewhere.get(person.pubkey); return agent && !channel.members?.includes(person.pubkey) ? [agent] @@ -2955,7 +3020,7 @@ function Composer({ if (brought === null) return; added = brought; } - const missing = captured.recipients.filter( + const missing = people.filter( (person) => !channel.members?.includes(person.pubkey) && !added.includes(person.pubkey), diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index 03c9093468..e2cb1de626 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -106,6 +106,30 @@ const TokenChip = memo(function TokenChip({ ); }); +/** One chip `@label` for several people, with the people it notifies + * counted beside it and named in its accessible name. */ +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, @@ -315,8 +339,21 @@ export function RichComposerInput({ ...(mention ? { mention } : {}), }); }; - for (const recipient of draft.recipients) + // A group's members share its span; the first claims it for the chip. + const groups = new Map(); + for (const recipient of draft.recipients) { + if (recipient.label !== undefined) { + const name = labels.get(recipient.pubkey) ?? recipient.name; + const group = groups.get(recipient.start); + if (group) group.names.push(name); + else + groups.set(recipient.start, { + label: recipient.label, + names: [name], + }); + } add(recipient.start, recipient.end, recipient.pubkey); + } // Identity links are display references, not new notification recipients. // Keep their exact source token so editing surrounding prose preserves it. const profileLinks = new Map(); @@ -380,6 +417,20 @@ export function RichComposerInput({ const preview = gifPreviews.get(start); if (preview && preview.end === end && !mention) return { start, end, editAsText: false, content: preview.content }; + const group = mention ? groups.get(start) : undefined; + if (group && draft.text.slice(start, end) === `@${group.label}`) + return { + start, + end, + editAsText: false, + content: ( + + ), + }; const profile = mention ? undefined : profileLinks.get(start); const identity = mention ?? profile?.pubkey; const label = profile?.label ?? draft.text.slice(start + 1, end); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 0ffc25ef93..53c5c84c8f 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -9,6 +9,7 @@ import { composerLinkUrl } from "./composer-link"; import { scanMarkdown } from "../relay/message-content"; import type { MentionDraft, + MentionRecipient, DraftRecipient, PendingMention, } from "./mention-draft"; @@ -102,6 +103,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. */ @@ -212,6 +216,93 @@ 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, +): ComposerGroup | null { + if (!value || typeof value !== "object") return null; + const { label, members } = value as Record; + if ( + typeof label !== "string" || + !label.trim() || + source !== `@${label}` || + !Array.isArray(members) || + !members.length || + members.length > 32 + ) + return null; + const keys = new Set(); + for (const member of members) { + if ( + !member || + typeof member.pubkey !== "string" || + !/^[0-9a-f]{64}$/.test(member.pubkey) || + typeof member.name !== "string" || + !member.name.trim() || + keys.has(member.pubkey) + ) + return null; + keys.add(member.pubkey); + } + return value as ComposerGroup; +} +/** The members of a group chip that the draft still mentions on its range. */ +export function groupMembers( + group: ComposerGroup, + recipients: readonly DraftRecipient[], + start: number, + end: number, +): MentionRecipient[] { + return group.members.flatMap((member) => + recipients.some( + (item) => + item.pubkey === member.pubkey && + item.name === member.name && + item.label === group.label && + item.start === start && + item.end === end, + ) + ? [{ pubkey: member.pubkey, name: member.name }] + : [], + ); +} +/** A source token's recipient attributes from the draft's recipients on its + * range: every labelled one as a group, else the one recipient. */ +export function tokenRecipients( + recipients: readonly DraftRecipient[], + source: string, + range: { start: number; end: number }, +): { recipient: MentionRecipient | null; group: ComposerGroup | null } { + const on = recipients.filter( + (item) => item.start === range.start && item.end === range.end, + ); + const label = on.find((item) => item.label !== undefined)?.label; + if (label !== undefined) { + const members = on + .filter((item) => item.label === label) + .map(({ pubkey, name }) => ({ pubkey, name })); + const group = composerGroup( + { + label, + members: [...new Map(members.map((m) => [m.pubkey, m])).values()], + }, + source, + ); + return { recipient: null, group }; + } + const one = on[0]; + return { + recipient: one ? { pubkey: one.pubkey, name: one.name } : null, + group: null, + }; +} /** Draft text stays the editing/completion coordinate space. Formatting metadata * is local authoring state; message publication serializes it separately. */ export function readComposerDocument( @@ -246,6 +337,10 @@ export function readComposerDocument( return composerSchema.text(node.attrs.source, marks); const resource = composerResource(node.attrs.resource); const semantic = composerToken(node.attrs.semantic); + const group = composerGroup(node.attrs.group, node.attrs.source); + const members = group + ? groupMembers(group, draft.recipients, start, end) + : []; return node.type.create( { ...node.attrs, @@ -254,9 +349,11 @@ export function readComposerDocument( ? semantic : null, recipient: - node.attrs.recipient && valid(node.attrs.recipient) + !group && node.attrs.recipient && valid(node.attrs.recipient) ? node.attrs.recipient : null, + group: + group && members.length ? { label: group.label, members } : null, resource: resource && resource.source === node.attrs.source && @@ -287,14 +384,12 @@ export function readComposerDocument( while (offset < draft.text.length) { const token = tokens.find((token) => token.start === offset); if (token) { + const source = draft.text.slice(token.start, token.end); nodes.push( composerSchema.nodes.token.create({ - source: draft.text.slice(token.start, token.end), + source, editAsText: !!token.editAsText, - recipient: - draft.recipients.find( - (item) => item.start === token.start && item.end === token.end, - ) ?? null, + ...tokenRecipients(draft.recipients, source, token), }), ); offset = token.end; @@ -483,7 +578,17 @@ function project(doc: EditorNode) { node, editAsText: node.attrs.editAsText, }); - if (node.attrs.recipient) + const group = composerGroup(node.attrs.group, node.attrs.source); + if (group) + for (const { pubkey, name } of group.members) + recipients.push({ + pubkey, + name, + label: group.label, + start, + end: text.length, + }); + else if (node.attrs.recipient) recipients.push({ ...node.attrs.recipient, start, end: text.length }); if (node.attrs.pending) pending.push({ ...node.attrs.pending, start, end: text.length }); diff --git a/src/features/messages/composer-dom.ts b/src/features/messages/composer-dom.ts index 0ff2e9b90d..87ec2461dd 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"; @@ -104,7 +105,8 @@ export type ComposerInputElement = HTMLDivElement & { setSelectionRange(start: number, end: number, direction?: string): void; insertText( text: string, - recipient?: MentionRecipient | readonly MentionRecipient[], + /** People to mention; a group is one chip `@label` for all its members. */ + recipient?: MentionRecipient | readonly MentionRecipient[] | ComposerGroup, range?: { start: number; end: number }, /** The key typed to end the query. A closing colon is recorded before * conversion for one-step undo; after recipients, it takes the place of diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index 9e7d9528da..e7c16165c7 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -85,14 +85,17 @@ function qualifyNamesakes(doc: EditorNode): EditorNode { composerSchema.marks.recipient.isInSet(node?.marks ?? [])?.attrs; const keys = new Map>(); doc.descendants((node) => { - const found = person(node); + // A chip for several people tags each of them, so they are namesakes too. + 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; diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 645ddb4e27..660d1cbcfc 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -252,3 +252,45 @@ 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 }, + ]); + // Another label, or a word that only starts with it, is prose. + expect(crew("team").recipients).toEqual([]); + expect(crew("crew", "@crews hi").recipients).toEqual([]); + // The group's span is removed once, so prose after it still counts. + expect(addressingOnly(crew("crew", "@crew "))).toBe(true); + expect(addressingOnly(crew("crew"))).toBe(false); +}); +it("the recipient cap counts distinct people, keeping each one's spans", () => { + const people = Array.from({ length: 33 }, (_, i) => ({ + pubkey: i.toString(16).padStart(64, "0"), + name: "x", + })); + const 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); +}); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 34260933ee..a72aee5abb 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -5,8 +5,43 @@ import { } from "./composer-document"; export type MentionRecipient = Readonly<{ pubkey: string; name: string }>; +/** One recipient on a span. A group chip projects one per member, each with + * the group's `label`: then the span is `@label`, not `@name`. */ export type DraftRecipient = MentionRecipient & - Readonly<{ start: number; end: number }>; + Readonly<{ start: number; end: number; label?: string }>; +/** A message notifies at most this many distinct people. */ +export const MAX_RECIPIENTS = 32; +/** The distinct people `recipients` mention; a group shares a span with its + * members, and two chips can name the same person. */ +export function distinctRecipients( + recipients: readonly MentionRecipient[], +): number { + return new Set(recipients.map((item) => item.pubkey)).size; +} +/** `recipients` up to the first `MAX_RECIPIENTS` distinct people, keeping + * every span of each one it keeps. */ +function capRecipients(recipients: readonly T[]) { + const kept = new Set(); + return recipients.filter((item) => { + if (!kept.has(item.pubkey) && kept.size >= MAX_RECIPIENTS) return false; + kept.add(item.pubkey); + return true; + }); +} +/** `text` without the spans `recipients` cover; a group's span counts once. */ +export function withoutSpans( + text: string, + recipients: readonly Readonly<{ start: number; end: number }>[], +) { + const spans = [ + ...new Map( + recipients.map((item) => [`${item.start}:${item.end}`, item]), + ).values(), + ].sort((a, b) => b.start - a.start); + for (const { start, end } of spans) + text = text.slice(0, start) + text.slice(end); + return text; +} // Serializable draft metadata must not expose editor implementation types to plugins. export type ComposerSnapshot = { version: 1; content: unknown }; /** A name Space committed before the chooser could decide. The editor resolves @@ -71,11 +106,13 @@ export function mentionDraft(value: unknown): MentionDraft { /^[0-9a-f]{64}$/.test(item.pubkey) && typeof item.name === "string" && !!item.name.trim() && + (item.label === undefined || + (typeof item.label === "string" && !!item.label.trim())) && Number.isInteger(item.start) && Number.isInteger(item.end) && item.start >= 0 && item.end <= text.length && - text.slice(item.start, item.end) === `@${item.name}` && + text.slice(item.start, item.end) === `@${item.label ?? item.name}` && mentionBoundary(text, item.end), ) : []; @@ -102,9 +139,12 @@ export function mentionDraft(value: unknown): MentionDraft { } : {}), ...(doc ? { document: document as ComposerSnapshot } : {}), - recipients: safe - .slice(0, 32) - .map(({ pubkey, name, start, end }) => ({ pubkey, name, start, end })), + recipients: capRecipients(safe).map( + ({ pubkey, name, label, start, end }) => + label === undefined + ? { pubkey, name, start, end } + : { pubkey, name, label, start, end }, + ), }; } /** What counts as a draft everywhere: text, an attached chat or GIF, or `files`. @@ -129,12 +169,7 @@ export function legacyFollowupDraft(value: MentionDraft): boolean { export function addressingOnly(value: MentionDraft): boolean { if (!value.recipients.length || value.chatCards?.length || value.gifs?.length) return false; - let rest = value.text; - for (const { start, end } of [...value.recipients].sort( - (a, b) => b.start - a.start, - )) - rest = rest.slice(0, start) + rest.slice(end); - return !rest.trim(); + return !withoutSpans(value.text, value.recipients).trim(); } /** Prefill exact, already-selected identities; never infer recipients from prose. */ export function followupDraft( diff --git a/src/features/solo/chat-title.test.ts b/src/features/solo/chat-title.test.ts index a8009285c8..3e8b1af09c 100644 --- a/src/features/solo/chat-title.test.ts +++ b/src/features/solo/chat-title.test.ts @@ -74,3 +74,17 @@ it("drops leading namesake tags with their full-key qualifiers", () => { ); expect(startingChatTitle(draft)).toBe("fix the build"); }); + +it("drops a leading group tag whole, even when it starts with a member's name", () => { + const label = "Ann's team"; + const ann = { pubkey: "a".repeat(64), name: "Ann", label, start: 0, end: 11 }; + const bo = { pubkey: "b".repeat(64), name: "Bo", label, start: 0, end: 11 }; + const scout = { pubkey: "c".repeat(64), name: "Scout", start: 12, end: 18 }; + const draft = typedDraft( + mentionDraft({ + text: "@Ann's team @Scout do X", + recipients: [ann, bo, scout], + }), + ); + expect(startingChatTitle(draft)).toBe("do X"); +}); diff --git a/src/features/solo/chat-title.ts b/src/features/solo/chat-title.ts index 1ecb010d09..abb59e3178 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,13 +35,15 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { + // A group's members share its `@label` span, which counts once. + if (recipient.start < draftStart && recipient.end === draftStart) continue; if ( recipient.start < draftStart || draft.text.slice(draftStart, recipient.start).trim() ) break; const leading = text.slice(start).match(/^\s*/)?.[0].length ?? 0; - const tag = `@${recipient.name}`; + const tag = `@${recipient.label ?? recipient.name}`; if (!text.startsWith(tag, start + leading)) break; start += leading + tag.length; // A namesake is sent with its full key; that qualifier is part of the tag. From fe32d1096bef1a7d418ffc2f25840943a75b6bd6 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 23:51:08 -0500 Subject: [PATCH 5/5] fix(composer): protect a group chip's label like a recipient's name In a paragraph with formatting, a group chip's @label was not masked as a recipient span: italic wrapped it in _..._ and a * in the label was backslash-escaped on send. Treat a group chip like a recipient chip when serializing, and exclude it from semantic tokens when reading a snapshot. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/composer-document.test.ts | 26 +++++++++++++++++++ src/features/messages/composer-document.ts | 1 + src/features/messages/composer-markdown.ts | 5 +++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 31802c3c72..68825f3170 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -724,6 +724,32 @@ describe("inline formatting batch", () => { ), ).toBe("_@Honey_"); }); + it("sends a group chip like a recipient chip: exact label beside formatting, italic with asterisks", () => { + const members = [ + { pubkey: "a".repeat(64), name: "Honey" }, + { pubkey: "b".repeat(64), name: "Pollen" }, + ]; + const chip = (label: string, ...marks: InlineFormat[]) => + schema.nodes.token.create( + { source: `@${label}`, group: { label, members } }, + null, + marks.map((name) => schema.marks[name].create()), + ); + expect(serialize(chip("eng_ios", "italic"), schema.text(" "))).toBe( + "*@eng\\_ios* ", + ); + // The label is sent as typed, so a reader of the raw text can match it. + expect( + serialize(chip("eng*ops"), schema.text(" hi "), marked("b", "bold")), + ).toBe("@eng*ops hi **b**"); + expect( + serialize( + chip("eng*"), + schema.text("b", [schema.marks.italic.create()]), + schema.text("*"), + ), + ).toBe("@eng**b*\\*"); + }); it("escapes literal punctuation in each generated format", () => { for (const mark of ["bold", "italic", "strike"] as const) for (const character of ["*", "_", "~", "!"]) { diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 53c5c84c8f..be4210e1e6 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -721,6 +721,7 @@ function read(value: unknown): EditorNode | undefined { !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-markdown.ts b/src/features/messages/composer-markdown.ts index e7c16165c7..e13f61fe36 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -254,7 +254,7 @@ function authoredLiteralRanges(doc: EditorNode) { ? "\n" : node.attrs.source; context.source += - node.marks.length || node.attrs.recipient + node.marks.length || node.attrs.recipient || node.attrs.group ? value.replace(/\S/g, "a") : value; }); @@ -320,8 +320,11 @@ function paragraphMarkdown( : node.attrs.source; if (composerSchema.marks.literal.isInSet(node.marks)) literals.push({ start, end: text.length }); + // A group chip's @label is protected like a recipient's exact name, so + // its characters are never escaped or paired as emphasis. if ( node.attrs.recipient || + node.attrs.group || composerSchema.marks.recipient.isInSet(node.marks) ) recipients.push({ start, end: text.length });