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

{status}

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

+ {status} +

+ ))} , // A body sibling would sit behind a fullscreen modal and outside its // accessibility boundary. Ordinary composers keep the body portal. diff --git a/src/features/conversation/completion.test.ts b/src/features/conversation/completion.test.ts index 6e89baea69..25f6651245 100644 --- a/src/features/conversation/completion.test.ts +++ b/src/features/conversation/completion.test.ts @@ -51,6 +51,22 @@ it("validates and deterministically arbitrates optional provider ranges", () => matchCompletion([provider("a", 0, 3)], { ...observation, end: 4 }, context), ).toBeUndefined(); }); +it("keeps a supplement beside the winner only at the winner's start", () => { + const beside = (start: number, order = -20) => ({ + ...provider(`beside-${start}`, start, 3, order), + supplement: true as const, + }); + const match = matchCompletion( + [provider("people", 1, 3), beside(1), beside(0)], + observation, + context, + ); + expect(match?.provider.id).toBe("people"); + expect(match?.supplements.map(({ provider }) => provider.id)).toEqual([ + "beside-1", + ]); + expect(matchCompletion([beside(1)], observation, context)).toBeUndefined(); +}); it("snapshots valid edit primitives, rejects malformed/duplicate candidates and bounds output", () => { const recipient = { pubkey: "a".repeat(64), name: "Honey" }; const input = { diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 1d59ce7f6a..299ea116fa 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -33,45 +33,60 @@ export type HostCompletionSuggestion = Omit & export type HostCompletionResult = Omit & Readonly<{ items: readonly HostCompletionSuggestion[] }>; +export type CompletionMatch = Readonly<{ + provider: Contribution; + query: CompletionQuery; +}>; +const order = (value: ComposerCompletion) => + Number.isFinite(value.order) ? (value.order ?? 0) : 0; +/** Provider precedence: `order`, then contribution key. */ +export const byOrder = ( + a: Contribution, + b: Contribution, +) => order(a) - order(b) || a.key.localeCompare(b.key); export function matchCompletion( providers: readonly Contribution[], observation: ComposerObservation, context: CompletionContext, resolved: readonly Readonly<{ start: number; end: number }>[] = [], -) { - const order = (value: ComposerCompletion) => - Number.isFinite(value.order) ? (value.order ?? 0) : 0; - let winner: - | { provider: Contribution; query: CompletionQuery } - | undefined; - for (const provider of [...providers].sort( - (a, b) => order(a) - order(b) || a.key.localeCompare(b.key), - )) { +): (CompletionMatch & { supplements: readonly CompletionMatch[] }) | undefined { + let winner: CompletionMatch | undefined; + const supplements: CompletionMatch[] = []; + for (const provider of [...providers].sort(byOrder)) { try { const query = provider.match(observation, context); // A later trigger owns the caret over a broad earlier query (e.g. // @Mary Jane :smile). Order/key resolve providers claiming the same start. // A trigger inside a resolved chip is not an open query. if ( - validQuery(query, observation) && - !resolved.some( + !validQuery(query, observation) || + resolved.some( (span) => span.start <= query.start && query.start < span.end, - ) && - (!winner || query.start > winner.query.start) + ) ) - winner = { - provider, - query: Object.freeze({ - start: query.start, - end: query.end, - query: query.query, - }), - }; + continue; + const match = Object.freeze({ + provider, + query: Object.freeze({ + start: query.start, + end: query.end, + query: query.query, + }), + }); + if (provider.supplement === true) supplements.push(match); + else if (!winner || query.start > winner.query.start) winner = match; } catch { /* A broken optional matcher cannot break editing. */ } } - return winner; + return ( + winner && { + ...winner, + supplements: supplements.filter( + (match) => match.query.start === winner.query.start, + ), + } + ); } function validQuery( query: CompletionQuery | null, @@ -96,6 +111,9 @@ export function completionResult( ): HostCompletionResult { const ids = new Set(); const items: HostCompletionSuggestion[] = []; + // A supplement's rows sit under the host's heading for it and carry no + // agent mark; only its hold bears on the winner's exact match. + const supplement = provider?.supplement === true; for (const item of (Array.isArray(result?.items) ? result.items : []).slice( 0, 50, @@ -153,9 +171,10 @@ export function completionResult( label: item.label, ...(typeof item.detail === "string" ? { detail: item.detail } : {}), preview: item.preview, - ...(item.agent === true ? { agent: true } : {}), + ...(item.agent === true && !supplement ? { agent: true } : {}), ...(typeof item.group === "string" && item.group && + !supplement && provider && isBundledContribution(provider) ? { group: item.group } @@ -194,6 +213,9 @@ export function completionResult( ...(typeof result.spaceId === "string" && ids.has(result.spaceId) ? { spaceId: result.spaceId } : {}), + ...(supplement && result.holdAutoSelect === true + ? { holdAutoSelect: true } + : {}), ...(result.spacePending && typeof result.spacePending.name === "string" && result.spacePending.name && diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index e222ef091c..f8a18f0247 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -430,6 +430,10 @@ export type CompletionResult = Readonly<{ status?: string; /** Optional explicit recovery. A new query or disposal revokes this action. */ retry?: () => void; + /** Supplements only: something in the provider's whole source, not only its + * shown rows, has or extends the typed name, or that source is still + * loading. A terminator then never accepts the winner's exact match. */ + holdAutoSelect?: boolean; }>; export type ComposerCompletionProps = CompletionContext & Readonly<{ @@ -443,6 +447,12 @@ export type ComposerCompletion = Readonly<{ id: string; title: string; order?: number; + /** Adds rows beside the provider that owns the caret when this one's match + * has the same `start`; never owns it, so never opens alone. Its rows sit + * under a host-drawn `title`, sections in `order` then key. Publish on + * mount, even with no rows: until then the winner's exact match waits. Its + * `spaceId`, `spacePending`, `agent` and `group` are ignored. */ + supplement?: true; /** Pure syntax matcher. Host prefers the closest trigger; order/key break ties. */ match( observation: ComposerObservation, From 4ccb32df1208a5b30f8038c6b830f09202e5ccd9 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 16:33:56 -0500 Subject: [PATCH 2/3] test(completions): a supplement removed mid-menu; docs on default and hold A supplement whose plugin is removed while the menu is open loses its rows and its hold, and a publish from its old owner is refused. Nothing covered that before. The docs now say that a supplement publishing later with a lower order moves the default row until the user moves the selection, and that a hold has no time limit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 6 ++- .../conversation/ComposerCompletions.test.tsx | 43 +++++++++++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 63f2147db6..6e5ab26f56 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3145,7 +3145,9 @@ supplement's section sits under a host-drawn heading with its `title`, and so does the winner's when another section comes first and the winner draws no heading of its own. The first row is selected by default, so Enter and Tab take a supplement row ordered above the winner's; a terminator still accepts only the -winner's exact match. Each row keeps its provider: a row is identified by +winner's exact match. A supplement that publishes later with a lower `order` +moves the default row until the user moves the selection, which then stays on +its row while that row exists. Each row keeps its provider: a row is identified by provider and ID, and acceptance, `canSelect`, `disabled`, retry and status go to the provider that published it. Each provider keeps its own 50-row cap. A supplement decides no exact match. The host ignores its `spaceId`, `spacePending`, @@ -3154,7 +3156,7 @@ shown rows, has or extends the typed name, or is still loading. Then a typed terminator never accepts the winner's exact match and types as text. A supplement that has not published yet for this query holds the same way, so supplements publish on mount, even with no rows. One that fails drops only its own section -and holds nothing. +and holds nothing. A hold has no time limit. Providers receive immutable observation/range evidence and `publish(result)`—not DOM, focus or replacement commands. Results contain stable IDs, labels, optional diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index d3bb82fa6a..8e898d4a6c 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -352,7 +352,7 @@ function mountSources( }, ); const publishes = new Map(); - const registered = sources.map((source) => { + let registered = sources.map((source) => { const contribution = { id: source.id, key: `test.${source.id}/${source.id}`, @@ -394,9 +394,18 @@ function mountSources( keys: { current: undefined }, composing: { current: false }, } as CompletionEditor; + const listeners = new Set<() => void>(); render( registered, subscribe: () => () => {} }} + registry={{ + snapshot: () => registered, + subscribe: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }} editor={editor} input={{ current: input }} replace={replace} @@ -419,7 +428,12 @@ function mountSources( } as unknown as Parameters< NonNullable >[0]) ?? false; - return { replace, press, publishes }; + const unregister = (id: string) => + act(() => { + registered = registered.filter((contribution) => contribution.id !== id); + for (const listener of listeners) listener(); + }); + return { replace, press, publishes, unregister }; } const people = (result: Partial = {}): Source => ({ id: "people", @@ -573,6 +587,29 @@ it("drops a failed supplement's rows and refuses its later publications", async ); error.mockRestore(); }); +it("drops a supplement removed while the menu is open, with its hold", async () => { + const { replace, press, publishes, unregister } = mountSources([ + people(), + groups({ items: [groupRow], holdAutoSelect: true }), + ]); + await screen.findByRole("option", { name: /^eng$/ }); + const stale = publishes.get("groups"); + unregister("groups"); + expect(listed()).toEqual(["Eng Bot"]); + let late: ReturnType | undefined; + act(() => { + late = stale?.({ items: [groupRow] }); + }); + expect(late).toBe(false); + expect(listed()).toEqual(["Eng Bot"]); + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); +}); it("keeps the winner's rows when a supplement's preview throws", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); function Broken(): never { From 4f31f7798c600528c8ea335b262e673e56a676f2 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 16:53:54 -0500 Subject: [PATCH 3/3] 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 {