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.

7.3 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

// Shared so the in-place collapse and the post-message auto-render agree on renderable fences.

export type CodeFence = {
  language: string | null;
  source: string;
};

// One fenced block spanning the whole string. The close is THREE OR MORE backticks (CommonMark
// "at least as many"), and needs a line break before it unless the body is empty.
export const CODE_FENCE_RE =
  /^```([^\r\n`]*)\r?\n(?:([\s\S]*?)\r?\n`{3,}|`{3,})$/;

export type ToolCallPartLike = {
  type?: string;
  toolName?: string;
  args?: unknown;
  result?: unknown;
};

// True when a part is a render_html tool call with usable code or a non-error result.
export function isRenderableRenderHtmlToolPart(part: unknown): boolean {
  const toolPart = part as ToolCallPartLike;
  if (toolPart.type !== "tool-call" || toolPart.toolName !== "render_html") {
    return false;
  }
  if (
    typeof toolPart.result === "string" &&
    toolPart.result.startsWith("Error:")
  ) {
    return false;
  }
  if (
    typeof toolPart.result === "string" &&
    toolPart.result.startsWith("Rendered HTML canvas")
  ) {
    return true;
  }
  const args = toolPart.args as { code?: unknown } | undefined;
  return typeof args?.code === "string" && args.code.trim().length > 0;
}

export function getCodeFence(blockContent: string): CodeFence | null {
  const match = blockContent.trimEnd().match(CODE_FENCE_RE);
  if (!match) {
    return null;
  }
  // CommonMark closes a fence at the FIRST bare run on its own line, so a body still holding one
  // means the match overran; a delimiter line with an info string is ordinary code.
  if (/^ {0,3}`{3,}[\t ]*\r?$/m.test(match[2])) {
    return null;
  }

  return {
    language: match[1]?.trim() || null,
    // Absent only for a fence that closes on the line after it opens.
    source: match[2] ?? "",
  };
}

export function isSvgFence(codeFence: CodeFence): boolean {
  const lang = codeFence.language?.toLowerCase() ?? "";
  if (lang === "svg") return true;
  if (lang === "xml" || lang === "html") {
    const trimmed = codeFence.source.trimStart();
    // <svg directly, or <?xml ...?> then <svg
    if (trimmed.startsWith("<svg")) return true;
    if (trimmed.startsWith("<?xml") && trimmed.includes("<svg")) return true;
  }
  return false;
}

export function isHtmlFence(codeFence: CodeFence): boolean {
  const lang = codeFence.language?.toLowerCase() ?? "";
  return lang === "html" && !isSvgFence(codeFence);
}

export function isFullHtmlDocument(source: string): boolean {
  const trimmed = source.trimStart();
  return /^<!doctype\s+html\b/i.test(trimmed) || /^<html[\s>]/i.test(trimmed);
}

export interface HtmlFence {
  source: string;
  isFullDocument: boolean;
  // The only fence form CODE_FENCE_RE collapses, so only these may be skipped as shown.
  isPlainFence: boolean;
  index: number;
}

// Opening fence: up to 3 leading spaces, >=3 backticks, then a backtick-free info string.
const FENCE_OPEN_RE = /^( {0,3})(`{3,})([^`\r\n]*)$/;

// Line-based so multiple fences are found and backticks inside a <script> never split a block.
export function extractHtmlFences(text: string): HtmlFence[] {
  const lines = text.split(/\r?\n/);
  const fences: HtmlFence[] = [];
  let i = 0;
  let index = 0;

  while (i < lines.length) {
    const open = lines[i].match(FENCE_OPEN_RE);
    if (!open) {
      i++;
      continue;
    }
    const indent = open[1].length;
    const ticks = open[2].length;
    const lang = open[3].trim().split(/\s+/)[0]?.toLowerCase() ?? "";

    const closeRe = new RegExp(`^ {0,3}\`{${ticks},}\\s*$`);
    // Strip up to `indent` leading spaces (CommonMark fence indentation).
    const indentRe = indent > 0 ? new RegExp(`^ {0,${indent}}`) : null;
    let j = i + 1;
    const body: string[] = [];
    let closed = false;
    while (j < lines.length) {
      if (closeRe.test(lines[j])) {
        closed = true;
        break;
      }
      body.push(indentRe ? lines[j].replace(indentRe, "") : lines[j]);
      j++;
    }

    if (!closed) {
      break; // everything after an unterminated open fence is inside it
    }

    if (lang === "html") {
      const source = body.join("\n");
      if (!isSvgFence({ language: "html", source })) {
        fences.push({
          source,
          isFullDocument: isFullHtmlDocument(source),
          isPlainFence: indent === 0 && ticks === 3,
          index: index++,
        });
      }
    }

    i = j + 1;
  }

  return fences;
}

