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.

5.7 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

"use client";

import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { escapeBidiControls } from "@/lib/escape-bidi-controls";
import { MAX_HIGHLIGHT_CHARS, codeFence } from "@/lib/markdown-plugins";
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { Tick02Icon } from "@/lib/tick-icon";
import { toast } from "@/lib/toast";
import { Download01Icon } from "@hugeicons/core-free-icons";
import { Copy01Icon } from "@/lib/copy-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import { IconActionButton } from "./icon-action-button";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Streamdown } from "streamdown";
import { codePlugin } from "./shared-code-plugin";

const COPY_RESET_MS = 2000;
const SHIKI_THEME = ["github-light", "github-dark"] as [
  "github-light",
  "github-dark",
];
/** Within this many px of the bottom counts as following the stream. */
const PIN_SLACK_PX = 40;

export function CopyBtn({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    return () => {
      if (timer.current) {
        clearTimeout(timer.current);
      }
    };
  }, []);

  const copy = useCallback(async () => {
    if (await copyToClipboard(text)) {
      setCopied(true);
      if (timer.current) {
        clearTimeout(timer.current);
      }
      timer.current = setTimeout(() => setCopied(false), COPY_RESET_MS);
    }
  }, [text]);

  return (
    <IconActionButton label={copied ? "Copied" : "Copy to clipboard"} onClick={copy}>
      {copied ? (
        <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3" />
      ) : (
        <HugeiconsIcon icon={Copy01Icon} className="size-3" />
      )}
    </IconActionButton>
  );
}

function DownloadBtn({ code, name }: { code: string; name: string }) {
  // A bare blob anchor is silently dropped by WebView2; the shared boundary gives Tauri a save chooser.
  const download = useCallback(() => {
    void downloadFile(code, name, "text/plain;charset=utf-8").catch((error) => {
      if (!isDownloadCancelled(error)) {
        toast.error("Could not save file.");
      }
    });
  }, [code, name]);

  return (
    <IconActionButton label="Download" onClick={download}>
      <HugeiconsIcon icon={Download01Icon} className="size-3" />
    </IconActionButton>
  );
}

/** Shiki tokenizes only once the block nears the viewport; immediate without IntersectionObserver. */
function HighlightedCode({
  code: source,
  language,
  plain = false,
}: {
  code: string;
  language: string;
  plain?: boolean;
}) {
  const markdown = useMemo(() => {
    const fence = codeFence(source);
    return `${fence}${language}\n${source}\n${fence}`;
  }, [source, language]);
  const containerRef = useRef<HTMLDivElement>(null);
  const [nearViewport, setNearViewport] = useState(
    () => typeof IntersectionObserver === "undefined",
  );
  const pinnedToBottom = useRef(true);
  useEffect(() => {
    if (nearViewport) return;
    const el = containerRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          setNearViewport(true);
          io.disconnect();
        }
      },
      { rootMargin: "200px" },
    );
    io.observe(el);
    return () => io.disconnect();
  }, [nearViewport]);

  useEffect(() => {
    const el = containerRef.current;
    if (plain && el && pinnedToBottom.current) {
      el.scrollTop = el.scrollHeight;
    }
  }, [plain, source]);

  const handleScroll = () => {
    const el = containerRef.current;
    if (el) {
      pinnedToBottom.current =
        el.scrollHeight - el.scrollTop - el.clientHeight < PIN_SLACK_PX;
    }
  };

  // Skip shiki while the model is writing (it re-tokenizes every fragment) and on payloads too big.
  const highlight =
    nearViewport && !plain && source.length <= MAX_HIGHLIGHT_CHARS;

  return (
    <div
      ref={containerRef}
      onScroll={handleScroll}
      className="max-h-48 overflow-auto text-xs [&_pre]:!m-0 [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:!text-xs [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!p-3 [&_[data-streamdown=code-block]]:!border-0"
    >
      {highlight ? (
        <Streamdown
          mode="static"
          plugins={{ code: codePlugin }}
          controls={{ code: false }}
          shikiTheme={SHIKI_THEME}
        >
          {markdown}
        </Streamdown>
      ) : (
        // A div, not a <pre>: the container's [&_pre]:!p-0 would shift content when shiki swaps in.
        <div className="whitespace-pre p-3 font-mono text-xs text-muted-foreground">
          {source}
        </div>
      )}
    </div>
  );
}

export function ToolCodeCell({
  label,
  code,
  language,
  downloadName,
  streaming = false,
}: {
  label: string;
  code: string;
  language: string;
  downloadName: string;
  streaming?: boolean;
}) {
  return (
    <div className="border-l-2 border-muted-foreground/20 pl-2">
      <div className="flex items-center justify-between">
        <span className="text-xs font-medium text-muted-foreground">
          {label}
        </span>
        <div className="flex items-center gap-1">
          <CopyBtn text={code} />
          <DownloadBtn code={code} name={downloadName} />
        </div>
      </div>
      {/* Display only: Copy and Download above keep the code as it runs. */}
      <HighlightedCode
        code={escapeBidiControls(code)}
        language={language}
        plain={streaming}
      />
    </div>
  );
}