Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
useRetainedContextPayloads,
} from "./chat/composerContextUndo";

import type { ServerProviderSkill } from "@t3tools/contracts";
import { matchComposerInlineSuggestion } from "@t3tools/client-runtime/composerInlineSuggestion";
import { EnvironmentId, type ServerProviderSkill } from "@t3tools/contracts";
import type { Editor } from "@tiptap/core";
import { redoDepth, undoDepth } from "@tiptap/pm/history";
import { NodeSelection } from "@tiptap/pm/state";
Expand Down Expand Up @@ -36,12 +37,13 @@ function Composer({
richTextEnabled,
skills,
onChange,
...inlineSuggestions
}: {
value: string;
richTextEnabled: boolean;
skills: ReadonlyArray<ServerProviderSkill>;
onChange?: ComposerPromptEditorProps["onChange"] | undefined;
}) {
} & Pick<ComposerPromptEditorProps, "matchInlineSuggestion" | "onAcceptInlineSuggestion">) {
const [prompt, setPrompt] = useState({ value, cursor: value.length });
return (
<ComposerPromptEditor
Expand All @@ -58,6 +60,7 @@ function Composer({
onChange?.(...args);
}}
onPaste={() => {}}
{...inlineSuggestions}
/>
);
}
Expand Down Expand Up @@ -233,6 +236,80 @@ 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(
<Composer
value=""
richTextEnabled
skills={[]}
matchInlineSuggestion={(text) => 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(
<Composer
value="**Mac** m"
richTextEnabled
skills={[]}
matchInlineSuggestion={(text) => 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());
});

it("lets composition replace selected text without surrounding it", async () => {
await using screen = await mountEditor("word");
const { editor } = screen;
Expand Down
152 changes: 152 additions & 0 deletions apps/web/src/components/ComposerPromptEditorTiptap.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
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";
Expand Down Expand Up @@ -183,6 +185,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;
Expand Down Expand Up @@ -714,6 +718,126 @@ 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<ComposerInlineCandidate>;

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<InlineSuggestionState>(
"composer-inline-suggestion",
);
const CHIP_PLACEHOLDER = "\ufffc";

function inlineSuggestionAtCaret(
{ selection }: EditorState,
match: InlineSuggestionStorage["match"],
): Pick<InlineSuggestionState, "suggestion" | "from"> | 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<unknown, InlineSuggestionStorage>({
name: "composerInlineSuggestion",
addStorage() {
return { match: () => null };
},
addProseMirrorPlugins() {
const storage = this.storage;
return [
new Plugin<InlineSuggestionState>({
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 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") ||
tr.getMeta("history$") ||
tr.getMeta("preventUpdate") ||
tr.getMeta("composition") !== undefined
) {
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[] = [];
Expand Down Expand Up @@ -818,6 +942,7 @@ function createComposerExtensions(richText: boolean) {
ComposerCitationExtension,
ComposerContextReferenceExtension,
ComposerChipSelectionExtension,
ComposerInlineSuggestionExtension,
...(richText
? [
ComposerMarkdownSourceExtension,
Expand Down Expand Up @@ -926,6 +1051,8 @@ function ComposerPromptEditorTiptapInner(
onChange,
onVisibleSelectionChange,
onCommandKeyDown,
matchInlineSuggestion,
onAcceptInlineSuggestion,
onPageScrollKeyDown,
onPageScrollKeyUp,
onPageScrollRelease,
Expand All @@ -952,6 +1079,8 @@ function ComposerPromptEditorTiptapInner(
onChange,
onVisibleSelectionChange,
onCommandKeyDown,
matchInlineSuggestion,
onAcceptInlineSuggestion,
isPathQueryActive,
importContextFragment,
}));
Expand Down Expand Up @@ -1094,9 +1223,32 @@ 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,
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
Expand Down
Loading
Loading