export type ReactFenceLang = "jsx" | "tsx";

export interface ReactFence {
  source: string;
  lang: ReactFenceLang;
  index: number;
}

const IMPORTS_REACT_RE = /\bfrom\s*["'](?:react|react-dom)(?:\/[^"']*)?["']/;
const RENDERABLE_ENTRY_RE =
  /\bexport\s+default\b|\bas\s+default\s*[,}]|\b(?:function|const|let|var|class)\s+App\b/;

// A fence gets a React preview only when it has something to mount: without a default export or an
// App, every TS snippet in a coding answer would get a card that can only fail.
export function reactFenceLang(language: string | null, source: string): ReactFenceLang | null {
  const lang = language?.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
  if (!RENDERABLE_ENTRY_RE.test(source)) return null;
  if (lang === "jsx" || lang === "tsx") return lang;
  if (!IMPORTS_REACT_RE.test(source)) return null;
  if (lang === "js" || lang === "javascript" || lang === "mjs") return "jsx";
  if (lang === "ts" || lang === "typescript") return "tsx";
  return null;
}

// Same line scanner as extractHtmlFences, for every closed fence that reactFenceLang accepts.
export function extractReactFences(text: string): ReactFence[] {
  const lines = text.split(/\r?\n/);
  const fences: ReactFence[] = [];
  let i = 0;
  let index = 0;

  while (i < lines.length) {
    const open = lines[i].match(FENCE_OPEN_RE);
    if (!open) {
      i++;
      continue;
    }
    const indent = open[1].length;
    const ticks = open[2].length;
    const closeRe = new RegExp(`^ {0,3}\`{${ticks},}\\s*$`);
    const indentRe = indent > 0 ? new RegExp(`^ {0,${indent}}`) : null;
    let j = i + 1;
    const body: string[] = [];
    let closed = false;
    while (j < lines.length) {
      if (closeRe.test(lines[j])) {
        closed = true;
        break;
      }
      body.push(indentRe ? lines[j].replace(indentRe, "") : lines[j]);
      j++;
    }

    if (!closed) {
      break;
    }

    const source = body.join("\n");
    const lang = reactFenceLang(open[3], source);
    if (lang) fences.push({ source, lang, index: index++ });

    i = j + 1;
  }

  return fences;
}

const COMPONENT_NAME_RES = [
  /\bexport\s+default\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,
  /\bexport\s+default\s+class\s+([A-Za-z_$][\w$]*)/,
  // Tabs and spaces only, around an optional `;`: `\s*;?\s*` backtracks quadratically on a long run.
  /\bexport\s+default\s+([A-Za-z_$][\w$]*)[ \t]*(?:;[ \t]*)?\r?$/m,
  /\bexport\s*\{[^{}]*?\b([A-Za-z_$][\w$]*)\s+as\s+default\b/,
];

/** The component's name for the card title, or null. */
export function reactComponentName(source: string): string | null {
  for (const re of COMPONENT_NAME_RES) {
    const name = re.exec(source)?.[1];
    if (name && name !== "function" && name !== "class") return name;
  }
  return /\b(?:function|const|let|var|class)\s+App\b/.test(source) ? "App" : null;
}