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.

Studio: chat attachment cards, chips and the Library viewer (#12017)

Michael Han0db1cc52854a
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index f0acb0f5716..e2f2b9c2db1 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -3923,6 +3923,8 @@ class PersonalizationCustomization(BaseModel):
uiFontSize: Optional[int] = Field(None, ge = 12, le = 20)
codeFontSize: Optional[int] = Field(None, ge = 10, le = 20)
chatWidth: Literal["standard", "wide", "full"] = "standard"
+ composerAttachments: Literal["cards", "compact"] = "cards"
+ sentAttachments: Literal["auto", "list", "chips"] = "auto"
contrast: int = Field(50, ge = 0, le = 100)
pointerCursors: bool = False
reduceMotion: Literal["system", "on", "off"] = "system"
@@ -4033,6 +4035,8 @@ class PersonalizationResponse(PersonalizationPayload):
# overrides instead of treating a server-filled default as an explicit value.
customizationSaved: bool = False
chatWidthSaved: bool = False
+ composerAttachmentsSaved: bool = False
+ sentAttachmentsSaved: bool = False
paletteSaved: bool = False
greetingSlothSaved: bool = False
@@ -4049,6 +4053,12 @@ def get_personalization_settings(
profile = stored.get("profile") if isinstance(stored, dict) else None
response.customizationSaved = isinstance(appearance, dict) and "customization" in appearance
response.chatWidthSaved = isinstance(customization, dict) and "chatWidth" in customization
+ response.composerAttachmentsSaved = (
+ isinstance(customization, dict) and "composerAttachments" in customization
+ )
+ response.sentAttachmentsSaved = (
+ isinstance(customization, dict) and "sentAttachments" in customization
+ )
response.paletteSaved = isinstance(appearance, dict) and "palette" in appearance
response.greetingSlothSaved = isinstance(profile, dict) and "showGreetingSloth" in profile
return response
diff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.py
index 301e8618d59..844a2bd83af 100644
--- a/studio/backend/tests/test_personalization_settings.py
+++ b/studio/backend/tests/test_personalization_settings.py
@@ -90,6 +90,8 @@ def test_customization_defaults():
assert c.chatFont is None
assert c.uiFontSize is None
assert c.chatWidth == "standard"
+ assert c.composerAttachments == "cards"
+ assert c.sentAttachments == "auto"
assert [(i.id, i.visible) for i in c.sidebarMenu] == [
("api", True),
("darkMode", True),
@@ -115,6 +117,14 @@ def test_customization_invalid_values_rejected():
PersonalizationPayload.model_validate({"appearance": {"customization": {"uiFontSize": 99}}})
with pytest.raises(ValidationError):
PersonalizationPayload.model_validate({"appearance": {"customization": {"contrast": 500}}})
+ with pytest.raises(ValidationError):
+ PersonalizationPayload.model_validate(
+ {"appearance": {"customization": {"composerAttachments": "huge"}}}
+ )
+ with pytest.raises(ValidationError):
+ PersonalizationPayload.model_validate(
+ {"appearance": {"customization": {"sentAttachments": "grid"}}}
+ )
with pytest.raises(ValidationError):
PersonalizationPayload.model_validate(
{"appearance": {"customization": {"reduceMotion": "sometimes"}}}
@@ -500,6 +510,8 @@ def test_personalization_route_roundtrip_real_shape(monkeypatch):
"headingFont": "Avenir Next",
"chatFont": "Georgia",
"chatWidth": "full",
+ "composerAttachments": "compact",
+ "sentAttachments": "chips",
"codeFont": None,
"importedFonts": [
{"name": "SF Pro Text", "dataUrl": "data:font/woff2;base64,AAAA"}
@@ -605,6 +617,41 @@ def test_personalization_legacy_chat_width_presence(monkeypatch):
assert body["appearance"]["customization"]["uiFont"] == "Arial"
+def test_personalization_legacy_attachment_display_presence(monkeypatch):
+ store = {
+ pers.PERSONALIZATION_SETTING_KEY: {
+ "appearance": {"customization": {"chatWidth": "wide"}},
+ }
+ }
+ client = _shared_setup_1(monkeypatch, store)
+ body = client.get("/api/settings/personalization").json()
+ assert body["customizationSaved"] is True
+ assert body["composerAttachmentsSaved"] is False
+ assert body["sentAttachmentsSaved"] is False
+ assert body["appearance"]["customization"]["composerAttachments"] == "cards"
+ assert body["appearance"]["customization"]["sentAttachments"] == "auto"
+
+ put = client.put(
+ "/api/settings/personalization",
+ json = {"appearance": {"customization": {"composerAttachments": "compact"}}},
+ )
+ assert put.status_code == 200
+ body = client.get("/api/settings/personalization").json()
+ assert body["composerAttachmentsSaved"] is True
+ assert body["sentAttachmentsSaved"] is False
+ assert body["appearance"]["customization"]["composerAttachments"] == "compact"
+
+ put = client.put(
+ "/api/settings/personalization",
+ json = {"appearance": {"customization": {"sentAttachments": "chips"}}},
+ )
+ assert put.status_code == 200
+ body = client.get("/api/settings/personalization").json()
+ assert body["sentAttachmentsSaved"] is True
+ assert body["appearance"]["customization"]["sentAttachments"] == "chips"
+ assert body["appearance"]["customization"]["composerAttachments"] == "compact"
+
+
@pytest.mark.parametrize("width", ["standard", "wide", "full"])
def test_personalization_saved_chat_width_survives_stale_write(monkeypatch, width):
store = {
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 1d171ff6c69..47cf0f74fe3 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -32,16 +32,11 @@ const DIST = resolve(HERE, "..", "dist");
* machine.
*/
export const BUDGET = {
- // Measured, one machine and one build per side, so the pair is comparable to itself rather
- // than to a runner's: 5,599.7 KB raw / 1,663.4 KB transfer at 0065fade6 once its two
- // ineffective import() calls were made static, leaving 210.8 KB and 65.1 KB spare, the margin
- // the previous raise chose. Both halves are re-measured TOGETHER, or each drags main red on
- // its own. Since that raise the eager set gained one 303-byte chunk (#11607's
- // thread-message-slot split) and otherwise grew inside chunks already eager: #11607's fork
- // boundary and #11648's UI scale, so what ran out is headroom, not laziness.
- // The resource monitor remains eager so its frame can coordinate with overlays.
- transferBytes: 1_770_000,
- rawBytes: 5_950_000,
+ // Re-measured together on one machine and build: 5,813.8 KB raw / 1,730.2 KB transfer at d7795365c,
+ // plus the margin the previous raise chose (210.8 KB raw, 65.1 KB transfer). The growth since is
+ // chat attachment cards, chips and their layout (#12017), which the first chat screen renders.
+ transferBytes: 1_840_000,
+ rawBytes: 6_170_000,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx b/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx
index d57dc067b0c..fed4c57d9f4 100644
--- a/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx
+++ b/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx
@@ -3,10 +3,14 @@
"use client";
+import {
+ ATTACHMENT_PAGE_SCALES,
+ attachmentViewerMeta,
+} from "@/components/assistant-ui/attachment-viewer-meta";
import type { AttachmentSource } from "@/components/assistant-ui/use-attachment-source";
import { DocumentView, documentKind, isMarkdown } from "@/components/file-viewer";
import { MarkdownPreview } from "@/components/markdown/markdown-preview";
-import { MediaViewer, ScaleMenu } from "@/components/media-viewer";
+import { type MediaViewerActions, MediaViewer, ScaleMenu } from "@/components/media-viewer";
import { Spinner } from "@/components/ui/spinner";
import {
attachmentBodyText,
@@ -14,14 +18,110 @@ import {
readAttachmentText,
truncateAttachmentPreviewText,
} from "@/features/chat";
-import { formatBytes } from "@/features/hub";
+import { startLibraryChat } from "@/features/library";
import { useT } from "@/i18n";
+import { MessageCircleIcon } from "@/lib/hugeicons-derived";
import { downloadFile } from "@/lib/native-files";
import { useAuiState } from "@assistant-ui/react";
+import { useNavigate } from "@tanstack/react-router";
import { Slot } from "radix-ui";
-import { type FC, type PropsWithChildren, useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import {
+ type FC,
+ type PropsWithChildren,
+ type ReactNode,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
-const SCALES = [0.5, 0.75, 1, 1.25, 1.5, 2];
+/** Opens an attachment in the Library's viewer; `load` is read on click, so nothing is copied until asked. */
+export const AttachmentViewer: FC<{
+ trigger: ReactNode;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ source: Pick<AttachmentSource, "name" | "contentType">;
+ meta: string;
+ media: boolean;
+ noun: "image" | "video" | "clip" | "file";
+ redactFromReload: boolean;
+ load?: () => Promise<Blob>;
+ saveAs?: { name: string; contentType: string };
+ flush?: boolean;
+ extra?: ReactNode;
+ children: ReactNode;
+}> = ({
+ trigger,
+ open,
+ onOpenChange,
+ source,
+ meta,
+ media,
+ noun,
+ redactFromReload,
+ load,
+ saveAs,
+ flush = true,
+ extra,
+ children,
+}) => {
+ const t = useT();
+ const navigate = useNavigate();
+ // Mounted on first open: every mounted viewer's project menu refetches the project list.
+ const [mounted, setMounted] = useState(open);
+ if (open && !mounted) setMounted(true);
+ const name = saveAs?.name ?? (source.name || "attachment");
+ const contentType = saveAs?.contentType ?? source.contentType;
+ const actions: MediaViewerActions = {
+ primary:
+ load && !redactFromReload
+ ? {
+ label: t("library.menu.chatAboutThis"),
+ icon: MessageCircleIcon,
+ onClick: () =>
+ void load()
+ .then((blob) => {
+ const file = new File([blob], name, { type: contentType || blob.type });
+ onOpenChange(false);
+ startLibraryChat(navigate, { files: [file] });
+ })
+ .catch(() => toast.error(`Could not read ${name}`)),
+ }
+ : undefined,
+ onDownload: load
+ ? () =>
+ void load()
+ .then((blob) => downloadFile(blob, name, contentType || undefined))
+ .catch(() => toast.error(t("library.toast.downloadFailed", { name })))
+ : undefined,
+ };
+ return (
+ <>
+ <Slot.Root
+ onClick={() => onOpenChange(true)}
+ className="aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50"
+ >
+ {trigger}
+ </Slot.Root>
+ {mounted && (
+ <MediaViewer
+ open={open}
+ onOpenChange={onOpenChange}
+ title={source.name}
+ meta={meta}
+ media={media}
+ noun={noun}
+ flush={flush}
+ redactFromReload={redactFromReload}
+ extra={extra}
+ actions={actions}
+ >
+ {open && children}
+ </MediaViewer>
+ )}
+ </>
+ );
+};
type Loaded = { blob?: Blob; text?: string; plain?: string; truncated?: boolean; error?: boolean };
@@ -104,56 +204,35 @@ const DocumentDialog: FC<
}, [open, loaded, markdown, textFallback, source.name, source.contentType]);
const blob = loaded?.blob;
- const meta = [
- source.name.split(".").pop()?.toUpperCase(),
- blob ? formatBytes(blob.size) : null,
- loaded?.truncated ? "preview truncated" : null,
- ]
- .filter(Boolean)
- .join(" · ");
-
return (
- <>
- <Slot.Root
- onClick={() => setOpen(true)}
- className="aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50"
- >
- {children}
- </Slot.Root>
- <MediaViewer
- open={open}
- onOpenChange={(next) => {
- setOpen(next);
- if (!next) setLoaded(null);
- }}
- title={source.name}
- meta={meta}
- media={false}
- noun="file"
- flush={true}
- redactFromReload={redactFromReload}
- extra={
- <ScaleMenu value={scale} scales={SCALES} onChange={(value) => setScale(Number(value))} />
- }
- actions={{
- onDownload: blob
- ? () =>
- void (loaded?.plain !== undefined
- ? downloadFile(blob, `${source.name.replace(/\.[^.]+$/, "")}.txt`, "text/plain")
- : downloadFile(blob, source.name, source.contentType || undefined))
- : undefined,
- }}
- >
- {open && (
- <DocumentBody
- name={source.name}
- contentType={source.contentType}
- loaded={loaded ?? {}}
- scale={scale}
- />
- )}
- </MediaViewer>
- </>
+ <AttachmentViewer
+ trigger={children}
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setLoaded(null);
+ }}
+ source={source}
+ meta={attachmentViewerMeta(source, blob?.size, loaded?.truncated && "preview truncated")}
+ media={false}
+ noun="file"
+ redactFromReload={redactFromReload}
+ load={blob ? () => Promise.resolve(blob) : undefined}
+ saveAs={
+ loaded?.plain !== undefined
+ ? { name: `${source.name.replace(/\.[^.]+$/, "")}.txt`, contentType: "text/plain" }
+ : undefined
+ }
+ extra={
+ <ScaleMenu
+ value={scale}
+ scales={ATTACHMENT_PAGE_SCALES}
+ onChange={(value) => setScale(Number(value))}
+ />
+ }
+ >
+ <DocumentBody name={source.name} contentType={source.contentType} loaded={loaded ?? {}} scale={scale} />
+ </AttachmentViewer>
);
};
diff --git a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx b/studio/frontend/src/components/assistant-ui/attachment-preview.tsx
index fdcf6cd4123..d8bb6747f7d 100644
--- a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx
+++ b/studio/frontend/src/components/assistant-ui/attachment-preview.tsx
@@ -3,113 +3,108 @@
"use client";
-import { AttachmentDocumentDialog } from "@/components/assistant-ui/attachment-document-dialog";
+
+import {
+ AttachmentDocumentDialog,
+ AttachmentViewer,
+} from "@/components/assistant-ui/attachment-document-dialog";
+import {
+ ATTACHMENT_PAGE_SCALES,
+ attachmentViewerMeta,
+} from "@/components/assistant-ui/attachment-viewer-meta";
import { AudioPlayer } from "@/components/assistant-ui/audio-player";
+import { CodeToggleIcon } from "@/components/assistant-ui/code-toggle-icon";
+import type { AttachmentVideoPart } from "@/components/assistant-ui/attachment-selection";
import {
type AttachmentSource,
useAttachmentSource,
} from "@/components/assistant-ui/use-attachment-source";
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
+import { CodeSourceView } from "@/components/code-source-view";
+import { ScaleMenu } from "@/components/media-viewer";
import { Spinner } from "@/components/ui/spinner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
type AttachmentText,
+ ArtifactHtmlFrame,
attachmentAudioSrc,
+ attachmentBodyText,
attachmentTextLanguage,
countAttachmentTextLines,
parseAttachmentText,
readAttachmentText,
truncateAttachmentPreviewText,
} from "@/features/chat";
-import { formatBytes } from "@/features/hub";
-import { MAX_HIGHLIGHT_CHARS, codeFence } from "@/lib/markdown-plugins";
+import { useT } from "@/i18n";
+import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";
import { cn } from "@/lib/utils";
-import { code as codePlugin } from "@streamdown/code";
+import { PlayIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
import {
type FC,
type PropsWithChildren,
+ type ReactNode,
useEffect,
useMemo,
useState,
} from "react";
-import { Streamdown } from "streamdown";
type TextPreviewState =
| { status: "loading" }
| { status: "error" }
| ({ status: "ready" } & AttachmentText);
-const SHIKI_THEME = ["github-light", "github-dark"] as [
- "github-light",
- "github-dark",
-];
+const WEB_PAGE_NAME = /\.(html?|xhtml)$/i;
-const AttachmentImage: FC<{ src: string }> = ({ src }) => {
- const [isLoaded, setIsLoaded] = useState(false);
- return (
- <img
- src={src}
- alt="Preview"
- className={cn(
- "block h-auto max-h-[90dvh] w-auto max-w-[92vw] object-contain",
- isLoaded
- ? "aui-attachment-preview-image-loaded"
- : "aui-attachment-preview-image-loading invisible",
- )}
- onLoad={() => setIsLoaded(true)}
- />
- );
-};
+const fetchBlob = (src: string): Promise<Blob> => fetch(src).then((response) => response.blob());
-const AttachmentPreviewTrigger: FC<PropsWithChildren> = ({ children }) => {
- return (
- <DialogTrigger
- className="aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50"
- asChild={true}
+const Zoomed: FC<{ scale: number; children: ReactNode }> = ({ scale, children }) => (
+ <div className="size-full overflow-hidden">
+ <div
+ className="origin-top-left"
+ style={{
+ width: `${100 / scale}%`,
+ height: `${100 / scale}%`,
+ transform: `scale(${scale})`,
+ }}
>
{children}
- </DialogTrigger>
- );
-};
+ </div>
+ </div>
+);
const AttachmentImageDialog: FC<
- PropsWithChildren<{ src: string; redactFromReload?: boolean }>
-> = ({ children, src, redactFromReload = false }) => {
+ PropsWithChildren<{ source: AttachmentSource; src: string; redactFromReload?: boolean }>
+> = ({ children, source, src, redactFromReload = false }) => {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const [failed, setFailed] = useState(false);
return (
- <Dialog>
- <AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>
- {/* Chrome-free lightbox: the image floats on the dimmed backdrop with
- no dialog panel, and the close button sits in the screen corner. */}
- <DialogContent
- data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}
- overlayClassName="bg-black/70"
- className="aui-attachment-preview-dialog-content top-0 left-0 grid h-dvh w-screen max-h-none max-w-none translate-x-0 translate-y-0 place-items-center overflow-hidden rounded-none border-0 bg-transparent p-0 shadow-none ring-0 sm:max-w-none [&>button]:fixed [&>button]:top-4 [&>button]:right-4 [&>button]:z-20 [&>button]:size-9 [&>button]:rounded-full [&>button]:bg-transparent [&>button]:text-white [&>button]:opacity-100 [&>button]:ring-0! [&>button]:hover:bg-white/25 [&>button]:hover:text-white [&_svg]:text-white"
- >
- <DialogTitle className="aui-sr-only sr-only">
- Image Attachment Preview
- </DialogTitle>
- {/* Clicking the backdrop (anywhere off the image) closes the preview. */}
- <DialogClose asChild={true}>
- <div aria-hidden="true" className="absolute inset-0" />
- </DialogClose>
- <div className="aui-attachment-preview pointer-events-none relative z-10 flex items-center justify-center">
- <span className="pointer-events-auto">
- <AttachmentImage src={src} />
- </span>
- </div>
- </DialogContent>
- </Dialog>
+ <AttachmentViewer
+ trigger={children}
+ open={open}
+ onOpenChange={setOpen}
+ source={source}
+ meta={attachmentViewerMeta(source, source.file?.size)}
+ media={!failed}
+ noun="image"
+ redactFromReload={redactFromReload}
+ load={() => (source.file ? Promise.resolve(source.file) : fetchBlob(src))}
+ >
+ {failed ? (
+ <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>
+ ) : (
+ <img
+ src={src}
+ alt={source.name || "Image attachment"}
+ onError={() => setFailed(true)}
+ className="size-full object-contain"
+ />
+ )}
+ </AttachmentViewer>
);
};
-// Extraction only starts once the dialog has been opened: parsing every PDF or
+// Extraction only starts once the viewer has been opened: parsing every PDF or
// spreadsheet in a thread up front would stall the composer.
const useAttachmentTextPreview = (
enabled: boolean,
@@ -155,51 +150,39 @@ const useAttachmentTextPreview = (
return file ? fileState : sentState;
};
-/**
- * The preview body: a source file keeps its syntax colours, prose stays plain.
- *
- * Highlighting is skipped past MAX_HIGHLIGHT_CHARS, the same ceiling the
- * transcript uses, so a long file still opens without tokenizing on the way in.
- */
-const AttachmentTextBody: FC<{ text: string; language: string | null }> = ({
- text,
- language,
-}) => {
- const markdown = useMemo(() => {
- if (!language || text.length > MAX_HIGHLIGHT_CHARS) {
- return null;
- }
- const fence = codeFence(text);
- return `${fence}${language}\n${text}\n${fence}`;
- }, [text, language]);
-
- if (!markdown) {
- return (
- <pre className="whitespace-pre-wrap break-words px-4 py-3 font-mono text-xs leading-relaxed">
- {text}
- </pre>
- );
- }
-
- // streamdown draws its own card and language header, flattened here so the dialog panel is the only one
- return (
- <div className="[&_[data-streamdown=code-block-header]]:!hidden [&_[data-streamdown=code-block]]:!my-0 [&_[data-streamdown=code-block]]:!gap-0 [&_[data-streamdown=code-block]]:!rounded-none [&_[data-streamdown=code-block]]:!border-0 [&_[data-streamdown=code-block]]:!bg-transparent [&_[data-streamdown=code-block]]:!p-0 [&_[data-streamdown=code-block-body]]:!rounded-none [&_[data-streamdown=code-block-body]]:!border-0 [&_[data-streamdown=code-block-body]]:!bg-transparent [&_[data-streamdown=code-block-body]]:!p-0 [&_pre]:!m-0 [&_pre]:!bg-transparent [&_pre]:!px-4 [&_pre]:!py-3 [&_pre]:!text-xs [&_pre]:!leading-relaxed">
- <Streamdown
- mode="static"
- plugins={{ code: codePlugin }}
- controls={{ code: false }}
- shikiTheme={SHIKI_THEME}
+const ViewButton: FC<{
+ label: string;
+ active: boolean;
+ onClick: () => void;
+ children: ReactNode;
+}> = ({ label, active, onClick, children }) => (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={label}
+ aria-pressed={active}
+ onClick={onClick}
+ className={cn(
+ "flex size-9 shrink-0 items-center justify-center rounded-full outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring",
+ active && "bg-muted",
+ )}
>
- {markdown}
- </Streamdown>
- </div>
- );
-};
+ {children}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+);
const AttachmentTextDialog: FC<
PropsWithChildren<{ source: AttachmentSource; redactFromReload?: boolean }>
> = ({ children, source, redactFromReload = false }) => {
+ const t = useT();
+ const [open, setOpen] = useState(false);
const [opened, setOpened] = useState(false);
+ const [scale, setScale] = useState(1);
+ const [showCode, setShowCode] = useState(false);
const state = useAttachmentTextPreview(
opened,
source.file,
@@ -207,90 +190,131 @@ const AttachmentTextDialog: FC<
source.contentType,
source.text,
);
+ const ready = state.status === "ready" ? state : null;
const preview = useMemo(
- () =>
- state.status === "ready"
- ? truncateAttachmentPreviewText(state.text)
- : undefined,
- [state],
- );
- const language = useMemo(
- () =>
- state.status === "ready"
- ? attachmentTextLanguage(source.name, state.label)
- : null,
- [state, source.name],
+ () => (ready ? truncateAttachmentPreviewText(ready.text) : undefined),
+ [ready],
);
+ const truncated = Boolean(preview?.truncated || ready?.truncated);
+ // Highlighting stops at the transcript's ceiling so a long file opens without tokenizing.
+ const language = useMemo(() => {
+ if (!ready || !preview || preview.text.length > MAX_HIGHLIGHT_CHARS) return null;
+ return attachmentTextLanguage(source.name, ready.label);
+ }, [ready, preview, source.name]);
+ // A page's own HTML renders, as the Library shows it; text pulled out of a document never does.
+ const webPage = Boolean(ready && !ready.label && !truncated && WEB_PAGE_NAME.test(source.name));
const meta = useMemo(() => {
- if (state.status === "error") {
- return "This file could not be read";
- }
- if (state.status !== "ready" || !preview) {
- return "Reading file";
- }
- // Counting the capped text, not state.text: a sent attachment keeps its
+ if (state.status === "error") return "This file could not be read";
+ if (!ready || !preview) return "Reading file";
+ // Counting the capped text, not ready.text: a sent attachment keeps its
// full payload in memory and splitting all of it would stall the webview.
const lines = countAttachmentTextLines(preview.text);
- return [
- source.file ? formatBytes(source.file.size) : null,
+ return attachmentViewerMeta(
+ source,
+ source.file?.size,
`${lines} ${lines === 1 ? "line" : "lines"}`,
- state.label ? `text extracted from ${state.label}` : null,
- preview.truncated || state.truncated ? "preview truncated" : null,
- ]
- .filter(Boolean)
- .join(" · ");
- }, [state, preview, source.file]);
+ ready.label && `text extracted from ${ready.label}`,
+ truncated && "preview truncated",
+ );
+ }, [state.status, ready, preview, source, truncated]);
+ // The preview caps a sent body, so the whole one is cut from the stored text on click.
+ const { file, text: sentText } = source;
+ const load = file
+ ? () => Promise.resolve<Blob>(file)
+ : ready && !ready.label && sentText !== undefined
+ ? () =>
+ Promise.resolve(
+ new Blob([attachmentBodyText(sentText)], { type: source.contentType || "text/plain" }),
+ )
+ : undefined;
+
+ let body: ReactNode;
+ if (!ready) {
+ body =
+ state.status === "error" ? (
+ <p className="m-auto text-sm text-muted-foreground">This file could not be read.</p>
+ ) : (
+ <Spinner className="m-auto size-6" />
+ );
+ } else if (!preview?.text.trim()) {
+ body = (
+ <p className="m-auto text-sm text-muted-foreground">
+ {truncated
+ ? "No readable text in the part of this file the preview reads."
+ : "No readable text in this file."}
+ </p>
+ );
+ } else if (webPage && !showCode) {
+ body = (
+ <Zoomed scale={scale}>
+ <ArtifactHtmlFrame code={preview.text} title={source.name} fill />
+ </Zoomed>
+ );
+ } else {
+ const code = truncated ? `${preview.text}\n\n…` : preview.text;
+ body = (
+ <Zoomed scale={scale}>
+ {language || webPage ? (
+ <CodeSourceView code={code} language={language ?? "html"} className="px-6 pb-6" />
+ ) : (
+ <pre className="size-full overflow-auto whitespace-pre-wrap break-words px-6 pb-6 font-mono text-sm leading-relaxed select-text">
+ {code}
+ </pre>
+ )}
+ </Zoomed>
+ );
+ }
return (
- <Dialog
- onOpenChange={(isOpen) => {
- if (isOpen) {
- setOpened(true);
- }
+ <AttachmentViewer
+ trigger={children}
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (next) setOpened(true);
}}
- >
- <AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>
- <DialogContent
- data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}
- className="aui-attachment-text-dialog-content gap-4 sm:max-w-2xl"
- >
- <DialogHeader className="gap-1 pr-10">
- <DialogTitle className="truncate">
- {source.name || "Attachment"}
- </DialogTitle>
- <DialogDescription className="text-xs">{meta}</DialogDescription>
- </DialogHeader>
- <div className="overflow-hidden rounded-2xl border bg-muted/40">
- {state.status === "loading" ? (
- <div className="flex h-32 items-center justify-center">
- <Spinner className="size-5 text-muted-foreground" />
- </div>
- ) : preview?.text.trim() ? (
- <div className="overlay-scrollbar-gutter max-h-[60dvh] overflow-y-auto">
- <AttachmentTextBody text={preview.text} language={language} />
- </div>
- ) : (
- <div className="px-4 py-6 text-muted-foreground text-sm">
- {state.status === "error"
- ? "This file could not be read."
- : state.status === "ready" && state.truncated
- ? "No readable text in the part of this file the preview reads."
- : "No readable text in this file."}
+ source={source}
+ meta={meta}
+ media={false}
+ noun="file"
+ redactFromReload={redactFromReload}
+ load={load}
+ extra={
+ <>
+ <ScaleMenu
+ value={scale}
+ scales={ATTACHMENT_PAGE_SCALES}
+ onChange={(value) => setScale(Number(value))}
+ />
+ {webPage && (
+ <div className="mr-1 flex items-center gap-1">
+ <ViewButton label={t("library.preview.code")} active={showCode} onClick={() => setShowCode(true)}>
+ <CodeToggleIcon className="size-4.5" />
+ </ViewButton>
+ <ViewButton
+ label={t("library.preview.preview")}
+ active={!showCode}
+ onClick={() => setShowCode(false)}
+ >
+ <HugeiconsIcon icon={PlayIcon} strokeWidth={1.75} className="size-5" />
+ </ViewButton>
</div>
)}
- </div>
- </DialogContent>
- </Dialog>
+ </>
+ }
+ >
+ {body}
+ </AttachmentViewer>
);
};
/**
- * The player, and the only place a sent clip's data URL is built.
+ * The player, and the only place a sent clip's data URL is built for playback.
*
* Joining the header onto the base64 payload copies up to MAX_AUDIO_SIZE of
* it, and a transcript mounts `useAttachmentSource` once per tile and again
- * per dialog, so the join waits until DialogContent renders, which Radix only
- * does once the dialog is open.
+ * per dialog, so the join waits until the viewer renders its body, which it
+ * only does once open.
*/
const AttachmentAudioBody: FC<{ source: AttachmentSource }> = ({ source }) => {
const src = useMemo(() => {
@@ -303,36 +327,88 @@ const AttachmentAudioBody: FC<{ source: AttachmentSource }> = ({ source }) => {
}, [source.src, source.audio, source.contentType, source.name]);
return src ? (
- <AudioPlayer src={src} filename={source.name || "attachment.wav"} />
+ <div className="m-auto w-full max-w-lg px-6">
+ <AudioPlayer src={src} filename={source.name || "attachment.wav"} />
+ </div>
) : null;
};
const AttachmentAudioDialog: FC<
PropsWithChildren<{ source: AttachmentSource; redactFromReload?: boolean }>
> = ({ children, source, redactFromReload = false }) => {
+ const [open, setOpen] = useState(false);
+ const { file, src, audio } = source;
return (
- <Dialog>
- <AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>
- <DialogContent
- data-reload-snapshot-sensitive={redactFromReload ? "" : undefined}
- className="aui-attachment-audio-dialog-content gap-4 sm:max-w-lg"
- >
- <DialogHeader className="gap-1 pr-10">
- <DialogTitle className="truncate">
- {source.name || "Audio attachment"}
- </DialogTitle>
- <DialogDescription className="text-xs">
- {[
- source.file ? formatBytes(source.file.size) : null,
- source.contentType || "audio",
- ]
- .filter(Boolean)
- .join(" · ")}
- </DialogDescription>
- </DialogHeader>
- <AttachmentAudioBody source={source} />
- </DialogContent>
- </Dialog>
+ <AttachmentViewer
+ trigger={children}
+ open={open}
+ onOpenChange={setOpen}
+ source={source}
+ meta={attachmentViewerMeta(source, file?.size)}
+ media={false}
+ noun="clip"
+ redactFromReload={redactFromReload}
+ // Built on click, like the player's: a sent clip is only base64 until someone asks for it.
+ load={
+ file
+ ? () => Promise.resolve(file)
+ : src || audio
+ ? () => fetchBlob(src ?? attachmentAudioSrc(audio!, source.contentType, source.name))
+ : undefined
+ }
+ >
+ <AttachmentAudioBody source={source} />
+ </AttachmentViewer>
+ );
+};
+
+const attachmentVideoSrc = (video: AttachmentVideoPart): string =>
+ video.data.startsWith("data:") ? video.data : `data:${video.mimeType};base64,${video.data}`;
+
+const AttachmentVideoBody: FC<{ source: AttachmentSource; onError: () => void }> = ({
+ source,
+ onError,
+}) => {
+ const src = useMemo(
+ () => source.src ?? (source.video ? attachmentVideoSrc(source.video) : undefined),
+ [source.src, source.video],
+ );
+ return src ? (
+ <video src={src} controls autoPlay onError={onError} className="size-full object-contain" />
+ ) : null;
+};
+
+const AttachmentVideoDialog: FC<
+ PropsWithChildren<{ source: AttachmentSource; redactFromReload?: boolean }>
+> = ({ children, source, redactFromReload = false }) => {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const { file, src, video } = source;
+ return (
+ <AttachmentViewer
+ trigger={children}
+ open={open}
+ onOpenChange={setOpen}
+ source={source}
+ meta={attachmentViewerMeta(source, file?.size)}
+ media={!failed}
+ noun="video"
+ redactFromReload={redactFromReload}
+ load={
+ file
+ ? () => Promise.resolve(file)
+ : src || video
+ ? () => fetchBlob(src ?? attachmentVideoSrc(video!))
+ : undefined
+ }
+ >
+ {failed ? (
+ <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>
+ ) : (
+ <AttachmentVideoBody source={source} onError={() => setFailed(true)} />
+ )}
+ </AttachmentViewer>
);
};
@@ -344,7 +420,7 @@ export const AttachmentPreviewDialog: FC<
if (source.kind === "image") {
return source.src ? (
- <AttachmentImageDialog src={source.src} redactFromReload={redactFromReload}>
+ <AttachmentImageDialog source={source} src={source.src} redactFromReload={redactFromReload}>
{children}
</AttachmentImageDialog>
) : (
@@ -362,6 +438,16 @@ export const AttachmentPreviewDialog: FC<
);
}
+ if (source.kind === "video") {
+ return source.src || source.video ? (
+ <AttachmentVideoDialog source={source} redactFromReload={redactFromReload}>
+ {children}
+ </AttachmentVideoDialog>
+ ) : (
+ children
+ );
+ }
+
if (source.kind === "document") {
return (
<AttachmentDocumentDialog source={source} redactFromReload={redactFromReload}>
diff --git a/studio/frontend/src/components/assistant-ui/attachment-selection.ts b/studio/frontend/src/components/assistant-ui/attachment-selection.ts
index 982ae585809..19b4e55492c 100644
--- a/studio/frontend/src/components/assistant-ui/attachment-selection.ts
+++ b/studio/frontend/src/components/assistant-ui/attachment-selection.ts
@@ -4,15 +4,19 @@
import { documentKind, isMarkdown, sheetDelimiter } from "@/components/file-viewer/kind";
import { isAudioAttachment } from "@/features/chat/attachment-content";
-export type AttachmentPreviewKind = "image" | "audio" | "text" | "document";
+export type AttachmentPreviewKind = "image" | "audio" | "video" | "text" | "document";
export type AttachmentAudioPart = { data: string; format: string };
+export type AttachmentVideoPart = { data: string; mimeType: string };
+
type AttachmentContentPart = {
type: string;
text?: string;
image?: string;
audio?: AttachmentAudioPart;
+ data?: string;
+ mimeType?: string;
};
export type AttachmentSelection = {
@@ -22,10 +26,13 @@ export type AttachmentSelection = {
file: File | undefined;
image: string | undefined;
audio: AttachmentAudioPart | undefined;
+ video: AttachmentVideoPart | undefined;
text: string | undefined;
hasOriginal: boolean;
};
+const VIDEO_MIME = /^video\//i;
+
function isViewableDocument(
name: string,
contentType: string | undefined,
@@ -53,6 +60,7 @@ export const selectAttachmentSource = ({
attachment: {
type?: string;
name: string;
+ contentType?: string;
content?: AttachmentContentPart[];
};
}): AttachmentSelection => {
@@ -61,12 +69,20 @@ export const selectAttachmentSource = ({
const file = held instanceof File ? held : undefined;
const contentType =
file?.type ||
- (attachment as { contentType?: string }).contentType ||
+ attachment.contentType ||
undefined;
const audio = parts.find((part) => part.type === "audio")?.audio;
+ const video = parts.find(
+ (part): part is AttachmentContentPart & AttachmentVideoPart =>
+ part.type === "file" && Boolean(part.data) && VIDEO_MIME.test(part.mimeType ?? ""),
+ );
const isImage = attachment.type === "image";
+ // Before audio: the audio names include .mp4 and .webm, which a clip shares.
+ const isVideo = !isImage && !audio && (!!video || VIDEO_MIME.test(contentType ?? ""));
const isAudio =
- !isImage && (!!audio || isAudioAttachment(attachment.name, contentType));
+ !isImage &&
+ !isVideo &&
+ (!!audio || isAudioAttachment(attachment.name, contentType));
const text = parts
.filter((part) => part.type === "text")
.map((part) => part.text)
@@ -75,10 +91,19 @@ export const selectAttachmentSource = ({
const isDocument =
!isImage &&
!isAudio &&
+ !isVideo &&
isViewableDocument(attachment.name, contentType, file, hasOriginal, Boolean(text));
return {
- kind: isImage ? "image" : isAudio ? "audio" : isDocument ? "document" : "text",
+ kind: isImage
+ ? "image"
+ : isVideo
+ ? "video"
+ : isAudio
+ ? "audio"
+ : isDocument
+ ? "document"
+ : "text",
name: attachment.name,
contentType,
file,
@@ -86,6 +111,7 @@ export const selectAttachmentSource = ({
? parts.find((part) => part.type === "image")?.image
: undefined,
audio: isImage ? undefined : audio,
+ video: isVideo ? video : undefined,
text: text || undefined,
hasOriginal,
};
diff --git a/studio/frontend/src/components/assistant-ui/attachment-viewer-meta.ts b/studio/frontend/src/components/assistant-ui/attachment-viewer-meta.ts
new file mode 100644
index 00000000000..8753c5574c5
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/attachment-viewer-meta.ts
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { formatBytes } from "@/features/hub";
+
+export const ATTACHMENT_PAGE_SCALES = [0.5, 0.75, 1, 1.25, 1.5, 2];
+
+function typeLabel(name: string, contentType: string | undefined): string | null {
+ const dot = name.lastIndexOf(".");
+ if (dot > 0 && dot < name.length - 1) return name.slice(dot + 1).toUpperCase();
+ const subtype = contentType?.split("/")[1]?.split(";")[0];
+ return subtype ? subtype.toUpperCase() : null;
+}
+
+export function attachmentViewerMeta(
+ source: { name: string; contentType: string | undefined },
+ bytes: number | null | undefined,
+ ...extra: Array<string | null | false | undefined>
+): string {
+ return [typeLabel(source.name, source.contentType), bytes ? formatBytes(bytes) : null, ...extra]
+ .filter(Boolean)
+ .join(" · ");
+}
diff --git a/studio/frontend/src/components/assistant-ui/attachment.tsx b/studio/frontend/src/components/assistant-ui/attachment.tsx
index c3a4afad5d8..aa4de99ff5f 100644
--- a/studio/frontend/src/components/assistant-ui/attachment.tsx
+++ b/studio/frontend/src/components/assistant-ui/attachment.tsx
@@ -6,6 +6,7 @@
// Avatar removed — caused circular crop on image thumbnails
import { AttachmentPreviewDialog } from "@/components/assistant-ui/attachment-preview";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
+import { Button } from "@/components/ui/button";
import { useAttachmentImageSrc } from "@/components/assistant-ui/use-attachment-source";
import {
Dialog,
@@ -19,8 +20,16 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import {
+ ATTACHMENT_KIND_ICON_CLASS,
+ ATTACHMENT_KIND_ICONS,
PASTED_TEXT_PREVIEW_MAX_CHARS,
+ attachmentFileKind,
+ attachmentKindLabel,
+ composerAttachmentsOverflow,
isAudioAttachment,
+ sentAttachmentLayout,
+ type AttachmentFileKind,
+ type SentAttachmentLayout,
isPastedTextContent,
isPastedTextFile,
pastedTextContentBytes,
@@ -28,6 +37,7 @@ import {
pastedTextPreview,
} from "@/features/chat";
import { formatBytes } from "@/features/hub";
+import { useAppearanceCustomStore } from "@/features/settings";
import { cn } from "@/lib/utils";
import { useShallow } from "zustand/shallow";
import {
@@ -39,24 +49,35 @@ import {
} from "@assistant-ui/react";
import {
AudioWave01Icon,
+ File01Icon,
File02Icon,
TextAlignLeft01Icon,
+ Video01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { ChevronRightIcon, PlusIcon, XIcon } from "lucide-react";
import {
+ createContext,
type FC,
type PropsWithChildren,
+ type ReactNode,
useCallback,
+ useContext,
useEffect,
+ useLayoutEffect,
useRef,
useState,
} from "react";
import { ScrollPane } from "./scroll-pane";
+// Before the audio names, which include .mp4 and .webm: the video adapter types every clip video/*.
+const isVideoAttachment = (attachment: unknown): boolean =>
+ /^video\//i.test((attachment as { contentType?: string }).contentType ?? "");
+
const AttachmentThumb: FC = () => {
const src = useAttachmentImageSrc();
const name = useAuiState(({ attachment }) => attachment.name);
+ const isVideo = useAuiState(({ attachment }) => isVideoAttachment(attachment));
const contentType = useAuiState(
({ attachment }) =>
(attachment as { file?: File }).file?.type ??
@@ -78,7 +99,11 @@ const AttachmentThumb: FC = () => {
<div className="flex h-full w-full items-center justify-center">
<HugeiconsIcon
icon={
- isAudioAttachment(name, contentType) ? AudioWave01Icon : File02Icon
+ isVideo
+ ? Video01Icon
+ : isAudioAttachment(name, contentType)
+ ? AudioWave01Icon
+ : File02Icon
}
strokeWidth={2}
className="size-6 text-muted-foreground"
@@ -87,6 +112,85 @@ const AttachmentThumb: FC = () => {
);
};
+const CARD_SLOT =
+ "shrink-0 w-[calc((100%_-_var(--spacing)*8)/5)] min-w-[calc(7rem*var(--ui-space-scale,1))]";
+const CARD_SIZE = "h-[calc(7rem*var(--ui-space-scale,1))] w-full";
+const SENT_IMAGE_SIZE = "size-[calc(9rem*var(--ui-space-scale,1))]";
+const SENT_IMAGE_SIZE_COMPACT = "size-[calc(5rem*var(--ui-space-scale,1))]";
+const SENT_ROW_WIDTH = "w-[calc(18rem*var(--ui-space-scale,1))]";
+const CARD_EDGE =
+ "border border-[color-mix(in_oklab,var(--foreground)_calc(12%*var(--contrast-edge-gain,1)),transparent)]";
+const CARD_SURFACE =
+ "bg-[color-mix(in_oklab,var(--foreground)_3%,transparent)] hover:bg-[color-mix(in_oklab,var(--foreground)_6%,transparent)]";
+
+const useAttachmentKind = (): {
+ name: string;
+ kind: AttachmentFileKind;
+} => {
+ const name = useAuiState(({ attachment }) => attachment.name ?? "");
+ const isImage = useAuiState(({ attachment }) => attachment.type === "image");
+ const contentType = useAuiState(
+ ({ attachment }) =>
+ // An unknown type reads as "", which must not hide the stored one.
+ (attachment as { file?: File }).file?.type ||
+ (attachment as { contentType?: string }).contentType ||
+ "",
+ );
+ return {
+ name,
+ kind: isImage ? "image" : attachmentFileKind(name, contentType),
+ };
+};
+
+const AttachmentKindIcon: FC<{ kind: AttachmentFileKind; className?: string }> = ({
+ kind,
+ className,
+}) => (
+ <HugeiconsIcon
+ icon={ATTACHMENT_KIND_ICONS[kind]}
+ strokeWidth={1.75}
+ className={cn("shrink-0", ATTACHMENT_KIND_ICON_CLASS[kind], className)}
+ />
+);
+
+const FileCardBody: FC<{
+ name: string;
+ kind: AttachmentFileKind;
+ center?: ReactNode;
+ icon?: ReactNode;
+}> = ({ name, kind, center, icon }) => (
+ <span className="flex h-full w-full flex-col">
+ <span className="flex min-h-0 flex-1 items-center justify-center px-3 text-muted-foreground">
+ {center ?? (
+ <HugeiconsIcon icon={File01Icon} strokeWidth={1.5} className="size-6" />
+ )}
+ </span>
+ <span className="flex min-w-0 items-center gap-1.5 px-3 pb-2.5">
+ {icon ?? <AttachmentKindIcon kind={kind} className="size-4" />}
+ <span className="min-w-0 truncate text-ui-13 leading-ui-18 text-foreground">
+ {name}
+ </span>
+ </span>
+ </span>
+);
+
+const CardImageOrBody: FC<{ name: string; kind: AttachmentFileKind; src: string | undefined }> = ({
+ name,
+ kind,
+ src,
+}) => {
+ if (src) {
+ return (
+ <img
+ src={src}
+ alt={name || "Attachment preview"}
+ className="h-full w-full object-cover"
+ />
+ );
+ }
+ return <FileCardBody name={name} kind={kind} />;
+};
+
type PastedTextAttachment = {
readonly file?: File;
readonly sentText?: string;
@@ -172,11 +276,14 @@ const PastedTextPreviewDialog: FC<
);
};
+type PastedTextVariant = "chip" | "card" | "row" | "pill";
+
const PastedTextAttachmentUI: FC<{
attachment: PastedTextAttachment;
isComposer: boolean;
name: string;
-}> = ({ attachment, isComposer, name }) => {
+ variant?: PastedTextVariant;
+}> = ({ attachment, isComposer, name, variant = "chip" }) => {
const aui = useAui();
const attachmentId = useAuiState(({ attachment: state }) => state.id);
const [inlining, setInlining] = useState(false);
@@ -218,7 +325,87 @@ const PastedTextAttachmentUI: FC<{
});
}, [attachment, attachmentId, aui, inlining]);
- const chip = (
+ const sizeLabel = bytes === undefined ? "Pasted text" : formatBytes(bytes);
+ const ariaLabel = isComposer
+ ? `Pasted text: ${name}. Show in text field`
+ : `Pasted text: ${name}. Show contents`;
+ const textIcon = (className: string) => (
+ <HugeiconsIcon
+ icon={TextAlignLeft01Icon}
+ strokeWidth={2}
+ className={cn("shrink-0 text-muted-foreground", className)}
+ />
+ );
+ const chip =
+ variant === "card" ? (
+ <button
+ className={cn(
+ "aui-pasted-text-card group flex cursor-pointer overflow-hidden rounded-[18px] text-left transition-colors",
+ CARD_SIZE,
+ CARD_EDGE,
+ CARD_SURFACE,
+ )}
+ type="button"
+ title={name}
+ aria-label={ariaLabel}
+ onClick={isComposer ? showInTextField : undefined}
+ >
+ <FileCardBody
+ name={name}
+ kind="text"
+ icon={textIcon("size-4")}
+ center={
+ <span className="flex flex-col items-center gap-1 text-ui-11">
+ {textIcon("size-6")}
+ {/* Hover swaps the size for the action. */}
+ <span className={isComposer ? "group-hover:hidden" : undefined}>
+ {sizeLabel}
+ </span>
+ {isComposer ? (
+ <span className="hidden items-center gap-0.5 underline underline-offset-2 group-hover:inline-flex">
+ Show in text field
+ <ChevronRightIcon className="size-3" />
+ </span>
+ ) : null}
+ </span>
+ }
+ />
+ </button>
+ ) : variant === "row" ? (
+ <button
+ className={cn(
+ "aui-pasted-text-row flex max-w-full cursor-pointer items-center gap-3 rounded-[18px] px-4 py-3 text-left transition-colors",
+ SENT_ROW_WIDTH,
+ CARD_EDGE,
+ "hover:bg-[color-mix(in_oklab,var(--foreground)_5%,transparent)]",
+ )}
+ type="button"
+ title={name}
+ aria-label={ariaLabel}
+ >
+ {textIcon("size-7")}
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate font-medium text-sm">{name}</span>
+ <span className="truncate text-muted-foreground text-xs">
+ {sizeLabel}
+ </span>
+ </span>
+ </button>
+ ) : variant === "pill" ? (
+ <button
+ className={cn(
+ "aui-pasted-text-pill inline-flex h-9 max-w-[calc(16rem*var(--ui-space-scale,1))] cursor-pointer items-center gap-1.5 rounded-full px-3 text-sm transition-colors",
+ CARD_EDGE,
+ "hover:bg-[color-mix(in_oklab,var(--foreground)_5%,transparent)]",
+ )}
+ type="button"
+ title={name}
+ aria-label={ariaLabel}
+ >
+ {textIcon("size-4")}
+ <span className="truncate">{name}</span>
+ </button>
+ ) : (
<button
className={cn(
// Borderless, and in dark mode a shade under the composer surface.
@@ -257,10 +444,15 @@ const PastedTextAttachmentUI: FC<{
</span>
</span>
</button>
- );
+ );
return (
- <AttachmentPrimitive.Root className="aui-attachment-root relative">
+ <AttachmentPrimitive.Root
+ className={cn(
+ "aui-attachment-root relative",
+ variant === "card" && cn("group/attachment-card", CARD_SLOT),
+ )}
+ >
{isComposer ? (
chip
) : (
@@ -268,7 +460,8 @@ const PastedTextAttachmentUI: FC<{
{chip}
</PastedTextPreviewDialog>
)}
- {isComposer && <AttachmentRemove />}
+ {isComposer &&
+ (variant === "card" ? <AttachmentCardRemove /> : <AttachmentRemove />)}
</AttachmentPrimitive.Root>
);
};
@@ -289,6 +482,7 @@ const AttachmentUI: FC = () => {
case "document":
return "Document";
case "file":
+ if (isVideoAttachment(attachment)) return "Video";
return isAudioAttachment(
attachment.name,
(attachment as { file?: File }).file?.type ?? "",
@@ -354,34 +548,309 @@ const AttachmentUI: FC = () => {
const AttachmentRemove: FC = () => {
return (
<AttachmentPrimitive.Remove asChild={true}>
- <TooltipIconButton
- tooltip="Remove file"
- className="aui-attachment-tile-remove absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white text-muted-foreground opacity-100 shadow-sm hover:bg-white! [&_svg]:text-black hover:[&_svg]:text-destructive"
- side="top"
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label="Remove file"
+ className="aui-attachment-tile-remove absolute top-1.5 right-1.5 size-3.5 rounded-full bg-white p-0 text-muted-foreground opacity-100 shadow-sm hover:bg-white! [&_svg]:text-black hover:[&_svg]:text-destructive"
>
<XIcon className="aui-attachment-remove-icon size-3 dark:stroke-[2.5px]" />
- </TooltipIconButton>
+ </Button>
+ </AttachmentPrimitive.Remove>
+ );
+};
+
+const AttachmentCardRemove: FC = () => {
+ return (
+ <AttachmentPrimitive.Remove asChild={true}>
+ {/* No tooltip: the X says what it does, and a label popping over the next card is noise. */}
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label="Remove file"
+ className="aui-attachment-card-remove absolute top-1.5 right-1.5 size-5 rounded-full bg-foreground p-0 opacity-0 shadow-sm transition-opacity hover:bg-foreground! focus-visible:opacity-100 group-hover/attachment-card:opacity-100 group-focus-within/attachment-card:opacity-100 [@media(pointer:coarse)]:opacity-100 [&_svg]:text-background"
+ >
+ <XIcon className="aui-attachment-remove-icon size-3 stroke-[2.5px]" />
+ </Button>
</AttachmentPrimitive.Remove>
);
};
+const ComposerAttachmentCard: FC = () => {
+ const pastedText = usePastedTextAttachment();
+ const src = useAttachmentImageSrc();
+ const attachmentId = useAuiState(({ attachment }) => attachment.id);
+ const { name, kind } = useAttachmentKind();
+
+ if (pastedText) {
+ return (
+ <PastedTextAttachmentUI
+ key={attachmentId}
+ attachment={pastedText}
+ isComposer={true}
+ name={name || "Pasted text"}
+ variant="card"
+ />
+ );
+ }
+
+ const label = attachmentKindLabel(kind, name);
+ return (
+ <AttachmentPrimitive.Root
+ key={attachmentId}
+ className={cn("aui-attachment-root aui-attachment-card group/attachment-card relative", CARD_SLOT)}
+ >
+ <AttachmentPreviewDialog redactFromReload={true}>
+ <button
+ className={cn(
+ "aui-attachment-card-tile flex cursor-pointer overflow-hidden rounded-[18px] text-left transition-colors",
+ CARD_SIZE,
+ !src && CARD_EDGE,
+ !src && CARD_SURFACE,
+ )}
+ type="button"
+ title={name}
+ aria-label={name ? `${label} attachment: ${name}` : `${label} attachment`}
+ >
+ <CardImageOrBody name={name} kind={kind} src={src} />
+ </button>
+ </AttachmentPreviewDialog>
+ <AttachmentCardRemove />
+ </AttachmentPrimitive.Root>
+ );
+};
+
+const SentAttachmentLayoutContext = createContext<SentAttachmentLayout>("list");
+
+const NoAttachment: FC = () => null;
+
+const SentImageTile: FC = () => {
+ const layout = useContext(SentAttachmentLayoutContext);
+ const attachmentId = useAuiState(({ attachment }) => attachment.id);
+ const { name, kind } = useAttachmentKind();
+ return (
+ <AttachmentPrimitive.Root key={attachmentId} className="aui-attachment-root relative">
+ <AttachmentPreviewDialog redactFromReload={false}>
+ <button
+ className={cn(
+ "aui-attachment-image-tile block cursor-pointer overflow-hidden rounded-[18px] transition-opacity hover:opacity-85",
+ layout === "list" ? SENT_IMAGE_SIZE : SENT_IMAGE_SIZE_COMPACT,
+ CARD_EDGE,
+ )}
+ type="button"
+ title={name}
+ aria-label={name ? `Image attachment: ${name}` : "Image attachment"}
+ >
+ <SentImageThumb name={name} kind={kind} />
+ </button>
+ </AttachmentPreviewDialog>
+ </AttachmentPrimitive.Root>
+ );
+};
+
+const SentImageThumb: FC<{ name: string; kind: AttachmentFileKind }> = ({
+ name,
+ kind,
+}) => {
+ const src = useAttachmentImageSrc();
+ if (src) {
+ return (
+ <img
+ src={src}
+ alt={name || "Attachment preview"}
+ className="h-full w-full object-cover"
+ />
+ );
+ }
+ return (
+ <span className="flex h-full w-full items-center justify-center bg-muted">
+ <AttachmentKindIcon kind={kind} className="size-6" />
+ </span>
+ );
+};
+
+const SentFileItem: FC = () => {
+ const layout = useContext(SentAttachmentLayoutContext);
+ const pastedText = usePastedTextAttachment();
+ const attachmentId = useAuiState(({ attachment }) => attachment.id);
+ const { name, kind } = useAttachmentKind();
+
+ if (pastedText) {
+ return (
+ <PastedTextAttachmentUI
+ key={attachmentId}
+ attachment={pastedText}
+ isComposer={false}
+ name={name || "Pasted text"}
+ variant={layout === "list" ? "row" : "pill"}
+ />
+ );
+ }
+
+ const label = attachmentKindLabel(kind, name);
+ const accessibleName = name ? `${label} attachment: ${name}` : `${label} attachment`;
+ return (
+ <AttachmentPrimitive.Root
+ key={attachmentId}
+ className="aui-attachment-root relative max-w-full"
+ >
+ <AttachmentPreviewDialog redactFromReload={false}>
+ {layout === "list" ? (
+ <button
+ className={cn(
+ "aui-attachment-row flex max-w-full cursor-pointer items-center gap-3 rounded-[18px] px-4 py-3 text-left transition-colors",
+ SENT_ROW_WIDTH,
+ CARD_EDGE,
+ "hover:bg-[color-mix(in_oklab,var(--foreground)_5%,transparent)]",
+ )}
+ type="button"
+ title={name}
+ aria-label={accessibleName}
+ >
+ <AttachmentKindIcon kind={kind} className="size-7" />
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate font-medium text-sm">
+ {name || label}
+ </span>
+ <span className="truncate text-muted-foreground text-xs">
+ {label}
+ </span>
+ </span>
+ </button>
+ ) : (
+ <button
+ className={cn(
+ "aui-attachment-chip inline-flex h-9 max-w-[calc(16rem*var(--ui-space-scale,1))] cursor-pointer items-center gap-1.5 rounded-full px-3 text-sm transition-colors",
+ CARD_EDGE,
+ "hover:bg-[color-mix(in_oklab,var(--foreground)_5%,transparent)]",
+ )}
+ type="button"
+ title={name}
+ aria-label={accessibleName}
+ >
+ <AttachmentKindIcon kind={kind} className="size-4" />
+ <span className="truncate">{name || label}</span>
+ </button>
+ )}
+ </AttachmentPreviewDialog>
+ </AttachmentPrimitive.Root>
+ );
+};
+
+// Module constants: the primitive re-renders every attachment when these change identity.
+const SENT_IMAGE_COMPONENTS = {
+ Image: SentImageTile,
+ Document: NoAttachment,
+ File: NoAttachment,
+};
+const SENT_FILE_COMPONENTS = {
+ Image: NoAttachment,
+ Document: SentFileItem,
+ File: SentFileItem,
+};
+const COMPACT_COMPONENTS = { Attachment: AttachmentUI };
+const CARD_COMPONENTS = { Attachment: ComposerAttachmentCard };
+
export const UserMessageAttachments: FC = () => {
+ const setting = useAppearanceCustomStore(
+ (s) => s.customization.sentAttachments,
+ );
+ const count = useAuiState(({ message }) =>
+ message.role === "user" ? message.attachments.length : 0,
+ );
+ if (count === 0) return null;
+ const layout = sentAttachmentLayout(setting, count);
+ return (
+ <SentAttachmentLayoutContext.Provider value={layout}>
+ <div className="aui-user-message-attachments-end flex w-full flex-col items-end gap-2">
+ <div className="aui-user-message-attachment-images flex max-w-full flex-row flex-wrap justify-end gap-2 empty:hidden">
+ <MessagePrimitive.Attachments components={SENT_IMAGE_COMPONENTS} />
+ </div>
+ <div
+ className={cn(
+ "aui-user-message-attachment-files max-w-full empty:hidden",
+ layout === "list"
+ ? "flex flex-col items-end gap-2"
+ : "flex flex-row flex-wrap justify-end gap-2",
+ )}
+ >
+ <MessagePrimitive.Attachments components={SENT_FILE_COMPONENTS} />
+ </div>
+ </div>
+ </SentAttachmentLayoutContext.Provider>
+ );
+};
+
+// The layout decision is a DOM data attribute, never state, so a resize or new card re-renders no card.
+const ComposerAttachmentCards: FC = () => {
+ const count = useAuiState(({ composer }) => composer.attachments.length);
+ const ref = useRef<HTMLDivElement | null>(null);
+ const previousCount = useRef(count);
+
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const layout = () => {
+ const card = el.firstElementChild as HTMLElement | null;
+ const style = getComputedStyle(el);
+ const width =
+ el.clientWidth -
+ Number.parseFloat(style.paddingLeft) -
+ Number.parseFloat(style.paddingRight);
+ const strip = composerAttachmentsOverflow(
+ count,
+ width,
+ card?.getBoundingClientRect().width ?? 0,
+ Number.parseFloat(style.columnGap) || 0,
+ );
+ const next = strip ? "strip" : "wrap";
+ if (el.dataset.layout !== next) el.dataset.layout = next;
+ };
+ layout();
+ if (count > previousCount.current && el.dataset.layout === "strip") {
+ el.scrollLeft = el.scrollWidth;
+ }
+ previousCount.current = count;
+ const observer = new ResizeObserver(layout);
+ observer.observe(el);
+ const onWheel = (event: WheelEvent) => {
+ if (el.dataset.layout !== "strip") return;
+ if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
+ const max = el.scrollWidth - el.clientWidth;
+ const next = Math.min(max, Math.max(0, el.scrollLeft + event.deltaY));
+ if (next === el.scrollLeft) return;
+ event.preventDefault();
+ el.scrollLeft = next;
+ };
+ el.addEventListener("wheel", onWheel, { passive: false });
+ return () => {
+ observer.disconnect();
+ el.removeEventListener("wheel", onWheel);
+ };
+ }, [count]);
+
return (
- <div className="aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2">
- <MessagePrimitive.Attachments components={{ Attachment: AttachmentUI }} />
+ <div
+ ref={ref}
+ data-reload-snapshot-sensitive
+ className="aui-composer-attachments aui-composer-attachment-cards mb-4 flex w-full flex-row flex-wrap gap-2 px-1.5 pt-0.5 pb-1 empty:hidden data-[layout=strip]:flex-nowrap data-[layout=strip]:overflow-x-auto data-[layout=strip]:overscroll-x-contain"
+ >
+ <ComposerPrimitive.Attachments components={CARD_COMPONENTS} />
</div>
);
};
export const ComposerAttachments: FC = () => {
+ const style = useAppearanceCustomStore(
+ (s) => s.customization.composerAttachments,
+ );
+ if (style === "cards") return <ComposerAttachmentCards />;
return (
<div
data-reload-snapshot-sensitive
- className="aui-composer-attachments mb-2 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden"
+ className="aui-composer-attachments mb-4 flex w-full flex-row items-center gap-2 overflow-x-auto px-1.5 pt-0.5 pb-1 empty:hidden"
>
- <ComposerPrimitive.Attachments
- components={{ Attachment: AttachmentUI }}
- />
+ <ComposerPrimitive.Attachments components={COMPACT_COMPONENTS} />
</div>
);
};
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 223e781317d..7a441a5b099 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -6442,8 +6442,9 @@ const ComposerToolsMenu: FC<{
);
const audioAttachmentsEnabled = useChatRuntimeStore((s) => {
const activeCheckpoint = s.params.checkpoint;
+ // No model yet: offer audio too, since files attached now wait for the model loaded next.
if (!activeCheckpoint || s.modelLoading) {
- return false;
+ return true;
}
const activeModel = s.models.find((m) => m.id === activeCheckpoint);
return Boolean(activeModel?.hasAudioInput);
diff --git a/studio/frontend/src/components/assistant-ui/use-attachment-source.ts b/studio/frontend/src/components/assistant-ui/use-attachment-source.ts
index 9f7603ea922..f0fd51d6e4e 100644
--- a/studio/frontend/src/components/assistant-ui/use-attachment-source.ts
+++ b/studio/frontend/src/components/assistant-ui/use-attachment-source.ts
@@ -6,6 +6,7 @@
import {
type AttachmentAudioPart,
type AttachmentPreviewKind,
+ type AttachmentVideoPart,
selectAttachmentSource,
} from "@/components/assistant-ui/attachment-selection";
import { useAuiState } from "@assistant-ui/react";
@@ -21,6 +22,7 @@ export type AttachmentSource = {
file: File | undefined;
src: string | undefined;
audio: AttachmentAudioPart | undefined;
+ video: AttachmentVideoPart | undefined;
text: string | undefined;
hasOriginal: boolean;
};
@@ -50,7 +52,7 @@ export const useAttachmentSource = (): AttachmentSource => {
source.kind === "text" || source.kind === "document" ? undefined : source.file,
);
- // audio passes through unjoined: the payload is MAX_AUDIO_SIZE of base64 and every tile mounts this hook
+ // audio and video pass through unjoined: a clip is up to MAX_VIDEO_SIZE of base64 and every tile mounts this hook
return {
kind: source.kind,
name: source.name,
@@ -58,6 +60,7 @@ export const useAttachmentSource = (): AttachmentSource => {
file: source.file,
src: fileSrc ?? source.image,
audio: source.audio,
+ video: source.video,
text: source.text,
hasOriginal: source.hasOriginal,
};
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index b5f9f424cfb..443811467b9 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { attachedMediaUnavailableReason } from "../lib/attached-media-gate";
+import { externalModelLabel } from "../lib/external-model-label";
import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";
import { minPSamplingPayload } from "../lib/min-p-policy";
import {
@@ -5143,6 +5145,17 @@ export function createOpenAIStreamAdapter(
addSystemInstruction(outboundMessages, effectiveDisabledToolGuard);
addSystemInstruction(outboundMessages, artifactInstruction);
+ const blockAttachmentRun = (reason: string): never => {
+ toast.error(reason);
+ // Flip on->off so compare-mode waitForRunEnd resolves: this gate fires before setThreadRunning(true).
+ const gatedThreadKey = resolvedThreadId || "__default";
+ // Own token: siblings share "__default", so an ownerless clear would drop entries that are still generating.
+ const gateOwner = createImageGateRunOwner();
+ runtime.setThreadRunning(gatedThreadKey, true, { owner: gateOwner });
+ runtime.setThreadRunning(gatedThreadKey, false, { owner: gateOwner });
+ clearSelectedImageEditReference();
+ throw new Error(reason);
+ };
// Block when ANY image is in the outbound payload and the loaded model cannot process images;
// switching models means starting a new chat.
if (imageBase64) {
@@ -5164,18 +5177,26 @@ export function createOpenAIStreamAdapter(
mmprojFallbackReason: runtime.mmprojFallbackReason,
});
if (imageGateReason) {
- toast.error(imageGateReason);
- // Flip the per-thread running flag on->off so compare-mode waitForRunEnd resolves: this gate
- // fires before the streaming path's setThreadRunning(true).
- const gatedThreadKey = resolvedThreadId || "__default";
- // Own token: siblings share "__default", so an ownerless clear would drop entries that are still generating.
- const gateOwner = createImageGateRunOwner();
- runtime.setThreadRunning(gatedThreadKey, true, { owner: gateOwner });
- runtime.setThreadRunning(gatedThreadKey, false, { owner: gateOwner });
- clearSelectedImageEditReference();
- throw new Error(imageGateReason);
+ blockAttachmentRun(imageGateReason);
}
}
+ // Media attached before a model loaded skipped the add-time check; recorded audio is not counted.
+ const answeringModel = runtime.models.find(
+ (m) => m.id === params.checkpoint,
+ );
+ const attachedMediaReason = attachedMediaUnavailableReason({
+ activeModel: answeringModel,
+ checkpoint: params.checkpoint,
+ modelLabel:
+ answeringModel?.name ||
+ externalModelLabel(params.checkpoint) ||
+ params.checkpoint,
+ audio: Boolean(findLatestUserAudioBase64(survivingMessages, false)),
+ video: Boolean(videoBase64),
+ });
+ if (attachedMediaReason) {
+ blockAttachmentRun(attachedMediaReason);
+ }
if (audioBase64 && !queuedRunSettings) {
const audioName = runtime.pendingAudioName;
if (audioName) {
diff --git a/studio/frontend/src/features/chat/audio-attachment-adapter.ts b/studio/frontend/src/features/chat/audio-attachment-adapter.ts
index e593e237571..baecd8d2f6b 100644
--- a/studio/frontend/src/features/chat/audio-attachment-adapter.ts
+++ b/studio/frontend/src/features/chat/audio-attachment-adapter.ts
@@ -24,8 +24,7 @@ function newAttachmentId(): string {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
-// Audio shares the "Add photos & files" picker. Like VisionImageAdapter, unsupported models are
-// rejected at add() time with a toast.
+// A loaded model without audio rejects at add(); with none loaded, the send path checks it later.
export class AudioAttachmentAdapter implements AttachmentAdapter {
// MIME is unreliable for some containers (m4a), so also match by extension. No .webm extension:
// it would claim video/webm files; real audio webm (MediaRecorder) always reports the audio/webm
@@ -40,12 +39,7 @@ export class AudioAttachmentAdapter implements AttachmentAdapter {
const activeModel = state.models.find((m) => m.id === checkpoint);
const modelLoaded = !!checkpoint && !state.modelLoading;
let unavailableReason: string | null = null;
- if (!modelLoaded) {
- // Mirror the image gate: flag a failed load vs "no model picked".
- unavailableReason = state.lastModelLoadError
- ? "The last model failed to load. Check the server logs, then load a model before adding audio files."
- : "Load a model before adding audio files.";
- } else if (!activeModel?.hasAudioInput) {
+ if (modelLoaded && !activeModel?.hasAudioInput) {
// A connected provider's model has no row in `models`, so without the parse this named it by its
// raw `external::` id (#8405).
const label =
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index da0241d6d95..7b37086607e 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -292,6 +292,20 @@ export {
repackDocxPreviewArchive,
truncateAttachmentPreviewText,
} from "./attachment-content";
+export {
+ ATTACHMENT_KIND_ICON_CLASS,
+ ATTACHMENT_KIND_ICONS,
+ attachmentFileKind,
+ attachmentKindLabel,
+ type AttachmentFileKind,
+} from "./lib/attachment-file-kind";
+export {
+ COMPOSER_ATTACHMENT_MAX_ROWS,
+ SENT_ATTACHMENT_LIST_MAX,
+ composerAttachmentsOverflow,
+ sentAttachmentLayout,
+ type SentAttachmentLayout,
+} from "./lib/attachment-layout";
export { ApiProviderLogo } from "./api-provider-logo";
export { useExternalProvidersStore } from "./stores/external-providers-store";
export { DeleteChatFilesSwitch } from "./components/delete-chat-files-switch";
diff --git a/studio/frontend/src/features/chat/lib/attached-media-gate.ts b/studio/frontend/src/features/chat/lib/attached-media-gate.ts
new file mode 100644
index 00000000000..018a42be6ee
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/attached-media-gate.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export function attachedMediaUnavailableReason({
+ activeModel,
+ checkpoint,
+ modelLabel,
+ audio,
+ video,
+}: {
+ activeModel: { hasAudioInput?: boolean; hasVideoInput?: boolean } | undefined;
+ checkpoint: string | null | undefined;
+ modelLabel: string;
+ audio: boolean;
+ video: boolean;
+}): string | null {
+ if (!checkpoint || (!audio && !video)) return null;
+ if (audio && !activeModel?.hasAudioInput) {
+ return `${modelLabel} cannot accept audio. Load an audio-input model, or remove the audio file.`;
+ }
+ if (video && !activeModel?.hasVideoInput) {
+ return `${modelLabel} cannot accept video. Load a model that reads video, or remove the video.`;
+ }
+ return null;
+}
diff --git a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts b/studio/frontend/src/features/chat/lib/attachment-file-kind.ts
new file mode 100644
index 00000000000..e23a265bc11
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/attachment-file-kind.ts
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Name and MIME type only: the bytes can be megabytes and this runs on every tile and row.
+
+import {
+ AudioWave01Icon,
+ Doc02Icon,
+ File02Icon,
+ Globe02Icon,
+ Image02Icon,
+ Pdf02Icon,
+ Presentation01Icon,
+ SourceCodeIcon,
+ Video01Icon,
+ Xls02Icon,
+ Zip02Icon,
+} from "@hugeicons/core-free-icons";
+
+export type AttachmentFileKind =
+ | "image"
+ | "pdf"
+ | "audio"
+ | "video"
+ | "document"
+ | "spreadsheet"
+ | "presentation"
+ | "web"
+ | "code"
+ | "text"
+ | "archive"
+ | "file";
+
+const EXTENSION_KINDS: Record<string, AttachmentFileKind> = {};
+function register(kind: AttachmentFileKind, extensions: string) {
+ for (const extension of extensions.split(" ")) EXTENSION_KINDS[extension] = kind;
+}
+register("image", "png jpg jpeg gif webp avif bmp svg heic heif tif tiff ico");
+register("pdf", "pdf");
+register(
+ "audio",
+ "mp3 mp2 wav m4a ogg oga opus flac aac aiff aif aifc caf wma amr",
+);
+register("video", "mp4 m4v mov mkv avi webm 3gp 3g2 mpg mpeg wmv");
+register("document", "doc docx odt rtf pages epub");
+register("spreadsheet", "csv tsv xls xlsx xlsm ods numbers");
+register("presentation", "ppt pptx odp key");
+register("web", "html htm xhtml mhtml");
+register(
+ "code",
+ "py pyi ipynb js mjs cjs ts mts cts tsx jsx json jsonl c h cc cpp cxx hpp cs java kt kts go rs rb php swift scala sh bash zsh fish ps1 bat cmd css scss sass less sql yaml yml toml ini cfg conf xml r lua dart vue svelte gradle cmake proto graphql gql pl hs ex exs erl clj zig nim jl m mm",
+);
+register("text", "txt md markdown mdx rst log patch diff tex srt vtt");
+register("archive", "zip tar gz tgz bz2 xz zst 7z rar");
+
+const CODE_BASENAMES = new Set(["dockerfile", "makefile", "gemfile", "rakefile"]);
+
+function extensionOf(name: string): string {
+ const base = name.toLowerCase().split(/[\\/]/).pop() ?? "";
+ const dot = base.lastIndexOf(".");
+ return dot > 0 ? base.slice(dot + 1) : "";
+}
+
+export function attachmentFileKind(
+ name: string | undefined,
+ contentType: string | undefined,
+): AttachmentFileKind {
+ const mime = (contentType ?? "").toLowerCase();
+ if (mime.startsWith("image/")) return "image";
+ if (mime.startsWith("audio/")) return "audio";
+ if (mime.startsWith("video/")) return "video";
+ if (mime === "application/pdf") return "pdf";
+ if (mime === "text/html") return "web";
+ const extension = extensionOf(name ?? "");
+ if (extension && Object.hasOwn(EXTENSION_KINDS, extension)) {
+ return EXTENSION_KINDS[extension];
+ }
+ const base = (name ?? "").toLowerCase().split(/[\\/]/).pop() ?? "";
+ if (CODE_BASENAMES.has(base)) return "code";
+ if (mime.startsWith("text/")) return "text";
+ return "file";
+}
+
+export const ATTACHMENT_KIND_ICONS = {
+ image: Image02Icon,
+ pdf: Pdf02Icon,
+ audio: AudioWave01Icon,
+ video: Video01Icon,
+ document: Doc02Icon,
+ spreadsheet: Xls02Icon,
+ presentation: Presentation01Icon,
+ web: Globe02Icon,
+ code: SourceCodeIcon,
+ text: File02Icon,
+ archive: Zip02Icon,
+ file: File02Icon,
+} as const satisfies Record<AttachmentFileKind, unknown>;
+
+export const ATTACHMENT_KIND_ICON_CLASS: Record<AttachmentFileKind, string> = {
+ image: "text-sky-500",
+ pdf: "text-red-500",
+ audio: "text-violet-500",
+ video: "text-pink-500",
+ document: "text-blue-500",
+ spreadsheet: "text-emerald-500",
+ presentation: "text-orange-500",
+ web: "text-foreground",
+ code: "text-blue-500",
+ text: "text-blue-500",
+ archive: "text-amber-500",
+ file: "text-muted-foreground",
+};
+
+const KIND_LABELS: Record<Exclude<AttachmentFileKind, "file">, string> = {
+ image: "Image",
+ pdf: "PDF",
+ audio: "Audio",
+ video: "Video",
+ document: "Document",
+ spreadsheet: "Spreadsheet",
+ presentation: "Presentation",
+ web: "HTML",
+ code: "Code",
+ text: "Text",
+ archive: "Archive",
+};
+
+export function attachmentKindLabel(
+ kind: AttachmentFileKind,
+ name: string | undefined,
+): string {
+ if (kind !== "file") return KIND_LABELS[kind];
+ const extension = extensionOf(name ?? "");
+ return extension && extension.length <= 6 ? extension.toUpperCase() : "File";
+}
diff --git a/studio/frontend/src/features/chat/lib/attachment-layout.ts b/studio/frontend/src/features/chat/lib/attachment-layout.ts
new file mode 100644
index 00000000000..69807acf10f
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/attachment-layout.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+export type SentAttachmentLayout = "list" | "chips";
+
+export const SENT_ATTACHMENT_LIST_MAX = 6;
+
+export const COMPOSER_ATTACHMENT_MAX_ROWS = 2;
+
+export function sentAttachmentLayout(
+ // The Appearance setting of the same name; spelled out so this module imports nothing.
+ setting: "auto" | "list" | "chips",
+ count: number,
+): SentAttachmentLayout {
+ if (setting === "auto") {
+ return count > SENT_ATTACHMENT_LIST_MAX ? "chips" : "list";
+ }
+ return setting;
+}
+
+export function composerAttachmentsOverflow(
+ count: number,
+ width: number,
+ cardWidth: number,
+ gap: number,
+): boolean {
+ if (count === 0 || cardWidth <= 0) return false;
+ // Cards sized to a fifth of the row divide it exactly; the slack absorbs subpixel rounding.
+ const perRow = Math.max(1, Math.floor((width + gap) / (cardWidth + gap) + 0.01));
+ return Math.ceil(count / perRow) > COMPOSER_ATTACHMENT_MAX_ROWS;
+}
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 94a6330d6c5..57c3be828c0 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -311,17 +311,19 @@ class VisionImageAdapter implements AttachmentAdapter {
);
externalModelLabel = externalSelection.modelId;
}
- const unavailableReason = getImageInputUnavailableReason({
- activeModel,
- isExternalModel,
- externalSupportsVision,
- externalModelLabel,
- loadedIsMultimodal: state.loadedIsMultimodal,
- modelLoaded,
- loadError: state.lastModelLoadError,
- visionDisabledByUser: state.loadedVisionDisabledByUser,
- mmprojFallbackReason: state.mmprojFallbackReason,
- });
+ const unavailableReason = !modelLoaded
+ ? null
+ : getImageInputUnavailableReason({
+ activeModel,
+ isExternalModel,
+ externalSupportsVision,
+ externalModelLabel,
+ loadedIsMultimodal: state.loadedIsMultimodal,
+ modelLoaded,
+ loadError: state.lastModelLoadError,
+ visionDisabledByUser: state.loadedVisionDisabledByUser,
+ mmprojFallbackReason: state.mmprojFallbackReason,
+ });
if (unavailableReason) {
toast.error(unavailableReason);
throw new Error(unavailableReason);
diff --git a/studio/frontend/src/features/chat/video-attachment-adapter.ts b/studio/frontend/src/features/chat/video-attachment-adapter.ts
index a706380ca09..a33f7667d3b 100644
--- a/studio/frontend/src/features/chat/video-attachment-adapter.ts
+++ b/studio/frontend/src/features/chat/video-attachment-adapter.ts
@@ -37,12 +37,7 @@ export class VideoAttachmentAdapter implements AttachmentAdapter {
const activeModel = state.models.find((m) => m.id === checkpoint);
const modelLoaded = !!checkpoint && !state.modelLoading;
let unavailableReason: string | null = null;
- if (!modelLoaded) {
- // Mirror the image and audio gates: a failed load reads differently from no model picked.
- unavailableReason = state.lastModelLoadError
- ? "The last model failed to load. Check the server logs, then load a model before adding video."
- : "Load a model before adding video.";
- } else if (!activeModel?.hasVideoInput) {
+ if (modelLoaded && !activeModel?.hasVideoInput) {
const label =
activeModel?.name ||
externalModelLabel(checkpoint) ||
diff --git a/studio/frontend/src/features/library/index.ts b/studio/frontend/src/features/library/index.ts
index e12d63d6fd9..b3111e827b4 100644
--- a/studio/frontend/src/features/library/index.ts
+++ b/studio/frontend/src/features/library/index.ts
@@ -3,7 +3,7 @@
export { useLibraryChatHandoffStore } from "./chat-handoff-store";
export { useLibraryFavorites } from "./favorites-store";
-export { chatAboutMedia } from "./start-chat";
+export { chatAboutMedia, startLibraryChat } from "./start-chat";
export { revealInFolder, useRevealLabel } from "./reveal";
export { LIBRARY_TABS, validateLibrarySearch, type LibrarySearch, type LibraryTab } from "./search";
export {
diff --git a/studio/frontend/src/features/library/start-chat.ts b/studio/frontend/src/features/library/start-chat.ts
index 8414e58b214..dde2be3c75b 100644
--- a/studio/frontend/src/features/library/start-chat.ts
+++ b/studio/frontend/src/features/library/start-chat.ts
@@ -33,8 +33,12 @@ export function startLibraryChat(
): void {
const nonce = createModelConfigHandoffRequestId();
resetToNewChat();
- useLibraryChatHandoffStore.getState().offer(`single:${nonce}`, handoff);
- void navigate({ to: "/chat", search: { new: nonce } });
+ // Offered once the new chat is on screen: drained earlier it would attach to the old thread's composer.
+ void navigate({ to: "/chat", search: { new: nonce } }).then(() => {
+ requestAnimationFrame(() =>
+ useLibraryChatHandoffStore.getState().offer(`single:${nonce}`, handoff),
+ );
+ });
}
export const MAX_IMAGE_OR_TEXT_BYTES = 20 * 1024 * 1024;
diff --git a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
index d8ebed64786..4beb871ca53 100644
--- a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
+++ b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
@@ -277,14 +277,26 @@ export function usePersonalizationSync(enabled: boolean): void {
const keepLocalChatWidth =
remote.chatWidthSaved === false ||
remote.appearance.customization?.chatWidth === undefined;
+ const keepLocalComposerAttachments =
+ remote.composerAttachmentsSaved === false ||
+ remote.appearance.customization?.composerAttachments === undefined;
+ const keepLocalSentAttachments =
+ remote.sentAttachmentsSaved === false ||
+ remote.appearance.customization?.sentAttachments === undefined;
const nextCustomization = keepLocalCustomization
? localCustomization
- : keepLocalChatWidth
- ? {
- ...remoteCustomization,
+ : {
+ ...remoteCustomization,
+ ...(keepLocalChatWidth && {
chatWidth: localCustomization.chatWidth,
- }
- : remoteCustomization;
+ }),
+ ...(keepLocalComposerAttachments && {
+ composerAttachments: localCustomization.composerAttachments,
+ }),
+ ...(keepLocalSentAttachments && {
+ sentAttachments: localCustomization.sentAttachments,
+ }),
+ };
const remoteLanguage = remoteLanguagePreference(
remote.version,
remote.appearance.language,
diff --git a/studio/frontend/src/features/settings/api/personalization.ts b/studio/frontend/src/features/settings/api/personalization.ts
index ca2eac917a8..28c62af2bb2 100644
--- a/studio/frontend/src/features/settings/api/personalization.ts
+++ b/studio/frontend/src/features/settings/api/personalization.ts
@@ -31,6 +31,8 @@ export type Personalization = {
// client then keeps local values instead of the server-filled defaults.
customizationSaved: boolean;
chatWidthSaved?: boolean;
+ composerAttachmentsSaved?: boolean;
+ sentAttachmentsSaved?: boolean;
paletteSaved: boolean;
greetingSlothSaved: boolean;
};
@@ -51,6 +53,8 @@ export async function savePersonalization(
| "saved"
| "customizationSaved"
| "chatWidthSaved"
+ | "composerAttachmentsSaved"
+ | "sentAttachmentsSaved"
| "paletteSaved"
| "greetingSlothSaved"
>,
diff --git a/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx b/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx
index 0c50be1cd63..8f6bbbd1375 100644
--- a/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx
+++ b/studio/frontend/src/features/settings/components/appearance-custom-controls.tsx
@@ -49,7 +49,9 @@ import {
DEFAULT_CUSTOMIZATION,
MAX_IMPORTED_FONTS,
MAX_TOTAL_IMPORTED_FONT_DATA_URL_LENGTH,
+ type ComposerAttachmentsSetting,
type ReduceMotionSetting,
+ type SentAttachmentsSetting,
UI_FONT_SIZE_RANGE,
isDefaultCustomization,
useAppearanceCustomStore,
@@ -917,6 +919,75 @@ export function ChatWidthSelect() {
);
}
+const COMPOSER_ATTACHMENTS_OPTIONS: ComposerAttachmentsSetting[] = [
+ "cards",
+ "compact",
+];
+
+export function ComposerAttachmentsSelect() {
+ const t = useT();
+ const value = useAppearanceCustomStore(
+ (s) => s.customization.composerAttachments,
+ );
+ const patch = useAppearanceCustomStore((s) => s.patch);
+ return (
+ <Select
+ value={value}
+ onValueChange={(next) => {
+ if (next === "cards" || next === "compact") {
+ patch({ composerAttachments: next });
+ }
+ }}
+ >
+ <SelectTrigger
+ className="w-40"
+ aria-label={t("settings.appearance.custom.composerAttachments.label")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {COMPOSER_ATTACHMENTS_OPTIONS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {t(`settings.appearance.custom.composerAttachments.${option}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+const SENT_ATTACHMENTS_OPTIONS: SentAttachmentsSetting[] = ["auto", "list", "chips"];
+
+export function SentAttachmentsSelect() {
+ const t = useT();
+ const value = useAppearanceCustomStore((s) => s.customization.sentAttachments);
+ const patch = useAppearanceCustomStore((s) => s.patch);
+ return (
+ <Select
+ value={value}
+ onValueChange={(next) => {
+ if (next === "auto" || next === "list" || next === "chips") {
+ patch({ sentAttachments: next });
+ }
+ }}
+ >
+ <SelectTrigger
+ className="w-40"
+ aria-label={t("settings.appearance.custom.sentAttachments.label")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {SENT_ATTACHMENTS_OPTIONS.map((option) => (
+ <SelectItem key={option} value={option}>
+ {t(`settings.appearance.custom.sentAttachments.${option}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
/** Run settings track and field, sized like the other controls in the column. */
export function ContrastSliderRow() {
const t = useT();
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index aee7e7057a3..3b144a98118 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -69,6 +69,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.appearance.custom.headingFont.label",
"settings.appearance.custom.chatFont.label",
"settings.appearance.custom.chatWidth.label",
+ "settings.appearance.custom.composerAttachments.label",
+ "settings.appearance.custom.sentAttachments.label",
"settings.appearance.custom.codeFont.label",
"settings.appearance.custom.contrast.label",
"settings.appearance.custom.pointerCursors.label",
diff --git a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
index fb68c3961d7..f4c325f8f47 100644
--- a/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
+++ b/studio/frontend/src/features/settings/stores/appearance-custom-store.ts
@@ -39,6 +39,8 @@ const guardedLocalStorage: StateStorage = {
export type ReduceMotionSetting = "system" | "on" | "off";
export type ChatWidthSetting = "standard" | "wide" | "full";
+export type ComposerAttachmentsSetting = "cards" | "compact";
+export type SentAttachmentsSetting = "auto" | "list" | "chips";
export type CustomModeColors = {
accent: string | null;
@@ -236,6 +238,8 @@ export type AppearanceCustomization = {
headingFont: string | null;
chatFont: string | null;
chatWidth: ChatWidthSetting;
+ composerAttachments: ComposerAttachmentsSetting;
+ sentAttachments: SentAttachmentsSetting;
codeFont: string | null;
importedFonts: ImportedFont[];
/** UI font size in px. null = app default (15). */
@@ -269,6 +273,8 @@ export const DEFAULT_CUSTOMIZATION: AppearanceCustomization = {
headingFont: null,
chatFont: null,
chatWidth: "standard",
+ composerAttachments: "cards",
+ sentAttachments: "auto",
codeFont: null,
importedFonts: [],
uiFontSize: null,
@@ -483,6 +489,12 @@ export function sanitizeCustomization(value: unknown): AppearanceCustomization {
source.chatWidth === "wide" || source.chatWidth === "full"
? source.chatWidth
: "standard",
+ composerAttachments:
+ source.composerAttachments === "compact" ? "compact" : "cards",
+ sentAttachments:
+ source.sentAttachments === "list" || source.sentAttachments === "chips"
+ ? source.sentAttachments
+ : "auto",
codeFont: sanitizeFont(source.codeFont),
importedFonts: sanitizeImportedFonts(source.importedFonts),
uiFontSize: sanitizeSize(source.uiFontSize, UI_FONT_SIZE_RANGE),
diff --git a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx b/studio/frontend/src/features/settings/tabs/appearance-tab.tsx
index 1b892ef3aa7..4877b55e421 100644
--- a/studio/frontend/src/features/settings/tabs/appearance-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/appearance-tab.tsx
@@ -9,6 +9,8 @@ import {
ActiveColorControl,
ChatFontRow,
ChatWidthSelect,
+ ComposerAttachmentsSelect,
+ SentAttachmentsSelect,
CodeFontRow,
CodeFontSizeRow,
ContrastSliderRow,
@@ -131,6 +133,22 @@ export function AppearanceTab() {
>
<ChatWidthSelect />
</SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.custom.composerAttachments.label")}
+ description={t(
+ "settings.appearance.custom.composerAttachments.description",
+ )}
+ >
+ <ComposerAttachmentsSelect />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.appearance.custom.sentAttachments.label")}
+ description={t(
+ "settings.appearance.custom.sentAttachments.description",
+ )}
+ >
+ <SentAttachmentsSelect />
+ </SettingsRow>
<SettingsRow
label={t("settings.appearance.custom.pointerCursors.label")}
description={t(
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 6b1e3d75aa0..7420d3edb8a 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1311,6 +1311,21 @@ export const ar = {
wide: "واسع",
full: "العرض الكامل",
},
+ composerAttachments: {
+ label: "المرفقات في حقل الكتابة",
+ description:
+ "بطاقات كبيرة تُوسّع حقل الكتابة، أو صف مضغوط من المربعات الصغيرة.",
+ cards: "بطاقات كبيرة",
+ compact: "مربعات مضغوطة",
+ },
+ sentAttachments: {
+ label: "المرفقات في الرسائل المرسلة",
+ description:
+ "قائمة تعرض نوع كل ملف، أو شارات صغيرة. يتحوّل الوضع التلقائي إلى الشارات عند تجاوز ستة ملفات.",
+ auto: "تلقائي",
+ list: "قائمة",
+ chips: "شارات",
+ },
reset: "إعادة تعيين",
resetAll: "إعادة تعيين التخصيص",
preferencesTitle: "التفضيلات",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 4175e620884..c0ea1b73967 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1337,6 +1337,21 @@ export const de = {
wide: "Breit",
full: "Volle Breite",
},
+ composerAttachments: {
+ label: "Anhänge im Eingabefeld",
+ description:
+ "Große Karten, die das Eingabefeld vergrößern, oder eine kompakte Reihe von Kacheln.",
+ cards: "Große Karten",
+ compact: "Kompakte Kacheln",
+ },
+ sentAttachments: {
+ label: "Anhänge in gesendeten Nachrichten",
+ description:
+ "Eine Liste mit dem Typ jeder Datei oder kleine Chips. „Automatisch“ wechselt ab sieben Dateien zu Chips.",
+ auto: "Automatisch",
+ list: "Liste",
+ chips: "Chips",
+ },
reset: "Zurücksetzen",
resetAll: "Anpassungen zurücksetzen",
preferencesTitle: "Weitere Optionen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 6a2192318d1..6e4fd993d55 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1312,6 +1312,21 @@ export const en = {
wide: "Wide",
full: "Full width",
},
+ composerAttachments: {
+ label: "Attachments in the composer",
+ description:
+ "Large cards that grow the message box, or a compact row of tiles.",
+ cards: "Large cards",
+ compact: "Compact tiles",
+ },
+ sentAttachments: {
+ label: "Attachments in sent messages",
+ description:
+ "A list with each file's type, or small chips. Auto switches to chips past six files.",
+ auto: "Auto",
+ list: "List",
+ chips: "Chips",
+ },
reset: "Reset",
resetAll: "Reset customization",
preferencesTitle: "Preferences",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 30c71439231..f4f27bf6fc6 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1332,6 +1332,21 @@ export const es = {
wide: "Amplio",
full: "Ancho completo",
},
+ composerAttachments: {
+ label: "Adjuntos en el cuadro de texto",
+ description:
+ "Tarjetas grandes que agrandan el cuadro de texto o una fila compacta de miniaturas.",
+ cards: "Tarjetas grandes",
+ compact: "Miniaturas compactas",
+ },
+ sentAttachments: {
+ label: "Adjuntos en los mensajes enviados",
+ description:
+ "Una lista con el tipo de cada archivo o pequeñas etiquetas. Automático cambia a etiquetas con más de seis archivos.",
+ auto: "Automático",
+ list: "Lista",
+ chips: "Etiquetas",
+ },
reset: "Restablecer",
resetAll: "Restablecer la personalización",
preferencesTitle: "Preferencias",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 8ad40c02acb..0282bb81f23 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1336,6 +1336,21 @@ export const fr = {
wide: "Large",
full: "Pleine largeur",
},
+ composerAttachments: {
+ label: "Pièces jointes dans la zone de saisie",
+ description:
+ "De grandes cartes qui agrandissent la zone de saisie, ou une rangée compacte de vignettes.",
+ cards: "Grandes cartes",
+ compact: "Vignettes compactes",
+ },
+ sentAttachments: {
+ label: "Pièces jointes dans les messages envoyés",
+ description:
+ "Une liste indiquant le type de chaque fichier, ou de petites étiquettes. Le mode automatique passe aux étiquettes au-delà de six fichiers.",
+ auto: "Automatique",
+ list: "Liste",
+ chips: "Étiquettes",
+ },
reset: "Réinitialiser",
resetAll: "Réinitialiser la personnalisation",
preferencesTitle: "Préférences",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index bae630548e1..ad60edcd3a6 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1314,6 +1314,21 @@ export const hi = {
wide: "चौड़ा",
full: "पूरी चौड़ाई",
},
+ composerAttachments: {
+ label: "इनपुट बॉक्स में अटैचमेंट",
+ description:
+ "बड़े कार्ड जो इनपुट बॉक्स को बड़ा करते हैं, या टाइलों की एक कॉम्पैक्ट पंक्ति।",
+ cards: "बड़े कार्ड",
+ compact: "कॉम्पैक्ट टाइलें",
+ },
+ sentAttachments: {
+ label: "भेजे गए संदेशों में अटैचमेंट",
+ description:
+ "हर फ़ाइल के प्रकार के साथ एक सूची, या छोटे चिप्स। छह से ज़्यादा फ़ाइलें होने पर ऑटो चिप्स पर स्विच हो जाता है।",
+ auto: "ऑटो",
+ list: "सूची",
+ chips: "चिप्स",
+ },
reset: "रीसेट करें",
resetAll: "कस्टमाइज़ेशन रीसेट करें",
preferencesTitle: "प्राथमिकताएं",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 57e9fb0dd07..c43c8467104 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1297,6 +1297,21 @@ export const it = {
wide: "Ampia",
full: "Larghezza piena",
},
+ composerAttachments: {
+ label: "Allegati nel campo di testo",
+ description:
+ "Schede grandi che ingrandiscono il campo di testo, oppure una riga compatta di riquadri.",
+ cards: "Schede grandi",
+ compact: "Riquadri compatti",
+ },
+ sentAttachments: {
+ label: "Allegati nei messaggi inviati",
+ description:
+ "Un elenco con il tipo di ogni file, oppure piccole etichette. Automatico passa alle etichette oltre i sei file.",
+ auto: "Automatico",
+ list: "Elenco",
+ chips: "Etichette",
+ },
reset: "Ripristina",
resetAll: "Ripristina la personalizzazione",
preferencesTitle: "Preferenze",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index e295671aa38..0a7cc301173 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1293,6 +1293,21 @@ export const ja = {
wide: "広い",
full: "全幅",
},
+ composerAttachments: {
+ label: "入力欄の添付ファイル",
+ description:
+ "入力欄を広げる大きなカード、またはコンパクトなタイルの列で表示します。",
+ cards: "大きなカード",
+ compact: "コンパクトなタイル",
+ },
+ sentAttachments: {
+ label: "送信済みメッセージの添付ファイル",
+ description:
+ "各ファイルの種類を示すリスト、または小さなチップで表示します。自動では 7 件以上でチップに切り替わります。",
+ auto: "自動",
+ list: "リスト",
+ chips: "チップ",
+ },
reset: "リセット",
resetAll: "カスタマイズをリセット",
preferencesTitle: "環境設定",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 96bdb5563f6..38421f5b12b 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1307,6 +1307,21 @@ export const ko = {
wide: "넓게",
full: "전체 너비",
},
+ composerAttachments: {
+ label: "입력창의 첨부 파일",
+ description:
+ "입력창을 키우는 큰 카드 또는 작은 타일 한 줄로 표시합니다.",
+ cards: "큰 카드",
+ compact: "작은 타일",
+ },
+ sentAttachments: {
+ label: "보낸 메시지의 첨부 파일",
+ description:
+ "각 파일의 형식을 보여 주는 목록 또는 작은 칩으로 표시합니다. 자동은 파일이 6개를 넘으면 칩으로 바뀝니다.",
+ auto: "자동",
+ list: "목록",
+ chips: "칩",
+ },
reset: "초기화",
resetAll: "사용자 지정 초기화",
preferencesTitle: "환경설정",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index d980a59bf8c..a34b70cffff 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1324,6 +1324,21 @@ export const ptBR = {
wide: "Ampla",
full: "Largura total",
},
+ composerAttachments: {
+ label: "Anexos no campo de texto",
+ description:
+ "Cartões grandes que aumentam o campo de texto ou uma fileira compacta de miniaturas.",
+ cards: "Cartões grandes",
+ compact: "Miniaturas compactas",
+ },
+ sentAttachments: {
+ label: "Anexos nas mensagens enviadas",
+ description:
+ "Uma lista com o tipo de cada arquivo ou pequenas etiquetas. O modo automático muda para etiquetas com mais de seis arquivos.",
+ auto: "Automático",
+ list: "Lista",
+ chips: "Etiquetas",
+ },
reset: "Redefinir",
resetAll: "Redefinir personalização",
preferencesTitle: "Preferências",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index b87625275dd..09b670faf33 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1316,6 +1316,21 @@ export const ru = {
wide: "Широкая",
full: "Полная ширина",
},
+ composerAttachments: {
+ label: "Вложения в поле ввода",
+ description:
+ "Крупные карточки, увеличивающие поле ввода, или компактный ряд плиток.",
+ cards: "Крупные карточки",
+ compact: "Компактные плитки",
+ },
+ sentAttachments: {
+ label: "Вложения в отправленных сообщениях",
+ description:
+ "Список с типом каждого файла или небольшие метки. В автоматическом режиме при более чем шести файлах используются метки.",
+ auto: "Авто",
+ list: "Список",
+ chips: "Метки",
+ },
reset: "Сбросить",
resetAll: "Сбросить настройки оформления",
preferencesTitle: "Параметры",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index ae9c88d041d..281d82bb5aa 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1294,6 +1294,21 @@ export const zhCN = {
wide: "宽",
full: "全宽",
},
+ composerAttachments: {
+ label: "输入框中的附件",
+ description:
+ "使用会撑大输入框的大卡片,或紧凑的一行小图块。",
+ cards: "大卡片",
+ compact: "紧凑图块",
+ },
+ sentAttachments: {
+ label: "已发送消息中的附件",
+ description:
+ "显示各文件类型的列表,或小标签。超过六个文件时,“自动”会切换为小标签。",
+ auto: "自动",
+ list: "列表",
+ chips: "小标签",
+ },
reset: "重置",
resetAll: "重置自定义",
preferencesTitle: "偏好设置",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 6fe0d22befb..e2b3dcf5039 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -4755,6 +4755,24 @@ html.force-reduced-motion .sidebar-section-drop-line {
background: oklch(0.67 0 0 / 0.5);
}
+/* Unlayered like the rules above, which a utility class could not outrank. */
+.aui-composer-attachment-cards[data-layout="strip"] {
+ scrollbar-width: none;
+}
+
+.aui-composer-attachment-cards[data-layout="strip"]::-webkit-scrollbar {
+ display: none;
+}
+
+/* The negative margin cancels the surface's p-2.5; the clip keeps cards inside its rounded top corners. */
+.unsloth-composer-surface .aui-composer-attachment-cards[data-layout="strip"] {
+ margin-inline: -0.625rem;
+ width: calc(100% + 1.25rem);
+ padding-inline: 1rem;
+ scroll-padding-inline: 1rem;
+ clip-path: inset(-0.625rem 0 0 0 round 28px 28px 0 0);
+}
+
/* Avoid iOS Safari focus zoom. Important in the base layer, because an important
declaration in an earlier layer beats important utilities such as text-ui-13!. */
@layer base {
diff --git a/studio/frontend/tests/attachment-source-cost.test.ts b/studio/frontend/tests/attachment-source-cost.test.ts
index e859fb5a5be..49719ee3d47 100644
--- a/studio/frontend/tests/attachment-source-cost.test.ts
+++ b/studio/frontend/tests/attachment-source-cost.test.ts
@@ -86,7 +86,48 @@ test("the audio data URL is built in the dialog, not on every attachment tile",
true,
"the audio data URL is built outside AttachmentAudioBody",
);
- assert.match(preview, /<DialogContent[\s\S]*<AttachmentAudioBody/);
+ assert.match(preview, /<AttachmentViewer[\s\S]*<AttachmentAudioBody/);
+ const viewer = readSrc("components/assistant-ui/attachment-document-dialog.tsx");
+ assert.match(viewer, /\{open && children\}/);
+});
+
+test("the attachment selector resolves a video from the composer and from a sent message", () => {
+ const part = { type: "file", filename: "clip.mp4", data: "A".repeat(1024), mimeType: "video/mp4" };
+ const state = {
+ attachment: { type: "file", name: "clip.mp4", contentType: "video/mp4", content: [part] },
+ };
+ const sent = selectAttachmentSource(state);
+ assert.equal(sent.kind, "video");
+ assert.equal(Object.is(sent.video, part), true, "the selector copied the clip's payload");
+ assert.equal(sent.audio, undefined);
+
+ const file = new File(["x"], "clip.webm", { type: "video/webm" });
+ const unsent = { attachment: { type: "file", name: "clip.webm", contentType: "video/webm", file } };
+ const composer = selectAttachmentSource(unsent);
+ assert.equal(composer.kind, "video");
+ assert.equal(composer.file, file);
+
+ const listen = selectAttachmentSource({
+ attachment: {
+ type: "file",
+ name: "talk.mp4",
+ contentType: "audio/mp4",
+ content: [{ type: "audio" as const, audio: { data: "AAA", format: "wav" } }],
+ },
+ });
+ assert.equal(listen.kind, "audio");
+ assert.equal(listen.video, undefined);
+});
+
+test("the video data URL is built in the viewer, not on every attachment tile", () => {
+ const hook = readSrc("components/assistant-ui/use-attachment-source.ts");
+ assert.match(hook, /video: source\.video/);
+ assert.doesNotMatch(hook, /attachmentVideoSrc/);
+ const preview = readSrc("components/assistant-ui/attachment-preview.tsx");
+ const body = preview.slice(preview.indexOf("const AttachmentVideoBody"));
+ assert.match(body, /attachmentVideoSrc\(source\.video\)/);
+ assert.match(preview, /<AttachmentViewer[\s\S]*<AttachmentVideoBody/);
+ assert.match(preview, /source\.kind === "video"[\s\S]*?<AttachmentVideoDialog/);
});
// A plain text/document attachment must keep working: the control that has to
diff --git a/studio/frontend/tests/chat-attachment-display.test.ts b/studio/frontend/tests/chat-attachment-display.test.ts
new file mode 100644
index 00000000000..2ec47e6a897
--- /dev/null
+++ b/studio/frontend/tests/chat-attachment-display.test.ts
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { attachedMediaUnavailableReason } from "../src/features/chat/lib/attached-media-gate.ts";
+import {
+ ATTACHMENT_KIND_ICON_CLASS,
+ attachmentFileKind,
+ attachmentKindLabel,
+} from "../src/features/chat/lib/attachment-file-kind.ts";
+import {
+ COMPOSER_ATTACHMENT_MAX_ROWS,
+ composerAttachmentsOverflow,
+ SENT_ATTACHMENT_LIST_MAX,
+ sentAttachmentLayout,
+} from "../src/features/chat/lib/attachment-layout.ts";
+import {
+ DEFAULT_CUSTOMIZATION,
+ sanitizeCustomization,
+} from "../src/features/settings/stores/appearance-custom-store.ts";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const ATTACHMENT = await readSrcAsync("components/assistant-ui/attachment.tsx");
+
+test("each file kind is read off the name, with a decisive MIME type first", () => {
+ const cases: Array<[string, string, string]> = [
+ ["invoice_INV-6.pdf", "", "pdf"],
+ ["scan", "application/pdf", "pdf"],
+ ["Rain 2.6-1.mp3", "audio/mpeg", "audio"],
+ ["Book.m4a", "", "audio"],
+ ["clip.mov", "", "video"],
+ ["Untitled document.docx", "", "document"],
+ ["results.csv", "text/csv", "spreadsheet"],
+ ["deck.pptx", "", "presentation"],
+ ["flappy-bird(1)(1).html", "", "web"],
+ ["glm-5-next-sgl.patch", "", "text"],
+ ["README.md", "text/markdown", "text"],
+ ["train.py", "text/x-python", "code"],
+ ["Dockerfile", "", "code"],
+ ["weights.zip", "application/zip", "archive"],
+ ["photo.HEIC", "", "image"],
+ ["mystery.bin", "application/octet-stream", "file"],
+ ["notes", "text/plain", "text"],
+ ];
+ for (const [name, mime, kind] of cases) {
+ assert.equal(attachmentFileKind(name, mime), kind, `${name} (${mime || "no type"})`);
+ }
+ assert.equal(attachmentFileKind("recording.txt", "audio/wav"), "audio");
+ assert.equal(attachmentFileKind("x.constructor", ""), "file");
+});
+
+test("the common kinds carry the colors people recognize", () => {
+ assert.match(ATTACHMENT_KIND_ICON_CLASS.pdf, /red/);
+ assert.match(ATTACHMENT_KIND_ICON_CLASS.audio, /violet/);
+ assert.match(ATTACHMENT_KIND_ICON_CLASS.document, /blue/);
+ assert.match(ATTACHMENT_KIND_ICON_CLASS.spreadsheet, /emerald/);
+ assert.match(ATTACHMENT_KIND_ICON_CLASS.presentation, /orange/);
+});
+
+test("a sent file is labeled by its kind, or by its extension when unknown", () => {
+ assert.equal(attachmentKindLabel("pdf", "a.pdf"), "PDF");
+ assert.equal(attachmentKindLabel("audio", "a.mp3"), "Audio");
+ assert.equal(attachmentKindLabel("document", "a.docx"), "Document");
+ assert.equal(attachmentKindLabel("file", "model.safetensors"), "File");
+ assert.equal(attachmentKindLabel("file", "blob.bin"), "BIN");
+ assert.equal(attachmentKindLabel("file", "noextension"), "File");
+});
+
+test("Auto lists up to six sent files, then collapses them to chips", () => {
+ assert.equal(SENT_ATTACHMENT_LIST_MAX, 6);
+ assert.equal(sentAttachmentLayout("auto", 1), "list");
+ assert.equal(sentAttachmentLayout("auto", 6), "list");
+ assert.equal(sentAttachmentLayout("auto", 7), "chips");
+ assert.equal(sentAttachmentLayout("list", 40), "list");
+ assert.equal(sentAttachmentLayout("chips", 1), "chips");
+});
+
+test("composer cards wrap for two rows, then become one scrolling strip", () => {
+ assert.equal(COMPOSER_ATTACHMENT_MAX_ROWS, 2);
+ const fifth = (724 - 4 * 8) / 5;
+ assert.equal(composerAttachmentsOverflow(10, 724, fifth, 8), false);
+ assert.equal(composerAttachmentsOverflow(11, 724, fifth, 8), true);
+ assert.equal(composerAttachmentsOverflow(10, 724, fifth + 0.004, 8), false);
+ assert.equal(composerAttachmentsOverflow(7, 300, 105, 8), true);
+ assert.equal(composerAttachmentsOverflow(0, 724, fifth, 8), false);
+ assert.equal(composerAttachmentsOverflow(20, 724, 0, 8), false);
+ assert.match(
+ ATTACHMENT,
+ /const CARD_SLOT =\n\s*"shrink-0 w-\[calc\(\(100%_-_var\(--spacing\)\*8\)\/5\)\] min-w-\[calc\(7rem\*var\(--ui-space-scale,1\)\)\]";/,
+ );
+ assert.match(ATTACHMENT, /const CARD_SIZE = "h-\[calc\(7rem\*var\(--ui-space-scale,1\)\)\] w-full";/);
+ assert.match(ATTACHMENT, /className=\{cn\("aui-attachment-root aui-attachment-card group\/attachment-card relative", CARD_SLOT\)\}/);
+ assert.match(ATTACHMENT, /variant === "card" && cn\("group\/attachment-card", CARD_SLOT\)/);
+ assert.match(ATTACHMENT, /aui-composer-attachment-cards [^"]*\bgap-2\b/);
+});
+
+test("cards keep their hairline edge in dark mode", () => {
+ const edge = /const CARD_EDGE =\n\s*"([^"]*)";/.exec(ATTACHMENT)?.[1] ?? "";
+ const surface = /const CARD_SURFACE =\n\s*"([^"]*)";/.exec(ATTACHMENT)?.[1] ?? "";
+ assert.match(edge, /^border border-\[/);
+ assert.doesNotMatch(edge + surface, /dark:/);
+});
+
+test("the strip is laid out through the DOM, never through React state", () => {
+ const strip = ATTACHMENT.slice(
+ ATTACHMENT.indexOf("const ComposerAttachmentCards: FC"),
+ ATTACHMENT.indexOf("export const ComposerAttachments: FC"),
+ );
+ assert.match(strip, /el\.dataset\.layout = next/);
+ assert.doesNotMatch(strip, /useState/);
+ assert.match(strip, /\}, \[count\]\);/);
+ assert.match(strip, /new ResizeObserver\(layout\)/);
+});
+
+test("sent attachments split images from files by type, with stable component maps", () => {
+ assert.match(
+ ATTACHMENT,
+ /const SENT_IMAGE_COMPONENTS = \{\n\s*Image: SentImageTile,\n\s*Document: NoAttachment,\n\s*File: NoAttachment,\n\};/,
+ );
+ assert.match(
+ ATTACHMENT,
+ /const SENT_FILE_COMPONENTS = \{\n\s*Image: NoAttachment,\n\s*Document: SentFileItem,\n\s*File: SentFileItem,\n\};/,
+ );
+ const sent = ATTACHMENT.slice(ATTACHMENT.indexOf("const SentFileItem: FC"));
+ assert.match(sent, /<AttachmentPreviewDialog redactFromReload=\{false\}>/);
+});
+
+test("both attachment settings default to the new look and reject anything else", () => {
+ assert.equal(DEFAULT_CUSTOMIZATION.composerAttachments, "cards");
+ assert.equal(DEFAULT_CUSTOMIZATION.sentAttachments, "auto");
+ const saved = sanitizeCustomization({
+ composerAttachments: "compact",
+ sentAttachments: "chips",
+ });
+ assert.equal(saved.composerAttachments, "compact");
+ assert.equal(saved.sentAttachments, "chips");
+ const junk = sanitizeCustomization({
+ composerAttachments: "huge",
+ sentAttachments: 7,
+ });
+ assert.equal(junk.composerAttachments, "cards");
+ assert.equal(junk.sentAttachments, "auto");
+});
+
+test("audio or video attached before a model loaded is checked when sent", () => {
+ const listener = { hasAudioInput: true, hasVideoInput: false };
+ const textOnly = { hasAudioInput: false, hasVideoInput: false };
+ const base = { checkpoint: "unsloth/model", modelLabel: "Model" };
+ assert.equal(
+ attachedMediaUnavailableReason({ ...base, activeModel: listener, audio: true, video: false }),
+ null,
+ );
+ assert.match(
+ attachedMediaUnavailableReason({ ...base, activeModel: textOnly, audio: true, video: false }) ?? "",
+ /^Model cannot accept audio\./,
+ );
+ assert.match(
+ attachedMediaUnavailableReason({ ...base, activeModel: listener, audio: false, video: true }) ?? "",
+ /^Model cannot accept video\./,
+ );
+ assert.ok(
+ attachedMediaUnavailableReason({ ...base, activeModel: undefined, audio: true, video: false }),
+ );
+ assert.equal(
+ attachedMediaUnavailableReason({ ...base, activeModel: textOnly, audio: false, video: false }),
+ null,
+ );
+ assert.equal(
+ attachedMediaUnavailableReason({
+ ...base,
+ checkpoint: null,
+ activeModel: textOnly,
+ audio: true,
+ video: false,
+ }),
+ null,
+ );
+});
+
+test("attaching no longer needs a loaded model, only a capable one when one is loaded", async () => {
+ const audio = await readSrcAsync("features/chat/audio-attachment-adapter.ts");
+ const video = await readSrcAsync("features/chat/video-attachment-adapter.ts");
+ const provider = await readSrcAsync("features/chat/runtime-provider.tsx");
+ assert.ok(!audio.includes("Load a model before adding audio files."));
+ assert.ok(!video.includes("Load a model before adding video."));
+ assert.match(provider, /const unavailableReason = !modelLoaded\n\s*\? null/);
+});
+
+test("every attachment opens in the Library's viewer, from the composer and from a message", async () => {
+ const preview = await readSrcAsync("components/assistant-ui/attachment-preview.tsx");
+ const viewer = await readSrcAsync("components/assistant-ui/attachment-document-dialog.tsx");
+ for (const dialog of [
+ "AttachmentImageDialog",
+ "AttachmentTextDialog",
+ "AttachmentAudioDialog",
+ "AttachmentVideoDialog",
+ ]) {
+ const body = preview.slice(preview.indexOf(`const ${dialog}: FC`));
+ assert.match(body, /^[\s\S]*?<AttachmentViewer\n/, dialog);
+ }
+ assert.match(viewer, /const DocumentDialog[\s\S]*?<AttachmentViewer\n/);
+ assert.match(viewer, /export const AttachmentViewer[\s\S]*?<MediaViewer\n/);
+ assert.doesNotMatch(preview, /<DialogContent/);
+ assert.match(viewer, /load && !redactFromReload/);
+ assert.match(viewer, /startLibraryChat\(navigate, \{ files: \[file\] \}\)/);
+ assert.match(preview, /<ArtifactHtmlFrame code=\{preview\.text\}/);
+});
+
+test("files handed to a new chat wait until it is on screen", async () => {
+ const start = await readSrcAsync("features/library/start-chat.ts");
+ const fn = start.slice(start.indexOf("export function startLibraryChat("));
+ const navigate = fn.indexOf('navigate({ to: "/chat"');
+ const offer = fn.indexOf(".offer(");
+ assert.ok(navigate !== -1 && offer > navigate, "the files are offered before the new chat opens");
+ assert.match(fn, /\.then\(\(\) => \{\n\s*requestAnimationFrame\(/);
+});
+
+test("an image card in the composer has no border or fill; file cards keep both", () => {
+ const card = ATTACHMENT.slice(
+ ATTACHMENT.indexOf("const ComposerAttachmentCard: FC"),
+ ATTACHMENT.indexOf("const SentAttachmentLayoutContext"),
+ );
+ assert.match(card, /const src = useAttachmentImageSrc\(\);/);
+ assert.match(card, /!src && CARD_EDGE,\n\s*!src && CARD_SURFACE,/);
+ assert.match(card, /<CardImageOrBody name=\{name\} kind=\{kind\} src=\{src\} \/>/);
+});
+
+test("an attachment's viewer mounts on first open, not with every tile", async () => {
+ const viewer = await readSrcAsync("components/assistant-ui/attachment-document-dialog.tsx");
+ assert.match(viewer, /const \[mounted, setMounted\] = useState\(open\);\n\s*if \(open && !mounted\) setMounted\(true\);/);
+ assert.match(viewer, /\{mounted && \(\n\s*<MediaViewer/);
+});
+
+test("the viewer's chat and download report a file they could not read", async () => {
+ const viewer = await readSrcAsync("components/assistant-ui/attachment-document-dialog.tsx");
+ assert.match(viewer, /\.catch\(\(\) => toast\.error\(`Could not read \$\{name\}`\)\)/);
+ assert.match(viewer, /\.catch\(\(\) => toast\.error\(t\("library\.toast\.downloadFailed", \{ name \}\)\)\)/);
+});
+
+test("a sent text file downloads whole, not the capped preview", async () => {
+ const preview = await readSrcAsync("components/assistant-ui/attachment-preview.tsx");
+ assert.match(preview, /new Blob\(\[attachmentBodyText\(sentText\)\]/);
+ assert.doesNotMatch(preview, /new Blob\(\[ready\.text\]/);
+});
+
+test("a composer clip reads as a video, not by its .mp4 name as audio", () => {
+ assert.match(ATTACHMENT, /if \(isVideoAttachment\(attachment\)\) return "Video";\n\s*return isAudioAttachment\(/);
+ assert.match(ATTACHMENT, /isVideo\n\s*\? Video01Icon\n\s*: isAudioAttachment\(name, contentType\)/);
+});
+
+test("a sent document shown from its stored text downloads and chats as a .txt", async () => {
+ const dialog = await readSrcAsync("components/assistant-ui/attachment-document-dialog.tsx");
+ assert.match(
+ dialog,
+ /saveAs=\{\n\s*loaded\?\.plain !== undefined\n\s*\? \{ name: `\$\{source\.name\.replace\(\/\\\.\[\^\.\]\+\$\/, ""\)\}\.txt`, contentType: "text\/plain" \}/,
+ );
+ assert.match(dialog, /const name = saveAs\?\.name \?\? \(source\.name \|\| "attachment"\);/);
+ assert.match(dialog, /downloadFile\(blob, name, contentType \|\| undefined\)/);
+});
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index a3a9351e218..749b3c6353b 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -2749,7 +2749,11 @@ test("only the gate's own tokens are read as a refusal", () => {
test("the gate's pulse is tagged where it is fired and read where it matters", () => {
// Neither end is exercised by a unit test: the adapter's gate is deep inside a run, and
// the keeper's real signal reads a zustand store. Pinned at both ends instead.
- const gate = CHAT_ADAPTER.slice(CHAT_ADAPTER.indexOf("const imageGateReason ="));
+ const gate = CHAT_ADAPTER.slice(CHAT_ADAPTER.indexOf("const blockAttachmentRun ="));
+ assert.match(
+ CHAT_ADAPTER.slice(CHAT_ADAPTER.indexOf("const imageGateReason =")),
+ /if \(imageGateReason\) \{\n\s*blockAttachmentRun\(imageGateReason\);/,
+ );
assert.match(
gate,
/const gateOwner = createImageGateRunOwner\(\)/,
diff --git a/studio/frontend/tests/connected-model-row-actions.test.ts b/studio/frontend/tests/connected-model-row-actions.test.ts
index 49010fb7548..ff23cfc0c81 100644
--- a/studio/frontend/tests/connected-model-row-actions.test.ts
+++ b/studio/frontend/tests/connected-model-row-actions.test.ts
@@ -103,7 +103,11 @@ test("modality comes from the resolvers the app already has", () => {
audioAdapter,
/const activeModel = state\.models\.find\(\(m\) => m\.id === checkpoint\);/,
);
- assert.match(audioAdapter, /\} else if \(!activeModel\?\.hasAudioInput\) \{/);
+ assert.match(audioAdapter, /if \(modelLoaded && !activeModel\?\.hasAudioInput\) \{/);
+ assert.match(
+ readSrc("features/chat/lib/attached-media-gate.ts"),
+ /if \(audio && !activeModel\?\.hasAudioInput\) \{/,
+ );
// So the filter drops its Audio option rather than offering one that matches nothing.
assert.match(
pickers,
diff --git a/studio/frontend/tests/mmproj-fallback.test.ts b/studio/frontend/tests/mmproj-fallback.test.ts
index 175b21fbd33..1deb6c90392 100644
--- a/studio/frontend/tests/mmproj-fallback.test.ts
+++ b/studio/frontend/tests/mmproj-fallback.test.ts
@@ -86,7 +86,7 @@ function sourceBetween(path: string, start: string, end: string): string {
test("attachment and send gates forward projector fallback state", () => {
const attachmentGate = sourceBetween(
"../src/features/chat/runtime-provider.tsx",
- "const unavailableReason = getImageInputUnavailableReason({",
+ ": getImageInputUnavailableReason({",
"if (unavailableReason)",
);
assert.match(
diff --git a/studio/frontend/tests/personalization-locale-hydration.test.ts b/studio/frontend/tests/personalization-locale-hydration.test.ts
index 9a65559b5eb..dcb4a3df586 100644
--- a/studio/frontend/tests/personalization-locale-hydration.test.ts
+++ b/studio/frontend/tests/personalization-locale-hydration.test.ts
@@ -189,6 +189,8 @@ function setup(
localCustomization?: Record<string, unknown>;
remote?: ReturnType<typeof remotePersonalization> & {
chatWidthSaved?: boolean;
+ composerAttachmentsSaved?: boolean;
+ sentAttachmentsSaved?: boolean;
};
} = {},
) {
@@ -431,3 +433,67 @@ test("an older server without chat width metadata preserves local width", async
assert.equal(app.saves[0]?.appearance.customization.chatWidth, "wide");
app.host.unmount();
});
+
+function attachmentsRemote(saved: boolean | undefined, customization: Record<string, string>) {
+ const remote = remotePersonalization("auto");
+ return {
+ ...remote,
+ version: 5,
+ chatWidthSaved: true,
+ composerAttachmentsSaved: saved,
+ sentAttachmentsSaved: saved,
+ appearance: {
+ ...remote.appearance,
+ customization: { chatWidth: "standard", uiFont: "Georgia", ...customization },
+ },
+ };
+}
+
+test("legacy attachment display preserves and uploads the local choice", async () => {
+ const app = setup("stalled", {
+ localCustomization: { composerAttachments: "compact", sentAttachments: "chips" },
+ remote: attachmentsRemote(false, { composerAttachments: "cards", sentAttachments: "auto" }),
+ });
+ app.render();
+ await settle();
+ app.render();
+
+ assert.equal(app.customization().composerAttachments, "compact");
+ assert.equal(app.customization().sentAttachments, "chips");
+ assert.equal(app.customization().uiFont, "Georgia");
+ app.runTimers();
+ await settle();
+ assert.equal(app.saves.length, 1);
+ assert.equal(app.saves[0]?.appearance.customization.composerAttachments, "compact");
+ assert.equal(app.saves[0]?.appearance.customization.sentAttachments, "chips");
+ app.host.unmount();
+});
+
+test("saved attachment display overrides local without another save", async () => {
+ const app = setup("stalled", {
+ localCustomization: { composerAttachments: "compact", sentAttachments: "chips" },
+ remote: attachmentsRemote(true, { composerAttachments: "cards", sentAttachments: "list" }),
+ });
+ app.render();
+ await settle();
+ app.render();
+ assert.equal(app.customization().composerAttachments, "cards");
+ assert.equal(app.customization().sentAttachments, "list");
+ app.runTimers();
+ await settle();
+ assert.equal(app.saves.length, 0);
+ app.host.unmount();
+});
+
+test("an older server without attachment display keys preserves the local choice", async () => {
+ const app = setup("stalled", {
+ localCustomization: { composerAttachments: "compact", sentAttachments: "list" },
+ remote: attachmentsRemote(undefined, {}),
+ });
+ app.render();
+ await settle();
+ app.render();
+ assert.equal(app.customization().composerAttachments, "compact");
+ assert.equal(app.customization().sentAttachments, "list");
+ app.host.unmount();
+});
diff --git a/studio/frontend/tests/reload-snapshot.test.ts b/studio/frontend/tests/reload-snapshot.test.ts
index 5c783d3ad3f..8ac8a198bc8 100644
--- a/studio/frontend/tests/reload-snapshot.test.ts
+++ b/studio/frontend/tests/reload-snapshot.test.ts
@@ -1418,14 +1418,24 @@ test("carries live form state, except what sensitive fields hide", () => {
"AttachmentTextDialog",
"AttachmentAudioDialog",
]) {
+ const body = attachmentPreviewSource.slice(
+ attachmentPreviewSource.indexOf(`const ${dialog}: FC`),
+ );
assert.match(
- attachmentPreviewSource,
- new RegExp(
- `${dialog}[\\s\\S]*?data-reload-snapshot-sensitive=\\{redactFromReload \\? "" : undefined\\}`,
- ),
+ body,
+ /^[\s\S]*?<AttachmentViewer[\s\S]*?redactFromReload=\{redactFromReload\}/,
`${dialog} must redact its portaled content`,
);
}
+ const viewer = readSrc("components/assistant-ui/attachment-document-dialog.tsx");
+ assert.match(
+ viewer,
+ /export const AttachmentViewer[\s\S]*?<MediaViewer[\s\S]*?redactFromReload=\{redactFromReload\}/,
+ );
+ assert.match(
+ readSrc("components/media-viewer.tsx"),
+ /data-reload-snapshot-sensitive=\{redactFromReload \? "" : undefined\}/,
+ );
});
test("keeps native select options that paint the closed control label", () => {