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

{status}

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

+ {status} +

+ ))} , // A body sibling would sit behind a fullscreen modal and outside its // accessibility boundary. Ordinary composers keep the body portal. diff --git a/src/features/conversation/completion.test.ts b/src/features/conversation/completion.test.ts index 6e89baea69..25f6651245 100644 --- a/src/features/conversation/completion.test.ts +++ b/src/features/conversation/completion.test.ts @@ -51,6 +51,22 @@ it("validates and deterministically arbitrates optional provider ranges", () => matchCompletion([provider("a", 0, 3)], { ...observation, end: 4 }, context), ).toBeUndefined(); }); +it("keeps a supplement beside the winner only at the winner's start", () => { + const beside = (start: number, order = -20) => ({ + ...provider(`beside-${start}`, start, 3, order), + supplement: true as const, + }); + const match = matchCompletion( + [provider("people", 1, 3), beside(1), beside(0)], + observation, + context, + ); + expect(match?.provider.id).toBe("people"); + expect(match?.supplements.map(({ provider }) => provider.id)).toEqual([ + "beside-1", + ]); + expect(matchCompletion([beside(1)], observation, context)).toBeUndefined(); +}); it("snapshots valid edit primitives, rejects malformed/duplicate candidates and bounds output", () => { const recipient = { pubkey: "a".repeat(64), name: "Honey" }; const input = { diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 1d59ce7f6a..299ea116fa 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -33,45 +33,60 @@ export type HostCompletionSuggestion = Omit & export type HostCompletionResult = Omit & Readonly<{ items: readonly HostCompletionSuggestion[] }>; +export type CompletionMatch = Readonly<{ + provider: Contribution; + query: CompletionQuery; +}>; +const order = (value: ComposerCompletion) => + Number.isFinite(value.order) ? (value.order ?? 0) : 0; +/** Provider precedence: `order`, then contribution key. */ +export const byOrder = ( + a: Contribution, + b: Contribution, +) => order(a) - order(b) || a.key.localeCompare(b.key); export function matchCompletion( providers: readonly Contribution[], observation: ComposerObservation, context: CompletionContext, resolved: readonly Readonly<{ start: number; end: number }>[] = [], -) { - const order = (value: ComposerCompletion) => - Number.isFinite(value.order) ? (value.order ?? 0) : 0; - let winner: - | { provider: Contribution; query: CompletionQuery } - | undefined; - for (const provider of [...providers].sort( - (a, b) => order(a) - order(b) || a.key.localeCompare(b.key), - )) { +): (CompletionMatch & { supplements: readonly CompletionMatch[] }) | undefined { + let winner: CompletionMatch | undefined; + const supplements: CompletionMatch[] = []; + for (const provider of [...providers].sort(byOrder)) { try { const query = provider.match(observation, context); // A later trigger owns the caret over a broad earlier query (e.g. // @Mary Jane :smile). Order/key resolve providers claiming the same start. // A trigger inside a resolved chip is not an open query. if ( - validQuery(query, observation) && - !resolved.some( + !validQuery(query, observation) || + resolved.some( (span) => span.start <= query.start && query.start < span.end, - ) && - (!winner || query.start > winner.query.start) + ) ) - winner = { - provider, - query: Object.freeze({ - start: query.start, - end: query.end, - query: query.query, - }), - }; + continue; + const match = Object.freeze({ + provider, + query: Object.freeze({ + start: query.start, + end: query.end, + query: query.query, + }), + }); + if (provider.supplement === true) supplements.push(match); + else if (!winner || query.start > winner.query.start) winner = match; } catch { /* A broken optional matcher cannot break editing. */ } } - return winner; + return ( + winner && { + ...winner, + supplements: supplements.filter( + (match) => match.query.start === winner.query.start, + ), + } + ); } function validQuery( query: CompletionQuery | null, @@ -96,6 +111,9 @@ export function completionResult( ): HostCompletionResult { const ids = new Set(); const items: HostCompletionSuggestion[] = []; + // A supplement's rows sit under the host's heading for it and carry no + // agent mark; only its hold bears on the winner's exact match. + const supplement = provider?.supplement === true; for (const item of (Array.isArray(result?.items) ? result.items : []).slice( 0, 50, @@ -153,9 +171,10 @@ export function completionResult( label: item.label, ...(typeof item.detail === "string" ? { detail: item.detail } : {}), preview: item.preview, - ...(item.agent === true ? { agent: true } : {}), + ...(item.agent === true && !supplement ? { agent: true } : {}), ...(typeof item.group === "string" && item.group && + !supplement && provider && isBundledContribution(provider) ? { group: item.group } @@ -194,6 +213,9 @@ export function completionResult( ...(typeof result.spaceId === "string" && ids.has(result.spaceId) ? { spaceId: result.spaceId } : {}), + ...(supplement && result.holdAutoSelect === true + ? { holdAutoSelect: true } + : {}), ...(result.spacePending && typeof result.spacePending.name === "string" && result.spacePending.name && diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index e222ef091c..f8a18f0247 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -430,6 +430,10 @@ export type CompletionResult = Readonly<{ status?: string; /** Optional explicit recovery. A new query or disposal revokes this action. */ retry?: () => void; + /** Supplements only: something in the provider's whole source, not only its + * shown rows, has or extends the typed name, or that source is still + * loading. A terminator then never accepts the winner's exact match. */ + holdAutoSelect?: boolean; }>; export type ComposerCompletionProps = CompletionContext & Readonly<{ @@ -443,6 +447,12 @@ export type ComposerCompletion = Readonly<{ id: string; title: string; order?: number; + /** Adds rows beside the provider that owns the caret when this one's match + * has the same `start`; never owns it, so never opens alone. Its rows sit + * under a host-drawn `title`, sections in `order` then key. Publish on + * mount, even with no rows: until then the winner's exact match waits. Its + * `spaceId`, `spacePending`, `agent` and `group` are ignored. */ + supplement?: true; /** Pure syntax matcher. Host prefers the closest trigger; order/key break ties. */ match( observation: ComposerObservation, From 4ccb32df1208a5b30f8038c6b830f09202e5ccd9 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 16:33:56 -0500 Subject: [PATCH 02/11] test(completions): a supplement removed mid-menu; docs on default and hold A supplement whose plugin is removed while the menu is open loses its rows and its hold, and a publish from its old owner is refused. Nothing covered that before. The docs now say that a supplement publishing later with a lower order moves the default row until the user moves the selection, and that a hold has no time limit. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 6 ++- .../conversation/ComposerCompletions.test.tsx | 43 +++++++++++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 63f2147db6..6e5ab26f56 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3145,7 +3145,9 @@ supplement's section sits under a host-drawn heading with its `title`, and so does the winner's when another section comes first and the winner draws no heading of its own. The first row is selected by default, so Enter and Tab take a supplement row ordered above the winner's; a terminator still accepts only the -winner's exact match. Each row keeps its provider: a row is identified by +winner's exact match. A supplement that publishes later with a lower `order` +moves the default row until the user moves the selection, which then stays on +its row while that row exists. Each row keeps its provider: a row is identified by provider and ID, and acceptance, `canSelect`, `disabled`, retry and status go to the provider that published it. Each provider keeps its own 50-row cap. A supplement decides no exact match. The host ignores its `spaceId`, `spacePending`, @@ -3154,7 +3156,7 @@ shown rows, has or extends the typed name, or is still loading. Then a typed terminator never accepts the winner's exact match and types as text. A supplement that has not published yet for this query holds the same way, so supplements publish on mount, even with no rows. One that fails drops only its own section -and holds nothing. +and holds nothing. A hold has no time limit. Providers receive immutable observation/range evidence and `publish(result)`—not DOM, focus or replacement commands. Results contain stable IDs, labels, optional diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index d3bb82fa6a..8e898d4a6c 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -352,7 +352,7 @@ function mountSources( }, ); const publishes = new Map(); - const registered = sources.map((source) => { + let registered = sources.map((source) => { const contribution = { id: source.id, key: `test.${source.id}/${source.id}`, @@ -394,9 +394,18 @@ function mountSources( keys: { current: undefined }, composing: { current: false }, } as CompletionEditor; + const listeners = new Set<() => void>(); render( registered, subscribe: () => () => {} }} + registry={{ + snapshot: () => registered, + subscribe: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }} editor={editor} input={{ current: input }} replace={replace} @@ -419,7 +428,12 @@ function mountSources( } as unknown as Parameters< NonNullable >[0]) ?? false; - return { replace, press, publishes }; + const unregister = (id: string) => + act(() => { + registered = registered.filter((contribution) => contribution.id !== id); + for (const listener of listeners) listener(); + }); + return { replace, press, publishes, unregister }; } const people = (result: Partial = {}): Source => ({ id: "people", @@ -573,6 +587,29 @@ it("drops a failed supplement's rows and refuses its later publications", async ); error.mockRestore(); }); +it("drops a supplement removed while the menu is open, with its hold", async () => { + const { replace, press, publishes, unregister } = mountSources([ + people(), + groups({ items: [groupRow], holdAutoSelect: true }), + ]); + await screen.findByRole("option", { name: /^eng$/ }); + const stale = publishes.get("groups"); + unregister("groups"); + expect(listed()).toEqual(["Eng Bot"]); + let late: ReturnType | undefined; + act(() => { + late = stale?.({ items: [groupRow] }); + }); + expect(late).toBe(false); + expect(listed()).toEqual(["Eng Bot"]); + expect(press(" ")).toBe(true); + expect(replace).toHaveBeenCalledWith( + { mention: ENG_BOT }, + expect.anything(), + expect.anything(), + " ", + ); +}); it("keeps the winner's rows when a supplement's preview throws", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); function Broken(): never { From 4f31f7798c600528c8ea335b262e673e56a676f2 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Tue, 17 Nov 2026 16:53:54 -0500 Subject: [PATCH 03/11] test(completions): a late supplement with a lower order moves only an untouched default Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 8e898d4a6c..a71259d450 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -610,6 +610,31 @@ it("drops a supplement removed while the menu is open, with its hold", async () " ", ); }); +it.each([ + ["moves an untouched default to it", [], { mentions: [BOB] }], + ["keeps a row the user moved to", ["ArrowDown"], { mention: ENG_BOT }], +])( + "for a late supplement with a lower order, %s", + async (_, keys, accepted) => { + const { replace, press, publishes } = mountSources([ + people(), + groups(undefined), + ]); + await screen.findByRole("option", { name: /^Eng Bot$/ }); + for (const key of keys) press(key); + act(() => { + publishes.get("groups")?.({ items: [groupRow] }); + }); + expect(listed()).toEqual(["Groups", "eng", "Mention", "Eng Bot"]); + press("Enter"); + expect(replace).toHaveBeenCalledWith( + accepted, + expect.anything(), + expect.anything(), + "Enter", + ); + }, +); it("keeps the winner's rows when a supplement's preview throws", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); function Broken(): never { From 36a7ec245dac7be88eda18aa538cab6c4f2998ce Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 12:31:35 -0500 Subject: [PATCH 04/11] refactor(completions): shrink the supplement change matchCompletion returns the winner and its supplements in provider precedence as `sources`, so byOrder and the second sort go. Per-source state is keyed by contributionKey. The option row is back at main's indentation, with headings and descriptions computed before the JSX. Drop group checks that only winner rows could reach, since supplements never carry a group. The key handler reads no publication while a supplement holds. Restore main's comment wording where the change only reflowed it. No behavior change. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.tsx | 435 ++++++++---------- src/features/conversation/completion.ts | 55 +-- 2 files changed, 230 insertions(+), 260 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index 2bc826ffee..3283320e3d 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -12,7 +12,6 @@ import { createPortal } from "react-dom"; import { RobotIcon } from "../../shared/design-system/icons/index"; import { useCompletionPosition } from "./useCompletionPosition"; import { - Fragment, useId, useCallback, useEffect, @@ -37,7 +36,6 @@ import type { import { ContributionBoundary, contributionKey } from "./ContributionBoundary"; import { IdentityMarks } from "./IdentityMarks"; import { - byOrder, completionResult, matchCompletion, type CompletionMatch, @@ -96,8 +94,8 @@ function EmojiCompletionName({ * owner whose provider has not published by the end of its mount effects * clears it. A query opened elsewhere, by another provider, or after the * popup closed starts empty: `ComposerCompletions` evicts the store in its - * closed render, so a carried result means only a continuing open query. - * Results are kept per provider: the winner and each supplement beside it. */ + * closed render, so a carried result means only a continuing open query. */ +// By `contributionKey` of the publishing provider, winner or supplement. type Shown = Readonly>; function createDisplay() { let shown: { key: string; results: Shown | undefined } = { @@ -271,7 +269,7 @@ export function ComposerCompletions({ identityMarks={identityMarks} display={display} provider={match.provider} - supplements={match.supplements} + sources={match.sources} query={match.query} observation={observation} editor={editor} @@ -282,20 +280,20 @@ export function ComposerCompletions({ ); } -type Source = CompletionMatch; type Row = Readonly<{ - source: Source; + source: CompletionMatch; key: string; item?: HostCompletionSuggestion; heading?: string; }>; +const slot = ({ provider }: CompletionMatch) => contributionKey(provider); // A row's identity is its provider and its id: two providers may share ids. -const rowKey = (source: Source, id?: string) => - JSON.stringify([contributionKey(source.provider), id ?? null]); +const rowKey = (source: CompletionMatch, id?: string) => + JSON.stringify([slot(source), id ?? null]); function OwnedCompletion({ provider, - supplements: matched, + sources: matched, registry, identityMarks, display, @@ -308,7 +306,7 @@ function OwnedCompletion({ ...context }: CompletionContext & { provider: Contribution; - supplements: readonly Source[]; + sources: readonly CompletionMatch[]; registry: ContributionReader; identityMarks?: ContributionReader | undefined; display: ReturnType; @@ -346,28 +344,19 @@ function OwnedCompletion({ const list = useRef(null); const trigger = `${contributionKey(provider)}:${query.start}`; // Fixed for this lifetime: a changed set of supplements remounts it. - const [{ winner, supplements, sources }] = useState(() => { - const winner: Source = { provider, query }; - return { - winner, - supplements: matched, - sources: [winner, ...matched].sort((a, b) => - byOrder(a.provider, b.provider), - ), - }; - }); + const [sources] = useState(matched); const results = useSyncExternalStore( display.subscribe, () => display.read(trigger), () => display.read(trigger), ); const result = results?.[contributionKey(provider)]; - // This lifetime's own publications; a carried display is never acted on. - const latest = useRef(new Map()); + // This lifetime's own publication; a carried display is never acted on. + const latest = useRef(new Map()); // A failed supplement is done for this lifetime: its section goes, it holds // nothing back, and it can no longer publish or accept. - const failed = useRef(new Set()); - // Only user navigation pins a row; automatic selection follows the first result. + const failed = useRef(new Set()); + // Only user navigation pins an ID; automatic selection follows the first result. const [selected, setSelected] = useState(); const [keyboardSelection, setKeyboardSelection] = useState(); const pointerMoved = useCallback( @@ -399,49 +388,41 @@ function OwnedCompletion({ current.current = { editor, replace }; }); const active = useCallback( - (source: Source) => + (candidate: Contribution) => live.current && - !failed.current.has(source) && - registry.snapshot().includes(source.provider) && + !failed.current.has(contributionKey(candidate)) && + registry.snapshot().includes(candidate) && current.current.editor.valid(observation), [registry, observation], ); const [publishers, setPublishers] = - useState>(); + useState(); useLayoutEffect(() => { live.current = true; let owned = true; const published = latest.current; setPublishers( - new Map( - sources.map((source) => [ - source, - (incoming: CompletionResult) => { - if (!owned || !active(source)) return false; - const next = completionResult(incoming, source.provider); - const slot = contributionKey(source.provider); - published.set(source, next); - revealSelection.current = true; - display.set(trigger, slot, next); - // A pinned row of this provider stays only while it still exists. - setSelected((previous) => { - if (!previous?.startsWith(`[${slot},`)) return previous; - const kept = - previous === rowKey(source) - ? !!next.retry - : next.items.some( - (item) => previous === rowKey(source, item.id), - ); - return kept ? previous : undefined; - }); - return () => { - if (published.get(source) !== next) return; - published.delete(source); - if (live.current) display.set(trigger, slot); - }; - }, - ]), - ), + sources.map((source) => (incoming: CompletionResult) => { + if (!owned || !active(source.provider)) return false; + const next = completionResult(incoming, source.provider); + published.set(slot(source), next); + revealSelection.current = true; + display.set(trigger, slot(source), next); + // A pinned row of this provider stays only while it still exists. + setSelected((previous) => { + if (!previous?.startsWith(`[${slot(source)},`)) return previous; + const kept = + previous === rowKey(source) + ? !!next.retry + : next.items.some((item) => previous === rowKey(source, item.id)); + return kept ? previous : undefined; + }); + return () => { + if (published.get(slot(source)) !== next) return; + published.delete(slot(source)); + if (live.current) display.set(trigger, slot(source)); + }; + }), ); return () => { owned = false; @@ -449,42 +430,39 @@ function OwnedCompletion({ published.clear(); }; }, [active, display, sources, trigger]); - // A carried result stands only until this query's providers have run their + // A carried result stands only until this query's provider has run its // mount effects, which precede this one; a provider that has not published - // by then shows nothing, as for a first query, so a stale display is never - // painted. A provider no longer beside this query keeps nothing either. + // by then leaves the popup closed, as for a first query, so a stale display + // is never painted. Each supplement is judged alone. useEffect(() => { if (!publishers) return; - const published = new Set( - [...latest.current.keys()].map(({ provider }) => - contributionKey(provider), - ), - ); - for (const slot of Object.keys(display.read(trigger) ?? {})) - if (!published.has(Number(slot))) display.set(trigger, Number(slot)); + for (const key of Object.keys(display.read(trigger) ?? {})) + if (!latest.current.has(Number(key))) display.set(trigger, Number(key)); }, [publishers, display, trigger]); // The winner's exact match waits while a supplement has, or may have, a // name the typed one is, or begins. const held = () => - supplements.some((source) => { - const published = latest.current.get(source); + sources.some((source) => { + const published = latest.current.get(slot(source)); return ( - !failed.current.has(source) && - (!published || published.holdAutoSelect === true) + source.provider !== provider && + !failed.current.has(slot(source)) && + (!published || published.holdAutoSelect) ); }); // The winner's failure closes the popup; a supplement's drops only its own // section, whether its provider or one of its previews throws. - const isolate = (source: Source, node: ReactNode) => - source === winner ? ( + const isolate = (source: CompletionMatch, node: ReactNode) => + source.provider === provider ? ( node ) : ( { if (!failure) return; - failed.current.add(source); - display.set(trigger, contributionKey(source.provider)); + failed.current.add(slot(source)); + display.set(trigger, slot(source)); }} > {node} @@ -492,7 +470,7 @@ function OwnedCompletion({ ); const rows: Row[] = []; for (const source of sources) { - const shown = results?.[contributionKey(source.provider)]; + const shown = results?.[slot(source)]; const own: Row[] = [ ...(shown?.items ?? []).map((item) => ({ source, @@ -504,14 +482,32 @@ function OwnedCompletion({ // A supplement's rows sit under its title; the winner's too when rows // precede them and the provider draws no heading of its own. const first = own[0]; - if (first && (source !== winner || (rows.length > 0 && !first.item?.group))) + if ( + first && + (source.provider !== provider || (rows.length > 0 && !first.item?.group)) + ) own[0] = { ...first, heading: source.provider.title }; rows.push(...own); } const statuses = sources.flatMap((source) => { - const status = results?.[contributionKey(source.provider)]?.status; + const status = results?.[slot(source)]?.status; return status ? [{ source, status }] : []; }); + const lines = rows.map((row, i) => { + const { item, source } = row; + const lead = rows.findIndex((other) => other.source === source); + const group = item?.group; + return { + ...row, + heading: + row.heading ?? (group !== rows[i - 1]?.item?.group ? group : undefined), + described: group + ? `${id}-group-${rows.findIndex((other) => other.item?.group === group)}` + : rows[lead]?.heading + ? `${id}-group-${lead}` + : undefined, + }; + }); // Matching syntax is not evidence of pending work. Providers publish their // own status when needed; an empty/unpublished result must not flash a portal. const visible = !!(rows.length || statuses.length); @@ -521,9 +517,9 @@ function OwnedCompletion({ function accept(index: number, key = "click") { const terminator = terminates(key); const row = terminator ? undefined : rows[index]; - const source = row?.source ?? winner; - const published = latest.current.get(source); - if (!active(source) || !published) return false; + const source = row?.source ?? { provider, query }; + const published = latest.current.get(slot(source)); + if (!active(source.provider) || !published) return false; if (row && !row.item) { if (!published.retry) return false; published.retry(); @@ -546,10 +542,10 @@ function OwnedCompletion({ } useLayoutEffect(() => { const element = input.current; - // Escape must still dismiss an unpublished provider, or a supplement that - // still holds, without advertising a nonexistent listbox. A settled empty - // result leaves ordinary keys alone; an undecided one still owns the - // terminator, with nothing to show yet. + // Escape must still dismiss an unpublished provider without advertising a + // nonexistent listbox. A settled empty result leaves ordinary keys alone; + // an undecided one still owns the terminator, with nothing to show yet. + // A supplement that still holds counts as undecided. if (!element || (!visible && result && !result.spacePending && !held())) return; if (visible) { @@ -582,7 +578,7 @@ function OwnedCompletion({ (event.key === " " || !terminates(event.key)) ) return false; - if (!active(winner)) { + if (!active(provider)) { // A displayed choice owns plain acceptance even when its final evidence // was revoked. Never turn a rejected edit into an unintended send. if ((event.key === "Enter" || event.key === "Tab") && count) { @@ -597,13 +593,13 @@ function OwnedCompletion({ // yet, so both terminator branches read the publication. Space is not // redirected away from an exact match the display showed: a publication // that moves it to another id leaves Space literal. The displayed row - // is never accepted on its own; only the publication selects. A - // supplement holding the terminator leaves it literal too. - const published = latest.current.get(winner); - const waiting = terminates(event.key) && held(); + // is never accepted on its own; only the publication selects. + // A supplement holding the terminator leaves it literal too. + const published = held() + ? undefined + : latest.current.get(contributionKey(provider)); if ( terminates(event.key) && - !waiting && published?.spaceId && (!result?.spaceId || result.spaceId === published.spaceId) ) { @@ -622,7 +618,6 @@ function OwnedCompletion({ // decision is deferred to the resolver under the full rule. if ( terminates(event.key) && - !waiting && published?.spacePending && !published.spaceId && current.current.replace( @@ -673,22 +668,19 @@ function OwnedCompletion({ return ( <> {publishers && - sources.map((source) => { + sources.map((source, i) => { const Provider = source.provider.component; - const publish = publishers.get(source); + const publish = publishers[i]; if (!publish) return null; - return ( - - {isolate( - source, - , - )} - + return isolate( + source, + , ); })} {visible && @@ -709,140 +701,117 @@ function OwnedCompletion({ ref={list} className={styles.list} > - {rows.flatMap((row, i) => { - const { item, source } = row; - const previous = rows[i - 1]; - const group = - item?.group && - (previous?.source !== source || - item.group !== previous.item?.group) && - item.group; - const heading = row.heading ?? group; - const lead = rows.findIndex((other) => other.source === source); - const describedBy = item?.group - ? `${id}-group-${rows.findIndex((other) => other.source === source && other.item?.group === item.group)}` - : rows[lead]?.heading - ? `${id}-group-${lead}` - : undefined; - const option = ( - // The textarea owns keyboard focus/selection via aria-activedescendant. - // biome-ignore lint/a11y/useKeyWithClickEvents: Keyboard acceptance belongs to the focused textarea. + {lines.flatMap(({ item, source, key, heading, described }, i) => [ + heading && ( + // Read as the description of each row it heads.
{ - if (event.button === 0) event.preventDefault(); - }} - onPointerMove={ - compact || named - ? (event) => { - // WebKit can report a pointermove when keyboard - // scrolling moves another row under a resting pointer. - if (compact && !pointerMoved(event)) return; - revealSelection.current = false; - setKeyboardSelection(undefined); - setSelected(row.key); - } - : undefined - } - onClick={() => accept(i)} - className={styles.option} + key={`group:${key}`} + id={`${id}-group-${i}`} + aria-hidden="true" + className={styles.group} > - {!item ? ( - source === winner ? ( - "Retry suggestions" - ) : ( - `Retry ${source.provider.title} suggestions` - ) - ) : ( - <> - {item.preview && ( - - )} - - {compact ? ( - - ) : named ? ( - // Only the name ellipsizes; the agent mark stays visible. - - {item.label} - {mention && - source === winner && - item.edit.mention && ( - - )} - {item.agent && ( - - )} - {item.agent && ( - Agent - )} + {heading} +
+ ), + // The textarea owns keyboard focus/selection via aria-activedescendant. + // biome-ignore lint/a11y/useKeyWithClickEvents: Keyboard acceptance belongs to the focused textarea. +
{ + if (event.button === 0) event.preventDefault(); + }} + onPointerMove={ + compact || named + ? (event) => { + // WebKit can report a pointermove when keyboard + // scrolling moves another row under a resting pointer. + if (compact && !pointerMoved(event)) return; + revealSelection.current = false; + setKeyboardSelection(undefined); + setSelected(key); + } + : undefined + } + onClick={() => accept(i)} + className={styles.option} + > + {item?.preview && ( + + )} + {item && ( + + {compact ? ( + + ) : named ? ( + // Only the name ellipsizes; the agent mark stays visible. + + {item.label} + {mention && + source.provider === provider && + item.edit.mention && ( + + )} + {item.agent && ( + - ) : ( - item.label )} - {item.detail && ( - - {item.detail} - + {item.agent && ( + Agent )} - {channel && i === selectedIndex && ( - - )} - - )} -
- ); - return [ - heading && ( - // Read as the description of each row it heads. - - ), - option, - ]; - })} + ) : ( + item.label + )} + {item.detail && ( + + {item.detail} + + )} +
+ )} + {channel && item && i === selectedIndex && ( + + )} + {!item && + (source.provider === provider + ? "Retry suggestions" + : `Retry ${source.provider.title} suggestions`)} + , + ])} {statuses.map(({ source, status }) => ( -

+

{status}

))} diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 299ea116fa..62687cac0f 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -37,54 +37,55 @@ export type CompletionMatch = Readonly<{ provider: Contribution; query: CompletionQuery; }>; -const order = (value: ComposerCompletion) => - Number.isFinite(value.order) ? (value.order ?? 0) : 0; -/** Provider precedence: `order`, then contribution key. */ -export const byOrder = ( - a: Contribution, - b: Contribution, -) => order(a) - order(b) || a.key.localeCompare(b.key); export function matchCompletion( providers: readonly Contribution[], observation: ComposerObservation, context: CompletionContext, resolved: readonly Readonly<{ start: number; end: number }>[] = [], -): (CompletionMatch & { supplements: readonly CompletionMatch[] }) | undefined { - let winner: CompletionMatch | undefined; - const supplements: CompletionMatch[] = []; - for (const provider of [...providers].sort(byOrder)) { +) { + const order = (value: ComposerCompletion) => + Number.isFinite(value.order) ? (value.order ?? 0) : 0; + const matches: CompletionMatch[] = []; + for (const provider of [...providers].sort( + (a, b) => order(a) - order(b) || a.key.localeCompare(b.key), + )) { try { const query = provider.match(observation, context); // A later trigger owns the caret over a broad earlier query (e.g. // @Mary Jane :smile). Order/key resolve providers claiming the same start. // A trigger inside a resolved chip is not an open query. if ( - !validQuery(query, observation) || - resolved.some( + validQuery(query, observation) && + !resolved.some( (span) => span.start <= query.start && query.start < span.end, ) ) - continue; - const match = Object.freeze({ - provider, - query: Object.freeze({ - start: query.start, - end: query.end, - query: query.query, - }), - }); - if (provider.supplement === true) supplements.push(match); - else if (!winner || query.start > winner.query.start) winner = match; + matches.push({ + provider, + query: Object.freeze({ + start: query.start, + end: query.end, + query: query.query, + }), + }); } catch { /* A broken optional matcher cannot break editing. */ } } + const owners = matches.filter(({ provider }) => provider.supplement !== true); + const start = Math.max(...owners.map(({ query }) => query.start)); + const winner = owners.find(({ query }) => query.start === start); + // The winner and its supplements, in provider precedence. + const sources = matches.filter( + (match) => + match === winner || + (match.provider.supplement === true && match.query.start === start), + ); return ( winner && { ...winner, - supplements: supplements.filter( - (match) => match.query.start === winner.query.start, - ), + sources, + supplements: sources.filter((match) => match !== winner), } ); } From 90efaa2c9339a0940e12e469639050fc37d61e21 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 14:21:59 -0500 Subject: [PATCH 05/11] Remove the prose comments this change adds Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 7 ------- .../conversation/ComposerCompletions.tsx | 16 +--------------- src/features/conversation/completion.ts | 3 --- 3 files changed, 1 insertion(+), 25 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index a71259d450..2ed4f3f302 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -330,9 +330,7 @@ type Source = Readonly<{ order?: number; supplement?: true; title?: string; - /** Undefined publishes nothing; a function throws while rendering. */ result?: CompletionResult | (() => never) | undefined; - /** Publishes `result` without keeping its withdrawal, then throws. */ crashAfterPublish?: true; }>; function mountSources( @@ -467,18 +465,15 @@ const groupRow = { edit: { mentions: [BOB] }, } as const; -// Headings and rows as the listbox lays them out. const listed = () => [...screen.getByRole("listbox").children].map((node) => node.textContent); it("shows a supplement's rows under its title beside the winner, in provider order", async () => { mountSources([people(), groups({ items: [groupRow] })]); await screen.findByRole("option", { name: /^eng$/ }); - // The winner's rows never read as part of the section above them. expect(listed()).toEqual(["Groups", "eng", "Mention", "Eng Bot"]); cleanup(); mountSources([people(), groups({ items: [groupRow] }, 10)]); await screen.findByRole("option", { name: /^eng$/ }); - // First, the winner looks as it does alone. expect(listed()).toEqual(["Eng Bot", "Groups", "eng"]); }); it("opens with a supplement's rows when the winner has none", async () => { @@ -577,7 +572,6 @@ it("drops a failed supplement's rows and refuses its later publications", async }); expect(late).toBe(false); expect(listed()).toEqual(["Eng Bot"]); - // Its hold went with it. expect(press(" ")).toBe(true); expect(replace).toHaveBeenCalledWith( { mention: ENG_BOT }, @@ -652,7 +646,6 @@ it("lets Escape dismiss a supplement that has not answered beside an empty winne const empty = people({ items: [], spaceId: undefined }); expect(mountSources([empty, groups(undefined)]).press("Escape")).toBe(true); cleanup(); - // A settled, empty popup leaves Escape to the composer. expect(mountSources([empty, groups({ items: [] })]).press("Escape")).toBe( false, ); diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index 3283320e3d..b541a0d4dd 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -95,7 +95,6 @@ function EmojiCompletionName({ * clears it. A query opened elsewhere, by another provider, or after the * popup closed starts empty: `ComposerCompletions` evicts the store in its * closed render, so a carried result means only a continuing open query. */ -// By `contributionKey` of the publishing provider, winner or supplement. type Shown = Readonly>; function createDisplay() { let shown: { key: string; results: Shown | undefined } = { @@ -287,7 +286,6 @@ type Row = Readonly<{ heading?: string; }>; const slot = ({ provider }: CompletionMatch) => contributionKey(provider); -// A row's identity is its provider and its id: two providers may share ids. const rowKey = (source: CompletionMatch, id?: string) => JSON.stringify([slot(source), id ?? null]); @@ -343,7 +341,6 @@ function OwnedCompletion({ ); const list = useRef(null); const trigger = `${contributionKey(provider)}:${query.start}`; - // Fixed for this lifetime: a changed set of supplements remounts it. const [sources] = useState(matched); const results = useSyncExternalStore( display.subscribe, @@ -353,8 +350,6 @@ function OwnedCompletion({ const result = results?.[contributionKey(provider)]; // This lifetime's own publication; a carried display is never acted on. const latest = useRef(new Map()); - // A failed supplement is done for this lifetime: its section goes, it holds - // nothing back, and it can no longer publish or accept. const failed = useRef(new Set()); // Only user navigation pins an ID; automatic selection follows the first result. const [selected, setSelected] = useState(); @@ -408,7 +403,6 @@ function OwnedCompletion({ published.set(slot(source), next); revealSelection.current = true; display.set(trigger, slot(source), next); - // A pinned row of this provider stays only while it still exists. setSelected((previous) => { if (!previous?.startsWith(`[${slot(source)},`)) return previous; const kept = @@ -433,14 +427,12 @@ function OwnedCompletion({ // A carried result stands only until this query's provider has run its // mount effects, which precede this one; a provider that has not published // by then leaves the popup closed, as for a first query, so a stale display - // is never painted. Each supplement is judged alone. + // is never painted. useEffect(() => { if (!publishers) return; for (const key of Object.keys(display.read(trigger) ?? {})) if (!latest.current.has(Number(key))) display.set(trigger, Number(key)); }, [publishers, display, trigger]); - // The winner's exact match waits while a supplement has, or may have, a - // name the typed one is, or begins. const held = () => sources.some((source) => { const published = latest.current.get(slot(source)); @@ -450,8 +442,6 @@ function OwnedCompletion({ (!published || published.holdAutoSelect) ); }); - // The winner's failure closes the popup; a supplement's drops only its own - // section, whether its provider or one of its previews throws. const isolate = (source: CompletionMatch, node: ReactNode) => source.provider === provider ? ( node @@ -479,8 +469,6 @@ function OwnedCompletion({ })), ...(shown?.retry ? [{ source, key: rowKey(source) }] : []), ]; - // A supplement's rows sit under its title; the winner's too when rows - // precede them and the provider draws no heading of its own. const first = own[0]; if ( first && @@ -545,7 +533,6 @@ function OwnedCompletion({ // Escape must still dismiss an unpublished provider without advertising a // nonexistent listbox. A settled empty result leaves ordinary keys alone; // an undecided one still owns the terminator, with nothing to show yet. - // A supplement that still holds counts as undecided. if (!element || (!visible && result && !result.spacePending && !held())) return; if (visible) { @@ -594,7 +581,6 @@ function OwnedCompletion({ // redirected away from an exact match the display showed: a publication // that moves it to another id leaves Space literal. The displayed row // is never accepted on its own; only the publication selects. - // A supplement holding the terminator leaves it literal too. const published = held() ? undefined : latest.current.get(contributionKey(provider)); diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 62687cac0f..dbb2c13c90 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -75,7 +75,6 @@ export function matchCompletion( const owners = matches.filter(({ provider }) => provider.supplement !== true); const start = Math.max(...owners.map(({ query }) => query.start)); const winner = owners.find(({ query }) => query.start === start); - // The winner and its supplements, in provider precedence. const sources = matches.filter( (match) => match === winner || @@ -112,8 +111,6 @@ export function completionResult( ): HostCompletionResult { const ids = new Set(); const items: HostCompletionSuggestion[] = []; - // A supplement's rows sit under the host's heading for it and carry no - // agent mark; only its hold bears on the winner's exact match. const supplement = provider?.supplement === true; for (const item of (Array.isArray(result?.items) ? result.items : []).slice( 0, From 7024324640724761dfe8d4e051c945736317fabb Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Wed, 18 Nov 2026 14:22:29 -0500 Subject: [PATCH 06/11] Infer the test sources' types and check them with satisfies Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 48 ++++++++++--------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 2ed4f3f302..b2136a3db6 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -433,32 +433,34 @@ function mountSources( }); return { replace, press, publishes, unregister }; } -const people = (result: Partial = {}): Source => ({ - id: "people", - title: "Mention", - order: -10, - result: { - items: [ - { - id: "x", - label: "Eng Bot", - edit: { mention: ENG_BOT }, - }, - ], - spaceId: "x", - ...result, - }, -}); +const people = (result: Partial = {}) => + ({ + id: "people", + title: "Mention", + order: -10, + result: { + items: [ + { + id: "x", + label: "Eng Bot", + edit: { mention: ENG_BOT }, + }, + ], + spaceId: "x", + ...result, + }, + }) satisfies Source; const groups = ( result: CompletionResult | (() => never) | undefined, order = -20, -): Source => ({ - id: "groups", - title: "Groups", - order, - supplement: true, - result, -}); +) => + ({ + id: "groups", + title: "Groups", + order, + supplement: true, + result, + }) satisfies Source; const groupRow = { id: "x", label: "eng", From ba160730f81c687bc92172ab0439c890c5b91717 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Thu, 19 Nov 2026 00:30:45 -0500 Subject: [PATCH 07/11] Register supplements through their own method A provider with `supplement: true` passed to `registerCompletion` on a host without supplements is an ordinary provider there: with a lower `order` than the host's mentions it owns the `@` caret and hides the people rows. `registerCompletionSupplement` is the only way to register a supplement, and `registerCompletion` refuses one, so a plugin calls it as `registerCompletionSupplement?.()` and registers nothing on a host that lacks it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 5 +++- src/features/conversation/contracts.ts | 3 +- src/features/conversation/service.test.tsx | 35 ++++++++++++++++++++++ src/features/conversation/service.tsx | 18 ++++++++++- 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 32e1988c86..24a007ac3b 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3159,7 +3159,10 @@ Before the first publication the menu is also hidden: syntax matching is not evi of loading. Providers must publish an explicit status for actual pending work. Escape still revokes unpublished work, without exposing ARIA controls for a missing listbox. -A provider registered with `supplement: true` never owns the caret. It mounts +A provider registered with `ctx.conversation.registerCompletionSupplement(provider)` +never owns the caret. Hosts without supplements lack that method, so a plugin +calls it with `?.` and adds nothing on them. `registerCompletion` refuses +`supplement`, so that method is the only way to register one. It mounts beside the winner when its own match has the same start, with its own query, and it never opens a menu alone. Each provider's rows form a section, and sections follow `order`, then the contribution key, with the winner among them. A diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 85524274f7..f77c7762b7 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -447,7 +447,8 @@ export type ComposerCompletion = Readonly<{ id: string; title: string; order?: number; - /** Adds rows beside the provider that owns the caret when this one's match + /** Set only by `registerCompletionSupplement`; `registerCompletion` refuses + * it. Adds rows beside the provider that owns the caret when this one's match * has the same `start`; never owns it, so never opens alone. Its rows sit * under a host-drawn `title`, sections in `order` then key. Publish on * mount, even with no rows: until then the winner's exact match waits. Its diff --git a/src/features/conversation/service.test.tsx b/src/features/conversation/service.test.tsx index 621140d3a1..2bc0b8cbb1 100644 --- a/src/features/conversation/service.test.tsx +++ b/src/features/conversation/service.test.tsx @@ -413,6 +413,41 @@ it("owns completion registration through disable, replacement and failed activat ); expect(broken.service.completions.snapshot()).toHaveLength(0); }); +it("makes a supplement only through registerCompletionSupplement", async () => { + const provider = { + title: "Rows", + match: () => null, + component: Component, + }; + const h = harness({ + inject: ["conversation"], + apply(ctx) { + ctx.conversation.registerCompletion({ ...provider, id: "owner" }); + ctx.conversation.registerCompletionSupplement({ + ...provider, + id: "rows", + }); + expect(() => + ctx.conversation.registerCompletion({ + ...provider, + id: "refused", + supplement: true, + }), + ).toThrow("registerCompletionSupplement"); + }, + }); + h.runtime.reconcile([h.plugin]); + await vi.waitFor(() => + expect( + h.service.completions + .snapshot() + .map(({ id, supplement }) => [id, supplement === true]), + ).toEqual([ + ["owner", false], + ["rows", true], + ]), + ); +}); it.each([ [emoji, ["typeahead"]], [mentions, ["typeahead", "folders", "skills"]], diff --git a/src/features/conversation/service.tsx b/src/features/conversation/service.tsx index b4c52ea808..d7cdbcdf4a 100644 --- a/src/features/conversation/service.tsx +++ b/src/features/conversation/service.tsx @@ -82,6 +82,9 @@ export type Conversation = { registerTool(tool: ComposerTool): void; completions: ContributionReader; registerCompletion(provider: ComposerCompletion): void; + /** Registers `provider` with `supplement: true`. Hosts without supplements + * lack this method, so plugins call it as `registerCompletionSupplement?.()`. */ + registerCompletionSupplement(provider: ComposerCompletion): void; annotators: ContributionReader; /** Marks on the focused composer's prose; see `ComposerAnnotator`. */ registerAnnotator(annotator: ComposerAnnotator): void; @@ -397,10 +400,23 @@ export class ConversationService extends Service implements Conversation { this.toolEntries.register(this.ctx, value); } registerCompletion(value: ComposerCompletion) { + if (value?.supplement !== undefined) + throw new Error( + "Register a supplement with registerCompletionSupplement", + ); + this.addCompletion(value); + } + registerCompletionSupplement(value: ComposerCompletion) { + this.addCompletion(value, true); + } + private addCompletion(value: ComposerCompletion, supplement?: true) { validate(value); if (typeof value.match !== "function") throw new Error("A completion provider needs a matcher"); - this.completionEntries.register(this.ctx, value); + this.completionEntries.register( + this.ctx, + supplement ? { ...value, supplement } : value, + ); } registerAnnotator(value: ComposerAnnotator) { validate(value); From 644624b5092e45f1092c3760913489c3c0730248 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 13:20:21 -0500 Subject: [PATCH 08/11] fix(completions): keep the arrow-key selection when a supplement changes Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- .../conversation/ComposerCompletions.test.tsx | 37 +++++++++++++---- .../conversation/ComposerCompletions.tsx | 40 +++++++++++++++---- 2 files changed, 61 insertions(+), 16 deletions(-) diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index b2136a3db6..426f11b6af 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -325,6 +325,7 @@ it("opens no query at a trigger inside a resolved chip", () => { 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; @@ -493,10 +494,6 @@ it("opens with a supplement's rows when the winner has none", async () => { "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(), @@ -523,6 +520,16 @@ it("accepts each row through its own provider when their ids collide", async () 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([ @@ -585,19 +592,33 @@ it("drops a failed supplement's rows and refuses its later publications", async }); 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 }), + 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"]); + 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"]); + expect(listed()).toEqual(["Eng Bot", "Eng Lead"]); expect(press(" ")).toBe(true); expect(replace).toHaveBeenCalledWith( { mention: ENG_BOT }, diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index b541a0d4dd..295275b1b1 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -19,8 +19,10 @@ import { useRef, useState, useSyncExternalStore, + type Dispatch, type ReactNode, type RefObject, + type SetStateAction, } from "react"; import type { Contribution } from "../../plugins/contributions"; import type { @@ -199,6 +201,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 = @@ -225,6 +229,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 && @@ -245,11 +269,7 @@ export function ComposerCompletions({ return ( [ contributionKey(provider), query.end, @@ -275,6 +295,8 @@ export function ComposerCompletions({ input={input} replace={replace} pointerPosition={pointerPosition} + selected={pin?.scope === scope ? pin.row : undefined} + setSelected={select} /> ); @@ -301,8 +323,12 @@ function OwnedCompletion({ input, replace, pointerPosition, + selected, + setSelected, ...context }: CompletionContext & { + selected: string | undefined; + setSelected: Dispatch>; provider: Contribution; sources: readonly CompletionMatch[]; registry: ContributionReader; @@ -351,8 +377,6 @@ function OwnedCompletion({ // This lifetime's own publication; a carried display is never acted on. const latest = useRef(new Map()); const failed = useRef(new Set()); - // Only user navigation pins an ID; automatic selection follows the first result. - const [selected, setSelected] = useState(); const [keyboardSelection, setKeyboardSelection] = useState(); const pointerMoved = useCallback( (event: Pick) => { @@ -423,7 +447,7 @@ function OwnedCompletion({ live.current = false; published.clear(); }; - }, [active, display, sources, 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 From 275173f99b83a4c04cfc0032abcbce15e9d88fa9 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 19:12:07 -0500 Subject: [PATCH 09/11] test(completions): prove an owner mention only from a person's pick A completion row the person clicks or picks with a key marks its recipients as the owner's explicit mention; the same row picked by a script does not. Cover a people row and a plugin supplement row in the browser, where only a real input event is trusted. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- tests/browser/completion-work.spec.mjs | 64 ++++++++++++++++++++++++++ tests/fixtures/mentions.tsx | 45 ++++++++++++++++++ 2 files changed, 109 insertions(+) diff --git a/tests/browser/completion-work.spec.mjs b/tests/browser/completion-work.spec.mjs index 703fc022d0..617fe1522b 100644 --- a/tests/browser/completion-work.spec.mjs +++ b/tests/browser/completion-work.spec.mjs @@ -314,3 +314,67 @@ 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()); + } + }); +} diff --git a/tests/fixtures/mentions.tsx b/tests/fixtures/mentions.tsx index 43e592ae5a..6c67a69569 100644 --- a/tests/fixtures/mentions.tsx +++ b/tests/fixtures/mentions.tsx @@ -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).has("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,49 @@ const plugins = createPluginManager(context, { ({ manifest }) => channels && ["buzz.channels", "buzz.links"].includes(manifest.id), ), + ...(supplement + ? [ + { + manifest: { + id: "test.crew", + name: "Crew supplement", + apiVersion: 1, + }, + module: { + inject: ["conversation"], + apply(ctx) { + ctx.conversation.registerCompletionSupplement({ + id: "crew", + title: "Crews", + order: 10, + match: ({ text, start }) => mentionQuery(text, start), + component: ({ publish }) => { + useLayoutEffect( + () => + publish({ + items: [ + { + id: "crew", + label: "Honey crew", + edit: { + mentions: [ + { pubkey: first.pubkey, name: "Honey" }, + { pubkey: second.pubkey, name: "Honey" }, + ], + }, + }, + ], + }) || undefined, + [publish], + ); + return null; + }, + }); + }, + }, + }, + ] + : []), { manifest: { id: "test.disabled-command", From cd95a6906ec4eea98bb5ed04a42a76995f6b6f0e Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 23:01:54 -0500 Subject: [PATCH 10/11] fix(completions): hold Space only on a published hold A supplement that has published nothing for the query no longer holds Space. Only a published `holdAutoSelect: true` keeps Space from picking the winner's exact match, so a supplement that is still loading publishes the hold itself. One that never publishes leaves Space, and Escape, to the winner. Cover a held and a silent supplement in the browser with an unpaused Space, and Enter and Tab taking a supplement row ordered first. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 9 +++-- .../conversation/ComposerCompletions.test.tsx | 19 ++++------ .../conversation/ComposerCompletions.tsx | 2 +- tests/browser/completion-work.spec.mjs | 38 +++++++++++++++++++ tests/fixtures/mentions.tsx | 22 ++++++----- 5 files changed, 65 insertions(+), 25 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 4670fdf0e3..631b0515e0 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3458,10 +3458,11 @@ 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. A hold has no time limit. +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` +itself. 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 diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 426f11b6af..e182f8166b 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -541,6 +541,7 @@ it("keeps Space from picking the winner's exact match while a supplement holds i expect(replace).not.toHaveBeenCalled(); }); it.each([ + ["has not answered", undefined], ["publishes no rows", { items: [] }], [ "fails", @@ -665,13 +666,15 @@ it("keeps the winner's rows when a supplement's preview throws", async () => { expect(listed()).toEqual(["Eng Bot"]); error.mockRestore(); }); -it("lets Escape dismiss a supplement that has not answered beside an empty winner", () => { +it("lets Escape dismiss a supplement that holds beside an empty winner", () => { const empty = people({ items: [], spaceId: undefined }); - expect(mountSources([empty, groups(undefined)]).press("Escape")).toBe(true); + expect( + mountSources([empty, groups({ items: [], holdAutoSelect: true })]).press( + "Escape", + ), + ).toBe(true); cleanup(); - expect(mountSources([empty, groups({ items: [] })]).press("Escape")).toBe( - false, - ); + 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(); @@ -698,12 +701,6 @@ it("holds a pending exact match too while a supplement holds it", async () => { " ", ); }); -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(); diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index fffd342caf..ae99a21aa8 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -464,7 +464,7 @@ function OwnedCompletion({ return ( source.provider !== provider && !failed.current.has(slot(source)) && - (!published || published.holdAutoSelect) + published?.holdAutoSelect === true ); }); const isolate = (source: CompletionMatch, node: ReactNode) => diff --git a/tests/browser/completion-work.spec.mjs b/tests/browser/completion-work.spec.mjs index 617fe1522b..b9515d9181 100644 --- a/tests/browser/completion-work.spec.mjs +++ b/tests/browser/completion-work.spec.mjs @@ -378,3 +378,41 @@ for (const row of ["people", "supplement"]) { } }); } + +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 6c67a69569..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"; @@ -93,7 +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).has("supplement"); +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. @@ -346,7 +346,7 @@ const plugins = createPluginManager(context, { ({ manifest }) => channels && ["buzz.channels", "buzz.links"].includes(manifest.id), ), - ...(supplement + ...(supplement !== null ? [ { manifest: { @@ -360,11 +360,12 @@ const plugins = createPluginManager(context, { ctx.conversation.registerCompletionSupplement({ id: "crew", title: "Crews", - order: 10, + order: supplement === "hold" ? -20 : 10, match: ({ text, start }) => mentionQuery(text, start), component: ({ publish }) => { - useLayoutEffect( - () => + useEffect(() => { + if (supplement === "silent") return; + return ( publish({ items: [ { @@ -378,9 +379,12 @@ const plugins = createPluginManager(context, { }, }, ], - }) || undefined, - [publish], - ); + ...(supplement === "hold" + ? { holdAutoSelect: true } + : {}), + }) || undefined + ); + }, [publish]); return null; }, }); From e4cdd8ff182ace150f3effeba2226e6b3c8e09a1 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 23:20:17 -0500 Subject: [PATCH 11/11] docs(completions): a loading supplement publishes its hold in its mount effect The supplement remounts on each keystroke, so a hold published after an async step leaves Space open until it lands. Say so in the contract's TSDoc and the architecture doc, and name the Escape test for both of its cases. Co-Authored-By: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- docs/plugin-architecture.md | 4 ++-- src/features/conversation/ComposerCompletions.test.tsx | 2 +- src/features/conversation/contracts.ts | 7 ++++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 631b0515e0..6e23a5ece3 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -3461,8 +3461,8 @@ 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` -itself. One that fails drops only its own section and holds nothing. A hold has -no time limit. +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 diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index e182f8166b..60684f4e03 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -666,7 +666,7 @@ it("keeps the winner's rows when a supplement's preview throws", async () => { expect(listed()).toEqual(["Eng Bot"]); error.mockRestore(); }); -it("lets Escape dismiss a supplement that holds beside an empty winner", () => { +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( diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 8cd8bbae28..2ba6178c37 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -453,9 +453,10 @@ export type ComposerCompletion = Readonly<{ /** Set only by `registerCompletionSupplement`; `registerCompletion` refuses * it. Adds rows beside the provider that owns the caret when this one's match * has the same `start`; never owns it, so never opens alone. Its rows sit - * under a host-drawn `title`, sections in `order` then key. Publish on - * mount, even with no rows: until then the winner's exact match waits. Its - * `spaceId`, `spacePending`, `agent` and `group` are ignored. */ + * 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(