The platform for continuously improving AI agents.
// Adapted from AI SDK Agents ghost-completion; see NOTICE.md.
import { type KeyboardEvent, type SyntheticEvent, useEffect, useId, useState } from "react";
import { Kbd } from "@/components/ui/kbd";
export const CHAT_COMPLETIONS = [
"Explore the data and help me prepare it for model training.",
"Explain the latest results in plain English.",
"Compare the model against the baseline.",
"Create an eval set for this dataset.",
"Train a model using the prepared dataset.",
"Show me what changed in this experiment.",
"Continue from the retained results and explain the next step.",
];
export function completionFor(
value: string,
candidates: readonly string[],
suggestOnEmpty = false
) {
if (value === "" && suggestOnEmpty) return candidates[0] ?? "";
if (value.trim().length < 3 || value.includes("@") || value.includes("\n")) return "";
const match = candidates.find(
(candidate) =>
candidate.toLowerCase().startsWith(value.toLowerCase()) && candidate.length > value.length
);
return match?.slice(value.length) ?? "";
}
export function useGhostCompletion(
value: string,
onValueChange: (value: string) => void,
candidates: readonly string[] = CHAT_COMPLETIONS,
suggestOnEmpty = false
) {
const [ready, setReady] = useState("");
const [dismissed, setDismissed] = useState<string | null>(null);
const [eligible, setEligible] = useState(false);
const [composing, setComposing] = useState(false);
const [scroll, setScroll] = useState({ left: 0, top: 0 });
const hintId = useId();
useEffect(() => {
const timer = setTimeout(() => setReady(value), 350);
return () => clearTimeout(timer);
}, [value]);
const suffix =
eligible && !composing && dismissed !== value && ready === value
? completionFor(value, candidates, suggestOnEmpty)
: "";
const track = (event: SyntheticEvent<HTMLTextAreaElement>) => {
const field = event.currentTarget;
setEligible(
document.activeElement === field &&
field.selectionStart === field.value.length &&
field.selectionEnd === field.value.length
);
};
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
if (!suffix || event.nativeEvent.isComposing || composing) return;
const field = event.currentTarget;
if (field.selectionStart !== value.length || field.selectionEnd !== value.length) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setDismissed(value);
return;
}
const word =
event.key === "ArrowRight" &&
(event.altKey || event.ctrlKey) &&
!event.shiftKey &&
!event.metaKey;
if (
(event.key === "Tab" &&
!event.shiftKey &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey) ||
word
) {
event.preventDefault();
event.stopPropagation();
const next = value + (word ? (/^\s*\S+/.exec(suffix)?.[0] ?? suffix) : suffix);
setReady(next);
onValueChange(next);
requestAnimationFrame(() => field.setSelectionRange(next.length, next.length));
}
};
return {
hint: suffix ? (
<span className="sr-only" id={hintId}>
Suggestion: {suffix}. Press Tab to accept, Alt Right to accept one word, or Escape to
dismiss.
</span>
) : null,
inputProps: {
"aria-describedby": suffix ? hintId : undefined,
onBlur: () => setEligible(false),
onCompositionEnd: (event: SyntheticEvent<HTMLTextAreaElement>) => {
setComposing(false);
track(event);
},
onCompositionStart: () => setComposing(true),
onFocus: track,
onKeyDownCapture: onKeyDown,
onScroll: (event: SyntheticEvent<HTMLTextAreaElement>) =>
setScroll({ left: event.currentTarget.scrollLeft, top: event.currentTarget.scrollTop }),
onSelect: track,
},
layer: suffix ? (
<div
aria-hidden="true"
className={
suggestOnEmpty
? "pointer-events-none col-start-1 row-start-1 overflow-hidden"
: "pointer-events-none absolute inset-0 overflow-hidden"
}
>
<div
className="ghost-completion-text whitespace-pre-wrap break-words text-xs leading-4"
style={{ transform: `translate(${-scroll.left}px, ${-scroll.top}px)` }}
>
<span className="invisible">{value}</span>
<span className="text-muted-foreground">{suffix}</span>
<Kbd className="ml-1">Tab</Kbd>
</div>
</div>
) : null,
suffix,
};
}