Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

14.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import {
  SKILL_MENTION_PATTERN,
  type SkillRecord,
  refreshSkillsCatalog,
  useSkillsCatalog,
} from "@/features/chat";
import { useT } from "@/i18n";
import type {
  Unstable_DirectiveFormatter,
  Unstable_DirectiveSegment,
} from "@assistant-ui/core";
import {
  ComposerPrimitive,
  unstable_useMentionAdapter,
  unstable_useTriggerPopoverScopeContext,
  useAui,
} from "@assistant-ui/react";
import { Scroll01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
  type KeyboardEvent,
  type MutableRefObject,
  type ReactElement,
  type RefObject,
  useCallback,
  useEffect,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import {
  type MentionToken,
  mentionTokenAt,
  mentionableSkills,
  rankMentionSkills,
  replaceMentionToken,
} from "./skill-mention-token";

// cap results because each root can contain 1,000 skills.
const MAX_MENTION_RESULTS = 50;

const skillMentionFormatter: Unstable_DirectiveFormatter = {
  serialize: (item) => `@${item.label}`,
  parse(text) {
    const segments: Unstable_DirectiveSegment[] = [];
    let lastIndex = 0;

    // Same pattern as the send path, so a chip and a catalog lookup agree on what a mention is.
    for (const match of text.matchAll(SKILL_MENTION_PATTERN)) {
      const whitespace = match[1] ?? "";
      const mentionStart = match.index + whitespace.length;
      if (mentionStart > lastIndex) {
        segments.push({
          kind: "text",
          text: text.slice(lastIndex, mentionStart),
        });
      }
      const label = match[2] ?? "";
      segments.push({
        kind: "mention",
        type: "skill",
        label,
        id: label,
      });
      lastIndex = match.index + match[0].length;
    }

    if (lastIndex < text.length) {
      segments.push({ kind: "text", text: text.slice(lastIndex) });
    }
    return segments;
  },
};

function useHighlightedItemScroll(root: HTMLElement | null) {
  useEffect(() => {
    if (!root) return;
    const scroll = () => {
      root
        .querySelector<HTMLElement>("[data-highlighted]")
        ?.scrollIntoView({ block: "nearest" });
    };
    const observer = new MutationObserver(scroll);
    observer.observe(root, {
      subtree: true,
      attributes: true,
      attributeFilter: ["data-highlighted"],
    });
    scroll();
    return () => observer.disconnect();
  }, [root]);
}

function MentionEnterSignal({
  onChange,
  active,
}: {
  onChange?: (consumesEnter: boolean) => void;
  active: boolean;
}): null {
  useEffect(() => {
    if (!onChange) return;
    onChange(active);
    return () => onChange(false);
  }, [active, onChange]);
  return null;
}

function MentionOpenSignal({
  onChange,
}: {
  onChange?: (open: boolean) => void;
}): null {
  const { open } = unstable_useTriggerPopoverScopeContext();
  useLayoutEffect(() => {
    if (!onChange) return;
    onChange(open);
    return () => onChange(false);
  }, [open, onChange]);
  return null;
}

// accept Tab only in the composer because the library handles Enter and focus may move elsewhere.
function MentionTabAccept({
  scopeRef,
}: {
  scopeRef: RefObject<HTMLElement | null>;
}): null {
  const { open, items, handleKeyDown } = unstable_useTriggerPopoverScopeContext();
  const active = open && items.length > 0;
  useEffect(() => {
    if (!active) return;
    const accept = (event: globalThis.KeyboardEvent) => {
      if (event.key !== "Tab" || event.shiftKey || event.isComposing) return;
      if (
        !(event.target instanceof HTMLTextAreaElement) ||
        !scopeRef.current?.contains(event.target)
      )
        return;
      const enter = {
        key: "Enter",
        shiftKey: false,
        preventDefault: () => event.preventDefault(),
      };
      if (handleKeyDown(enter)) event.stopPropagation();
    };
    // intercept before the browser moves focus or the composer handles Tab.
    window.addEventListener("keydown", accept, true);
    return () => window.removeEventListener("keydown", accept, true);
  }, [active, handleKeyDown, scopeRef]);
  return null;
}

// replace the full token because the library insert stops at the caret and leaves trailing text.
function MentionTokenReplacer(): null {
  const aui = useAui();
  const { registerSelectItemOverride, setCursorPosition } =
    unstable_useTriggerPopoverScopeContext();
  useEffect(
    () =>
      registerSelectItemOverride((item) => {
        const input = document.activeElement;
        if (!(input instanceof HTMLTextAreaElement)) return false;
        const text = aui.composer().getState().text;
        if (input.value !== text) return false;
        const token = mentionTokenAt(text, input.selectionStart);
        if (!token) return false;
        const next = replaceMentionToken(
          text,
          token,
          skillMentionFormatter.serialize(item),
        );
        aui.composer().setText(next.text);
        setCursorPosition(next.caret);
        requestAnimationFrame(() => {
          input.setSelectionRange(next.caret, next.caret);
        });
        return true;
      }),
    [aui, registerSelectItemOverride, setCursorPosition],
  );
  return null;
}

export function SkillMentionPopover({
  enabled: mentionsEnabled,
  composerRef,
  onConsumesEnterChange,
  onOpenChange,
}: {
  enabled: boolean;
  composerRef: RefObject<HTMLElement | null>;
  onConsumesEnterChange?: (consumesEnter: boolean) => void;
  onOpenChange?: (open: boolean) => void;
}): ReactElement | null {
  const t = useT();
  const { skills } = useSkillsCatalog();
  const [listElement, setListElement] = useState<HTMLDivElement | null>(null);
  const available = useMemo(
    () => (mentionsEnabled ? mentionableSkills(skills) : []),
    [mentionsEnabled, skills],
  );
  const items = useMemo(
    () =>
      available.map((skill) => ({
        id: skill.name,
        type: "skill",
        label: skill.name,
        description: skill.description,
      })),
    [available],
  );
  const mention = unstable_useMentionAdapter({
    items,
    includeModelContextTools: false,
    formatter: skillMentionFormatter,
  });
  // cap ranked adapter results because the popover navigates them, not only rendered rows.
  const adapter = useMemo(() => {
    const byName = new Map(items.map((item) => [item.id, item]));
    return {
      ...mention.adapter,
      search: (query: string) =>
        rankMentionSkills(available, query, MAX_MENTION_RESULTS).flatMap(
          (skill) => byName.get(skill.name) ?? [],
        ),
    };
  }, [available, items, mention.adapter]);
  useHighlightedItemScroll(listElement);
  if (items.length === 0) return null;

  return (
    <ComposerPrimitive.Unstable_TriggerPopover
      char="@"
      adapter={adapter}
      aria-label={t("skills.mentions")}
      className="dropdown-surface data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 absolute bottom-[calc(100%+8px)] left-3 z-40 w-[min(360px,calc(100%-24px))] overflow-hidden rounded-lg border border-border/60 bg-popover p-1 text-popover-foreground shadow-border duration-100"
    >
      <ComposerPrimitive.Unstable_TriggerPopover.Directive
        {...mention.directive}
      />
      <MentionOpenSignal onChange={onOpenChange} />
      <MentionTokenReplacer />
      <MentionTabAccept scopeRef={composerRef} />
      <ComposerPrimitive.Unstable_TriggerPopoverItems>
        {(results) => (
          <>
            <MentionEnterSignal
              onChange={onConsumesEnterChange}
              active={results.length > 0}
            />
            <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
              {t("skills.mentions")}
            </div>
            <div ref={setListElement} className="max-h-64 overflow-y-auto">
              {results.map((item, index) => (
                <ComposerPrimitive.Unstable_TriggerPopoverItem
                  key={item.id}
                  item={item}
                  index={index}
                  // Keep focus (and the caret) in the textarea so the token replacer sees it.
                  onMouseDown={(event) => event.preventDefault()}
                  className="flex w-full items-start gap-2.5 rounded-md px-3 py-2 text-left outline-none transition-colors hover:bg-accent hover:text-accent-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground"
                >
                  <HugeiconsIcon
                    icon={Scroll01Icon}
                    strokeWidth={1.75}
                    className="mt-0.5 size-4 shrink-0 text-primary"
                  />
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-sm font-medium">
                      {item.label}
                    </span>
                    {item.description ? (
                      <span className="line-clamp-2 max-h-8 overflow-hidden break-words text-xs leading-4 text-muted-foreground">
                        {item.description}
                      </span>
                    ) : null}
                  </span>
                </ComposerPrimitive.Unstable_TriggerPopoverItem>
              ))}
            </div>
          </>
        )}
      </ComposerPrimitive.Unstable_TriggerPopoverItems>
    </ComposerPrimitive.Unstable_TriggerPopover>
  );
}

type MentionRange = MentionToken | null;

export function useTextareaSkillMentions({
  text,
  setText,
  inputRef,
  composingRef,
  enabled: mentionsEnabled,
}: {
  text: string;
  setText: (text: string) => void;
  inputRef: RefObject<HTMLTextAreaElement | null>;
  composingRef: MutableRefObject<boolean>;
  enabled: boolean;
}) {
  const t = useT();
  const { skills } = useSkillsCatalog();
  const [range, setRange] = useState<MentionRange>(null);
  const listboxId = useId();
  const [highlighted, setHighlighted] = useState(0);
  const results = useMemo(
    () =>
      range && mentionsEnabled
        ? rankMentionSkills(
            mentionableSkills(skills),
            range.query,
            MAX_MENTION_RESULTS,
          )
        : [],
    [mentionsEnabled, range, skills],
  );

  const open = range !== null && results.length > 0;
  const activeOptionId = open
    ? `${listboxId}-option-${highlighted}`
    : undefined;
  useEffect(() => {
    if (
      !mentionsEnabled ||
      (range &&
        (text.length < range.end ||
          !text.slice(range.start, range.end).startsWith("@")))
    ) {
      setRange(null);
    }
  }, [mentionsEnabled, range, text]);

  const resultsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!range) return;
    resultsRef.current
      ?.querySelector<HTMLElement>(`[data-mention-index="${highlighted}"]`)
      ?.scrollIntoView({ block: "nearest" });
  }, [highlighted, range]);

  const update = useCallback(
    (nextText: string, caret: number) => {
      if (composingRef.current) {
        setRange(null);
        return;
      }
      const next = mentionTokenAt(nextText, caret);
      // A fresh @ re-reads the folders, so a skill written since page load is offered.
      if (next?.query === "") refreshSkillsCatalog();
      setRange(next);
      setHighlighted(0);
    },
    [composingRef],
  );

  const insert = useCallback(
    (skill: SkillRecord) => {
      if (!range) return;
      const directive = skillMentionFormatter.serialize({
        id: skill.name,
        type: "skill",
        label: skill.name,
      });
      const next = replaceMentionToken(text, range, directive);
      setText(next.text);
      setRange(null);
      requestAnimationFrame(() => {
        inputRef.current?.focus();
        inputRef.current?.setSelectionRange(next.caret, next.caret);
      });
    },
    [inputRef, range, setText, text],
  );

  const onKeyDown = useCallback(
    (event: KeyboardEvent<HTMLTextAreaElement>): boolean => {
      if (!range || composingRef.current || results.length === 0) return false;
      if (event.key === "ArrowDown" || event.key === "ArrowUp") {
        event.preventDefault();
        const direction = event.key === "ArrowDown" ? 1 : -1;
        setHighlighted(
          (index) => (index + direction + results.length) % results.length,
        );
        return true;
      }
      if ((event.key === "Enter" && !event.shiftKey) || event.key === "Tab") {
        event.preventDefault();
        insert(results[highlighted] ?? results[0]);
        return true;
      }
      if (event.key === "Escape") {
        event.preventDefault();
        setRange(null);
        return true;
      }
      return false;
    },
    [composingRef, highlighted, insert, range, results],
  );

  const popover = open ? (
    <div className="dropdown-surface animate-in fade-in-0 zoom-in-95 absolute bottom-[calc(100%+8px)] left-3 z-40 w-[min(360px,calc(100%-24px))] overflow-hidden rounded-lg border border-border/60 bg-popover p-1 text-popover-foreground shadow-border duration-100">
      <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
        {t("skills.mentions")}
      </div>
      <div
        ref={resultsRef}
        id={listboxId}
        role="listbox"
        aria-label={t("skills.mentions")}
        className="max-h-64 overflow-y-auto"
      >
        {results.map((skill, index) => (
          <button
            key={`${skill.source}:${skill.name}`}
            type="button"
            id={`${listboxId}-option-${index}`}
            role="option"
            aria-selected={index === highlighted}
            tabIndex={-1}
            data-mention-index={index}
            data-highlighted={index === highlighted}
            className="flex w-full items-start gap-2.5 rounded-md px-3 py-2 text-left outline-none transition-colors hover:bg-accent hover:text-accent-foreground data-[highlighted=true]:bg-accent data-[highlighted=true]:text-accent-foreground"
            onMouseDown={(event) => event.preventDefault()}
            onClick={() => insert(skill)}
            onMouseEnter={() => setHighlighted(index)}
          >
            <HugeiconsIcon
              icon={Scroll01Icon}
              strokeWidth={1.75}
              className="mt-0.5 size-4 shrink-0 text-primary"
            />
            <span className="min-w-0 flex-1">
              <span className="block truncate text-sm font-medium">
                {skill.name}
              </span>
              <span className="line-clamp-2 max-h-8 overflow-hidden break-words text-xs leading-4 text-muted-foreground">
                {skill.description}
              </span>
            </span>
          </button>
        ))}
      </div>
    </div>
  ) : null;

  return {
    update,
    onKeyDown,
    popover,
    close: () => setRange(null),
    inputProps: {
      role: "combobox" as const,
      "aria-autocomplete": "list" as const,
      "aria-expanded": open,
      "aria-controls": open ? listboxId : undefined,
      "aria-activedescendant": activeOptionId,
    },
  };
}