diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 2016330cc9..6e23a5ece3 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3439,6 +3439,31 @@ 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 `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 +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. 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`, +`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. Only a +published hold holds: a supplement that has published nothing for this query +holds nothing, so one that is still loading publishes `holdAutoSelect: true` +in its mount effect, for every query. One that fails drops only its own section +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 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..60684f4e03 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,402 @@ 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" }; +const ENG_LEAD = { pubkey: "f".repeat(64), name: "Eng Lead" }; +type Source = Readonly<{ + id: string; + order?: number; + supplement?: true; + title?: string; + result?: CompletionResult | (() => never) | undefined; + 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(); + let 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; + const listeners = new Set<() => void>(); + render( + registered, + subscribe: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }} + 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; + 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 = {}) => + ({ + 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, +) => + ({ + id: "groups", + title: "Groups", + order, + supplement: true, + result, + }) satisfies Source; +const groupRow = { + id: "x", + label: "eng", + edit: { mentions: [BOB] }, +} as const; + +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$/ }); + expect(listed()).toEqual(["Groups", "eng", "Mention", "Eng Bot"]); + cleanup(); + mountSources([people(), groups({ items: [groupRow] }, 10)]); + await screen.findByRole("option", { name: /^eng$/ }); + 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("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", + ); + cleanup(); + const fresh = mountSources([people(), groups({ items: [groupRow] }, 10)]); + await screen.findByRole("option", { name: /^eng$/ }); + fresh.press("Enter"); + expect(fresh.replace).toHaveBeenLastCalledWith( + { mention: ENG_BOT }, + 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([ + ["has not answered", undefined], + ["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"]); + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); + error.mockRestore(); +}); +it("drops a supplement removed while the menu is open, with its hold", async () => { + const { replace, press, publishes, unregister } = mountSources([ + people({ + items: [ + { id: "x", label: "Eng Bot", edit: { mention: ENG_BOT } }, + { id: "y", label: "Eng Lead", edit: { mention: ENG_LEAD } }, + ], + }), + groups({ items: [groupRow], holdAutoSelect: true }, 10), + ]); + await screen.findByRole("option", { name: /^eng$/ }); + press("ArrowDown"); + await screen.findByRole("option", { name: /^Eng Lead$/, selected: true }); + const stale = publishes.get("groups"); + unregister("groups"); + expect(listed()).toEqual(["Eng Bot", "Eng Lead"]); + press("Enter"); + expect(replace).toHaveBeenLastCalledWith( + { mention: ENG_LEAD }, + expect.anything(), + expect.anything(), + "Enter", + ); + let late: ReturnType | undefined; + act(() => { + late = stale?.({ items: [groupRow] }); + }); + expect(late).toBe(false); + expect(listed()).toEqual(["Eng Bot", "Eng Lead"]); + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); +}); +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 { + 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("keeps Escape for a supplement that publishes a hold beside an empty winner, and not for a silent one", () => { + const empty = people({ items: [], spaceId: undefined }); + expect( + mountSources([empty, groups({ items: [], holdAutoSelect: true })]).press( + "Escape", + ), + ).toBe(true); + cleanup(); + expect(mountSources([empty, groups(undefined)]).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("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 cfad1b1f14..ae99a21aa8 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -20,7 +20,10 @@ import { useRef, useState, useSyncExternalStore, + type Dispatch, + type ReactNode, type RefObject, + type SetStateAction, } from "react"; import type { Contribution } from "../../plugins/contributions"; import type { @@ -38,15 +41,15 @@ import { IdentityMarks } from "./IdentityMarks"; import { 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, @@ -95,16 +98,23 @@ 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. */ +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) { @@ -192,6 +202,8 @@ export function ComposerCompletions({ registry.snapshot, ); const [display] = useState(createDisplay); + // Only user navigation pins an ID; automatic selection follows the first result. + const [pin, setPin] = useState<{ scope: string; row?: string | undefined }>(); // Query owners remount on typing. Keep the last physical position with the // host, recording after row handlers have compared the previous position. const pointerPosition = @@ -218,6 +230,26 @@ export function ComposerCompletions({ ...(resolved.pending ?? []), ...(resolved.tokens ?? []), ]); + const scope = JSON.stringify( + match && observation + ? [ + contributionKey(match.provider), + observation.revision, + match.query.start, + match.query.end, + match.query.query, + ] + : null, + ); + const select = useCallback( + (row: SetStateAction) => + setPin((previous) => { + const held = previous?.scope === scope ? previous.row : undefined; + const next = typeof row === "function" ? row(held) : row; + return next === held ? previous : { scope, row: next }; + }), + [scope], + ); const open = !!match && !!observation && @@ -232,17 +264,18 @@ 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 ( [ + contributionKey(provider), + query.end, + query.query, + ]), ])} fallback={ @@ -256,18 +289,32 @@ export function ComposerCompletions({ identityMarks={identityMarks} display={display} provider={match.provider} + sources={match.sources} query={match.query} observation={observation} editor={editor} input={input} replace={replace} pointerPosition={pointerPosition} + selected={pin?.scope === scope ? pin.row : undefined} + setSelected={select} /> ); } +type Row = Readonly<{ + source: CompletionMatch; + key: string; + item?: HostCompletionSuggestion; + heading?: string; +}>; +const slot = ({ provider }: CompletionMatch) => contributionKey(provider); +const rowKey = (source: CompletionMatch, id?: string) => + JSON.stringify([slot(source), id ?? null]); + function OwnedCompletion({ provider, + sources: matched, registry, identityMarks, display, @@ -277,9 +324,14 @@ function OwnedCompletion({ input, replace, pointerPosition, + selected, + setSelected, ...context }: CompletionContext & { + selected: string | undefined; + setSelected: Dispatch>; provider: Contribution; + sources: readonly CompletionMatch[]; registry: ContributionReader; identityMarks?: ContributionReader | undefined; display: ReturnType; @@ -316,15 +368,16 @@ function OwnedCompletion({ ); const list = useRef(null); const trigger = `${contributionKey(provider)}:${query.start}`; - const result = useSyncExternalStore( + const [sources] = useState(matched); + const results = useSyncExternalStore( display.subscribe, () => display.read(trigger), () => display.read(trigger), ); + const result = results?.[contributionKey(provider)]; // 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 latest = useRef(new Map()); + const failed = useRef(new Set()); const [keyboardSelection, setKeyboardSelection] = useState(); const pointerMoved = useCallback( (event: Pick) => { @@ -355,63 +408,132 @@ function OwnedCompletion({ current.current = { editor, replace }; }); const active = useCallback( - () => + (candidate: Contribution) => live.current && - registry.snapshot().includes(provider) && + !failed.current.has(contributionKey(candidate)) && + registry.snapshot().includes(candidate) && 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( + 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); + 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; live.current = false; - latest.current = undefined; + published.clear(); }; - }, [active, display, provider, trigger]); + }, [active, display, sources, trigger, setSelected]); // 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. useEffect(() => { - if (publish && !latest.current) display.set(trigger, undefined); - }, [publish, display, trigger]); - const items = result?.items ?? []; + 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]); + const held = () => + sources.some((source) => { + const published = latest.current.get(slot(source)); + return ( + source.provider !== provider && + !failed.current.has(slot(source)) && + published?.holdAutoSelect === true + ); + }); + const isolate = (source: CompletionMatch, node: ReactNode) => + source.provider === provider ? ( + node + ) : ( + { + if (!failure) return; + failed.current.add(slot(source)); + display.set(trigger, slot(source)); + }} + > + {node} + + ); + const rows: Row[] = []; + for (const source of sources) { + const shown = results?.[slot(source)]; + const own: Row[] = [ + ...(shown?.items ?? []).map((item) => ({ + source, + key: rowKey(source, item.id), + item, + })), + ...(shown?.retry ? [{ source, key: rowKey(source) }] : []), + ]; + const first = own[0]; + 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?.[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 = !!(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, event: Event, 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 ?? { 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(); return true; @@ -419,11 +541,11 @@ 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 = withHumanMentionSelection(event, () => - current.current.replace(item.edit, query, observation, key), + current.current.replace(item.edit, source.query, observation, key), ); if (accepted) current.current.editor.invalidate(); return accepted; @@ -433,7 +555,8 @@ 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. - if (!element || (!visible && result && !result.spacePending)) return; + if (!element || (!visible && result && !result.spacePending && !held())) + return; if (visible) { element.setAttribute("aria-autocomplete", "list"); element.setAttribute("aria-haspopup", "listbox"); @@ -464,7 +587,7 @@ function OwnedCompletion({ (event.key === " " || !terminates(event.key)) ) return false; - if (!active()) { + 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) { @@ -480,7 +603,9 @@ 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. - const published = latest.current; + const published = held() + ? undefined + : latest.current.get(contributionKey(provider)); if ( terminates(event.key) && published?.spaceId && @@ -524,8 +649,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) { @@ -551,17 +676,24 @@ function OwnedCompletion({ element.removeAttribute("aria-activedescendant"); }; }); - const Provider = provider.component; return ( <> - {publish && ( - - )} + {publishers && + sources.map((source, i) => { + const Provider = source.provider.component; + const publish = publishers[i]; + if (!publish) return null; + return isolate( + source, + , + ); + })} {visible && input.current && createPortal( @@ -580,16 +712,16 @@ function OwnedCompletion({ ref={list} className={styles.list} > - {items.flatMap((item, i) => [ - item.group && item.group !== items[i - 1]?.group && ( + {lines.flatMap(({ item, source, key, heading, described }, i) => [ + heading && ( // Read as the description of each row it heads. ), // The textarea owns keyboard focus/selection via aria-activedescendant. @@ -598,21 +730,18 @@ function OwnedCompletion({ role="option" tabIndex={-1} aria-selected={i === selectedIndex} - aria-disabled={!!item.disabled} + aria-disabled={item && !!item.disabled} aria-label={ - compact && item.detail + compact && item?.detail ? `${item.label} ${item.detail}` : undefined } id={`${id}-${i}`} // The provider's identity for the row (a mention's key), // which its label no longer spells out. - data-completion-id={item.id} - key={item.id} - aria-describedby={ - item.group && - `${id}-group-${items.findIndex((row) => row.group === item.group)}` - } + data-completion-id={item?.id} + key={key} + aria-describedby={described} onPointerDown={(event) => { if (event.button === 0) event.preventDefault(); }} @@ -624,87 +753,79 @@ function OwnedCompletion({ if (compact && !pointerMoved(event)) return; revealSelection.current = false; setKeyboardSelection(undefined); - setSelected(item.id); + setSelected(key); } : undefined } onClick={(event) => accept(i, event.nativeEvent)} className={styles.option} > - {item.preview && ( + {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.agent && ( + Agent + )} + + ) : ( + item.label + )} + {item.detail && ( + + {item.detail} + + )} )} - - {compact ? ( - - ) : named ? ( - // Only the name ellipsizes; the agent mark stays visible. - - {item.label} - {mention && item.edit.mention && ( - - )} - {item.agent && ( - - )} - {item.agent && Agent} - - ) : ( - item.label - )} - {item.detail && ( - - {item.detail} - - )} - - {channel && i === selectedIndex && ( + {channel && item && i === selectedIndex && ( )} + {!item && + (source.provider === provider + ? "Retry suggestions" + : `Retry ${source.provider.title} suggestions`)} , ])} - {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={(event) => accept(items.length, event.nativeEvent)} - > - Retry suggestions -
- )} - {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..dbb2c13c90 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -33,6 +33,10 @@ export type HostCompletionSuggestion = Omit & export type HostCompletionResult = Omit & Readonly<{ items: readonly HostCompletionSuggestion[] }>; +export type CompletionMatch = Readonly<{ + provider: Contribution; + query: CompletionQuery; +}>; export function matchCompletion( providers: readonly Contribution[], observation: ComposerObservation, @@ -41,9 +45,7 @@ export function matchCompletion( ) { const order = (value: ComposerCompletion) => Number.isFinite(value.order) ? (value.order ?? 0) : 0; - let winner: - | { provider: Contribution; query: CompletionQuery } - | undefined; + const matches: CompletionMatch[] = []; for (const provider of [...providers].sort( (a, b) => order(a) - order(b) || a.key.localeCompare(b.key), )) { @@ -56,22 +58,35 @@ export function matchCompletion( validQuery(query, observation) && !resolved.some( (span) => span.start <= query.start && query.start < span.end, - ) && - (!winner || query.start > winner.query.start) + ) ) - winner = { + matches.push({ provider, query: Object.freeze({ start: query.start, end: query.end, query: query.query, }), - }; + }); } catch { /* A broken optional matcher cannot break editing. */ } } - return winner; + 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); + const sources = matches.filter( + (match) => + match === winner || + (match.provider.supplement === true && match.query.start === start), + ); + return ( + winner && { + ...winner, + sources, + supplements: sources.filter((match) => match !== winner), + } + ); } function validQuery( query: CompletionQuery | null, @@ -96,6 +111,7 @@ export function completionResult( ): HostCompletionResult { const ids = new Set(); const items: HostCompletionSuggestion[] = []; + const supplement = provider?.supplement === true; for (const item of (Array.isArray(result?.items) ? result.items : []).slice( 0, 50, @@ -153,9 +169,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 +211,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 4c053aeb51..2ba6178c37 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -433,6 +433,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<{ @@ -446,6 +450,14 @@ export type ComposerCompletion = Readonly<{ id: string; title: string; order?: number; + /** 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. A supplement + * that has published nothing holds nothing, so one whose source is still + * loading publishes `holdAutoSelect: true` in its mount effect, for every + * query. 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, diff --git a/src/features/conversation/service.test.tsx b/src/features/conversation/service.test.tsx index f71ec423d1..2b8c4b758a 100644 --- a/src/features/conversation/service.test.tsx +++ b/src/features/conversation/service.test.tsx @@ -415,6 +415,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 c86e42f7d9..dfea754a74 100644 --- a/src/features/conversation/service.tsx +++ b/src/features/conversation/service.tsx @@ -87,6 +87,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; @@ -413,10 +416,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); diff --git a/tests/browser/completion-work.spec.mjs b/tests/browser/completion-work.spec.mjs index 703fc022d0..b9515d9181 100644 --- a/tests/browser/completion-work.spec.mjs +++ b/tests/browser/completion-work.spec.mjs @@ -314,3 +314,105 @@ test("completed, dismissed and refuted mention searches stay closed while fresh await freshSearch(before); expect(await searches()).not.toContainEqual(expect.stringContaining("Zed ")); }); + +for (const row of ["people", "supplement"]) { + 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"); + const input = page.getByRole("textbox", { name: "Message #General" }); + await expect + .poll(() => page.evaluate(() => window.mentionFixture.list().status)) + .toBe("ready"); + const crew = page.getByRole("option", { name: "Honey crew" }); + const pick = + row === "people" + ? page.getByRole("option").filter({ hasNotText: "Honey crew" }).first() + : crew; + const proof = () => + page.evaluate(() => window.mentionFixture.ownerMention(null)); + for (const trusted of [false, true]) { + await input.fill("@Hon"); + await expect(crew).toBeVisible(); + if (trusted) await pick.click(); + else await pick.dispatchEvent("click"); + await expect(input.locator(".inline-chip")).toHaveCount( + row === "people" ? 1 : 2, + ); + const count = await page.evaluate( + () => window.mentionFixture.publications.length, + ); + await page + .getByRole("button", { name: "Send message", exact: true }) + .click(); + await expect + .poll(() => + page.evaluate(() => window.mentionFixture.publications.length), + ) + .toBe(count + 1); + const sent = await page.evaluate(() => + window.mentionFixture.publications.at(-1), + ); + const tagged = sent.tags + .filter(([tag]) => tag === "p") + .map(([, key]) => key); + expect(tagged).toHaveLength(row === "people" ? 1 : 2); + await expect + .poll(() => + page.evaluate( + (id) => window.mentionFixture.confirmedOwnerSends(null, [id]), + sent.id, + ), + ) + .toEqual([sent.id]); + if (!trusted) { + expect(await proof()).toBeNull(); + continue; + } + const latest = await proof(); + expect(latest?.eventId).toBe(sent.id); + expect([...latest.recipientIds].sort()).toEqual(tagged.sort()); + } + }); +} + +for (const mode of ["hold", "silent"]) { + test(`Space picks an exact person unless a supplement published a hold (${mode})`, async ({ + page, + }) => { + await page.goto( + `/tests/fixtures/mentions.html?delayed-profiles&supplement=${mode}`, + ); + await page.evaluate(() => window.mentionFixture.releaseProfiles()); + const input = page.getByRole("textbox", { name: "Message #General" }); + await expect + .poll(() => page.evaluate(() => window.mentionFixture.list().status)) + .toBe("ready"); + await input.pressSequentially("@Mary Jane "); + if (mode === "silent") { + await expect(input.locator(".inline-chip")).toHaveText("@Mary Jane"); + return; + } + await expect(input).toHaveJSProperty("value", "@Mary Jane "); + await expect(input.locator(".inline-chip")).toHaveCount(0); + }); +} + +for (const key of ["Enter", "Tab"]) { + test(`${key} takes a supplement row ordered first`, async ({ page }) => { + await page.goto("/tests/fixtures/mentions.html?supplement=hold"); + const input = page.getByRole("textbox", { name: "Message #General" }); + await expect + .poll(() => page.evaluate(() => window.mentionFixture.list().status)) + .toBe("ready"); + await input.fill("@Hon"); + await expect( + page.getByRole("option", { name: "Honey crew", selected: true }), + ).toBeVisible(); + await input.press(key); + await expect(input.locator(".inline-chip")).toHaveCount(2); + }); +} diff --git a/tests/fixtures/mentions.tsx b/tests/fixtures/mentions.tsx index 43e592ae5a..fdf0ab8793 100644 --- a/tests/fixtures/mentions.tsx +++ b/tests/fixtures/mentions.tsx @@ -3,7 +3,7 @@ import { MessageComposer } from "../../src/features/messages/MessageComposer"; import "../../src/shared/styles/globals.css"; import { useKeyboardFocusVisibility } from "../../src/shared/design-system/useKeyboardFocusVisibility"; import { AgentSettings } from "../../src/app/AgentSettings"; -import { StrictMode, useState, useLayoutEffect } from "react"; +import { StrictMode, useEffect, useState, useLayoutEffect } from "react"; import { createRoot } from "react-dom/client"; import { finalizeEvent } from "nostr-tools"; import { Context } from "@deepseek-ai/cordis"; @@ -16,6 +16,7 @@ import { SettingsCardsService } from "../../src/features/settings/service"; import { provideNavigation } from "../../src/features/navigation/service"; import { ConversationService } from "../../src/features/conversation/service"; import { bundledPlugins } from "../../src/bundled"; +import { mentionQuery } from "../../src/bundled/mentions/mention-query"; import { conversationFeatures } from "../../src/app/conversation-features"; import { bindNames } from "../../src/features/identity-names/service"; import { createAgentDirectory } from "../../src/features/identity-names/testing"; @@ -92,6 +93,7 @@ const secondProfile = () => ); const delayed = new URLSearchParams(location.search).has("delayed-profiles"); const testControls = new URLSearchParams(location.search).has("test-controls"); +const supplement = new URLSearchParams(location.search).get("supplement"); const channels = new URLSearchParams(location.search).has("channels"); const stream = new URLSearchParams(location.search).has("stream"); // Opt-in roster scale for local typing diagnostics; ordinary journeys keep two channels. @@ -344,6 +346,53 @@ const plugins = createPluginManager(context, { ({ manifest }) => channels && ["buzz.channels", "buzz.links"].includes(manifest.id), ), + ...(supplement !== null + ? [ + { + manifest: { + id: "test.crew", + name: "Crew supplement", + apiVersion: 1, + }, + module: { + inject: ["conversation"], + apply(ctx) { + ctx.conversation.registerCompletionSupplement({ + id: "crew", + title: "Crews", + order: supplement === "hold" ? -20 : 10, + match: ({ text, start }) => mentionQuery(text, start), + component: ({ publish }) => { + useEffect(() => { + if (supplement === "silent") return; + return ( + publish({ + items: [ + { + id: "crew", + label: "Honey crew", + edit: { + mentions: [ + { pubkey: first.pubkey, name: "Honey" }, + { pubkey: second.pubkey, name: "Honey" }, + ], + }, + }, + ], + ...(supplement === "hold" + ? { holdAutoSelect: true } + : {}), + }) || undefined + ); + }, [publish]); + return null; + }, + }); + }, + }, + }, + ] + : []), { manifest: { id: "test.disabled-command",