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.

19.9 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

// Harness for tests/studio/playwright_thread_weight.py: the real Thread and real markdown bodies,
// seeded via thread.import on a local runtime (only it backs export/import used by delete).

import {
  hasPendingProgressiveMounts,
  holdProgressiveMounts,
} from "@/components/assistant-ui/progressive-messages";
import { Thread } from "@/components/assistant-ui/thread";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { TooltipProvider } from "@/components/ui/tooltip";
import {
  AssistantRuntimeProvider,
  type ChatModelAdapter,
  ExportedMessageRepository,
  SimpleImageAttachmentAdapter,
  type ThreadAssistantMessagePart,
  type ThreadMessageLike,
  useAui,
  unstable_useRemoteThreadListRuntime,
  type unstable_RemoteThreadListAdapter,
  useLocalRuntime,
} from "@assistant-ui/react";
import {
  RouterProvider,
  createMemoryHistory,
  createRootRoute,
  createRouter,
} from "@tanstack/react-router";
import { type ReactElement, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import "./src/index.css";
import { watchModalPointerLock } from "./src/lib/modal-pointer-lock";

// Answer ForkCountBadge GETs in-page: a Playwright-side answer would add a CDP round trip per
// assistant message inside the timed region.
const realFetch = window.fetch.bind(window);
const apiWrites: { url: string; body: string | null }[] = [];
window.fetch = (input, init) => {
  const url = typeof input === "string" ? input : (input as Request).url ?? String(input);
  if (url.includes("/api/")) {
    if (init?.method && init.method !== "GET") {
      apiWrites.push({ url, body: typeof init.body === "string" ? init.body : null });
    }
    return Promise.resolve(
      new Response("{}", {
        status: 200,
        headers: { "content-type": "application/json" },
      }),
    );
  }
  return realFetch(input, init);
};

const PROSE =
  "The reception of a long thread is decided by what the renderer does on every " +
  "interaction, not by what it did once at load. This paragraph exists to give each " +
  "message real prose to lay out, to wrap over several lines at a chat column's width, " +
  "and to make the message tall enough that a seeded thread overflows the viewport.";

const CLOSING =
  "A second paragraph, so each message has more than one block-level child and the " +
  "layout pass inside it is not trivially small.";

function codeFence(index: number): string {
  return [
    "```python",
    `def step_${index}(rows):`,
    '    """One fence per message, so every message pays a highlighter pass."""',
    "    total = 0",
    "    for row in rows:",
    "        total += row.weight * row.count",
    "    return total",
    "```",
  ].join("\n");
}

function katexBlock(index: number): string {
  return `$$\n\\sum_{k=1}^{${index + 1}} \\frac{1}{k^2} \\le \\frac{\\pi^2}{6}\n$$`;
}

function assistantMarkdown(index: number): string {
  return [
    `Reply ${index}. ${PROSE}`,
    codeFence(index),
    katexBlock(index),
    CLOSING,
  ].join("\n\n");
}

/** Plain prose reply with zero focusable controls (fenced bodies always carry a Copy button). */
function plainAssistantMarkdown(index: number): string {
  return [`Reply ${index}. ${PROSE}`, CLOSING].join("\n\n");
}

function userMarkdown(index: number): string {
  return `Prompt ${index}. ${PROSE}`;
}

/**
 * Which assistant replies are plain prose, by their ordinal among assistant messages.
 * `"all"` makes every reply plain; omitting it keeps the default fenced body everywhere, so
 * the existing weight measurements are untouched.
 */
type SeedOptions = {
  plainAssistants?: readonly number[] | "all";
  /**
   * `rounds` x reasoning, tool call, answer per reply; truncation every `compactionEvery`th.
   * `sources` adds six URL source parts after every web_search call.
   */
  agent?: { rounds: number; compactionEvery?: number; sources?: boolean; rich?: boolean };
  /** Each default reply also carries a numbered equation, which KaTeX counts page-wide, and
   *  the same environments as code. */
  numbered?: boolean;
};

const AGENT_TOOLS = ["web_search", "terminal", "python"] as const;

function urlSources(tag: string) {
  return Array.from({ length: 6 }, (_, source) => ({
    type: "source" as const,
    sourceType: "url" as const,
    id: `source_${tag}_${source}`,
    url: `https://example${source}.org/${tag}`,
    title: `Source ${source} for ${tag}`,
  }));
}

function table(tag: string): string {
  return ["| step | loss | lr |", "|---|---|---|", ...[0, 1, 2, 3].map((row) => `| ${tag}.${row} | 0.${row}4 | 2e-4 |`)].join("\n");
}

function agentContent(index: number, rounds: number, sources = false, rich = false) {
  const parts: Exclude<ThreadMessageLike["content"], string>[number][] = [];
  for (let round = 0; round < rounds; round++) {
    const tag = `${index}_${round}`;
    const toolName = AGENT_TOOLS[(index + round) % AGENT_TOOLS.length];
    const args: Record<string, string> =
      toolName === "web_search"
        ? { query: `step ${tag} reference for the scheduler buffer` }
        : { code: `print("step ${tag}")` };
    parts.push({
      type: "reasoning" as const,
      text: `Round ${tag}. ${PROSE} ${CLOSING}`,
    });
    parts.push({
      type: "tool-call" as const,
      toolCallId: `call_${tag}`,
      toolName,
      args,
      argsText: JSON.stringify(args),
      result: `Result ${tag}. ${PROSE}\n${PROSE}\n${CLOSING}`,
    });
    if (sources && toolName === "web_search") parts.push(...urlSources(tag));
    parts.push({
      type: "text" as const,
      text: rich
        ? [assistantMarkdown(index * 10 + round), table(tag), `- first item ${tag}\n- second item ${tag}`].join("\n\n")
        : `Answer ${tag}. ${PROSE}\n\n- first item ${tag}\n- second item ${tag}`,
    });
  }
  return parts;
}

function isPlain(assistantOrdinal: number, options: SeedOptions | undefined): boolean {
  const plain = options?.plainAssistants;
  if (!plain) return false;
  if (plain === "all") return true;
  return plain.includes(assistantOrdinal);
}

function buildMessages(
  count: number,
  options?: SeedOptions,
): ThreadMessageLike[] {
  const agent = options?.agent;
  return Array.from({ length: count }, (_, index): ThreadMessageLike => {
    if (index % 2 === 0) {
      return {
        role: "user" as const,
        content: [
          {
            type: "text" as const,
            // A prompt shows math source as text, so these take no number.
            text:
              userMarkdown(index) +
              (options?.numbered ? "\n\n$$\\begin{equation}p=1\\end{equation}$$" : ""),
          },
        ],
      };
    }
    if (agent) {
      const ordinal = (index - 1) / 2;
      const every = agent.compactionEvery ?? 0;
      const compacted = every > 0 && ordinal > 0 && ordinal % every === 0;
      return {
        role: "assistant" as const,
        content: agentContent(index, agent.rounds, agent.sources, agent.rich),
        ...(compacted
          ? {
              metadata: {
                custom: {
                  contextTruncation: {
                    dropped_messages: Math.max(1, index - 4),
                    boundary_messages: Math.max(1, index - 4),
                    fits: true,
                  },
                },
              },
            }
          : {}),
      };
    }
    return {
      role: "assistant" as const,
      content: [
        {
          type: "text" as const,
          text: isPlain((index - 1) / 2, options)
            ? plainAssistantMarkdown(index)
            : assistantMarkdown(index) +
              (options?.numbered
                ? `\n\n$$\n\\begin{equation}E_{${index}} = mc^2\\end{equation}\n$$` +
                  "\n\n$$\n\\begin{align}f &= \\begin{cases}1\\\\0\\end{cases}\\\\ g &= 2\\end{align}\n$$" +
                  // Examples, not math: they render verbatim and take no number.
                  "\n\n```latex\n\\begin{equation}x\\end{equation}\n```\n\nInline `\\begin{align}a\\end{align}` too."
                : ""),
        },
      ],
    };
  });
}

// A run would need a backend. Seeding goes through `thread.import`, which does not use this.
const STREAM_CHUNKS = Number(
  new URLSearchParams(window.location.search).get("stream") ?? "0",
);
// `&sources=1`: the streamed reply follows a web_search call with six URL sources.
const STREAM_SOURCES =
  new URLSearchParams(window.location.search).get("sources") === "1";
// `&rounds=N`: N agent rounds (reasoning, a call, its result, text with math) stream before the reply.
const STREAM_ROUNDS = Number(
  new URLSearchParams(window.location.search).get("rounds") ?? "0",
);
const tick = () => new Promise((resolve) => setTimeout(resolve, 20));
const NEVER_RUNS: ChatModelAdapter = STREAM_CHUNKS > 0
  ? {
      async *run({ abortSignal }) {
        const rounds: ThreadAssistantMessagePart[] = [];
        for (let round = 0; round < STREAM_ROUNDS; round++) {
          const callArgs = { url: `https://example.com/${round}` };
          const call = {
            type: "tool-call" as const,
            toolCallId: `call_round_${round}`,
            toolName: "browser_snapshot",
            args: callArgs,
            argsText: JSON.stringify(callArgs),
          };
          for (const step of [
            () => rounds.push({ type: "reasoning", text: `Planning round ${round}.` }),
            () => rounds.push(call),
            () => (rounds[rounds.length - 1] = { ...call, result: `Snapshot ${round}. ${PROSE}` }),
            () => rounds.push({ type: "text", text: `Round ${round} gave $x_{${round}}^2$.` }),
          ]) {
            step();
            await tick();
            if (abortSignal.aborted) return;
            yield { content: [...rounds] };
          }
        }
        const args = { query: "live reference" };
        const prefix = STREAM_SOURCES
          ? [
              {
                type: "tool-call" as const,
                toolCallId: "call_live",
                toolName: "web_search",
                args,
                argsText: JSON.stringify(args),
                result: `Result live. ${PROSE}`,
              },
              ...urlSources("live"),
            ]
          : [];
        let text = "";
        for (let chunk = 0; chunk < STREAM_CHUNKS; chunk++) {
          await tick();
          if (abortSignal.aborted) return;
          text += `word${chunk} `;
          yield { content: [...rounds, ...prefix, { type: "text" as const, text }] };
        }
      },
    }
  : {
      run: () => {
        throw new Error("smoke-thread-weight does not run the model");
      },
    };

function ThreadWeightApi({
  setThreadMounted,
}: {
  setThreadMounted: (mounted: boolean) => void;
}): null {
  const aui = useAui();

  useEffect(() => {
    const api = {
      send(text: string): void {
        aui.thread().append({
          role: "user",
          content: [{ type: "text", text }],
        });
      },
      isRunning(): boolean {
        return aui.thread().getState().isRunning;
      },
      /** Replace the thread with `count` messages, oldest first. */
      seed(count: number, options?: SeedOptions): void {
        aui
          .thread()
          .import(
            ExportedMessageRepository.fromArray(buildMessages(count, options)),
          );
      },
      /** Toggle the Thread while the runtime lives, like a sidebar switch; isHovering outlives it. */
      setThreadMounted(mounted: boolean): void {
        setThreadMounted(mounted);
      },
      /** Reads the runtime flag so a leak test sees isHovering even when nothing is rendered. */
      hoverFlags(): { id: string; isHovering: boolean }[] {
        return aui
          .thread()
          .getState()
          .messages.map((message) => ({
            id: message.id,
            isHovering: Boolean(message.isHovering),
          }));
      },
      /** Cheap poll target; counts() is too heavy to poll at 500 messages. */
      messageCount(): number {
        return document.querySelectorAll("[data-role]").length;
      },
      /** Opens the last user prompt's editor; returns its message id. */
      editLastPrompt(): string | null {
        const messages = aui.thread().getState().messages;
        for (let index = messages.length - 1; index >= 0; index -= 1) {
          if (messages[index].role !== "user") continue;
          aui.thread().message({ index }).composer().beginEdit();
          return messages[index].id;
        }
        return null;
      },
      /** The conversation's length, where messageCount() is how much of it is mounted. */
      threadLength(): number {
        return aui.thread().getState().messages.length;
      },
      /** What the turn rail waits on before it renders: a full mount still under way. */
      pendingMounts(): boolean {
        return hasPendingProgressiveMounts();
      },
      counts(): {
        messages: number;
        assistantMessages: number;
        userMessages: number;
        domNodes: number;
        codeBlocks: number;
        katexNodes: number;
        actionBars: number;
        tooltipTriggers: number;
      } {
        return {
          messages: document.querySelectorAll("[data-role]").length,
          assistantMessages: document.querySelectorAll('[data-role="assistant"]')
            .length,
          userMessages: document.querySelectorAll('[data-role="user"]').length,
          domNodes: document.getElementsByTagName("*").length,
          codeBlocks: document.querySelectorAll("pre").length,
          katexNodes: document.querySelectorAll(".katex").length,
          actionBars: document.querySelectorAll(".aui-assistant-action-bar-root")
            .length,
          tooltipTriggers: document.querySelectorAll(
            '[data-slot="tooltip-trigger"]',
          ).length,
        };
      },
      viewportMetrics(): {
        scrollHeight: number;
        scrollTop: number;
        clientHeight: number;
      } {
        const element = api.viewport();
        if (!element) {
          return { scrollHeight: -1, scrollTop: -1, clientHeight: -1 };
        }
        return {
          scrollHeight: element.scrollHeight,
          scrollTop: element.scrollTop,
          clientHeight: element.clientHeight,
        };
      },
      viewport(): HTMLElement | null {
        return document.querySelector<HTMLElement>(".aui-thread-viewport");
      },
      /** Non-GET /api/ calls the stub above answered. */
      apiWrites(): { url: string; body: string | null }[] {
        return apiWrites;
      },
      composer(): HTMLTextAreaElement | null {
        return document.querySelector<HTMLTextAreaElement>(
          ".aui-composer-input",
        );
      },
      /** Runtime's composer text; reading the textarea would just echo what the caller wrote. */
      composerText(): string {
        return aui.composer().getState().text;
      },
      katexCount(): number {
        return document.querySelectorAll(".katex").length;
      },
      /** Shiki runs after the <pre> exists, so counting <pre> gates nothing. */
      highlightedTokenCount(): number {
        return document.querySelectorAll("pre code span").length;
      },
      /** An empty popover would satisfy "the menu opened", so count items. */
      openMenuItemCount(): number {
        return document.querySelectorAll(".aui-action-bar-more-item").length;
      },
      lastAssistantMessage(): HTMLElement | null {
        const messages = document.querySelectorAll<HTMLElement>(
          '[data-role="assistant"]',
        );
        return messages[messages.length - 1] ?? null;
      },
      /** TooltipIconButton puts the name in an sr-only span, not aria-label, so match on text. */
      actionButton(label: string): HTMLButtonElement | null {
        const last = api.lastAssistantMessage();
        if (!last) return null;
        const buttons = Array.from(last.querySelectorAll("button"));
        return (
          buttons.find(
            (button) => (button.textContent ?? "").trim() === label,
          ) ?? null
        );
      },
    };
    (window as unknown as { __threadWeight: typeof api }).__threadWeight = api;
  }, [aui, setThreadMounted]);

  return null;
}

// The checks on this page measure what a whole thread costs in the DOM (the state an open find bar
// or a print puts the app in), so every row stays mounted. `?window=1` leaves the thread as the
// app opens it: only the rows near the reader are mounted.
if (new URLSearchParams(window.location.search).get("window") !== "1") {
  holdProgressiveMounts();
}

// `?shell=1`: the ancestors the app puts around the thread (root layout + chat page), so CSS
// anchored on them (e.g. a `:has()` on the wallpaper workspace) runs here as it does in Studio.
const SHELL = new URLSearchParams(window.location.search).get("shell") === "1";

function AppShell({ children }: { children: ReactElement }): ReactElement {
  if (!SHELL) return children;
  return (
    <SidebarProvider
      data-wallpaper-workspace=""
      data-wallpaper-route="chat"
      className="relative !min-h-0 h-[100dvh] overflow-hidden"
    >
      <SidebarInset className="overflow-hidden">
        <div className="relative flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden">
          <div data-chat-content-root="" className="relative flex min-h-0 flex-1 flex-col">
            {children}
          </div>
        </div>
      </SidebarInset>
    </SidebarProvider>
  );
}

// `?remote=1`: the remote thread list + attachments adapter the app uses, for the same scopes.
const REMOTE = new URLSearchParams(window.location.search).get("remote") === "1";

const MEMORY_THREAD_LIST: unstable_RemoteThreadListAdapter = {
  list: async () => ({ threads: [] }),
  rename: async () => {},
  archive: async () => {},
  unarchive: async () => {},
  delete: async () => {},
  initialize: async (threadId) => ({ remoteId: threadId, externalId: undefined }),
  generateTitle: async () =>
    new ReadableStream({ start: (controller) => controller.close() }) as never,
  fetch: async (threadId) => ({
    status: "regular",
    remoteId: threadId,
    externalId: undefined,
    title: undefined,
  }),
};

const ATTACHMENTS = new SimpleImageAttachmentAdapter();

function useSmokeLocalRuntime() {
  return useLocalRuntime(NEVER_RUNS, { adapters: { attachments: ATTACHMENTS } });
}

function RemoteHarness(): ReactElement {
  const runtime = unstable_useRemoteThreadListRuntime({
    runtimeHook: useSmokeLocalRuntime,
    adapter: MEMORY_THREAD_LIST,
  });
  return <HarnessBody runtime={runtime} />;
}

function LocalHarness(): ReactElement {
  const runtime = useLocalRuntime(NEVER_RUNS);
  return <HarnessBody runtime={runtime} />;
}

function Harness(): ReactElement {
  return REMOTE ? <RemoteHarness /> : <LocalHarness />;
}

function HarnessBody({
  runtime,
}: {
  runtime: ReturnType<typeof useLocalRuntime>;
}): ReactElement {
  const [threadMounted, setThreadMounted] = useState(true);
  return (
    <TooltipProvider>
      <AssistantRuntimeProvider runtime={runtime}>
        <ThreadWeightApi setThreadMounted={setThreadMounted} />
        {/* Thread is flex-1 basis-0 min-h-0, so it needs a bounded flex parent to scroll. */}
        <AppShell>
          <div
            data-smoke="thread"
            style={{ display: "flex", flexDirection: "column", height: SHELL ? "100%" : "100vh" }}
          >
            {threadMounted ? <Thread hideWelcome={true} /> : null}
          </div>
        </AppShell>
      </AssistantRuntimeProvider>
    </TooltipProvider>
  );
}

// Memory router: without one, every action bar console.warns from useNavigate, scaling with N.
const rootRoute = createRootRoute({ component: Harness });
const router = createRouter({
  routeTree: rootRoute,
  history: createMemoryHistory({ initialEntries: ["/"] }),
});

const root = document.getElementById("root");
if (!root) {
  throw new Error("missing #root");
}
// As in main.tsx: the gate's modal lock check then times the attributes the app mirrors from the
// body lock, not a bare inline style the modal rules no longer read.
watchModalPointerLock(document);
createRoot(root).render(<RouterProvider router={router as unknown as never} />);