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
Composer attachments: first page previews, Library icons, lighter cards (#12261)
Michael Han6fabaab67017
diff --git a/studio/frontend/src/components/assistant-ui/attachment-card-preview.tsx b/studio/frontend/src/components/assistant-ui/attachment-card-preview.tsxnew file mode 100644index 00000000000..9f2e0b5541b--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/attachment-card-preview.tsx@@ -0,0 +1,160 @@+// 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 DocumentKind, DocumentView, documentKind, isMarkdown, sheetDelimiter } from "@/components/file-viewer";+import { queueParse } from "@/components/file-viewer/parse-queue";+import { MarkdownPreview } from "@/components/markdown/markdown-preview";+import { type AttachmentFileKind, isTextAttachment, readAttachmentText } from "@/features/chat";+import { cn } from "@/lib/utils";+import { type FC, type ReactNode, useEffect, useLayoutEffect, useState } from "react";++// Larger files keep the icon: a visible card parses its whole file.+const MAX_PREVIEW_BYTES = 10 * 1024 * 1024;+const TEXT_PREVIEW_CHARS = 8 * 1024;+// Width the first page lays out at before it is scaled to the card.+const PAGE_WIDTH: Record<DocumentKind, number> = { pdf: 400, docx: 816, sheet: 640, slides: 640 };+const TEXT_WIDTH = 480;++export type AttachmentPreview =+ | { kind: "document"; document: DocumentKind }+ | { kind: "markdown" }+ | { kind: "text" };++export function attachmentPreview(+ file: File | undefined,+ kind: AttachmentFileKind,+): AttachmentPreview | null {+ if (!file || file.size === 0 || file.size > MAX_PREVIEW_BYTES) return null;+ // The resolved kind is MIME first; only preview when the extension agrees with it.+ const document = documentKind(file.name, file.type);+ // The text adapter runs first: a text/plain "notes.pdf" is sent, so previewed, as text.+ const binary = document !== null && (document !== "sheet" || !sheetDelimiter(file.name, file.type));+ if (binary && isTextAttachment(file.name, file.type)) return { kind: "text" };+ if (document) return DOCUMENT_KINDS[document] === kind ? { kind: "document", document } : null;+ if (kind === "text" && isMarkdown(file.name, file.type)) return { kind: "markdown" };+ if (kind === "text" || kind === "code" || kind === "web") return { kind: "text" };+ return null;+}++const DOCUMENT_KINDS: Record<DocumentKind, AttachmentFileKind> = {+ pdf: "pdf",+ docx: "document",+ sheet: "spreadsheet",+ slides: "presentation",+};++/** Whether the element is on screen now; the strip clips offscreen cards. */+function useVisible(element: HTMLElement | null): boolean {+ const [visible, setVisible] = useState(false);+ useEffect(() => {+ if (!element) return;+ const observer = new IntersectionObserver((entries) => {+ const entry = entries[entries.length - 1];+ if (entry) setVisible(entry.isIntersecting);+ });+ observer.observe(element);+ return () => observer.disconnect();+ }, [element]);+ return visible;+}++function useSize(element: HTMLElement | null): { width: number; height: number } {+ const [size, setSize] = useState({ width: 0, height: 0 });+ useLayoutEffect(() => {+ if (!element) return;+ const measure = () => setSize({ width: element.clientWidth, height: element.clientHeight });+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ return () => observer.disconnect();+ }, [element]);+ return size;+}++// Same decoder as the attachment itself, so a declared charset reads correctly.+// Queued like Office parses: a charset-declaring file is read whole.+function useLeadingText(file: File, enabled: boolean): { text: string } | "failed" | null {+ const [state, setState] = useState<{ file: File; text: string | null } | null>(null);+ const done = state?.file === file;+ useEffect(() => {+ if (!enabled || done) return;+ let cancelled = false;+ queueParse(() => readAttachmentText(file, file.name, file.type), () => cancelled).then(+ (read) => !cancelled && read && setState({ file, text: read.text.slice(0, TEXT_PREVIEW_CHARS) }),+ () => !cancelled && setState({ file, text: null }),+ );+ return () => {+ cancelled = true;+ };+ }, [file, enabled, done]);+ if (state?.file !== file) return null;+ return state.text === null ? "failed" : { text: state.text };+}++/** First page of the file, scaled to fill the card. Display only: never focused or clicked. */+export const AttachmentCardPreview: FC<{+ file: File;+ preview: AttachmentPreview;+ /** Shown when the text cannot be decoded. */+ fallback: ReactNode;+}> = ({ file, preview, fallback }) => {+ const [frame, setFrame] = useState<HTMLDivElement | null>(null);+ const size = useSize(frame);+ // Reads start only while visible. Documents unmount offscreen; read text stays.+ const visible = useVisible(frame);+ const text = useLeadingText(file, visible && preview.kind !== "document");+ const pageWidth = preview.kind === "document" ? PAGE_WIDTH[preview.document] : TEXT_WIDTH;+ const scale = size.width / pageWidth;+ // PDF, Word and slide pages are white paper; sheets and text follow the theme.+ const paper = preview.kind === "document" && preview.document !== "sheet";++ if (text === "failed") return fallback;++ let body: ReactNode = null;+ if (preview.kind === "document") {+ body = visible ? (+ <DocumentView+ file={file}+ kind={preview.document}+ name={file.name}+ contentType={file.type}+ thumbnail={true}+ />+ ) : null;+ } else if (text !== null && preview.kind === "markdown") {+ body = (+ <MarkdownPreview+ markdown={text.text}+ inert={true}+ className="max-h-none overflow-visible border-0 bg-transparent px-6 py-5 text-ui-15p5"+ />+ );+ } else if (text !== null) {+ body = (+ <pre className="whitespace-pre-wrap break-words px-6 py-5 font-mono text-[13px] leading-snug text-foreground">+ {text.text}+ </pre>+ );+ }++ return (+ <div+ ref={setFrame}+ aria-hidden={true}+ inert={true}+ className={cn(+ "attachment-card-preview pointer-events-none relative size-full select-none overflow-hidden",+ paper ? "bg-white" : "bg-background",+ )}+ >+ {scale > 0 && (+ <div+ className="attachment-card-preview-page absolute top-0 left-0 flex origin-top-left flex-col"+ style={{ width: pageWidth, height: size.height / scale, transform: `scale(${scale})` }}+ >+ {body}+ </div>+ )}+ </div>+ );+};diff --git a/studio/frontend/src/components/assistant-ui/attachment.tsx b/studio/frontend/src/components/assistant-ui/attachment.tsxindex aa4de99ff5f..796d98ec87a 100644--- a/studio/frontend/src/components/assistant-ui/attachment.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment.tsx@@ -4,6 +4,10 @@"use client";// Avatar removed — caused circular crop on image thumbnails+import {+ AttachmentCardPreview,+ attachmentPreview,+} from "@/components/assistant-ui/attachment-card-preview";import { AttachmentPreviewDialog } from "@/components/assistant-ui/attachment-preview";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import { Button } from "@/components/ui/button";@@ -49,10 +53,9 @@ import {} from "@assistant-ui/react";import {AudioWave01Icon,- File01Icon,- File02Icon,+ FileEmpty02Icon,+ FlimSlateIcon,TextAlignLeft01Icon,- Video01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { ChevronRightIcon, PlusIcon, XIcon } from "lucide-react";@@ -100,10 +103,10 @@ const AttachmentThumb: FC = () => {<HugeiconsIconicon={isVideo- ? Video01Icon+ ? FlimSlateIcon: isAudioAttachment(name, contentType)? AudioWave01Icon- : File02Icon+ : FileEmpty02Icon}strokeWidth={2}className="size-6 text-muted-foreground"@@ -120,8 +123,9 @@ const SENT_IMAGE_SIZE_COMPACT = "size-[calc(5rem*var(--ui-space-scale,1))]";const SENT_ROW_WIDTH = "w-[calc(18rem*var(--ui-space-scale,1))]";const CARD_EDGE ="border border-[color-mix(in_oklab,var(--foreground)_calc(12%*var(--contrast-edge-gain,1)),transparent)]";+// No fill, so cards take the composer background; hover still tints.const CARD_SURFACE =- "bg-[color-mix(in_oklab,var(--foreground)_3%,transparent)] hover:bg-[color-mix(in_oklab,var(--foreground)_6%,transparent)]";+ "hover:bg-[color-mix(in_oklab,var(--foreground)_6%,transparent)]";const useAttachmentKind = (): {name: string;@@ -153,21 +157,28 @@ const AttachmentKindIcon: FC<{ kind: AttachmentFileKind; className?: string }> =/>);+const CardCenter: FC<{ children?: ReactNode }> = ({ children }) => (+ <span className="flex h-full min-h-0 flex-1 items-center justify-center px-3 text-muted-foreground">+ {children ?? <HugeiconsIcon icon={FileEmpty02Icon} strokeWidth={1.5} className="size-6" />}+ </span>+);+const FileCardBody: FC<{name: string;kind: AttachmentFileKind;center?: ReactNode;icon?: ReactNode;-}> = ({ name, kind, center, icon }) => (+ preview?: ReactNode;+}> = ({ name, kind, center, icon, preview }) => (<span className="flex h-full w-full flex-col">- <span className="flex min-h-0 flex-1 items-center justify-center px-3 text-muted-foreground">- {center ?? (- <HugeiconsIcon icon={File01Icon} strokeWidth={1.5} className="size-6" />- )}- </span>- <span className="flex min-w-0 items-center gap-1.5 px-3 pb-2.5">- {icon ?? <AttachmentKindIcon kind={kind} className="size-4" />}- <span className="min-w-0 truncate text-ui-13 leading-ui-18 text-foreground">+ {preview ? (+ <span className="min-h-0 flex-1 overflow-hidden">{preview}</span>+ ) : (+ <CardCenter>{center}</CardCenter>+ )}+ <span className={cn("flex min-w-0 items-center gap-1.5 px-2.25 pb-1.75", preview && "pt-1.25")}>+ {icon ?? <AttachmentKindIcon kind={kind} className="size-3.25" />}+ <span className="min-w-0 truncate text-ui-11p5 leading-ui-15 text-foreground">{name}</span></span>@@ -179,6 +190,7 @@ const CardImageOrBody: FC<{ name: string; kind: AttachmentFileKind; src: stringkind,src,}) => {+ const file = useAuiState(({ attachment }) => (attachment as { file?: File }).file);if (src) {return (<img@@ -188,7 +200,18 @@ const CardImageOrBody: FC<{ name: string; kind: AttachmentFileKind; src: string/>);}- return <FileCardBody name={name} kind={kind} />;+ const preview = attachmentPreview(file, kind);+ return (+ <FileCardBody+ name={name}+ kind={kind}+ preview={+ file && preview ? (+ <AttachmentCardPreview file={file} preview={preview} fallback={<CardCenter />} />+ ) : undefined+ }+ />+ );};type PastedTextAttachment = {@@ -340,7 +363,7 @@ const PastedTextAttachmentUI: FC<{variant === "card" ? (<buttonclassName={cn(- "aui-pasted-text-card group flex cursor-pointer overflow-hidden rounded-[18px] text-left transition-colors",+ "aui-pasted-text-card group flex cursor-pointer overflow-hidden rounded-[15px] text-left transition-colors",CARD_SIZE,CARD_EDGE,CARD_SURFACE,@@ -353,7 +376,7 @@ const PastedTextAttachmentUI: FC<{<FileCardBodyname={name}kind="text"- icon={textIcon("size-4")}+ icon={textIcon("size-3.25")}center={<span className="flex flex-col items-center gap-1 text-ui-11">{textIcon("size-6")}@@ -603,9 +626,9 @@ const ComposerAttachmentCard: FC = () => {<AttachmentPreviewDialog redactFromReload={true}><buttonclassName={cn(- "aui-attachment-card-tile flex cursor-pointer overflow-hidden rounded-[18px] text-left transition-colors",+ "aui-attachment-card-tile flex cursor-pointer overflow-hidden rounded-[15px] text-left transition-colors",CARD_SIZE,- !src && CARD_EDGE,+ CARD_EDGE,!src && CARD_SURFACE,)}type="button"diff --git a/studio/frontend/src/components/file-viewer/document-view.tsx b/studio/frontend/src/components/file-viewer/document-view.tsxindex b43e73f88d8..12587836f99 100644--- a/studio/frontend/src/components/file-viewer/document-view.tsx+++ b/studio/frontend/src/components/file-viewer/document-view.tsx@@ -14,19 +14,22 @@ export function DocumentView({name,contentType = "",scale = 1,+ thumbnail = false,}: {file: Blob;kind: DocumentKind;name: string;contentType?: string;scale?: number;+ /** Card thumbnail: first PDF page or slide only, Office parses queued. */+ thumbnail?: boolean;}) {return (<Suspense fallback={<Spinner className="m-auto size-6" />}>{kind === "pdf" ? (- <PdfView file={file} scale={scale} />+ <PdfView file={file} scale={scale} firstPageOnly={thumbnail} />) : (- <OfficeView file={file} kind={kind} name={name} contentType={contentType} scale={scale} />+ <OfficeView file={file} kind={kind} name={name} contentType={contentType} scale={scale} thumbnail={thumbnail} />)}</Suspense>);diff --git a/studio/frontend/src/components/file-viewer/office-view.tsx b/studio/frontend/src/components/file-viewer/office-view.tsxindex b04cc69b89a..f5456342951 100644--- a/studio/frontend/src/components/file-viewer/office-view.tsx+++ b/studio/frontend/src/components/file-viewer/office-view.tsx@@ -10,11 +10,13 @@ import { cn } from "@/lib/utils";import { useVirtualizer } from "@tanstack/react-virtual";import { type CSSProperties, type MouseEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { type DocumentKind, sheetDelimiter } from "./kind";+import { queueParse } from "./parse-queue";import { useWidth } from "./use-width";import {type Deck,type Sheet,type SheetCell,+ type SheetLimits,type Slide,type SlideBox,columnName,@@ -29,11 +31,19 @@ type Parsed =| { kind: "sheet"; sheets: Sheet[] }| { kind: "slides"; deck: Deck };-async function parse(file: Blob, kind: DocumentKind, name: string, contentType: string): Promise<Parsed> {+async function parse(+ file: Blob,+ kind: DocumentKind,+ name: string,+ contentType: string,+ thumbnail = false,+): Promise<Parsed> {const bytes = new Uint8Array(await file.arrayBuffer());if (kind === "docx") {const { default: mammoth } = await import("mammoth");- const repacked = repackDocxPreviewArchive(name, bytes, MAX_DOCX_PARAGRAPHS);+ const repacked = thumbnail+ ? repackDocxPreviewArchive(name, bytes, THUMBNAIL_DOCX_PARAGRAPHS, { keptImagesOnly: true })+ : repackDocxPreviewArchive(name, bytes, MAX_DOCX_PARAGRAPHS);let dropped = false;let pixelsLeft = MAX_DOCX_PIXELS;const convertImage = mammoth.images.imgElement(async (image) => {@@ -46,10 +56,17 @@ async function parse(file: Blob, kind: DocumentKind, name: string, contentType:return { src: "" };});const { value } = await mammoth.convertToHtml({ arrayBuffer: repacked.archive.buffer as ArrayBuffer }, { convertImage, idPrefix: "docx-" });- const { html, truncated } = sanitizeDocxHtml(value);+ const { html, truncated } = thumbnail+ ? sanitizeDocxHtml(value, THUMBNAIL_DOCX_ELEMENTS, { links: false })+ : sanitizeDocxHtml(value, MAX_DOCX_ELEMENTS);return { kind, html, truncated: truncated || repacked.truncated || dropped };}- if (kind === "slides") return { kind, deck: readPptx(bytes) };+ if (kind === "slides") {+ if (!thumbnail) return { kind, deck: readPptx(bytes) };+ return { kind, deck: { ...readPptx(bytes, { maxSlides: 1 }), truncated: false } };+ }+ // A card shows the top-left of the first sheet; later tabs keep their names only.+ const limits = thumbnail ? THUMBNAIL_SHEET_LIMITS : undefined;const delimiter = sheetDelimiter(name, contentType);if (delimiter) {const encoding =@@ -58,10 +75,10 @@ async function parse(file: Blob, kind: DocumentKind, name: string, contentType:: bytes[0] === 0xfe && bytes[1] === 0xff? "utf-16be": "utf-8";- const text = new TextDecoder(encoding).decode(bytes);- return { kind: "sheet", sheets: [readDelimited(text, delimiter, name)] };+ const text = new TextDecoder(encoding).decode(thumbnail ? bytes.subarray(0, THUMBNAIL_TEXT_BYTES) : bytes);+ return { kind: "sheet", sheets: [untruncated(readDelimited(text, delimiter, name, limits), thumbnail)] };}- return { kind: "sheet", sheets: readXlsx(bytes) };+ return { kind: "sheet", sheets: readXlsx(bytes, limits).map((sheet) => untruncated(sheet, thumbnail)) };}const DOCX_TAGS = new Set(@@ -72,13 +89,28 @@ const DOCX_ATTRIBUTES = new Set(["href", "src", "alt", "id", "colspan", "rowspanconst MAX_DOCX_PARAGRAPHS = 20_000;const MAX_DOCX_ELEMENTS = 50_000;const MAX_DOCX_PIXELS = 128 * 1024 * 1024;+// A card shows only the opening of a document.+const THUMBNAIL_DOCX_PARAGRAPHS = 60;+const THUMBNAIL_DOCX_ELEMENTS = 2_000;+const THUMBNAIL_SHEET_LIMITS: SheetLimits = { sheets: 1, rows: 60, columns: 30, extraNames: 8 };+const THUMBNAIL_TEXT_BYTES = 256 * 1024;++// A thumbnail cut is expected, so it shows no truncation note.+function untruncated(sheet: Sheet, thumbnail: boolean): Sheet {+ return thumbnail ? { ...sheet, truncated: false } : sheet;+}-function sanitizeDocxHtml(html: string): { html: string; truncated: boolean } {+// A thumbnail sits inside a button, so it drops links: interactive content cannot nest there.+function sanitizeDocxHtml(+ html: string,+ maxElements: number,+ { links = true } = {},+): { html: string; truncated: boolean } {// Cut before parsing: mammoth escapes each < in text, so every one left is a tag.const opening = /<[a-z]/gi;let cut = -1;for (let count = 0; opening.exec(html); count++) {- if (count === MAX_DOCX_ELEMENTS) {+ if (count === maxElements) {cut = opening.lastIndex - 2;break;}@@ -94,7 +126,7 @@ function sanitizeDocxHtml(html: string): { html: string; truncated: boolean } {const value = attr.value.trim().toLowerCase();const unsafe =!DOCX_ATTRIBUTES.has(attr.name) ||- (attr.name === "href" && !/^(https?:|mailto:|#)/.test(value)) ||+ (attr.name === "href" && (!links || !/^(https?:|mailto:|#)/.test(value))) ||(attr.name === "src" && !value.startsWith("data:image/"));if (unsafe) element.removeAttribute(attr.name);}@@ -290,7 +322,18 @@ function SheetGrid({);}-function SheetView({ sheets, tabs, scale }: { sheets: Sheet[]; tabs: boolean; scale: number }) {+function SheetView({+ sheets,+ tabs,+ scale,+ thumbnail = false,+}: {+ sheets: Sheet[];+ tabs: boolean;+ scale: number;+ /** Tabs as labels: a thumbnail sits inside a button. */+ thumbnail?: boolean;+}) {const t = useT();const uiScale = useUiSpaceScale();const [active, setActive] = useState(0);@@ -302,19 +345,21 @@ function SheetView({ sheets, tabs, scale }: { sheets: Sheet[]; tabs: boolean; sc{(tabs || sheet.truncated) && (<div className="flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2 py-1.5">{tabs &&- sheets.map((item, index) => (- <button- key={index}- type="button"- onClick={() => setActive(index)}- className={cn(- "shrink-0 rounded-md px-3 py-1 text-ui-13 transition-colors hover:bg-muted",- index === active ? "bg-muted font-medium text-foreground" : "text-muted-foreground",- )}- >- {item.name}- </button>- ))}+ sheets.map((item, index) => {+ const className = cn(+ "shrink-0 rounded-md px-3 py-1 text-ui-13 transition-colors hover:bg-muted",+ index === active ? "bg-muted font-medium text-foreground" : "text-muted-foreground",+ );+ return thumbnail ? (+ <span key={index} className={className}>+ {item.name}+ </span>+ ) : (+ <button key={index} type="button" onClick={() => setActive(index)} className={className}>+ {item.name}+ </button>+ );+ })}{sheet.truncated && (<span className="ml-auto shrink-0 px-2 text-ui-12 text-muted-foreground">{t("library.preview.sheetTruncated")}@@ -511,32 +556,43 @@ export default function OfficeView({name,contentType,scale,+ thumbnail = false,}: {file: Blob;kind: DocumentKind;name: string;contentType: string;scale: number;+ /** Card thumbnail: parse queued, first slide only. */+ thumbnail?: boolean;}) {const t = useT();const [state, setState] = useState<{ file: Blob; parsed?: Parsed; error?: boolean } | null>(null);useEffect(() => {let cancelled = false;- parse(file, kind, name, contentType).then(- (parsed) => !cancelled && setState({ file, parsed }),+ const run = () => parse(file, kind, name, contentType, thumbnail);+ (thumbnail ? queueParse(run, () => cancelled) : run()).then(+ (parsed) => !cancelled && parsed && setState({ file, parsed }),() => !cancelled && setState({ file, error: true }),);return () => {cancelled = true;};- }, [file, kind, name, contentType]);+ }, [file, kind, name, contentType, thumbnail]);const current = state?.file === file ? state : null;+ const parsed = current?.parsed;if (current?.error) {return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>;}- const parsed = current?.parsed;if (!parsed) return <Spinner className="m-auto size-6" />;if (parsed.kind === "docx") return <DocxView html={parsed.html} truncated={parsed.truncated} scale={scale} />;if (parsed.kind === "slides") return <SlidesView deck={parsed.deck} scale={scale} />;- return <SheetView sheets={parsed.sheets} tabs={!sheetDelimiter(name, contentType)} scale={scale} />;+ return (+ <SheetView+ sheets={parsed.sheets}+ tabs={!sheetDelimiter(name, contentType)}+ scale={scale}+ thumbnail={thumbnail}+ />+ );}diff --git a/studio/frontend/src/components/file-viewer/office.ts b/studio/frontend/src/components/file-viewer/office.tsindex 65acd0670de..d20e948c32a 100644--- a/studio/frontend/src/components/file-viewer/office.ts+++ b/studio/frontend/src/components/file-viewer/office.ts@@ -12,6 +12,16 @@ export const MAX_SHEET_COLUMNS = 200;const MAX_WORKBOOK_CELLS = MAX_SHEET_ROWS * (MAX_SHEET_COLUMNS + 1);const MAX_SHEETS = 100;+export interface SheetLimits {+ sheets: number;+ rows: number;+ columns: number;+ /** Sheets past the limit listed by name only, unparsed, up to this many. */+ extraNames?: number;+}++const FULL_SHEET_LIMITS: SheetLimits = { sheets: MAX_SHEETS, rows: MAX_SHEET_ROWS, columns: MAX_SHEET_COLUMNS };+export interface SheetCell {text: string;numeric?: boolean;@@ -860,6 +870,7 @@ function readSheet(style: (index: number) => CellStyle | undefined,date1904: boolean,budget: { cells: number },+ limits: SheetLimits,): Sheet {const rows: (SheetCell | undefined)[][] = [];const widths: (number | undefined)[] = [];@@ -869,7 +880,7 @@ function readSheet(const head = dataAt === -1 ? text : text.slice(0, dataAt);for (const [attrs] of elements(head, COL_OPEN, COL_CLOSE)) {const min = Number(attribute(attrs, "min") ?? 1);- const max = Math.min(Number(attribute(attrs, "max") ?? min), MAX_SHEET_COLUMNS);+ const max = Math.min(Number(attribute(attrs, "max") ?? min), limits.columns);const width = Number(attribute(attrs, "width"));const hide = isTrue(attribute(attrs, "hidden"));for (let i = min; i <= max; i++) {@@ -886,7 +897,7 @@ function readSheet(for (const [rowAttrs, rowBody] of elements(data, ROW_OPEN, ROW_CLOSE)) {const r = Number(attribute(rowAttrs, "r") ?? nextRow + 1) - 1;nextRow = r + 1;- if (r >= MAX_SHEET_ROWS || budget.cells <= 0) {+ if (r >= limits.rows || budget.cells <= 0) {truncated = true;break;}@@ -900,7 +911,7 @@ function readSheet(const ref = attribute(attrs, "r");const col = ref ? columnIndex(ref) : nextColumn;nextColumn = col + 1;- if (col >= MAX_SHEET_COLUMNS) {+ if (col >= limits.columns) {truncated ||= !rowHidden;continue;}@@ -1100,7 +1111,7 @@ function styleSections(bytes: Uint8Array | undefined): { doc: Document | null; creturn { doc: parseXml(`${open}${parts.join("")}</${prefix}styleSheet>`), cut };}-export function readXlsx(bytes: Uint8Array): Sheet[] {+export function readXlsx(bytes: Uint8Array, limits: SheetLimits = FULL_SHEET_LIMITS): Sheet[] {const read = archive(bytes);const main = mainPart(read, "xl/workbook.xml");if ((read.size(main) ?? 0) > MAX_XML_PART_BYTES) throw new Error("File is too large to preview.");@@ -1136,7 +1147,12 @@ export function readXlsx(bytes: Uint8Array): Sheet[] {const budget = { cells: MAX_WORKBOOK_CELLS };for (const sheet of all(workbook, "sheet")) {if (sheet.getAttribute("state") === "hidden" || sheet.getAttribute("state") === "veryHidden") continue;- if (budget.cells <= 0 || sheets.length >= MAX_SHEETS) {+ if (limits.extraNames !== undefined && sheets.length >= limits.sheets) {+ if (sheets.length >= limits.sheets + limits.extraNames) break;+ sheets.push({ name: sheet.getAttribute("name") ?? "Sheet", rows: [], widths: [], truncated: false });+ continue;+ }+ if (budget.cells <= 0 || sheets.length >= limits.sheets) {const last = sheets.at(-1);if (last) last.truncated = true;break;@@ -1145,23 +1161,28 @@ export function readXlsx(bytes: Uint8Array): Sheet[] {const part = path ? read.head(path, MAX_SHEET_XML_BYTES + 1) : undefined;if (!part) continue;const whole = part.length <= MAX_SHEET_XML_BYTES;- const { text, cut } = sheetText(part, Math.min(MAX_SHEET_ROWS, budget.cells), whole);+ const { text, cut } = sheetText(part, Math.min(limits.rows, budget.cells), whole);missed = false;- const parsed = readSheet(text, sheet.getAttribute("name") ?? "Sheet", string, style, date1904, budget);+ const parsed = readSheet(text, sheet.getAttribute("name") ?? "Sheet", string, style, date1904, budget, limits);if (cut || missed) parsed.truncated = true;sheets.push(parsed);}return sheets;}-export function readDelimited(text: string, delimiter: string, name: string): Sheet {+export function readDelimited(+ text: string,+ delimiter: string,+ name: string,+ limits: SheetLimits = FULL_SHEET_LIMITS,+): Sheet {const rows: (SheetCell | undefined)[][] = [];let row: (SheetCell | undefined)[] = [];let field = "";let quoted = false;let truncated = false;const push = () => {- if (row.length < MAX_SHEET_COLUMNS) {+ if (row.length < limits.columns) {const numeric = field.trim() !== "" && Number.isFinite(Number(field.replace(/[$,%]/g, "")));row.push(field === "" ? undefined : { text: field, numeric });} else truncated = true;@@ -1186,7 +1207,7 @@ export function readDelimited(text: string, delimiter: string, name: string): Shpush();rows.push(row);row = [];- if (rows.length >= MAX_SHEET_ROWS) {+ if (rows.length >= limits.rows) {truncated = i < text.length - 1;break;}@@ -1481,7 +1502,7 @@ function degrees(xfrm: Element | undefined): number {return Number(xfrm?.getAttribute("rot")) / 60000 || 0;}-export function readPptx(bytes: Uint8Array, { images = true } = {}): Deck {+export function readPptx(bytes: Uint8Array, { images = true, maxSlides = MAX_SLIDES } = {}): Deck {const read = archive(bytes);const main = mainPart(read, "ppt/presentation.xml");if ((read.size(main) ?? 0) > MAX_XML_PART_BYTES) throw new Error("File is too large to preview.");@@ -1503,7 +1524,7 @@ export function readPptx(bytes: Uint8Array, { images = true } = {}): Deck {for (const [index, path] of slidePaths.entries()) {if (!path) continue;if ((read.size(path) ?? 0) > MAX_XML_PART_BYTES) {- if (slides.length === MAX_SLIDES) {+ if (slides.length === maxSlides) {truncated = true;break;}@@ -1513,7 +1534,7 @@ export function readPptx(bytes: Uint8Array, { images = true } = {}): Deck {const part = read([path, relsPath(path)], MAX_XML_PART_BYTES);const slideXml = part[path];if (!slideXml || HIDDEN_SLIDE.test(strFromU8(slideXml.subarray(0, 16384)))) continue;- if (slides.length === MAX_SLIDES) {+ if (slides.length === maxSlides) {truncated = true;break;}diff --git a/studio/frontend/src/components/file-viewer/parse-queue.ts b/studio/frontend/src/components/file-viewer/parse-queue.tsnew file mode 100644index 00000000000..50875c63131--- /dev/null+++ b/studio/frontend/src/components/file-viewer/parse-queue.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A started parse cannot be cancelled, so thumbnails run a few at a time.+export const MAX_QUEUED_PARSES = 2;++let active = 0;+const waiting: (() => void)[] = [];++function next(): void {+ while (active < MAX_QUEUED_PARSES && waiting.length > 0) waiting.shift()!();+}++/** Runs `task` once a slot is free. Resolves null, without running it, if cancelled while waiting. */+export function queueParse<T>(task: () => Promise<T>, cancelled: () => boolean): Promise<T | null> {+ return new Promise<T | null>((resolve, reject) => {+ waiting.push(() => {+ if (cancelled()) {+ resolve(null);+ return;+ }+ active += 1;+ task()+ .then(resolve, reject)+ .finally(() => {+ active -= 1;+ next();+ });+ });+ next();+ });+}diff --git a/studio/frontend/src/components/file-viewer/pdf-view.tsx b/studio/frontend/src/components/file-viewer/pdf-view.tsxindex b475d2b0bf9..f5954fc862b 100644--- a/studio/frontend/src/components/file-viewer/pdf-view.tsx+++ b/studio/frontend/src/components/file-viewer/pdf-view.tsx@@ -7,6 +7,7 @@ import { useVirtualizer } from "@tanstack/react-virtual";import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";import { Document, Page, pdfjs, usePageContext } from "react-pdf";import "react-pdf/dist/Page/TextLayer.css";+import { queueParse } from "./parse-queue";import { useWidth } from "./use-width";pdfjs.GlobalWorkerOptions.workerSrc = new URL(@@ -198,7 +199,42 @@ function PdfPages({);}-export default function PdfView({ file, scale }: { file: Blob; scale: number }) {+/** Waits for a shared parse slot and holds it until `release`, so thumbnails load a few at a time. */+function useParseSlot(enabled: boolean, file: Blob): { ready: boolean; release: () => void } {+ const [ready, setReady] = useState<Blob | null>(null);+ const done = useRef<(() => void) | null>(null);+ const release = useCallback(() => {+ done.current?.();+ done.current = null;+ }, []);+ useEffect(() => {+ if (!enabled) return;+ let cancelled = false;+ void queueParse(+ () =>+ new Promise<void>((resolve) => {+ done.current = resolve;+ setReady(file);+ }),+ () => cancelled,+ );+ return () => {+ cancelled = true;+ release();+ };+ }, [enabled, file, release]);+ return { ready: !enabled || ready === file, release };+}++export default function PdfView({+ file,+ scale,+ firstPageOnly = false,+}: {+ file: Blob;+ scale: number;+ firstPageOnly?: boolean;+}) {const t = useT();const [container, setContainer] = useState<HTMLDivElement | null>(null);const available = useWidth(container);@@ -207,16 +243,19 @@ export default function PdfView({ file, scale }: { file: Blob; scale: number })const [aspect, setAspect] = useState(1.294);const [failed, setFailed] = useState<Blob | null>(null);const width = Math.max(200, Math.min(available, MAX_PAGE_WIDTH)) * scale;+ const slot = useParseSlot(firstPageOnly, file);if (failed === file) {return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>;}+ if (!slot.ready) return <div className="size-full bg-muted/60" />;return (<div ref={setContainer} className="size-full overflow-auto bg-muted/60"><Documentfile={file}options={PDF_OPTIONS}onLoadSuccess={(document) => {+ slot.release();setPdf(document);setPages(document.numPages);void document.getPage(1).then((page) => {@@ -224,20 +263,23 @@ export default function PdfView({ file, scale }: { file: Blob; scale: number })setAspect(clampAspect(viewport.height / viewport.width));});}}- onLoadError={() => setFailed(file)}+ onLoadError={() => {+ slot.release();+ setFailed(file);+ }}loading={<Spinner className="mx-auto mt-24 size-6" />}>{available > 0 && pdf && (<PdfPageskey={`${width}:${aspect}`}pdf={pdf}- pages={Math.min(pages, MAX_PDF_PAGES)}+ pages={firstPageOnly ? Math.min(pages, 1) : Math.min(pages, MAX_PDF_PAGES)}width={width}aspect={aspect}scrollElement={container}/>)}- {available > 0 && pdf && pages > MAX_PDF_PAGES && (+ {available > 0 && pdf && !firstPageOnly && pages > MAX_PDF_PAGES && (<p className="pb-6 text-center text-ui-12 text-muted-foreground">{t("library.preview.documentTruncated")}</p>)}</Document>diff --git a/studio/frontend/src/components/markdown/inert-components.ts b/studio/frontend/src/components/markdown/inert-components.tsnew file mode 100644index 00000000000..b2aec9c4053--- /dev/null+++ b/studio/frontend/src/components/markdown/inert-components.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Plain .ts so the node tests can load it.+import { type ComponentProps, createElement } from "react";++/** Links and task checkboxes as plain text, for markdown shown inside another control. */+export const INERT_MARKDOWN_COMPONENTS = {+ a: ({ children }: ComponentProps<"a">) =>+ createElement("span", { className: "text-primary underline decoration-primary/40 underline-offset-2" }, children),+ input: ({ type, checked }: ComponentProps<"input">) =>+ type === "checkbox" ? createElement("span", { "aria-hidden": true }, checked ? "☑ " : "☐ ") : null,+};diff --git a/studio/frontend/src/components/markdown/markdown-preview.tsx b/studio/frontend/src/components/markdown/markdown-preview.tsxindex 9359d197384..a14cee895ad 100644--- a/studio/frontend/src/components/markdown/markdown-preview.tsx+++ b/studio/frontend/src/components/markdown/markdown-preview.tsx@@ -18,6 +18,7 @@ import {useState,} from "react";import { Streamdown } from "streamdown";+import { INERT_MARKDOWN_COMPONENTS } from "./inert-components";import "katex/dist/katex.min.css";type MarkdownPlugins = NonNullable<@@ -45,6 +46,8 @@ type MarkdownPreviewProps = {markdown: string;className?: string;plain?: boolean;+ /** No links or checkboxes, for a preview nested in another control. */+ inert?: boolean;/*** Parse on the next idle callback so the surrounding UI paints first. For a document that* arrives whole and is big enough to stall - a finished research report - the wait is the same@@ -57,6 +60,7 @@ function MarkdownPreviewImpl({markdown,className,plain = false,+ inert = false,defer = false,}: MarkdownPreviewProps): ReactElement {// Math and mermaid over a document with neither still cost a pass per node, and shiki over a@@ -96,7 +100,7 @@ function MarkdownPreviewImpl({<Streamdownmode="static"plugins={plugins}- components={MARKDOWN_COMPONENTS}+ components={inert ? INERT_MARKDOWN_COMPONENTS : MARKDOWN_COMPONENTS}urlTransform={safeMarkdownUrl}controls={false}className={markdownClassName}diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 88bf85c1a5b..205ad85a9d1 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -498,7 +498,8 @@ export function isRtfAttachment(// CompositeAttachmentAdapter selects the first matching accept string. 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(+/** Whether the text adapter claims the file; it runs before the document ones. */+export function isTextAttachment(name: string,contentType: string | undefined,): boolean {@@ -663,7 +664,12 @@ function docxPreviewImages(bytes: Uint8Array): { isImage: (name: string) => boolreturn { isImage, used };}-function unpackDocxEntries(filename: string, bytes: Uint8Array, keepLarge = false): DocxArchive {+function unpackDocxEntries(+ filename: string,+ bytes: Uint8Array,+ keepLarge = false,+ skipImages = false,+): DocxArchive {const names = new Set<string>();const oversized = new Set<string>();let count = 0;@@ -680,7 +686,7 @@ function unpackDocxEntries(filename: string, bytes: Uint8Array, keepLarge = falsfilter: (entry) => {names.add(entry.name);const image = images?.isImage(entry.name) ?? false;- if (image && !images!.used.has(entry.name)) return false;+ if (image && (skipImages || !images!.used.has(entry.name))) return false;if (entry.originalSize > MAX_OPEN_DOCUMENT_XML_BYTES) {oversized.add(entry.name);if (!image) return false;@@ -780,15 +786,120 @@ export function repackDocxPreviewArchive(filename: string,bytes: Uint8Array,maxParagraphs: number,+ { keptImagesOnly = false } = {},): { archive: Uint8Array; truncated: boolean } {- const archive = unpackDocxEntries(filename, bytes, true);+ const archive = unpackDocxEntries(filename, bytes, true, keptImagesOnly);const mainDocument = assertDocxPartSizes(filename, archive);const main = archive.entries[mainDocument];const cut = main ? cutDocxParagraphs(strFromU8(main), maxParagraphs) : null;if (cut !== null) archive.entries[mainDocument] = strToU8(cut);+ if (keptImagesOnly && main) {+ addKeptDocxImages(bytes, archive, mainDocument, cut ?? strFromU8(main));+ }return { archive: zipSync(archive.entries, { level: 0 }), truncated: cut !== null };}+// Element tags only, skipping any ">" inside an attribute value.+const XML_ELEMENT_TAG_RE = /<[^\s/>!?](?:"[^"]*"|'[^']*'|[^"'>])*>/g;+// Relationship id attributes, whatever their prefix.+const DOCX_RELATIONSHIP_ID_ATTRIBUTE_RE = /^[\w.-]+:(?:embed|link|id)$/;+const DOCX_IMAGE_RELATIONSHIP_TYPE_RE = /\/image$/;++type DocxRelationship = { id: string; type: string; path: string };++function docxRelationships(rels: Uint8Array | undefined, base: string): DocxRelationship[] {+ if (!rels) return [];+ const list: DocxRelationship[] = [];+ const markup = strFromU8(rels).replace(XML_NON_ELEMENT_RE, "");+ for (const tag of markup.match(DOCX_RELATIONSHIP_TAG_RE) ?? []) {+ let id = "";+ let target = "";+ let type = "";+ for (const [, name, double, single] of tag.matchAll(XML_ATTRIBUTE_RE)) {+ const value = decodeXmlEntities(double ?? single ?? "");+ if (name === "Id") id = value;+ else if (name === "Target") target = value;+ else if (name === "Type") type = value;+ }+ if (id && target) list.push({ id, type, path: joinDocxPath(base, target) });+ }+ return list;+}++/** Each element tag's local name and attributes; comments, CDATA and text are skipped. */+function* docxElementTags(xml: string): Generator<{ local: string; attributes: Map<string, string> }> {+ for (const tag of xml.replace(XML_NON_ELEMENT_RE, "").match(XML_ELEMENT_TAG_RE) ?? []) {+ const name = /^<([^\s/>]+)/.exec(tag)![1]!;+ const attributes = new Map<string, string>();+ for (const [, key, double, single] of tag.matchAll(XML_ATTRIBUTE_RE)) {+ attributes.set(key!, decodeXmlEntities(double ?? single ?? ""));+ }+ yield { local: name.slice(name.indexOf(":") + 1), attributes };+ }+}++function relationshipIdsIn(xml: string): Set<string> {+ const ids = new Set<string>();+ for (const { attributes } of docxElementTags(xml)) {+ for (const [name, value] of attributes) if (DOCX_RELATIONSHIP_ID_ATTRIBUTE_RE.test(name)) ids.add(value);+ }+ return ids;+}++const DOCX_NOTE_REFERENCES: Record<string, string> = {+ footnoteReference: "footnote",+ endnoteReference: "endnote",+ commentReference: "comment",+};++/** Inflates only the images the kept body, and the notes it refers to, reference. */+function addKeptDocxImages(bytes: Uint8Array, archive: DocxArchive, mainDocument: string, body: string): void {+ const dirname = (path: string) => path.slice(0, Math.max(0, path.lastIndexOf("/")));+ const wanted = new Set<string>();+ const addImages = (relationships: DocxRelationship[], ids: Set<string>) => {+ for (const rel of relationships) {+ // Images only: an oversized altChunk or OLE part the first pass left out stays out.+ if (ids.has(rel.id) && DOCX_IMAGE_RELATIONSHIP_TYPE_RE.test(rel.type)) wanted.add(rel.path);+ }+ };+ const mainRels = docxRelationships(archive.entries[docxRelationshipsPath(mainDocument)], dirname(mainDocument));+ addImages(mainRels, relationshipIdsIn(body));+ // Notes the kept body refers to, by element name ("footnote") and id.+ const notes = new Map<string, Set<string>>();+ for (const { local, attributes } of docxElementTags(body)) {+ const note = DOCX_NOTE_REFERENCES[local];+ const id = [...attributes].find(([name]) => name === "id" || name.endsWith(":id"))?.[1];+ if (note && id !== undefined) notes.set(note, (notes.get(note) ?? new Set()).add(id));+ }+ for (const [note, noteIds] of notes) {+ const part = mainRels.find((rel) => rel.type.endsWith(`/${note}s`))?.path;+ const xml = part ? archive.entries[part] : undefined;+ if (!part || !xml) continue;+ // Just the referenced notes' elements, not the whole part.+ const element = new RegExp(`<([\\w.-]+:)?${note}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^"'>])*>[\\s\\S]*?</\\1?${note}>`, "g");+ const kept = [...strFromU8(xml).replace(XML_NON_ELEMENT_RE, "").matchAll(element)]+ .map(([whole]) => whole)+ .filter((whole) => {+ const open = docxElementTags(whole).next().value;+ const id = open && [...open.attributes].find(([name]) => name === "id" || name.endsWith(":id"))?.[1];+ return id !== undefined && noteIds.has(id);+ });+ addImages(docxRelationships(archive.entries[docxRelationshipsPath(part)], dirname(part)), relationshipIdsIn(kept.join("")));+ }+ if (wanted.size === 0) return;+ // One budget with the parts already unpacked.+ let unpacked = Object.values(archive.entries).reduce((total, entry) => total + entry.length, 0);+ const images = unzipSync(bytes, {+ filter: (entry) => {+ if (!wanted.has(entry.name) || archive.entries[entry.name]) return false;+ if (unpacked + entry.originalSize > MAX_DOCX_UNPACKED_BYTES) return false;+ unpacked += entry.originalSize;+ return true;+ },+ });+ Object.assign(archive.entries, images);+}+/** The bytes of a view, as an ArrayBuffer, without copying when it owns one. jszip reads the* whole buffer 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. */diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 2759cc1e974..b4fdc2a28f6 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -289,6 +289,7 @@ export {isAudioAttachment,attachmentBodyText,parseAttachmentText,+ isTextAttachment,readAttachmentText,repackDocxAttachmentArchive,repackDocxPreviewArchive,diff --git a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts b/studio/frontend/src/features/chat/lib/attachment-file-kind.tsindex e23a265bc11..986997ef4fe 100644--- a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts+++ b/studio/frontend/src/features/chat/lib/attachment-file-kind.ts@@ -5,17 +5,18 @@import {AudioWave01Icon,- Doc02Icon,File02Icon,- Globe02Icon,+ FileEmpty02Icon,+ FlimSlateIcon,Image02Icon,- Pdf02Icon,+ InternetIcon,+ Pdf01Icon,Presentation01Icon,SourceCodeIcon,- Video01Icon,- Xls02Icon,Zip02Icon,} from "@hugeicons/core-free-icons";+// Relative so the node tests can load this file.+import { SheetIcon } from "../../../lib/hugeicons-derived.ts";export type AttachmentFileKind =| "image"@@ -81,26 +82,27 @@ export function attachmentFileKind(return "file";}+// Same icon shapes as the Library (features/library/file-kind.ts).export const ATTACHMENT_KIND_ICONS = {image: Image02Icon,- pdf: Pdf02Icon,+ pdf: Pdf01Icon,audio: AudioWave01Icon,- video: Video01Icon,- document: Doc02Icon,- spreadsheet: Xls02Icon,+ video: FlimSlateIcon,+ document: File02Icon,+ spreadsheet: SheetIcon,presentation: Presentation01Icon,- web: Globe02Icon,+ web: InternetIcon,code: SourceCodeIcon,text: File02Icon,archive: Zip02Icon,- file: File02Icon,+ file: FileEmpty02Icon,} as const satisfies Record<AttachmentFileKind, unknown>;export const ATTACHMENT_KIND_ICON_CLASS: Record<AttachmentFileKind, string> = {image: "text-sky-500",pdf: "text-red-500",audio: "text-violet-500",- video: "text-pink-500",+ video: "text-pink-400 scale-90",document: "text-blue-500",spreadsheet: "text-emerald-500",presentation: "text-orange-500",diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.cssindex f0543b2cadb..22c3af94776 100644--- a/studio/frontend/src/index.css+++ b/studio/frontend/src/index.css@@ -4836,6 +4836,21 @@ html.force-reduced-motion .sidebar-section-drop-line {background-clip: padding-box;}+/* Attachment card page previews: drop the viewer's gray backdrop, padding and+ scrollbars so the first page fills the card. */+.attachment-card-preview-page > * {+ background: transparent;+ padding-block: 0;+}++.attachment-card-preview * {+ scrollbar-width: none;+}++.attachment-card-preview *::-webkit-scrollbar {+ display: none;+}+/* Composer textarea: keep the scroll thumb faint until the user hovers ordrags the thumb itself, so a tall draft never shows a heavy dark rail. */.composer-input,diff --git a/studio/frontend/tests/attachment-preview-text.test.ts b/studio/frontend/tests/attachment-preview-text.test.tsindex f40a51fbb6f..668e6f3c539 100644--- a/studio/frontend/tests/attachment-preview-text.test.ts+++ b/studio/frontend/tests/attachment-preview-text.test.ts@@ -25,9 +25,11 @@ const {extractPdfAttachmentText,getDocxAttachmentError,isAudioAttachment,+ isTextAttachment,parseAttachmentText,readAttachmentText,repackDocxAttachmentArchive,+ repackDocxPreviewArchive,truncateAttachmentPreviewText,} = await import("../src/features/chat/attachment-content.ts");const { definePDFJSModule } = await import("unpdf");@@ -1078,3 +1080,112 @@ test("an RTF reader stays bounded", async () => {await assert.rejects(readRtf(`{\\rtf1 ${"{".repeat(2000)}`), /nest too deeply/);await assert.rejects(readRtf("plain text"), /Not an RTF file/);});++test("a thumbnail repack inflates only the images its kept paragraphs use", () => {+ const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";+ const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+ const A = "http://schemas.openxmlformats.org/drawingml/2006/main";+ const picture = (id: string) => `<w:p><w:r><w:drawing><a:blip r:embed="${id}"/></w:drawing></w:r></w:p>`;+ const image = (id: string) =>+ `<Relationship Id="${id}" Type="${R}/image" Target="media/${id}.png"/>`;+ const bytes = zipSync({+ "[Content_Types].xml": strToU8(+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="png" ContentType="image/png"/></Types>`,+ ),+ "_rels/.rels": strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="d" Type="${R}/officeDocument" Target="word/document.xml"/></Relationships>`,+ ),+ "word/document.xml": strToU8(+ `<w:document xmlns:w="${W}" xmlns:r="${R}" xmlns:a="${A}"><w:body>${picture("rId1")}${picture("rId2")}</w:body></w:document>`,+ ),+ "word/_rels/document.xml.rels": strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${image("rId1")}${image("rId2")}</Relationships>`,+ ),+ "word/media/rId1.png": new Uint8Array([1, 2, 3]),+ "word/media/rId2.png": new Uint8Array([4, 5, 6]),+ });+ const names = (archive: Uint8Array) => Object.keys(unzipSync(archive)).filter((name) => name.endsWith(".png")).sort();+ assert.deepEqual(names(repackDocxPreviewArchive("a.docx", bytes, 1).archive), ["word/media/rId1.png", "word/media/rId2.png"]);+ const thumbnail = repackDocxPreviewArchive("a.docx", bytes, 1, { keptImagesOnly: true });+ assert.equal(thumbnail.truncated, true);+ assert.deepEqual(names(thumbnail.archive), ["word/media/rId1.png"]);+ const whole = repackDocxPreviewArchive("a.docx", bytes, 10, { keptImagesOnly: true });+ assert.deepEqual(names(whole.archive), ["word/media/rId1.png", "word/media/rId2.png"]);+});++test("a thumbnail repack restores only image parts the kept elements reference", () => {+ const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";+ const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+ const A = "http://schemas.openxmlformats.org/drawingml/2006/main";+ const rel = (id: string, type: string, target: string) =>+ `<Relationship Id="${id}" Type="${R}/${type}" Target="${target}"/>`;+ const body =+ `<w:p><w:r><w:drawing><a:blip r:embed="rId1"/></w:drawing></w:r></w:p>` ++ `<!-- <a:blip r:embed="rId2"/> --><w:p><w:r><w:t>r:embed="rId2"</w:t></w:r></w:p>` ++ `<w:altChunk r:id="rId3"/>`;+ const bytes = zipSync({+ "[Content_Types].xml": strToU8(+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="png" ContentType="image/png"/></Types>`,+ ),+ "_rels/.rels": strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="d" Type="${R}/officeDocument" Target="word/document.xml"/></Relationships>`,+ ),+ "word/document.xml": strToU8(+ `<w:document xmlns:w="${W}" xmlns:r="${R}" xmlns:a="${A}"><w:body>${body}<w:p/><w:p/></w:body></w:document>`,+ ),+ "word/_rels/document.xml.rels": strToU8(+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${rel("rId1", "image", "media/one.png")}${rel("rId2", "image", "media/two.png")}${rel("rId3", "aFChunk", "chunk.mht")}</Relationships>`,+ ),+ "word/media/one.png": new Uint8Array([1, 2, 3]),+ "word/media/two.png": new Uint8Array([4, 5, 6]),+ // Past the per-part ceiling, so the first pass leaves it out.+ "word/chunk.mht": new Uint8Array(11 * 1024 * 1024),+ });+ const kept = Object.keys(unzipSync(repackDocxPreviewArchive("a.docx", bytes, 3, { keptImagesOnly: true }).archive));+ assert.ok(kept.includes("word/media/one.png"));+ assert.ok(!kept.includes("word/media/two.png"));+ assert.ok(!kept.includes("word/chunk.mht"));+});++test("the text adapter claims text/plain documents but not real ones", () => {+ const cases: [string, string, boolean][] = [+ ["notes.pdf", "text/plain", true],+ ["notes.docx", "text/plain", true],+ ["a.pdf", "application/pdf", false],+ ["a.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", false],+ ["a.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", false],+ ["a.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", false],+ ["a.pdf", "", false],+ ];+ for (const [name, type, text] of cases) assert.equal(isTextAttachment(name, type), text, `${name} (${type || "no type"})`);+});++test("a thumbnail repack restores images in the notes its kept paragraphs refer to", () => {+ const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";+ const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+ const A = "http://schemas.openxmlformats.org/drawingml/2006/main";+ const PKG = "http://schemas.openxmlformats.org/package/2006/relationships";+ const ns = `xmlns:w="${W}" xmlns:r="${R}" xmlns:a="${A}"`;+ const note = (id: string, image: string) =>+ `<w:footnote w:id="${id}"><w:p><w:r><w:drawing><a:blip r:embed="${image}"/></w:drawing></w:r></w:p></w:footnote>`;+ const ref = (id: string) => `<w:p><w:r><w:footnoteReference w:id="${id}"/></w:r></w:p>`;+ const bytes = zipSync({+ "[Content_Types].xml": strToU8(+ `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="png" ContentType="image/png"/></Types>`,+ ),+ "_rels/.rels": strToU8(`<Relationships xmlns="${PKG}"><Relationship Id="d" Type="${R}/officeDocument" Target="word/document.xml"/></Relationships>`),+ "word/document.xml": strToU8(`<w:document ${ns}><w:body>${ref("1")}${ref("2")}</w:body></w:document>`),+ "word/_rels/document.xml.rels": strToU8(+ `<Relationships xmlns="${PKG}"><Relationship Id="f" Type="${R}/footnotes" Target="footnotes.xml"/></Relationships>`,+ ),+ "word/footnotes.xml": strToU8(`<w:footnotes ${ns}>${note("1", "rIdA")}${note("2", "rIdB")}</w:footnotes>`),+ "word/_rels/footnotes.xml.rels": strToU8(+ `<Relationships xmlns="${PKG}"><Relationship Id="rIdA" Type="${R}/image" Target="media/a.png"/><Relationship Id="rIdB" Type="${R}/image" Target="media/b.png"/></Relationships>`,+ ),+ "word/media/a.png": new Uint8Array([1]),+ "word/media/b.png": new Uint8Array([2]),+ });+ const kept = Object.keys(unzipSync(repackDocxPreviewArchive("a.docx", bytes, 1, { keptImagesOnly: true }).archive));+ assert.ok(kept.includes("word/media/a.png"));+ assert.ok(!kept.includes("word/media/b.png"));+});diff --git a/studio/frontend/tests/chat-attachment-display.test.ts b/studio/frontend/tests/chat-attachment-display.test.tsindex 2ec47e6a897..28f9dbb4f06 100644--- a/studio/frontend/tests/chat-attachment-display.test.ts+++ b/studio/frontend/tests/chat-attachment-display.test.ts@@ -218,13 +218,13 @@ test("files handed to a new chat wait until it is on screen", async () => {assert.match(fn, /\.then\(\(\) => \{\n\s*requestAnimationFrame\(/);});-test("an image card in the composer has no border or fill; file cards keep both", () => {+test("an image card in the composer shares the file card border but has no fill", () => {const card = ATTACHMENT.slice(ATTACHMENT.indexOf("const ComposerAttachmentCard: FC"),ATTACHMENT.indexOf("const SentAttachmentLayoutContext"),);assert.match(card, /const src = useAttachmentImageSrc\(\);/);- assert.match(card, /!src && CARD_EDGE,\n\s*!src && CARD_SURFACE,/);+ assert.match(card, /CARD_EDGE,\n\s*!src && CARD_SURFACE,/);assert.match(card, /<CardImageOrBody name=\{name\} kind=\{kind\} src=\{src\} \/>/);});@@ -248,7 +248,7 @@ test("a sent text file downloads whole, not the capped preview", async () => {test("a composer clip reads as a video, not by its .mp4 name as audio", () => {assert.match(ATTACHMENT, /if \(isVideoAttachment\(attachment\)\) return "Video";\n\s*return isAudioAttachment\(/);- assert.match(ATTACHMENT, /isVideo\n\s*\? Video01Icon\n\s*: isAudioAttachment\(name, contentType\)/);+ assert.match(ATTACHMENT, /isVideo\n\s*\? FlimSlateIcon\n\s*: isAudioAttachment\(name, contentType\)/);});test("a sent document shown from its stored text downloads and chats as a .txt", async () => {@@ -260,3 +260,8 @@ test("a sent document shown from its stored text downloads and chats as a .txt",assert.match(dialog, /const name = saveAs\?\.name \?\? \(source\.name \|\| "attachment"\);/);assert.match(dialog, /downloadFile\(blob, name, contentType \|\| undefined\)/);});++test("a card preview follows the text adapter before a binary document viewer", async () => {+ const preview = await readSrcAsync("components/assistant-ui/attachment-card-preview.tsx");+ assert.match(preview, /if \(binary && isTextAttachment\(file\.name, file\.type\)\) return \{ kind: "text" \};\n\s*if \(document\)/);+});diff --git a/studio/frontend/tests/file-viewer-office.test.ts b/studio/frontend/tests/file-viewer-office.test.tsindex 73bec7efe21..b89757a6d27 100644--- a/studio/frontend/tests/file-viewer-office.test.ts+++ b/studio/frontend/tests/file-viewer-office.test.ts@@ -7,7 +7,7 @@ import test from "node:test";import { DOMParser } from "@xmldom/xmldom";import { strToU8, zipSync } from "fflate";-import { formatNumber, readPptx, readXlsx } from "../src/components/file-viewer/office.ts";+import { formatNumber, readDelimited, readPptx, readXlsx } from "../src/components/file-viewer/office.ts";{const proto = Object.getPrototypeOf(new DOMParser().parseFromString("<a/>", "application/xml").documentElement);@@ -214,3 +214,60 @@ test("xlsx: out-of-range date values do not prevent reading the workbook", () =>));assert.deepEqual(sheet?.rows[0]?.map((cell) => cell?.text), ["1700000000", "Mar-23", "42"]);});++test("pptx: maxSlides stops reading after that many slides", () => {+ const P = "http://schemas.openxmlformats.org/presentationml/2006/main";+ const A = "http://schemas.openxmlformats.org/drawingml/2006/main";+ const ids = [1, 2, 3].map((n) => `<p:sldId id="${255 + n}" r:id="rId${n}"/>`).join("");+ const links = [1, 2, 3].map((n) => `<Relationship Id="rId${n}" Type="${REL}/slide" Target="slides/slide${n}.xml"/>`).join("");+ const slide = (t: string) =>+ strToU8(`<p:sld xmlns:p="${P}" xmlns:a="${A}"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${t}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`);+ const zip = zipSync({+ "ppt/presentation.xml": strToU8(`<p:presentation xmlns:p="${P}" xmlns:r="${REL}"><p:sldIdLst>${ids}</p:sldIdLst></p:presentation>`),+ "ppt/_rels/presentation.xml.rels": rels(links),+ "ppt/slides/slide1.xml": slide("one"),+ "ppt/slides/slide2.xml": slide("two"),+ "ppt/slides/slide3.xml": slide("three"),+ });+ assert.equal(readPptx(zip).slides.length, 3);+ const first = readPptx(zip, { maxSlides: 1 });+ assert.equal(first.slides.length, 1);+ assert.equal(first.truncated, true);+ assert.equal(first.slides[0]!.boxes[0]?.paragraphs?.[0]?.text, "one");+});++test("sheet limits cap rows, columns and parsed sheets", () => {+ const cells = (r: number) => Array.from({ length: 5 }, (_, c) => `<c r="${"ABCDE"[c]}${r}"><v>${r}</v></c>`).join("");+ const rows = Array.from({ length: 10 }, (_, i) => `<row r="${i + 1}">${cells(i + 1)}</row>`).join("");+ const sheet = strToU8(`<worksheet xmlns="${MAIN}"><sheetData>${rows}</sheetData></worksheet>`);+ const zip = zipSync({+ "xl/workbook.xml": strToU8(+ `<workbook xmlns="${MAIN}" xmlns:r="${REL}"><sheets><sheet name="One" sheetId="1" r:id="rId1"/><sheet name="Two" sheetId="2" r:id="rId2"/></sheets></workbook>`,+ ),+ "xl/_rels/workbook.xml.rels": rels(+ `<Relationship Id="rId1" Type="${REL}/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="${REL}/worksheet" Target="worksheets/sheet2.xml"/>`,+ ),+ "xl/worksheets/sheet1.xml": sheet,+ "xl/worksheets/sheet2.xml": sheet,+ });+ const full = readXlsx(zip);+ assert.deepEqual([full.length, full[1]!.rows.length], [2, 10]);+ const [first, second] = readXlsx(zip, { sheets: 1, rows: 3, columns: 2, extraNames: 1 });+ assert.equal(readXlsx(zip, { sheets: 1, rows: 3, columns: 2, extraNames: 0 }).length, 1);+ assert.equal(first!.rows.length, 3);+ assert.ok(first!.rows.every((row) => row.length <= 2));+ assert.equal(first!.truncated, true);+ assert.deepEqual([second!.name, second!.rows.length], ["Two", 0]);++ const csv = readDelimited("a,b,c\n1,2,3\n4,5,6\n7,8,9\n", ",", "x.csv", { sheets: 1, rows: 2, columns: 2 });+ assert.deepEqual(csv.rows.map((row) => row.map((cell) => cell?.text)), [["a", "b"], ["1", "2"]]);+});++test("thumbnails render no nested controls: sheet tabs as labels, Word links without href", async () => {+ const { readFileSync } = await import("node:fs");+ const view = readFileSync(new URL("../src/components/file-viewer/office-view.tsx", import.meta.url), "utf8");+ assert.match(view, /return thumbnail \? \(\n\s*<span key=\{index\} className=\{className\}>/);+ assert.match(view, /sanitizeDocxHtml\(value, THUMBNAIL_DOCX_ELEMENTS, \{ links: false \}\)/);+ assert.match(view, /attr\.name === "href" && \(!links \|\|/);+ assert.match(view, /thumbnail=\{thumbnail\}\n\s*\/>/);+});diff --git a/studio/frontend/tests/file-viewer-parse-queue.test.ts b/studio/frontend/tests/file-viewer-parse-queue.test.tsnew file mode 100644index 00000000000..08e5e396251--- /dev/null+++ b/studio/frontend/tests/file-viewer-parse-queue.test.ts@@ -0,0 +1,67 @@+// 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 { MAX_QUEUED_PARSES, queueParse } from "../src/components/file-viewer/parse-queue.ts";++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++test("no more than the limit run at once, and the rest start as slots free", { timeout: 2000 }, async () => {+ let running = 0;+ let peak = 0;+ const gates = Array.from({ length: 6 }, deferred);+ const results = gates.map((gate, index) =>+ queueParse(async () => {+ running += 1;+ peak = Math.max(peak, running);+ await gate.promise;+ running -= 1;+ return index;+ }, () => false),+ );+ await Promise.resolve();+ assert.equal(running, MAX_QUEUED_PARSES);+ for (const gate of gates) gate.resolve();+ assert.deepEqual(await Promise.all(results), [0, 1, 2, 3, 4, 5]);+ assert.equal(peak, MAX_QUEUED_PARSES);+});++test("a task cancelled while waiting never runs and frees no slot it never took", { timeout: 2000 }, async () => {+ const gates = Array.from({ length: MAX_QUEUED_PARSES }, deferred);+ const busy = gates.map((gate) => queueParse(() => gate.promise, () => false));+ let ran = false;+ let cancelled = false;+ const skipped = queueParse(async () => {+ ran = true;+ }, () => cancelled);+ const after = queueParse(async () => "after", () => false);+ cancelled = true;+ for (const gate of gates) gate.resolve();+ await Promise.all(busy);+ assert.equal(await skipped, null);+ assert.equal(await after, "after");+ assert.equal(ran, false);+});++test("a failed task still frees its slot", { timeout: 2000 }, async () => {+ await assert.rejects(queueParse(() => Promise.reject(new Error("bad file")), () => false), /bad file/);+ await new Promise((settle) => setImmediate(settle));+ let running = 0;+ const gates = Array.from({ length: MAX_QUEUED_PARSES }, deferred);+ const busy = gates.map((gate) =>+ queueParse(async () => {+ running += 1;+ await gate.promise;+ }, () => false),+ );+ assert.equal(running, MAX_QUEUED_PARSES);+ for (const gate of gates) gate.resolve();+ await Promise.all(busy);+});diff --git a/studio/frontend/tests/markdown-inert-components.test.ts b/studio/frontend/tests/markdown-inert-components.test.tsnew file mode 100644index 00000000000..73d1f658ff7--- /dev/null+++ b/studio/frontend/tests/markdown-inert-components.test.ts@@ -0,0 +1,28 @@+// 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 React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { Streamdown } from "streamdown";+import { INERT_MARKDOWN_COMPONENTS } from "../src/components/markdown/inert-components.ts";++const MARKDOWN = "See [the docs](https://unsloth.ai) and <https://example.com>.\n\n- [x] done\n- [ ] todo\n";++function render(components?: typeof INERT_MARKDOWN_COMPONENTS): string {+ return renderToStaticMarkup(+ React.createElement(Streamdown, { mode: "static", controls: false, components }, MARKDOWN),+ );+}++test("inert markdown renders links and task checkboxes as text", () => {+ const plain = render();+ assert.match(plain, /<(?:a|button)[\s>]/);+ assert.match(plain, /<input/);+ const inert = render(INERT_MARKDOWN_COMPONENTS);+ assert.doesNotMatch(inert, /<a[\s>]|<input|<button/);+ assert.match(inert, /the docs/);+ assert.match(inert, /☑ /);+ assert.match(inert, /☐ /);+});