From 3c3191c967dfa1494cdde6cdd64a3977060eb85b Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 12:10:47 -0500 Subject: [PATCH 01/35] 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 02/35] 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 03/35] 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 04/35] 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 05/35] 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 }); From 60e2cb46ae2dd3ae0325edcc5d90d537efc59ed0 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 08:34:15 -0500 Subject: [PATCH 06/35] fix(composer): escape group chip labels and keep them to one line A group chip's label came from a plugin and was sent unescaped, so a label such as `x](https://example.com)[y`, `*ops*`, a backtick or a blank line plus a heading changed how the sent message rendered. The sent label now escapes the characters that can open inline Markdown, so it renders as the label the chip shows; inside code it stays as is. Group labels also follow the rule token chips already had: at most 256 characters, with no control or bidirectional override characters. A completion row with another label is dropped, and a restored chip with one is prose. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/conversation/completion.test.ts | 12 +++- src/features/conversation/completion.ts | 9 ++- .../messages/composer-document.test.ts | 56 ++++++++++++++----- src/features/messages/composer-document.ts | 4 +- src/features/messages/composer-markdown.ts | 24 ++++++-- src/features/messages/composer-token.ts | 13 +++-- 6 files changed, 89 insertions(+), 29 deletions(-) diff --git a/src/features/conversation/completion.test.ts b/src/features/conversation/completion.test.ts index a8b1eb91bd..26e2a67f39 100644 --- a/src/features/conversation/completion.test.ts +++ b/src/features/conversation/completion.test.ts @@ -188,7 +188,7 @@ 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", () => { +it("keeps a group's label and drops one that is blank, not a string or not one plain line", () => { const mentions = [{ pubkey: "a".repeat(64), name: "Carl" }]; const edit = (extra: object) => completionResult({ @@ -201,7 +201,15 @@ it("keeps a group's label and drops a blank or non-string one", () => { ], }).items[0]?.edit; expect(edit({ label: "crew" })).toEqual({ mentions, label: "crew" }); - for (const label of ["", " ", 7, null]) + for (const label of [ + "", + " ", + 7, + null, + "crew\n\n# Title", + "\u202ecrew", + "x".repeat(257), + ]) expect(edit({ label })).toBeUndefined(); }); it("keeps a host workspace edit and drops a provider's look-alike", () => { diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index eb48448fa6..15b55f1c82 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -1,5 +1,9 @@ import type { MentionRecipient } from "../messages/mention-draft"; -import { composerToken, type ComposerToken } from "../messages/composer-token"; +import { + chipLabel, + composerToken, + type ComposerToken, +} from "../messages/composer-token"; import type { Contribution } from "../../plugins/contributions"; import { isBundledContribution } from "../../plugins/provenance"; import type { @@ -152,8 +156,7 @@ export function completionResult( typeof person.name !== "string" || !person.name.trim(), ) || - (edit.label !== undefined && - (typeof edit.label !== "string" || !edit.label.trim())) + (edit.label !== undefined && !chipLabel(edit.label)) ) continue; } else if ("mention" in edit) { diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 68825f3170..f92ae8ee0f 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { + composerGroup, composerSchema as schema, projectComposerDocument, readComposerDocument, @@ -724,7 +725,7 @@ describe("inline formatting batch", () => { ), ).toBe("_@Honey_"); }); - it("sends a group chip like a recipient chip: exact label beside formatting, italic with asterisks", () => { + it("escapes a group chip's label like prose, so it never changes the Markdown", () => { const members = [ { pubkey: "a".repeat(64), name: "Honey" }, { pubkey: "b".repeat(64), name: "Pollen" }, @@ -735,20 +736,49 @@ describe("inline formatting batch", () => { null, marks.map((name) => schema.marks[name].create()), ); - expect(serialize(chip("eng_ios", "italic"), schema.text(" "))).toBe( - "*@eng\\_ios* ", + // What a reader's Markdown renders: the node kinds and the text. + const rendered = (markdown: string) => { + const kinds = new Set(); + let text = ""; + const visit = (node: Nodes) => { + kinds.add(node.type); + if (node.type === "text") text += node.value; + if ("children" in node) node.children.forEach(visit); + }; + visit(fromMarkdown(markdown)); + return { kinds: [...kinds], text }; + }; + expect(serialize(chip("Design Team"), schema.text(" hi"))).toBe( + "@Design Team hi", ); - // 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**"); + for (const label of [ + "eng_ios", + "eng*ops", + "*ops*", + "a`b", + "x](https://evil.example)[y", + "[x](https://evil.example)", + ]) + expect(rendered(serialize(chip(label), schema.text(" hi")))).toEqual({ + kinds: ["root", "paragraph", "text"], + text: `@${label} hi`, + }); expect( - serialize( - chip("eng*"), - schema.text("b", [schema.marks.italic.create()]), - schema.text("*"), - ), - ).toBe("@eng**b*\\*"); + rendered(serialize(chip("eng_ios", "italic"), schema.text(" hi"))), + ).toEqual({ + kinds: ["root", "paragraph", "emphasis", "text"], + text: "@eng_ios hi", + }); + // Code shows its text as is. + expect(serialize(chip("eng_ios", "code"))).toBe("`@eng_ios`"); + }); + it("trusts a group chip only with a one-line label", () => { + const members = [{ pubkey: "a".repeat(64), name: "Honey" }]; + const group = (label: string) => + composerGroup({ label, members }, `@${label}`); + expect(group("crew")).not.toBeNull(); + for (const label of ["crew\n\n# Title", "\u202ecrew", "x".repeat(257)]) + expect(group(label)).toBeNull(); }); it("escapes literal punctuation in each generated format", () => { for (const mark of ["bold", "italic", "strike"] as const) diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index be4210e1e6..188972781e 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -15,6 +15,7 @@ import type { } from "./mention-draft"; import type { ComposerResource } from "../conversation/contracts"; import { + chipLabel, composerToken, composerTokenText, type ComposerToken, @@ -230,8 +231,7 @@ export function composerGroup( if (!value || typeof value !== "object") return null; const { label, members } = value as Record; if ( - typeof label !== "string" || - !label.trim() || + !chipLabel(label) || source !== `@${label}` || !Array.isArray(members) || !members.length || diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index e13f61fe36..ffa32bc0a9 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -54,12 +54,25 @@ export function composerMarkdown( draft: MentionDraft, { authored = false }: { authored?: boolean } = {}, ): string { + // A group's label comes from a plugin, so its Markdown characters are sent + // escaped: it renders as the label the chip shows. In code it stays as is. const project = (node: EditorNode): EditorNode => node.type.name === "token" && node.attrs.semantic ? node.mark(composerSchema.marks.literal.create().addToSet(node.marks)) - : node.isLeaf - ? node - : node.copy(Fragment.fromArray(node.content.content.map(project))); + : node.type.name === "token" && + node.attrs.group && + !composerSchema.marks.code.isInSet(node.marks) + ? node.type.create( + { + ...node.attrs, + source: `@${node.attrs.group.label.replace(/[\\`*_[\]<~]/g, "\\$&")}`, + }, + null, + node.marks, + ) + : node.isLeaf + ? node + : node.copy(Fragment.fromArray(node.content.content.map(project))); const doc = project(readComposerDocument(draft, [])); const wire = (body: EditorNode) => [...(draft.chatCards ?? []), blocksMarkdown(body), ...(draft.gifs ?? [])] @@ -320,8 +333,9 @@ 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. + // A group chip's @label arrives escaped (see composerMarkdown) and is + // protected like a recipient's exact name, so it is never escaped again or + // paired as emphasis. if ( node.attrs.recipient || node.attrs.group || diff --git a/src/features/messages/composer-token.ts b/src/features/messages/composer-token.ts index 2e369c9e17..baa4842da7 100644 --- a/src/features/messages/composer-token.ts +++ b/src/features/messages/composer-token.ts @@ -10,6 +10,14 @@ export type ComposerToken = Readonly< ) & { readonly [key: string]: JsonValue | undefined } >; +/** A chip's label: one line, at most 256 characters, with no control or + * bidirectional override characters. */ +export const chipLabel = (label: unknown): label is string => + typeof label === "string" && + !!label.trim() && + label.length <= 256 && + !/[\p{Cc}\u202a-\u202e\u2066-\u2069]/u.test(label); + /** Copy only bounded JSON. A provider cannot retain mutable editor metadata or * turn a token into a recipient through a label, prototype or callback. */ export function composerToken(value: unknown): ComposerToken | undefined { @@ -25,10 +33,7 @@ export function composerToken(value: unknown): ComposerToken | undefined { !token.id || token.id.length > 4096 || /\p{Cc}/u.test(token.id) || - typeof token.label !== "string" || - !token.label.trim() || - token.label.length > 256 || - /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u.test(token.label) + !chipLabel(token.label) ) return; if (token.kind === "skill") { From 702e5a6622dfce4962cb936831099abfe9d69f40 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 08:34:16 -0500 Subject: [PATCH 07/35] fix(composer): announce a group chip as a group; keep its label in Solo titles A group chip was announced as "Person crew, 2 recipients: ...". It now says "Group crew, ...", through an optional kind name on InlineChip. A Solo chat that started with a group chip was never named automatically: its starting title dropped `@crew`, but Solo naming rereads the sent text, where `@crew` names no tagged person, and so kept it. The starting title now keeps a leading group label too, and a label that starts with a member's name is no longer cut at that name. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 2 +- src/features/messages/RichComposerInput.tsx | 1 + src/features/solo/chat-title.test.ts | 39 +++++++++++++------ src/features/solo/chat-title.ts | 7 ++-- src/shared/design-system/ui/InlineChip.tsx | 5 ++- 5 files changed, 37 insertions(+), 17 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 9f904485cc..9ca82e52e5 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -12693,7 +12693,7 @@ it("a labelled mentions edit is one chip, sent as `@label` with each member once expect( // The namesakes' names say which key each one is. screen.getByRole("img", { - name: "Person Crew, 2 recipients: Honey · rcaj, Honey · 04hu", + name: "Group Crew, 2 recipients: Honey · rcaj, Honey · 04hu", }), ).toHaveTextContent("@Crew · 2"); // A member also mentioned alone is still one recipient. diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index e2cb1de626..8f5a9498ff 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -120,6 +120,7 @@ const GroupChip = memo(function GroupChip({ return ( { 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], +it("keeps a leading group tag, so Solo naming matches the sent text", () => { + const member = (pubkey: string, name: string, label: string) => ({ + pubkey: pubkey.repeat(64), + name, + label, + start: 0, + end: label.length + 1, + }); + const title = (text: string, label: string) => + startingChatTitle( + typedDraft( + mentionDraft({ + text, + recipients: [member("a", "Ann", label), member("b", "Bo", label)], + }), + ), + ); + expect(title("@crew do X", "crew")).toBe("@crew do X"); + // The sent text tags no one named `@crew`, so its reading keeps the label too. + expect( + isStartingChatTitle(title("@crew do X", "crew"), { + text: "@crew do X", + recipients: [], }), - ); - expect(startingChatTitle(draft)).toBe("do X"); + ).toBe(true); + // A label that starts with a member's name is never cut at that name. + expect(title("@Ann's team do X", "Ann's team")).toBe("@Ann's team do X"); }); diff --git a/src/features/solo/chat-title.ts b/src/features/solo/chat-title.ts index abb59e3178..aa0a6534bd 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,15 +35,16 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { - // A group's members share its `@label` span, which counts once. - if (recipient.start < draftStart && recipient.end === draftStart) continue; + // A group's `@label` stays: Solo naming rereads the sent text, where it + // names no tagged person. + if (recipient.label !== undefined) break; 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.label ?? recipient.name}`; + const tag = `@${recipient.name}`; if (!text.startsWith(tag, start + leading)) break; start += leading + tag.length; // A namesake is sent with its full key; that qualifier is part of the tag. diff --git a/src/shared/design-system/ui/InlineChip.tsx b/src/shared/design-system/ui/InlineChip.tsx index a728ed25e1..09d18b50b1 100644 --- a/src/shared/design-system/ui/InlineChip.tsx +++ b/src/shared/design-system/ui/InlineChip.tsx @@ -36,6 +36,7 @@ export function InlineChip({ qualifier, interactive = true, onActivate, + kindName, }: { address: ChipAddress; /** Scoped display data supplied by a host that already owns identity lookup. */ @@ -51,11 +52,13 @@ export function InlineChip({ interactive?: boolean; /** An explicit owner-provided action; previews never imply a deep-open. */ onActivate?: (address: ChipAddress) => void; + /** The kind it is announced as, when its address kind's name doesn't fit. */ + kindName?: string; }) { const face = useChipFace(address, suppliedFace); const Icon = KIND_ICON[address.kind]; const trigger = CHIP_KIND_TRIGGER[address.kind]; - const kind = accessibleKind(address.kind); + const kind = kindName ?? accessibleKind(address.kind); const content = ( <> From 4c1a5a13cdc134b35efb9d3ec06d124fc1fa416a Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 08:49:38 -0500 Subject: [PATCH 08/35] fix(composer): escape a group label picked while editing Picking a group while editing a sent message inserted `@label` as typed Markdown, so a label such as `*ops*` changed how the edited message rendered. An edit now inserts the label escaped, the same way a chip sends it. Inside code it still goes in as is. A chip inside a link was escaped twice, once by the chip and again by the link's own text escaping; the link now escapes it once. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 42 ++++++++++--------- src/features/messages/MessageComposer.tsx | 11 +++-- .../messages/composer-document.test.ts | 23 ++++++++++ src/features/messages/composer-markdown.ts | 13 ++++-- 4 files changed, 62 insertions(+), 27 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 9ca82e52e5..ceded8459b 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -12671,16 +12671,11 @@ it("batch insertion rejects an unavailable member atomically and does not send o function offerCrew( h: ReturnType, mentions: readonly MentionRecipient[], + label = "Crew", ) { act(() => { h.completionRequests.at(-1)?.({ - items: [ - { - id: "crew", - label: "Crew", - edit: { mentions, label: "Crew" }, - }, - ], + items: [{ id: "crew", label, edit: { mentions, label } }], }); }); } @@ -12717,19 +12712,26 @@ it("a labelled mentions edit inside Markdown code is only its name", async () => 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.each([ + ["Crew", "@Crew "], + // An edit is Markdown, so the label goes in escaped, as a chip sends it. + ["*ops*", "@\\*ops\\* "], +])( + "a labelled mentions edit while editing a sent message adds only its text (%s)", + async (label, text) => { + const h = mount({}, undefined, first.pubkey); + h.setRows([editableMessage()]); + fireEvent.keyDown(h.input(), { key: "ArrowUp" }); + h.fill("!Crew"); + offerCrew(h, [first, second], label); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue(text); + expect(h.commands().recipients).toEqual([]); + h.submit(); + expect(h.messages.edit.mock.calls[0]?.[1]).toBe(text); + expect(h.messages.send).not.toHaveBeenCalled(); + }, +); it("a labelled mentions edit with an unavailable member adds nothing", async () => { const h = mount({ inviteAgents: true }); h.fill("!Crew"); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index fb561156b4..63c73e414f 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -189,7 +189,7 @@ import type { AnnotationMenuRequest } from "./composer-dom"; import { formatMediaTime, mediaTimeReply } from "./media-timecode"; import { RichComposerInput } from "./RichComposerInput"; import type { MessageLinkOrigin } from "./MessageRow"; -import { composerMarkdown } from "./composer-markdown"; +import { composerMarkdown, groupLabelMarkdown } from "./composer-markdown"; import type { ComposerInputElement, ComposerLinkEdit, @@ -2217,7 +2217,8 @@ function Composer({ } /** 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. */ + * in, since edits never add notification intent; an edit is Markdown, so + * there the label goes in escaped, as a chip sends it. */ function insertGroup( edit: Readonly<{ mentions: readonly MentionRecipient[]; label: string }>, range: CompletionQuery, @@ -2231,9 +2232,11 @@ function Composer({ input.current.readOnly ) return false; + if (inMarkdownCode(range)) + return insert(`@${edit.label} `, undefined, range); + if (editing.target) + return insert(`${groupLabelMarkdown(edit.label)} `, undefined, range); 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 }]), diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index f92ae8ee0f..2d102033c4 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -769,6 +769,29 @@ describe("inline formatting batch", () => { kinds: ["root", "paragraph", "emphasis", "text"], text: "@eng_ios hi", }); + // Emphasis beside an escaped label still pairs only its own delimiters. + expect( + rendered( + serialize( + chip("eng*"), + schema.text("b", [schema.marks.italic.create()]), + schema.text("*"), + ), + ), + ).toEqual({ + kinds: ["root", "paragraph", "text", "emphasis"], + text: "@eng*b*", + }); + // A link escapes its own text, once. + const linked = schema.nodes.token.create( + { source: "@eng_ios", group: { label: "eng_ios", members } }, + null, + [schema.marks.link.create({ href: "https://example.com" })], + ); + expect(rendered(serialize(linked))).toEqual({ + kinds: ["root", "paragraph", "link", "text"], + text: "@eng_ios", + }); // Code shows its text as is. expect(serialize(chip("eng_ios", "code"))).toBe("`@eng_ios`"); }); diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index ffa32bc0a9..1e468adf02 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -45,6 +45,11 @@ const strike: Handle & { peek?: Handle } = (node, parent, state, info) => { }; strike.peek = () => "~"; +/** A group chip's `@label` as Markdown prose: the characters that can open + * inline Markdown are escaped, so it renders as the label. */ +export const groupLabelMarkdown = (label: string) => + `@${label.replace(/[\\`*_[\]<~]/g, "\\$&")}`; + /** Plain portions are authored Markdown, not rich-editor literal text. Keeping * their source verbatim avoids normalizing formats this slice does not edit. * Marked content uses CommonMark/GFM delimiter escaping and flanking rules. @@ -55,17 +60,19 @@ export function composerMarkdown( { authored = false }: { authored?: boolean } = {}, ): string { // A group's label comes from a plugin, so its Markdown characters are sent - // escaped: it renders as the label the chip shows. In code it stays as is. + // escaped: it renders as the label the chip shows. Code shows it as is, and + // a link's text is escaped by the link. const project = (node: EditorNode): EditorNode => node.type.name === "token" && node.attrs.semantic ? node.mark(composerSchema.marks.literal.create().addToSet(node.marks)) : node.type.name === "token" && node.attrs.group && - !composerSchema.marks.code.isInSet(node.marks) + !composerSchema.marks.code.isInSet(node.marks) && + !composerSchema.marks.link.isInSet(node.marks) ? node.type.create( { ...node.attrs, - source: `@${node.attrs.group.label.replace(/[\\`*_[\]<~]/g, "\\$&")}`, + source: groupLabelMarkdown(node.attrs.group.label), }, null, node.marks, From 36a7ec245dac7be88eda18aa538cab6c4f2998ce Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 12:31:35 -0500 Subject: [PATCH 09/35] refactor(completions): shrink the supplement change matchCompletion returns the winner and its supplements in provider precedence as `sources`, so byOrder and the second sort go. Per-source state is keyed by contributionKey. The option row is back at main's indentation, with headings and descriptions computed before the JSX. Drop group checks that only winner rows could reach, since supplements never carry a group. The key handler reads no publication while a supplement holds. Restore main's comment wording where the change only reflowed it. No behavior change. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.tsx | 435 ++++++++---------- src/features/conversation/completion.ts | 55 +-- 2 files changed, 230 insertions(+), 260 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index 2bc826ffee..3283320e3d 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -12,7 +12,6 @@ import { createPortal } from "react-dom"; import { RobotIcon } from "../../shared/design-system/icons/index"; import { useCompletionPosition } from "./useCompletionPosition"; import { - Fragment, useId, useCallback, useEffect, @@ -37,7 +36,6 @@ import type { import { ContributionBoundary, contributionKey } from "./ContributionBoundary"; import { IdentityMarks } from "./IdentityMarks"; import { - byOrder, completionResult, matchCompletion, type CompletionMatch, @@ -96,8 +94,8 @@ 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. - * Results are kept per provider: the winner and each supplement beside it. */ + * closed render, so a carried result means only a continuing open query. */ +// By `contributionKey` of the publishing provider, winner or supplement. type Shown = Readonly>; function createDisplay() { let shown: { key: string; results: Shown | undefined } = { @@ -271,7 +269,7 @@ export function ComposerCompletions({ identityMarks={identityMarks} display={display} provider={match.provider} - supplements={match.supplements} + sources={match.sources} query={match.query} observation={observation} editor={editor} @@ -282,20 +280,20 @@ export function ComposerCompletions({ ); } -type Source = CompletionMatch; type Row = Readonly<{ - source: Source; + source: CompletionMatch; key: string; item?: HostCompletionSuggestion; heading?: string; }>; +const slot = ({ provider }: CompletionMatch) => contributionKey(provider); // 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]); +const rowKey = (source: CompletionMatch, id?: string) => + JSON.stringify([slot(source), id ?? null]); function OwnedCompletion({ provider, - supplements: matched, + sources: matched, registry, identityMarks, display, @@ -308,7 +306,7 @@ function OwnedCompletion({ ...context }: CompletionContext & { provider: Contribution; - supplements: readonly Source[]; + sources: readonly CompletionMatch[]; registry: ContributionReader; identityMarks?: ContributionReader | undefined; display: ReturnType; @@ -346,28 +344,19 @@ function OwnedCompletion({ const list = useRef(null); const trigger = `${contributionKey(provider)}:${query.start}`; // 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 [sources] = useState(matched); const results = useSyncExternalStore( display.subscribe, () => display.read(trigger), () => display.read(trigger), ); const result = results?.[contributionKey(provider)]; - // This lifetime's own publications; a carried display is never acted on. - const latest = useRef(new Map()); + // This lifetime's own publication; 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 failed = useRef(new Set()); + // Only user navigation pins an ID; automatic selection follows the first result. const [selected, setSelected] = useState(); const [keyboardSelection, setKeyboardSelection] = useState(); const pointerMoved = useCallback( @@ -399,49 +388,41 @@ function OwnedCompletion({ current.current = { editor, replace }; }); const active = useCallback( - (source: Source) => + (candidate: Contribution) => live.current && - !failed.current.has(source) && - registry.snapshot().includes(source.provider) && + !failed.current.has(contributionKey(candidate)) && + registry.snapshot().includes(candidate) && current.current.editor.valid(observation), [registry, observation], ); const [publishers, setPublishers] = - useState>(); + useState(); useLayoutEffect(() => { live.current = true; let owned = true; 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); - }; - }, - ]), - ), + sources.map((source) => (incoming: CompletionResult) => { + if (!owned || !active(source.provider)) return false; + const next = completionResult(incoming, source.provider); + published.set(slot(source), next); + revealSelection.current = true; + display.set(trigger, slot(source), next); + // A pinned row of this provider stays only while it still exists. + setSelected((previous) => { + if (!previous?.startsWith(`[${slot(source)},`)) 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(slot(source)) !== next) return; + published.delete(slot(source)); + if (live.current) display.set(trigger, slot(source)); + }; + }), ); return () => { owned = false; @@ -449,42 +430,39 @@ function OwnedCompletion({ published.clear(); }; }, [active, display, sources, trigger]); - // A carried result stands only until this query's providers have run their + // A carried result stands only until this query's provider has run its // mount effects, which precede this one; a provider that has not published - // 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. + // by then leaves the popup closed, as for a first query, so a stale display + // is never painted. Each supplement is judged alone. useEffect(() => { 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)); + for (const key of Object.keys(display.read(trigger) ?? {})) + if (!latest.current.has(Number(key))) display.set(trigger, Number(key)); }, [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); + sources.some((source) => { + const published = latest.current.get(slot(source)); return ( - !failed.current.has(source) && - (!published || published.holdAutoSelect === true) + source.provider !== provider && + !failed.current.has(slot(source)) && + (!published || published.holdAutoSelect) ); }); // 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 ? ( + const isolate = (source: CompletionMatch, node: ReactNode) => + source.provider === provider ? ( node ) : ( { if (!failure) return; - failed.current.add(source); - display.set(trigger, contributionKey(source.provider)); + failed.current.add(slot(source)); + display.set(trigger, slot(source)); }} > {node} @@ -492,7 +470,7 @@ function OwnedCompletion({ ); const rows: Row[] = []; for (const source of sources) { - const shown = results?.[contributionKey(source.provider)]; + const shown = results?.[slot(source)]; const own: Row[] = [ ...(shown?.items ?? []).map((item) => ({ source, @@ -504,14 +482,32 @@ function OwnedCompletion({ // 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))) + if ( + first && + (source.provider !== provider || (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; + const status = results?.[slot(source)]?.status; return status ? [{ source, status }] : []; }); + const lines = rows.map((row, i) => { + const { item, source } = row; + const lead = rows.findIndex((other) => other.source === source); + const group = item?.group; + return { + ...row, + heading: + row.heading ?? (group !== rows[i - 1]?.item?.group ? group : undefined), + described: group + ? `${id}-group-${rows.findIndex((other) => other.item?.group === group)}` + : rows[lead]?.heading + ? `${id}-group-${lead}` + : undefined, + }; + }); // 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 = !!(rows.length || statuses.length); @@ -521,9 +517,9 @@ function OwnedCompletion({ function accept(index: number, key = "click") { 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; + const source = row?.source ?? { provider, query }; + const published = latest.current.get(slot(source)); + if (!active(source.provider) || !published) return false; if (row && !row.item) { if (!published.retry) return false; published.retry(); @@ -546,10 +542,10 @@ function OwnedCompletion({ } useLayoutEffect(() => { const element = input.current; - // 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. + // 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. + // A supplement that still holds counts as undecided. if (!element || (!visible && result && !result.spacePending && !held())) return; if (visible) { @@ -582,7 +578,7 @@ function OwnedCompletion({ (event.key === " " || !terminates(event.key)) ) return false; - if (!active(winner)) { + if (!active(provider)) { // 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) { @@ -597,13 +593,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. A - // supplement holding the terminator leaves it literal too. - const published = latest.current.get(winner); - const waiting = terminates(event.key) && held(); + // is never accepted on its own; only the publication selects. + // A supplement holding the terminator leaves it literal too. + const published = held() + ? undefined + : latest.current.get(contributionKey(provider)); if ( terminates(event.key) && - !waiting && published?.spaceId && (!result?.spaceId || result.spaceId === published.spaceId) ) { @@ -622,7 +618,6 @@ function OwnedCompletion({ // decision is deferred to the resolver under the full rule. if ( terminates(event.key) && - !waiting && published?.spacePending && !published.spaceId && current.current.replace( @@ -673,22 +668,19 @@ function OwnedCompletion({ return ( <> {publishers && - sources.map((source) => { + sources.map((source, i) => { const Provider = source.provider.component; - const publish = publishers.get(source); + const publish = publishers[i]; if (!publish) return null; - return ( - - {isolate( - source, - , - )} - + return isolate( + source, + , ); })} {visible && @@ -709,140 +701,117 @@ function OwnedCompletion({ ref={list} className={styles.list} > - {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. + {lines.flatMap(({ item, source, key, heading, described }, i) => [ + heading && ( + // Read as the description of each row it heads.
{ - 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(row.key); - } - : undefined - } - onClick={() => accept(i)} - className={styles.option} + key={`group:${key}`} + id={`${id}-group-${i}`} + aria-hidden="true" + className={styles.group} > - {!item ? ( - source === winner ? ( - "Retry suggestions" - ) : ( - `Retry ${source.provider.title} suggestions` - ) - ) : ( - <> - {item.preview && ( - - )} - - {compact ? ( - - ) : named ? ( - // Only the name ellipsizes; the agent mark stays visible. - - {item.label} - {mention && - source === winner && - item.edit.mention && ( - - )} - {item.agent && ( - - )} - {item.agent && ( - Agent - )} + {heading} +
+ ), + // The textarea owns keyboard focus/selection via aria-activedescendant. + // biome-ignore lint/a11y/useKeyWithClickEvents: Keyboard acceptance belongs to the focused textarea. +
{ + 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(key); + } + : undefined + } + onClick={() => accept(i)} + className={styles.option} + > + {item?.preview && ( + + )} + {item && ( + + {compact ? ( + + ) : named ? ( + // Only the name ellipsizes; the agent mark stays visible. + + {item.label} + {mention && + source.provider === provider && + item.edit.mention && ( + + )} + {item.agent && ( + - ) : ( - item.label )} - {item.detail && ( - - {item.detail} - + {item.agent && ( + Agent )} - {channel && i === selectedIndex && ( - - )} - - )} -
- ); - return [ - heading && ( - // Read as the description of each row it heads. - - ), - option, - ]; - })} + ) : ( + item.label + )} + {item.detail && ( + + {item.detail} + + )} +
+ )} + {channel && item && i === selectedIndex && ( + + )} + {!item && + (source.provider === provider + ? "Retry suggestions" + : `Retry ${source.provider.title} suggestions`)} + , + ])} {statuses.map(({ source, status }) => ( -

+

{status}

))} diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 299ea116fa..62687cac0f 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -37,54 +37,55 @@ 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 }>[] = [], -): (CompletionMatch & { supplements: readonly CompletionMatch[] }) | undefined { - let winner: CompletionMatch | undefined; - const supplements: CompletionMatch[] = []; - for (const provider of [...providers].sort(byOrder)) { +) { + const order = (value: ComposerCompletion) => + Number.isFinite(value.order) ? (value.order ?? 0) : 0; + const matches: CompletionMatch[] = []; + for (const provider of [...providers].sort( + (a, b) => order(a) - order(b) || a.key.localeCompare(b.key), + )) { 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, ) ) - 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; + matches.push({ + provider, + query: Object.freeze({ + start: query.start, + end: query.end, + query: query.query, + }), + }); } catch { /* A broken optional matcher cannot break editing. */ } } + const owners = matches.filter(({ provider }) => provider.supplement !== true); + const start = Math.max(...owners.map(({ query }) => query.start)); + const winner = owners.find(({ query }) => query.start === start); + // The winner and its supplements, in provider precedence. + const sources = matches.filter( + (match) => + match === winner || + (match.provider.supplement === true && match.query.start === start), + ); return ( winner && { ...winner, - supplements: supplements.filter( - (match) => match.query.start === winner.query.start, - ), + sources, + supplements: sources.filter((match) => match !== winner), } ); } From 2c8389413e6a590eaa1a45c4344c226b3fcbea42 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 12:23:35 -0500 Subject: [PATCH 10/35] refactor(composer): shrink the labelled-mentions change Fold insertGroup into insertMentions with an optional label, keeping the group's error wording. Render the group chip with InlineChip directly. Use one CompletionEdit mentions variant with an optional label. Use the literal 32 recipient limit, as the rest of the composer does. Let distinctRecipients return the distinct people, and tighten composerGroup, tokenRecipients, replaceRecipients and the Markdown group projection. No behavior change. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/conversation/contracts.ts | 13 +-- src/features/messages/EditableInput.tsx | 46 ++++----- src/features/messages/MessageComposer.tsx | 101 ++++++-------------- src/features/messages/RichComposerInput.tsx | 31 +++--- src/features/messages/composer-document.ts | 51 +++++----- src/features/messages/composer-markdown.ts | 34 ++++--- src/features/messages/mention-draft.ts | 19 ++-- 7 files changed, 110 insertions(+), 185 deletions(-) diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index c7b288dae4..1648636de0 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -392,16 +392,9 @@ 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; + /** 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. */ + label?: string; text?: never; mention?: never; pending?: never; diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index 286af96217..01ad72f5fb 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -98,7 +98,6 @@ import { } from "./composer-clipboard"; import { distinctRecipients, - MAX_RECIPIENTS, mentionBoundary, mentionDraft, type MentionDraft, @@ -919,7 +918,6 @@ export function EditableInput({ text = text.replace(/\r\n?/g, "\n"); const tr = closeHistory(editor.state.tr); if (group) { - // One chip for every member; in code, the text alone. const source = `@${group.label}`; tr.replaceWith( from, @@ -971,8 +969,8 @@ export function EditableInput({ ); if ( (Array.isArray(recipient) || group) && - distinctRecipients(projectComposerDocument(tr.doc).draft.recipients) > - MAX_RECIPIENTS + distinctRecipients(projectComposerDocument(tr.doc).draft.recipients) + .length > 32 ) return false; if ( @@ -1134,28 +1132,25 @@ export function EditableInput({ const added = recipients.filter((person) => !existing.has(person.pubkey)); const tr = closeHistory(editor.state.tr); // 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)); + // requested, and is plain text without them. Attributes keep positions. + for (const token of source.tokens) { + const group = composerGroup( + token.node.attrs.group, + token.node.attrs.source, + ); + const members = group?.members.filter((m) => requested.has(m.pubkey)); + if (group && members && members.length < group.members.length) tr.setNodeMarkup(token.from, undefined, { ...token.node.attrs, group: members.length ? { label: group.label, members } : null, }); + } + for (const person of [...source.draft.recipients].reverse()) { + if (requested.has(person.pubkey) || person.label !== undefined) continue; - } - const end = span.end + (source.draft.text[span.end] === " " ? 1 : 0); - tr.delete(source.position(start), source.position(end, -1)); + const end = + person.end + (source.draft.text[person.end] === " " ? 1 : 0); + tr.delete(source.position(person.start), source.position(end, -1)); } if (added.length) { const at = Selection.atStart(tr.doc).from; @@ -1180,7 +1175,7 @@ export function EditableInput({ } const next = projectComposerDocument(tr.doc).draft; if ( - distinctRecipients(next.recipients) > MAX_RECIPIENTS || + distinctRecipients(next.recipients).length > 32 || composerMarkdown(next).length > current.current.maxLength ) return false; @@ -1750,7 +1745,7 @@ export function EditableInput({ const identity = identityLink(token.node.attrs.source); if ( !identity || - (!counted.has(identity.pubkey) && counted.size >= MAX_RECIPIENTS) || + (!counted.has(identity.pubkey) && counted.size >= 32) || !mentionBoundary( projectComposerDocument(tr.doc).draft.text, token.end, @@ -2628,10 +2623,7 @@ export function EditableInput({ 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; + const group = composerGroup(node.attrs.group, node.attrs.source); if (group?.members.some((m) => m.pubkey === pubkey)) { const members = group.members.filter((m) => m.pubkey !== pubkey); tr.setNodeMarkup(pos, undefined, { diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 63c73e414f..d018e95ba2 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -1838,7 +1838,8 @@ function Composer({ } if ( recipient && - distinctRecipients([...valueRef.current.recipients, recipient]) > 32 + distinctRecipients([...valueRef.current.recipients, recipient]).length > + 32 ) { setError("Choose at most 32 recipients"); return false; @@ -1939,7 +1940,8 @@ function Composer({ ? "unresolved" : !admits()(recipient.pubkey) ? "unavailable" - : distinctRecipients([...valueRef.current.recipients, recipient]) > 32 + : distinctRecipients([...valueRef.current.recipients, recipient]) + .length > 32 ? "limit" : undefined; const accepted = @@ -2136,9 +2138,11 @@ function Composer({ if (focus) input.current?.focus(); return true; } + /** With `label`, one chip `@label` stands for all of `recipients`. */ function insertMentions( recipients: readonly MentionRecipient[], range?: CompletionQuery, + label?: string, ) { if ( !Array.isArray(recipients) || @@ -2169,31 +2173,46 @@ function Composer({ input.current.readOnly ) return false; + // In code only the text goes in, as in a message edit. + if (label !== undefined && range && inMarkdownCode(range)) + return insert(`@${label} `, undefined, range); // Message edits only add references, never new notification intent. if (editing.target) return insert( - unique.map((person) => editMentionText(person)).join(""), + label === undefined + ? unique.map((person) => editMentionText(person)).join("") + : `${groupLabelMarkdown(label)} `, undefined, range, ); const admitted = admits(); + const noun = label === undefined ? "team" : "group"; if (unique.some((person) => !admitted(person.pubkey))) { setError( - "A team member is no longer available. Refresh choices before trying again.", + label === undefined + ? "A team member is no longer available. Refresh choices before trying again." + : "A recipient is no longer available. Refresh choices before trying again.", ); return false; } - const text = unique.map((person) => `@${person.name} `).join(""); + const text = + label === undefined + ? unique.map((person) => `@${person.name} `).join("") + : `@${label} `; if ( !(solo && !range ? keepProseCaret( (at) => !!input.current?.insertText(text, unique, at, undefined, false), ) - : input.current.insertText(text, unique, range)) + : input.current.insertText( + text, + label === undefined ? unique : { label, members: unique }, + range, + )) ) { setError( - "The team would exceed the message length or 32-recipient limit. Nothing was added.", + `The ${noun} would exceed the message length or 32-recipient limit. Nothing was added.`, ); return false; } @@ -2215,58 +2234,6 @@ function Composer({ (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; an edit is Markdown, so - * there the label goes in escaped, as a chip sends it. */ - 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; - if (inMarkdownCode(range)) - return insert(`@${edit.label} `, undefined, range); - if (editing.target) - return insert(`${groupLabelMarkdown(edit.label)} `, undefined, range); - const text = `@${edit.label} `; - 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) || @@ -2352,9 +2319,7 @@ function Composer({ return true; } if ("mentions" in edit && edit.mentions) - return edit.label !== undefined - ? insertGroup(edit, query) - : insertMentions(edit.mentions, query); + return insertMentions(edit.mentions, query, edit.label); if ("mention" in edit && edit.mention) return insert(`@${edit.mention.name} `, edit.mention, query, typed); if ("token" in edit && edit.token) { @@ -2989,9 +2954,9 @@ function Composer({ return; } let references: readonly string[] = []; - let recipients = [ - ...new Set(capturedRecipients.map((item) => item.pubkey)), - ]; + let recipients = distinctRecipients(capturedRecipients).map( + (item) => item.pubkey, + ); let declinedImports: readonly string[] = []; if (soloConversation || ownSoloConversation) { admission.current = true; @@ -3002,11 +2967,7 @@ function Composer({ )); } 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(), - ]; + const people = distinctRecipients(captured.recipients); // An agent only an earlier Buzz runs would not answer; offer it here first. const lookup = oldAgents.find(people); const old = lookup instanceof Promise ? await lookup : lookup; diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index 8f5a9498ff..f23026e00e 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -340,21 +340,8 @@ export function RichComposerInput({ ...(mention ? { mention } : {}), }); }; - // 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], - }); - } + for (const recipient of draft.recipients) 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(); @@ -418,17 +405,23 @@ 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}`) + // A group's members share its span: one chip, counting them. + const people = draft.recipients.filter( + (item) => item.start === start && item.label !== undefined, + ); + const group = people[0]?.label; + if (group !== undefined && draft.text.slice(start, end) === `@${group}`) return { start, end, editAsText: false, content: ( labels.get(item.pubkey) ?? item.name) + .join(", ")} + count={people.length} /> ), }; diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 188972781e..7cb9fed275 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -235,22 +235,18 @@ export function composerGroup( source !== `@${label}` || !Array.isArray(members) || !members.length || - members.length > 32 + members.length > 32 || + members.some( + (member) => + !member || + typeof member.pubkey !== "string" || + !/^[0-9a-f]{64}$/.test(member.pubkey) || + typeof member.name !== "string" || + !member.name.trim(), + ) || + new Set(members.map((member) => member.pubkey)).size < members.length ) return null; - 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. */ @@ -284,23 +280,20 @@ export function tokenRecipients( (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]; + if (label === undefined) + return { + recipient: one ? { pubkey: one.pubkey, name: one.name } : null, + group: null, + }; + const members = new Map( + on + .filter((item) => item.label === label) + .map(({ pubkey, name }) => [pubkey, { pubkey, name }]), + ); return { - recipient: one ? { pubkey: one.pubkey, name: one.name } : null, - group: null, + recipient: null, + group: composerGroup({ label, members: [...members.values()] }, source), }; } /** Draft text stays the editing/completion coordinate space. Formatting metadata diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index 1e468adf02..882739357b 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -50,6 +50,19 @@ strike.peek = () => "~"; export const groupLabelMarkdown = (label: string) => `@${label.replace(/[\\`*_[\]<~]/g, "\\$&")}`; +/** A group's label comes from a plugin, so a chip sends it escaped: it renders + * as the label the chip shows. Code shows it as is; a link escapes its text. */ +const groupChip = (node: EditorNode) => + node.attrs.group && + !composerSchema.marks.code.isInSet(node.marks) && + !composerSchema.marks.link.isInSet(node.marks) + ? node.type.create( + { ...node.attrs, source: groupLabelMarkdown(node.attrs.group.label) }, + null, + node.marks, + ) + : node; + /** Plain portions are authored Markdown, not rich-editor literal text. Keeping * their source verbatim avoids normalizing formats this slice does not edit. * Marked content uses CommonMark/GFM delimiter escaping and flanking rules. @@ -59,27 +72,12 @@ export function composerMarkdown( draft: MentionDraft, { authored = false }: { authored?: boolean } = {}, ): string { - // A group's label comes from a plugin, so its Markdown characters are sent - // escaped: it renders as the label the chip shows. Code shows it as is, and - // a link's text is escaped by the link. const project = (node: EditorNode): EditorNode => node.type.name === "token" && node.attrs.semantic ? node.mark(composerSchema.marks.literal.create().addToSet(node.marks)) - : node.type.name === "token" && - node.attrs.group && - !composerSchema.marks.code.isInSet(node.marks) && - !composerSchema.marks.link.isInSet(node.marks) - ? node.type.create( - { - ...node.attrs, - source: groupLabelMarkdown(node.attrs.group.label), - }, - null, - node.marks, - ) - : node.isLeaf - ? node - : node.copy(Fragment.fromArray(node.content.content.map(project))); + : node.isLeaf + ? groupChip(node) + : node.copy(Fragment.fromArray(node.content.content.map(project))); const doc = project(readComposerDocument(draft, [])); const wire = (body: EditorNode) => [...(draft.chatCards ?? []), blocksMarkdown(body), ...(draft.gifs ?? [])] diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 180533a4c1..7afa4fe01a 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -10,21 +10,16 @@ export type MentionRecipient = Readonly<{ pubkey: string; name: string }>; * the group's `label`: then the span is `@label`, not `@name`. */ export type DraftRecipient = MentionRecipient & 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. */ +/** One entry per person: a group shares a span with its members, and two + * chips can name the same person. */ +export const distinctRecipients = ( + recipients: readonly T[], +) => [...new Map(recipients.map((item) => [item.pubkey, item])).values()]; +/** `recipients` up to the first 32 distinct people, keeping all their spans. */ function capRecipients(recipients: readonly T[]) { const kept = new Set(); return recipients.filter((item) => { - if (!kept.has(item.pubkey) && kept.size >= MAX_RECIPIENTS) return false; + if (!kept.has(item.pubkey) && kept.size >= 32) return false; kept.add(item.pubkey); return true; }); From b1b8ae3ac6f0342450c4e236e72f21a2d6cbe90c Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 12:53:14 -0500 Subject: [PATCH 11/35] refactor(composer): restore a group chip from the draft's recipients Restoring a saved chip rebuilt its members with groupMembers, a second copy of what tokenRecipients already derives from the draft's labelled recipients on the token's range. Use tokenRecipients behind the same snapshot gate and drop groupMembers. The editor writes one labelled recipient per chip member, in member order, beside the snapshot, and mentionDraft only removes entries, so the restored chip is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/composer-document.ts | 29 ++++------------------ 1 file changed, 5 insertions(+), 24 deletions(-) diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 7cb9fed275..33c136250c 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -249,26 +249,6 @@ export function composerGroup( return null; 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( @@ -331,9 +311,6 @@ export function readComposerDocument( 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, @@ -346,7 +323,11 @@ export function readComposerDocument( ? node.attrs.recipient : null, group: - group && members.length ? { label: group.label, members } : null, + group && + tokenRecipients(draft.recipients, node.attrs.source, { + start, + end, + }).group, resource: resource && resource.source === node.attrs.source && From 90efaa2c9339a0940e12e469639050fc37d61e21 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 14:21:59 -0500 Subject: [PATCH 12/35] Remove the prose comments this change adds Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 7 ------- .../conversation/ComposerCompletions.tsx | 16 +--------------- src/features/conversation/completion.ts | 3 --- 3 files changed, 1 insertion(+), 25 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index a71259d450..2ed4f3f302 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -330,9 +330,7 @@ type Source = Readonly<{ 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( @@ -467,18 +465,15 @@ const groupRow = { 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 () => { @@ -577,7 +572,6 @@ it("drops a failed supplement's rows and refuses its later publications", async }); expect(late).toBe(false); expect(listed()).toEqual(["Eng Bot"]); - // Its hold went with it. expect(press(" ")).toBe(true); expect(replace).toHaveBeenCalledWith( { mention: ENG_BOT }, @@ -652,7 +646,6 @@ it("lets Escape dismiss a supplement that has not answered beside an empty winne 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, ); diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index 3283320e3d..b541a0d4dd 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -95,7 +95,6 @@ function EmojiCompletionName({ * 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. */ -// By `contributionKey` of the publishing provider, winner or supplement. type Shown = Readonly>; function createDisplay() { let shown: { key: string; results: Shown | undefined } = { @@ -287,7 +286,6 @@ type Row = Readonly<{ heading?: string; }>; const slot = ({ provider }: CompletionMatch) => contributionKey(provider); -// A row's identity is its provider and its id: two providers may share ids. const rowKey = (source: CompletionMatch, id?: string) => JSON.stringify([slot(source), id ?? null]); @@ -343,7 +341,6 @@ function OwnedCompletion({ ); const list = useRef(null); const trigger = `${contributionKey(provider)}:${query.start}`; - // Fixed for this lifetime: a changed set of supplements remounts it. const [sources] = useState(matched); const results = useSyncExternalStore( display.subscribe, @@ -353,8 +350,6 @@ function OwnedCompletion({ const result = results?.[contributionKey(provider)]; // This lifetime's own publication; 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 an ID; automatic selection follows the first result. const [selected, setSelected] = useState(); @@ -408,7 +403,6 @@ function OwnedCompletion({ published.set(slot(source), next); revealSelection.current = true; display.set(trigger, slot(source), next); - // A pinned row of this provider stays only while it still exists. setSelected((previous) => { if (!previous?.startsWith(`[${slot(source)},`)) return previous; const kept = @@ -433,14 +427,12 @@ function OwnedCompletion({ // A carried result stands only until this query's provider has run its // 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. Each supplement is judged alone. + // is never painted. useEffect(() => { if (!publishers) return; for (const key of Object.keys(display.read(trigger) ?? {})) if (!latest.current.has(Number(key))) display.set(trigger, Number(key)); }, [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 = () => sources.some((source) => { const published = latest.current.get(slot(source)); @@ -450,8 +442,6 @@ function OwnedCompletion({ (!published || published.holdAutoSelect) ); }); - // 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: CompletionMatch, node: ReactNode) => source.provider === provider ? ( node @@ -479,8 +469,6 @@ function OwnedCompletion({ })), ...(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 && @@ -545,7 +533,6 @@ function OwnedCompletion({ // 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. - // A supplement that still holds counts as undecided. if (!element || (!visible && result && !result.spacePending && !held())) return; if (visible) { @@ -594,7 +581,6 @@ function OwnedCompletion({ // 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. - // A supplement holding the terminator leaves it literal too. const published = held() ? undefined : latest.current.get(contributionKey(provider)); diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 62687cac0f..dbb2c13c90 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -75,7 +75,6 @@ export function matchCompletion( const owners = matches.filter(({ provider }) => provider.supplement !== true); const start = Math.max(...owners.map(({ query }) => query.start)); const winner = owners.find(({ query }) => query.start === start); - // The winner and its supplements, in provider precedence. const sources = matches.filter( (match) => match === winner || @@ -112,8 +111,6 @@ 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, From 7024324640724761dfe8d4e051c945736317fabb Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 14:22:29 -0500 Subject: [PATCH 13/35] Infer the test sources' types and check them with satisfies Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 48 ++++++++++--------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 2ed4f3f302..b2136a3db6 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -433,32 +433,34 @@ function mountSources( }); return { replace, press, publishes, unregister }; } -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 people = (result: Partial = {}) => + ({ + id: "people", + title: "Mention", + order: -10, + result: { + items: [ + { + id: "x", + label: "Eng Bot", + edit: { mention: ENG_BOT }, + }, + ], + spaceId: "x", + ...result, + }, + }) satisfies Source; const groups = ( result: CompletionResult | (() => never) | undefined, order = -20, -): Source => ({ - id: "groups", - title: "Groups", - order, - supplement: true, - result, -}); +) => + ({ + id: "groups", + title: "Groups", + order, + supplement: true, + result, + }) satisfies Source; const groupRow = { id: "x", label: "eng", From 3a633a9aace09919e5ec908574f4f906874c999a Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 14:24:06 -0500 Subject: [PATCH 14/35] Remove the prose comments this change adds Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/EditableInput.test.tsx | 2 -- src/features/messages/EditableInput.tsx | 3 --- src/features/messages/MessageComposer.test.tsx | 8 -------- src/features/messages/MessageComposer.tsx | 7 ------- src/features/messages/RichComposerInput.tsx | 3 --- src/features/messages/composer-document.test.ts | 4 ---- src/features/messages/composer-dom.ts | 1 - src/features/messages/composer-markdown.ts | 6 ------ src/features/messages/mention-draft.test.ts | 2 -- src/features/messages/mention-draft.ts | 1 - src/features/solo/chat-title.test.ts | 2 -- src/features/solo/chat-title.ts | 2 -- 12 files changed, 41 deletions(-) diff --git a/src/features/messages/EditableInput.test.tsx b/src/features/messages/EditableInput.test.tsx index 716c37fa50..7c0535eb2e 100644 --- a/src/features/messages/EditableInput.test.tsx +++ b/src/features/messages/EditableInput.test.tsx @@ -5031,7 +5031,6 @@ describe("group chip", () => { 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); @@ -5093,7 +5092,6 @@ describe("group chip", () => { })); 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)); diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index 01ad72f5fb..a409d7b404 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -1131,8 +1131,6 @@ export function EditableInput({ return true; const added = recipients.filter((person) => !existing.has(person.pubkey)); const tr = closeHistory(editor.state.tr); - // A group's members share its chip: the chip keeps the members still - // requested, and is plain text without them. Attributes keep positions. for (const token of source.tokens) { const group = composerGroup( token.node.attrs.group, @@ -2622,7 +2620,6 @@ export function EditableInput({ ...node.attrs, recipient: null, }); - // A group drops the member; without members it is plain text. const group = composerGroup(node.attrs.group, node.attrs.source); if (group?.members.some((m) => m.pubkey === pubkey)) { const members = group.members.filter((m) => m.pubkey !== pubkey); diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index ceded8459b..602a353e16 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -8243,7 +8243,6 @@ it("rejects overlong and over-limit tool edits without changing accepted intent" act(() => { 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; @@ -8789,7 +8788,6 @@ 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, @@ -12667,7 +12665,6 @@ 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[], @@ -12686,16 +12683,13 @@ it("a labelled mentions edit is one chip, sent as `@label` with each member once await h.user.keyboard("{Enter}"); expect(h.input()).toHaveValue("@Crew "); expect( - // The namesakes' names say which key each one is. screen.getByRole("img", { name: "Group 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}) `, ); @@ -12714,7 +12708,6 @@ it("a labelled mentions edit inside Markdown code is only its name", async () => }); it.each([ ["Crew", "@Crew "], - // An edit is Markdown, so the label goes in escaped, as a chip sends it. ["*ops*", "@\\*ops\\* "], ])( "a labelled mentions edit while editing a sent message adds only its text (%s)", @@ -12766,7 +12759,6 @@ it("a person in a chip and also mentioned alone is one reference outside a DM", 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"])( diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index d018e95ba2..3277fa31a8 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -2116,7 +2116,6 @@ function Composer({ function keepProseCaret(add: (at: CompletionQuery) => boolean, focus = true) { const before = valueRef.current; let start = 0; - // 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]), @@ -2138,7 +2137,6 @@ function Composer({ if (focus) input.current?.focus(); return true; } - /** With `label`, one chip `@label` stands for all of `recipients`. */ function insertMentions( recipients: readonly MentionRecipient[], range?: CompletionQuery, @@ -2173,7 +2171,6 @@ function Composer({ input.current.readOnly ) return false; - // In code only the text goes in, as in a message edit. if (label !== undefined && range && inMarkdownCode(range)) return insert(`@${label} `, undefined, range); // Message edits only add references, never new notification intent. @@ -2222,9 +2219,6 @@ 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 @@ -2966,7 +2960,6 @@ function Composer({ fromPill, )); } else if (recipients.length) { - // A person in several chips, or also mentioned alone, is offered once. const people = distinctRecipients(captured.recipients); // An agent only an earlier Buzz runs would not answer; offer it here first. const lookup = oldAgents.find(people); diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index f23026e00e..3c7f07917e 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -106,8 +106,6 @@ 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, @@ -405,7 +403,6 @@ export function RichComposerInput({ const preview = gifPreviews.get(start); if (preview && preview.end === end && !mention) return { start, end, editAsText: false, content: preview.content }; - // A group's members share its span: one chip, counting them. const people = draft.recipients.filter( (item) => item.start === start && item.label !== undefined, ); diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 2d102033c4..c13a806018 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -736,7 +736,6 @@ describe("inline formatting batch", () => { null, marks.map((name) => schema.marks[name].create()), ); - // What a reader's Markdown renders: the node kinds and the text. const rendered = (markdown: string) => { const kinds = new Set(); let text = ""; @@ -769,7 +768,6 @@ describe("inline formatting batch", () => { kinds: ["root", "paragraph", "emphasis", "text"], text: "@eng_ios hi", }); - // Emphasis beside an escaped label still pairs only its own delimiters. expect( rendered( serialize( @@ -782,7 +780,6 @@ describe("inline formatting batch", () => { kinds: ["root", "paragraph", "text", "emphasis"], text: "@eng*b*", }); - // A link escapes its own text, once. const linked = schema.nodes.token.create( { source: "@eng_ios", group: { label: "eng_ios", members } }, null, @@ -792,7 +789,6 @@ describe("inline formatting batch", () => { kinds: ["root", "paragraph", "link", "text"], text: "@eng_ios", }); - // Code shows its text as is. expect(serialize(chip("eng_ios", "code"))).toBe("`@eng_ios`"); }); it("trusts a group chip only with a one-line label", () => { diff --git a/src/features/messages/composer-dom.ts b/src/features/messages/composer-dom.ts index 87ec2461dd..5469d90f86 100644 --- a/src/features/messages/composer-dom.ts +++ b/src/features/messages/composer-dom.ts @@ -105,7 +105,6 @@ export type ComposerInputElement = HTMLDivElement & { setSelectionRange(start: number, end: number, direction?: string): void; insertText( text: string, - /** 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 diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index 882739357b..73c6ff8a6f 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -50,8 +50,6 @@ strike.peek = () => "~"; export const groupLabelMarkdown = (label: string) => `@${label.replace(/[\\`*_[\]<~]/g, "\\$&")}`; -/** A group's label comes from a plugin, so a chip sends it escaped: it renders - * as the label the chip shows. Code shows it as is; a link escapes its text. */ const groupChip = (node: EditorNode) => node.attrs.group && !composerSchema.marks.code.isInSet(node.marks) && @@ -103,7 +101,6 @@ function qualifyNamesakes(doc: EditorNode): EditorNode { composerSchema.marks.recipient.isInSet(node?.marks ?? [])?.attrs; const keys = new Map>(); doc.descendants((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 @@ -338,9 +335,6 @@ function paragraphMarkdown( : node.attrs.source; if (composerSchema.marks.literal.isInSet(node.marks)) literals.push({ start, end: text.length }); - // A group chip's @label arrives escaped (see composerMarkdown) and is - // protected like a recipient's exact name, so it is never escaped again or - // paired as emphasis. if ( node.attrs.recipient || node.attrs.group || diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 660d1cbcfc..abb31a11f1 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -265,10 +265,8 @@ it("keeps a group's members only on the exact text `@label`", () => { { ...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); }); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 7afa4fe01a..019e1b0eb8 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -15,7 +15,6 @@ export type DraftRecipient = MentionRecipient & export const distinctRecipients = ( recipients: readonly T[], ) => [...new Map(recipients.map((item) => [item.pubkey, item])).values()]; -/** `recipients` up to the first 32 distinct people, keeping all their spans. */ function capRecipients(recipients: readonly T[]) { const kept = new Set(); return recipients.filter((item) => { diff --git a/src/features/solo/chat-title.test.ts b/src/features/solo/chat-title.test.ts index d9a667ee01..a141e889af 100644 --- a/src/features/solo/chat-title.test.ts +++ b/src/features/solo/chat-title.test.ts @@ -93,13 +93,11 @@ it("keeps a leading group tag, so Solo naming matches the sent text", () => { ), ); expect(title("@crew do X", "crew")).toBe("@crew do X"); - // The sent text tags no one named `@crew`, so its reading keeps the label too. expect( isStartingChatTitle(title("@crew do X", "crew"), { text: "@crew do X", recipients: [], }), ).toBe(true); - // A label that starts with a member's name is never cut at that name. expect(title("@Ann's team do X", "Ann's team")).toBe("@Ann's team do X"); }); diff --git a/src/features/solo/chat-title.ts b/src/features/solo/chat-title.ts index aa0a6534bd..519732402a 100644 --- a/src/features/solo/chat-title.ts +++ b/src/features/solo/chat-title.ts @@ -35,8 +35,6 @@ function chatTitle( for (const recipient of [...draft.recipients].sort( (a, b) => a.start - b.start, )) { - // A group's `@label` stays: Solo naming rereads the sent text, where it - // names no tagged person. if (recipient.label !== undefined) break; if ( recipient.start < draftStart || From 1ac9b9aeb7c1976aff7bfe90dd269049b26490d2 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 14:24:39 -0500 Subject: [PATCH 15/35] Infer the group helpers' return types Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/composer-document.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 33c136250c..49d425cf1d 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -224,10 +224,7 @@ export type ComposerGroup = Readonly<{ /** 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 { +export function composerGroup(value: unknown, source: unknown) { if (!value || typeof value !== "object") return null; const { label, members } = value as Record; if ( @@ -255,7 +252,7 @@ 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, ); From ba160730f81c687bc92172ab0439c890c5b91717 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Thu, 19 Nov 2026 00:30:45 -0500 Subject: [PATCH 16/35] Register supplements through their own method A provider with `supplement: true` passed to `registerCompletion` on a host without supplements is an ordinary provider there: with a lower `order` than the host's mentions it owns the `@` caret and hides the people rows. `registerCompletionSupplement` is the only way to register a supplement, and `registerCompletion` refuses one, so a plugin calls it as `registerCompletionSupplement?.()` and registers nothing on a host that lacks it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 5 +++- src/features/conversation/contracts.ts | 3 +- src/features/conversation/service.test.tsx | 35 ++++++++++++++++++++++ src/features/conversation/service.tsx | 18 ++++++++++- 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 32e1988c86..24a007ac3b 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3159,7 +3159,10 @@ 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 +A provider registered with `ctx.conversation.registerCompletionSupplement(provider)` +never owns the caret. Hosts without supplements lack that method, so a plugin +calls it with `?.` and adds nothing on them. `registerCompletion` refuses +`supplement`, so that method is the only way to register one. 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 diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 85524274f7..f77c7762b7 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -447,7 +447,8 @@ export type ComposerCompletion = Readonly<{ id: string; title: string; order?: number; - /** Adds rows beside the provider that owns the caret when this one's match + /** Set only by `registerCompletionSupplement`; `registerCompletion` refuses + * it. 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 diff --git a/src/features/conversation/service.test.tsx b/src/features/conversation/service.test.tsx index 621140d3a1..2bc0b8cbb1 100644 --- a/src/features/conversation/service.test.tsx +++ b/src/features/conversation/service.test.tsx @@ -413,6 +413,41 @@ it("owns completion registration through disable, replacement and failed activat ); expect(broken.service.completions.snapshot()).toHaveLength(0); }); +it("makes a supplement only through registerCompletionSupplement", async () => { + const provider = { + title: "Rows", + match: () => null, + component: Component, + }; + const h = harness({ + inject: ["conversation"], + apply(ctx) { + ctx.conversation.registerCompletion({ ...provider, id: "owner" }); + ctx.conversation.registerCompletionSupplement({ + ...provider, + id: "rows", + }); + expect(() => + ctx.conversation.registerCompletion({ + ...provider, + id: "refused", + supplement: true, + }), + ).toThrow("registerCompletionSupplement"); + }, + }); + h.runtime.reconcile([h.plugin]); + await vi.waitFor(() => + expect( + h.service.completions + .snapshot() + .map(({ id, supplement }) => [id, supplement === true]), + ).toEqual([ + ["owner", false], + ["rows", true], + ]), + ); +}); it.each([ [emoji, ["typeahead"]], [mentions, ["typeahead", "folders", "skills"]], diff --git a/src/features/conversation/service.tsx b/src/features/conversation/service.tsx index b4c52ea808..d7cdbcdf4a 100644 --- a/src/features/conversation/service.tsx +++ b/src/features/conversation/service.tsx @@ -82,6 +82,9 @@ export type Conversation = { registerTool(tool: ComposerTool): void; completions: ContributionReader; registerCompletion(provider: ComposerCompletion): void; + /** Registers `provider` with `supplement: true`. Hosts without supplements + * lack this method, so plugins call it as `registerCompletionSupplement?.()`. */ + registerCompletionSupplement(provider: ComposerCompletion): void; annotators: ContributionReader; /** Marks on the focused composer's prose; see `ComposerAnnotator`. */ registerAnnotator(annotator: ComposerAnnotator): void; @@ -397,10 +400,23 @@ export class ConversationService extends Service implements Conversation { this.toolEntries.register(this.ctx, value); } registerCompletion(value: ComposerCompletion) { + if (value?.supplement !== undefined) + throw new Error( + "Register a supplement with registerCompletionSupplement", + ); + this.addCompletion(value); + } + registerCompletionSupplement(value: ComposerCompletion) { + this.addCompletion(value, true); + } + private addCompletion(value: ComposerCompletion, supplement?: true) { validate(value); if (typeof value.match !== "function") throw new Error("A completion provider needs a matcher"); - this.completionEntries.register(this.ctx, value); + this.completionEntries.register( + this.ctx, + supplement ? { ...value, supplement } : value, + ); } registerAnnotator(value: ComposerAnnotator) { validate(value); From 9ca9599c77e132836adb26b2f7d836de7b714926 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 04:51:33 +0000 Subject: [PATCH 17/35] fix(composer): keep a group one chip only when its label reads as one A picked group stays one chip only when its label is letters, digits and spaces and no member or recipient already in the draft has a name that a reader would bind inside `@label`. Each name is checked alone. Otherwise the pick inserts the members as person chips. Group members keep `explicit` through the draft, as a picked person does, so a send records the owner mention for them too. An opened group chip stays one chip, and a group can be picked inside link text. Code still takes only the label text. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/EditableInput.tsx | 5 +- .../messages/MessageComposer.test.tsx | 256 +++++++++++++++++- src/features/messages/MessageComposer.tsx | 22 +- .../messages/MessageMarkdown.test.tsx | 54 +++- .../messages/composer-document.test.ts | 32 +++ src/features/messages/composer-document.ts | 36 ++- tests/browser/completion-work.spec.mjs | 8 +- tests/fixtures/mentions.tsx | 3 + 8 files changed, 391 insertions(+), 25 deletions(-) diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index 06d5275bb7..a3125b5ccd 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -1087,8 +1087,9 @@ export function EditableInput({ const source = projection(); const inside = source.tokens.filter( (token) => - (start > token.start && start < token.end) || - (end > token.start && end < token.end), + !token.node.attrs.group && + ((start > token.start && start < token.end) || + (end > token.start && end < token.end)), ); if (!inside.length) return; const tr = editor.state.tr; diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index ff68d90b16..443cf634e4 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -225,6 +225,10 @@ function mount( viewer?: string, agents?: Agents, task?: ChannelMessage, + match: ComposerCompletion["match"] = ({ text, start }) => + text.startsWith("!") && start > 0 + ? { start: 0, end: start, query: text.slice(1, start) } + : null, ) { let commands: ComposerToolProps; const completionRequests: ComposerCompletionProps["publish"][] = []; @@ -241,10 +245,7 @@ function mount( pluginId: "test", revision, title: "Delayed", - match: ({ text, start }) => - text.startsWith("!") && start > 0 - ? { start: 0, end: start, query: text.slice(1, start) } - : null, + match, component: Completion, }); let completions: readonly Contribution[] = [ @@ -13291,6 +13292,12 @@ it("batch insertion rejects an unavailable member atomically and does not send o expect(h.messages.send).not.toHaveBeenCalled(); expect(screen.getByRole("alert")).toHaveTextContent("no longer available"); }); +const bangAnywhere: ComposerCompletion["match"] = ({ text, start }) => { + const at = text.lastIndexOf("!", start - 1); + return at >= 0 && /^$|[\s`]$/.test(text.slice(0, at).slice(-1)) + ? { start: at, end: start, query: text.slice(at + 1, start) } + : null; +}; function offerCrew( h: ReturnType, mentions: readonly MentionRecipient[], @@ -13324,19 +13331,120 @@ it("a labelled mentions edit is one chip, sent as `@label` with each member once second.pubkey, ]); }); -it("a labelled mentions edit inside Markdown code is only its name", async () => { +it("a selection offset inside a group chip keeps it one chip that notifies every member", async () => { const h = mount(); - h.fill("!`Crew`"); + h.fill("!Crew"); offerCrew(h, [first, second]); await h.user.keyboard("{Enter}"); - expect(h.input()).toHaveValue("@Crew "); + act(() => h.input().setSelectionRange(2, 2)); + fireEvent(document, new Event("selectionchange")); + expect( + screen.getByRole("img", { + name: "Group Crew, 2 recipients: Honey · rcaj, Honey · 04hu", + }), + ).toBeVisible(); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe("@Crew "); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([ + first.pubkey, + second.pubkey, + ]); +}); +it("deleting a group chip after a selection offset inside it, or removing a member, still updates who is notified", async () => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [first, second]); + await h.user.keyboard("{Enter}"); + act(() => h.input().setSelectionRange(2, 2)); + act(() => h.input().removeRecipient(first.pubkey)); + expect(h.commands().recipients.map(({ pubkey }) => pubkey)).toEqual([ + second.pubkey, + ]); + act(() => h.input().setSelectionRange(0, 5)); + await h.user.keyboard("{Backspace}"); expect(h.commands().recipients).toEqual([]); + expect(screen.queryByRole("img", { name: /^Group Crew/ })).toBeNull(); }); +it.each([ + [ + "a group", + { mentions: [first, second], label: "Crew" }, + [first.pubkey, second.pubkey], + ], + ["a person", { mention: first }, [first.pubkey]], +])( + "picking %s inside link text keeps its recipients", + async (_, edit, notified) => { + const h = mount( + {}, + undefined, + undefined, + undefined, + undefined, + bangAnywhere, + ); + const label = "go !Crew now"; + await h.user.type(h.input(), label); + act(() => h.input().setSelectionRange(0, label.length)); + act(() => void h.input().editLink()?.save(label, "https://example.test/")); + act(() => h.input().setSelectionRange(8, 8)); + fireEvent(document, new Event("selectionchange")); + expect(h.input().querySelector("a")).not.toBeNull(); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "pick", label: "Pick", edit }], + }); + }); + await h.user.keyboard("{Enter}"); + expect(h.input().querySelector("a [data-source]")).not.toBeNull(); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual(notified); + }, +); +it.each([ + ["a code span", "Crew", "see `run !Crew` now", "see `run @Crew ` now"], + ["a fenced block", "Crew", "```\nrun !Crew\n```", "```\nrun @Crew \n```"], + [ + "a code span", + "Honey team", + "see `run !Crew` now", + "see `run @Honey team ` now", + ], +])( + "a labelled mentions edit inside %s is only its name (%s)", + async (_, label, text, sent) => { + const h = mount( + {}, + undefined, + undefined, + undefined, + undefined, + bangAnywhere, + ); + h.fill(text); + const caret = text.indexOf("!Crew") + "!Crew".length; + act(() => h.input().setSelectionRange(caret, caret)); + fireEvent(document, new Event("selectionchange")); + offerCrew(h, [first, second], label); + await h.user.keyboard("{Enter}"); + expect(h.input()).toHaveValue(sent); + expect(h.commands().recipients).toEqual([]); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe(sent); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([]); + }, +); it.each([ ["Crew", "@Crew "], - ["*ops*", "@\\*ops\\* "], + [ + "*ops*", + "[@Honey](nostr:npub1424242424242424242424242424242424242424242424242424qamrcaj) [@Honey](nostr:npub1hwamhwamhwamhwamhwamhwamhwamhwamhwamhwamhwamhwamhwasxw04hu) ", + ], ])( - "a labelled mentions edit while editing a sent message adds only its text (%s)", + "a labelled mentions edit while editing a sent message adds text and no recipients (%s)", async (label, text) => { const h = mount({}, undefined, first.pubkey); h.setRows([editableMessage()]); @@ -18300,3 +18408,133 @@ it("pastes a copied forward literally inside a code block", async () => { screen.queryByRole("button", { name: "Remove forwarded message" }), ).not.toBeInTheDocument(); }); + +const groupLabelMatrix = [ + ...[..."*_`~[]<>|#\\&!=:@"].flatMap((c) => [`x${c}y`, `${c}${c}x`]), + "Design Team", + "R&D ©", + "ops ||tier 2||", + "eng_ios", + "a_b_c", + "*ops*", + "_ops_", + "a`b", + "x](https://evil.example)[y", + "[x](https://evil.example)", + "![x](https://evil.example/x.png)", + "", + "x", + "https://evil.example", + "www.evil.example", + "buzz://channel/x", + "a@b.co", + ":party_parrot:", + "a~~b~~", + "1. x", + "- x", + "> x", + "trailing\\", + "x|", + "Ops:", + "x:y", + "Honey's team", + "Honey team", + "Honey", + "Crew", + "ops @Honey", + "Oncall #general", + "[x](https:evil.example)", + "Team example.com", + "b.co", + "x www.example.com", + "a`b`c", + "x :party_parrot:", + "x mailto:y", + "x xmpp:y", + "R&D", + "Dev/Ops", + "Ops (EU)", + "Launch crew", + "eng-oncall", + "Other team", +]; +const oneChipLabels = new Set([ + "Design Team", + "Crew", + "Launch crew", + "Other team", +]); +async function pickSent(edit: { + mentions: MentionRecipient[]; + label?: string; +}) { + const h = mount(); + h.fill("!Crew"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "crew", label: "Crew", edit }], + }); + }); + await h.user.keyboard("{Enter}"); + const chips = screen + .queryAllByRole("img") + .map((node) => node.getAttribute("aria-label")); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + const [, content, tags] = h.messages.send.mock.calls[0] ?? []; + cleanup(); + return { chips, content, tags }; +} +it.each(groupLabelMatrix)( + "a group picked with the label %s is one chip only when the label is plain text and starts with no member's name", + async (label) => { + const group = await pickSent({ mentions: [first, second], label }); + expect(group.tags).toEqual([first.pubkey, second.pubkey]); + if (oneChipLabels.has(label)) { + expect(group.content).toBe(`@${label} `); + expect(group.chips).toEqual([ + `Group ${label}, 2 recipients: Honey · rcaj, Honey · 04hu`, + ]); + } else { + expect(group).toEqual(await pickSent({ mentions: [first, second] })); + expect(group.chips.some((name) => name?.startsWith("Group"))).toBe(false); + } + }, +); + +it.each([true, false])( + "a group label that starts with the name of a person already in the draft is its members (person in the draft: %s)", + async (withPerson) => { + const h = mount( + {}, + undefined, + undefined, + undefined, + undefined, + bangAnywhere, + ); + if (withPerson) { + h.fill("!H"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "honey", label: "Honey", edit: { mention: first } }], + }); + }); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("!Crew"); + } else h.fill("!Crew"); + offerCrew(h, [{ ...second, name: "Wes" }], "Honey crew"); + await h.user.keyboard("{Enter}"); + expect( + screen.queryAllByRole("img", { name: /^Group Honey crew/ }), + ).toHaveLength(withPerson ? 0 : 1); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe( + withPerson ? "@Honey @Wes " : "@Honey crew ", + ); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual( + withPerson ? [first.pubkey, second.pubkey] : [second.pubkey], + ); + }, +); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 1912630938..b28b8cac8e 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -52,6 +52,7 @@ import { readComposerSnapshot, composerMarkdownContext, markdownRanges, + groupLabelHolds, } from "./composer-document"; import { useMessageEdit, lastEditableMessage } from "./useMessageEdit"; import { editMentionText } from "./message-edit"; @@ -2445,7 +2446,7 @@ function Composer({ function insertMentions( recipients: readonly MentionRecipient[], range?: CompletionQuery, - label?: string, + requested?: string, ) { if ( !Array.isArray(recipients) || @@ -2460,6 +2461,14 @@ function Composer({ ) ) return false; + const label = + requested !== undefined && + groupLabelHolds(requested, [ + ...recipients, + ...valueRef.current.recipients, + ]) + ? requested + : undefined; const unique = [ ...new Map( recipients.map((person) => [person.pubkey, editorMention(person)]), @@ -2478,8 +2487,8 @@ function Composer({ input.current.readOnly ) return false; - if (label !== undefined && range && inMarkdownCode(range)) - return insert(`@${label} `, undefined, range); + if (requested !== undefined && range && inMarkdownCode(range, false)) + return insert(`@${requested} `, undefined, range); // Message edits only add references, never new notification intent. if (editing.target) return insert( @@ -2526,10 +2535,13 @@ function Composer({ setError(undefined); return true; } - function inMarkdownCode(range: Readonly<{ start: number; end: number }>) { + function inMarkdownCode( + range: Readonly<{ start: number; end: number }>, + links = true, + ) { const doc = readComposerSnapshot(valueRef.current.document); const context = doc - ? composerMarkdownContext(doc) + ? composerMarkdownContext(doc, undefined, links) : { text: valueRef.current.text, protected: [] }; return [...context.protected, ...markdownRanges(context.text).literal].some( (r) => range.start < r.end && range.end > r.start, diff --git a/src/features/messages/MessageMarkdown.test.tsx b/src/features/messages/MessageMarkdown.test.tsx index b262e8a018..82967e2df4 100644 --- a/src/features/messages/MessageMarkdown.test.tsx +++ b/src/features/messages/MessageMarkdown.test.tsx @@ -30,7 +30,8 @@ import { LinkLabel } from "../../bundled/links/InlineLink"; import { MessageMarkdown } from "./MessageMarkdown"; import { serializeSelection } from "./selection-copy"; import { buzzCopyDocument } from "./composer-clipboard"; -import { projectComposerDocument } from "./composer-document"; +import { composerSchema, projectComposerDocument } from "./composer-document"; +import { composerMarkdown } from "./composer-markdown"; import { createRelaySession } from "../relay/session"; import { createAgentDirectory } from "../identity-names/testing"; import { bindNames } from "../identity-names/service"; @@ -1698,3 +1699,54 @@ it("renders frozen forwarded mention labels without source profiles or notificat expect(html).not.toContain(`(${other})`); expect(html).toContain("data-mention-kind"); }); + +const markdownSyntax = [..."*_`~[]<>|#\\&!=:@"]; +it.each([ + ...markdownSyntax.map((character) => `x${character}y`), + "R&D ©", + "ops ||tier 2||", + "x](https://evil.example)[y", + "[x](https://evil.example)", + "![x](https://evil.example/x.png)", + "", + "x", + "https://evil.example", + "www.evil.example", + "a@b.co", + ":party_parrot:", + "trailing\\", +])( + "a group chip labelled %s inside link text renders its label verbatim, with no nested link, code, image or spoiler from the label", + (label) => { + const href = "https://example.test/notes"; + const members = [smith, other].map((pubkey) => ({ + pubkey, + name: profiles.get(pubkey)?.name ?? "", + })); + const { draft } = projectComposerDocument( + composerSchema.nodes.doc.create(null, [ + composerSchema.nodes.paragraph.create(null, [ + composerSchema.nodes.token.create( + { source: `@${label}`, group: { label, members } }, + null, + [composerSchema.marks.link.create({ href })], + ), + composerSchema.text(" hi"), + ]), + ]), + ); + const { container } = renderDom( + , + ); + expect(container.textContent).toBe(`@${label} hi`); + const links = container.querySelectorAll("a"); + expect(links).toHaveLength(1); + expect(links[0]).toHaveAttribute("href", href); + expect(links[0]).toHaveTextContent(`@${label}`); + expect( + container.querySelector("a a, code, img, [data-spoiler]"), + ).toBeNull(); + }, +); diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index ae8439589d..6c0bafcc04 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -854,3 +854,35 @@ it.each(["chat", "document"] as const)( expect(readComposerDocument(draft, []).eq(original)).toBe(true); }, ); + +it("a group chip's members keep `explicit` through a saved draft, as a person chip does", () => { + const ann = { pubkey: "a".repeat(64), name: "Ann", explicit: true as const }; + const bo = { pubkey: "b".repeat(64), name: "Bo", explicit: true as const }; + const saved = mentionDraft( + projectComposerDocument( + doc( + paragraph( + schema.nodes.token.create({ + source: "@Crew", + group: { label: "Crew", members: [ann, bo] }, + }), + schema.text(" "), + schema.nodes.token.create({ source: "@Ann", recipient: ann }), + ), + ), + ).draft, + ); + expect( + projectComposerDocument( + readComposerDocument(saved, []), + ).draft.recipients.map(({ pubkey, label, explicit }) => [ + pubkey, + label, + explicit, + ]), + ).toEqual([ + [ann.pubkey, "Crew", true], + [bo.pubkey, "Crew", true], + [ann.pubkey, undefined, true], + ]); +}); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 5337ac92ae..239a1eff0d 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -14,6 +14,7 @@ import type { PendingMention, } from "./mention-draft"; import type { ComposerResource } from "../conversation/contracts"; +import { profileMentionParts } from "./profile-mentions"; import { chipLabel, composerToken, @@ -297,6 +298,26 @@ export function composerGroup(value: unknown, source: unknown) { return null; return value as ComposerGroup; } +/** Whether `@label` reads as one group to whoever gets it: plain text in + * which the reader binds none of `people`'s names, each taken alone. */ +export function groupLabelHolds( + label: string, + people: readonly MentionRecipient[], +) { + return ( + /^[\p{L}\p{N} ]+$/u.test(label) && + !people.some((person) => + profileMentionParts( + { + content: `@${label}`, + mentions: [person.pubkey], + mentionLabels: [{ id: person.pubkey, names: [person.name] }], + }, + undefined, + ).some((part) => part.target), + ) + ); +} /** 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( @@ -317,7 +338,10 @@ export function tokenRecipients( const members = new Map( on .filter((item) => item.label === label) - .map(({ pubkey, name }) => [pubkey, { pubkey, name }]), + .map(({ pubkey, name, explicit }) => [ + pubkey, + { pubkey, name, ...(explicit ? { explicit } : {}) }, + ]), ); return { recipient: null, @@ -625,11 +649,12 @@ function project(doc: EditorNode) { }); const group = composerGroup(node.attrs.group, node.attrs.source); if (group) - for (const { pubkey, name } of group.members) + for (const { pubkey, name, explicit } of group.members) recipients.push({ pubkey, name, label: group.label, + ...(explicit ? { explicit } : {}), start, end: text.length, }); @@ -686,6 +711,7 @@ function project(doc: EditorNode) { export function composerMarkdownContext( doc: EditorNode, source = projectComposerDocument(doc), + links = true, ) { let text = source.draft.text; const protectedRanges: SourceRange[] = []; @@ -698,6 +724,7 @@ export function composerMarkdownContext( text.slice(start, end).replace(/[^\r\n]/g, "x") + text.slice(end); }; + const { code, link, literal } = composerSchema.marks; doc.descendants((node, position) => { if (node.type.name === "markdown_table") { mask(position, position + node.nodeSize); @@ -709,9 +736,8 @@ export function composerMarkdownContext( } if ( node.isInline && - (["code", "link", "literal"] as const).some((name) => - composerSchema.marks[name].isInSet(node.marks), - ) + (code.isInSet(node.marks) || + (link.isInSet(node.marks) ? links : literal.isInSet(node.marks))) ) mask(position, position + node.nodeSize); }); diff --git a/tests/browser/completion-work.spec.mjs b/tests/browser/completion-work.spec.mjs index b9515d9181..de31a79694 100644 --- a/tests/browser/completion-work.spec.mjs +++ b/tests/browser/completion-work.spec.mjs @@ -315,14 +315,16 @@ test("completed, dismissed and refuted mention searches stay closed while fresh expect(await searches()).not.toContainEqual(expect.stringContaining("Zed ")); }); -for (const row of ["people", "supplement"]) { +for (const row of ["people", "supplement", "group"]) { test(`a ${row} row proves the owner's mention only from a person's pick`, async ({ page, }) => { await page.addInitScript(() => { localStorage.setItem("buzz-remember-mentioned-agents.v1", "off"); }); - await page.goto("/tests/fixtures/mentions.html?supplement"); + await page.goto( + `/tests/fixtures/mentions.html?supplement=${row === "group" ? "group" : ""}`, + ); const input = page.getByRole("textbox", { name: "Message #General" }); await expect .poll(() => page.evaluate(() => window.mentionFixture.list().status)) @@ -340,7 +342,7 @@ for (const row of ["people", "supplement"]) { if (trusted) await pick.click(); else await pick.dispatchEvent("click"); await expect(input.locator(".inline-chip")).toHaveCount( - row === "people" ? 1 : 2, + row === "supplement" ? 2 : 1, ); const count = await page.evaluate( () => window.mentionFixture.publications.length, diff --git a/tests/fixtures/mentions.tsx b/tests/fixtures/mentions.tsx index fdf0ab8793..fdeac731cb 100644 --- a/tests/fixtures/mentions.tsx +++ b/tests/fixtures/mentions.tsx @@ -376,6 +376,9 @@ const plugins = createPluginManager(context, { { pubkey: first.pubkey, name: "Honey" }, { pubkey: second.pubkey, name: "Honey" }, ], + ...(supplement === "group" + ? { label: "Crew" } + : {}), }, }, ], From 891236009b1434c48a5d7b74898055ef41db06e9 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 05:42:38 +0000 Subject: [PATCH 18/35] fix(composer): allow hyphens and combining marks in a group label A group label may hold combining marks, so labels in scripts such as Devanagari and Thai, and accents typed as two characters, stay one chip. A hyphen may sit between two letters or digits, so `eng-oncall` stays one chip. A leading, trailing, doubled or spaced hyphen still inserts the members. Every label the gate keeps is plain text, so the Markdown escape for a group chip's label is gone, and a message edit inserts `@label` as is. A person chip rebuilt from the draft text, as when inline code is turned off again, keeps the whole draft recipient, as on main. So it keeps `explicit`, and the send records the owner mention for it. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 12 ++- src/features/conversation/contracts.ts | 5 +- .../messages/MessageComposer.test.tsx | 97 ++++++++----------- src/features/messages/MessageComposer.tsx | 4 +- .../messages/MessageMarkdown.test.tsx | 54 +---------- .../messages/composer-document.test.ts | 79 +++------------ src/features/messages/composer-document.ts | 16 ++- src/features/messages/composer-markdown.ts | 17 +--- 8 files changed, 77 insertions(+), 207 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index e79c25bddc..aa5f3f200d 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3487,9 +3487,15 @@ 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. 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 +text `@label`, with one `p` tag per mention. The host keeps a label only when +readers will see it as that text. It must be letters, digits and spaces, with a +hyphen allowed between two letters or digits. And no name of its mentions, or of +a recipient already in the draft, may read as a mention inside `@label`: +`Honey team` with a member Honey would show as `@Honey`. Otherwise the label is +dropped and each mention goes in as its own chip. In code, a labelled edit +inserts only the text `@label`. A message edit adds no recipients: it inserts +the text `@label`, or each mention's reference when the label is dropped. +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/contracts.ts b/src/features/conversation/contracts.ts index c84f40fab7..76e050afc5 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -396,7 +396,10 @@ export type CompletionEdit = | Readonly<{ mentions: readonly Readonly<{ pubkey: string; name: string }>[]; /** 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. */ + * `@label`. Kept only when it is letters, digits and spaces (a hyphen may + * sit between two letters or digits) and no name in the draft reads as a + * mention inside it; otherwise each of `mentions` is its own chip. In + * code only the text goes in, and a message edit adds no recipients. */ label?: string; text?: never; mention?: never; diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 443cf634e4..db8d9a49f2 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -13351,16 +13351,11 @@ it("a selection offset inside a group chip keeps it one chip that notifies every second.pubkey, ]); }); -it("deleting a group chip after a selection offset inside it, or removing a member, still updates who is notified", async () => { +it("deleting a group chip removes every member from who is notified", async () => { const h = mount(); h.fill("!Crew"); offerCrew(h, [first, second]); await h.user.keyboard("{Enter}"); - act(() => h.input().setSelectionRange(2, 2)); - act(() => h.input().removeRecipient(first.pubkey)); - expect(h.commands().recipients.map(({ pubkey }) => pubkey)).toEqual([ - second.pubkey, - ]); act(() => h.input().setSelectionRange(0, 5)); await h.user.keyboard("{Backspace}"); expect(h.commands().recipients).toEqual([]); @@ -18409,61 +18404,26 @@ it("pastes a copied forward literally inside a code block", async () => { ).not.toBeInTheDocument(); }); +const oneChipLabels = new Set([ + "Team 42", + "24-7", + "eng-oncall", + "a-b-c", + "हिंदी टीम", + "हिंदी-टीम", + "ทีมไทย", + "Cafe\u0301 crew", +]); const groupLabelMatrix = [ - ...[..."*_`~[]<>|#\\&!=:@"].flatMap((c) => [`x${c}y`, `${c}${c}x`]), - "Design Team", - "R&D ©", - "ops ||tier 2||", + ...oneChipLabels, "eng_ios", - "a_b_c", - "*ops*", - "_ops_", - "a`b", - "x](https://evil.example)[y", - "[x](https://evil.example)", - "![x](https://evil.example/x.png)", - "", - "x", - "https://evil.example", - "www.evil.example", - "buzz://channel/x", - "a@b.co", - ":party_parrot:", - "a~~b~~", - "1. x", - "- x", - "> x", - "trailing\\", - "x|", - "Ops:", - "x:y", - "Honey's team", + "-ops", + "ops-", + "a--b", + "a - b", "Honey team", - "Honey", - "Crew", - "ops @Honey", - "Oncall #general", - "[x](https:evil.example)", - "Team example.com", - "b.co", - "x www.example.com", - "a`b`c", - "x :party_parrot:", - "x mailto:y", - "x xmpp:y", - "R&D", - "Dev/Ops", - "Ops (EU)", - "Launch crew", - "eng-oncall", - "Other team", + "Honey-crew", ]; -const oneChipLabels = new Set([ - "Design Team", - "Crew", - "Launch crew", - "Other team", -]); async function pickSent(edit: { mentions: MentionRecipient[]; label?: string; @@ -18501,6 +18461,29 @@ it.each(groupLabelMatrix)( } }, ); +it.each(["eng-oncall", "a-b-c"])( + "a group labelled %s is still one chip after its saved draft is restored", + async (label) => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [first, second], label); + await h.user.keyboard("{Enter}"); + act(() => h.input().blur()); + h.remount(); + expect( + screen + .queryAllByRole("img") + .map((node) => node.getAttribute("aria-label")), + ).toEqual([`Group ${label}, 2 recipients: Honey · rcaj, Honey · 04hu`]); + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + expect(h.messages.send.mock.calls[0]?.[1]).toBe(`@${label} `); + expect(h.messages.send.mock.calls[0]?.[2]).toEqual([ + first.pubkey, + second.pubkey, + ]); + }, +); it.each([true, false])( "a group label that starts with the name of a person already in the draft is its members (person in the draft: %s)", diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index b28b8cac8e..802f549b96 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -199,7 +199,7 @@ import type { AnnotationMenuRequest } from "./composer-dom"; import { formatMediaTime, mediaTimeReply } from "./media-timecode"; import { RichComposerInput } from "./RichComposerInput"; import type { MessageLinkOrigin } from "./MessageRow"; -import { composerMarkdown, groupLabelMarkdown } from "./composer-markdown"; +import { composerMarkdown } from "./composer-markdown"; import type { ComposerInputElement, ComposerLinkEdit, @@ -2494,7 +2494,7 @@ function Composer({ return insert( label === undefined ? unique.map((person) => editMentionText(person)).join("") - : `${groupLabelMarkdown(label)} `, + : `@${label} `, undefined, range, ); diff --git a/src/features/messages/MessageMarkdown.test.tsx b/src/features/messages/MessageMarkdown.test.tsx index 82967e2df4..b262e8a018 100644 --- a/src/features/messages/MessageMarkdown.test.tsx +++ b/src/features/messages/MessageMarkdown.test.tsx @@ -30,8 +30,7 @@ import { LinkLabel } from "../../bundled/links/InlineLink"; import { MessageMarkdown } from "./MessageMarkdown"; import { serializeSelection } from "./selection-copy"; import { buzzCopyDocument } from "./composer-clipboard"; -import { composerSchema, projectComposerDocument } from "./composer-document"; -import { composerMarkdown } from "./composer-markdown"; +import { projectComposerDocument } from "./composer-document"; import { createRelaySession } from "../relay/session"; import { createAgentDirectory } from "../identity-names/testing"; import { bindNames } from "../identity-names/service"; @@ -1699,54 +1698,3 @@ it("renders frozen forwarded mention labels without source profiles or notificat expect(html).not.toContain(`(${other})`); expect(html).toContain("data-mention-kind"); }); - -const markdownSyntax = [..."*_`~[]<>|#\\&!=:@"]; -it.each([ - ...markdownSyntax.map((character) => `x${character}y`), - "R&D ©", - "ops ||tier 2||", - "x](https://evil.example)[y", - "[x](https://evil.example)", - "![x](https://evil.example/x.png)", - "", - "x", - "https://evil.example", - "www.evil.example", - "a@b.co", - ":party_parrot:", - "trailing\\", -])( - "a group chip labelled %s inside link text renders its label verbatim, with no nested link, code, image or spoiler from the label", - (label) => { - const href = "https://example.test/notes"; - const members = [smith, other].map((pubkey) => ({ - pubkey, - name: profiles.get(pubkey)?.name ?? "", - })); - const { draft } = projectComposerDocument( - composerSchema.nodes.doc.create(null, [ - composerSchema.nodes.paragraph.create(null, [ - composerSchema.nodes.token.create( - { source: `@${label}`, group: { label, members } }, - null, - [composerSchema.marks.link.create({ href })], - ), - composerSchema.text(" hi"), - ]), - ]), - ); - const { container } = renderDom( - , - ); - expect(container.textContent).toBe(`@${label} hi`); - const links = container.querySelectorAll("a"); - expect(links).toHaveLength(1); - expect(links[0]).toHaveAttribute("href", href); - expect(links[0]).toHaveTextContent(`@${label}`); - expect( - container.querySelector("a a, code, img, [data-spoiler]"), - ).toBeNull(); - }, -); diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 6c0bafcc04..4a8110b476 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -736,72 +736,6 @@ describe("inline formatting batch", () => { ), ).toBe("_@Honey_"); }); - it("escapes a group chip's label like prose, so it never changes the Markdown", () => { - 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()), - ); - const rendered = (markdown: string) => { - const kinds = new Set(); - let text = ""; - const visit = (node: Nodes) => { - kinds.add(node.type); - if (node.type === "text") text += node.value; - if ("children" in node) node.children.forEach(visit); - }; - visit(fromMarkdown(markdown)); - return { kinds: [...kinds], text }; - }; - expect(serialize(chip("Design Team"), schema.text(" hi"))).toBe( - "@Design Team hi", - ); - for (const label of [ - "eng_ios", - "eng*ops", - "*ops*", - "a`b", - "x](https://evil.example)[y", - "[x](https://evil.example)", - ]) - expect(rendered(serialize(chip(label), schema.text(" hi")))).toEqual({ - kinds: ["root", "paragraph", "text"], - text: `@${label} hi`, - }); - expect( - rendered(serialize(chip("eng_ios", "italic"), schema.text(" hi"))), - ).toEqual({ - kinds: ["root", "paragraph", "emphasis", "text"], - text: "@eng_ios hi", - }); - expect( - rendered( - serialize( - chip("eng*"), - schema.text("b", [schema.marks.italic.create()]), - schema.text("*"), - ), - ), - ).toEqual({ - kinds: ["root", "paragraph", "text", "emphasis"], - text: "@eng*b*", - }); - const linked = schema.nodes.token.create( - { source: "@eng_ios", group: { label: "eng_ios", members } }, - null, - [schema.marks.link.create({ href: "https://example.com" })], - ); - expect(rendered(serialize(linked))).toEqual({ - kinds: ["root", "paragraph", "link", "text"], - text: "@eng_ios", - }); - expect(serialize(chip("eng_ios", "code"))).toBe("`@eng_ios`"); - }); it("trusts a group chip only with a one-line label", () => { const members = [{ pubkey: "a".repeat(64), name: "Honey" }]; const group = (label: string) => @@ -886,3 +820,16 @@ it("a group chip's members keep `explicit` through a saved draft, as a person ch [ann.pubkey, undefined, true], ]); }); + +it("a person chip keeps `explicit` when it is rebuilt from the draft text", () => { + const ann = { pubkey: "a".repeat(64), name: "Ann", explicit: true as const }; + const draft = mentionDraft({ + text: "@Ann ", + recipients: [{ ...ann, start: 0, end: 4 }], + }); + expect( + projectComposerDocument( + readComposerDocument(draft, [{ start: 0, end: 4 }]), + ).draft.recipients.map(({ pubkey, explicit }) => [pubkey, explicit]), + ).toEqual([[ann.pubkey, true]]); +}); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 239a1eff0d..2d0ea6ff5a 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -298,14 +298,17 @@ export function composerGroup(value: unknown, source: unknown) { return null; return value as ComposerGroup; } -/** Whether `@label` reads as one group to whoever gets it: plain text in - * which the reader binds none of `people`'s names, each taken alone. */ +/** Whether `@label` reads as one group to whoever gets it: letters, digits + * and spaces, a hyphen only between two of them, in which the reader binds + * none of `people`'s names, each taken alone. */ export function groupLabelHolds( label: string, people: readonly MentionRecipient[], ) { return ( - /^[\p{L}\p{N} ]+$/u.test(label) && + /^(?:[\p{L}\p{M}\p{N} ]|(?<=[\p{L}\p{M}\p{N}])-(?=[\p{L}\p{N}]))+$/u.test( + label, + ) && !people.some((person) => profileMentionParts( { @@ -329,12 +332,7 @@ export function tokenRecipients( (item) => item.start === range.start && item.end === range.end, ); const label = on.find((item) => item.label !== undefined)?.label; - const one = on[0]; - if (label === undefined) - return { - recipient: one ? { pubkey: one.pubkey, name: one.name } : null, - group: null, - }; + if (label === undefined) return { recipient: on[0] ?? null, group: null }; const members = new Map( on .filter((item) => item.label === label) diff --git a/src/features/messages/composer-markdown.ts b/src/features/messages/composer-markdown.ts index ab79ef98bd..904183e6f8 100644 --- a/src/features/messages/composer-markdown.ts +++ b/src/features/messages/composer-markdown.ts @@ -46,21 +46,6 @@ const strike: Handle & { peek?: Handle } = (node, parent, state, info) => { strike.peek = () => "~"; export type ComposerMarkdownMode = "chat" | "document"; -/** A group chip's `@label` as Markdown prose: the characters that can open - * inline Markdown are escaped, so it renders as the label. */ -export const groupLabelMarkdown = (label: string) => - `@${label.replace(/[\\`*_[\]<~]/g, "\\$&")}`; - -const groupChip = (node: EditorNode) => - node.attrs.group && - !composerSchema.marks.code.isInSet(node.marks) && - !composerSchema.marks.link.isInSet(node.marks) - ? node.type.create( - { ...node.attrs, source: groupLabelMarkdown(node.attrs.group.label) }, - null, - node.marks, - ) - : node; /** Plain portions are authored Markdown, not rich-editor literal text. Keeping * their source verbatim avoids normalizing formats this slice does not edit. @@ -78,7 +63,7 @@ export function composerMarkdown( node.type.name === "token" && node.attrs.semantic ? node.mark(composerSchema.marks.literal.create().addToSet(node.marks)) : node.isLeaf - ? groupChip(node) + ? node : node.copy(Fragment.fromArray(node.content.content.map(project))); const doc = project(readComposerDocument(draft, [], mode)); const wire = (body: EditorNode) => From 0c7f579798dd7f0b2dccbc439bff28943d5a1426 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 08:31:51 +0000 Subject: [PATCH 19/35] fix(composer): check a group label against mobile's reader, and again on load A group stays one chip only when mobile's reader binds no one in it either. Mobile binds a tagged person's name, or its first word, at the start of the text after `@`, in any case, where a word ends. So with Mary Jane in the draft, "Mary crew" inserts the members, and "Marys crew" and "Crew Mary" stay one chip. A saved draft gets the same check when it loads: on mount, when a conflict reopens, and when another window or a reset loads it. A group whose label no longer holds against the draft's recipients comes back as one chip per member, as the pick makes it, and every member is still tagged. Typing does not run the check again. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 128 ++++++++++++++++++ src/features/messages/MessageComposer.tsx | 7 +- src/features/messages/composer-document.ts | 15 +- src/features/messages/mention-draft.test.ts | 22 +++ src/features/messages/mention-draft.ts | 37 +++++ 5 files changed, 204 insertions(+), 5 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index db8d9a49f2..f3c8352c23 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -18461,6 +18461,29 @@ it.each(groupLabelMatrix)( } }, ); +const maryJane = { ...first, name: "Mary Jane" }; +const wes = { ...second, name: "Wes" }; +it.each([ + ["Mary crew", [maryJane, wes], false], + ["mary crew", [maryJane, wes], false], + ["MARY CREW", [maryJane, wes], false], + ["Mary-crew", [maryJane, wes], false], + ["Mary Jane crew", [maryJane, wes], false], + ["Wes", [maryJane, wes], false], + ["Marys crew", [maryJane, wes], true], + ["Crew Mary", [maryJane, wes], true], + ["Wesley team", [maryJane, wes], true], + ["ÉMILE crew", [{ ...first, name: "Émile Durand" }], false], + ["ſam crew", [{ ...first, name: "Sam Lee" }], false], +])( + "a group picked with the label %s is one chip only when mobile's reader binds no member's name or first word at its start", + async (label, members, holds) => { + const group = await pickSent({ mentions: members, label }); + expect(group.tags).toEqual(members.map((person) => person.pubkey)); + if (holds) expect(group.content).toBe(`@${label} `); + else expect(group).toEqual(await pickSent({ mentions: members })); + }, +); it.each(["eng-oncall", "a-b-c"])( "a group labelled %s is still one chip after its saved draft is restored", async (label) => { @@ -18521,3 +18544,108 @@ it.each([true, false])( ); }, ); + +const savedCrew = ( + text: string, + label: string, + crew: readonly MentionRecipient[], + before: readonly MentionRecipient[] = [], +) => { + const start = text.indexOf(`@${label}`); + return { + text, + recipients: [ + ...before.map((person) => ({ ...person, start: 0, end: start - 1 })), + ...crew.map((person) => ({ + ...person, + start, + end: start + label.length + 1, + label, + })), + ], + }; +}; +const opsCrew = savedCrew("@*ops* hi", "*ops*", [maryJane, wes]); +async function sentGroups(h: ReturnType) { + const groups = screen.queryAllByRole("img", { name: /^Group / }).length; + h.submit(); + await waitFor(() => expect(h.messages.send).toHaveBeenCalled()); + const [, content, tags] = h.messages.send.mock.calls[0] ?? []; + return { groups, content, tags }; +} +it.each([ + ["*ops*", opsCrew], + [ + "Mary crew", + savedCrew("@Mary Jane @Mary crew hi", "Mary crew", [wes], [maryJane]), + ], +])( + "a saved group labelled %s comes back as its members, as a pick would make it now", + async (_label, saved) => { + writeView("scope", "draft:channel", typedDraft(saved)); + expect(await sentGroups(mount())).toEqual({ + groups: 0, + content: "@Mary Jane @Wes hi", + tags: [maryJane.pubkey, wes.pubkey], + }); + }, +); +it("a group whose label no longer holds is its members in a draft saved without a document", async () => { + writeView("scope", "draft:channel", opsCrew); + expect(await sentGroups(mount())).toEqual({ + groups: 0, + content: "@Mary Jane @Wes hi", + tags: [maryJane.pubkey, wes.pubkey], + }); +}); +it("a group whose label no longer holds is its members in a draft another window saves", async () => { + const h = mount(); + act(() => writeView("scope", "draft:channel", typedDraft(opsCrew))); + expect(await sentGroups(h)).toEqual({ + groups: 0, + content: "@Mary Jane @Wes hi", + tags: [maryJane.pubkey, wes.pubkey], + }); +}); +it("a group whose label a person added after it binds is its members when the draft reopens over a conflict", async () => { + const h = mount({}, undefined, undefined, undefined, undefined, bangAnywhere); + h.fill("!Crew"); + offerCrew(h, [wes], "Mary crew"); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("!M"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "mary", label: "Mary Jane", edit: { mention: maryJane } }], + }); + }); + await h.user.keyboard("{Enter}"); + expect(screen.queryAllByRole("img", { name: /^Group / })).toHaveLength(1); + act(() => writeView("scope", "draft:channel", "Saved elsewhere")); + h.remount(); + expect(screen.getByRole("alert")).toHaveTextContent(/changed elsewhere/); + fireEvent.click(screen.getByRole("button", { name: "Keep my draft" })); + expect(await sentGroups(h)).toEqual({ + groups: 0, + content: "@Wes @Mary Jane ", + tags: [wes.pubkey, maryJane.pubkey], + }); +}); +it("undoing and redoing a group pick brings back one chip with the same members", async () => { + const h = mount(); + h.fill("!Crew"); + offerCrew(h, [maryJane, wes]); + await h.user.keyboard("{Enter}"); + const chips = () => + screen.queryAllByRole("img").map((node) => node.getAttribute("aria-label")); + const picked = chips(); + expect(picked).toEqual(["Group Crew, 2 recipients: Mary Jane, Wes"]); + act(() => h.input().undo(false)); + expect(chips()).toEqual([]); + act(() => h.input().undo(true)); + expect(chips()).toEqual(picked); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Crew ", + tags: [maryJane.pubkey, wes.pubkey], + }); +}); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 802f549b96..9f4dd895f5 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -160,6 +160,7 @@ import { editorMention, hasHumanMentionSelection, hostComposerProvenance, + restoredDraft, stageableGif, withoutSpans, type MentionDraft, @@ -732,7 +733,7 @@ function Composer({ const saved = parseDraftView(savedRevision); if (saved && saved !== "oversized") return { - draft: mentionDraft(saved.value), + draft: restoredDraft(saved.value), revision: savedRevision, cursor, }; @@ -861,7 +862,7 @@ function Composer({ const [initial] = useState(() => { if (reopenedConflict) return { value: reopenedConflict, applied: undefined, automatic: false }; - const stored = mentionDraft( + const stored = restoredDraft( accepted?.next ?? submission?.recoveredDraft ?? readView(scope, draftKey, submission?.initialDraft ?? ""), @@ -1786,7 +1787,7 @@ function Composer({ diagnose("load", revision.current, raw); let next: MentionDraft; try { - next = restoreChatLinks(mentionDraft(JSON.parse(raw ?? "null"))); + next = restoreChatLinks(restoredDraft(JSON.parse(raw ?? "null"))); } catch { next = mentionDraft(""); } diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 2d0ea6ff5a..20b814618b 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -299,8 +299,9 @@ export function composerGroup(value: unknown, source: unknown) { return value as ComposerGroup; } /** Whether `@label` reads as one group to whoever gets it: letters, digits - * and spaces, a hyphen only between two of them, in which the reader binds - * none of `people`'s names, each taken alone. */ + * and spaces, a hyphen only between two of them, in which no reader binds + * any of `people`. This app's reader matches a whole name; mobile's matches + * a name or its first word at the start, in any case, where a word ends. */ export function groupLabelHolds( label: string, people: readonly MentionRecipient[], @@ -318,6 +319,16 @@ export function groupLabelHolds( }, undefined, ).some((part) => part.target), + ) && + !people.some((person) => + [person.name, person.name.split(/\s+/)[0]].some( + (name) => + !!name && + new RegExp( + `^${name.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&")}(?![\\p{L}\\p{M}\\p{N}])`, + "iu", + ).test(label), + ), ) ); } diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index abb31a11f1..7b386ca4a1 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -5,6 +5,7 @@ import { legacyFollowupDraft, mentionDraft, followupDraft, + restoredDraft, } from "./mention-draft"; import { typedDraft } from "./composer-testing"; import { composerMarkdown } from "./composer-markdown"; @@ -292,3 +293,24 @@ it("the recipient cap counts distinct people, keeping each one's spans", () => { restored.filter((item) => item.pubkey === people[0]?.pubkey), ).toHaveLength(2); }); +it("a restored group whose label no longer holds is one chip per member, each keeping its explicit pick", () => { + const mary = { + pubkey: "5".repeat(64), + name: "Mary", + explicit: true as const, + }; + const wes = { pubkey: "6".repeat(64), name: "Wes" }; + const saved = typedDraft({ + text: "@*ops* hi", + recipients: [mary, wes].map((person) => ({ + ...person, + label: "*ops*", + start: 0, + end: 6, + })), + }); + expect(restoredDraft(saved).recipients).toEqual([ + { ...mary, start: 0, end: 5 }, + { ...wes, start: 6, end: 10 }, + ]); +}); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 0745852155..d3167a023d 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -1,7 +1,11 @@ +import { Fragment, Slice } from "prosemirror-model"; import { forwardReference, type ForwardReference } from "./forward-clipboard"; import { canonicalChatCard } from "./chat-cards"; import { + composerSchema, + groupLabelHolds, projectComposerDocument, + readComposerDocument, readComposerSnapshot, } from "./composer-document"; @@ -179,6 +183,39 @@ export function mentionDraft(value: unknown): MentionDraft { ), }; } +/** A saved draft as a pick would make it now: a group chip whose label no + * longer holds against the draft's recipients is one chip per member. The + * normalize pass reads every change through `mentionDraft`, so only loading + * a draft calls this. */ +export function restoredDraft(value: unknown) { + const draft = mentionDraft(value); + const doc = readComposerDocument(draft, draft.recipients); + const stale = projectComposerDocument(doc).tokens.filter( + ({ node }) => + node.attrs.group && + !groupLabelHolds(node.attrs.group.label, draft.recipients), + ); + if (!stale.length) return draft; + const split = stale.reduceRight((next, { from, to, node }) => { + const members: readonly MentionRecipient[] = node.attrs.group.members; + const chips = members.flatMap((person, index) => [ + ...(index ? [composerSchema.text(" ", node.marks)] : []), + composerSchema.nodes.token.create( + { source: `@${person.name}`, recipient: person, editAsText: false }, + null, + node.marks, + ), + ]); + return next.replace(from, to, new Slice(Fragment.from(chips), 0, 0)); + }, doc); + const { text, recipients, document } = projectComposerDocument(split).draft; + return mentionDraft({ + ...draft, + text, + recipients, + ...(draft.document ? { document } : {}), + }); +} /** What counts as a draft everywhere: text, an attached chat or GIF, or `files`. * A typed tag is text the person put there; the composer no longer saves * tags of its own, and the ones earlier releases saved are not content. */ From 689a272322d74a1c04c44f177df2052793b358ab Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 08:56:03 +0000 Subject: [PATCH 20/35] fix(composer): read a saved draft's groups only when it has one A draft with no labelled recipient has no group chip on either path, so loading it returns mentionDraft's result without building a document. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/mention-draft.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index d3167a023d..a90384e14e 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -189,6 +189,7 @@ export function mentionDraft(value: unknown): MentionDraft { * a draft calls this. */ export function restoredDraft(value: unknown) { const draft = mentionDraft(value); + if (!draft.recipients.some((item) => item.label !== undefined)) return draft; const doc = readComposerDocument(draft, draft.recipients); const stale = projectComposerDocument(doc).tokens.filter( ({ node }) => From e494b07fe35a36abb60a1a7063d44df250ee3787 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 09:32:44 +0000 Subject: [PATCH 21/35] fix(composer): check a group label once, where the send takes its draft A saved draft now loads as typed, so the box shows the group chip the person picked. The send checks each group label against the people it tags: the send's recipients in a Solo chat with agents only, the draft's tagged people elsewhere. A group whose label no longer holds is sent as one chip per member, each keeping its explicit pick. If the message sent that way would be longer than 16000 characters, the send is refused before anything is submitted, the draft stays as typed, and the error names the group: "@label could not be tagged: the message would be too long." Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../direct-messages/NewMessage.test.tsx | 39 ++++++++- .../messages/MessageComposer.test.tsx | 84 ++++++++++++++++--- src/features/messages/MessageComposer.tsx | 38 ++++++--- src/features/messages/mention-draft.test.ts | 6 +- src/features/messages/mention-draft.ts | 17 ++-- 5 files changed, 148 insertions(+), 36 deletions(-) diff --git a/src/features/direct-messages/NewMessage.test.tsx b/src/features/direct-messages/NewMessage.test.tsx index f09beb92d8..21928a1252 100644 --- a/src/features/direct-messages/NewMessage.test.tsx +++ b/src/features/direct-messages/NewMessage.test.tsx @@ -2,7 +2,7 @@ import { SEARCH_DEBOUNCE_MS } from "../../shared/search-debounce"; import type { ConversationHostServices } from "../conversation/ConversationHost"; // @vitest-environment jsdom import "@testing-library/jest-dom/vitest"; -import { composerDOMFixture } from "../messages/composer-testing"; +import { composerDOMFixture, typedDraft } from "../messages/composer-testing"; import { afterEach, @@ -39,6 +39,7 @@ import { publicKeyLabels, } from "../../shared/identity/public-key"; import type { RelaySession } from "../relay/session"; +import { writeView } from "../../shared/view-state"; import { NewMessage } from "./NewMessage"; import { createAgentChoices } from "../agents/choices"; import type { LocalAgentsSnapshot } from "../agents/local"; @@ -1490,6 +1491,42 @@ it("locks during opening and delivery, waits for confirmation, and retries the s expect(t.directMessages.delivered).toHaveBeenCalledTimes(2); }); +it("sends a saved group whose label no longer holds as its members, and Retry sends the same text", async () => { + const crew = [ + { pubkey: people[2]?.pubkey ?? "", name: "Mary Jane" }, + { pubkey: people[3]?.pubkey ?? "", name: "Wes" }, + ]; + writeView( + scope, + "direct-message:new-draft", + typedDraft({ + text: "@*ops* hi", + recipients: crew.map((person) => ({ + ...person, + start: 0, + end: 6, + label: "*ops*", + })), + }), + ); + const t = setup(); + t.directMessages.delivery.mockReturnValue("unknown"); + t.directMessages.delivered.mockRejectedValueOnce( + new Error("Delivery uncertain"), + ); + t.mount(); + await t.user.click(await screen.findByRole("option", { name: "Person 1" })); + await t.user.click(send()); + await t.user.click(await screen.findByRole("button", { name: "Retry send" })); + await waitFor(() => expect(t.onStarted).toHaveBeenCalledOnce()); + expect(t.messages.send).toHaveBeenCalledOnce(); + expect(t.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@Mary Jane @Wes hi", + crew.map((person) => person.pubkey), + ]); + expect(t.directMessages.delivered).toHaveBeenCalledTimes(2); +}); + it("preserves recipients and draft after opening fails and across remount", async () => { const t = setup(); const view = t.mount(); diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index f3c8352c23..215ebf0e27 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -18468,8 +18468,6 @@ it.each([ ["mary crew", [maryJane, wes], false], ["MARY CREW", [maryJane, wes], false], ["Mary-crew", [maryJane, wes], false], - ["Mary Jane crew", [maryJane, wes], false], - ["Wes", [maryJane, wes], false], ["Marys crew", [maryJane, wes], true], ["Crew Mary", [maryJane, wes], true], ["Wesley team", [maryJane, wes], true], @@ -18580,34 +18578,34 @@ it.each([ savedCrew("@Mary Jane @Mary crew hi", "Mary crew", [wes], [maryJane]), ], ])( - "a saved group labelled %s comes back as its members, as a pick would make it now", + "a saved group labelled %s comes back as typed and is sent as its members", async (_label, saved) => { writeView("scope", "draft:channel", typedDraft(saved)); expect(await sentGroups(mount())).toEqual({ - groups: 0, + groups: 1, content: "@Mary Jane @Wes hi", tags: [maryJane.pubkey, wes.pubkey], }); }, ); -it("a group whose label no longer holds is its members in a draft saved without a document", async () => { +it("a group whose label no longer holds is sent as its members from a draft saved without a document", async () => { writeView("scope", "draft:channel", opsCrew); expect(await sentGroups(mount())).toEqual({ - groups: 0, + groups: 1, content: "@Mary Jane @Wes hi", tags: [maryJane.pubkey, wes.pubkey], }); }); -it("a group whose label no longer holds is its members in a draft another window saves", async () => { +it("a group whose label no longer holds is sent as its members from a draft another window saves", async () => { const h = mount(); act(() => writeView("scope", "draft:channel", typedDraft(opsCrew))); expect(await sentGroups(h)).toEqual({ - groups: 0, + groups: 1, content: "@Mary Jane @Wes hi", tags: [maryJane.pubkey, wes.pubkey], }); }); -it("a group whose label a person added after it binds is its members when the draft reopens over a conflict", async () => { +it("a group whose label a person added after it binds is sent as its members when the draft reopens over a conflict", async () => { const h = mount({}, undefined, undefined, undefined, undefined, bangAnywhere); h.fill("!Crew"); offerCrew(h, [wes], "Mary crew"); @@ -18619,17 +18617,81 @@ it("a group whose label a person added after it binds is its members when the dr }); }); await h.user.keyboard("{Enter}"); - expect(screen.queryAllByRole("img", { name: /^Group / })).toHaveLength(1); act(() => writeView("scope", "draft:channel", "Saved elsewhere")); h.remount(); expect(screen.getByRole("alert")).toHaveTextContent(/changed elsewhere/); fireEvent.click(screen.getByRole("button", { name: "Keep my draft" })); expect(await sentGroups(h)).toEqual({ - groups: 0, + groups: 1, content: "@Wes @Mary Jane ", tags: [wes.pubkey, maryJane.pubkey], }); }); +it("a group picked before a member whose name starts its label is sent as its members, with the text after it in place", async () => { + const h = mount({}, undefined, undefined, undefined, undefined, bangAnywhere); + h.fill("!Crew"); + offerCrew(h, [wes], "Mary crew"); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("!M"); + act(() => { + h.completionRequests.at(-1)?.({ + items: [{ id: "mary", label: "Mary Jane", edit: { mention: maryJane } }], + }); + }); + await h.user.keyboard("{Enter}"); + await h.user.keyboard("see you"); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Wes @Mary Jane see you", + tags: [wes.pubkey, maryJane.pubkey], + }); +}); +it("in a Solo chat with agents only, a group of people outside it whose label starts with the toolbar agent's name is sent as its members", async () => { + const { h } = mountSoloAgents({ main: first.pubkey }); + const outside = [ + { pubkey: "d".repeat(64), name: "Cy" }, + { pubkey: "e".repeat(64), name: "Di" }, + ]; + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, outside, "Ada crew"); + await h.user.keyboard("{Enter}"); + act(() => void h.commands().insertText("hi")); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Cy @Di hi", + tags: [first.pubkey], + }); +}); +it.each([ + ["the composer's own send", false], + ["a submission", true], +])( + "a group sent as its members past the length limit is refused through %s, and the draft stays", + async (_path, submitted) => { + const submit = vi.fn(); + const draftKey = submitted ? "new-draft" : "draft:channel"; + const text = `@*ops* ${"x".repeat(15990)}`; + writeView( + "scope", + draftKey, + typedDraft(savedCrew(text, "*ops*", [maryJane, wes])), + ); + const h = mount( + submitted + ? { submission: { draftKey, locked: false, disabled: false, submit } } + : {}, + ); + h.submit(); + expect(await screen.findByRole("alert")).toHaveTextContent( + "@*ops* could not be tagged: the message would be too long.", + ); + expect(submit).not.toHaveBeenCalled(); + expect(h.messages.send).not.toHaveBeenCalled(); + expect(screen.queryAllByRole("img", { name: /^Group / })).toHaveLength(1); + expect(h.input()).toHaveValue(text); + }, +); it("undoing and redoing a group pick brings back one chip with the same members", async () => { const h = mount(); h.fill("!Crew"); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 9f4dd895f5..02971c44a8 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -160,7 +160,7 @@ import { editorMention, hasHumanMentionSelection, hostComposerProvenance, - restoredDraft, + sentDraft, stageableGif, withoutSpans, type MentionDraft, @@ -733,7 +733,7 @@ function Composer({ const saved = parseDraftView(savedRevision); if (saved && saved !== "oversized") return { - draft: restoredDraft(saved.value), + draft: mentionDraft(saved.value), revision: savedRevision, cursor, }; @@ -862,7 +862,7 @@ function Composer({ const [initial] = useState(() => { if (reopenedConflict) return { value: reopenedConflict, applied: undefined, automatic: false }; - const stored = restoredDraft( + const stored = mentionDraft( accepted?.next ?? submission?.recoveredDraft ?? readView(scope, draftKey, submission?.initialDraft ?? ""), @@ -1787,7 +1787,7 @@ function Composer({ diagnose("load", revision.current, raw); let next: MentionDraft; try { - next = restoreChatLinks(restoredDraft(JSON.parse(raw ?? "null"))); + next = restoreChatLinks(mentionDraft(JSON.parse(raw ?? "null"))); } catch { next = mentionDraft(""); } @@ -3179,7 +3179,11 @@ function Composer({ let retiredByOwner = false; const attempt = new AbortController(); sendAttempt.current = attempt; - const captured = valueRef.current; + const typed = valueRef.current; + const captured = sentDraft( + typed, + routing ? recipientsNow : typed.recipients, + ); const explicit = human && ownerProvenance ? captured.recipients @@ -3216,6 +3220,14 @@ function Composer({ !threadRootId && followUpBehaviorPreference() === "queue"; try { + if (captured !== typed && composerMarkdown(captured).length > 16000) { + const groups = new Set(typed.recipients.map((item) => item.label)); + for (const item of captured.recipients) groups.delete(item.label); + groups.delete(undefined); + throw new Error( + `${[...groups].map((label) => `@${label}`).join(", ")} ${pendingRefusals.length}.`, + ); + } const tokens = draftTokens(captured); messageTokenTags(tokens); if (command && onCommand) { @@ -3224,7 +3236,7 @@ function Composer({ setSending(true); if (await handled) { attempt.signal.throwIfAborted(); - if (valueRef.current !== captured) return; + if (valueRef.current !== typed) return; const current = viewRevision(scope, draftKey); if (current !== savedRevision) { diagnose("send-upload-conflict", savedRevision, current); @@ -3310,7 +3322,7 @@ function Composer({ old, attempt.signal, () => - valueRef.current === captured && + valueRef.current === typed && sameAttachmentSelection( attachments.store.snapshot(), capturedAttachments, @@ -3325,7 +3337,7 @@ function Composer({ .channels.find((item) => item.id === channelId); if (channel?.members && allowsOutsideMentions(channel)) { const current = () => - valueRef.current === captured && + valueRef.current === typed && sameAttachmentSelection( attachments.store.snapshot(), capturedAttachments, @@ -3381,7 +3393,7 @@ function Composer({ if (attachments.store.snapshot().some((item) => item.status === "error")) return; if ( - valueRef.current !== captured || + valueRef.current !== typed || !sameAttachmentSelection( attachments.store.snapshot(), capturedAttachments, @@ -3419,7 +3431,7 @@ function Composer({ setError(undefined); const current = () => permitted.current && - valueRef.current === captured && + valueRef.current === typed && viewRevision(scope, draftKey) === savedRevision && sameAttachmentSelection( attachments.store.snapshot(), @@ -3653,7 +3665,7 @@ function Composer({ // restored. A later edit belongs to its author, not this job. if (!flushPendingDraft(scope, draftKey)) return "conflict"; const current = viewRevision(scope, draftKey); - const capturedRevision = JSON.stringify(captured); + const capturedRevision = JSON.stringify(typed); const cleared = (raw: string | null | undefined) => { if (!raw) return false; try { @@ -3716,7 +3728,7 @@ function Composer({ if (target.snapshot().length) return "conflict"; if ( current !== capturedRevision && - replaceView(scope, draftKey, current, captured) !== "saved" + replaceView(scope, draftKey, current, typed) !== "saved" ) return false; if (!target.adopt(files)) return false; @@ -3724,7 +3736,7 @@ function Composer({ // The whole captured pick set returns with the whole draft; the // recipient filter above applies again on the next send. notifyRecovered(session, recoveryKey, { - draft: captured, + draft: typed, picks: capturedPicks, preparationError, }); diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 7b386ca4a1..0e83d88afd 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -5,7 +5,7 @@ import { legacyFollowupDraft, mentionDraft, followupDraft, - restoredDraft, + sentDraft, } from "./mention-draft"; import { typedDraft } from "./composer-testing"; import { composerMarkdown } from "./composer-markdown"; @@ -293,7 +293,7 @@ it("the recipient cap counts distinct people, keeping each one's spans", () => { restored.filter((item) => item.pubkey === people[0]?.pubkey), ).toHaveLength(2); }); -it("a restored group whose label no longer holds is one chip per member, each keeping its explicit pick", () => { +it("a sent group whose label no longer holds is one chip per member, each keeping its explicit pick", () => { const mary = { pubkey: "5".repeat(64), name: "Mary", @@ -309,7 +309,7 @@ it("a restored group whose label no longer holds is one chip per member, each ke end: 6, })), }); - expect(restoredDraft(saved).recipients).toEqual([ + expect(sentDraft(saved, saved.recipients).recipients).toEqual([ { ...mary, start: 0, end: 5 }, { ...wes, start: 6, end: 10 }, ]); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index a90384e14e..48c723a874 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -183,18 +183,19 @@ export function mentionDraft(value: unknown): MentionDraft { ), }; } -/** A saved draft as a pick would make it now: a group chip whose label no - * longer holds against the draft's recipients is one chip per member. The - * normalize pass reads every change through `mentionDraft`, so only loading - * a draft calls this. */ -export function restoredDraft(value: unknown) { - const draft = mentionDraft(value); +/** `draft` as a send gives it: a group chip whose label no longer holds + * against the `people` the send tags is one chip per member, each keeping its + * explicit pick. With nothing to split it returns `draft` itself; the draft + * in the box is left as typed. */ +export function sentDraft( + draft: MentionDraft, + people: readonly MentionRecipient[], +) { if (!draft.recipients.some((item) => item.label !== undefined)) return draft; const doc = readComposerDocument(draft, draft.recipients); const stale = projectComposerDocument(doc).tokens.filter( ({ node }) => - node.attrs.group && - !groupLabelHolds(node.attrs.group.label, draft.recipients), + node.attrs.group && !groupLabelHolds(node.attrs.group.label, people), ); if (!stale.length) return draft; const split = stale.reduceRight((next, { from, to, node }) => { From b13c7598e6eebb842dfc2aaa7d92a20b78d206d2 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 10:10:55 +0000 Subject: [PATCH 22/35] fix(composer): check a group label against a DM's agent partner In a one-to-one DM whose other member is an agent, every send tags that agent. The group label check at the pick and at send now counts that agent, under the name its profile gives, so in a DM with "Ops" the group "Ops crew" goes in, and is sent, as its members. The new-message test of a saved group no longer retries the send; the delivery test already covers Retry. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../direct-messages/NewMessage.test.tsx | 8 +--- .../messages/MessageComposer.test.tsx | 39 +++++++++++++++++++ src/features/messages/MessageComposer.tsx | 21 ++++++++-- 3 files changed, 57 insertions(+), 11 deletions(-) diff --git a/src/features/direct-messages/NewMessage.test.tsx b/src/features/direct-messages/NewMessage.test.tsx index 21928a1252..1885a2476b 100644 --- a/src/features/direct-messages/NewMessage.test.tsx +++ b/src/features/direct-messages/NewMessage.test.tsx @@ -1491,7 +1491,7 @@ it("locks during opening and delivery, waits for confirmation, and retries the s expect(t.directMessages.delivered).toHaveBeenCalledTimes(2); }); -it("sends a saved group whose label no longer holds as its members, and Retry sends the same text", async () => { +it("sends a saved group whose label no longer holds as its members", async () => { const crew = [ { pubkey: people[2]?.pubkey ?? "", name: "Mary Jane" }, { pubkey: people[3]?.pubkey ?? "", name: "Wes" }, @@ -1510,21 +1510,15 @@ it("sends a saved group whose label no longer holds as its members, and Retry se }), ); const t = setup(); - t.directMessages.delivery.mockReturnValue("unknown"); - t.directMessages.delivered.mockRejectedValueOnce( - new Error("Delivery uncertain"), - ); t.mount(); await t.user.click(await screen.findByRole("option", { name: "Person 1" })); await t.user.click(send()); - await t.user.click(await screen.findByRole("button", { name: "Retry send" })); await waitFor(() => expect(t.onStarted).toHaveBeenCalledOnce()); expect(t.messages.send).toHaveBeenCalledOnce(); expect(t.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ "@Mary Jane @Wes hi", crew.map((person) => person.pubkey), ]); - expect(t.directMessages.delivered).toHaveBeenCalledTimes(2); }); it("preserves recipients and draft after opening fails and across remount", async () => { diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 215ebf0e27..28a9b0bedb 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -18663,6 +18663,45 @@ it("in a Solo chat with agents only, a group of people outside it whose label st tags: [first.pubkey], }); }); +it.each([ + ["picked", 0], + ["saved in a draft", 1], +])( + "in a one-to-one DM with an agent, a group whose label starts with the agent's name is %s and sent as its members", + async (_how, groups) => { + const viewer = "d".repeat(64); + const ops = "c".repeat(64); + if (groups) + writeView( + "scope", + "draft:channel", + typedDraft(savedCrew("@Ops crew hi", "Ops crew", [maryJane, wes])), + ); + const h = mount({}, undefined, viewer); + h.setProfiles(new Map([[ops, { name: "Ops", isAgent: true }]])); + const dm = { + status: "ready" as const, + channels: [ + { id: "channel", channelType: "dm" as const, members: [viewer, ops] }, + ], + }; + Object.assign(h.session.channels, { + list: () => dm, + get: () => dm.channels[0], + }); + h.remount(); + if (!groups) { + h.fill("!Crew"); + offerCrew(h, [maryJane, wes], "Ops crew"); + await h.user.keyboard("{Enter}hi"); + } + expect(await sentGroups(h)).toEqual({ + groups, + content: "@Mary Jane @Wes hi", + tags: [], + }); + }, +); it.each([ ["the composer's own send", false], ["a submission", true], diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 02971c44a8..924b76a58a 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -1150,6 +1150,18 @@ function Composer({ ]), ] : pubkeys; + const dmAgents = () => { + const viewer = session.viewer; + const profiles = session.profiles.snapshot(); + return viewer && dmMembers?.length === 2 && dmMembers.includes(viewer) + ? dmMembers.flatMap((pubkey) => { + const profile = profiles.get(pubkey); + return pubkey !== viewer && profile?.isAgent + ? [{ pubkey, name: profile.name }] + : []; + }) + : []; + }; // Read at send time: inline mentions win, else the toolbar's agents. A // reference addresses nobody, so it goes along with the toolbar's agents. const sendRecipients = () => { @@ -2467,6 +2479,7 @@ function Composer({ groupLabelHolds(requested, [ ...recipients, ...valueRef.current.recipients, + ...dmAgents(), ]) ? requested : undefined; @@ -3180,10 +3193,10 @@ function Composer({ const attempt = new AbortController(); sendAttempt.current = attempt; const typed = valueRef.current; - const captured = sentDraft( - typed, - routing ? recipientsNow : typed.recipients, - ); + const captured = sentDraft(typed, [ + ...(routing ? recipientsNow : typed.recipients), + ...dmAgents(), + ]); const explicit = human && ownerProvenance ? captured.recipients From e092a1062264e42ed1ba36afc39b17944bfb29fb Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 11:35:58 +0000 Subject: [PATCH 23/35] fix(composer): check a group label against every name a reader links A reader links a mention by the person's shown name and both verified names. The mobile app also links a verified person by the name their own profile gives. The group label check at the pick and at send now counts all of these, so for a member shown as "MJ" whose verified full name is "Mary Jane Jones", the group "Mary Jane Jones crew" goes in, and is sent, as its members. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 74 +++++++++++++++++++ src/features/messages/MessageComposer.tsx | 33 ++++++--- 2 files changed, 98 insertions(+), 9 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 28a9b0bedb..941b93e57b 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -107,6 +107,7 @@ import type { EmojiSnapshot } from "../relay/emoji-directory"; import { emojiQuery } from "../../bundled/emoji/emoji-query"; import type { ComposerInputElement } from "./composer-dom"; import { profileTarget } from "../profiles/target"; +import { profileMentionParts } from "./profile-mentions"; import { fromMarkdown } from "mdast-util-from-markdown"; import { setRememberAgentsPreference } from "./mention-preferences"; import * as modelStorage from "./solo-model-picks-storage"; @@ -18702,6 +18703,79 @@ it.each([ }); }, ); +it.each([ + ["verified", "picked", 0, "Mary Jane Jones crew", ""], + ["verified", "saved in a draft", 1, "Mary Jane Jones crew", ""], + ["self-set", "picked", 0, "Mo crew", "Mo Jones"], +])( + "a group whose label starts with a member's %s name is %s and sent as its members", + async (_name, _how, groups, label, own) => { + const mj = { ...first, name: "MJ" }; + const verified = { + displayName: "MJ", + username: "mj", + fullName: "Mary Jane Jones", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }; + if (groups) + writeView( + "scope", + "draft:channel", + typedDraft(savedCrew(`@${label} hi`, label, [mj, wes])), + ); + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ", verified }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + if (own) + Object.assign(h.session.profiles, { + event: (pubkey: string) => + pubkey === mj.pubkey + ? { + id: "e".repeat(64), + pubkey, + created_at: 1, + kind: 0, + content: JSON.stringify({ name: own }), + tags: [], + } + : undefined, + }); + if (!groups) { + h.fill("!Crew"); + offerCrew(h, [mj, wes], label); + await h.user.keyboard("{Enter}hi"); + } + const sent = await sentGroups(h); + const reader = new Map([ + [mj.pubkey, { name: "Mary Jane Jones", verified }], + [wes.pubkey, { name: "Wes" }], + ]); + expect({ + ...sent, + parts: profileMentionParts( + { content: sent.content ?? "", mentions: sent.tags ?? [] }, + reader, + ), + }).toEqual({ + groups, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + parts: [ + { text: "@MJ", target: profileTarget(mj.pubkey) }, + { text: " " }, + { text: "@Wes", target: profileTarget(wes.pubkey) }, + { text: " hi" }, + ], + }); + }, +); it.each([ ["the composer's own send", false], ["a submission", true], diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 924b76a58a..70cbc2f610 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -58,6 +58,8 @@ import { useMessageEdit, lastEditableMessage } from "./useMessageEdit"; import { editMentionText } from "./message-edit"; import type { ChannelMessage } from "../relay/contracts"; import { useListedChannel } from "../relay/listed-channel"; +import { foldProfiles } from "../relay/profiles"; +import { profileMentionNames } from "./profile-mentions"; import { FileDropOverlay } from "./FileDropOverlay"; import { useFileDrop } from "./use-file-drop"; import { Button } from "../../shared/design-system/ui/Button"; @@ -1162,6 +1164,20 @@ function Composer({ }) : []; }; + const boundNames = (people: readonly MentionRecipient[]) => { + const profiles = session.profiles.snapshot(); + return [...people, ...dmAgents()].flatMap(({ pubkey, name }) => { + const event = session.profiles.event?.(pubkey); + const own = event && foldProfiles([event]).get(pubkey); + return [ + ...new Set([ + name, + ...profileMentionNames(profiles.get(pubkey)), + own && !own.nameIsFallback ? own.name : undefined, + ]), + ].flatMap((each) => (each ? [{ pubkey, name: each }] : [])); + }); + }; // Read at send time: inline mentions win, else the toolbar's agents. A // reference addresses nobody, so it goes along with the toolbar's agents. const sendRecipients = () => { @@ -2476,11 +2492,10 @@ function Composer({ return false; const label = requested !== undefined && - groupLabelHolds(requested, [ - ...recipients, - ...valueRef.current.recipients, - ...dmAgents(), - ]) + groupLabelHolds( + requested, + boundNames([...recipients, ...valueRef.current.recipients]), + ) ? requested : undefined; const unique = [ @@ -3193,10 +3208,10 @@ function Composer({ const attempt = new AbortController(); sendAttempt.current = attempt; const typed = valueRef.current; - const captured = sentDraft(typed, [ - ...(routing ? recipientsNow : typed.recipients), - ...dmAgents(), - ]); + const captured = sentDraft( + typed, + boundNames(routing ? recipientsNow : typed.recipients), + ); const explicit = human && ownerProvenance ? captured.recipients From 807beb382547044cb5a294e2099e6f01b80a3505 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 01:01:54 +0000 Subject: [PATCH 24/35] refactor(composer): move three group rules into plain functions Three rules the group chip uses now live in functions of plain values. The components gather the inputs and act on the result. - `readerNames` returns every name a reader may link for each person: the shown name, both verified names and the name the person's own profile gives, plus a one-to-one DM's agent partner. The composer passes in the session's profiles, profile events and DM members. - `groupKeeping` returns a group without the members a change removes, or null when none are left. Removing a recipient and replacing the recipients both call it. - The group chip in the box reads its group through `tokenRecipients`, as the editor does. - A send takes its draft before it holds the send lock, so an error while taking the draft can no longer leave the lock held. The label, reader-name and keeping cases are now tables over these functions. The composer tests keep one case for each way the inputs reach them. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/EditableInput.tsx | 19 +- .../messages/MessageComposer.test.tsx | 222 +++++------------- src/features/messages/MessageComposer.tsx | 41 +--- src/features/messages/RichComposerInput.tsx | 16 +- .../messages/composer-document.test.ts | 167 +++++++++++++ src/features/messages/composer-document.ts | 46 +++- 6 files changed, 303 insertions(+), 208 deletions(-) diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index a3125b5ccd..56fc758210 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -54,6 +54,7 @@ import { brokenResources, resourceBlockingMarks, composerGroup, + groupKeeping, tokenRecipients, type ComposerGroup, } from "./composer-document"; @@ -1405,11 +1406,12 @@ export function EditableInput({ token.node.attrs.group, token.node.attrs.source, ); - const members = group?.members.filter((m) => requested.has(m.pubkey)); - if (group && members && members.length < group.members.length) + const kept = + group && groupKeeping(group, (pubkey) => requested.has(pubkey)); + if (kept !== group) tr.setNodeMarkup(token.from, undefined, { ...token.node.attrs, - group: members.length ? { label: group.label, members } : null, + group: kept, }); } for (const person of [...source.draft.recipients].reverse()) { @@ -3090,13 +3092,10 @@ export function EditableInput({ recipient: null, }); const group = composerGroup(node.attrs.group, node.attrs.source); - 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 kept = + group && groupKeeping(group, (member) => member !== pubkey); + if (kept !== group) + tr.setNodeMarkup(pos, undefined, { ...node.attrs, group: kept }); const mark = composerSchema.marks.recipient.isInSet(node.marks); if (mark?.attrs.pubkey === pubkey) tr.removeMark(pos, pos + node.nodeSize, mark); diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index d57116f1df..7d9c51e6c1 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -113,7 +113,6 @@ import type { EmojiSnapshot } from "../relay/emoji-directory"; import { emojiQuery } from "../../bundled/emoji/emoji-query"; import type { ComposerInputElement } from "./composer-dom"; import { profileTarget } from "../profiles/target"; -import { profileMentionParts } from "./profile-mentions"; import { fromMarkdown } from "mdast-util-from-markdown"; import { setRememberAgentsPreference } from "./mention-preferences"; import * as modelStorage from "./solo-model-picks-storage"; @@ -18543,26 +18542,6 @@ it("pastes a copied forward literally inside a code block", async () => { ).not.toBeInTheDocument(); }); -const oneChipLabels = new Set([ - "Team 42", - "24-7", - "eng-oncall", - "a-b-c", - "हिंदी टीम", - "हिंदी-टीम", - "ทีมไทย", - "Cafe\u0301 crew", -]); -const groupLabelMatrix = [ - ...oneChipLabels, - "eng_ios", - "-ops", - "ops-", - "a--b", - "a - b", - "Honey team", - "Honey-crew", -]; async function pickSent(edit: { mentions: MentionRecipient[]; label?: string; @@ -18584,41 +18563,26 @@ async function pickSent(edit: { cleanup(); return { chips, content, tags }; } -it.each(groupLabelMatrix)( - "a group picked with the label %s is one chip only when the label is plain text and starts with no member's name", - async (label) => { - const group = await pickSent({ mentions: [first, second], label }); - expect(group.tags).toEqual([first.pubkey, second.pubkey]); - if (oneChipLabels.has(label)) { - expect(group.content).toBe(`@${label} `); - expect(group.chips).toEqual([ - `Group ${label}, 2 recipients: Honey · rcaj, Honey · 04hu`, - ]); - } else { - expect(group).toEqual(await pickSent({ mentions: [first, second] })); - expect(group.chips.some((name) => name?.startsWith("Group"))).toBe(false); - } - }, -); const maryJane = { ...first, name: "Mary Jane" }; const wes = { ...second, name: "Wes" }; it.each([ + ["eng-oncall", [first, second], true], + ["eng_ios", [first, second], false], ["Mary crew", [maryJane, wes], false], - ["mary crew", [maryJane, wes], false], - ["MARY CREW", [maryJane, wes], false], - ["Mary-crew", [maryJane, wes], false], - ["Marys crew", [maryJane, wes], true], - ["Crew Mary", [maryJane, wes], true], - ["Wesley team", [maryJane, wes], true], - ["ÉMILE crew", [{ ...first, name: "Émile Durand" }], false], - ["ſam crew", [{ ...first, name: "Sam Lee" }], false], ])( - "a group picked with the label %s is one chip only when mobile's reader binds no member's name or first word at its start", + "a group picked with the label %s is one chip only when its label holds for every reader", async (label, members, holds) => { const group = await pickSent({ mentions: members, label }); expect(group.tags).toEqual(members.map((person) => person.pubkey)); - if (holds) expect(group.content).toBe(`@${label} `); - else expect(group).toEqual(await pickSent({ mentions: members })); + if (holds) { + expect(group.content).toBe(`@${label} `); + expect(group.chips).toEqual([ + `Group ${label}, 2 recipients: Honey · rcaj, Honey · 04hu`, + ]); + } else { + expect(group).toEqual(await pickSent({ mentions: members })); + expect(group.chips.some((name) => name?.startsWith("Group"))).toBe(false); + } }, ); it.each(["eng-oncall", "a-b-c"])( @@ -18802,118 +18766,56 @@ it("in a Solo chat with agents only, a group of people outside it whose label st tags: [first.pubkey], }); }); -it.each([ - ["picked", 0], - ["saved in a draft", 1], -])( - "in a one-to-one DM with an agent, a group whose label starts with the agent's name is %s and sent as its members", - async (_how, groups) => { - const viewer = "d".repeat(64); - const ops = "c".repeat(64); - if (groups) - writeView( - "scope", - "draft:channel", - typedDraft(savedCrew("@Ops crew hi", "Ops crew", [maryJane, wes])), - ); - const h = mount({}, undefined, viewer); - h.setProfiles(new Map([[ops, { name: "Ops", isAgent: true }]])); - const dm = { - status: "ready" as const, - channels: [ - { id: "channel", channelType: "dm" as const, members: [viewer, ops] }, - ], - }; - Object.assign(h.session.channels, { - list: () => dm, - get: () => dm.channels[0], - }); - h.remount(); - if (!groups) { - h.fill("!Crew"); - offerCrew(h, [maryJane, wes], "Ops crew"); - await h.user.keyboard("{Enter}hi"); - } - expect(await sentGroups(h)).toEqual({ - groups, - content: "@Mary Jane @Wes hi", - tags: [], - }); - }, -); -it.each([ - ["verified", "picked", 0, "Mary Jane Jones crew", ""], - ["verified", "saved in a draft", 1, "Mary Jane Jones crew", ""], - ["self-set", "picked", 0, "Mo crew", "Mo Jones"], -])( - "a group whose label starts with a member's %s name is %s and sent as its members", - async (_name, _how, groups, label, own) => { - const mj = { ...first, name: "MJ" }; - const verified = { - displayName: "MJ", - username: "mj", - fullName: "Mary Jane Jones", - issuerLabel: "Example", - verifiedAt: 1, - status: "checked" as const, - multipleIssuers: false, - }; - if (groups) - writeView( - "scope", - "draft:channel", - typedDraft(savedCrew(`@${label} hi`, label, [mj, wes])), - ); - const h = mount(); - h.setProfiles( - new Map([ - [mj.pubkey, { name: "MJ", verified }], - [wes.pubkey, { name: "Wes" }], - ]), - ); - if (own) - Object.assign(h.session.profiles, { - event: (pubkey: string) => - pubkey === mj.pubkey - ? { - id: "e".repeat(64), - pubkey, - created_at: 1, - kind: 0, - content: JSON.stringify({ name: own }), - tags: [], - } - : undefined, - }); - if (!groups) { - h.fill("!Crew"); - offerCrew(h, [mj, wes], label); - await h.user.keyboard("{Enter}hi"); - } - const sent = await sentGroups(h); - const reader = new Map([ - [mj.pubkey, { name: "Mary Jane Jones", verified }], - [wes.pubkey, { name: "Wes" }], - ]); - expect({ - ...sent, - parts: profileMentionParts( - { content: sent.content ?? "", mentions: sent.tags ?? [] }, - reader, - ), - }).toEqual({ - groups, - content: "@MJ @Wes hi", - tags: [mj.pubkey, wes.pubkey], - parts: [ - { text: "@MJ", target: profileTarget(mj.pubkey) }, - { text: " " }, - { text: "@Wes", target: profileTarget(wes.pubkey) }, - { text: " hi" }, - ], - }); - }, -); +it("in a one-to-one DM with an agent, a group picked with a label that starts with the agent's name is sent as its members", async () => { + const viewer = "d".repeat(64); + const ops = "c".repeat(64); + const h = mount({}, undefined, viewer); + h.setProfiles(new Map([[ops, { name: "Ops", isAgent: true }]])); + const dm = { + status: "ready" as const, + channels: [ + { id: "channel", channelType: "dm" as const, members: [viewer, ops] }, + ], + }; + Object.assign(h.session.channels, { + list: () => dm, + get: () => dm.channels[0], + }); + h.remount(); + h.fill("!Crew"); + offerCrew(h, [maryJane, wes], "Ops crew"); + await h.user.keyboard("{Enter}hi"); + expect(await sentGroups(h)).toEqual({ + groups: 0, + content: "@Mary Jane @Wes hi", + tags: [], + }); +}); +it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { + const mj = { ...first, name: "MJ" }; + const h = mount(); + Object.assign(h.session.profiles, { + event: (pubkey: string) => + pubkey === mj.pubkey + ? { + id: "e".repeat(64), + pubkey, + created_at: 1, + kind: 0, + content: JSON.stringify({ name: "Mo Jones" }), + tags: [], + } + : undefined, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mo crew"); + await h.user.keyboard("{Enter}hi"); + expect(await sentGroups(h)).toEqual({ + groups: 0, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + }); +}); it.each([ ["the composer's own send", false], ["a submission", true], diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index cb10fdb624..f47157ac7a 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -53,13 +53,12 @@ import { composerMarkdownContext, markdownRanges, groupLabelHolds, + readerNames, } from "./composer-document"; import { useMessageEdit, lastEditableMessage } from "./useMessageEdit"; import { editMentionText } from "./message-edit"; import type { ChannelMessage } from "../relay/contracts"; import { useListedChannel } from "../relay/listed-channel"; -import { foldProfiles } from "../relay/profiles"; -import { profileMentionNames } from "./profile-mentions"; import { FileDropOverlay } from "./FileDropOverlay"; import { useFileDrop } from "./use-file-drop"; import { Button } from "../../shared/design-system/ui/Button"; @@ -1153,32 +1152,14 @@ function Composer({ ]), ] : pubkeys; - const dmAgents = () => { - const viewer = session.viewer; - const profiles = session.profiles.snapshot(); - return viewer && dmMembers?.length === 2 && dmMembers.includes(viewer) - ? dmMembers.flatMap((pubkey) => { - const profile = profiles.get(pubkey); - return pubkey !== viewer && profile?.isAgent - ? [{ pubkey, name: profile.name }] - : []; - }) - : []; - }; - const boundNames = (people: readonly MentionRecipient[]) => { - const profiles = session.profiles.snapshot(); - return [...people, ...dmAgents()].flatMap(({ pubkey, name }) => { - const event = session.profiles.event?.(pubkey); - const own = event && foldProfiles([event]).get(pubkey); - return [ - ...new Set([ - name, - ...profileMentionNames(profiles.get(pubkey)), - own && !own.nameIsFallback ? own.name : undefined, - ]), - ].flatMap((each) => (each ? [{ pubkey, name: each }] : [])); - }); - }; + const boundNames = (people: readonly MentionRecipient[]) => + readerNames( + people, + session.profiles.snapshot(), + (pubkey) => session.profiles.event?.(pubkey), + session.viewer, + dmMembers, + ); // Read at send time: inline mentions win, else the toolbar's agents. A // reference addresses nobody, so it goes along with the toolbar's agents. const sendRecipients = () => { @@ -3206,13 +3187,13 @@ function Composer({ const savedRevision = revision.current; const retirementCursor = draftRetirementCursor(scope, draftKey); let retiredByOwner = false; - const attempt = new AbortController(); - sendAttempt.current = attempt; const typed = valueRef.current; const captured = sentDraft( typed, boundNames(routing ? recipientsNow : typed.recipients), ); + const attempt = new AbortController(); + sendAttempt.current = attempt; const explicit = human && ownerProvenance ? captured.recipients diff --git a/src/features/messages/RichComposerInput.tsx b/src/features/messages/RichComposerInput.tsx index 9106c5eae9..d481e4f499 100644 --- a/src/features/messages/RichComposerInput.tsx +++ b/src/features/messages/RichComposerInput.tsx @@ -19,6 +19,7 @@ import { useReferenceDirectory } from "./ReferenceText"; import { readComposerSnapshot, composerMarkdownContext, + tokenRecipients, } from "./composer-document"; import { messageLinkParts } from "./message-link-parts"; import { parseBuzzLink } from "../navigation/buzz-links"; @@ -401,22 +402,23 @@ export function RichComposerInput({ const preview = gifPreviews.get(start); if (preview && preview.end === end && !mention) return { start, end, editAsText: false, content: preview.content }; - const people = draft.recipients.filter( - (item) => item.start === start && item.label !== undefined, + const { group } = tokenRecipients( + draft.recipients, + draft.text.slice(start, end), + { start, end }, ); - const group = people[0]?.label; - if (group !== undefined && draft.text.slice(start, end) === `@${group}`) + if (group) return { start, end, editAsText: false, content: ( labels.get(item.pubkey) ?? item.name) .join(", ")} - count={people.length} + count={group.members.length} /> ), }; diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 4a8110b476..f43db0cdd7 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "vitest"; import { composerGroup, + groupKeeping, + groupLabelHolds, + readerNames, composerSchema as schema, projectComposerDocument, readComposerDocument, @@ -15,6 +18,7 @@ import { gfmStrikethroughFromMarkdown } from "mdast-util-gfm-strikethrough"; import { gfmStrikethrough } from "micromark-extension-gfm-strikethrough"; import type { Nodes, RootContent } from "mdast"; import type { InlineFormat } from "./composer-dom"; +import type { Profile } from "../relay/contracts"; const paragraph = (...children: ReturnType[]) => schema.nodes.paragraph.create(null, children); @@ -833,3 +837,166 @@ it("a person chip keeps `explicit` when it is rebuilt from the draft text", () = ).draft.recipients.map(({ pubkey, explicit }) => [pubkey, explicit]), ).toEqual([[ann.pubkey, true]]); }); + +const honey = [ + { pubkey: "a".repeat(64), name: "Honey" }, + { pubkey: "b".repeat(64), name: "Honey" }, +]; +const maryJaneAndWes = [ + { pubkey: "a".repeat(64), name: "Mary Jane" }, + { pubkey: "b".repeat(64), name: "Wes" }, +]; +it.each([ + ["Team 42", honey, true], + ["24-7", honey, true], + ["eng-oncall", honey, true], + ["a-b-c", honey, true], + ["हिंदी टीम", honey, true], + ["हिंदी-टीम", honey, true], + ["ทีมไทย", honey, true], + ["Cafe\u0301 crew", honey, true], + ["eng_ios", honey, false], + ["-ops", honey, false], + ["ops-", honey, false], + ["a--b", honey, false], + ["a - b", honey, false], + ["Honey team", honey, false], + ["Honey-crew", honey, false], + ["Mary crew", maryJaneAndWes, false], + ["mary crew", maryJaneAndWes, false], + ["MARY CREW", maryJaneAndWes, false], + ["Mary-crew", maryJaneAndWes, false], + ["Marys crew", maryJaneAndWes, true], + ["Crew Mary", maryJaneAndWes, true], + ["Wesley team", maryJaneAndWes, true], + ["ÉMILE crew", [{ pubkey: "a".repeat(64), name: "Émile Durand" }], false], + ["ſam crew", [{ pubkey: "a".repeat(64), name: "Sam Lee" }], false], +])( + "the group label %s holds only when it is plain text and no reader binds a member's name or first word at its start", + (label, people, holds) => { + expect(groupLabelHolds(label, people)).toBe(holds); + }, +); + +const crew = { label: "Crew", members: honey }; +it.each<[string, string[], ReturnType]>([ + [ + "some members left", + ["a".repeat(64)], + { label: "Crew", members: honey.slice(0, 1) }, + ], + ["none left", [], null], + ["nothing removed", ["a".repeat(64), "b".repeat(64)], crew], +])("a group keeping its members: %s", (_case, keep, expected) => { + const kept = groupKeeping(crew, (pubkey) => keep.includes(pubkey)); + expect(kept).toEqual(expected); + expect(kept === crew).toBe(expected === crew); +}); + +const viewer = "c".repeat(64); +const [mary, ops] = ["a".repeat(64), "b".repeat(64)]; +const verified = { + displayName: "MJ", + username: "mj", + fullName: "Mary Jane Jones", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, +}; +it.each< + [ + string, + Record, + object | undefined, + { viewer?: string; members?: string[] }, + string[][], + ] +>([ + ["the shown name", {}, undefined, {}, [[mary, "Mary"]]], + [ + "both verified names", + { [mary]: { name: "Mary", verified } }, + undefined, + {}, + [ + [mary, "Mary"], + [mary, "MJ"], + [mary, "Mary Jane Jones"], + ], + ], + [ + "the self-set name", + {}, + { name: "Mo Jones" }, + {}, + [ + [mary, "Mary"], + [mary, "Mo Jones"], + ], + ], + ["no fallback name", {}, { about: "no name" }, {}, [[mary, "Mary"]]], + [ + "each name once", + { + [mary]: { name: "Mary", verified: { ...verified, displayName: "Mary" } }, + }, + { display_name: "Mary" }, + {}, + [ + [mary, "Mary"], + [mary, "Mary Jane Jones"], + ], + ], + [ + "a one-to-one DM's agent partner", + { [ops]: { name: "Ops", isAgent: true } }, + undefined, + { viewer, members: [viewer, ops] }, + [ + [mary, "Mary"], + [ops, "Ops"], + ], + ], + [ + "no human partner", + { [ops]: { name: "Wes" } }, + undefined, + { viewer, members: [viewer, ops] }, + [[mary, "Mary"]], + ], + [ + "no partner in a DM without the viewer", + { [ops]: { name: "Ops", isAgent: true } }, + undefined, + { viewer, members: [mary, ops] }, + [[mary, "Mary"]], + ], + [ + "no partner in a group DM", + { [ops]: { name: "Ops", isAgent: true } }, + undefined, + { viewer, members: [viewer, ops, "d".repeat(64)] }, + [[mary, "Mary"]], + ], +])("a reader may bind %s", (_case, profiles, own, dm, entries) => { + expect( + readerNames( + [{ pubkey: mary, name: "Mary" }], + new Map(Object.entries(profiles)), + (pubkey) => + own && pubkey === mary + ? { + id: "e".repeat(64), + pubkey, + created_at: 1, + kind: 0, + content: JSON.stringify(own), + tags: [], + } + : undefined, + dm.viewer, + dm.members, + ).map(({ pubkey, name }) => [pubkey, name]), + ).toEqual(entries); +}); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index 20b814618b..eb834d7acd 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -14,7 +14,10 @@ import type { PendingMention, } from "./mention-draft"; import type { ComposerResource } from "../conversation/contracts"; -import { profileMentionParts } from "./profile-mentions"; +import { profileMentionNames, profileMentionParts } from "./profile-mentions"; +import { foldProfiles } from "../relay/profiles"; +import type { Profile } from "../relay/contracts"; +import type { EventData } from "../relay/events"; import { chipLabel, composerToken, @@ -298,6 +301,16 @@ export function composerGroup(value: unknown, source: unknown) { return null; return value as ComposerGroup; } +/** `group` with only the members `keep` admits: itself when it loses none, + * `null` when none are left. */ +export function groupKeeping( + group: ComposerGroup, + keep: (pubkey: string) => boolean, +) { + const members = group.members.filter((member) => keep(member.pubkey)); + if (members.length === group.members.length) return group; + return members.length ? { label: group.label, members } : null; +} /** Whether `@label` reads as one group to whoever gets it: letters, digits * and spaces, a hyphen only between two of them, in which no reader binds * any of `people`. This app's reader matches a whole name; mobile's matches @@ -332,6 +345,37 @@ export function groupLabelHolds( ) ); } +/** Every name a reader may bind to each of `people`, and to a 1:1 DM's agent + * partner, whom the relay tags: the shown name, the verified names and the + * name set on their own profile, never a fallback name. */ +export function readerNames( + people: readonly MentionRecipient[], + profiles: ReadonlyMap, + ownProfile: (pubkey: string) => EventData | undefined, + viewer?: string, + dmMembers: readonly string[] = [], +) { + const partners = + viewer && dmMembers.length === 2 && dmMembers.includes(viewer) + ? dmMembers.flatMap((pubkey) => { + const profile = profiles.get(pubkey); + return pubkey !== viewer && profile?.isAgent + ? [{ pubkey, name: profile.name }] + : []; + }) + : []; + return [...people, ...partners].flatMap(({ pubkey, name }) => { + const event = ownProfile(pubkey); + const own = event && foldProfiles([event]).get(pubkey); + return [ + ...new Set([ + name, + ...profileMentionNames(profiles.get(pubkey)), + own && !own.nameIsFallback ? own.name : undefined, + ]), + ].flatMap((each) => (each ? [{ pubkey, name: each }] : [])); + }); +} /** A source token's recipient attributes from the draft's recipients on its * range: every labelled one as a group, else the one recipient. */ export function tokenRecipients( From a8ea5e3e3dd73194e33dda2ca1782fb49338f568 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 01:49:57 +0000 Subject: [PATCH 25/35] fix(composer): check mobile's raw name, restore only chip labels - The group label check also reads the name mobile shows for a person: the raw `display_name` of their own profile, else its raw `name`. Mobile links that name and its first word as they are, so a display name this app drops (a control or bidi character) no longer lets a label through that mobile shows as one person. - A saved draft keeps a group's members only when a chip can hold its label. Any other label comes back as plain text with no recipients, so it is no longer sent with every member tagged and no label check. - The send lock is set right before the send's `try`, so nothing that runs before it can leave the lock held. - A new message counts its recipients with `distinctRecipients`. Tests: a `tokenRecipients` table; label rows for a name with a tab in it and for a combining mark after a name; the raw-name row; the saved draft that is sent as text; and the saved group in a one-to-one DM with an agent, the case that reaches the send's label check. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/direct-messages/NewMessage.tsx | 10 ++- .../messages/MessageComposer.test.tsx | 64 ++++++++++------- src/features/messages/MessageComposer.tsx | 4 +- .../messages/composer-document.test.ts | 71 +++++++++++++++++-- src/features/messages/composer-document.ts | 16 ++++- src/features/messages/mention-draft.test.ts | 14 ++++ src/features/messages/mention-draft.ts | 4 +- 7 files changed, 145 insertions(+), 38 deletions(-) diff --git a/src/features/direct-messages/NewMessage.tsx b/src/features/direct-messages/NewMessage.tsx index 356a731b96..84c97fa9a1 100644 --- a/src/features/direct-messages/NewMessage.tsx +++ b/src/features/direct-messages/NewMessage.tsx @@ -32,7 +32,11 @@ import { type AttachmentDraft, } from "../messages/attachment-draft"; import { MessageComposer } from "../messages/MessageComposer"; -import { mentionDraft, type MentionDraft } from "../messages/mention-draft"; +import { + distinctRecipients, + mentionDraft, + type MentionDraft, +} from "../messages/mention-draft"; import { clearView, readView, writeView } from "../../shared/view-state"; import type { MessageIntent } from "../channel-navigation/routes"; import { Button } from "../../shared/design-system/ui/Button"; @@ -459,7 +463,9 @@ export function NewMessage({ session.messages.send( id, content, - [...new Set(draft.recipients.map((person) => person.pubkey))], + distinctRecipients(draft.recipients).map( + (person) => person.pubkey, + ), uploaded, { key: recoveryKey, diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 7d9c51e6c1..0d62c6557f 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -18766,31 +18766,45 @@ it("in a Solo chat with agents only, a group of people outside it whose label st tags: [first.pubkey], }); }); -it("in a one-to-one DM with an agent, a group picked with a label that starts with the agent's name is sent as its members", async () => { - const viewer = "d".repeat(64); - const ops = "c".repeat(64); - const h = mount({}, undefined, viewer); - h.setProfiles(new Map([[ops, { name: "Ops", isAgent: true }]])); - const dm = { - status: "ready" as const, - channels: [ - { id: "channel", channelType: "dm" as const, members: [viewer, ops] }, - ], - }; - Object.assign(h.session.channels, { - list: () => dm, - get: () => dm.channels[0], - }); - h.remount(); - h.fill("!Crew"); - offerCrew(h, [maryJane, wes], "Ops crew"); - await h.user.keyboard("{Enter}hi"); - expect(await sentGroups(h)).toEqual({ - groups: 0, - content: "@Mary Jane @Wes hi", - tags: [], - }); -}); +it.each([ + ["picked", 0], + ["saved in a draft", 1], +])( + "in a one-to-one DM with an agent, a group whose label starts with the agent's name is %s and sent as its members", + async (_how, groups) => { + const viewer = "d".repeat(64); + const ops = "c".repeat(64); + if (groups) + writeView( + "scope", + "draft:channel", + typedDraft(savedCrew("@Ops crew hi", "Ops crew", [maryJane, wes])), + ); + const h = mount({}, undefined, viewer); + h.setProfiles(new Map([[ops, { name: "Ops", isAgent: true }]])); + const dm = { + status: "ready" as const, + channels: [ + { id: "channel", channelType: "dm" as const, members: [viewer, ops] }, + ], + }; + Object.assign(h.session.channels, { + list: () => dm, + get: () => dm.channels[0], + }); + h.remount(); + if (!groups) { + h.fill("!Crew"); + offerCrew(h, [maryJane, wes], "Ops crew"); + await h.user.keyboard("{Enter}hi"); + } + expect(await sentGroups(h)).toEqual({ + groups, + content: "@Mary Jane @Wes hi", + tags: [], + }); + }, +); it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { const mj = { ...first, name: "MJ" }; const h = mount(); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index f47157ac7a..f28d57953e 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -3192,8 +3192,6 @@ function Composer({ typed, boundNames(routing ? recipientsNow : typed.recipients), ); - const attempt = new AbortController(); - sendAttempt.current = attempt; const explicit = human && ownerProvenance ? captured.recipients @@ -3229,6 +3227,8 @@ function Composer({ ownSoloConversation && !threadRootId && followUpBehaviorPreference() === "queue"; + const attempt = new AbortController(); + sendAttempt.current = attempt; try { if (captured !== typed && composerMarkdown(captured).length > 16000) { const groups = new Set(typed.recipients.map((item) => item.label)); diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index f43db0cdd7..8d6dad7a7a 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -4,6 +4,7 @@ import { groupKeeping, groupLabelHolds, readerNames, + tokenRecipients, composerSchema as schema, projectComposerDocument, readComposerDocument, @@ -12,7 +13,7 @@ import { import { composerMarkdown } from "./composer-markdown"; import { profileMentionParts } from "./profile-mentions"; import { profileTarget } from "../profiles/target"; -import { mentionDraft } from "./mention-draft"; +import { mentionDraft, type DraftRecipient } from "./mention-draft"; import { fromMarkdown } from "mdast-util-from-markdown"; import { gfmStrikethroughFromMarkdown } from "mdast-util-gfm-strikethrough"; import { gfmStrikethrough } from "micromark-extension-gfm-strikethrough"; @@ -838,10 +839,9 @@ it("a person chip keeps `explicit` when it is rebuilt from the draft text", () = ).toEqual([[ann.pubkey, true]]); }); -const honey = [ - { pubkey: "a".repeat(64), name: "Honey" }, - { pubkey: "b".repeat(64), name: "Honey" }, -]; +const honeyA = { pubkey: "a".repeat(64), name: "Honey" }; +const honeyB = { pubkey: "b".repeat(64), name: "Honey" }; +const honey = [honeyA, honeyB]; const maryJaneAndWes = [ { pubkey: "a".repeat(64), name: "Mary Jane" }, { pubkey: "b".repeat(64), name: "Wes" }, @@ -871,6 +871,8 @@ it.each([ ["Wesley team", maryJaneAndWes, true], ["ÉMILE crew", [{ pubkey: "a".repeat(64), name: "Émile Durand" }], false], ["ſam crew", [{ pubkey: "a".repeat(64), name: "Sam Lee" }], false], + ["Ann team", [{ pubkey: "a".repeat(64), name: "Ann\tLee" }], false], + ["Rene\u0301 fans", [{ pubkey: "a".repeat(64), name: "Rene" }], false], ])( "the group label %s holds only when it is plain text and no reader binds a member's name or first word at its start", (label, people, holds) => { @@ -893,6 +895,54 @@ it.each<[string, string[], ReturnType]>([ expect(kept === crew).toBe(expected === crew); }); +const onCrew = (person: typeof honeyA, label = "Crew") => ({ + ...person, + label, + start: 0, + end: label.length + 1, +}); +it.each<[string, DraftRecipient[], string, ReturnType]>( + [ + [ + "one recipient", + [{ ...honeyA, start: 0, end: 6 }], + "@Honey", + { recipient: { ...honeyA, start: 0, end: 6 }, group: null }, + ], + [ + "a labelled group", + [onCrew(honeyA), onCrew(honeyB)], + "@Crew", + { recipient: null, group: { label: "Crew", members: honey } }, + ], + [ + "the same person twice counts once", + [onCrew(honeyA), onCrew(honeyA), onCrew(honeyB)], + "@Crew", + { recipient: null, group: { label: "Crew", members: honey } }, + ], + [ + "a label that fails composerGroup gives neither", + [onCrew(honeyA, "Crew\u0007"), onCrew(honeyB, "Crew\u0007")], + "@Crew\u0007", + { recipient: null, group: null }, + ], + [ + "a recipient with another start or end is not on the range", + [ + { ...honeyA, start: 0, end: 11 }, + { ...honeyB, start: 1, end: 6 }, + ], + "@Honey", + { recipient: null, group: null }, + ], + ], +)("a source token's recipients: %s", (_case, recipients, source, expected) => { + expect( + tokenRecipients(recipients, source, { start: 0, end: source.length }), + ).toStrictEqual(expected); +}); + const viewer = "c".repeat(64); const [mary, ops] = ["a".repeat(64), "b".repeat(64)]; const verified = { @@ -936,6 +986,17 @@ it.each< ], ], ["no fallback name", {}, { about: "no name" }, {}, [[mary, "Mary"]]], + [ + "the raw name mobile reads", + {}, + { display_name: "Ann Lee\u200e", name: "alee" }, + {}, + [ + [mary, "Mary"], + [mary, "alee"], + [mary, "Ann Lee\u200e"], + ], + ], [ "each name once", { diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index eb834d7acd..c0cb518ead 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -345,9 +345,20 @@ export function groupLabelHolds( ) ); } +function mobileName(content: string) { + try { + const body = JSON.parse(content) as Record | null; + const name = + typeof body?.display_name === "string" ? body.display_name : body?.name; + return typeof name === "string" ? name : undefined; + } catch { + return undefined; + } +} /** Every name a reader may bind to each of `people`, and to a 1:1 DM's agent - * partner, whom the relay tags: the shown name, the verified names and the - * name set on their own profile, never a fallback name. */ + * partner, whom the relay tags: the shown name, the verified names, the name + * set on their own profile and, as mobile reads it, that profile's raw + * `display_name` or else `name`; never a fallback name. */ export function readerNames( people: readonly MentionRecipient[], profiles: ReadonlyMap, @@ -372,6 +383,7 @@ export function readerNames( name, ...profileMentionNames(profiles.get(pubkey)), own && !own.nameIsFallback ? own.name : undefined, + event && mobileName(event.content), ]), ].flatMap((each) => (each ? [{ pubkey, name: each }] : [])); }); diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 0e83d88afd..63ac80df13 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -314,3 +314,17 @@ it("a sent group whose label no longer holds is one chip per member, each keepin { ...wes, start: 6, end: 10 }, ]); }); +it("a saved group whose label has a control character, which no chip holds, is sent as text that tags nobody", () => { + const text = "@crew\u0007 hi"; + const saved = mentionDraft({ + text, + recipients: [first, second].map((person) => ({ + ...person, + label: "crew\u0007", + start: 0, + end: 6, + })), + }); + const sent = sentDraft(saved, saved.recipients); + expect([sent.text, sent.recipients]).toEqual([text, []]); +}); diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 48c723a874..172ecbb210 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -1,6 +1,7 @@ import { Fragment, Slice } from "prosemirror-model"; import { forwardReference, type ForwardReference } from "./forward-clipboard"; import { canonicalChatCard } from "./chat-cards"; +import { chipLabel } from "./composer-token"; import { composerSchema, groupLabelHolds, @@ -135,8 +136,7 @@ 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())) && + (item.label === undefined || chipLabel(item.label)) && Number.isInteger(item.start) && Number.isInteger(item.end) && item.start >= 0 && From ee5ac153bf75650a32359f6620e2fdfdb6244462 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 02:31:38 +0000 Subject: [PATCH 26/35] test(composer): guard the raw name when a profile has no display name readerNames also gives the raw kind 0 name that mobile binds: the display_name when it is a string, else the name. Only the first half had a row. This row gives an own profile whose only name has a bidi control, which this app's profile reader refuses, and expects the raw name back. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/composer-document.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 8d6dad7a7a..41a472fdaa 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -997,6 +997,16 @@ it.each< [mary, "Ann Lee\u200e"], ], ], + [ + "the raw name mobile reads with no display name", + {}, + { name: "Ann Lee\u200e" }, + {}, + [ + [mary, "Mary"], + [mary, "Ann Lee\u200e"], + ], + ], [ "each name once", { From 764d877646b6fe650642103a2bff8c4ce7facfa0 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 04:10:25 +0000 Subject: [PATCH 27/35] fix(composer): read a name trimmed, and keep the key prefix name - The group label check also tests each name after the widest trim a reader applies, whole and by its first word. That trim is Dart's `String.trim`: JavaScript's whitespace plus U+0085. A phone surface trims the raw name before it links it, so a name such as " Ann\tLee" or "Ann\u0085" no longer lets the label "Ann team" through. - `readerNames` keeps the key prefix shown for someone whose own profile sets no usable name. A reader that has that profile and no verified name shows the prefix and links it, so a label that starts with it no longer holds. Tests: label rows for a name with a leading space and for one that ends in U+0085; the reader-name rows for a profile with no name and for one whose only name is refused now expect the key prefix; one check that a label starting with the key prefix doesn't hold. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/composer-document.test.ts | 31 ++++++++++++++++++- src/features/messages/composer-document.ts | 27 +++++++++------- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 41a472fdaa..6855627720 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -872,6 +872,8 @@ it.each([ ["ÉMILE crew", [{ pubkey: "a".repeat(64), name: "Émile Durand" }], false], ["ſam crew", [{ pubkey: "a".repeat(64), name: "Sam Lee" }], false], ["Ann team", [{ pubkey: "a".repeat(64), name: "Ann\tLee" }], false], + ["Ann team", [{ pubkey: "a".repeat(64), name: " Ann\tLee" }], false], + ["Ann team", [{ pubkey: "a".repeat(64), name: "Ann\u0085" }], false], ["Rene\u0301 fans", [{ pubkey: "a".repeat(64), name: "Rene" }], false], ])( "the group label %s holds only when it is plain text and no reader binds a member's name or first word at its start", @@ -985,7 +987,16 @@ it.each< [mary, "Mo Jones"], ], ], - ["no fallback name", {}, { about: "no name" }, {}, [[mary, "Mary"]]], + [ + "the fallback name", + {}, + { about: "no name" }, + {}, + [ + [mary, "Mary"], + [mary, "aaaaaaaaaa"], + ], + ], [ "the raw name mobile reads", {}, @@ -1004,6 +1015,7 @@ it.each< {}, [ [mary, "Mary"], + [mary, "aaaaaaaaaa"], [mary, "Ann Lee\u200e"], ], ], @@ -1071,3 +1083,20 @@ it.each< ).map(({ pubkey, name }) => [pubkey, name]), ).toEqual(entries); }); + +it("a group label that starts with a member's fallback name doesn't hold", () => { + const own = { + id: "e".repeat(64), + pubkey: mary, + created_at: 1, + kind: 0, + content: JSON.stringify({ about: "no name" }), + tags: [], + }; + const people = readerNames( + [{ pubkey: mary, name: "Mary" }], + new Map(), + (pubkey) => (pubkey === mary ? own : undefined), + ); + expect(groupLabelHolds("aaaaaaaaaa team", people)).toBe(false); +}); diff --git a/src/features/messages/composer-document.ts b/src/features/messages/composer-document.ts index c0cb518ead..6e36ce4d26 100644 --- a/src/features/messages/composer-document.ts +++ b/src/features/messages/composer-document.ts @@ -314,7 +314,8 @@ export function groupKeeping( /** Whether `@label` reads as one group to whoever gets it: letters, digits * and spaces, a hyphen only between two of them, in which no reader binds * any of `people`. This app's reader matches a whole name; mobile's matches - * a name or its first word at the start, in any case, where a word ends. */ + * a name or its first word, as written or trimmed, at the start, in any + * case, where a word ends. */ export function groupLabelHolds( label: string, people: readonly MentionRecipient[], @@ -334,14 +335,16 @@ export function groupLabelHolds( ).some((part) => part.target), ) && !people.some((person) => - [person.name, person.name.split(/\s+/)[0]].some( - (name) => - !!name && - new RegExp( - `^${name.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&")}(?![\\p{L}\\p{M}\\p{N}])`, - "iu", - ).test(label), - ), + [person.name, person.name.replace(/^[\s\u0085]+|[\s\u0085]+$/g, "")] + .flatMap((name) => [name, name.split(/\s+/)[0]]) + .some( + (name) => + !!name && + new RegExp( + `^${name.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&")}(?![\\p{L}\\p{M}\\p{N}])`, + "iu", + ).test(label), + ), ) ); } @@ -357,8 +360,8 @@ function mobileName(content: string) { } /** Every name a reader may bind to each of `people`, and to a 1:1 DM's agent * partner, whom the relay tags: the shown name, the verified names, the name - * set on their own profile and, as mobile reads it, that profile's raw - * `display_name` or else `name`; never a fallback name. */ + * set on their own profile or the key prefix shown when it sets none and, as + * mobile reads it, that profile's raw `display_name` or else `name`. */ export function readerNames( people: readonly MentionRecipient[], profiles: ReadonlyMap, @@ -382,7 +385,7 @@ export function readerNames( ...new Set([ name, ...profileMentionNames(profiles.get(pubkey)), - own && !own.nameIsFallback ? own.name : undefined, + own?.name, event && mobileName(event.content), ]), ].flatMap((each) => (each ? [{ pubkey, name: each }] : [])); From b185c5257b6242c8d4153dfafc448b712270e192 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 04:29:10 +0000 Subject: [PATCH 28/35] test(composer): one label row per name rule - The two label rows added for the trim get labels of their own, so a failing row names itself. - " Ann\tLee" becomes " Ann Lee". The row now needs only the trimmed name's first word; the "Ann\tLee" row keeps the split on any space. - A row for the name as written: " ann pals" with the name " Ann". The phone matches the name as written, in any case; this app's reader matches case, so the row turns on that clause alone. - The test that chained `readerNames` into `groupLabelHolds` goes. The "the fallback name" row guards the same thing. Tests: each label row fails on its own control (the name as written left out, the trimmed name left out, JavaScript's trim, the trimmed name's first word left out, a split on spaces only). Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/composer-document.test.ts | 22 +++---------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index 6855627720..bb746d45b2 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -872,8 +872,9 @@ it.each([ ["ÉMILE crew", [{ pubkey: "a".repeat(64), name: "Émile Durand" }], false], ["ſam crew", [{ pubkey: "a".repeat(64), name: "Sam Lee" }], false], ["Ann team", [{ pubkey: "a".repeat(64), name: "Ann\tLee" }], false], - ["Ann team", [{ pubkey: "a".repeat(64), name: " Ann\tLee" }], false], - ["Ann team", [{ pubkey: "a".repeat(64), name: "Ann\u0085" }], false], + ["Ann crew", [{ pubkey: "a".repeat(64), name: " Ann Lee" }], false], + ["Ann squad", [{ pubkey: "a".repeat(64), name: "Ann\u0085" }], false], + [" ann pals", [{ pubkey: "a".repeat(64), name: " Ann" }], false], ["Rene\u0301 fans", [{ pubkey: "a".repeat(64), name: "Rene" }], false], ])( "the group label %s holds only when it is plain text and no reader binds a member's name or first word at its start", @@ -1083,20 +1084,3 @@ it.each< ).map(({ pubkey, name }) => [pubkey, name]), ).toEqual(entries); }); - -it("a group label that starts with a member's fallback name doesn't hold", () => { - const own = { - id: "e".repeat(64), - pubkey: mary, - created_at: 1, - kind: 0, - content: JSON.stringify({ about: "no name" }), - tags: [], - }; - const people = readerNames( - [{ pubkey: mary, name: "Mary" }], - new Map(), - (pubkey) => (pubkey === mary ? own : undefined), - ); - expect(groupLabelHolds("aaaaaaaaaa team", people)).toBe(false); -}); From 3539c27397b2d7fa75ddd563516e6338ec8f9f78 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 05:09:06 +0000 Subject: [PATCH 29/35] test(composer): a member name with regex characters "C++" is an ordinary name. The row checks that `groupLabelHolds` escapes a name before it builds a pattern from it: without the escape, building the pattern throws. Tests: the row passes with the escape and is the only failure without it (1 of 107). Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/composer-document.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/features/messages/composer-document.test.ts b/src/features/messages/composer-document.test.ts index bb746d45b2..d27a67d7a9 100644 --- a/src/features/messages/composer-document.test.ts +++ b/src/features/messages/composer-document.test.ts @@ -876,6 +876,7 @@ it.each([ ["Ann squad", [{ pubkey: "a".repeat(64), name: "Ann\u0085" }], false], [" ann pals", [{ pubkey: "a".repeat(64), name: " Ann" }], false], ["Rene\u0301 fans", [{ pubkey: "a".repeat(64), name: "Rene" }], false], + ["Crew", [{ pubkey: "a".repeat(64), name: "C++" }], true], ])( "the group label %s holds only when it is plain text and no reader binds a member's name or first word at its start", (label, people, holds) => { From a7e485748142aa0e3c134d61d91f6a8aa3b4b208 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 16:52:31 +0000 Subject: [PATCH 30/35] test(messages): restore the verified-name group label sends The composer's send tests for a group whose label starts with a member's verified name went away when that table moved to readerNames. Two rows come back, picked and saved in a draft. Each checks the sent text, the exact p set and how a receiver who knows the member by the verified name draws the mentions. With verified names left out of the names the composer binds labels against, when a group is picked and when it is sent, no other test in the 69 test files related to the composer fails (2273 tests), so these rows own that wiring. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 0d62c6557f..ae5b69ccd3 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -113,6 +113,7 @@ import type { EmojiSnapshot } from "../relay/emoji-directory"; import { emojiQuery } from "../../bundled/emoji/emoji-query"; import type { ComposerInputElement } from "./composer-dom"; import { profileTarget } from "../profiles/target"; +import { profileMentionParts } from "./profile-mentions"; import { fromMarkdown } from "mdast-util-from-markdown"; import { setRememberAgentsPreference } from "./mention-preferences"; import * as modelStorage from "./solo-model-picks-storage"; @@ -18805,6 +18806,65 @@ it.each([ }); }, ); +it.each([ + ["picked", 0], + ["saved in a draft", 1], +])( + "a group whose label starts with a member's verified name is %s and sent as its members", + async (_how, groups) => { + const mj = { ...first, name: "MJ" }; + const label = "Mary Jane Jones crew"; + const verified = { + displayName: "MJ", + username: "mj", + fullName: "Mary Jane Jones", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }; + if (groups) + writeView( + "scope", + "draft:channel", + typedDraft(savedCrew(`@${label} hi`, label, [mj, wes])), + ); + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ", verified }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + if (!groups) { + h.fill("!Crew"); + offerCrew(h, [mj, wes], label); + await h.user.keyboard("{Enter}hi"); + } + const sent = await sentGroups(h); + const reader = new Map([ + [mj.pubkey, { name: "Mary Jane Jones", verified }], + [wes.pubkey, { name: "Wes" }], + ]); + expect({ + ...sent, + parts: profileMentionParts( + { content: sent.content ?? "", mentions: sent.tags ?? [] }, + reader, + ), + }).toEqual({ + groups, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + parts: [ + { text: "@MJ", target: profileTarget(mj.pubkey) }, + { text: " " }, + { text: "@Wes", target: profileTarget(wes.pubkey) }, + { text: " hi" }, + ], + }); + }, +); it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { const mj = { ...first, name: "MJ" }; const h = mount(); From 39b2ddefa2ccde6aa3e96cd014592445c35156f8 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 16:52:34 +0000 Subject: [PATCH 31/35] fix(messages): stop a send whose group label a new name broke The send binds each group label to the members' names when it takes the draft, then waits: a Solo chat's members, the old-agent prompt, bringing agents in, adding people, link sharing, and in a detached window the upload. A member who took a name during a wait that the label starts with, such as the verified name "Mary" under the label "Mary crew", still had "@Mary crew hi" published, and readers linked "@Mary" to that member. Now the labels are bound again after the last wait before the text is handed to the sender: after link sharing, and in a detached window after the upload. If the answer differs, the send stops with "A member's name changed while sending. Send again." The draft and its attachments stay, Send is free, and the next Send binds the labels afresh: a label a new name broke goes out as its members. A label that was broken when Send was pressed and holds again after a wait also stops the send once. What the waits already did, such as agents brought in, people added and links shared, stays done. Once the text is handed to the sender the message is committed. A main-window upload or a send gate's hold, for example, carries it, and a name that changes then reads as any rename after sending does. Not caught: a verified name the profile store holds but has not yet published to the composer, the sender's own name change still waiting to be sent, a DM's member list that loads during the wait, and a name this device has not loaded. The first send of a new conversation from New message or a new Solo chat is not checked again either: those screens take the text before their own waits. And a new DM to one agent named "Mary" with the group "Mary crew" publishes "@Mary crew" with no wait and no rename, because that composer does not know who the DM is with. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 159 ++++++++++++++++++ src/features/messages/MessageComposer.tsx | 13 +- 2 files changed, 168 insertions(+), 4 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index ae5b69ccd3..ef4ab1a1b2 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -18865,6 +18865,165 @@ it.each([ }); }, ); +it("a group whose label a member's new verified name breaks while link sharing checks a linked chat is not sent, and the next Send sends it as its members", async () => { + const mj = { ...first, name: "MJ" }; + const link = "[Session: Work](buzz://channel/session-id)"; + const list = { + status: "ready" as const, + channels: [ + { + id: "channel", + name: "general", + channelType: "stream", + members: [mj.pubkey, wes.pubkey], + }, + { + id: "session-id", + name: "Work", + channelType: "solo", + creator: "viewer", + members: ["viewer"], + }, + ], + }; + const details = { visibility: "public", joinRole: "member" }; + const held = deferred(); + const asked = deferred(); + let loads = 0; + const load = () => { + asked.resolve(); + return loads++ ? Promise.resolve(details) : held.promise; + }; + const h = mount({}, undefined, "viewer"); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ" }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + h.retarget({ + session: { + ...h.session, + channels: { + ...h.session.channels, + list: () => list, + get: (id: string) => list.channels.find((channel) => channel.id === id), + }, + channelDetails: { snapshot: () => undefined, load }, + } as unknown as RelaySession, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mary crew"); + await h.user.keyboard("{Enter}hi "); + act(() => h.input().insertText(link)); + h.submit(); + await act(() => asked.promise); + h.setProfiles( + new Map([ + [ + mj.pubkey, + { + name: "MJ", + verified: { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }, + }, + ], + [wes.pubkey, { name: "Wes" }], + ]), + ); + await act(async () => held.resolve(details)); + await waitFor(() => + expect({ + sent: h.messages.send.mock.calls.map(([, content]) => content), + draft: h.input().value, + line: + screen.queryAllByText( + "A member's name changed while sending. Send again.", + ).length > 0, + }).toEqual({ sent: [], draft: `@Mary crew hi ${link}`, line: true }), + ); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: `@MJ @Wes hi ${link}`, + tags: [mj.pubkey, wes.pubkey], + }); +}); +it("a group whose label a member's new verified name breaks while a detached window uploads its file is not sent, and the next Send sends it as its members", async () => { + const mj = { ...first, name: "MJ" }; + const result = deferred>(); + const started = deferred(); + const upload = () => { + started.resolve(); + return result.promise; + }; + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ" }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + const { unread: _full, ...detached } = h.session; + h.retarget({ + session: { + ...detached, + attachments: { upload }, + } as unknown as RelaySession, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mary crew"); + await h.user.keyboard("{Enter}hi"); + attachByPaste(h.input(), attachmentFile()); + await act(() => started.promise); + h.submit(); + await waitFor(() => + expect(screen.getByRole("button", { name: "Send message" })).toBeDisabled(), + ); + h.setProfiles( + new Map([ + [ + mj.pubkey, + { + name: "MJ", + verified: { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }, + }, + ], + [wes.pubkey, { name: "Wes" }], + ]), + ); + await act(async () => result.resolve(uploadDescriptor())); + await waitFor(() => + expect({ + sent: h.messages.send.mock.calls.map(([, content]) => content), + draft: h.input().value, + file: screen.queryAllByText("notes.txt").length > 0, + line: + screen.queryAllByText( + "A member's name changed while sending. Send again.", + ).length > 0, + }).toEqual({ sent: [], draft: "@Mary crew hi", file: true, line: true }), + ); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + }); +}); it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { const mj = { ...first, name: "MJ" }; const h = mount(); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index f28d57953e..dd34187c4d 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -3188,10 +3188,13 @@ function Composer({ const retirementCursor = draftRetirementCursor(scope, draftKey); let retiredByOwner = false; const typed = valueRef.current; - const captured = sentDraft( - typed, - boundNames(routing ? recipientsNow : typed.recipients), - ); + const bind = () => + sentDraft(typed, boundNames(routing ? recipientsNow : typed.recipients)); + const captured = bind(); + const recheckLabels = () => { + if (composerMarkdown(bind()) !== composerMarkdown(captured)) + throw new Error("A member's name changed while sending. Send again."); + }; const explicit = human && ownerProvenance ? captured.recipients @@ -3458,6 +3461,7 @@ function Composer({ } if (!current()) return; } + recheckLabels(); // Every prompt passed, so this message goes out to who was declined. oldAgents.decline(declinedImports); // Destination and content are fixed here; a background send never retargets. @@ -3673,6 +3677,7 @@ function Composer({ reportConflict(); return; } + recheckLabels(); id = await publish(uploaded); } else if (capturedAttachments.length) { // The revision acceptance saves; remembered agents are not a draft. From 51f6cbda790dd782460e38a432b68ef5e693dc20 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 19:31:41 +0000 Subject: [PATCH 32/35] fix(messages): bind the group labels again after a main-window upload The main-window upload now binds the labels again when the upload ends, before its publish call. Where that call sends at once, nothing is awaited after the check. A failure goes through the upload's own recovery, which shows the line and returns the draft and the files, or keeps them behind "Retry failed send recovery" when the person has typed a new draft meanwhile. The previous commit's message says a main-window upload carries the text past the check. That is no longer so where the send goes out at once. A send gate's hold and a Solo follow-up that takes the queue still do: a top-level send in the person's own Solo chat with the "queue" setting and at least one notified recipient, none of them a confirmed person in the chat. With an attachment such a send always enters the queue and waits there for a member refresh. Tests: one row sends to a channel with a file, so the send goes out when the upload ends. It holds the upload while a tagged member gains the verified name "Mary", then lets it finish. Nothing is sent, the composer shows "A member's name changed while sending. Send again.", the draft and the file are back in it, and the next Send sends "@MJ @Wes hi" to the two members. The row fails on the previous commit's production, which is this commit with the new line removed, and is then the only failure in the 69 test files related to the composer (2278 tests). Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 67 +++++++++++++++++++ src/features/messages/MessageComposer.tsx | 1 + 2 files changed, 68 insertions(+) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index ef4ab1a1b2..3bb5724ee6 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -19024,6 +19024,73 @@ it("a group whose label a member's new verified name breaks while a detached win tags: [mj.pubkey, wes.pubkey], }); }); +it("a group whose label a member's new verified name breaks while the main window uploads its file is not sent, and the next Send sends it as its members", async () => { + const mj = { ...first, name: "MJ" }; + const result = deferred>(); + const started = deferred(); + const upload = () => { + started.resolve(); + return result.promise; + }; + const h = mount(); + h.setProfiles( + new Map([ + [mj.pubkey, { name: "MJ" }], + [wes.pubkey, { name: "Wes" }], + ]), + ); + h.retarget({ + session: { + ...h.session, + attachments: { upload }, + } as unknown as RelaySession, + }); + h.fill("!Crew"); + offerCrew(h, [mj, wes], "Mary crew"); + await h.user.keyboard("{Enter}hi"); + attachByPaste(h.input(), attachmentFile()); + await act(() => started.promise); + h.submit(); + await waitFor(() => expect(h.input().value).toBe("")); + h.setProfiles( + new Map([ + [ + mj.pubkey, + { + name: "MJ", + verified: { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, + }, + }, + ], + [wes.pubkey, { name: "Wes" }], + ]), + ); + await act(async () => result.resolve(uploadDescriptor())); + const form = within(h.container).getByRole("form"); + await waitFor(() => + expect({ + sent: h.messages.send.mock.calls.map(([, content]) => content), + draft: h.input().value, + file: within(form).queryAllByText("notes.txt").length > 0, + line: + within(form).queryAllByText( + "A member's name changed while sending. Send again.", + ).length > 0, + }).toEqual({ sent: [], draft: "@Mary crew hi", file: true, line: true }), + ); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@MJ @Wes hi", + tags: [mj.pubkey, wes.pubkey], + }); +}); it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { const mj = { ...first, name: "MJ" }; const h = mount(); diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index dd34187c4d..2e6a8e79c9 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -3698,6 +3698,7 @@ function Composer({ }, capturedAttachments, async (uploaded) => { + recheckLabels(); // Report a synchronous publication before the new row can render. const result = publish(uploaded); const sent = typeof result === "string" ? result : await result; From 24177c5ebf922ff776a0f411edc931138b4e801e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 20:50:40 +0000 Subject: [PATCH 33/35] fix(messages): send groups as names in a queued Solo follow-up With the follow-up setting on "queue", a top-level send in the person's own Solo chat now sends every group as one name per member, so no group chip enters the follow-up queue or its storage. An edit of a queued message can add `@label` as plain text, as typing it does; it adds no recipient. It also applies to a send in that context that goes out at once: the route is known only after the member refresh, and the text is bound before it. Commit `51f6cbda79`'s message says a Solo follow-up that takes the queue carries the text past the check. That is no longer so. A send gate's hold still does. Tests: a `sentDraft` row keeps a group whose label holds as one chip, and a second row splits it when every group is to be split. In the person's own Solo chat with the "queue" setting, a send to two agents tagged as the group "Mary crew" waits in the queue while one of them is working; one of them then gains the verified name "Mary", and when the work ends the queue sends "@MJ @Wes hi" to exactly those two keys. Storage holds that text and those two keys, and after a reload the saved row sends the same text to the same keys. A send there that goes out at once, because a person in the chat is tagged, also sends the members' names. A new Solo chat's first send keeps the group as one chip. The upload row from commit `51f6cbda79` now also checks that the next Send carries the uploaded file. Controls, on the files related to the two changed sources (5,864 tests in 132 files, one skipped), with the tests as committed except two comment lines in a helper, since removed: with both production changes taken out, 4 fail: the held queue, the restart, the send that goes out at once and the row that splits every group; with every group split at every send, 11 fail, the new Solo chat's first send and ten existing one-chip tests; without the `!submission` check, only the new Solo chat's first send fails. With the main window's upload callback publishing no files, the upload row fails at its new file check (12 of 733 in `MessageComposer.test.tsx` fail; the other 11 are existing upload tests). Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 186 +++++++++++++++++- src/features/messages/MessageComposer.tsx | 17 +- src/features/messages/mention-draft.test.ts | 37 ++++ src/features/messages/mention-draft.ts | 6 +- 4 files changed, 237 insertions(+), 9 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 3bb5724ee6..90aa79c68c 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -64,7 +64,7 @@ import { MENTION_RESOLVE_TIMEOUT_MS } from "../conversation/completion"; import { bundledContribution } from "../../plugins/provenance"; import { mentionQuery } from "../../bundled/mentions/mention-query"; import { MentionCompletion } from "../../bundled/mentions/MentionCompletion"; -import type { MentionRecipient } from "./mention-draft"; +import type { MentionDraft, MentionRecipient } from "./mention-draft"; import type { AgentLibrarySnapshot } from "../agents/library"; import { createAgentChoices } from "../agents/choices"; import type { LocalAgents } from "../agents/local"; @@ -105,6 +105,7 @@ import { } from "../../shared/view-state"; import { clearDraft } from "../drafts-sent/drafts"; import { followupDraft } from "./mention-draft"; +import { followUpStorage } from "./follow-up-storage"; import { emojiMatches, type CustomEmoji } from "../relay/emoji"; import { CustomEmoji as CustomEmojiImage } from "../../bundled/emoji/CustomEmoji"; import { EmojiCompletion } from "../../bundled/emoji/EmojiCompletion"; @@ -19090,6 +19091,189 @@ it("a group whose label a member's new verified name breaks while the main windo content: "@MJ @Wes hi", tags: [mj.pubkey, wes.pubkey], }); + expect(h.messages.send.mock.calls[0]?.[3]).toEqual([uploadDescriptor()]); +}); +const maryVerified = { + displayName: "Mary", + username: "mary", + fullName: "Mary", + issuerLabel: "Example", + verifiedAt: 1, + status: "checked" as const, + multipleIssuers: false, +}; +function queueChat( + agents: readonly MentionRecipient[], + people: readonly MentionRecipient[] = [], +) { + localStorage.setItem("buzz-follow-up-behavior.v1", "queue"); + const h = mount(); + h.setLibrary(agents.map(({ pubkey, name }) => ({ pubkey, name }))); + const rename = (verified?: typeof maryVerified) => + h.setProfiles( + new Map([ + ...agents.map(({ pubkey, name }, index) => [ + pubkey, + { + name, + isAgent: true, + ...(index === 0 && verified ? { verified } : {}), + }, + ]), + ...people.map(({ pubkey, name }) => [pubkey, { name }]), + ] as [string, Profile][]), + ); + rename(); + const listeners = new Set<() => void>(); + let activity = { + status: "unavailable", + records: [], + turns: [], + typing: [], + local: agents.slice(0, 1).map(({ pubkey }) => ({ + agent: pubkey, + channelId: "channel", + messageId: "previous", + state: "working", + scope: "scope", + threadRootId: "", + startedAt: 1, + })), + }; + const chat = { + id: "channel", + channelType: "solo", + creator: "viewer", + members: ["viewer", ...[...agents, ...people].map(({ pubkey }) => pubkey)], + }; + const channelList = { status: "ready", channels: [chat] }; + h.retarget({ + ownSoloConversation: true, + requireMention: true, + session: { + ...h.session, + viewer: "viewer", + channels: { + ...h.session.channels, + list: () => channelList, + }, + channelWrites: { + refreshMembership: async () => chat, + addAgents: vi.fn(), + }, + agentActivity: { + activate: () => () => {}, + snapshot: () => activity, + subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }, + } as unknown as RelaySession, + }); + return { + h, + rename, + finish() { + activity = { + ...activity, + local: activity.local.map((row) => ({ ...row, state: "done" })), + }; + act(() => { + for (const listener of listeners) listener(); + }); + }, + }; +} +async function sendCrew( + h: ReturnType, + members: readonly MentionRecipient[], + label: string, +) { + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, members, label); + await h.user.keyboard("{Enter}hi"); + h.submit(); +} +it("a group in a Solo follow-up that waits in the queue is sent as its members, as named when it was sent", async () => { + const mj = { ...first, name: "MJ" }; + const chat = queueChat([mj, wes]); + await sendCrew(chat.h, [mj, wes], "Mary crew"); + await screen.findByRole("region", { name: "Queued follow-ups" }); + expect(chat.h.messages.send).not.toHaveBeenCalled(); + chat.rename(maryVerified); + chat.finish(); + await waitFor(() => expect(chat.h.messages.send).toHaveBeenCalledOnce()); + expect(chat.h.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@MJ @Wes hi", + [mj.pubkey, wes.pubkey], + ]); +}); +it("a group in a queued Solo follow-up is saved as its members and sent as its members after a restart", async () => { + const mj = { ...first, name: "MJ" }; + const before = queueChat([mj, wes]); + await sendCrew(before.h, [mj, wes], "Mary crew"); + await screen.findByRole("region", { name: "Queued follow-ups" }); + expect( + followUpStorage("scope") + .load() + .map(({ text, recipients }) => ({ text, recipients })), + ).toEqual([{ text: "@MJ @Wes hi", recipients: [mj.pubkey, wes.pubkey] }]); + cleanup(); + const after = queueChat([mj, wes]); + after.rename(maryVerified); + const queued = await screen.findByRole("region", { + name: "Queued follow-ups", + }); + await within(queued).findByText("Saved before restart. Send when ready."); + await after.h.user.click( + within(queued).getByRole("button", { name: "Send" }), + ); + await waitFor(() => expect(after.h.messages.send).toHaveBeenCalledOnce()); + expect(after.h.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@MJ @Wes hi", + [mj.pubkey, wes.pubkey], + ]); + expect(before.h.messages.send).not.toHaveBeenCalled(); +}); +it("a group in a Solo send that goes out at once with the follow-up setting on queue is also sent as its members", async () => { + const guest = { pubkey: "d".repeat(64), name: "Guest" }; + const chat = queueChat([first], [guest]); + await sendCrew(chat.h, [first, guest], "Crew"); + await waitFor(() => expect(chat.h.messages.send).toHaveBeenCalledOnce()); + expect(chat.h.messages.send.mock.calls[0]?.slice(1, 3)).toEqual([ + "@Honey @Guest hi", + [first.pubkey, guest.pubkey], + ]); + expect( + screen.queryByRole("region", { name: "Queued follow-ups" }), + ).toBeNull(); +}); +it("a new Solo chat's first send with the follow-up setting on queue keeps a group as one chip", async () => { + localStorage.setItem("buzz-follow-up-behavior.v1", "queue"); + const submit = vi.fn(); + const h = mount({ + ownSoloConversation: true, + submission: { + draftKey: "new-draft", + locked: false, + disabled: false, + submit, + }, + }); + h.setLibrary([first, second].map(({ pubkey, name }) => ({ pubkey, name }))); + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, [first, second], "Crew"); + await h.user.keyboard("{Enter}hi"); + h.submit(); + await waitFor(() => expect(submit).toHaveBeenCalledOnce()); + const sent = submit.mock.calls[0]?.[0] as MentionDraft; + expect([sent.text, sent.recipients.map(({ label }) => label)]).toEqual([ + "@Crew hi", + ["Crew", "Crew"], + ]); }); it("a group picked with a label that starts with the name a member set on their own profile is sent as its members", async () => { const mj = { ...first, name: "MJ" }; diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 2e6a8e79c9..ac4c541dfd 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -3188,8 +3188,18 @@ function Composer({ const retirementCursor = draftRetirementCursor(scope, draftKey); let retiredByOwner = false; const typed = valueRef.current; + const queueable = + !!host && + ownSoloConversation && + !submission && + !threadRootId && + followUpBehaviorPreference() === "queue"; const bind = () => - sentDraft(typed, boundNames(routing ? recipientsNow : typed.recipients)); + sentDraft( + typed, + boundNames(routing ? recipientsNow : typed.recipients), + queueable, + ); const captured = bind(); const recheckLabels = () => { if (composerMarkdown(bind()) !== composerMarkdown(captured)) @@ -3225,11 +3235,6 @@ function Composer({ const fromPill = routing && captured.recipients.every((person) => referenced(person.pubkey)); - const queueable = - !!host && - ownSoloConversation && - !threadRootId && - followUpBehaviorPreference() === "queue"; const attempt = new AbortController(); sendAttempt.current = attempt; try { diff --git a/src/features/messages/mention-draft.test.ts b/src/features/messages/mention-draft.test.ts index 63ac80df13..47e963ac33 100644 --- a/src/features/messages/mention-draft.test.ts +++ b/src/features/messages/mention-draft.test.ts @@ -314,6 +314,43 @@ it("a sent group whose label no longer holds is one chip per member, each keepin { ...wes, start: 6, end: 10 }, ]); }); +const crewMary = { pubkey: "5".repeat(64), name: "Mary" }; +const crewWes = { pubkey: "6".repeat(64), name: "Wes" }; +it.each([ + [ + false, + "@crew hi", + [crewMary, crewWes].map((person) => ({ + ...person, + label: "crew", + start: 0, + end: 5, + })), + ], + [ + true, + "@Mary @Wes hi", + [ + { ...crewMary, start: 0, end: 5 }, + { ...crewWes, start: 6, end: 10 }, + ], + ], +])( + "a sent group whose label holds is one chip, or one chip per member when every group is split (every: %s)", + (every, text, recipients) => { + const saved = typedDraft({ + text: "@crew hi", + recipients: [crewMary, crewWes].map((person) => ({ + ...person, + label: "crew", + start: 0, + end: 5, + })), + }); + const sent = sentDraft(saved, saved.recipients, every); + expect([sent.text, sent.recipients]).toEqual([text, recipients]); + }, +); it("a saved group whose label has a control character, which no chip holds, is sent as text that tags nobody", () => { const text = "@crew\u0007 hi"; const saved = mentionDraft({ diff --git a/src/features/messages/mention-draft.ts b/src/features/messages/mention-draft.ts index 172ecbb210..000aa5405d 100644 --- a/src/features/messages/mention-draft.ts +++ b/src/features/messages/mention-draft.ts @@ -186,16 +186,18 @@ export function mentionDraft(value: unknown): MentionDraft { /** `draft` as a send gives it: a group chip whose label no longer holds * against the `people` the send tags is one chip per member, each keeping its * explicit pick. With nothing to split it returns `draft` itself; the draft - * in the box is left as typed. */ + * in the box is left as typed. With `every`, every group chip is split. */ export function sentDraft( draft: MentionDraft, people: readonly MentionRecipient[], + every = false, ) { if (!draft.recipients.some((item) => item.label !== undefined)) return draft; const doc = readComposerDocument(draft, draft.recipients); const stale = projectComposerDocument(doc).tokens.filter( ({ node }) => - node.attrs.group && !groupLabelHolds(node.attrs.group.label, people), + node.attrs.group && + (every || !groupLabelHolds(node.attrs.group.label, people)), ); if (!stale.length) return draft; const split = stale.reduceRight((next, { from, to, node }) => { From 6c1dbde905fb138a9881e240f137f220c540160f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 23 Nov 2026 17:50:26 +0000 Subject: [PATCH 34/35] test(messages): a group further in a Solo draft joins the toolbar's agent Since #3854, a Solo draft alone with agents goes to the toolbar's agents and its tags, unless a tag opens the text. A group chip gives each member the chip's place in the text, so a chip further in joins the toolbar's agents, as a single tag does. The row: in a Solo chat of three agents with Ada in the toolbar, a saved draft "Plan this, then ask @Crew" (Crew: Bea and Cam) shows "Sending to Ada, Bea, Cam", keeps the chip, and sends that text to Ada, Bea and Cam. Control: with group members put at the text's start where `sendRecipients` asks who the draft is for, this row fails, and no other of the 2,377 tests in the files related to MessageComposer.tsx and recipients.ts. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../messages/MessageComposer.test.tsx | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 8c839c049a..34ddbe6593 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -19948,6 +19948,39 @@ it("in a Solo chat with agents only, a group of people outside it whose label st tags: [first.pubkey], }); }); +it("in a Solo chat with agents only, a group further in the draft joins the toolbar's agent", async () => { + const cam = { pubkey: "f".repeat(64), name: "Cam" }; + writeView( + "scope", + "draft:channel", + typedDraft( + savedCrew("Plan this, then ask @Crew", "Crew", [ + { pubkey: second.pubkey, name: "Bea" }, + cam, + ]), + ), + ); + const { h, ada, sendingTo } = mountSoloAgents({ + members: [first.pubkey, second.pubkey, cam.pubkey], + unpicked: true, + }); + h.setLibrary([first, second, cam]); + h.setProfiles( + new Map([ + [first.pubkey, { name: "Ada", isAgent: true }], + [second.pubkey, { name: "Bea", isAgent: true }], + [cam.pubkey, { name: "Cam", isAgent: true }], + ]), + ); + await choicesLoaded(); + act(() => h.commands().audience?.only([ada])); + expect(sendingTo("Ada, Bea, Cam")).toBeInTheDocument(); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "Plan this, then ask @Crew", + tags: [first.pubkey, second.pubkey, cam.pubkey], + }); +}); it.each([ ["picked", 0], ["saved in a draft", 1], From e28da5607f27da3dd0e7fc7f277b5d0ea3c2df7e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Mon, 23 Nov 2026 17:50:30 +0000 Subject: [PATCH 35/35] fix(solo): a group chip that opens a Solo draft opens it for its members A group chip tags each member at the chip's place in the text. When its first member is someone outside the chat, which only references them, and another member is one of the chat's agents, `soloAudience` took the first member as the opening tag, saw a reference, and the send added the toolbar's agents. The composer leaves references out before it asks, so it showed the group's agent alone. `soloAudience` now opens the draft when any recipient at the earliest place is named. Single tags never share a place, so their result is unchanged. Tests: a row in the `soloAudience` table (a reference and Bea, both at the start, open the draft) and a composer row (a Solo chat with Ada in the toolbar; "@Crew hi", where Crew is Cy, outside the chat, then Bea: it shows "Sending to Bea" and sends to Bea alone). Without the fix both fail: the table gives `opensWithTag: false`, and the send goes to Ada and Bea. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- src/features/messages/MessageComposer.test.tsx | 17 +++++++++++++++++ src/features/solo/recipients.test.ts | 11 +++++++++++ src/features/solo/recipients.ts | 13 ++++++------- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/src/features/messages/MessageComposer.test.tsx b/src/features/messages/MessageComposer.test.tsx index 34ddbe6593..47c545f366 100644 --- a/src/features/messages/MessageComposer.test.tsx +++ b/src/features/messages/MessageComposer.test.tsx @@ -19981,6 +19981,23 @@ it("in a Solo chat with agents only, a group further in the draft joins the tool tags: [first.pubkey, second.pubkey, cam.pubkey], }); }); +it("in a Solo chat with agents only, a group that opens the draft is for its members alone when the first is outside the chat", async () => { + const { h, sendingTo } = mountSoloAgents(); + await choicesLoaded(); + h.fill("!Crew"); + offerCrew(h, [ + { pubkey: "d".repeat(64), name: "Cy" }, + { pubkey: second.pubkey, name: "Bea" }, + ]); + await h.user.keyboard("{Enter}"); + act(() => void h.commands().insertText("hi")); + expect(sendingTo("Bea")).toBeInTheDocument(); + expect(await sentGroups(h)).toEqual({ + groups: 1, + content: "@Crew hi", + tags: [second.pubkey], + }); +}); it.each([ ["picked", 0], ["saved in a draft", 1], diff --git a/src/features/solo/recipients.test.ts b/src/features/solo/recipients.test.ts index 29619d919d..97ee2e5952 100644 --- a/src/features/solo/recipients.test.ts +++ b/src/features/solo/recipients.test.ts @@ -137,4 +137,15 @@ it("a draft that opens with a tag is for its tags; a later tag joins the toolbar }); // No tags: the toolbar's agents. expect(soloAudience("hi", [], [ada], named).recipients).toEqual([ada]); + expect( + soloAudience( + "@Crew hi", + [{ ...reference, end: 5 }, tag(bea, 0)], + [ada], + named, + ), + ).toEqual({ + opensWithTag: true, + recipients: [{ ...reference, end: 5 }, tag(bea, 0)], + }); }); diff --git a/src/features/solo/recipients.ts b/src/features/solo/recipients.ts index 5f40787376..5b4d346bf6 100644 --- a/src/features/solo/recipients.ts +++ b/src/features/solo/recipients.ts @@ -43,20 +43,19 @@ export function soloRecipients( /** Solo, alone with agents: who a draft addresses. A draft that opens with a * tag is for the agents it tags; a tag further in joins the toolbar's agents. - * `named` tells a notifying tag from a reference, which never opens one. */ + * `named` tells a notifying tag from a reference, which never opens one. A + * group chip tags each member at one place, so it opens the draft when any + * member is named. */ export function soloAudience>( text: string, typed: readonly (T & Readonly<{ start: number }>)[], toolbar: readonly T[], named: (pubkey: string) => boolean, ): { opensWithTag: boolean; recipients: readonly T[] } { - const first = typed.reduce<(typeof typed)[number] | undefined>( - (earliest, item) => - !earliest || item.start < earliest.start ? item : earliest, - undefined, - ); + const start = Math.min(...typed.map((item) => item.start)); const opensWithTag = - !!first && named(first.pubkey) && !text.slice(0, first.start).trim(); + typed.some((item) => item.start === start && named(item.pubkey)) && + !text.slice(0, start).trim(); const recipients = opensWithTag ? typed : [...toolbar, ...typed]; return { opensWithTag,