From fb6412b69863a7d42e33b5fe51df19dfc77148bb Mon Sep 17 00:00:00 2001 From: DominikScholz Date: Sun, 22 Nov 2026 20:29:22 +0100 Subject: [PATCH] feat(web): type a machine or model name, press Tab to make it a chip From the third letter and with no @, the rest of a machine or model name appears as ghost text after the caret. Tab turns it into the same chip the @ menu inserts, and Esc dismisses it. Only typing proposes a name: caret moves, pastes, undo, restored drafts and Markdown-source normalization do not, and nothing is offered while a composer menu is open. Co-Authored-By: Claude Opus 5.5 --- ...rPromptEditorTiptap.input.browser.test.tsx | 115 ++++++++++++- .../components/ComposerPromptEditorTiptap.tsx | 157 ++++++++++++++++++ apps/web/src/components/chat/ChatComposer.tsx | 76 ++++++++- .../components/chat/composerModelMentions.ts | 35 ++-- apps/web/src/composer-undo-grouping.ts | 6 +- apps/web/src/index.css | 19 +++ docs/user/composer.md | 5 + packages/client-runtime/package.json | 4 + .../src/composerInlineSuggestion.test.ts | 53 ++++++ .../src/composerInlineSuggestion.ts | 77 +++++++++ 10 files changed, 531 insertions(+), 16 deletions(-) create mode 100644 packages/client-runtime/src/composerInlineSuggestion.test.ts create mode 100644 packages/client-runtime/src/composerInlineSuggestion.ts diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ff5b426c0bf3..12696c30b4e0 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -7,6 +7,7 @@ import { useRetainedContextPayloads, } from "./chat/composerContextUndo"; +import { matchComposerInlineSuggestion } from "@t3tools/client-runtime/composerInlineSuggestion"; import { ComposerContextId, type ComposerContextRecord, @@ -70,6 +71,7 @@ function Composer({ disabled = false, placeholder = "", placeholderSuffix, + ...inlineSuggestions }: { value: string; richTextEnabled: boolean; @@ -81,7 +83,7 @@ function Composer({ disabled?: boolean; placeholder?: string; placeholderSuffix?: ComposerPromptEditorProps["placeholderSuffix"]; -}) { +} & Pick) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); return ( ); } @@ -419,6 +422,116 @@ it.each([false, true])( }, ); +it("draws a completion while typing, reports Tab, and keeps a dismissed one gone", async () => { + const candidate = { + kind: "environment", + environmentId: EnvironmentId.make("env-vps"), + label: "Hetzner VPS", + } as const; + const onAccept = vi.fn(); + await using screen = await render( + matchComposerInlineSuggestion(text, [candidate])} + onAcceptInlineSuggestion={onAccept} + />, + ); + const ghost = () => screen.container.querySelector(".composer-inline-suggestion")?.textContent; + await act(async () => editorIn(screen.container).view.focus()); + + await userEvent.keyboard("on hetz"); + await vi.waitFor(() => expect(ghost()).toBe("ner VPSTab")); + await userEvent.keyboard("{Tab}"); + expect(onAccept).toHaveBeenCalledWith({ candidate, typed: "hetz", remainder: "ner VPS" }); + + await userEvent.keyboard("{Escape}"); + await vi.waitFor(() => expect(ghost()).toBeUndefined()); + await userEvent.keyboard("n"); + expect(ghost()).toBeUndefined(); + + await userEvent.keyboard(" hetz"); + await vi.waitFor(() => expect(ghost()).toBe("ner VPSTab")); + await userEvent.keyboard("{ArrowLeft}"); + await vi.waitFor(() => expect(ghost()).toBeUndefined()); + expect(onAccept).toHaveBeenCalledTimes(1); +}); + +it("proposes no completion for pasted text or a name crossing formatting", async () => { + const candidate = { + kind: "environment", + environmentId: EnvironmentId.make("env-mini"), + label: "Mac mini", + } as const; + await using screen = await render( + matchComposerInlineSuggestion(text, [candidate])} + />, + ); + const editor = editorIn(screen.container); + const ghost = () => screen.container.querySelector(".composer-inline-suggestion"); + await act(async () => { + editor.view.focus(); + editor.commands.setTextSelection(editor.state.doc.content.size - 1); + }); + + await userEvent.keyboard("i"); + await vi.waitFor(() => expect(editor.state.doc.textContent).toContain("mi")); + expect(ghost()).toBeNull(); + + await userEvent.keyboard(" "); + await act(async () => { + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", "mac"); + editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true })); + }); + await vi.waitFor(() => expect(editor.state.doc.textContent).toContain("mi mac")); + expect(ghost()).toBeNull(); + + await userEvent.keyboard(" mac"); + await vi.waitFor(() => expect(ghost()).not.toBeNull()); + + // Revealing and then hiding the bold's Markdown source rewrites the document without typing. + await act(async () => { + editor.commands.setTextSelection(2); + editor.commands.setTextSelection(editor.state.doc.content.size - 1); + }); + expect(editor.state.doc.textContent).toContain("mi mac mac"); + expect(ghost()).toBeNull(); +}); + +it("completes the first name typed inside Markdown source shown after an undo", async () => { + const candidate = { + kind: "environment", + environmentId: EnvironmentId.make("env-vps"), + label: "Hetzner VPS", + } as const; + await using screen = await render( + matchComposerInlineSuggestion(text, [candidate])} + />, + ); + const editor = editorIn(screen.container); + const ghost = () => screen.container.querySelector(".composer-inline-suggestion")?.textContent; + await act(async () => { + editor.view.focus(); + editor.commands.setTextSelection(editor.state.doc.content.size - 1); + }); + await userEvent.keyboard("y{Control>}z{/Control}"); + await act(async () => editor.commands.setTextSelection(6)); + expect(editor.state.doc.textContent).toBe("**on he z** x"); + + await userEvent.keyboard("t"); + await vi.waitFor(() => expect(ghost()).toBe("zner VPSTab")); +}); + it("lets composition replace selected text without surrounding it", async () => { await using screen = await mountEditor("word"); const { editor } = screen; diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 402156b00128..32a7aef5574a 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1,6 +1,8 @@ import { useNativeFileDrag } from "../useNativeFileDrag"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { useAtomValue } from "@effect/atom-react"; +import type { ComposerInlineSuggestion } from "@t3tools/client-runtime/composerInlineSuggestion"; +import type { EnvironmentId } from "@t3tools/contracts"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills"; import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; @@ -113,6 +115,7 @@ import { COMPOSER_UNDO_GROUP_DELAY, type ComposerChangeKind, groupUndoByChangeKind, + isClipboardEdit, markAsClipboardEdit, markAsCompositionReplace, } from "~/composer-undo-grouping"; @@ -206,6 +209,8 @@ export interface ComposerPromptEditorProps { ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; + matchInlineSuggestion?: (textBeforeCaret: string) => ComposerEditorInlineSuggestion | null; + onAcceptInlineSuggestion?: (suggestion: ComposerEditorInlineSuggestion) => void; onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void; onPageScrollKeyUp?: (key: string) => void; onPageScrollRelease?: () => void; @@ -780,6 +785,130 @@ const ComposerChipSelectionExtension = Extension.create({ }, }); +/** A name the composer's ghost text can complete into a chip. */ +export type ComposerInlineCandidate = { readonly label: string } & ( + | { readonly kind: "environment"; readonly environmentId: EnvironmentId } + | { readonly kind: "model"; readonly instanceId: string; readonly model: string } +); + +/** What the composer proposes after the caret; the editor only draws it and reports Tab. */ +export type ComposerEditorInlineSuggestion = ComposerInlineSuggestion; + +interface InlineSuggestionState { + readonly suggestion: ComposerEditorInlineSuggestion | null; + readonly from: number | null; + /** Where the suggestion Escape dismissed starts, so it stays gone while that word grows. */ + readonly dismissedFrom: number | null; +} + +interface InlineSuggestionStorage { + match: (textBeforeCaret: string) => ComposerEditorInlineSuggestion | null; +} + +const InlineSuggestionPluginKey = new PluginKey( + "composer-inline-suggestion", +); +const CHIP_PLACEHOLDER = "\ufffc"; + +function inlineSuggestionAtCaret( + { selection }: EditorState, + match: InlineSuggestionStorage["match"], +): Pick | null { + const { $from, empty } = selection; + const { parent, parentOffset } = $from; + if (!empty || !parent.isTextblock || parent.type.spec.code) return null; + const next = parent.textBetween( + parentOffset, + Math.min(parentOffset + 1, parent.content.size), + undefined, + CHIP_PLACEHOLDER, + ); + if (next !== "" && !/\s/u.test(next)) return null; + const textBeforeCaret = parent.textBetween(0, parentOffset, undefined, (node) => + node.type.name === "hardBreak" ? "\n" : CHIP_PLACEHOLDER, + ); + const suggestion = match(textBeforeCaret); + // Accepting replaces serialized Markdown, so the name must not span formatting markers. + if (!suggestion || suggestion.typed.length > ($from.nodeBefore?.text?.length ?? 0)) return null; + return { suggestion, from: selection.from - suggestion.typed.length }; +} + +function inlineSuggestionWidget(remainder: string): HTMLElement { + const root = document.createElement("span"); + root.className = "composer-inline-suggestion"; + root.setAttribute("aria-hidden", "true"); + root.append(remainder); + const key = document.createElement("kbd"); + key.className = "composer-inline-suggestion-key"; + key.textContent = "Tab"; + root.append(key); + return root; +} + +const ComposerInlineSuggestionExtension = Extension.create({ + name: "composerInlineSuggestion", + addStorage() { + return { match: () => null }; + }, + addProseMirrorPlugins() { + const storage = this.storage; + return [ + new Plugin({ + key: InlineSuggestionPluginKey, + state: { + init: () => ({ suggestion: null, from: null, dismissedFrom: null }), + apply: (tr, previous, _, state) => { + const dismissing = tr.getMeta(InlineSuggestionPluginKey) === "dismiss"; + if (!tr.docChanged && !tr.selectionSet && !dismissing) return previous; + const appendedTo = tr.getMeta("appendedTransaction") as Transaction | undefined; + const dismissedFrom = dismissing + ? previous.from + : previous.dismissedFrom === null + ? null + : tr.mapping.map(previous.dismissedFrom); + const none = { suggestion: null, from: null, dismissedFrom }; + // Follows typing only: a moved caret, a paste, an undo or a restored draft has no word + // in progress, and Tab should keep its usual meaning there. + if ( + !tr.docChanged || + tr.getMeta("uiEvent") || + isClipboardEdit(tr) || + tr.getMeta("history$") || + tr.getMeta("preventUpdate") || + tr.getMeta("composition") !== undefined || + // Markdown-source normalization after a caret move rewrites text nobody typed. + (appendedTo?.selectionSet && !appendedTo.docChanged) + ) { + return none; + } + const found = inlineSuggestionAtCaret(state, storage.match); + return found === null || found.from === dismissedFrom + ? none + : { ...found, dismissedFrom }; + }, + }, + props: { + decorations: (state) => { + const suggestion = InlineSuggestionPluginKey.getState(state)?.suggestion; + if (!suggestion) return null; + return DecorationSet.create(state.doc, [ + Decoration.widget( + state.selection.head, + () => inlineSuggestionWidget(suggestion.remainder), + { + side: 1, + ignoreSelection: true, + key: `inline-suggestion:${suggestion.remainder}`, + }, + ), + ]); + }, + }, + }), + ]; + }, +}); + function chipSelectionDecorations({ doc, selection }: EditorState): DecorationSet { if (selection.empty) return DecorationSet.empty; const decorations: Decoration[] = []; @@ -889,6 +1018,7 @@ function createComposerExtensions(richText: boolean) { ComposerCitationExtension, ComposerContextReferenceExtension, ComposerChipSelectionExtension, + ComposerInlineSuggestionExtension, ...(richText ? [ ComposerMarkdownSourceExtension, @@ -996,6 +1126,8 @@ function ComposerPromptEditorTiptapInner( onChange, onVisibleSelectionChange, onCommandKeyDown, + matchInlineSuggestion, + onAcceptInlineSuggestion, onPageScrollKeyDown, onPageScrollKeyUp, onPageScrollRelease, @@ -1022,6 +1154,8 @@ function ComposerPromptEditorTiptapInner( onChange, onVisibleSelectionChange, onCommandKeyDown, + matchInlineSuggestion, + onAcceptInlineSuggestion, isPathQueryActive, importContextFragment, })); @@ -1165,6 +1299,13 @@ function ComposerPromptEditorTiptapInner( isKnownModel: (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)), }), editable: !disabled, + onBeforeCreate: ({ editor: created }) => { + const storage = created.storage as unknown as { + composerInlineSuggestion: InlineSuggestionStorage; + }; + storage.composerInlineSuggestion.match = (textBeforeCaret) => + readCallbacks().matchInlineSuggestion?.(textBeforeCaret) ?? null; + }, editorProps: { attributes: editorAttributes, handleDOMEvents: { @@ -1181,6 +1322,22 @@ function ComposerPromptEditorTiptapInner( }, }, handleKeyDown: (view, event) => { + const inlineSuggestion = InlineSuggestionPluginKey.getState(view.state)?.suggestion; + if ( + inlineSuggestion && + (event.key === "Tab" || event.key === "Escape") && + !event.isComposing && + !event.shiftKey && + !event.altKey && + !event.metaKey && + !event.ctrlKey + ) { + event.preventDefault(); + event.stopPropagation(); + if (event.key === "Tab") readCallbacks().onAcceptInlineSuggestion?.(inlineSuggestion); + else view.dispatch(view.state.tr.setMeta(InlineSuggestionPluginKey, "dismiss")); + return true; + } // In a right-to-left line the start is on the right. const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft"; const boundary = event.metaKey diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index af4871b45193..6ca102818481 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -12,7 +12,7 @@ import { runtimeModeDenial, } from "./runtimeModeConfig"; import { isLocalEnvironmentDisabled } from "../../localEnvironment"; -import { usePrimaryEnvironmentId } from "../../state/environments"; +import { useEnvironmentIdentities, usePrimaryEnvironmentId } from "../../state/environments"; import { useRightPanelStore } from "~/rightPanelStore"; import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste"; import { @@ -48,6 +48,8 @@ import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PRIMARY_LOCAL_ENVIRONMENT_ID, } from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { matchComposerInlineSuggestion } from "@t3tools/client-runtime/composerInlineSuggestion"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import * as Schema from "effect/Schema"; @@ -167,6 +169,7 @@ import { type ComposerCitationCommentRequest, type ComposerPromptEditorHandle, ComposerPromptEditorTiptap as ComposerPromptEditor, + type ComposerEditorInlineSuggestion, } from "../ComposerPromptEditorTiptap"; import { ComposerContextActionsContext, @@ -199,7 +202,7 @@ import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachmen import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; import { droppedThreadContextRecord } from "./threadContextDrop.logic"; import { readThreadShell } from "~/state/entities"; -import { useLinkedEnvironments } from "~/state/peerLinks"; +import { offersLinkedEnvironmentsAtom, useLinkedEnvironments } from "~/state/peerLinks"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; import type { ComposerContextRecord, @@ -224,6 +227,7 @@ import { CollapsedComposerStopAction, ComposerPrimaryActions } from "./ComposerP import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; +import { mentionableComposerModels } from "./composerModelMentions"; import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic"; import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState"; import { readPromptUltrathink } from "./TraitsPicker"; @@ -1170,6 +1174,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) composerPreviewAnnotations.length === 0 && composerReviewComments.length === 0; const linkedEnvironments = useLinkedEnvironments(environmentId); + const environmentIdentities = useEnvironmentIdentities(); + const offersMachines = useAtomValue(offersLinkedEnvironmentsAtom(environmentId)); const { items: composerMenuItems, isLoading: isComposerMenuLoading, @@ -2178,6 +2184,70 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const onSelectComposerItemStable = useStableCallback(onSelectComposerItem); + const matchInlineSuggestion = (textBeforeCaret: string) => + isLiteralPendingAnswer || questionAttachmentTarget !== null + ? null + : matchComposerInlineSuggestion(textBeforeCaret, [ + ...(offersMachines + ? environmentIdentities.map(({ environmentId: mentionedId, label }) => ({ + kind: "environment" as const, + environmentId: mentionedId, + label, + })) + : []), + // The thread's own provider wins when two offer a model of the same name. + ...mentionableComposerModels({ + instanceEntries: providerInstanceEntries, + modelOptionsByInstance, + }) + // "Default" and "Auto" are ordinary words first, and name no particular model. + .filter(({ option }) => !/^(?:default|auto)$/iu.test(option.name)) + .toSorted(({ entry: left }, { entry: right }) => + left.instanceId === selectedInstanceId + ? -1 + : right.instanceId === selectedInstanceId + ? 1 + : 0, + ) + .map(({ entry, option }) => ({ + kind: "model" as const, + instanceId: entry.instanceId, + model: option.slug, + label: option.name, + })), + ]); + const matchInlineSuggestionStable = useStableCallback(matchInlineSuggestion); + + const onAcceptInlineSuggestion = (accepted: ComposerEditorInlineSuggestion) => { + const { candidate } = accepted; + const snapshot = readComposerSnapshot(); + const rangeStart = snapshot.expandedCursor - accepted.typed.length; + // A model becomes the same mention the @ menu inserts; a machine becomes a context record. + let record: EnvironmentContextRecord | null = null; + let reference: string; + if (candidate.kind === "model") { + reference = formatComposerModelMention(candidate.instanceId, candidate.model); + } else { + record = environmentContextRecord(candidate.environmentId, candidate.label); + reference = formatInlineContextReference(environmentContextReference(record)); + } + const replacement = `${reference} `; + const rangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + snapshot.expandedCursor, + replacement, + ); + const applied = applyPromptReplacement(rangeStart, rangeEnd, replacement, { + expectedText: snapshot.value.slice(rangeStart, rangeEnd), + }); + if (applied && record) { + addComposerDraftEnvironmentContexts(composerDraftTarget, [record], { + appendReference: false, + }); + } + }; + const onAcceptInlineSuggestionStable = useStableCallback(onAcceptInlineSuggestion); + const onComposerMenuItemHighlighted = (itemId: string | null) => { setComposerHighlightedItemId(itemId); setComposerHighlightedSearchKey(composerMenuSearchKey); @@ -3871,6 +3941,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className={cn(showMobilePendingAnswerActions && "max-sm:pb-12")} onChange={onPromptChangeStable} onCommandKeyDown={onComposerCommandKeyStable} + matchInlineSuggestion={matchInlineSuggestionStable} + onAcceptInlineSuggestion={onAcceptInlineSuggestionStable} onPageScrollKeyDown={onPageScrollKeyDown} onPageScrollKeyUp={onPageScrollKeyUp} onPageScrollRelease={onPageScrollRelease} diff --git a/apps/web/src/components/chat/composerModelMentions.ts b/apps/web/src/components/chat/composerModelMentions.ts index b0a8d0bd3b64..e7f1f6fed147 100644 --- a/apps/web/src/components/chat/composerModelMentions.ts +++ b/apps/web/src/components/chat/composerModelMentions.ts @@ -7,12 +7,12 @@ import { getDisplayModelName, type ModelEsque } from "./providerIconUtils"; type ComposerModelItem = Extract; -export function matchComposerModelItems(input: { +/** The models a mention can name: ready instances only, as in the model picker. */ +export function mentionableComposerModels