Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
open every attachment type in a preview modal (#8655)
Maheswar Kumare0ae1311a7f2
diff --git a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx b/studio/frontend/src/components/assistant-ui/attachment-preview.tsxnew file mode 100644index 00000000000..c084f70db6e--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/attachment-preview.tsx@@ -0,0 +1,360 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"use client";++import { AudioPlayer } from "@/components/assistant-ui/audio-player";+import {+ type AttachmentSource,+ useAttachmentSource,+} from "@/components/assistant-ui/use-attachment-source";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Spinner } from "@/components/ui/spinner";+import {+ type AttachmentText,+ attachmentAudioSrc,+ attachmentTextLanguage,+ countAttachmentTextLines,+ parseAttachmentText,+ readAttachmentText,+ truncateAttachmentPreviewText,+} from "@/features/chat";+import { formatBytes } from "@/features/hub";+import { MAX_HIGHLIGHT_CHARS, codeFence } from "@/lib/markdown-plugins";+import { cn } from "@/lib/utils";+import { code as codePlugin } from "@streamdown/code";+import {+ type FC,+ type PropsWithChildren,+ 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 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 AttachmentPreviewTrigger: FC<PropsWithChildren> = ({ children }) => {+ return (+ <DialogTrigger+ className="aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50"+ asChild={true}+ >+ {children}+ </DialogTrigger>+ );+};++const AttachmentImageDialog: FC<PropsWithChildren<{ src: string }>> = ({+ children,+ src,+}) => {+ 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+ 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>+ );+};++// Extraction only starts once the dialog has been opened: parsing every PDF or+// spreadsheet in a thread up front would stall the composer.+const useAttachmentTextPreview = (+ enabled: boolean,+ file: File | undefined,+ name: string,+ contentType: string | undefined,+ text: string | undefined,+): TextPreviewState => {+ const [fileState, setFileState] = useState<TextPreviewState>({+ status: "loading",+ });+ // Unwrapping runs on open too: a thread can hold several large sent+ // attachments, and their payloads are scanned in full to strip the wrapper.+ const sentState = useMemo(+ (): TextPreviewState =>+ enabled+ ? { status: "ready", ...parseAttachmentText(text ?? "") }+ : { status: "loading" },+ [enabled, text],+ );++ useEffect(() => {+ if (!(enabled && file)) {+ return;+ }+ let active = true;+ readAttachmentText(file, name, contentType)+ .then((result) => {+ if (active) {+ setFileState({ status: "ready", ...result });+ }+ })+ .catch(() => {+ if (active) {+ setFileState({ status: "error" });+ }+ });+ return () => {+ active = false;+ };+ }, [enabled, file, name, contentType]);++ 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}+ >+ {markdown}+ </Streamdown>+ </div>+ );+};++const AttachmentTextDialog: FC<+ PropsWithChildren<{ source: AttachmentSource }>+> = ({ children, source }) => {+ const [opened, setOpened] = useState(false);+ const state = useAttachmentTextPreview(+ opened,+ source.file,+ source.name,+ source.contentType,+ source.text,+ );+ 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],+ );+ 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+ // 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,+ `${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]);++ return (+ <Dialog+ onOpenChange={(isOpen) => {+ if (isOpen) {+ setOpened(true);+ }+ }}+ >+ <AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>+ <DialogContent 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."}+ </div>+ )}+ </div>+ </DialogContent>+ </Dialog>+ );+};++/**+ * The player, and the only place a sent clip's data URL is built.+ *+ * 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.+ */+const AttachmentAudioBody: FC<{ source: AttachmentSource }> = ({ source }) => {+ const src = useMemo(() => {+ if (source.src) {+ return source.src;+ }+ return source.audio+ ? attachmentAudioSrc(source.audio, source.contentType, source.name)+ : undefined;+ }, [source.src, source.audio, source.contentType, source.name]);++ return src ? (+ <AudioPlayer src={src} filename={source.name || "attachment.wav"} />+ ) : null;+};++const AttachmentAudioDialog: FC<+ PropsWithChildren<{ source: AttachmentSource }>+> = ({ children, source }) => {+ return (+ <Dialog>+ <AttachmentPreviewTrigger>{children}</AttachmentPreviewTrigger>+ <DialogContent 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>+ );+};++export const AttachmentPreviewDialog: FC<PropsWithChildren> = ({+ children,+}) => {+ const source = useAttachmentSource();++ if (source.kind === "image") {+ return source.src ? (+ <AttachmentImageDialog src={source.src}>{children}</AttachmentImageDialog>+ ) : (+ children+ );+ }++ if (source.kind === "audio") {+ return source.src || source.audio ? (+ <AttachmentAudioDialog source={source}>{children}</AttachmentAudioDialog>+ ) : (+ children+ );+ }++ if (!(source.file || source.text)) {+ return children;+ }++ return (+ <AttachmentTextDialog source={source}>{children}</AttachmentTextDialog>+ );+};diff --git a/studio/frontend/src/components/assistant-ui/attachment-selection.ts b/studio/frontend/src/components/assistant-ui/attachment-selection.tsnew file mode 100644index 00000000000..4645ba1c0ea--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/attachment-selection.ts@@ -0,0 +1,71 @@+// 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 { isAudioAttachment } from "@/features/chat/attachment-content";++export type AttachmentPreviewKind = "image" | "audio" | "text";++export type AttachmentAudioPart = { data: string; format: string };++type AttachmentContentPart = {+ type: string;+ text?: string;+ image?: string;+ audio?: AttachmentAudioPart;+};++export type AttachmentSelection = {+ kind: AttachmentPreviewKind;+ name: string;+ contentType: string | undefined;+ file: File | undefined;+ image: string | undefined;+ audio: AttachmentAudioPart | undefined;+ text: string | undefined;+};++/**+ * Picks the parts a preview can show out of the attachment in scope.+ *+ * useAuiState reads through useSyncExternalStore, so this runs on every store+ * notification and on every render, and useShallow gates the re-render rather+ * than the call. It therefore only selects; the audio data URL is derived from+ * `audio` afterwards, because concatenating the base64 payload here and then+ * comparing that string in useShallow costs the whole payload every time.+ */+export const selectAttachmentSource = ({+ attachment,+}: {+ attachment: {+ type?: string;+ name: string;+ content?: AttachmentContentPart[];+ };+}): AttachmentSelection => {+ const parts = attachment.content ?? [];+ const file = (attachment as { file?: File }).file;+ const contentType =+ file?.type ||+ (attachment as { contentType?: string }).contentType ||+ undefined;+ const audio = parts.find((part) => part.type === "audio")?.audio;+ const isImage = attachment.type === "image";+ const isAudio =+ !isImage && (!!audio || isAudioAttachment(attachment.name, contentType));+ const text = parts+ .filter((part) => part.type === "text")+ .map((part) => part.text)+ .join("\n");++ return {+ kind: isImage ? "image" : isAudio ? "audio" : "text",+ name: attachment.name,+ contentType,+ file,+ image: isImage+ ? parts.find((part) => part.type === "image")?.image+ : undefined,+ audio: isImage ? undefined : audio,+ text: text || undefined,+ };+};diff --git a/studio/frontend/src/components/assistant-ui/attachment.tsx b/studio/frontend/src/components/assistant-ui/attachment.tsxindex ff5e7282c6c..eec648089b6 100644--- a/studio/frontend/src/components/assistant-ui/attachment.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment.tsx@@ -4,10 +4,11 @@"use client";// 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 { useAttachmentImageSrc } from "@/components/assistant-ui/use-attachment-source";import {Dialog,- DialogClose,DialogContent,DialogTitle,DialogTrigger,@@ -19,6 +20,7 @@ import {} from "@/components/ui/tooltip";import {PASTED_TEXT_PREVIEW_MAX_CHARS,+ isAudioAttachment,isPastedTextContent,isPastedTextFile,pastedTextContentBytes,@@ -27,6 +29,7 @@ import {} from "@/features/chat";import { formatBytes } from "@/features/hub";import { cn } from "@/lib/utils";+import { useShallow } from "zustand/shallow";import {AttachmentPrimitive,ComposerPrimitive,@@ -49,111 +52,9 @@ import {useRef,useState,} from "react";-import { useShallow } from "zustand/shallow";--const useFileSrc = (file: File | undefined): string | undefined => {- const [objectUrl, setObjectUrl] = useState<string | undefined>(undefined);-- useEffect(() => {- if (!file) {- setObjectUrl(undefined);- return;- }- const url = URL.createObjectURL(file);- setObjectUrl(url);- return () => URL.revokeObjectURL(url);- }, [file]);-- return objectUrl;-};--const useAttachmentSrc = (): string | undefined => {- const { file, src } = useAuiState(- useShallow(({ attachment }): { file?: File; src?: string } => {- if (attachment.type !== "image") {- return {};- }- if (attachment.file) {- return { file: attachment.file };- }- const src = attachment.content?.filter((c) => c.type === "image")[0]- ?.image;- if (!src) {- return {};- }- return { src };- }),- );-- return useFileSrc(file) ?? src;-};--type AttachmentPreviewProps = {- src: string;-};--const AttachmentPreview: FC<AttachmentPreviewProps> = ({ 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 AttachmentPreviewDialog: FC<PropsWithChildren> = ({ children }) => {- const src = useAttachmentSrc();-- if (!src) {- return children;- }-- return (- <Dialog>- <DialogTrigger- className="aui-attachment-preview-trigger cursor-pointer transition-colors hover:bg-accent/50"- asChild={true}- >- {children}- </DialogTrigger>- {/* Chrome-free lightbox: the image floats on the dimmed backdrop with- no dialog panel, and the close button sits in the screen corner. */}- <DialogContent- 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">- <AttachmentPreview src={src} />- </span>- </div>- </DialogContent>- </Dialog>- );-};--const AUDIO_ATTACHMENT_RE = /\.(wav|mp3|m4a|ogg|oga|flac|webm|mp4|aac)$/i;--const isAudioAttachment = (name: string | undefined, contentType: string) =>- /^audio\//i.test(contentType) || AUDIO_ATTACHMENT_RE.test(name ?? "");const AttachmentThumb: FC = () => {- const src = useAttachmentSrc();+ const src = useAttachmentImageSrc();const name = useAuiState(({ attachment }) => attachment.name);const contentType = useAuiState(({ attachment }) =>@@ -175,7 +76,9 @@ const AttachmentThumb: FC = () => {return (<div className="flex h-full w-full items-center justify-center"><HugeiconsIcon- icon={isAudioAttachment(name, contentType) ? AudioWave01Icon : File02Icon}+ icon={+ isAudioAttachment(name, contentType) ? AudioWave01Icon : File02Icon+ }strokeWidth={2}className="size-6 text-muted-foreground"/>@@ -373,6 +276,7 @@ const AttachmentUI: FC = () => {const pastedText = usePastedTextAttachment();const isImage = useAuiState(({ attachment }) => attachment.type === "image");+ const attachmentId = useAuiState(({ attachment }) => attachment.id);const name = useAuiState(({ attachment }) => attachment.name);const typeLabel = useAuiState(({ attachment }) => {const type = attachment.type;@@ -401,6 +305,7 @@ const AttachmentUI: FC = () => {if (pastedText) {return (<PastedTextAttachmentUI+ key={attachmentId}attachment={pastedText}isComposer={isComposer}name={name ?? "Pasted text"}@@ -411,6 +316,7 @@ const AttachmentUI: FC = () => {return (<Tooltip><AttachmentPrimitive.Root+ key={attachmentId}className={cn("aui-attachment-root relative",isImage &&diff --git a/studio/frontend/src/components/assistant-ui/audio-player.tsx b/studio/frontend/src/components/assistant-ui/audio-player.tsxindex 2052c318081..c067af06397 100644--- a/studio/frontend/src/components/assistant-ui/audio-player.tsx+++ b/studio/frontend/src/components/assistant-ui/audio-player.tsx@@ -13,9 +13,13 @@ import { type FC, useRef, useState } from "react";interface AudioPlayerProps {src: string;+ filename?: string;}-export const AudioPlayer: FC<AudioPlayerProps> = ({ src }) => {+export const AudioPlayer: FC<AudioPlayerProps> = ({+ src,+ filename = "generated-audio.wav",+}) => {const audioRef = useRef<HTMLAudioElement>(null);const [isPlaying, setIsPlaying] = useState(false);const [progress, setProgress] = useState(0);@@ -26,10 +30,15 @@ export const AudioPlayer: FC<AudioPlayerProps> = ({ src }) => {if (!audio) return;if (isPlaying) {audio.pause();- } else {- audio.play();+ setIsPlaying(false);+ return;}- setIsPlaying(!isPlaying);+ // An uploaded file can carry a codec the webview cannot decode, so the+ // button only flips once playback has actually started.+ audio.play().then(+ () => setIsPlaying(true),+ () => setIsPlaying(false),+ );};const handleTimeUpdate = () => {@@ -58,7 +67,7 @@ export const AudioPlayer: FC<AudioPlayerProps> = ({ src }) => {};const handleDownload = () => {- void downloadUrl(src, "generated-audio.wav").catch((error) => {+ void downloadUrl(src, filename).catch((error) => {if (!isDownloadCancelled(error)) {toast.error("Could not save audio.");}@@ -79,6 +88,7 @@ export const AudioPlayer: FC<AudioPlayerProps> = ({ src }) => {onTimeUpdate={handleTimeUpdate}onLoadedMetadata={handleLoadedMetadata}onEnded={handleEnded}+ onError={() => setIsPlaying(false)}preload="metadata"/><Buttondiff --git a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsxindex b5d7e613f31..fc5f04b3dfa 100644--- a/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-code-cell.tsx@@ -4,13 +4,13 @@"use client";import { copyToClipboard } from "@/lib/copy-to-clipboard";-import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";+import { MAX_HIGHLIGHT_CHARS, codeFence } from "@/lib/markdown-plugins";import { downloadFile, isDownloadCancelled } from "@/lib/native-files";+import { Tick02Icon } from "@/lib/tick-icon";import { toast } from "@/lib/toast";+import { HugeiconsIcon } from "@hugeicons/react";import { code as codePlugin } from "@streamdown/code";import { CopyIcon, DownloadIcon } from "lucide-react";-import { Tick02Icon } from "@/lib/tick-icon";-import { HugeiconsIcon } from "@hugeicons/react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Streamdown } from "streamdown";@@ -86,15 +86,6 @@ function DownloadBtn({ code, name }: { code: string; name: string }) {);}-/** A fence longer than any backtick run in the code, so a script containing ``` cannot end it early. */-function fenceFor(source: string): string {- const longest = (source.match(/`+/g) ?? []).reduce(- (max, run) => Math.max(max, run.length),- 0,- );- return "`".repeat(Math.max(3, longest + 1));-}-/** Syntax-highlighted code via Streamdown + shiki. Always in the DOM as plain monospace, but* shiki only tokenizes once the block nears the viewport, so a long transcript does not* highlight every script up front. Immediate where IntersectionObserver is missing. */@@ -108,7 +99,7 @@ function HighlightedCode({plain?: boolean;}) {const markdown = useMemo(() => {- const fence = fenceFor(source);+ const fence = codeFence(source);return `${fence}${language}\n${source}\n${fence}`;}, [source, language]);const containerRef = useRef<HTMLDivElement>(null);diff --git a/studio/frontend/src/components/assistant-ui/use-attachment-source.ts b/studio/frontend/src/components/assistant-ui/use-attachment-source.tsnew file mode 100644index 00000000000..2ca1b540201--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/use-attachment-source.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"use client";++import {+ type AttachmentAudioPart,+ type AttachmentPreviewKind,+ selectAttachmentSource,+} from "@/components/assistant-ui/attachment-selection";+import { useAuiState } from "@assistant-ui/react";+import { useEffect, useState } from "react";+import { useShallow } from "zustand/shallow";++export type { AttachmentPreviewKind };++export type AttachmentSource = {+ kind: AttachmentPreviewKind;+ name: string;+ contentType: string | undefined;+ file: File | undefined;+ src: string | undefined;+ audio: AttachmentAudioPart | undefined;+ text: string | undefined;+};++const useFileSrc = (file: File | undefined): string | undefined => {+ const [objectUrl, setObjectUrl] = useState<string | undefined>(undefined);++ useEffect(() => {+ if (!file) {+ setObjectUrl(undefined);+ return;+ }+ const url = URL.createObjectURL(file);+ setObjectUrl(url);+ return () => URL.revokeObjectURL(url);+ }, [file]);++ return objectUrl;+};++// Resolves what a preview can show for the attachment in scope: a composer+// attachment still holds its File, a sent one only the content parts.+export const useAttachmentSource = (): AttachmentSource => {+ const source = useAuiState(useShallow(selectAttachmentSource));++ const fileSrc = useFileSrc(source.kind === "text" ? undefined : source.file);++ // audio passes through unjoined: the payload is MAX_AUDIO_SIZE of base64 and every tile mounts this hook+ return {+ kind: source.kind,+ name: source.name,+ contentType: source.contentType,+ file: source.file,+ src: fileSrc ?? source.image,+ audio: source.audio,+ text: source.text,+ };+};++export const useAttachmentImageSrc = (): string | undefined => {+ const source = useAttachmentSource();+ return source.kind === "image" ? source.src : undefined;+};diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsnew file mode 100644index 00000000000..d2096a6deb0--- /dev/null+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -0,0 +1,772 @@+// 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 { type Unzipped, strFromU8, unzipSync, zipSync } from "fflate";++import {+ MAX_OPEN_DOCUMENT_ARCHIVE_BYTES,+ MAX_OPEN_DOCUMENT_XML_BYTES,+ OPEN_DOCUMENT_SPREADSHEET_MIME,+ OPEN_DOCUMENT_TEXT_MIME,+ readOpenDocumentAttachmentContent,+} from "./open-document";++export type AttachmentTextLabel = "PDF" | "DOCX" | "HTML" | "ODS" | "ODT";++export type AttachmentText = {+ label: AttachmentTextLabel | null;+ text: string;+ // True when the file was only read up to the preview cap, so the dialog can+ // say so even if the extracted text ends up short.+ truncated: boolean;+};++const AUDIO_ATTACHMENT_RE = /\.(wav|mp3|m4a|ogg|oga|flac|webm|mp4|aac)$/i;+const AUDIO_MIME_RE = /^audio\//i;+const PDF_ATTACHMENT_RE = /\.pdf$/i;+const DOCX_ATTACHMENT_RE = /\.docx$/i;+const HTML_ATTACHMENT_RE = /\.x?html?$/i;+const OPEN_DOCUMENT_ATTACHMENT_RE = /\.(ods|odt)$/i;+const LABELLED_ATTACHMENT_TEXT_RE = /^\[(PDF|DOCX|HTML|ODS|ODT): [^\n]*\]\n/;+const ATTACHMENT_TAG_OPEN_RE = /^<attachment name=[^\n]*>\n/;+const ATTACHMENT_TAG_CLOSE = "\n</attachment>";+// Both wrappers start on the first line, so only a prefix is matched against.+const MAX_ATTACHMENT_WRAPPER_LENGTH = 4096;+const DOCX_MIME =+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document";+// Shared with TextAttachmentAdapter so the preview applies the same first-match+// dispatch before falling through to the document-specific adapters.+export const TEXT_ATTACHMENT_ACCEPT = [+ "text/plain,text/markdown,text/csv,text/xml,text/json,text/css",+ "application/json,application/xml,image/svg+xml",+ ".txt,.text,.log,.md,.markdown,.mdx,.rst,.csv,.tsv",+ ".json,.jsonl,.ndjson,.xml,.yaml,.yml,.toml,.ini,.cfg,.conf,.env,.properties",+ ".css,.scss,.sass,.less,.svg",+ ".js,.jsx,.mjs,.cjs,.ts,.tsx,.py,.pyi,.ipynb,.rb,.php,.go,.rs,.java,.kt,.kts,.scala,.swift",+ ".c,.h,.cc,.cpp,.hpp,.cxx,.cs,.m,.mm",+ ".sh,.bash,.zsh,.fish,.ps1,.bat,.lua,.pl,.pm,.r,.jl,.dart,.vue,.svelte,.astro",+ ".sql,.graphql,.gql,.proto,.tf,.tfvars,.gradle,.dockerfile,.makefile,.cmake,.diff,.patch",+].join(",");+// mammoth picks the parts it parses out of the relationships, not out of the+// filenames, so a target may be called anything ("payload.bin") and still be+// inflated and parsed as XML, while an .xml part nothing points at (customXml,+// the glossary document) is never opened at all. The bound therefore follows+// docx-reader.js: the two package parts it always reads, the main document and+// its relationships, and the five parts resolved out of those relationships,+// each with mammoth's own "word/<name>.xml" fallback. Image targets stay lazy+// and are never read by extractRawText.+const DOCX_CONTENT_TYPES_PART = "[Content_Types].xml";+const DOCX_PACKAGE_RELATIONSHIPS = "_rels/.rels";+const DOCX_RELATIONSHIP_NAMESPACE =+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";+const DOCX_MAIN_DOCUMENT_TYPE = `${DOCX_RELATIONSHIP_NAMESPACE}officeDocument`;+const DOCX_RELATED_PART_NAMES = [+ "comments",+ "endnotes",+ "footnotes",+ "numbering",+ "styles",+];+// readXmlFileWithBody opens the relationships of every part it reads a body+// from, so these three carry a .rels part of their own.+const DOCX_BODY_PART_NAMES = new Set(["comments", "endnotes", "footnotes"]);+const DOCX_MAIN_DOCUMENT_FALLBACK = "word/document.xml";+// A <Relationship> tag, with the element prefix mammoth's namespace mapping+// accepts, and skipping any ">" that sits inside an attribute value.+const DOCX_RELATIONSHIP_TAG_RE =+ /<(?:[^\s/>"'=]+:)?Relationship(?=[\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>/g;+// Attribute names are matched by consuming whole name="value" pairs, so a+// value that itself contains Target= cannot be mistaken for an attribute.+// mammoth reads child.attributes.Target, which a prefixed r:Target never+// populates, so prefixed names are deliberately not accepted here.+const XML_ATTRIBUTE_RE = /([^\s/>"'=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;+/** Non-element markup: a `<Relationship>` inside a comment, CDATA section or processing instruction is text to mammoth's parser, and each ends at its first delimiter the way XML ends it. */+const XML_NON_ELEMENT_RE =+ /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>/g;+const XML_ENTITY_RE = /&(?:#(\d+)|#[xX]([\da-fA-F]+)|([a-zA-Z]+));/g;+const XML_NAMED_ENTITIES: Record<string, string> = {+ amp: "&",+ lt: "<",+ gt: ">",+ quot: '"',+ apos: "'",+};+/**+ * Ceiling on everything a DOCX unpacks to, and the reason mammoth never sees+ * the file the user chose.+ *+ * jszip takes each part's size from the central directory and inflates the part+ * in full before anything can reject it, so an entry declaring 1 KB that+ * expands to 1 GB exhausts the webview. fflate allocates every entry at its+ * declared size and stops there, so mammoth is handed a repack of fflate's+ * output and can only inflate what has already been bounded here.+ */+const MAX_DOCX_UNPACKED_BYTES = 2 * MAX_OPEN_DOCUMENT_ARCHIVE_BYTES;+const AUDIO_EXTENSION_MIMES: Record<string, string> = {+ wav: "audio/wav",+ mp3: "audio/mpeg",+ m4a: "audio/mp4",+ mp4: "audio/mp4",+ ogg: "audio/ogg",+ oga: "audio/ogg",+ flac: "audio/flac",+ aac: "audio/aac",+ webm: "audio/webm",+};+// Node.TEXT_NODE and Node.ELEMENT_NODE, spelled out so the extractor runs where the DOM globals do not.+const TEXT_NODE = 3;+const ELEMENT_NODE = 1;+/** The elements that end a line of rendered text; everything else stays inline. */+const HTML_BLOCK_TAGS = new Set([+ "address",+ "article",+ "aside",+ "blockquote",+ "dd",+ "div",+ "dl",+ "dt",+ "fieldset",+ "figcaption",+ "figure",+ "footer",+ "form",+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "header",+ "hr",+ "li",+ "main",+ "nav",+ "ol",+ "p",+ "pre",+ "section",+ "table",+ "tbody",+ "td",+ "tfoot",+ "th",+ "thead",+ "tr",+ "ul",+]);+/** The extensions the text and html previews colour, mapped to shiki ids; one missing here previews unstyled. */+const CODE_ATTACHMENT_LANGUAGES: Record<string, string> = {+ astro: "astro",+ bash: "shellscript",+ bat: "bat",+ c: "c",+ cc: "cpp",+ cfg: "ini",+ cjs: "javascript",+ cmake: "cmake",+ conf: "ini",+ cpp: "cpp",+ cs: "csharp",+ css: "css",+ cxx: "cpp",+ dart: "dart",+ diff: "diff",+ dockerfile: "docker",+ env: "dotenv",+ fish: "fish",+ go: "go",+ gql: "graphql",+ gradle: "groovy",+ graphql: "graphql",+ h: "c",+ hpp: "cpp",+ htm: "html",+ html: "html",+ ini: "ini",+ java: "java",+ jl: "julia",+ js: "javascript",+ json: "json",+ jsonl: "json",+ jsx: "jsx",+ kt: "kotlin",+ kts: "kotlin",+ less: "less",+ lua: "lua",+ makefile: "make",+ md: "markdown",+ markdown: "markdown",+ mdx: "mdx",+ mjs: "javascript",+ ndjson: "json",+ php: "php",+ pl: "perl",+ pm: "perl",+ properties: "ini",+ proto: "proto",+ ps1: "powershell",+ py: "python",+ pyi: "python",+ r: "r",+ rb: "ruby",+ rs: "rust",+ rst: "rst",+ sass: "sass",+ scala: "scala",+ scss: "scss",+ sh: "shellscript",+ sql: "sql",+ svelte: "svelte",+ svg: "xml",+ swift: "swift",+ tf: "terraform",+ tfvars: "terraform",+ toml: "toml",+ ts: "typescript",+ tsx: "tsx",+ vue: "vue",+ xml: "xml",+ yaml: "yaml",+ yml: "yaml",+ zsh: "shellscript",+};+// Long attachments still have to render inside a dialog, so the preview stops+// well before the point where a single <pre> stalls the webview.+const MAX_PREVIEW_TEXT_LENGTH = 200_000;+// Text and HTML have no size limit at upload, so a preview reads a bounded slice+// instead of the whole file. Five bytes per character keeps the slice past the+// character cap for any UTF-8 input, so truncation is still detected.+const MAX_PREVIEW_TEXT_BYTES = MAX_PREVIEW_TEXT_LENGTH * 5;++/** Own-property lookup: an extension or entity named "constructor" would otherwise resolve to a member of Object.prototype. */+function lookUp(table: Record<string, string>, key: string): string | undefined {+ return Object.hasOwn(table, key) ? table[key] : undefined;+}++export function isAudioAttachment(+ name: string | undefined,+ contentType: string | undefined,+): boolean {+ return (+ AUDIO_MIME_RE.test(contentType ?? "") ||+ AUDIO_ATTACHMENT_RE.test(name ?? "")+ );+}++// The audio part keeps only the coarse format the backend needs ("mp3" or+// "wav"), so the content type wins, then the extension for uploads the browser+// typed as empty, and the part format only as a last resort.+export function attachmentAudioSrc(+ audio: { data: string; format: string },+ contentType: string | undefined,+ name: string | undefined,+): string {+ const extension = name?.toLowerCase().split(".").pop() ?? "";+ const mime = AUDIO_MIME_RE.test(contentType ?? "")+ ? (contentType as string)+ : (lookUp(AUDIO_EXTENSION_MIMES, extension) ??+ (audio.format === "mp3" ? "audio/mpeg" : "audio/wav"));+ return `data:${mime};base64,${audio.data}`;+}++export function isPdfAttachment(+ name: string | undefined,+ contentType: string | undefined,+): boolean {+ return (+ contentType === "application/pdf" || PDF_ATTACHMENT_RE.test(name ?? "")+ );+}++export function isDocxAttachment(+ name: string | undefined,+ contentType: string | undefined,+): boolean {+ return contentType === DOCX_MIME || DOCX_ATTACHMENT_RE.test(name ?? "");+}++export function isHtmlAttachment(+ name: string | undefined,+ contentType: string | undefined,+): boolean {+ return contentType === "text/html" || HTML_ATTACHMENT_RE.test(name ?? "");+}++export function isOpenDocumentAttachment(+ name: string | undefined,+ contentType: string | undefined,+): boolean {+ return (+ contentType === OPEN_DOCUMENT_SPREADSHEET_MIME ||+ contentType === OPEN_DOCUMENT_TEXT_MIME ||+ OPEN_DOCUMENT_ATTACHMENT_RE.test(name ?? "")+ );+}++// CompositeAttachmentAdapter selects the first accept string that matches.+// Text comes before the document-specific adapters, so previews must apply the+// same MIME-or-extension match before looking at PDF/DOCX/HTML names.+function isTextAttachment(+ name: string,+ contentType: string | undefined,+): boolean {+ const extension = `.${name.split(".").pop()?.toLowerCase() ?? ""}`;+ const mime = contentType?.toLowerCase() ?? "";+ return TEXT_ATTACHMENT_ACCEPT.split(",").some((entry) => {+ const accepted = entry.trim().toLowerCase();+ if (accepted.startsWith(".")) {+ return accepted === extension;+ }+ if (accepted.endsWith("/*")) {+ return mime.startsWith(`${accepted.slice(0, -1)}`);+ }+ return accepted === mime;+ });+}++// unpdf and mammoth decode the whole file on the main thread, so both refuse a+// document past the ceiling the OpenDocument path already enforces, and refuse+// it before the read rather than after. The adapters call this from add() as+// well: the composer clears its text and attachments before it awaits send(),+// so a throw there loses the typed message along with the file.+export function getDocumentAttachmentSizeError(+ file: File,+ label: "PDF" | "DOCX",+): string | null {+ return file.size > MAX_OPEN_DOCUMENT_ARCHIVE_BYTES+ ? `${label} file is too large: ${file.name}`+ : null;+}++export function assertDocumentAttachmentSize(+ file: File,+ label: "PDF" | "DOCX",+): void {+ const error = getDocumentAttachmentSizeError(file, label);+ if (error) {+ throw new Error(error);+ }+}++// mammoth's joinPath: an absolute target drops the base path.+function joinDocxPath(basePath: string, target: string): string {+ const joined = target.startsWith("/")+ ? target+ : [basePath, target].filter(Boolean).join("/");+ return joined.startsWith("/") ? joined.slice(1) : joined;+}++// XML attribute values are entity-decoded by the parser mammoth hands the+// relationships to, so a target only matches the archive once decoded.+function decodeXmlEntities(value: string): string {+ return value.replace(XML_ENTITY_RE, (match, decimal, hex, name) => {+ const code = decimal+ ? Number.parseInt(decimal, 10)+ : hex+ ? Number.parseInt(hex, 16)+ : Number.NaN;+ if (Number.isNaN(code)) {+ return lookUp(XML_NAMED_ENTITIES, name) ?? match;+ }+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;+ });+}++// The relationship parts are XML, but only their targets are needed, so they+// are scanned rather than parsed: DOMParser is not available where this also+// runs under test, and a malformed rels file is mammoth's to report. The scan+// accepts every attribute form mammoth's parser resolves (both quote styles,+// entity-encoded values, a prefixed element name, ">" inside a value), so a+// crafted rels file cannot hide a target from the bound below.+function readDocxXmlTargets(+ rels: Uint8Array | undefined,+ basePath: string,+): Map<string, string[]> {+ const targets = new Map<string, string[]>();+ if (!rels) {+ return targets;+ }+ const markup = strFromU8(rels).replace(XML_NON_ELEMENT_RE, "");+ for (const tag of markup.match(DOCX_RELATIONSHIP_TAG_RE) ?? []) {+ let type: string | undefined;+ let target: string | undefined;+ for (const [, name, quoted, apostrophed] of tag.matchAll(+ XML_ATTRIBUTE_RE,+ )) {+ const value = quoted ?? apostrophed ?? "";+ if (name === "Type") {+ type = decodeXmlEntities(value);+ } else if (name === "Target") {+ target = decodeXmlEntities(value);+ }+ }+ if (type && target) {+ const resolved = targets.get(type) ?? [];+ resolved.push(joinDocxPath(basePath, target));+ targets.set(type, resolved);+ }+ }+ return targets;+}++// The .rels part that names the XML parts of the part at `path`.+function docxRelationshipsPath(path: string): string {+ const cut = path.lastIndexOf("/");+ const dirname = cut === -1 ? "" : path.slice(0, cut);+ const basename = path.slice(cut + 1);+ return joinDocxPath(dirname, `_rels/${basename}.rels`);+}++type DocxArchive = {+ entries: Unzipped;+ /** Every name the central directory declares, unpacked entries included, so a target resolves the way findPartPath resolves it. */+ names: Set<string>;+ oversized: Set<string>;+};++/**+ * Inflates the archive under fflate's declared-size allocation.+ *+ * An entry past the XML ceiling is left out rather than refused: mammoth opens+ * the package parts and whatever the relationships point at, so a large+ * unreferenced part, custom XML or an embedded image, must still preview.+ * `assertDocxPartSizes` refuses the ones mammoth would have parsed.+ */+function unpackDocxEntries(filename: string, bytes: Uint8Array): DocxArchive {+ const names = new Set<string>();+ const oversized = new Set<string>();+ let unpacked = 0;++ const entries = unzipSync(bytes, {+ filter: (entry) => {+ names.add(entry.name);+ if (entry.originalSize > MAX_OPEN_DOCUMENT_XML_BYTES) {+ oversized.add(entry.name);+ return false;+ }+ unpacked += entry.originalSize;+ if (unpacked > MAX_DOCX_UNPACKED_BYTES) {+ throw new Error(`DOCX file is too large: ${filename}`);+ }+ return true;+ },+ });++ return { entries, names, oversized };+}++/**+ * Refuses the parts mammoth goes on to parse when they exceed the XML ceiling.+ *+ * mammoth takes no entry filter, so the set is resolved the way findPartPaths+ * resolves it: the main document out of "_rels/.rels" and the styles,+ * numbering and note parts out of the document's own .rels, each falling back+ * to a fixed name when no target resolves. Both sides read the same bytes,+ * since mammoth is handed the repack of these entries.+ */+function assertDocxPartSizes(filename: string, archive: DocxArchive): void {+ const { entries, names, oversized } = archive;+ const bound = (path: string) => {+ if (oversized.has(path)) {+ throw new Error(`DOCX XML file is too large: ${filename}:${path}`);+ }+ };+ // findPartPath keeps the first target that exists, and every target it+ // discards is one mammoth never opens.+ const resolve = (targets: string[] | undefined, fallback: string) =>+ targets?.find((path) => names.has(path)) ?? fallback;++ bound(DOCX_CONTENT_TYPES_PART);+ bound(DOCX_PACKAGE_RELATIONSHIPS);+ const mainDocument = resolve(+ readDocxXmlTargets(entries[DOCX_PACKAGE_RELATIONSHIPS], "").get(+ DOCX_MAIN_DOCUMENT_TYPE,+ ),+ DOCX_MAIN_DOCUMENT_FALLBACK,+ );+ bound(mainDocument);+ const mainDocumentRels = docxRelationshipsPath(mainDocument);+ bound(mainDocumentRels);++ const cut = mainDocument.lastIndexOf("/");+ const documentTargets = readDocxXmlTargets(+ entries[mainDocumentRels],+ cut === -1 ? "" : mainDocument.slice(0, cut),+ );+ for (const name of DOCX_RELATED_PART_NAMES) {+ const path = resolve(+ documentTargets.get(`${DOCX_RELATIONSHIP_NAMESPACE}${name}`),+ `word/${name}.xml`,+ );+ bound(path);+ if (DOCX_BODY_PART_NAMES.has(name)) {+ bound(docxRelationshipsPath(path));+ }+ }+}++/** The archive mammoth is given: fflate's own output, so a part that lies about its size arrives truncated rather than inflated in full. */+export function repackDocxAttachmentArchive(+ filename: string,+ bytes: Uint8Array,+): Uint8Array {+ const archive = unpackDocxEntries(filename, bytes);+ assertDocxPartSizes(filename, archive);+ return zipSync(archive.entries, { level: 0 });+}++/**+ * The bytes of a view, as an ArrayBuffer, without copying when it owns one.+ *+ * jszip reads the whole buffer it is handed and looks for the end-of-directory+ * record at its tail, so a view that does not span its buffer would arrive as a+ * corrupt archive. zipSync happens to return an exact-fit array today, which is+ * not something its API promises.+ */+function toArrayBuffer(view: Uint8Array): ArrayBuffer {+ const spansBuffer =+ view.byteOffset === 0 && view.byteLength === view.buffer.byteLength;+ return (+ spansBuffer+ ? view.buffer+ : view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength)+ ) as ArrayBuffer;+}++function isDocxSizeError(error: unknown): boolean {+ return (+ error instanceof Error &&+ (error.message.startsWith("DOCX file is too large:") ||+ error.message.startsWith("DOCX XML file is too large:"))+ );+}++/**+ * The verdict add() needs before the attachment exists.+ *+ * The composer clears its text and attachments before it awaits send(), so a+ * DOCX that only fails there discards the typed message along with the file.+ * add() calls this instead, the way the audio adapter checks its own ceiling.+ */+export async function getDocxAttachmentError(+ file: File,+): Promise<string | null> {+ const sizeError = getDocumentAttachmentSizeError(file, "DOCX");+ if (sizeError) {+ return sizeError;+ }+ try {+ const bytes = new Uint8Array(await file.arrayBuffer());+ assertDocxPartSizes(file.name, unpackDocxEntries(file.name, bytes));+ } catch (error) {+ return isDocxSizeError(error)+ ? (error as Error).message+ : `DOCX file could not be read: ${file.name}`;+ }+ return null;+}++export async function extractPdfAttachmentText(file: File): Promise<string> {+ assertDocumentAttachmentSize(file, "PDF");+ const [{ extractText, getDocumentProxy }, buffer] = await Promise.all([+ import("unpdf"),+ file.arrayBuffer().then((bytes) => new Uint8Array(bytes)),+ ]);+ const pdf = await getDocumentProxy(buffer);+ try {+ // per page rather than merged: mergePages folds every newline pdf.js marks into one space+ const { text } = await extractText(pdf);+ return normalizeExtractedText(text.join("\n\n"));+ } finally {+ await pdf.destroy();+ }+}++export async function extractDocxAttachmentText(file: File): Promise<string> {+ assertDocumentAttachmentSize(file, "DOCX");+ const [{ default: mammoth }, buffer] = await Promise.all([+ import("mammoth"),+ file.arrayBuffer(),+ ]);+ const repacked = repackDocxAttachmentArchive(+ file.name,+ new Uint8Array(buffer),+ );+ const { value } = await mammoth.extractRawText({+ arrayBuffer: toArrayBuffer(repacked),+ });+ return value;+}++export function extractHtmlAttachmentText(html: string): string {+ const doc = new DOMParser().parseFromString(html, "text/html");+ for (const el of doc.querySelectorAll("script, style, noscript, template")) {+ el.remove();+ }+ return normalizeExtractedText(collectHtmlBlockText(doc.body));+}++/**+ * Text with the line structure the source had.+ *+ * `textContent` runs a whole page together, so every block-level element and+ * every `<br>` contributes a break of its own and the inline runs between them+ * are joined as written.+ */+function collectHtmlBlockText(node: Node | null): string {+ if (!node) {+ return "";+ }+ if (node.nodeType === TEXT_NODE) {+ return node.nodeValue ?? "";+ }+ if (node.nodeType !== ELEMENT_NODE) {+ return "";+ }++ const element = node as Element;+ const tag = element.tagName.toLowerCase();+ if (tag === "br") {+ return "\n";+ }++ const text = Array.from(element.childNodes)+ .map(collectHtmlBlockText)+ .join("");+ return HTML_BLOCK_TAGS.has(tag) ? `\n${text}\n` : text;+}++/** Collapses the spaces an extractor leaves between positioned runs while keeping the line breaks the source marked. */+function normalizeExtractedText(text: string): string {+ return text+ .replace(/[^\S\n]+/g, " ")+ .replace(/ ?\n ?/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++// reads what the matching adapter would send, except html, which previews as raw markup+export async function readAttachmentText(+ file: File,+ name: string,+ contentType: string | undefined,+): Promise<AttachmentText> {+ if (isTextAttachment(name, contentType)) {+ return { label: null, ...(await readBoundedText(file)) };+ }+ if (isPdfAttachment(name, contentType)) {+ return {+ label: "PDF",+ text: await extractPdfAttachmentText(file),+ truncated: false,+ };+ }+ if (isDocxAttachment(name, contentType)) {+ return {+ label: "DOCX",+ text: await extractDocxAttachmentText(file),+ truncated: false,+ };+ }+ // raw markup, not the extraction; kept before opendocument to match the adapters+ if (isHtmlAttachment(name, contentType)) {+ return { label: null, ...(await readBoundedText(file)) };+ }+ if (isOpenDocumentAttachment(name, contentType)) {+ const { label, text } = await readOpenDocumentAttachmentContent(+ file,+ name,+ contentType ?? "",+ );+ return { label, text, truncated: false };+ }+ return { label: null, ...(await readBoundedText(file)) };+}++async function readBoundedText(+ file: File,+): Promise<{ text: string; truncated: boolean }> {+ const truncated = file.size > MAX_PREVIEW_TEXT_BYTES;+ const slice = truncated ? file.slice(0, MAX_PREVIEW_TEXT_BYTES) : file;+ return { text: await slice.text(), truncated };+}++// A sent attachment keeps only the text its adapter produced, so the preview+// unwraps the adapter's header or tag rather than showing it to the user. The+// stored payload has no size limit, so the wrapper is matched on a prefix and+// only the capped body is copied out.+export function parseAttachmentText(raw: string): AttachmentText {+ const head = raw.slice(0, MAX_ATTACHMENT_WRAPPER_LENGTH);++ const labelled = head.match(LABELLED_ATTACHMENT_TEXT_RE);+ if (labelled) {+ return {+ label: labelled[1] as AttachmentTextLabel,+ ...sliceAttachmentBody(raw, labelled[0].length, raw.length),+ };+ }++ const tagOpen = head.match(ATTACHMENT_TAG_OPEN_RE);+ if (tagOpen && raw.endsWith(ATTACHMENT_TAG_CLOSE)) {+ return {+ label: null,+ ...sliceAttachmentBody(+ raw,+ tagOpen[0].length,+ raw.length - ATTACHMENT_TAG_CLOSE.length,+ ),+ };+ }++ return { label: null, ...sliceAttachmentBody(raw, 0, raw.length) };+}++function sliceAttachmentBody(+ raw: string,+ start: number,+ end: number,+): { text: string; truncated: boolean } {+ const bodyEnd = Math.max(start, end);+ const cappedEnd = Math.min(bodyEnd, start + MAX_PREVIEW_TEXT_LENGTH);+ return {+ text: raw.slice(start, cappedEnd),+ truncated: cappedEnd < bodyEnd,+ };+}++export function truncateAttachmentPreviewText(text: string): {+ text: string;+ truncated: boolean;+} {+ if (text.length <= MAX_PREVIEW_TEXT_LENGTH) {+ return { text, truncated: false };+ }+ return { text: text.slice(0, MAX_PREVIEW_TEXT_LENGTH), truncated: true };+}++/**+ * The shiki language a plain-text attachment previews as, or null for prose.+ *+ * Only the filename decides. Text pulled out of a PDF, a DOCX or a spreadsheet+ * is prose whatever the document was called, so callers pass the extracted+ * label instead of the name in that case.+ */+export function attachmentTextLanguage(+ name: string | undefined,+ label: AttachmentTextLabel | null,+): string | null {+ if (label) {+ return null;+ }+ const lower = name?.toLowerCase() ?? "";+ const extension = lower.includes(".") ? lower.split(".").pop() : lower;+ return lookUp(CODE_ATTACHMENT_LANGUAGES, extension ?? "") ?? null;+}++export function countAttachmentTextLines(text: string): number {+ if (!text) {+ return 0;+ }+ return text.split("\n").length;+}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 102265c93d4..7720be5709f 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -64,7 +64,6 @@ export {export { resolveStagedDiffusionClassification } from "./lib/gpu-placement";export {preferFullToolOutput,-preferSanitizedFullToolOutput,toolOutputKey,toolThreadScope,@@ -172,6 +171,17 @@ export {isExternalModelId,parseExternalModelId,} from "./external-providers";+export {+ type AttachmentText,+ assertDocumentAttachmentSize,+ attachmentAudioSrc,+ attachmentTextLanguage,+ countAttachmentTextLines,+ isAudioAttachment,+ parseAttachmentText,+ readAttachmentText,+ truncateAttachmentPreviewText,+} from "./attachment-content";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/open-document.ts b/studio/frontend/src/features/chat/open-document.tsindex 0f63afb3336..d0e6af24648 100644--- a/studio/frontend/src/features/chat/open-document.ts+++ b/studio/frontend/src/features/chat/open-document.ts@@ -15,8 +15,8 @@ const OPEN_DOCUMENT_CELL_VALUE_ATTRIBUTES = ["time-value",] as const;const OPEN_DOCUMENT_TEXT_BLOCK_NAMES = ["h", "p"] as const;-const MAX_OPEN_DOCUMENT_ARCHIVE_BYTES = 50 * 1024 * 1024;-const MAX_OPEN_DOCUMENT_XML_BYTES = 10 * 1024 * 1024;+export const MAX_OPEN_DOCUMENT_ARCHIVE_BYTES = 50 * 1024 * 1024;+export const MAX_OPEN_DOCUMENT_XML_BYTES = 10 * 1024 * 1024;const MAX_REPEATED_OPEN_DOCUMENT_ROWS = 100;const MAX_REPEATED_OPEN_DOCUMENT_COLUMNS = 100;const MAX_OPEN_DOCUMENT_COLUMN_INDEX = Number.MAX_SAFE_INTEGER;diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 60b50988869..3caa066e0ea 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -64,6 +64,14 @@ import {readActiveOpenDocumentAttachmentContent,readOpenDocumentAttachmentContent,} from "./open-document";+import {+ extractDocxAttachmentText,+ extractHtmlAttachmentText,+ extractPdfAttachmentText,+ getDocumentAttachmentSizeError,+ getDocxAttachmentError,+ TEXT_ATTACHMENT_ACCEPT,+} from "./attachment-content";import { AudioAttachmentAdapter } from "./audio-attachment-adapter";import { VideoAttachmentAdapter } from "./video-attachment-adapter";import {@@ -278,7 +286,17 @@ class VisionImageAdapter implements AttachmentAdapter {class PDFAttachmentAdapter implements AttachmentAdapter {accept = "application/pdf";+ // Refused here, not at send: the composer empties itself before it awaits+ // send(), so a ceiling that only fires there discards the typed message too.+ // The throw itself is invisible, as with audio: nothing subscribes to+ // attachmentAddError and the picker never awaits addAttachment, so the toast+ // is the only thing that tells the user why no file appeared.add({ file }: { file: File }): Promise<PendingAttachment> {+ const sizeError = getDocumentAttachmentSizeError(file, "PDF");+ if (sizeError) {+ toast.error(sizeError);+ throw new Error(sizeError);+ }return Promise.resolve({id: crypto.randomUUID(),type: "document",@@ -290,12 +308,7 @@ class PDFAttachmentAdapter implements AttachmentAdapter {}async send(attachment: PendingAttachment): Promise<CompleteAttachment> {- const [{ extractText, getDocumentProxy }, buffer] = await Promise.all([- import("unpdf"),- attachment.file.arrayBuffer().then((bytes) => new Uint8Array(bytes)),- ]);- const pdf = await getDocumentProxy(buffer);- const { text } = await extractText(pdf, { mergePages: true });+ const text = await extractPdfAttachmentText(attachment.file);return {id: attachment.id,type: "document",@@ -315,17 +328,7 @@ class TextAttachmentAdapter implements AttachmentAdapter {// MIME is unreliable for source files, so also match by extension// (assistant-ui's fileMatchesAccept supports ".ext" entries). Covers svg, code,// config and other plain-text formats; html keeps its own adapter below.- accept = [- "text/plain,text/markdown,text/csv,text/xml,text/json,text/css",- "application/json,application/xml,image/svg+xml",- ".txt,.text,.log,.md,.markdown,.mdx,.rst,.csv,.tsv",- ".json,.jsonl,.ndjson,.xml,.yaml,.yml,.toml,.ini,.cfg,.conf,.env,.properties",- ".css,.scss,.sass,.less,.svg",- ".js,.jsx,.mjs,.cjs,.ts,.tsx,.py,.pyi,.ipynb,.rb,.php,.go,.rs,.java,.kt,.kts,.scala,.swift",- ".c,.h,.cc,.cpp,.hpp,.cxx,.cs,.m,.mm",- ".sh,.bash,.zsh,.fish,.ps1,.bat,.lua,.pl,.pm,.r,.jl,.dart,.vue,.svelte,.astro",- ".sql,.graphql,.gql,.proto,.tf,.tfvars,.gradle,.dockerfile,.makefile,.cmake,.diff,.patch",- ].join(",");+ accept = TEXT_ATTACHMENT_ACCEPT;async add({ file }: { file: File }): Promise<PendingAttachment> {return {@@ -382,10 +385,7 @@ class HtmlAttachmentAdapter implements AttachmentAdapter {}async send(attachment: PendingAttachment): Promise<CompleteAttachment> {- const html = await attachment.file.text();- const doc = new DOMParser().parseFromString(html, "text/html");- for (const el of doc.querySelectorAll("script, style")) el.remove();- const text = (doc.body.textContent ?? "").replace(/\s+/g, " ").trim();+ const text = extractHtmlAttachmentText(await attachment.file.text());return {id: attachment.id,type: "document",@@ -405,29 +405,33 @@ class DocxAttachmentAdapter implements AttachmentAdapter {accept ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";- add({ file }: { file: File }): Promise<PendingAttachment> {- return Promise.resolve({+ // The archive's own parts are checked here too, not just the upload ceiling:+ // a small .docx can still declare a part that only mammoth's inflate would+ // grow past the cap, and refusing that at send() would empty the composer.+ async add({ file }: { file: File }): Promise<PendingAttachment> {+ const error = await getDocxAttachmentError(file);+ if (error) {+ toast.error(error);+ throw new Error(error);+ }+ return {id: crypto.randomUUID(),type: "document",name: file.name,contentType: file.type,file,status: { type: "requires-action", reason: "composer-send" },- });+ };}async send(attachment: PendingAttachment): Promise<CompleteAttachment> {- const [{ default: mammoth }, arrayBuffer] = await Promise.all([- import("mammoth"),- attachment.file.arrayBuffer(),- ]);- const { value } = await mammoth.extractRawText({ arrayBuffer });+ const text = await extractDocxAttachmentText(attachment.file);return {id: attachment.id,type: "document",name: attachment.name,contentType: attachment.contentType,- content: [{ type: "text", text: `[DOCX: ${attachment.name}]\n${value}` }],+ content: [{ type: "text", text: `[DOCX: ${attachment.name}]\n${text}` }],status: { type: "complete" },};}diff --git a/studio/frontend/src/lib/markdown-plugins.ts b/studio/frontend/src/lib/markdown-plugins.tsindex 7a88d5dfe60..807bff9332b 100644--- a/studio/frontend/src/lib/markdown-plugins.ts+++ b/studio/frontend/src/lib/markdown-plugins.ts@@ -20,6 +20,15 @@ const NEEDS_MERMAID = /(?:`{3,}|~{3,})[ \t]*mermaid\b/;/** Past this a document stays plain monospace: shiki is not worth the main-thread time. */export const MAX_HIGHLIGHT_CHARS = 20_000;+/** A fence longer than any backtick run in the source, so code containing ``` cannot end it early. */+export function codeFence(source: string): string {+ const longest = (source.match(/`+/g) ?? []).reduce(+ (max, run) => Math.max(max, run.length),+ 0,+ );+ return "`".repeat(Math.max(3, longest + 1));+}+export interface MarkdownPluginNeeds {math: boolean;mermaid: boolean;diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsnew file mode 100644index 00000000000..c579fbf9ae5--- /dev/null+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -0,0 +1,921 @@+// 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 {+ Unzip,+ UnzipInflate,+ strFromU8,+ strToU8,+ unzipSync,+ zipSync,+} from "fflate";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const {+ attachmentAudioSrc,+ attachmentTextLanguage,+ countAttachmentTextLines,+ extractHtmlAttachmentText,+ extractPdfAttachmentText,+ getDocxAttachmentError,+ isAudioAttachment,+ parseAttachmentText,+ readAttachmentText,+ repackDocxAttachmentArchive,+ truncateAttachmentPreviewText,+} = await import("../src/features/chat/attachment-content.ts");+const { definePDFJSModule } = await import("unpdf");++type StubNode = {+ nodeType: number;+ nodeValue?: string;+ tagName?: string;+ childNodes: StubNode[];+ parent?: StubNode;+ remove?: () => void;+};++function textNode(value: string): StubNode {+ return { nodeType: 3, nodeValue: value, childNodes: [] };+}++function element(tagName: string, ...childNodes: StubNode[]): StubNode {+ const node: StubNode = { nodeType: 1, tagName, childNodes };+ for (const child of childNodes) {+ child.parent = node;+ child.remove = () => {+ const siblings = node.childNodes;+ siblings.splice(siblings.indexOf(child), 1);+ };+ }+ return node;+}++function descendants(node: StubNode): StubNode[] {+ return node.childNodes.flatMap((child) => [child, ...descendants(child)]);+}++/** DOMParser is absent under node, so the extractor is driven over a hand-built tree. */+async function withStubDom<T>(+ build: (source: string) => StubNode,+ run: () => T | Promise<T>,+): Promise<T> {+ const original = (globalThis as { DOMParser?: unknown }).DOMParser;+ (globalThis as { DOMParser?: unknown }).DOMParser = class {+ parseFromString(source: string) {+ const body = build(source);+ return {+ body,+ querySelectorAll: (selector: string) => {+ const tags = new Set(selector.split(",").map((part) => part.trim()));+ return descendants(body).filter(+ (node) => node.tagName && tags.has(node.tagName),+ );+ },+ };+ }+ };+ try {+ return await run();+ } finally {+ (globalThis as { DOMParser?: unknown }).DOMParser = original;+ }+}++// The preview reads a sent attachment back out of the text the adapter built,+// so every wrapper the adapters write has to round-trip.+test("parseAttachmentText unwraps a labelled document header", () => {+ const parsed = parseAttachmentText("[PDF: report.pdf]\nline one\nline two");+ assert.deepEqual(parsed, {+ label: "PDF",+ text: "line one\nline two",+ truncated: false,+ });+});++test("parseAttachmentText unwraps the plain text attachment tag", () => {+ const parsed = parseAttachmentText(+ "<attachment name=notes.txt>\nline one\nline two\n</attachment>",+ );+ assert.deepEqual(parsed, {+ label: null,+ text: "line one\nline two",+ truncated: false,+ });+});++test("parseAttachmentText keeps text that carries no wrapper", () => {+ const parsed = parseAttachmentText("[not a label] still content");+ assert.deepEqual(parsed, {+ label: null,+ text: "[not a label] still content",+ truncated: false,+ });+});++test("parseAttachmentText keeps a header-like first line inside the body", () => {+ const parsed = parseAttachmentText("[PDF: a.pdf]\n[DOCX: b.docx]\nbody");+ assert.deepEqual(parsed, {+ label: "PDF",+ text: "[DOCX: b.docx]\nbody",+ truncated: false,+ });+});++test("truncateAttachmentPreviewText caps very long attachments", () => {+ const short = truncateAttachmentPreviewText("abc");+ assert.deepEqual(short, { text: "abc", truncated: false });++ const long = truncateAttachmentPreviewText("a".repeat(200_001));+ assert.equal(long.truncated, true);+ assert.equal(long.text.length, 200_000);+});++test("countAttachmentTextLines counts empty and single-line text", () => {+ assert.equal(countAttachmentTextLines(""), 0);+ assert.equal(countAttachmentTextLines("one line"), 1);+ assert.equal(countAttachmentTextLines("one\ntwo\n"), 3);+});++// The sent audio part only carries "mp3" or "wav", so an OGG or FLAC upload+// would be mislabelled without the attachment's own content type.+test("attachmentAudioSrc keeps the uploaded audio MIME", () => {+ const part = { data: "AAA", format: "wav" };+ assert.equal(+ attachmentAudioSrc(part, "audio/ogg", "clip.ogg"),+ "data:audio/ogg;base64,AAA",+ );+ assert.equal(+ attachmentAudioSrc({ data: "AAA", format: "mp3" }, undefined, "clip.mp3"),+ "data:audio/mpeg;base64,AAA",+ );+ assert.equal(+ attachmentAudioSrc(part, "", "clip.wav"),+ "data:audio/wav;base64,AAA",+ );+});++// An extension-only upload reaches the sent preview with an empty content type+// and format "wav", so the filename is what identifies the container.+test("attachmentAudioSrc falls back to the extension for untyped uploads", () => {+ const part = { data: "AAA", format: "wav" };+ assert.equal(+ attachmentAudioSrc(part, "", "clip.m4a"),+ "data:audio/mp4;base64,AAA",+ );+ assert.equal(+ attachmentAudioSrc(part, "application/octet-stream", "clip.flac"),+ "data:audio/flac;base64,AAA",+ );+ assert.equal(+ attachmentAudioSrc(part, undefined, "clip"),+ "data:audio/wav;base64,AAA",+ );+});++// The text and HTML adapters accept uploads with no size limit, so opening a+// preview must not materialize the whole file.+test("readAttachmentText reads a bounded slice of a large text file", async () => {+ const oversized = new File(["a".repeat(2_000_000)], "huge.txt", {+ type: "text/plain",+ });+ const { label, text, truncated } = await readAttachmentText(+ oversized,+ oversized.name,+ oversized.type,+ );+ assert.equal(label, null);+ assert.equal(truncated, true);+ assert.equal(text.length, 1_000_000);+ assert.equal(truncateAttachmentPreviewText(text).truncated, true);+});++test("readAttachmentText reads a bounded slice of a large html file", async () => {+ const oversized = new File(+ [`<p>${"b".repeat(2_000_000)}</p>`],+ "huge.html",+ { type: "text/html" },+ );+ const { label, text, truncated } = await readAttachmentText(+ oversized,+ oversized.name,+ oversized.type,+ );++ assert.equal(label, null);+ assert.equal(truncated, true);+ assert.equal(text.length, 1_000_000);+});++// the adapter sends the extraction; the preview shows the markup unextracted+test("readAttachmentText previews an html file as its markup", async () => {+ const markup = "<p>Drag to rotate<br>Scroll to zoom</p>";+ const file = new File([markup], "page.html", { type: "text/html" });++ assert.deepEqual(await readAttachmentText(file, file.name, file.type), {+ label: null,+ text: markup,+ truncated: false,+ });+});++/** textContent runs a whole page onto one line, and this extraction is what the html adapter sends the model. */+test("extractHtmlAttachmentText keeps the line structure of the page", async () => {+ const extracted = await withStubDom(+ () =>+ element(+ "body",+ element("h1", textNode("Solar System Explorer")),+ element(+ "p",+ textNode("Drag to rotate"),+ element("br"),+ textNode("Scroll to zoom"),+ ),+ element(+ "ul",+ element("li", textNode("Sun")),+ element("li", textNode("Mercury")),+ ),+ element("script", textNode("const planets = 8;")),+ element("style", textNode("body { margin: 0 }")),+ ),+ () => extractHtmlAttachmentText("<html/>"),+ );++ assert.equal(+ extracted,+ "Solar System Explorer\n\nDrag to rotate\nScroll to zoom\n\nSun\n\nMercury",+ );+});++test("isAudioAttachment matches by MIME and by extension", () => {+ assert.equal(isAudioAttachment("clip.m4a", ""), true);+ assert.equal(isAudioAttachment("clip", "audio/webm"), true);+ assert.equal(isAudioAttachment("notes.txt", "text/plain"), false);+ assert.equal(isAudioAttachment(undefined, undefined), false);+});++// CompositeAttachmentAdapter checks TextAttachmentAdapter before the+// document-specific adapters, so a browser-declared text MIME wins over a+// misleading extension in both the sent payload and its preview.+test("readAttachmentText follows text adapter precedence over document extensions", async () => {+ for (const name of ["notes.pdf", "notes.docx", "notes.html"]) {+ const file = new File([`plain text from ${name}`], name, {+ type: "text/plain",+ });+ assert.deepEqual(+ await readAttachmentText(file, file.name, file.type),+ {+ label: null,+ text: `plain text from ${name}`,+ truncated: false,+ },+ );+ }+});++// Stored payloads have no size limit, so unwrapping must copy at most the+// capped body rather than the whole attachment.+test("parseAttachmentText caps the body it copies out of a wrapper", () => {+ const body = "d".repeat(300_000);+ const tagged = parseAttachmentText(+ `<attachment name=huge.txt>\n${body}\n</attachment>`,+ );+ assert.equal(tagged.label, null);+ assert.equal(tagged.text.length, 200_000);+ assert.equal(tagged.truncated, true);++ const labelled = parseAttachmentText(`[PDF: huge.pdf]\n${body}`);+ assert.equal(labelled.label, "PDF");+ assert.equal(labelled.text.length, 200_000);+ assert.equal(labelled.truncated, true);++ const bare = parseAttachmentText(body);+ assert.equal(bare.text.length, 200_000);+ assert.equal(bare.truncated, true);+});++// A File the preview only ever asks for its size and its bytes, so the read can+// be observed without materializing a document-sized buffer.+function fakeDocumentFile(+ name: string,+ size: number,+ bytes: Uint8Array,+ reads: string[],+): File {+ return {+ name,+ size,+ arrayBuffer: () => {+ reads.push(name);+ return Promise.resolve(+ bytes.buffer.slice(+ bytes.byteOffset,+ bytes.byteOffset + bytes.byteLength,+ ) as ArrayBuffer,+ );+ },+ } as unknown as File;+}++function docxBytes(documentXml: string): Uint8Array {+ return zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": strToU8("<Relationships/>"),+ "word/document.xml": strToU8(documentXml),+ });+}++// unpdf and mammoth parse on the main thread, so an oversized document has to be+// refused before its bytes are read, not after.+test("readAttachmentText refuses an oversized pdf before reading it", async () => {+ const reads: string[] = [];+ const oversized = fakeDocumentFile(+ "huge.pdf",+ 60 * 1024 * 1024,+ new Uint8Array(0),+ reads,+ );+ await assert.rejects(+ readAttachmentText(oversized, oversized.name, "application/pdf"),+ /PDF file is too large: huge\.pdf/,+ );+ assert.deepEqual(reads, []);+});++test("readAttachmentText refuses an oversized docx before reading it", async () => {+ const reads: string[] = [];+ const oversized = fakeDocumentFile(+ "huge.docx",+ 60 * 1024 * 1024,+ new Uint8Array(0),+ reads,+ );+ await assert.rejects(+ readAttachmentText(oversized, oversized.name, undefined),+ /DOCX file is too large: huge\.docx/,+ );+ assert.deepEqual(reads, []);+});++test("extractPdfAttachmentText destroys the PDF proxy after success and failure", async () => {+ const destroyed: string[] = [];+ const proxies = [+ {+ _pdfInfo: {},+ numPages: 1,+ getPage: async () => ({+ getTextContent: async () => ({+ items: [+ { str: "page one", hasEOL: true },+ { str: "page two", hasEOL: false },+ ],+ }),+ }),+ destroy: async () => {+ destroyed.push("success");+ },+ },+ {+ _pdfInfo: {},+ numPages: 1,+ getPage: async () => {+ throw new Error("page extraction failed");+ },+ destroy: async () => {+ destroyed.push("failure");+ },+ },+ ];++ await definePDFJSModule(async () => ({+ getDocument: () => ({ promise: Promise.resolve(proxies.shift()) }),+ }));+ try {+ const file = new File(["%PDF"], "small.pdf", {+ type: "application/pdf",+ });+ assert.equal(await extractPdfAttachmentText(file), "page one\npage two");+ await assert.rejects(+ extractPdfAttachmentText(file),+ /page extraction failed/,+ );+ assert.deepEqual(destroyed, ["success", "failure"]);+ } finally {+ await definePDFJSModule(() => import("unpdf/pdfjs"));+ }+});++// The bytes are requested synchronously, so the extractor is reached without+// waiting on unpdf, which the preview test does not exercise.+test("readAttachmentText reads a pdf under the ceiling", () => {+ const reads: string[] = [];+ const small = fakeDocumentFile(+ "small.pdf",+ 64 * 1024,+ new Uint8Array([0x25, 0x50, 0x44, 0x46]),+ reads,+ );+ const pending = readAttachmentText(small, small.name, "application/pdf");+ pending.catch(() => undefined);+ assert.deepEqual(reads, ["small.pdf"]);+});++// mammoth's node build takes a buffer rather than an arrayBuffer, so the small+// case asserts the archive cleared both guards and reached mammoth itself.+test("readAttachmentText lets a normal docx through to the extractor", async () => {+ const reads: string[] = [];+ const bytes = docxBytes("<w:document><w:body/></w:document>");+ const small = fakeDocumentFile("notes.docx", bytes.length, bytes, reads);+ const error = await readAttachmentText(small, small.name, undefined).then(+ () => null,+ (thrown: Error) => thrown,+ );+ assert.deepEqual(reads, ["notes.docx"]);+ if (error) {+ assert.doesNotMatch(error.message, /too large/);+ }+});++// A DOCX is a zip, so a small upload can still declare a huge document.xml.+test("readAttachmentText refuses a docx that declares an oversized document.xml", async () => {+ const reads: string[] = [];+ const bytes = docxBytes("a".repeat(11 * 1024 * 1024));+ const bomb = fakeDocumentFile("bomb.docx", bytes.length, bytes, reads);+ assert.equal(bomb.size < 1024 * 1024, true);+ await assert.rejects(+ readAttachmentText(bomb, bomb.name, undefined),+ /DOCX XML file is too large: bomb\.docx:word\/document\.xml/,+ );+});++// mammoth reads "_rels/.rels" first and "[Content_Types].xml" next, and picks+// the body part out of "word/_rels/document.xml.rels", so a bomb parked in any+// of them never passes through word/*.xml.+test("readAttachmentText refuses an oversized docx part outside word/*.xml", async () => {+ const huge = "a".repeat(11 * 1024 * 1024);+ const parts = [+ "[Content_Types].xml",+ "_rels/.rels",+ "word/_rels/document.xml.rels",+ ];++ for (const part of parts) {+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": strToU8("<Relationships/>"),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ [part]: strToU8(huge),+ });+ const bomb = fakeDocumentFile("bomb.docx", bytes.length, bytes, []);+ assert.equal(bomb.size < 1024 * 1024, true);+ await assert.rejects(+ readAttachmentText(bomb, bomb.name, undefined),+ new RegExp(+ `DOCX XML file is too large: bomb\\.docx:${part.replace(+ /[.[\]/]/g,+ "\\$&",+ )}`,+ ),+ `a ${part} bomb reached mammoth`,+ );+ }+});++function relationships(entries: Array<[string, string]>): Uint8Array {+ return strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${entries+ .map(+ ([type, target], index) =>+ `<Relationship Id="rId${index + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${target}"/>`,+ )+ .join("")}</Relationships>`,+ );+}++// mammoth resolves the body and its styles/numbering/note parts through the+// relationships and parses whatever they point at as XML, so a target named+// "payload.bin" is inflated on the main thread even though no suffix says XML.+test("readAttachmentText refuses an oversized docx part reached through a relationship", async () => {+ const huge = strToU8("a".repeat(11 * 1024 * 1024));++ const bodyBomb = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "payload.bin"]]),+ "payload.bin": huge,+ });+ const bodyFile = fakeDocumentFile("bomb.docx", bodyBomb.length, bodyBomb, []);+ assert.equal(bodyFile.size < 1024 * 1024, true);+ await assert.rejects(+ readAttachmentText(bodyFile, bodyFile.name, undefined),+ /DOCX XML file is too large: bomb\.docx:payload\.bin/,+ );++ const stylesBomb = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "word/_rels/document.xml.rels": relationships([["styles", "styles.dat"]]),+ "word/styles.dat": huge,+ });+ const stylesFile = fakeDocumentFile(+ "styles.docx",+ stylesBomb.length,+ stylesBomb,+ [],+ );+ assert.equal(stylesFile.size < 1024 * 1024, true);+ await assert.rejects(+ readAttachmentText(stylesFile, stylesFile.name, undefined),+ /DOCX XML file is too large: styles\.docx:word\/styles\.dat/,+ );+});++// extractRawText never reads an image part, so a document that merely embeds a+// large picture still previews: the bound follows what mammoth parses.+test("readAttachmentText lets a docx with a large embedded image through", async () => {+ const reads: string[] = [];+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "word/_rels/document.xml.rels": relationships([+ ["image", "media/photo.png"],+ ]),+ "word/media/photo.png": new Uint8Array(12 * 1024 * 1024),+ });+ const file = fakeDocumentFile("photo.docx", bytes.length, bytes, reads);+ const error = await readAttachmentText(file, file.name, undefined).then(+ () => null,+ (thrown: Error) => thrown,+ );+ assert.deepEqual(reads, ["photo.docx"]);+ if (error) {+ assert.doesNotMatch(error.message, /too large/);+ }+});++// mammoth hands the relationships to a real XML parser, so every attribute+// form that parser resolves has to resolve here too: a target it reaches and+// the guard does not is inflated on the main thread unbounded.+test("readAttachmentText refuses a relationship target in any XML attribute form", async () => {+ const huge = strToU8("a".repeat(11 * 1024 * 1024));+ const type =+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";+ const forms: Array<[string, string, string]> = [+ [+ "single-quoted attributes",+ "payload.bin",+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id='rId1' Type='${type}' Target='payload.bin'/></Relationships>`,+ ],+ [+ "an entity-encoded target",+ "payload.bin",+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${type}" Target="payload.bin"/></Relationships>`,+ ],+ [+ "a prefixed element name",+ "payload.bin",+ `<pkg:Relationships xmlns:pkg="http://schemas.openxmlformats.org/package/2006/relationships"><pkg:Relationship Id="rId1" Type="${type}" Target="payload.bin"/></pkg:Relationships>`,+ ],+ [+ "a target holding a decoy attribute",+ "payload.bin",+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id='Target="word/document.xml"' Type="${type}" Target="payload.bin"/></Relationships>`,+ ],+ [+ "a target holding a closing bracket",+ "pay>load.bin",+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${type}" Target="pay>load.bin"/></Relationships>`,+ ],+ ];++ for (const [label, target, rels] of forms) {+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": strToU8(rels),+ [target]: huge,+ });+ const bomb = fakeDocumentFile("bomb.docx", bytes.length, bytes, []);+ assert.equal(bomb.size < 1024 * 1024, true);+ await assert.rejects(+ readAttachmentText(bomb, bomb.name, undefined),+ new RegExp(+ `DOCX XML file is too large: bomb\\.docx:${target.replace(/[.>]/g, "\\$&")}$`,+ ),+ `${label} reached mammoth unbounded`,+ );+ }+});++/**+ * A relationship inside non-element markup is text to mammoth's parser, so it+ * must not select the bounded part in either direction: it cannot stand in for+ * the real target and hide it, and it cannot refuse a document mammoth reads.+ */+test("readAttachmentText ignores a relationship inside non-element markup", async () => {+ const huge = strToU8("a".repeat(11 * 1024 * 1024));+ const type =+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";+ const wrappers: Array<[string, (tag: string) => string]> = [+ ["a comment", (tag) => `<!--${tag}-->`],+ ["a CDATA section", (tag) => `<![CDATA[${tag}]]>`],+ ["a processing instruction", (tag) => `<?guard ${tag}?>`],+ ];+ const rels = (wrap: (tag: string) => string, buried: string, live: string) =>+ strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${wrap(+ `<Relationship Id="rId0" Type="${type}" Target="${buried}"/>`,+ )}<Relationship Id="rId1" Type="${type}" Target="${live}"/></Relationships>`,+ );++ for (const [label, wrap] of wrappers) {+ const hidden = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": rels(wrap, "word/document.xml", "payload.bin"),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "payload.bin": huge,+ });+ const hiddenFile = fakeDocumentFile("bomb.docx", hidden.length, hidden, []);+ await assert.rejects(+ readAttachmentText(hiddenFile, hiddenFile.name, undefined),+ /DOCX XML file is too large: bomb\.docx:payload\.bin/,+ `${label} stood in for the live relationship`,+ );++ const reads: string[] = [];+ const refused = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": rels(wrap, "payload.bin", "word/document.xml"),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "word/_rels/document.xml.rels": relationships([]),+ "payload.bin": huge,+ });+ const refusedFile = fakeDocumentFile(+ "notes.docx",+ refused.length,+ refused,+ reads,+ );+ const error = await readAttachmentText(+ refusedFile,+ refusedFile.name,+ undefined,+ ).then(+ () => null,+ (thrown: Error) => thrown,+ );+ assert.deepEqual(reads, ["notes.docx"]);+ if (error) {+ assert.doesNotMatch(error.message, /too large/, label);+ }+ }+});++/** The XML declaration every real .rels file opens with is a processing instruction too, so stripping them must not cost a live relationship. */+test("readAttachmentText keeps resolving a rels file that opens with its xml declaration", async () => {+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": strToU8(+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n${strFromU8(+ relationships([["officeDocument", "payload.bin"]]),+ )}`,+ ),+ "payload.bin": strToU8("a".repeat(11 * 1024 * 1024)),+ });+ const file = fakeDocumentFile("bomb.docx", bytes.length, bytes, []);+ await assert.rejects(+ readAttachmentText(file, file.name, undefined),+ /DOCX XML file is too large: bomb\.docx:payload\.bin/,+ );+});++// findPartPaths only opens the package parts and what the relationships point+// at, so an .xml part nothing references is never inflated. Custom XML data is+// a standard payload and may be large, so the suffix must not decide.+test("readAttachmentText lets a docx with a large unreferenced xml part through", async () => {+ const reads: string[] = [];+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "word/_rels/document.xml.rels": relationships([]),+ "customXml/item1.xml": strToU8(+ `<data>${"b".repeat(11 * 1024 * 1024)}</data>`,+ ),+ });+ const file = fakeDocumentFile("custom.docx", bytes.length, bytes, reads);+ const error = await readAttachmentText(file, file.name, undefined).then(+ () => null,+ (thrown: Error) => thrown,+ );+ assert.deepEqual(reads, ["custom.docx"]);+ if (error) {+ assert.doesNotMatch(error.message, /too large/);+ }+});++// The composer empties itself before it awaits send(), so a part that only+// fails there takes the typed message with it: add() has to decide instead.+test("getDocxAttachmentError refuses an oversized part before the attachment is added", async () => {+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "word/_rels/document.xml.rels": relationships([["styles", "styles.dat"]]),+ "word/styles.dat": strToU8("a".repeat(11 * 1024 * 1024)),+ });+ const bomb = fakeDocumentFile("styles.docx", bytes.length, bytes, []);+ assert.equal(bomb.size < 1024 * 1024, true);+ assert.equal(+ await getDocxAttachmentError(bomb),+ "DOCX XML file is too large: styles.docx:word/styles.dat",+ );++ const oversized = fakeDocumentFile(+ "huge.docx",+ 60 * 1024 * 1024,+ new Uint8Array(0),+ [],+ );+ assert.equal(+ await getDocxAttachmentError(oversized),+ "DOCX file is too large: huge.docx",+ );++ const okBytes = docxBytes("<w:document><w:body/></w:document>");+ const ok = fakeDocumentFile("notes.docx", okBytes.length, okBytes, []);+ assert.equal(await getDocxAttachmentError(ok), null);+});++/** Rewrites every field holding `size` down to `declared`, the way a crafted archive lies about a part. */+function understateDeclaredSizes(+ archive: Uint8Array,+ size: number,+ declared: number,+): number {+ const view = new DataView(+ archive.buffer,+ archive.byteOffset,+ archive.byteLength,+ );+ let patched = 0;+ for (let offset = 0; offset + 4 <= archive.length; offset++) {+ if (view.getUint32(offset, true) === size) {+ view.setUint32(offset, declared, true);+ patched++;+ }+ }+ return patched;+}++/**+ * Inflated sizes as jszip sees them: the whole stream, whatever the archive+ * declares. `unzipSync` cannot answer this, since it allocates each entry at+ * its declared size and stops there, which is why the declared size proves+ * nothing about what mammoth would decompress.+ */+function inflatedSizes(archive: Uint8Array): Map<string, number> {+ const sizes = new Map<string, number>();+ const unzip = new Unzip();+ unzip.register(UnzipInflate);+ unzip.onfile = (file) => {+ let size = 0;+ file.ondata = (error, chunk) => {+ if (!error) {+ size += chunk.length;+ sizes.set(file.name, size);+ }+ };+ file.start();+ };+ unzip.push(archive, true);+ return sizes;+}++/**+ * jszip takes each part's size from the central directory and inflates the part+ * in full before it can be rejected, so a lying header still expands inside+ * mammoth. fflate allocates the entry at the declared size and stops, so the+ * repack is what contains the lie.+ */+test("repackDocxAttachmentArchive bounds a part that lies about its size", () => {+ const body = strToU8("a".repeat(30 * 1024 * 1024));+ const archive = zipSync(+ {+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": body,+ },+ { level: 9 },+ );+ assert.equal(understateDeclaredSizes(archive, body.length, 1024), 2);+ assert.equal(archive.length < 1024 * 1024, true);+ assert.equal(inflatedSizes(archive).get("word/document.xml"), body.length);++ const repacked = repackDocxAttachmentArchive("lie.docx", archive);+ assert.equal(inflatedSizes(repacked).get("word/document.xml"), 1024);+ assert.equal(unzipSync(repacked)["word/document.xml"].length, 1024);+});++test("repackDocxAttachmentArchive keeps an honest archive intact", () => {+ const files = {+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ "word/media/photo.png": new Uint8Array(4096),+ };+ const repacked = unzipSync(+ repackDocxAttachmentArchive("notes.docx", zipSync(files, { level: 9 })),+ );++ assert.deepEqual(Object.keys(repacked).sort(), Object.keys(files).sort());+ for (const [name, bytes] of Object.entries(files)) {+ assert.deepEqual(repacked[name], bytes, name);+ }+});++/** Every part can sit under the XML ceiling while the archive as a whole still unpacks to more than the webview can hold. */+test("repackDocxAttachmentArchive refuses an archive that unpacks past the ceiling", () => {+ const part = new Uint8Array(9 * 1024 * 1024);+ const files: Record<string, Uint8Array> = {+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": relationships([["officeDocument", "word/document.xml"]]),+ "word/document.xml": strToU8("<w:document><w:body/></w:document>"),+ };+ for (let index = 0; index < 12; index++) {+ files[`word/media/photo${index}.bin`] = part;+ }++ const archive = zipSync(files, { level: 1 });+ assert.throws(+ () => repackDocxAttachmentArchive("wide.docx", archive),+ /DOCX file is too large: wide\.docx/,+ );+});++/** A preview only colours what the filename says is source; extracted document text is prose whatever the file was called. */+test("attachmentTextLanguage maps source files and leaves prose alone", () => {+ assert.equal(attachmentTextLanguage("train.py", null), "python");+ assert.equal(attachmentTextLanguage("Chart.YAML", null), "yaml");+ assert.equal(attachmentTextLanguage("page.html", null), "html");+ assert.equal(attachmentTextLanguage("notes.txt", null), null);+ assert.equal(attachmentTextLanguage("script.py", "PDF"), null);+ // the label parsed from the adapter's wrapper keeps a sent extraction unhighlighted+ assert.equal(+ attachmentTextLanguage(+ "page.html",+ parseAttachmentText("[HTML: page.html]\nDrag to rotate").label,+ ),+ null,+ );+ assert.equal(attachmentTextLanguage(undefined, null), null);+});++/**+ * Every extension and entity table here is a plain object literal, so a key+ * that names a member of Object.prototype resolves to a function rather than+ * missing. The entity case is the one that matters: a resolved target would+ * carry the source text of that function and bound a path mammoth never reads.+ */+test("prototype member names do not resolve as table entries", async () => {+ assert.equal(attachmentTextLanguage("notes.constructor", null), null);+ assert.equal(attachmentTextLanguage("notes.toString", null), null);+ assert.equal(attachmentTextLanguage("notes.py", null), "python");++ assert.equal(+ attachmentAudioSrc({ data: "AAA", format: "wav" }, "", "clip.constructor"),+ "data:audio/wav;base64,AAA",+ );++ const type =+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";+ const bytes = zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "_rels/.rels": strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${type}" Target="pay&constructor;load.bin"/></Relationships>`,+ ),+ "pay&constructor;load.bin": strToU8("a".repeat(11 * 1024 * 1024)),+ });+ const bomb = fakeDocumentFile("bomb.docx", bytes.length, bytes, []);+ await assert.rejects(+ readAttachmentText(bomb, bomb.name, undefined),+ /DOCX XML file is too large: bomb\.docx:pay&constructor;load\.bin/,+ );+});++test("parseAttachmentText keeps an unterminated tag as plain text", () => {+ const parsed = parseAttachmentText("<attachment name=notes.txt>\nbody");+ assert.deepEqual(parsed, {+ label: null,+ text: "<attachment name=notes.txt>\nbody",+ truncated: false,+ });+});diff --git a/studio/frontend/tests/attachment-source-cost.test.ts b/studio/frontend/tests/attachment-source-cost.test.tsnew file mode 100644index 00000000000..4f5c9c08418--- /dev/null+++ b/studio/frontend/tests/attachment-source-cost.test.ts@@ -0,0 +1,206 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// useAuiState reads through useSyncExternalStore, so its selector runs on every+// store notification and on every render, and useShallow gates the re-render,+// not the selector. Building a "data:audio/wav;base64,..." string in there+// therefore copies the whole clip per token of a streamed reply, twice over:+// AttachmentThumb and AttachmentPreviewDialog each mount the hook.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { selectAttachmentSource } = await import(+ "../src/components/assistant-ui/attachment-selection.ts"+);+const { assertDocumentAttachmentSize } = await import(+ "../src/features/chat/attachment-content.ts"+);++const ATTACHMENT_ID_SELECTOR_RE =+ /const attachmentId = useAuiState\(\(\{ attachment \}\) => attachment\.id\)/;+const ATTACHMENT_ID_ROOT_KEY_RE =+ /<AttachmentPrimitive\.Root\s+key=\{attachmentId\}/;+const PASTED_TEXT_ID_KEY_RE =+ /<PastedTextAttachmentUI\s+key=\{attachmentId\}/;++function source(path: string): string {+ return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");+}++function audioAttachment(payload: string) {+ return {+ attachment: {+ type: "document",+ name: "clip.wav",+ contentType: "audio/wav",+ content: [+ { type: "audio" as const, audio: { data: payload, format: "wav" } },+ ],+ },+ };+}++// The selected value is what useShallow compares with Object.is. A fresh string+// each run makes that comparison walk the payload; the part itself is a stable+// reference off the store, so it compares in constant time.+test("the attachment selector does not rebuild the audio payload per run", () => {+ const state = audioAttachment("A".repeat(4 * 1024 * 1024));++ const first = selectAttachmentSource(state);+ const second = selectAttachmentSource(state);++ assert.equal(first.kind, "audio");+ for (const [key, value] of Object.entries(first)) {+ assert.equal(+ Object.is(value, second[key as keyof typeof second]),+ true,+ `selector rebuilt "${key}" on a second run over unchanged state`,+ );+ }+ assert.equal(Object.is(first.audio, state.attachment.content[0].audio), true);+});++/**+ * The selector hands the part through, so the hook must not join it either.+ *+ * Every tile in a transcript mounts `useAttachmentSource`, and the dialog+ * mounts it again, so a data URL built there copies MAX_AUDIO_SIZE of base64+ * twice per sent clip with the dialog still closed. Radix only renders+ * DialogContent once the dialog opens, which is where the join belongs.+ */+test("the audio data URL is built in the dialog, not on every attachment tile", () => {+ const hook = source("components/assistant-ui/use-attachment-source.ts");+ assert.doesNotMatch(+ hook,+ /attachmentAudioSrc/,+ "useAttachmentSource joins the audio payload before the preview opens",+ );+ assert.match(hook, /audio: source\.audio/);++ const preview = source("components/assistant-ui/attachment-preview.tsx");+ const body = preview.indexOf("const AttachmentAudioBody");+ assert.notEqual(body, -1, "no component owns the audio data URL");+ assert.equal(+ preview.indexOf("attachmentAudioSrc(") > body,+ true,+ "the audio data URL is built outside AttachmentAudioBody",+ );+ assert.match(preview, /<DialogContent[\s\S]*<AttachmentAudioBody/);+});++// A plain text/document attachment must keep working: the control that has to+// pass with and without the fix.+test("the attachment selector still resolves text and image attachments", () => {+ const text = selectAttachmentSource({+ attachment: {+ type: "document",+ name: "notes.txt",+ content: [{ type: "text", text: "line one" }],+ },+ });+ assert.equal(text.kind, "text");+ assert.equal(text.text, "line one");+ assert.equal(text.audio, undefined);++ const image = selectAttachmentSource({+ attachment: {+ type: "image",+ name: "shot.png",+ content: [{ type: "image", image: "data:image/png;base64,AAA" }],+ },+ });+ assert.equal(image.kind, "image");+ assert.equal(image.image, "data:image/png;base64,AAA");+ assert.equal(image.audio, undefined);+});++// ComposerPrimitive.Attachments keys its providers by list index. Removing the+// first attachment therefore reuses AttachmentUI for the next attachment, so+// every stateful preview/source branch needs the attachment identity as its own+// reset boundary.+test("attachment previews reset when an index is reused for another attachment", () => {+ const attachment = source("components/assistant-ui/attachment.tsx");+ const ui = attachment.slice(+ attachment.indexOf("const AttachmentUI"),+ attachment.indexOf("const AttachmentRemove"),+ );++ assert.match(ui, ATTACHMENT_ID_SELECTOR_RE);+ assert.match(+ ui,+ ATTACHMENT_ID_ROOT_KEY_RE,+ "index reuse can carry the previous dialog and object URL state into the successor tile",+ );+ assert.match(+ ui,+ PASTED_TEXT_ID_KEY_RE,+ "index reuse can carry an in-progress pasted-text conversion into the successor tile",+ );+});++// The composer runs _emptyTextAndAttachments() before it awaits adapter.send(),+// so a ceiling that only fires at send drops the typed message with the file.+// The refusal also has to be visible: the file picker calls addAttachment+// without awaiting it and nothing subscribes to attachmentAddError, so a bare+// throw leaves the user with no file and no reason, as the audio adapter's+// toast avoids.+test("the pdf and docx adapters refuse an oversized file at add, with a toast", () => {+ const provider = source("features/chat/runtime-provider.tsx");++ // DOCX also has to clear its per-part bound at add: a small archive can+ // still declare a part mammoth would inflate past the cap.+ for (const [adapter, call, toast] of [+ [+ "PDFAttachmentAdapter",+ 'getDocumentAttachmentSizeError(file, "PDF")',+ "toast.error(sizeError)",+ ],+ [+ "DocxAttachmentAdapter",+ "await getDocxAttachmentError(file)",+ "toast.error(error)",+ ],+ ]) {+ const start = provider.indexOf(`class ${adapter}`);+ assert.notEqual(start, -1, `${adapter} not found`);+ const body = provider.slice(start, provider.indexOf("\n}", start));+ const guard = body.indexOf(call);+ assert.notEqual(+ guard,+ -1,+ `${adapter} never applies the document size ceiling`,+ );+ assert.equal(+ guard > body.indexOf("add({ file }") &&+ guard < body.indexOf("async send("),+ true,+ `${adapter} accepts a file past the ceiling and only fails at send`,+ );+ const toasted = body.indexOf(toast);+ assert.equal(+ toasted > guard && toasted < body.indexOf("async send("),+ true,+ `${adapter} refuses an oversized file without telling the user`,+ );+ }+});++test("the shared ceiling refuses an oversized document and passes a normal one", () => {+ const oversized = { name: "huge.pdf", size: 60 * 1024 * 1024 } as File;+ assert.throws(+ () => assertDocumentAttachmentSize(oversized, "PDF"),+ /PDF file is too large: huge\.pdf/,+ );+ assert.doesNotThrow(() =>+ assertDocumentAttachmentSize(+ { name: "ok.docx", size: 64 * 1024 } as File,+ "DOCX",+ ),+ );+});diff --git a/studio/frontend/tests/research-render-budget.test.ts b/studio/frontend/tests/research-render-budget.test.tsindex 3235b3c44a1..6319dd2603b 100644--- a/studio/frontend/tests/research-render-budget.test.ts+++ b/studio/frontend/tests/research-render-budget.test.ts@@ -110,7 +110,14 @@ test("highlighting is capped, and the cap is one constant", () => {markdownPluginNeeds("x".repeat(MAX_HIGHLIGHT_CHARS + 1)).code,false,);- const cell = source("components/assistant-ui/tool-code-cell.tsx");- assert.match(cell, /import \{ MAX_HIGHLIGHT_CHARS \} from "@\/lib\/markdown-plugins";/);- assert.doesNotMatch(cell, /const MAX_HIGHLIGHT_CHARS = /);+ const imports =+ /import \{[^}]*\bMAX_HIGHLIGHT_CHARS\b[^}]*\} from "@\/lib\/markdown-plugins";/;+ for (const path of [+ "components/assistant-ui/tool-code-cell.tsx",+ "components/assistant-ui/attachment-preview.tsx",+ ]) {+ const cell = source(path);+ assert.match(cell, imports, path);+ assert.doesNotMatch(cell, /const MAX_HIGHLIGHT_CHARS = /, path);+ }});diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex a26ed74eb29..87994e3b126 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -294,7 +294,8 @@ def test_generated_download_buttons_use_the_native_save_boundary():assert 'rust: "rs"' in markdownassert "downloadUrl(part.image, filename)" in imageassert "urlToBlob(part.image)" in image- assert 'downloadUrl(src, "generated-audio.wav")' in audio+ assert "downloadUrl(src, filename)" in audio+ assert 'filename = "generated-audio.wav"' in audiotauri_config = (REPO / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8")assert "connect-src 'self' ipc: http://ipc.localhost" in tauri_config