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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
// 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 { partsHaveNonEmptyText } from "@/components/assistant-ui/message-derived";
import {
type ToolCallMessagePartComponent,
useAuiState,
} from "@assistant-ui/react";
import {
isSearchImagesToolResult,
useToolAwaitingApproval,
} from "@/features/chat";
import { escapeBidiControls } from "@/lib/escape-bidi-controls";
import { InternetGlyph } from "@/lib/internet-icon";
import { openLink } from "@/lib/open-link";
import { stringifyToolResult } from "@/lib/strip-ansi";
import { memo } from "react";
import { ScrollPane } from "./scroll-pane";
import { SearchImageThumb } from "./search-image";
import { Source, SourceIcon, SourceTitle } from "./sources";
import {
isToolCallRunning,
toolArgText,
webSearchToolName,
} from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
import { useToolActivityOpen } from "./use-tool-activity-open";
interface ParsedSource {
title: string;
url: string;
snippet: string;
}
const RE_BLOCK_SEP = /\n---\n/;
const RE_TITLE = /Title:\s*(.+)/;
const RE_URL = /URL:\s*(.+)/;
const RE_SNIPPET = /Snippet:\s*(.+)/s;
// Mirrors _normalize_url_scheme so the card names a host only when the backend fetches it.
const RE_BARE_HOST =
/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+(?::(\d{0,5}))?(?:[/?#]|$)/;
function isBareHostFetchedAsHttps(value: string): boolean {
const match = RE_BARE_HOST.exec(value);
if (!match) return false;
const port = match[1];
if (!port) return true;
return Number(port) >= 1 && Number(port) <= 65535;
}
/** Provider-controlled output: `javascript:` / `data:` must not reach an <a href>. */
function isSafeHttpUrl(raw: string): boolean {
const value = raw.trim();
if (!value || /[\r\n]/.test(value)) return false;
try {
const parsed = new URL(value);
return parsed.protocol === "http:" || parsed.protocol === "https:";
} catch {
return false;
}
}
/** Parse the backend's "Title: ...\nURL: ...\nSnippet: ...\n---" format into structured sources. */
function parseSearchResults(raw: string): ParsedSource[] {
if (!raw) {
return [];
}
const blocks = raw.split(RE_BLOCK_SEP).filter(Boolean);
const sources: ParsedSource[] = [];
for (const block of blocks) {
const titleMatch = block.match(RE_TITLE);
const urlMatch = block.match(RE_URL);
const snippetMatch = block.match(RE_SNIPPET);
if (!titleMatch || !urlMatch) continue;
const url = urlMatch[1].trim();
if (!isSafeHttpUrl(url)) continue;
sources.push({
title: titleMatch[1].trim(),
url,
snippet: snippetMatch?.[1]?.trim() ?? "",
});
}
return sources;
}
const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({
args,
result,
status,
toolCallId,
}) => {
// Coerced: local models emit numbers or objects here, and .trim() would crash the card.
const query = toolArgText((args as { query?: unknown })?.query);
const url = toolArgText((args as { url?: unknown })?.url).trim();
// gpt-5.x open_page/find_in_page; older streams omit them, so match a url+pattern by shape.
const pattern = toolArgText((args as { pattern?: unknown })?.pattern);
const actionType = toolArgText(
(args as { action_type?: unknown })?.action_type,
);
const isFindInPage =
actionType === "find_in_page" || (!!url && !!pattern.trim());
const isUrlFetch = !!url && !isFindInPage;
const rawImageQueries = (args as { image_queries?: unknown })?.image_queries;
const imageQueries = Array.isArray(rawImageQueries)
? rawImageQueries
.map((q) => toolArgText(q).trim())
.filter(Boolean)
.slice(0, 5)
: [];
const imageLabel = imageQueries.join(", ");
const isImageOnly =
!isUrlFetch && !isFindInPage && !query.trim() && imageQueries.length > 0;
// The header speaks for the result: a call that found nothing must not claim it did.
const foundImages = isSearchImagesToolResult(result);
// new URL() throws on the bare hosts the backend fetches, so mirror that grammar.
const bareUrl = url.startsWith("//") ? url.slice(2) : url;
const candidateUrl = isBareHostFetchedAsHttps(bareUrl)
? `https://${bareUrl}`
: url;
const safeUrl = isSafeHttpUrl(candidateUrl) ? candidateUrl : "";
const displayDomain = (() => {
if (!safeUrl) return "";
try {
return new URL(safeUrl).hostname.replace(/^www\./, "");
} catch {
return "";
}
})();
const isRunning = isToolCallRunning(status);
const withImages = isSearchImagesToolResult(result);
const resultText =
result == null
? ""
: withImages
? stringifyToolResult(result.text)
: stringifyToolResult(result);
const images = withImages ? result.webImages : [];
const sources = resultText ? parseSearchResults(resultText) : [];
const hasText = useAuiState(({ message }) =>
partsHaveNonEmptyText(message.content),
);
// What is being approved lives inside the content, while Allow/Deny render outside it.
const awaitingApproval = useToolAwaitingApproval(toolCallId);
const [open, setOpen] = useToolActivityOpen(isRunning, hasText);
const toolName = webSearchToolName({
isRunning,
isFindInPage,
isUrlFetch,
isImageOnly,
foundImages,
displayDomain,
pattern,
query,
imageLabel,
});
return (
<ToolFallbackRoot
open={open}
onOpenChange={setOpen}
awaitingApproval={awaitingApproval}
>
<ToolFallbackTrigger
toolName={toolName}
status={status}
icon={InternetGlyph}
/>
<ToolFallbackContent>
{/* The trigger shows only the host; Allow/Deny needs the full url. Inert text: untrusted. */}
{isRunning && url ? (
<div
data-slot="tool-web-fetch-url"
className="flex min-w-0 items-start gap-2 text-xs"
>
<span className="shrink-0 font-medium text-muted-foreground">
URL:
</span>
{/* Capped so a huge url cannot push Allow/Deny off screen. */}
<ScrollPane
className="min-w-0 rounded-lg bg-muted/50 px-2 py-1"
scrollerClassName="max-h-24 overflow-auto whitespace-pre-wrap break-all text-foreground/85"
>
<code dir="ltr" className="break-all text-foreground/85">
{escapeBidiControls(url)}
</code>
</ScrollPane>
</div>
) : null}
{isRunning ? (
<div className="flex items-center text-sm text-muted-foreground">
<span>
{isFindInPage ? (
pattern ? (
<>
Finding “{pattern}” in {displayDomain || "page"}
…
</>
) : (
<>Searching {displayDomain || "page"}…</>
)
) : isUrlFetch ? (
<>Reading {displayDomain || "page"}…</>
) : isImageOnly ? (
<>Finding images for “{imageLabel}”…</>
) : query ? (
<>Searching for “{query}”…</>
) : (
<>Searching…</>
)}
</span>
</div>
) : (
<div className="flex flex-col gap-2">
{/* Above the body: the citation backfill can replace this card's result with the run's sources. */}
{safeUrl ? (
<a
href={safeUrl}
target="_blank"
rel="noopener noreferrer"
// A bare target="_blank" does nothing in the Desktop webview; hand the url to the opener.
onClick={(e) => {
if (openLink(safeUrl)) {
e.preventDefault();
}
}}
className="break-all text-xs text-primary underline-offset-4 hover:underline"
>
{url}
</a>
) : null}
{sources.length === 0 && images.length > 0 ? (
<div className="flex flex-col gap-2">
<div
className="flex flex-wrap gap-1.5"
data-testid="web-search-images"
>
{images.map((entry) => (
<SearchImageThumb
key={entry.id}
entry={entry}
size="strip"
/>
))}
</div>
{resultText && (
<ScrollPane
className="rounded-lg bg-muted/50 p-2"
scrollerClassName="max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs"
>
{resultText}
</ScrollPane>
)}
</div>
) : sources.length > 0 ? (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap gap-1.5">
{sources.map((source, i) => (
<Source
key={`${source.url}-${i}`}
href={source.url}
variant="outline"
size="sm"
className="inline-flex items-center gap-1.5"
>
<SourceIcon url={source.url} size={3} />
<SourceTitle>{source.title}</SourceTitle>
</Source>
))}
</div>
{images.length > 0 && (
<div
className="flex flex-wrap gap-1.5"
data-testid="web-search-images"
>
{images.map((entry) => (
<SearchImageThumb
key={entry.id}
entry={entry}
size="strip"
/>
))}
</div>
)}
</div>
) : resultText ? (
<ScrollPane
className="rounded-lg bg-muted/50 p-2"
scrollerClassName="max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs"
>
{resultText}
</ScrollPane>
) : null}
</div>
)}
</ToolFallbackContent>
</ToolFallbackRoot>
);
};
export const WebSearchToolUI = memo(
WebSearchToolUIImpl,
) as unknown as ToolCallMessagePartComponent;
WebSearchToolUI.displayName = "WebSearchToolUI";