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
"use client";
import { openLink } from "@/lib/open-link";
import {
memo,
useState,
useRef,
useEffect,
useCallback,
useMemo,
type ComponentProps,
type FC,
} from "react";
import { useAuiState } from "@assistant-ui/react";
import { memoOnArray } from "@/components/assistant-ui/message-derived";
import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";
import { cn } from "@/lib/utils";
import { Badge, badgeVariants, type BadgeProps } from "./badge";
import {
HoverCard,
HoverCardTrigger,
HoverCardContent,
} from "@/components/ui/hover-card";
const extractDomain = (url: string): string => {
try {
return new URL(url).hostname.replace(/^www\./, "");
} catch {
return url;
}
};
const getDomainInitial = (url: string): string => {
const domain = extractDomain(url);
return domain.charAt(0).toUpperCase();
};
function SourceIcon({
url,
className,
size = 3,
allowRemoteIcons = true,
...props
}: ComponentProps<"span"> & { url: string; size?: number; allowRemoteIcons?: boolean }) {
const [hasError, setHasError] = useState(false);
const domain = extractDomain(url);
const SIZE_CLASSES: Record<number, string> = { 3: "size-3", 4: "size-4", 5: "size-5" };
const sizeClass = SIZE_CLASSES[size] ?? "size-3";
if (hasError || !allowRemoteIcons) {
return (
<span
data-slot="source-icon-fallback"
className={cn(
`flex ${sizeClass} shrink-0 items-center justify-center rounded-sm bg-muted font-medium text-ui-10`,
className,
)}
{...props}
>
{getDomainInitial(url)}
</span>
);
}
return (
<img
data-slot="source-icon"
src={`https://www.google.com/s2/favicons?domain=${domain}&sz=32`}
alt=""
className={cn(`${sizeClass} shrink-0 rounded-sm`, className)}
onError={() => setHasError(true)}
{...(props as ComponentProps<"img">)}
/>
);
}
function SourceTitle({ className, ...props }: ComponentProps<"span">) {
return (
<span
data-slot="source-title"
className={cn("max-w-37.5 truncate", className)}
{...props}
/>
);
}
export type SourceProps = Omit<BadgeProps, "asChild"> &
ComponentProps<"a"> & {
asChild?: boolean;
};
function Source({
className,
variant,
size,
asChild = false,
href,
onClick,
...props
}: SourceProps) {
return (
<Badge
asChild
variant={variant}
size={size}
className={cn(
"btn-fill rounded-full cursor-pointer border-transparent outline-none hover:text-chat-icon-fg-hover! focus-visible:border-ring",
className,
)}
>
<a
data-slot="source"
href={href}
rel="noopener noreferrer"
onClick={(e) => {
if (href && openLink(href)) {
e.preventDefault();
}
onClick?.(e);
}}
{...(props as ComponentProps<"a">)}
/>
</Badge>
);
}
export interface SourceData {
/** Two citations into the same source share a `url`, so React keys on `id`. */
id: string;
url: string;
title: string;
description?: string;
}
const SourceBadge: FC<{
source: SourceData;
allowRemoteIcons?: boolean;
showLinkPreviews: boolean;
}> = ({
source,
allowRemoteIcons = true,
showLinkPreviews,
}) => {
const domain = extractDomain(source.url);
const displayTitle = source.title || domain;
const badge = (
<span className="inline-block">
<Source href={source.url}>
<SourceIcon url={source.url} allowRemoteIcons={allowRemoteIcons} />
<SourceTitle>{displayTitle}</SourceTitle>
</Source>
</span>
);
if (!showLinkPreviews) return badge;
return (
<HoverCard openDelay={0} closeDelay={0}>
<HoverCardTrigger asChild>{badge}</HoverCardTrigger>
<HoverCardContent
side="top"
align="start"
className="!bg-(--tooltip-bg) !text-(--tooltip-fg) !w-72 !p-3 !rounded-2xl !shadow-(--tooltip-shadow) !ring-0 !duration-0"
style={{ animation: "none" }}
>
<div className="flex gap-2.5">
<SourceIcon
url={source.url}
size={4}
className="mt-0.5 shrink-0"
allowRemoteIcons={allowRemoteIcons}
/>
<div className="min-w-0 space-y-1">
<p className="text-sm font-semibold leading-tight truncate">
{source.title || domain}
</p>
<p className="text-xs text-(--tooltip-muted) truncate">{domain}</p>
{source.description && (
<p className="text-xs text-(--tooltip-muted) leading-relaxed line-clamp-3">
{source.description}
</p>
)}
</div>
</div>
</HoverCardContent>
</HoverCard>
);
};
const NO_SOURCES: readonly SourceData[] = [];
// A string selector stays equal while streaming rebuilds the content array.
const urlSourcesKey = memoOnArray((content: readonly unknown[]): string => {
const sources: SourceData[] = [];
for (const item of content) {
const part = item as {
type?: unknown;
sourceType?: unknown;
url?: unknown;
id?: unknown;
title?: string;
metadata?: { description?: string };
};
if (
part.type === "source" &&
"sourceType" in part &&
part.sourceType === "url" &&
"url" in part &&
part.url
) {
const url = part.url as string;
sources.push({
id: typeof part.id === "string" ? part.id : url,
url,
title: part.title || "",
description: part.metadata?.description,
});
}
}
return sources.length === 0 ? "" : JSON.stringify(sources);
});
const SourcesGroup: FC<{ sources?: SourceData[]; allowRemoteIcons?: boolean }> = ({
sources: suppliedSources,
allowRemoteIcons = true,
}) => {
const key = useAuiState(({ message }) =>
suppliedSources || !Array.isArray(message.content)
? ""
: urlSourcesKey(message.content),
);
const messageSources = useMemo<readonly SourceData[]>(
() => (key === "" ? NO_SOURCES : (JSON.parse(key) as SourceData[])),
[key],
);
return (
<SourcesGroupView
sources={suppliedSources ?? messageSources}
allowRemoteIcons={allowRemoteIcons}
/>
);
};
const SourcesGroupView = memo<{
sources: readonly SourceData[];
allowRemoteIcons: boolean;
}>(({ sources, allowRemoteIcons }) => {
const showLinkPreviews = useChatPreferencesStore((s) => s.showLinkPreviews);
const containerRef = useRef<HTMLDivElement>(null);
const [visibleCount, setVisibleCount] = useState<number | null>(null);
const [expanded, setExpanded] = useState(false);
const measure = useCallback(() => {
const container = containerRef.current;
if (!container || sources.length === 0) return;
const children = Array.from(container.children) as HTMLElement[];
if (children.length === 0) return;
const firstTop = children[0].offsetTop;
let rowCount = 1;
let prevTop = firstTop;
let cutoff = children.length;
for (let i = 1; i < children.length; i++) {
const childTop = children[i].offsetTop;
if (childTop > prevTop) {
rowCount++;
prevTop = childTop;
if (rowCount > 2) {
cutoff = i;
break;
}
}
}
setVisibleCount(rowCount > 2 ? cutoff : null);
}, [sources.length]);
useEffect(() => {
measure();
}, [measure]);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const observer = new ResizeObserver(measure);
observer.observe(container);
return () => observer.disconnect();
}, [measure]);
if (sources.length === 0) return null;
const shouldCollapse = visibleCount !== null && visibleCount < sources.length;
const displayedSources =
expanded || !shouldCollapse ? sources : sources.slice(0, visibleCount);
const hiddenCount = sources.length - (visibleCount ?? sources.length);
return (
<div className="relative mt-2 mb-3">
{/* Off-screen measurement; the clipped absolute wrapper keeps pills out of scrollHeight. */}
<div
aria-hidden
className="absolute pointer-events-none overflow-hidden h-0 w-full left-0 top-0"
>
<div
ref={containerRef}
className="flex w-full flex-wrap gap-1 invisible"
>
{sources.map((source) => (
<span key={source.id} className="inline-block">
<Source href={source.url}>
<SourceIcon url={source.url} allowRemoteIcons={allowRemoteIcons} />
<SourceTitle>{source.title || extractDomain(source.url)}</SourceTitle>
</Source>
</span>
))}
</div>
</div>
<div className="flex flex-wrap gap-1">
{displayedSources.map((source) => (
<SourceBadge
key={source.id}
source={source}
allowRemoteIcons={allowRemoteIcons}
showLinkPreviews={showLinkPreviews}
/>
))}
{shouldCollapse && !expanded && (
<button
type="button"
onClick={() => setExpanded(true)}
className={cn(
badgeVariants({ variant: "outline", size: "default" }),
"btn-fill rounded-full cursor-pointer border-transparent text-muted-foreground hover:text-chat-icon-fg-hover!",
)}
>
+{hiddenCount} more
</button>
)}
{shouldCollapse && expanded && (
<button
type="button"
onClick={() => setExpanded(false)}
className={cn(
badgeVariants({ variant: "outline", size: "default" }),
"btn-fill rounded-full cursor-pointer border-transparent text-muted-foreground hover:text-chat-icon-fg-hover!",
)}
>
Show less
</button>
)}
</div>
</div>
);
});
SourcesGroupView.displayName = "SourcesGroupView";
const SourcesNoop: FC<Record<string, unknown>> = () => null;
const Sources = memo(SourcesNoop) as unknown as FC<Record<string, unknown>> & {
Root: typeof Source;
Icon: typeof SourceIcon;
Title: typeof SourceTitle;
Group: typeof SourcesGroup;
};
Sources.displayName = "Sources";
Sources.Root = Source;
Sources.Icon = SourceIcon;
Sources.Title = SourceTitle;
Sources.Group = SourcesGroup;
export {
Sources,
SourcesGroup,
Source,
SourceIcon,
SourceTitle,
badgeVariants as sourceVariants,
};