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
Studio: composer accepts every document type chat with files parses (#13426)
Michael Hana595d4986976
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 834e25e99d6..78886380aa2 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1433,10 +1433,10 @@ _VIDEO_MULTIPART_UPLOAD_PATHS = ("/api/inference/videos",)_LIBRARY_UPLOAD_PATH = "/api/library/uploads"-# RAG document uploads (knowledge base, thread, project): multipart, capped by RAG_MAX_UPLOAD_BYTES in the route and+# RAG document uploads (knowledge base, thread, project, extract-text): multipart, capped by RAG_MAX_UPLOAD_BYTES in the route and# spooled by FastAPI, so they pass through on Content-Length instead of being held in memory here._RAG_DOCUMENT_UPLOAD_RE = _re.compile(- r"^/api/rag/(?:knowledge-bases|threads|projects)/[^/]+/documents/?$"+ r"^/api/rag/(?:(?:knowledge-bases|threads|projects)/[^/]+/documents|extract-text)/?$")# One file into a chat's sandbox folder (multipart, capped by the route), on both mounts of the router._SANDBOX_UPLOAD_RE = _re.compile(r"^/(?:api/inference|v1)/sandbox/[^/]+/upload/?$")diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.pyindex aae35747bf5..0ef0cce7dac 100644--- a/studio/backend/routes/rag.py+++ b/studio/backend/routes/rag.py@@ -6,7 +6,8 @@ access, not data.Without a working sqlite-vec the router still mounts, and one contract covers every endpoint. The KB list ispolled, so it answers 200 with an empty list carrying an availability marker, which is what lets a client tell-an empty store from a machine where RAG cannot run. Every other endpoint answers 503 stating the same reason.+an empty store from a machine where RAG cannot run. Every other endpoint but /extract-text, which only parses,+answers 503 stating the same reason.Nothing logs a traceback for it: the condition is fixed for the session and rag_db warns about it exactly once."""@@ -954,6 +955,45 @@ def folder_job_events()+# MAX_TEXT_ATTACHMENT_BYTES in text-attachment-accept.ts: the composer's ceiling for inline text.+_EXTRACT_TEXT_MAX_BYTES = 20 * 1024 * 1024+++# Not gated on sqlite-vec: the composer inlines the text of files its browser readers cannot open.[email protected]("/extract-text")+def extract_text(file: UploadFile = File(...), subject: str = Depends(get_current_subject)) -> dict:+ from core.rag import parsers++ stored_path, filename, _digest = _save_upload(file)+ try:+ pages = parsers.parse(stored_path)+ except ImportError as exc:+ raise HTTPException(status_code = 503, detail = f"{filename} could not be read: {exc}") from exc+ # Not only ValueError: python-docx raises its own errors for a damaged .docm/.dotx.+ except Exception as exc:+ raise HTTPException(status_code = 422, detail = f"{filename} could not be read: {exc}") from exc+ finally:+ _remove_stored_upload(stored_path)+ # Capped page by page: joining everything first would hold a huge extraction several times over.+ parts: list[bytes] = []+ room = _EXTRACT_TEXT_MAX_BYTES+ truncated = False+ for page in pages:+ chunk = page.text.strip().encode("utf-8")+ if not chunk:+ continue+ if parts:+ chunk = b"\n\n" + chunk+ if len(chunk) > room:+ parts.append(chunk[:room])+ truncated = True+ break+ parts.append(chunk)+ room -= len(chunk)+ text = b"".join(parts).decode("utf-8", errors = "ignore")+ return {"filename": filename, "text": text, "truncated": truncated}++@router.post("/search")def search(payload: SearchRequest, subject: str = Depends(get_current_subject)) -> dict:_require_rag()diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex 56a05d42418..92994fa50bd 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -1665,6 +1665,7 @@ def test_rag_document_uploads_pass_through_on_their_own_cap(main_module, monkeyp"/api/rag/knowledge-bases/kb1/documents","/api/rag/threads/t1/documents","/api/rag/projects/p1/documents/",+ "/api/rag/extract-text",):assert pattern.match(path), pathassert main_module._get_upload_passthrough_request_max_bytes(diff --git a/studio/backend/tests/test_rag_extract_text.py b/studio/backend/tests/test_rag_extract_text.pynew file mode 100644index 00000000000..e39b074d359--- /dev/null+++ b/studio/backend/tests/test_rag_extract_text.py@@ -0,0 +1,84 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""/api/rag/extract-text: the composer's reader for documents the browser cannot open."""++import io+import os++import pytest+from fastapi import HTTPException, UploadFile++from routes import rag as rag_routes+from utils.paths import rag_uploads_root++MHT = (+ "MIME-Version: 1.0\r\n"+ 'Content-Type: multipart/related; boundary="b"\r\n\r\n'+ "--b\r\nContent-Type: text/html; charset=utf-8\r\n\r\n"+ "<html><body><h1>Quarterly</h1><p>Revenue rose 12%.</p></body></html>\r\n"+ "--b--\r\n"+)+++def _upload(name: str, data: bytes) -> UploadFile:+ return UploadFile(file = io.BytesIO(data), filename = name)+++def _uploads_left() -> list[str]:+ root = rag_uploads_root()+ return os.listdir(root) if os.path.isdir(root) else []+++def test_extracts_text_and_keeps_no_copy(rag_home):+ result = rag_routes.extract_text(_upload("report.mht", MHT.encode()), subject = "owner")+ assert result["filename"] == "report.mht"+ assert "Quarterly" in result["text"] and "Revenue rose 12%." in result["text"]+ assert result["truncated"] is False+ assert _uploads_left() == []+++def test_works_without_sqlite_vec(rag_home, monkeypatch):+ from storage import rag_db++ monkeypatch.setattr(rag_db, "rag_available", lambda: False)+ result = rag_routes.extract_text(+ _upload("page.xhtml", b"<html><body><p>hello</p></body></html>"), subject = "owner"+ )+ assert result["text"] == "hello"+++def test_unsupported_type_is_refused(rag_home):+ with pytest.raises(HTTPException) as exc:+ rag_routes.extract_text(_upload("model.gguf", b"GGUF"), subject = "owner")+ assert exc.value.status_code == 400+ assert _uploads_left() == []++[email protected]("name", ["broken.doc", "broken.docm", "broken.epub"])+def test_damaged_document_is_422_and_cleaned_up(rag_home, name):+ with pytest.raises(HTTPException) as exc:+ rag_routes.extract_text(_upload(name, b"not a document"), subject = "owner")+ assert exc.value.status_code == 422+ assert name in exc.value.detail+ assert _uploads_left() == []+++def test_text_is_capped_on_a_character_boundary(rag_home, monkeypatch):+ monkeypatch.setattr(rag_routes, "_EXTRACT_TEXT_MAX_BYTES", 7)+ html = "<html><body><p>ééééé</p></body></html>".encode()+ result = rag_routes.extract_text(_upload("page.xhtml", html), subject = "owner")+ assert result == {"filename": "page.xhtml", "text": "ééé", "truncated": True}+++def test_cap_stops_at_the_page_that_crosses_it(rag_home, monkeypatch):+ from core.rag import parsers++ pages = [parsers._page(text, n) for n, text in enumerate(["first", " ", "second", "third"], 1)]+ monkeypatch.setattr(parsers, "parse", lambda path: pages)+ monkeypatch.setattr(rag_routes, "_EXTRACT_TEXT_MAX_BYTES", 12)+ result = rag_routes.extract_text(_upload("deck.ppt", b"x"), subject = "owner")+ assert (result["text"], result["truncated"]) == ("first\n\nsecon", True)+ monkeypatch.setattr(rag_routes, "_EXTRACT_TEXT_MAX_BYTES", 1024)+ result = rag_routes.extract_text(_upload("deck.ppt", b"x"), subject = "owner")+ assert (result["text"], result["truncated"]) == ("first\n\nsecond\n\nthird", False)diff --git a/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx b/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsxindex d84874eb6e2..1d53a6af1a3 100644--- a/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx@@ -10,7 +10,12 @@ import {import type { AttachmentSource } from "@/components/assistant-ui/use-attachment-source";import { AttachmentBrowserOpenContext } from "@/components/assistant-ui/attachment-browser-open-context";import { filesOpenInBrowser } from "@/features/browser";-import { DocumentView, documentKind, isMarkdown } from "@/components/file-viewer";+import {+ DocumentView,+ MAX_DOCUMENT_PREVIEW_BYTES,+ documentKind,+ isMarkdown,+} from "@/components/file-viewer";import { MarkdownPreview } from "@/components/markdown/markdown-preview";import {type MediaViewerActions,@@ -185,6 +190,10 @@ const DocumentBody: FC<{ name: string; contentType?: string; loaded: Loaded; sca}const kind = documentKind(name, contentType);if (!loaded.blob || !kind) return <Spinner className="m-auto size-6" />;+ // The Library's ceiling: a larger file was read on the server, and parsing it here blocks the main thread.+ if (loaded.blob.size > MAX_DOCUMENT_PREVIEW_BYTES) {+ return <p className="m-auto text-sm text-muted-foreground">{t("library.preview.cannotPreview")}</p>;+ }return <DocumentView file={loaded.blob} kind={kind} name={name} contentType={contentType} scale={scale} />;};diff --git a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx b/studio/frontend/src/components/assistant-ui/attachment-preview.tsxindex 2bcab1cc37b..0ab6ae20b75 100644--- a/studio/frontend/src/components/assistant-ui/attachment-preview.tsx+++ b/studio/frontend/src/components/assistant-ui/attachment-preview.tsx@@ -71,7 +71,8 @@ type TextPreviewState =| { status: "error" }| ({ status: "ready" } & AttachmentText);-const WEB_PAGE_NAME = /\.(html?|xhtml)$/i;+// Not .xhtml: the composer sends the backend parser's text for it, which must not render as markup.+const WEB_PAGE_NAME = /\.html?$/i;const fetchBlob = (src: string): Promise<Blob> => fetch(src).then((response) => response.blob());diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex efacd497bb1..2dd662c7b43 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -19,6 +19,7 @@ import {OPEN_DOCUMENT_TEXT_MIME,RTF_MIMES,isRtfAttachmentName,+ isServerDocumentAttachmentName,isToolOnlyAttachmentName,} from "./open-document-accept";import { readRtfAttachmentContent } from "./rtf";@@ -2055,6 +2056,14 @@ export async function readAttachmentText(name: string,contentType: string | undefined,): Promise<AttachmentText> {+ // Before text, which claims a .mht sent as message/rfc822; a large .odt/.ods reuses its server read.+ if (+ isServerDocumentAttachmentName(name) ||+ (file.size > MAX_OPEN_DOCUMENT_ARCHIVE_BYTES && isOpenDocumentAttachment(name, contentType))+ ) {+ const { extractServerDocumentText } = await import("./server-document");+ return { label: null, text: await extractServerDocumentText(file), truncated: false };+ }if (isTextAttachment(name, contentType)) {return { label: null, ...(await readBoundedText(file)) };}diff --git a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts b/studio/frontend/src/features/chat/lib/attachment-file-kind.tsindex 333b0302752..53ebee74ef2 100644--- a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts+++ b/studio/frontend/src/features/chat/lib/attachment-file-kind.ts@@ -43,10 +43,10 @@ register();register("video", "mp4 m4v mov mkv avi webm 3gp 3g2 mpg mpeg wmv");register("word", "doc docx docm dot dotx dotm odt ott rtf gdoc");-register("document", "pages epub");-register("spreadsheet", "csv tsv xls xlsx xlsm ods numbers");-register("presentation", "ppt pptx odp key");-register("web", "html htm xhtml mhtml");+register("document", "pages epub msg eml");+register("spreadsheet", "csv tsv xls xlsx xlsm xltx xltm ods ots numbers");+register("presentation", "ppt pptx pptm ppsx ppsm potx potm odp otp key");+register("web", "html htm xhtml xht mht mhtml");register("code","py pyi ipynb js mjs cjs ts mts cts tsx jsx json jsonl c h cc cpp cxx hpp cs java kt kts go rs rb php swift scala sh bash zsh fish ps1 bat cmd css scss sass less sql yaml yml toml ini cfg conf xml r lua dart vue svelte gradle cmake proto graphql gql pl hs ex exs erl clj zig nim jl m mm",diff --git a/studio/frontend/src/features/chat/open-document-accept.ts b/studio/frontend/src/features/chat/open-document-accept.tsindex 77b5501fa95..380a664c033 100644--- a/studio/frontend/src/features/chat/open-document-accept.ts+++ b/studio/frontend/src/features/chat/open-document-accept.ts@@ -30,6 +30,21 @@ export function isRtfAttachmentName(filename: string): boolean {return filename.toLowerCase().endsWith(RTF_ATTACHMENT_EXTENSIONS);}+// RAG_DOCUMENT_UPLOAD_ACCEPT minus browser-read types; spelled out so this module stays a chat-barrel leaf.+export const SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS = [+ ".doc,.docm,.dotx,.dotm,.xls,.xltx,.xltm,.ppt,.pptm,.potx,.potm,.ppsx,.ppsm",+ ".odp,.ott,.ots,.otp,.msg,.mht,.mhtml,.epub,.xhtml,.xht",+].join(",");+// RAG's MAX_UPLOAD_BYTES.+export const MAX_SERVER_DOCUMENT_BYTES = 200 * 1024 * 1024;++export function isServerDocumentAttachmentName(name: string): boolean {+ const lower = name.toLowerCase();+ return SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS.split(",").some((ext) =>+ lower.endsWith(ext),+ );+}+// Matched by extension only: their MIME types are missing or shared with unrelated files.// Keep in sync with TOOL_ONLY_ATTACHMENT_EXTS in native_path_policy.rs.export const TOOL_ONLY_ATTACHMENT_EXTENSIONS = [diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 1e0eb4f1860..b97e4037bd5 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -112,6 +112,7 @@ import {} from "./image-normalize";import { chatModelLoaded } from "./lib/chat-model-loaded";import {+ MAX_OPEN_DOCUMENT_ARCHIVE_BYTES,type OpenDocumentAttachmentContent,readActiveOpenDocumentAttachmentContent,readOpenDocumentAttachmentContent,@@ -119,7 +120,9 @@ import {import {OPEN_DOCUMENT_ATTACHMENT_ACCEPT,RTF_ATTACHMENT_ACCEPT,+ SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS,TOOL_ONLY_ATTACHMENT_EXTENSIONS,+ isToolOnlyAttachmentName,} from "./open-document-accept";import {providerHostsCodeExecution,@@ -235,6 +238,7 @@ import {import { syncExportedRepositoryToBackend } from "./utils/delete-thread-message";import { getImageInputUnavailableReason } from "./utils/image-input-support";import {+ attachmentContentText,attachmentsSample,} from "./utils/pasted-text";import { annotationsOfFile } from "./utils/document-annotations";@@ -730,8 +734,9 @@ class HtmlAttachmentAdapter implements AttachmentAdapter {}class DocxAttachmentAdapter implements AttachmentAdapter {+ // The extension too: a .docx can arrive with an empty MIME type.accept =- "application/vnd.openxmlformats-officedocument.wordprocessingml.document";+ ".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document";// The archive's own parts are checked too: a small .docx can declare a part that only mammoth's// inflate grows past the cap, and refusing that at send() would empty the composer.@@ -885,6 +890,142 @@ class RtfAttachmentAdapter implements AttachmentAdapter {}}+class ServerDocumentAttachmentAdapter implements AttachmentAdapter {+ accept = SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS;+ // null: no text to inline, so the python tool opens the file, as when .epub/.odp were tool-only.+ private readonly texts = new Map<string, Promise<string | null>>();++ owns(id: string): boolean {+ return this.texts.has(id);+ }++ private read(file: File): Promise<string | null> {+ // Loaded on use: the first screen has no document to read.+ const text = import("./server-document").then((m) => m.extractServerDocumentText(file));+ return text.catch((cause: unknown) => {+ // Not PDFs: their originals stop at 50 MB (chat_originals.max_bytes), so a textless one here is refused.+ if (+ (cause as Error | undefined)?.name === "NoDocumentTextError" &&+ isToolOnlyAttachmentName(file.name) &&+ pythonToolOpensAttachments()+ ) {+ return null;+ }+ throw cause;+ });+ }++ async *add({+ file,+ }: {+ file: File;+ }): AsyncGenerator<PendingAttachment, void> {+ const attachment = {+ id: crypto.randomUUID(),+ type: "document",+ name: file.name,+ contentType: file.type,+ file,+ status: { type: "running", reason: "uploading", progress: 0 },+ } satisfies PendingAttachment;+ const text = this.read(file);+ this.texts.set(attachment.id, text);+ yield attachment;+ let error: string | null = null;+ try {+ await text;+ } catch (cause) {+ error = (cause as Error).message;+ }+ // Removed or sent while reading: yielding again would put the chip back.+ if (this.texts.get(attachment.id) !== text) return;+ if (error) {+ toast.error(error);+ yield { ...attachment, status: { type: "incomplete", reason: "error" } };+ return;+ }+ yield {+ ...attachment,+ status: { type: "requires-action", reason: "composer-send" },+ };+ }++ async send(attachment: PendingAttachment): Promise<CompleteAttachment> {+ const pending = this.texts.get(attachment.id) ?? this.read(attachment.file);+ this.texts.delete(attachment.id);+ let text: string | null;+ try {+ text = await pending;+ } catch (cause) {+ // Thrown, not sent as text: PreStreamAwareAttachmentAdapter then cancels the run.+ toast.error((cause as Error).message);+ throw cause;+ }+ // Rechecked: without the python tool no original is kept, leaving the model only the placeholder.+ if (text === null && !pythonToolOpensAttachments()) {+ const error = `${attachment.name} has no text to read. Turn on Code so the python tool can open it.`;+ toast.error(error);+ throw new Error(error);+ }+ return {+ id: attachment.id,+ type: "document",+ name: attachment.name,+ contentType: attachment.contentType,+ content: [+ {+ type: "text",+ text:+ text === null+ ? `[${attachment.name}: only the python tool can read this file]`+ : attachmentContentText(attachment.name, text, false),+ },+ ],+ status: { type: "complete" },+ };+ }++ remove(attachment: Attachment): Promise<void> {+ this.texts.delete(attachment.id);+ return Promise.resolve();+ }+}++class LargeDocumentFallbackAdapter implements AttachmentAdapter {+ private readonly browser: AttachmentAdapter;+ private readonly server: ServerDocumentAttachmentAdapter;++ constructor(+ browser: AttachmentAdapter,+ server: ServerDocumentAttachmentAdapter,+ ) {+ this.browser = browser;+ this.server = server;+ }++ get accept(): string {+ return this.browser.accept;+ }++ add(state: { file: File }) {+ return state.file.size > MAX_OPEN_DOCUMENT_ARCHIVE_BYTES+ ? this.server.add(state)+ : this.browser.add(state);+ }++ send(attachment: PendingAttachment): Promise<CompleteAttachment> {+ return this.server.owns(attachment.id)+ ? this.server.send(attachment)+ : this.browser.send(attachment);+ }++ remove(attachment: Attachment): Promise<void> {+ return this.server.owns(attachment.id)+ ? this.server.remove(attachment)+ : this.browser.remove(attachment);+ }+}+class OpenDocumentAttachmentAdapter implements AttachmentAdapter {private readonly active = new Set<string>();private readonly sending = new Set<string>();@@ -2896,21 +3037,25 @@ function useStudioRuntimeAdapters(: undefined,[],);- const attachments = useMemo(- () =>- new PreStreamAwareAttachmentAdapter(+ const attachments = useMemo(() => {+ const server = new ServerDocumentAttachmentAdapter();+ const largeFallback = (browser: AttachmentAdapter) =>+ new LargeDocumentFallbackAdapter(browser, server);+ return new PreStreamAwareAttachmentAdapter(new CompositeAttachmentAdapter([new VisionImageAdapter(),new AudioAttachmentAdapter(),// Before the document adapters: a composite takes the first match, and .mkv/.mov must not fall// through to them.new VideoAttachmentAdapter(),+ // Before text, which claims message/rfc822 (.mht), and tool-only, which lists .epub/.docm/.odp.+ server,new TextAttachmentAdapter(),new HtmlAttachmentAdapter(),- new PDFAttachmentAdapter(),- new DocxAttachmentAdapter(),- new OfficeAttachmentAdapter(),- new OpenDocumentAttachmentAdapter(),+ largeFallback(new PDFAttachmentAdapter()),+ largeFallback(new DocxAttachmentAdapter()),+ largeFallback(new OfficeAttachmentAdapter()),+ largeFallback(new OpenDocumentAttachmentAdapter()),new RtfAttachmentAdapter(),new ToolOnlyAttachmentAdapter(),]),@@ -2921,9 +3066,8 @@ function useStudioRuntimeAdapters(useChatRuntimeStore.getState().activeThreadId,);},- ),- [aui],- );+ );+ }, [aui]);const adapters = useMemo(() => ({ history, dictation, speech, attachments }),[history, dictation, speech, attachments],diff --git a/studio/frontend/src/features/chat/sandbox-attachments.ts b/studio/frontend/src/features/chat/sandbox-attachments.tsindex 114feacc68b..6efb3d34e3a 100644--- a/studio/frontend/src/features/chat/sandbox-attachments.ts+++ b/studio/frontend/src/features/chat/sandbox-attachments.ts@@ -41,6 +41,14 @@ const MAX_SANDBOX_ATTACHMENTS = 64;type Attachment = { name?: string; content?: readonly unknown[] };+// attachmentContentText's wrapper, which the server-document adapter sends.+function hasInlineText(content: readonly unknown[]): boolean {+ return content.some((part) => {+ const text = (part as { text?: unknown } | null)?.text;+ return typeof text === "string" && text.startsWith("<attachment name=");+ });+}+function sandboxCopy(attachment: unknown): { sha256: string; path: string } | null {const original = attachmentOriginal(attachment);if (!original || !/^[0-9a-f]{64}$/.test(original.sha256)) return null;@@ -75,7 +83,8 @@ export function withSandboxAttachmentPaths<const { name = "", content = [] } = attachment as Attachment;const reader = sandboxReader(copy.path);const path = JSON.stringify(copy.path);- const note = isToolOnlyAttachmentName(name)+ // By content, not name: an .epub sent before its text was inlined still holds only a placeholder.+ const note = isToolOnlyAttachmentName(name) && !hasInlineText(content)? `[${name} is saved at ${copy.path} in the python tool's working directory${reader ? `; open it with ${reader}, where path = ${path}` : ""}]`: `[${name}: its text is below, so answer from it. For calculations, the python tool has the file at path = ${path}${reader ? `; ${reader}` : ""}]`;return {diff --git a/studio/frontend/src/features/chat/server-document.ts b/studio/frontend/src/features/chat/server-document.tsnew file mode 100644index 00000000000..a2eea6dcffd--- /dev/null+++ b/studio/frontend/src/features/chat/server-document.ts@@ -0,0 +1,55 @@+// 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 { getAuthSessionEpoch } from "@/features/auth";+import { extractDocumentText } from "@/features/rag/api/rag-api";+import { MAX_SERVER_DOCUMENT_BYTES } from "./open-document-accept";+import { MAX_TEXT_ATTACHMENT_BYTES } from "./text-attachment-accept";++export class NoDocumentTextError extends Error {+ // Matched by name: runtime-provider loads this module lazily, so it cannot use instanceof.+ override name = "NoDocumentTextError";+}++// Per File, so the chip's preview reuses the upload the adapter already made.+const extracted = new WeakMap<File, Promise<string>>();++async function extract(file: File): Promise<string> {+ if (file.size > MAX_SERVER_DOCUMENT_BYTES) {+ throw new Error(`File is too large: ${file.name}`);+ }+ // As uploadChatAttachmentOriginal: one account's file must not settle into another's composer.+ const epoch = getAuthSessionEpoch();+ const sameAccount = () => {+ if (getAuthSessionEpoch() !== epoch) {+ throw new Error("The account changed while reading the file.");+ }+ };+ let result: { text: string; truncated: boolean };+ try {+ result = await extractDocumentText(file, sameAccount);+ sameAccount();+ } catch (cause) {+ throw new Error(+ (cause as Error | undefined)?.message ||+ `File could not be read: ${file.name}`,+ );+ }+ if (!result.text.trim()) {+ throw new NoDocumentTextError(`${file.name} has no text to read.`);+ }+ return result.truncated+ ? `${result.text}\n\n[Truncated: the text stops after ${MAX_TEXT_ATTACHMENT_BYTES.toLocaleString("en-US")} bytes.]`+ : result.text;+}++export function extractServerDocumentText(file: File): Promise<string> {+ let pending = extracted.get(file);+ if (!pending) {+ pending = extract(file);+ extracted.set(file, pending);+ // A failed read (offline, signed out) may succeed when attached again.+ pending.catch(() => extracted.delete(file));+ }+ return pending;+}diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.tsindex 17f07cb42bd..fbffe99dd38 100644--- a/studio/frontend/src/features/native-intents/drop-paths.ts+++ b/studio/frontend/src/features/native-intents/drop-paths.ts@@ -8,6 +8,7 @@ import {RTF_ATTACHMENT_EXTENSIONS,isRtfAttachmentName,TOOL_ONLY_ATTACHMENT_EXTENSIONS,+ isServerDocumentAttachmentName,isToolOnlyAttachmentName,} from "../chat/open-document-accept.ts";import {@@ -24,6 +25,7 @@ export function isComposerAttachmentName(path: string): boolean {DOC_EXTS.some((ext) => path.toLowerCase().endsWith(ext)) ||isOpenDocumentAttachmentName(path) ||isRtfAttachmentName(path) ||+ isServerDocumentAttachmentName(path) ||isToolOnlyAttachmentName(path) ||isTextDropName(path));diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.tsindex 6c0105a44fe..2d37fa72e95 100644--- a/studio/frontend/src/features/rag/api/rag-api.ts+++ b/studio/frontend/src/features/rag/api/rag-api.ts@@ -98,6 +98,23 @@ async function ragUpload(return json as DocumentUploadResult;}+/** Not gated on sqlite-vec, so its status says nothing about RAG availability. */+export async function extractDocumentText(+ file: File,+ beforeRetry?: () => void,+): Promise<{ text: string; truncated: boolean }> {+ const form = new FormData();+ form.append("file", file);+ const response = await authFetch(+ `${RAG_BASE}/extract-text`,+ { method: "POST", body: form },+ { beforeRetry },+ );+ const json = await response.json().catch(() => null);+ if (!response.ok) throw ragError(response.status, json);+ return json as { text: string; truncated: boolean };+}+export async function listKnowledgeBases(): Promise<KnowledgeBase[]> {const data = await ragRequest<{knowledgeBases: KnowledgeBase[];diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex 8c7f0264f5c..ba289367807 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -220,16 +220,16 @@ for (const [format, extensions, adapter, rustList] of [});}-test("native chat accepts Office types with a composer adapter; native intake retains explicit RAG formats", () => {+test("native chat drops every Office, Outlook and saved-page type into the composer", () => {const office =".doc .xls .xlsx .xlsm .xltx .xltm .ppt .pptx .pptm .ppsx .ott .ots .otp .msg .mht .mhtml .xhtml .xht".split(" ",);for (const extension of office) {const path = `/docs/Report${extension.toUpperCase()}`;- const supported = [".xlsx", ".xlsm", ".pptx"].includes(extension);- assert.equal(classifyDropPaths([path]).kind, supported ? "docs" : "unsupported", path);- assert.equal(isComposerAttachmentName(path), supported, path);+ // Browser readers take .xlsx/.xlsm/.pptx; the server-document adapter reads the rest.+ assert.equal(classifyDropPaths([path]).kind, "docs", path);+ assert.equal(isComposerAttachmentName(path), true, path);}// Types with a composer adapter keep going to the composer.for (const ext of [".odt", ".rtf", ".epub", ".eml", ".docm"]) {diff --git a/studio/frontend/tests/sandbox-attachments.test.ts b/studio/frontend/tests/sandbox-attachments.test.tsindex 0eaff0cea2e..1d9662fbd02 100644--- a/studio/frontend/tests/sandbox-attachments.test.ts+++ b/studio/frontend/tests/sandbox-attachments.test.ts@@ -99,6 +99,22 @@ test("kept files across the history name their sandbox copy once each", () => {assert.equal(book.content.length, 1);});+test("an .epub's note follows its content: inlined text, or an older tool-only placeholder", () => {+ const inlined = {+ ...kept("book.epub", "d".repeat(64)),+ content: [{ type: "text", text: "<attachment name=book.epub>\nChapter one\n</attachment>" }],+ };+ const older = {+ ...kept("old.epub", "e".repeat(64)),+ content: [{ type: "text", text: "[old.epub: only the python tool can read this file]" }],+ };+ const { messages } = withSandboxAttachmentPaths([{ attachments: [inlined, older] }]);+ const note = (i: number) =>+ (messages[0]!.attachments[i] as { content: Part[] }).content[0]!.text;+ assert.match(note(0), /^\[book\.epub: its text is below/);+ assert.match(note(1), /^\[old\.epub is saved at /);+});+test("a thread past the request's limit carries its most recent files, not none", () => {const one = (i: number) => kept(`f${i}.parquet`, i.toString(16).padStart(64, "0"));const all = Array.from({ length: 70 }, (_, i) => ({ attachments: [one(i)] }));diff --git a/studio/frontend/tests/server-document-attachment.test.ts b/studio/frontend/tests/server-document-attachment.test.tsnew file mode 100644index 00000000000..f83db7c24d4--- /dev/null+++ b/studio/frontend/tests/server-document-attachment.test.ts@@ -0,0 +1,122 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";++import {+ OPEN_DOCUMENT_ATTACHMENT_EXTENSIONS,+ RTF_ATTACHMENT_EXTENSIONS,+ SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS,+ isServerDocumentAttachmentName,+} from "../src/features/chat/open-document-accept.ts";+import { TEXT_ATTACHMENT_EXTENSIONS } from "../src/features/chat/text-attachment-accept.ts";+import {+ RAG_DOCUMENT_UPLOAD_ACCEPT,+ RAG_UPLOAD_ACCEPT,+} from "../src/features/rag/types/rag.ts";++const split = (list: string) => list.split(",").map((ext) => ext.trim());++test("the composer takes every document type chat with files parses", () => {+ const browserRead = new Set([+ ".xlsx",+ ".xlsm",+ ".pptx",+ ...split(OPEN_DOCUMENT_ATTACHMENT_EXTENSIONS),+ RTF_ATTACHMENT_EXTENSIONS,+ ...TEXT_ATTACHMENT_EXTENSIONS,+ ]);+ const expected = split(RAG_DOCUMENT_UPLOAD_ACCEPT).filter(+ (ext) => !browserRead.has(ext),+ );+ assert.deepEqual(+ [...split(SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS)].sort(),+ expected.sort(),+ );+ // The base RAG types all have browser readers already (.pdf, .docx, .html, text).+ for (const ext of split(RAG_UPLOAD_ACCEPT)) {+ assert.equal(isServerDocumentAttachmentName(`a${ext}`), false, ext);+ }+});++test("no earlier composer adapter claims a server document by extension", () => {+ const text = new Set(TEXT_ATTACHMENT_EXTENSIONS);+ for (const ext of split(SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS)) {+ assert.equal(text.has(ext), false, ext);+ }+ assert.equal(isServerDocumentAttachmentName("Q3 Report.DOC"), true);+ assert.equal(isServerDocumentAttachmentName("notes.docx"), false);+});++test("a failed read cancels the send, and a textless tool-only type falls back to the python tool", () => {+ const source = readFileSync(+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),+ "utf8",+ );+ const adapter = source.slice(+ source.indexOf("class ServerDocumentAttachmentAdapter"),+ source.indexOf("class LargeDocumentFallbackAdapter"),+ );+ assert.match(adapter, /text = await pending;\s*\} catch \(cause\) \{[\s\S]*?throw cause;/);+ assert.doesNotMatch(adapter, /pending\.catch\(/);+ assert.match(+ adapter,+ /\?\.name === "NoDocumentTextError" &&\s*isToolOnlyAttachmentName\(file\.name\) &&\s*pythonToolOpensAttachments\(\)/,+ );+ // An oversized scanned PDF is past the PDF originals cap, so it may not fall back to the python tool.+ assert.doesNotMatch(adapter.slice(adapter.indexOf("private read(")), /\\\.pdf\$/);+ // Code can be turned off between attach and send; then the textless file is refused, not sent bare.+ assert.match(adapter, /if \(text === null && !pythonToolOpensAttachments\(\)\) \{[\s\S]*?throw new Error/);+ assert.match(adapter, /only the python tool can read this file/);+ const preview = readFileSync(+ new URL("../src/components/assistant-ui/attachment-preview.tsx", import.meta.url),+ "utf8",+ );+ const webPage = new RegExp(/const WEB_PAGE_NAME = \/(.+)\/i;/.exec(preview)![1]!, "i");+ assert.ok(webPage.test("page.html"));+ assert.ok(!webPage.test("page.xhtml"), "extracted .xhtml text must not render as markup");+});++test("server documents are routed ahead of text and tool-only adapters", () => {+ const source = readFileSync(+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),+ "utf8",+ );+ const order = (marker: string) => {+ const index = source.indexOf(marker, source.indexOf("new CompositeAttachmentAdapter(["));+ assert.notEqual(index, -1, marker);+ return index;+ };+ assert.ok(order(" server,") < order("new TextAttachmentAdapter()"));+ assert.ok(order(" server,") < order("new ToolOnlyAttachmentAdapter()"));+ for (const adapter of ["PDF", "Docx", "Office", "OpenDocument"]) {+ assert.ok(order(`largeFallback(new ${adapter}AttachmentAdapter())`) > 0);+ }+});++test("Desktop reads the same server-document types the composer does", () => {+ const policy = readFileSync(+ new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),+ "utf8",+ );+ const rust = [+ ...(policy+ .match(/SERVER_DOCUMENT_ATTACHMENT_EXTS: &\[&str\] = &\[([^\]]+)\]/)?.[1]+ .matchAll(/"([^"]+)"/g) ?? []),+ ].map((match) => `.${match[1]}`);+ assert.deepEqual(rust.sort(), split(SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS).sort());+});++test("an extraction started by one account never settles in another's composer", () => {+ const reader = readFileSync(+ new URL("../src/features/chat/server-document.ts", import.meta.url),+ "utf8",+ );+ assert.match(reader, /const epoch = getAuthSessionEpoch\(\);/);+ // Retries refuse a changed account, and the answer is checked again before its text is used.+ assert.match(reader, /await extractDocumentText\(file, sameAccount\);\s*sameAccount\(\);/);+ const api = readFileSync(new URL("../src/features/rag/api/rag-api.ts", import.meta.url), "utf8");+ assert.match(api, /\{ method: "POST", body: form \},\s*\{ beforeRetry \},/);+});diff --git a/studio/src-tauri/src/native_clipboard.rs b/studio/src-tauri/src/native_clipboard.rsindex 6436a43208f..2ee6f10d853 100644--- a/studio/src-tauri/src/native_clipboard.rs+++ b/studio/src-tauri/src/native_clipboard.rs@@ -130,6 +130,9 @@ fn clipboard_file_mime_type(path: &Path) -> Option<&'static str> {// list the composer and the drop path already share."txt" => "text/plain",other if crate::native_path_policy::TEXT_ATTACHMENT_EXTS.contains(&other) => "text/plain",+ other if crate::native_path_policy::SERVER_DOCUMENT_ATTACHMENT_EXTS.contains(&other) => {+ "application/octet-stream"+ }other if crate::native_path_policy::TOOL_ONLY_ATTACHMENT_EXTS.contains(&other) => {"application/octet-stream"}@@ -479,7 +482,10 @@ mod tests {#[test]fn clipboard_file_mime_types_cover_composer_documents() {- assert_eq!(clipboard_file_mime_type(Path::new("notes.rtf")), Some("application/rtf"));+ assert_eq!(+ clipboard_file_mime_type(Path::new("notes.rtf")),+ Some("application/rtf")+ );assert_eq!(clipboard_file_mime_type(Path::new("archive.tar.gz")),Some("application/octet-stream")diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rsindex e78eea5905e..08ba7807ae6 100644--- a/studio/src-tauri/src/native_intents.rs+++ b/studio/src-tauri/src/native_intents.rs@@ -699,6 +699,9 @@ fn attachment_mime_type(path: &Path) -> Option<&'static str> {other if crate::native_path_policy::TEXT_ATTACHMENT_EXTS.contains(&other) => {Some("text/plain")}+ other if crate::native_path_policy::SERVER_DOCUMENT_ATTACHMENT_EXTS.contains(&other) => {+ Some("application/octet-stream")+ }other if crate::native_path_policy::TOOL_ONLY_ATTACHMENT_EXTS.contains(&other) => {Some("application/octet-stream")}@@ -784,7 +787,8 @@ fn read_attachment_payload(entry: &NativePathEntry) -> Result<NativeAttachmentFiMAX_NATIVE_IMAGE_BYTES} else if mime_type.starts_with("video/") {MAX_NATIVE_VIDEO_BYTES- } else if mime_type.starts_with("application/vnd.oasis.opendocument.")+ } else if crate::native_path_policy::is_server_document_attachment(path)+ || mime_type.starts_with("application/vnd.oasis.opendocument.")|| mime_type.starts_with("application/vnd.openxmlformats-officedocument.")|| matches!(mime_type,@@ -1112,6 +1116,26 @@ mod tests {}}+ #[test]+ fn server_documents_read_inline_under_the_document_cap() {+ for ext in ["doc", "xls", "ppt", "msg", "mht", "epub"] {+ let path = temp_path("server-document").with_extension(ext);+ fs::write(&path, b"document bytes").unwrap();+ let (_state, entry) = attachment_entry(&path);+ let payload = read_attachment_payload(&entry).unwrap();+ assert_eq!(payload.mime_type, "application/octet-stream", "{ext}");+ let _ = fs::remove_file(path);+ }+ let path = temp_path("server-document-cap").with_extension("doc");+ fs::File::create(&path)+ .unwrap()+ .set_len(MAX_NATIVE_ATTACHMENT_BYTES + 1)+ .unwrap();+ let (_state, entry) = attachment_entry(&path);+ assert!(read_attachment_payload(&entry).is_ok());+ let _ = fs::remove_file(path);+ }+#[test]fn composer_documents_read_inline_with_adapter_mime_types() {for (ext, mime) in [diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rsindex f906c7e9d42..0c56f4c7bcc 100644--- a/studio/src-tauri/src/native_path_policy.rs+++ b/studio/src-tauri/src/native_path_policy.rs@@ -54,6 +54,17 @@ pub const OFFICE_ATTACHMENT_EXTS: &[&str] = &["doc", "xls", "xlsx", "xlsm", "xltx", "xltm", "ppt", "pptx", "pptm", "ppsx", "ott", "ots","otp", "msg", "mht", "mhtml", "xhtml", "xht",];+/// Read on the server by the composer; keep in sync with `SERVER_DOCUMENT_ATTACHMENT_EXTENSIONS`.+pub const SERVER_DOCUMENT_ATTACHMENT_EXTS: &[&str] = &[+ "doc", "docm", "dotx", "dotm", "xls", "xltx", "xltm", "ppt", "pptm", "potx", "potm", "ppsx",+ "ppsm", "odp", "ott", "ots", "otp", "msg", "mht", "mhtml", "epub", "xhtml", "xht",+];++pub fn is_server_document_attachment(path: &Path) -> bool {+ SERVER_DOCUMENT_ATTACHMENT_EXTS+ .iter()+ .any(|ext| has_extension(path, ext))+}/// OpenDocument files the chat composer parses directly rather than indexing as RAG sources.pub const OPEN_DOCUMENT_ATTACHMENT_EXTS: &[&str] = &["ods", "odt"];pub const RTF_ATTACHMENT_EXTS: &[&str] = &["rtf"];