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 takes README-style files, dotfiles, Office templates and more media (#13493)
Michael Han67fbacdb7b14
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.pyindex 3f1832e8084..59ab8f80dab 100644--- a/studio/backend/core/rag/config.py+++ b/studio/backend/core/rag/config.py@@ -46,7 +46,7 @@ SOURCE_TEXT_EXTS = frozenset(""".text .log .mdx .rst .adoc .asciidoc .org .textile .wiki .tex .latex .sty .cls .bib .rmd .qmd.srt .vtt .sbv .ass .ssa .sub .lrc- .csv .tsv .psv .json .jsonl .ndjson .jsonc .json5 .geojson .har .avsc .xml .yaml .yml .toml .ini+ .csv .tsv .psv .json .jsonl .ndjson .jsonc .json5 .geojson .kml .gpx .har .avsc .xml .yaml .yml .toml .ini.cfg .conf .cnf .env .properties .plist .edn .ron .cue .lock .mod .sum .reg .desktop .service.po .pot .strings .resx .xliff .xlf .ics .vcf .eml .mbox .m3u8 .pls.css .scss .sass .less .styl .svg .vue .svelte .astro .pug .jade .haml .slim .ejs .erb .hbs@@ -70,7 +70,7 @@ SOURCE_TEXT_EXTS = frozenset()DOCUMENT_UPLOAD_EXTS = frozenset("""- .doc .docm .dotx .dotm .xls .xlsx .xlsm .xltx .xltm .ppt .pptx .pptm .potx .potm .ppsx .ppsm+ .doc .docm .dotx .dotm .xls .xlt .xlsx .xlsm .xltx .xltm .ppt .pps .pptx .pptm .potx .potm .ppsx .ppsm.odt .ods .odp .ott .ots .otp .msg .eml .mht .mhtml .rtf .epub .xhtml .xht""".split())diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.pyindex c8b1d775672..99382c12772 100644--- a/studio/backend/core/rag/parsers.py+++ b/studio/backend/core/rag/parsers.py@@ -1085,6 +1085,11 @@ def parse(path: str, *, want_images: bool = False):pages = _office_document(path, ext)return (pages, []) if want_images else pages+ # .dot/.pot are Graphviz and gettext text too; only an OLE compound file is a Word/PowerPoint template.+ if ext in _OFFICE_TEMPLATE_EXTS and _is_compound_file(path):+ pages = _office_document(path, _OFFICE_TEMPLATE_EXTS[ext])+ return (pages, []) if want_images else pages+if ext in (".html", ".htm", ".txt", ".md", ".markdown") or ext in config.SOURCE_TEXT_EXTS:is_html = ext in (".html", ".htm")with open(path, "rb") as f:@@ -1101,6 +1106,15 @@ def parse(path: str, *, want_images: bool = False):raise ValueError(f"unsupported file type: {ext}")+_OFFICE_TEMPLATE_EXTS = {".dot": ".doc", ".pot": ".ppt"}+_OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"+++def _is_compound_file(path: str) -> bool:+ with open(path, "rb") as f:+ return f.read(len(_OLE_MAGIC)) == _OLE_MAGIC++def _html_bytes_text(raw: bytes) -> str:return "\n\n".join(page.text for page in _html(_decode_text(raw, html = True)))@@ -1115,8 +1129,8 @@ def _office_document(path: str, ext: str) -> list[Page]:readers = {".doc": office.doc,- ".xls": office.xls,- ".ppt": office.ppt,+ **dict.fromkeys((".xls", ".xlt"), office.xls),+ **dict.fromkeys((".ppt", ".pps"), office.ppt),".rtf": office.rtf,".epub": lambda p: office.epub(p, _html_bytes_text),".msg": lambda p: office.msg(p, _html_bytes_text),diff --git a/studio/backend/tests/test_rag_office_formats.py b/studio/backend/tests/test_rag_office_formats.pyindex dc79266fe26..2de02b25316 100644--- a/studio/backend/tests/test_rag_office_formats.py+++ b/studio/backend/tests/test_rag_office_formats.py@@ -492,8 +492,8 @@ def build_msg(path):BUILDERS = {".doc": build_doc,- ".xls": build_xls,- ".ppt": build_ppt,+ **dict.fromkeys((".xls", ".xlt"), build_xls),+ **dict.fromkeys((".ppt", ".pps"), build_ppt),".msg": build_msg,".eml": build_eml,".rtf": build_rtf,@@ -1270,3 +1270,14 @@ def test_documents_upload_index_and_stay_searchable(rag_home, stub_embeddings, tassert store.search_lexical(conn, scope, "zebramarker", 5)finally:conn.close()+++def test_binary_dot_and_pot_parse_as_office_templates_and_text_ones_stay_text(tmp_path):+ assert "Zebramarker" in _text(build_doc(tmp_path / "letter.dot"))+ assert "Zebramarker" in _text(build_ppt(tmp_path / "deck.pot"))+ graph = tmp_path / "graph.dot"+ graph.write_text("digraph { a -> b }", encoding = "utf-8")+ assert _text(graph) == "digraph { a -> b }"+ catalog = tmp_path / "messages.pot"+ catalog.write_text('msgid "hi"\nmsgstr ""\n', encoding = "utf-8")+ assert _text(catalog).startswith('msgid "hi"')diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex fdd26f2fe17..ac80655b1cf 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -6624,7 +6624,7 @@ const ToolStatusDisplay: FC = () => {// Plus menu: attachment and workflow actions. Opens downward in the welcome// composer; the docked composer passes side="top" to open upward.const AUDIO_ACCEPT_TOKEN_RE =- /^(audio\/|\.(?:wav|mp3|mp2|m4a|ogg|oga|opus|flac|aac|aiff|aif|aifc|caf|wma|amr)$)/i;+ /^(audio\/|\.(?:wav|mp3|mp2|m4a|ogg|oga|opus|flac|aac|aiff|aif|aifc|caf|wma|amr|m4b|weba|mka)$)/i;function attachmentAcceptForPicker(accept: string, audioEnabled: boolean): string {const enabledAccept =diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex 2dd662c7b43..9cd9c39078e 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -6,6 +6,7 @@ import {MAX_TEXT_ATTACHMENT_BYTES,TEXT_ATTACHMENT_ACCEPT,decodeTextAttachmentBytes,+ isBinaryOfficeTemplate,isTextAttachmentName,} from "./text-attachment-accept";@@ -45,9 +46,11 @@ export type AttachmentText = {};const AUDIO_ATTACHMENT_RE =- /\.(wav|mp3|mp2|m4a|ogg|oga|opus|flac|webm|mp4|aac|aiff|aif|aifc|caf|wma|amr)$/i;+ /\.(wav|mp3|mp2|m4a|ogg|oga|opus|flac|webm|mp4|aac|aiff|aif|aifc|caf|wma|amr|m4b|weba|mka)$/i;const AUDIO_MIME_RE = /^audio\//i;const PDF_ATTACHMENT_RE = /\.pdf$/i;+// Tested first so every other file starts its read without waiting on a sniff.+const OFFICE_TEMPLATE_NAME_RE = /\.(?:dot|pot)$/i;const DOCX_ATTACHMENT_RE = /\.docx$/i;const HTML_ATTACHMENT_RE = /\.x?html?$/i;const OPEN_DOCUMENT_ATTACHMENT_RE = /\.(ods|odt)$/i;@@ -123,6 +126,9 @@ const AUDIO_EXTENSION_MIMES: Record<string, string> = {caf: "audio/x-caf",wma: "audio/x-ms-wma",amr: "audio/amr",+ m4b: "audio/mp4",+ weba: "audio/webm",+ mka: "audio/x-matroska",webm: "audio/webm",};// Node.TEXT_NODE and Node.ELEMENT_NODE, spelled out so the extractor runs where the DOM globals do not.@@ -2059,7 +2065,8 @@ export async function readAttachmentText(// 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))+ (file.size > MAX_OPEN_DOCUMENT_ARCHIVE_BYTES && isOpenDocumentAttachment(name, contentType)) ||+ (OFFICE_TEMPLATE_NAME_RE.test(name) && (await isBinaryOfficeTemplate(file)))) {const { extractServerDocumentText } = await import("./server-document");return { label: null, text: await extractServerDocumentText(file), truncated: false };diff --git a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts b/studio/frontend/src/features/chat/lib/attachment-file-kind.tsindex 53ebee74ef2..d75d9099e11 100644--- a/studio/frontend/src/features/chat/lib/attachment-file-kind.ts+++ b/studio/frontend/src/features/chat/lib/attachment-file-kind.ts@@ -39,7 +39,7 @@ register("image", "png jpg jpeg gif webp avif bmp svg heic heif tif tiff ico");register("pdf", "pdf");register("audio",- "mp3 mp2 wav m4a ogg oga opus flac aac aiff aif aifc caf wma amr",+ "mp3 mp2 wav m4a m4b ogg oga opus flac aac aiff aif aifc caf wma amr weba mka",);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");diff --git a/studio/frontend/src/features/chat/open-document-accept.ts b/studio/frontend/src/features/chat/open-document-accept.tsindex 380a664c033..c717606ec59 100644--- a/studio/frontend/src/features/chat/open-document-accept.ts+++ b/studio/frontend/src/features/chat/open-document-accept.ts@@ -32,7 +32,7 @@ export function isRtfAttachmentName(filename: string): boolean {// 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",+ ".doc,.docm,.dotx,.dotm,.xls,.xlt,.xltx,.xltm,.ppt,.pps,.pptm,.potx,.potm,.ppsx,.ppsm",".odp,.ott,.ots,.otp,.msg,.mht,.mhtml,.epub,.xhtml,.xht",].join(",");// RAG's MAX_UPLOAD_BYTES.diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex b97e4037bd5..d38c19e8316 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -1026,6 +1026,38 @@ class LargeDocumentFallbackAdapter implements AttachmentAdapter {}}+/** .dot/.pot are Graphviz and gettext text unless their bytes are a Word or PowerPoint template. */+class OfficeTemplateAdapter implements AttachmentAdapter {+ accept = ".dot,.pot";+ private readonly text: AttachmentAdapter;+ private readonly server: ServerDocumentAttachmentAdapter;++ constructor(text: AttachmentAdapter, server: ServerDocumentAttachmentAdapter) {+ this.text = text;+ this.server = server;+ }++ async *add(state: { file: File }): AsyncGenerator<PendingAttachment, void> {+ if (await isBinaryOfficeTemplate(state.file)) {+ yield* this.server.add(state);+ return;+ }+ yield await (this.text.add(state) as Promise<PendingAttachment>);+ }++ send(attachment: PendingAttachment): Promise<CompleteAttachment> {+ return this.server.owns(attachment.id)+ ? this.server.send(attachment)+ : this.text.send(attachment);+ }++ remove(attachment: Attachment): Promise<void> {+ return this.server.owns(attachment.id)+ ? this.server.remove(attachment)+ : this.text.remove(attachment);+ }+}+class OpenDocumentAttachmentAdapter implements AttachmentAdapter {private readonly active = new Set<string>();private readonly sending = new Set<string>();@@ -3039,6 +3071,7 @@ function useStudioRuntimeAdapters();const attachments = useMemo(() => {const server = new ServerDocumentAttachmentAdapter();+ const text = new TextAttachmentAdapter();const largeFallback = (browser: AttachmentAdapter) =>new LargeDocumentFallbackAdapter(browser, server);return new PreStreamAwareAttachmentAdapter(@@ -3050,7 +3083,8 @@ function useStudioRuntimeAdapters(new VideoAttachmentAdapter(),// Before text, which claims message/rfc822 (.mht), and tool-only, which lists .epub/.docm/.odp.server,- new TextAttachmentAdapter(),+ new OfficeTemplateAdapter(text, server),+ text,new HtmlAttachmentAdapter(),largeFallback(new PDFAttachmentAdapter()),largeFallback(new DocxAttachmentAdapter()),diff --git a/studio/frontend/src/features/chat/text-attachment-accept.ts b/studio/frontend/src/features/chat/text-attachment-accept.tsindex a152909b1cf..e90afbfe883 100644--- a/studio/frontend/src/features/chat/text-attachment-accept.ts+++ b/studio/frontend/src/features/chat/text-attachment-accept.ts@@ -48,6 +48,8 @@ export const TEXT_ATTACHMENT_EXTENSIONS = [".jsonc",".json5",".geojson",+ ".kml",+ ".gpx",".har",".avsc",".xml",@@ -319,6 +321,52 @@ export const TEXT_ATTACHMENT_BASENAMES = ["containerfile","dockerfile","makefile",+ "gnumakefile",+ "justfile",+ "procfile",+ "jenkinsfile",+ "vagrantfile",+ "gemfile",+ "rakefile",+ "podfile",+ "brewfile",+ "pipfile",+ "caddyfile",+ "codeowners",+ "readme",+ "license",+ "licence",+ "copying",+ "notice",+ "authors",+ "contributors",+ "changelog",+ // Dotfiles: no extension either. .env stays out, since it usually holds secrets.+ ".gitignore",+ ".gitattributes",+ ".gitmodules",+ ".dockerignore",+ ".npmignore",+ ".prettierignore",+ ".eslintignore",+ ".editorconfig",+ ".npmrc",+ ".nvmrc",+ ".yarnrc",+ ".prettierrc",+ ".eslintrc",+ ".babelrc",+ ".pylintrc",+ ".flake8",+ ".clang-format",+ ".python-version",+ ".tool-versions",+ ".bashrc",+ ".bash_profile",+ ".zshrc",+ ".profile",+ ".vimrc",+ ".htaccess",] as const;const PATH_SEPARATOR_RE = /[\\/]/;@@ -1350,4 +1398,6 @@ export const TEXT_ATTACHMENT_ACCEPT = ["text/vtt,application/x-subrip,text/x-log,text/calendar,text/vcard,message/rfc822","application/json,application/xml,application/yaml,application/toml,image/svg+xml",TEXT_ATTACHMENT_EXTENSIONS.join(","),+ // assistant-ui matches "README" as ".readme" and ".gitignore" as ".gitignore".+ TEXT_ATTACHMENT_BASENAMES.map((name) => `.${name.replace(/^\./, "")}`).join(","),].join(",");diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.tsindex fbffe99dd38..928a061201b 100644--- a/studio/frontend/src/features/native-intents/drop-paths.ts+++ b/studio/frontend/src/features/native-intents/drop-paths.ts@@ -12,8 +12,8 @@ import {isToolOnlyAttachmentName,} from "../chat/open-document-accept.ts";import {+ TEXT_ATTACHMENT_BASENAMES,TEXT_ATTACHMENT_EXTENSIONS,- isTextAttachmentName,} from "../chat/text-attachment-accept.ts";import { MAX_AUDIO_FILES } from "../../lib/audio-utils.ts";@@ -33,10 +33,10 @@ export function isComposerAttachmentName(path: string): boolean {function isTextDropName(path: string): boolean {const name = nativeFileName(path).toLowerCase();- if (!name.includes(".") && isTextAttachmentName(name)) {+ if ((TEXT_ATTACHMENT_BASENAMES as readonly string[]).includes(name)) {return true;}- // A dotfile like ".env" has no extension and remains unsupported.+ // Other dotfiles, ".env" among them, have no extension and remain unsupported.const dot = name.lastIndexOf(".");return dot > 0 && TEXT_EXTS.includes(name.slice(dot));}@@ -49,7 +49,7 @@ const IMAGE_EXTS = CHAT_IMAGE_DROP_ACCEPT.split(",").map((ext) =>/** Chat audio attachments; keep in sync with `audio-attachment-adapter.ts` `accept`. */export const CHAT_AUDIO_DROP_ACCEPT =- ".wav,.mp3,.m4a,.ogg,.oga,.opus,.flac,.aac,.aiff,.aif,.aifc,.caf,.wma,.amr,.mp2";+ ".wav,.mp3,.m4a,.m4b,.ogg,.oga,.opus,.flac,.aac,.aiff,.aif,.aifc,.caf,.wma,.amr,.mp2,.weba,.mka";const AUDIO_EXTS = CHAT_AUDIO_DROP_ACCEPT.split(",").map((ext) =>ext.trim().toLowerCase(),@@ -59,7 +59,7 @@ const AUDIO_EXTS = CHAT_AUDIO_DROP_ACCEPT.split(",").map((ext) =>* `VIDEO_ATTACHMENT_EXTS`. llama-server decodes with ffmpeg, so this is what* ffmpeg reads, not what the webview can play. */export const CHAT_VIDEO_DROP_ACCEPT =- ".mp4,.m4v,.mov,.webm,.mkv,.avi,.mpg,.mpeg,.wmv,.flv,.3gp,.ogv,.m2ts";+ ".mp4,.m4v,.mov,.webm,.mkv,.avi,.mpg,.mpeg,.wmv,.flv,.3gp,.3g2,.ogv,.m2ts";const VIDEO_EXTS = CHAT_VIDEO_DROP_ACCEPT.split(",").map((ext) =>ext.trim().toLowerCase(),diff --git a/studio/frontend/src/features/rag/types/rag.ts b/studio/frontend/src/features/rag/types/rag.tsindex 7c5a6b03f09..8836313332d 100644--- a/studio/frontend/src/features/rag/types/rag.ts+++ b/studio/frontend/src/features/rag/types/rag.ts@@ -212,4 +212,4 @@ export const RAG_UPLOAD_ACCEPT = ".pdf,.txt,.md,.markdown,.docx,.html,.htm";/** Mirrors backend `DOCUMENT_UPLOAD_EXTS`. */export const RAG_DOCUMENT_UPLOAD_ACCEPT =- ".doc,.docm,.dotx,.dotm,.xls,.xlsx,.xlsm,.xltx,.xltm,.ppt,.pptx,.pptm,.potx,.potm,.ppsx,.ppsm,.odt,.ods,.odp,.ott,.ots,.otp,.msg,.eml,.mht,.mhtml,.rtf,.epub,.xhtml,.xht";+ ".doc,.docm,.dotx,.dotm,.xls,.xlt,.xlsx,.xlsm,.xltx,.xltm,.ppt,.pps,.pptx,.pptm,.potx,.potm,.ppsx,.ppsm,.odt,.ods,.odp,.ott,.ots,.otp,.msg,.eml,.mht,.mhtml,.rtf,.epub,.xhtml,.xht";diff --git a/studio/frontend/src/lib/audio-utils.ts b/studio/frontend/src/lib/audio-utils.tsindex 6944f51bdf5..664f26697fd 100644--- a/studio/frontend/src/lib/audio-utils.ts+++ b/studio/frontend/src/lib/audio-utils.ts@@ -4,11 +4,11 @@// Containers the backend can reach wav/mp3 from: wav and mp3 pass through, the// rest decode via libsndfile, PyAV's bundled FFmpeg, or finally librosa.export const AUDIO_ACCEPT =- "audio/wav,audio/mpeg,audio/webm,audio/ogg,audio/opus,audio/flac,audio/mp4,audio/aac,audio/aiff,audio/x-aiff,audio/x-caf,audio/x-ms-wma,audio/amr,audio/3gpp";+ "audio/wav,audio/mpeg,audio/webm,audio/ogg,audio/opus,audio/flac,audio/mp4,audio/aac,audio/aiff,audio/x-aiff,audio/x-caf,audio/x-ms-wma,audio/amr,audio/3gpp,audio/x-matroska";// Browsers report an empty or wrong type for several of these containers, so// every surface that takes audio matches the name as well as the MIME.export const AUDIO_ACCEPT_EXTENSIONS =- ".wav,.mp3,.m4a,.ogg,.oga,.opus,.flac,.aac,.aiff,.aif,.aifc,.caf,.wma,.amr,.mp2";+ ".wav,.mp3,.m4a,.m4b,.ogg,.oga,.opus,.flac,.aac,.aiff,.aif,.aifc,.caf,.wma,.amr,.mp2,.weba,.mka";/** What claims a file as audio: the MIME list plus those extensions. Keep .3gp* out of it. A recording and a clip share that extension, and the composer's* audio adapter is matched before its video one, so claiming the name herediff --git a/studio/frontend/src/lib/video-utils.ts b/studio/frontend/src/lib/video-utils.tsindex 3c15347b18d..d0a24b8e857 100644--- a/studio/frontend/src/lib/video-utils.ts+++ b/studio/frontend/src/lib/video-utils.ts@@ -5,7 +5,7 @@* what ffmpeg reads, not what the webview can play. Extensions ride along* because MIME is unreliable for mkv and some mov files. */export const VIDEO_ACCEPT =- "video/mp4,video/x-m4v,video/quicktime,video/webm,video/x-matroska,video/x-msvideo,video/mpeg,video/x-ms-wmv,video/x-flv,video/3gpp,video/ogg,video/mp2t,.mp4,.m4v,.mov,.webm,.mkv,.avi,.mpg,.mpeg,.wmv,.flv,.3gp,.ogv,.m2ts";+ "video/mp4,video/x-m4v,video/quicktime,video/webm,video/x-matroska,video/x-msvideo,video/mpeg,video/x-ms-wmv,video/x-flv,video/3gpp,video/3gpp2,video/ogg,video/mp2t,.mp4,.m4v,.mov,.webm,.mkv,.avi,.mpg,.mpeg,.wmv,.flv,.3gp,.3g2,.ogv,.m2ts";// Matches _MAX_VIDEO_B64_CHARS in the backend, so the composer does not accept// a clip the route refuses. The native reader's cap is a higher backstop.@@ -34,6 +34,7 @@ const VIDEO_MIME_BY_EXTENSION: Record<string, string> = {".wmv": "video/x-ms-wmv",".flv": "video/x-flv",".3gp": "video/3gpp",+ ".3g2": "video/3gpp2",".ogv": "video/ogg",".m2ts": "video/mp2t",};diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex ba289367807..5e53cf13baa 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -222,7 +222,7 @@ for (const [format, extensions, adapter, rustList] of [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(+ ".doc .xls .xlt .xlsx .xlsm .xltx .xltm .ppt .pps .pptx .pptm .ppsx .ott .ots .otp .msg .mht .mhtml .xhtml .xht".split(" ",);for (const extension of office) {@@ -1040,21 +1040,30 @@ test("both attachment stages go through the decode-once path", () => {});test("every basename the picker claims is one the drop paths accept", () => {- // assistant-ui derives the extension as `.${name.split(".").pop()}`, so an- // extensionless "Dockerfile" matches the ".dockerfile" token and the picker- // takes it. A drop of the same file has to agree, or the two disagree on one- // conventional build file.- for (const name of ["Dockerfile", "Makefile", "Containerfile"]) {+ // assistant-ui derives the extension as `.${name.split(".").pop()}`, so "README" matches+ // ".readme" and ".gitignore" matches ".gitignore". A drop of the same file has to agree.+ const accept = TEXT_ATTACHMENT_ACCEPT.split(",");+ for (const name of [+ "Dockerfile",+ "GNUmakefile",+ "README",+ "LICENSE",+ "Jenkinsfile",+ "CODEOWNERS",+ ".gitignore",+ ".editorconfig",+ ".zshrc",+ ]) {const derived = `.${name.split(".").pop()!.toLowerCase()}`;- assert.ok(- TEXT_ATTACHMENT_EXTENSIONS.includes(derived),- `${name} is claimed through ${derived}`,- );+ assert.ok(accept.includes(derived), `${name} is claimed through ${derived}`);assert.equal(isTextAttachmentName(name), true, `${name} is droppable`);+ assert.equal(classifyDropPaths([`/repo/${name}`]).kind, "docs", name);+ }+ // Unlisted names stay out of both, rather than being widened; .env usually holds secrets.+ for (const name of ["notes", ".env", ".DS_Store"]) {+ assert.equal(isTextAttachmentName(name), false, name);+ assert.equal(classifyDropPaths([`/repo/${name}`]).kind, "unsupported", name);}- // A name with no matching token stays out of both, rather than being widened.- assert.equal(TEXT_ATTACHMENT_EXTENSIONS.includes(".gnumakefile"), false);- assert.equal(isTextAttachmentName("GNUmakefile"), false);});test("a container declaring two charsets is refused, not part-decoded", async () => {@@ -2633,3 +2642,14 @@ test("formats the backends cannot take are converted, the rest sent as is", () =assert.ok(!isChatImageFile({ name: "pic.png", type: "" }));assert.ok(!isChatImageFile({ name: "x.constructor", type: "" }));});++test("audiobooks, WebM and Matroska audio, 3GPP2 video and map files attach", () => {+ for (const name of ["book.m4b", "voice.weba", "song.mka"]) {+ assert.equal(classifyDropPaths([`/media/${name}`]).kind, "audio", name);+ }+ assert.equal(classifyDropPaths(["/media/clip.3g2"]).kind, "video");+ for (const name of ["route.gpx", "places.kml"]) {+ assert.equal(isTextAttachmentName(name), true, name);+ assert.equal(classifyDropPaths([`/maps/${name}`]).kind, "docs", name);+ }+});diff --git a/studio/frontend/tests/server-document-attachment.test.ts b/studio/frontend/tests/server-document-attachment.test.tsindex f83db7c24d4..0b18c7adb2f 100644--- a/studio/frontend/tests/server-document-attachment.test.ts+++ b/studio/frontend/tests/server-document-attachment.test.ts@@ -89,7 +89,9 @@ test("server documents are routed ahead of text and tool-only adapters", () => {assert.notEqual(index, -1, marker);return index;};- assert.ok(order(" server,") < order("new TextAttachmentAdapter()"));+ assert.ok(order(" server,") < order("new OfficeTemplateAdapter(text, server)"));+ // Ahead of text, which also lists .dot/.pot, so a binary template is sniffed before text refuses it.+ assert.ok(order("new OfficeTemplateAdapter(text, server)") < order(" text,"));assert.ok(order(" server,") < order("new ToolOnlyAttachmentAdapter()"));for (const adapter of ["PDF", "Docx", "Office", "OpenDocument"]) {assert.ok(order(`largeFallback(new ${adapter}AttachmentAdapter())`) > 0);diff --git a/studio/src-tauri/src/native_clipboard.rs b/studio/src-tauri/src/native_clipboard.rsindex 2ee6f10d853..59c1e90a10e 100644--- a/studio/src-tauri/src/native_clipboard.rs+++ b/studio/src-tauri/src/native_clipboard.rs@@ -4,7 +4,7 @@use crate::native_path_policy::{has_transport_stream_extension, is_audio_only_3gp, is_binary_office_template,is_binary_property_list, is_binary_tracker_mod, is_binary_vobsub, is_compiled_fortran_mod,- is_mpeg_transport_stream,+ is_mpeg_transport_stream, office_template_mime_type,};use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};use serde::Serialize;@@ -110,6 +110,9 @@ fn clipboard_file_mime_type(path: &Path) -> Option<&'static str> {"odt" => "application/vnd.oasis.opendocument.text","ods" => "application/vnd.oasis.opendocument.spreadsheet","rtf" => "application/rtf",+ "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "xlsm" => "application/vnd.ms-excel.sheet.macroEnabled.12",+ "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation","mp3" | "mp2" => "audio/mpeg","wav" => "audio/wav","m4a" => "audio/mp4",@@ -121,8 +124,12 @@ fn clipboard_file_mime_type(path: &Path) -> Option<&'static str> {"caf" => "audio/x-caf","wma" => "audio/x-ms-wma","amr" => "audio/amr",+ "m4b" => "audio/mp4",+ "weba" => "audio/webm",+ "mka" => "audio/x-matroska",// Provisional until the BMFF handlers can be inspected after reading."3gp" => "video/3gpp",+ "3g2" => "video/3gpp2","vtt" => "text/vtt","srt" => "application/x-subrip",// .txt is a RAG type, so it is absent from TEXT_ATTACHMENT_EXTS and@@ -223,11 +230,12 @@ fn read_clipboard_files(paths: Vec<PathBuf>) -> Result<Vec<NativeClipboardFile>,|| is_binary_vobsub(&path, &bytes)|| is_binary_tracker_mod(&path, &bytes)|| is_compiled_fortran_mod(&path, &bytes)- || is_binary_office_template(&path, &bytes){continue;}- let mime_type = if is_3gp && is_audio_only_3gp(&bytes) {+ let mime_type = if is_binary_office_template(&path, &bytes) {+ office_template_mime_type(&path)+ } else if is_3gp && is_audio_only_3gp(&bytes) {"audio/3gpp"} else if is_mpeg_transport_stream(&path, &bytes) {"video/mp2t"@@ -490,6 +498,39 @@ mod tests {clipboard_file_mime_type(Path::new("archive.tar.gz")),Some("application/octet-stream"));+ for name in [+ "show.PPS",+ "budget.xlt",+ "letter.doc",+ "mail.msg",+ "page.mht",+ ] {+ assert_eq!(+ clipboard_file_mime_type(Path::new(name)),+ Some("application/octet-stream"),+ "{name}"+ );+ }+ assert_eq!(+ clipboard_file_mime_type(Path::new("deck.pptx")),+ Some("application/vnd.openxmlformats-officedocument.presentationml.presentation")+ );+ }++ #[test]+ fn office_templates_take_an_office_mime_and_text_dot_files_stay_text() {+ assert_eq!(+ office_template_mime_type(Path::new("letter.dot")),+ "application/msword"+ );+ assert_eq!(+ office_template_mime_type(Path::new("deck.POT")),+ "application/vnd.ms-powerpoint"+ );+ assert_eq!(+ clipboard_file_mime_type(Path::new("graph.dot")),+ Some("text/plain")+ );}#[test]diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rsindex 08ba7807ae6..95b0a59a26e 100644--- a/studio/src-tauri/src/native_intents.rs+++ b/studio/src-tauri/src/native_intents.rs@@ -8,7 +8,7 @@ use crate::native_path_policy::{classify_native_document_folder, classify_native_model_path, has_transport_stream_extension,is_audio_only_3gp, is_binary_office_template, is_binary_property_list, is_binary_tracker_mod,is_binary_vobsub, is_compiled_fortran_mod, is_mpeg_transport_stream, is_text_attachment_name,- reveal_target, ClassifiedPath, NativeArtifactKind,+ office_template_mime_type, reveal_target, ClassifiedPath, NativeArtifactKind,};use serde::Serialize;use std::collections::{HashMap, VecDeque};@@ -668,6 +668,9 @@ fn attachment_mime_type(path: &Path) -> Option<&'static str> {"caf" => Some("audio/x-caf"),"wma" => Some("audio/x-ms-wma"),"amr" => Some("audio/amr"),+ "m4b" => Some("audio/mp4"),+ "weba" => Some("audio/webm"),+ "mka" => Some("audio/x-matroska"),"mp4" => Some("video/mp4"),"m4v" => Some("video/x-m4v"),"mov" => Some("video/quicktime"),@@ -678,6 +681,7 @@ fn attachment_mime_type(path: &Path) -> Option<&'static str> {"wmv" => Some("video/x-ms-wmv"),"flv" => Some("video/x-flv"),"3gp" => Some("video/3gpp"),+ "3g2" => Some("video/3gpp2"),"ogv" => Some("video/ogg"),"m2ts" => Some("video/mp2t"),"ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),@@ -781,6 +785,9 @@ fn read_attachment_payload(entry: &NativePathEntry) -> Result<NativeAttachmentFi// reapplied below once the bytes say it is TypeScript.let max_bytes = if has_transport_stream_extension(path) {MAX_NATIVE_VIDEO_BYTES+ } else if crate::native_path_policy::has_office_template_extension(path) {+ // May be a Word/PowerPoint template; the text cap is reapplied below once the bytes say text.+ MAX_NATIVE_OPEN_DOCUMENT_BYTES} else if is_text_attachment || mime_type.starts_with("text/") {MAX_NATIVE_TEXT_BYTES} else if mime_type.starts_with("image/") {@@ -841,14 +848,12 @@ fn read_attachment_payload(entry: &NativePathEntry) -> Result<NativeAttachmentFi"Compiled Fortran .mod modules are not supported as text attachments.".to_string(),);}- if is_binary_office_template(path, &bytes) {- return Err(- "Legacy Word and PowerPoint templates are not supported as text attachments."- .to_string(),- );- }- let mime_type = attachment_payload_mime_type(path, &bytes)- .ok_or_else(|| "Only chat attachments can be read inline.".to_string())?;+ let mime_type = if is_binary_office_template(path, &bytes) {+ office_template_mime_type(path)+ } else {+ attachment_payload_mime_type(path, &bytes)+ .ok_or_else(|| "Only chat attachments can be read inline.".to_string())?+ };if mime_type.starts_with("text/") && bytes.len() as u64 > MAX_NATIVE_TEXT_BYTES {return Err("Attachment is unavailable or too large.".to_string());}@@ -1169,6 +1174,51 @@ mod tests {}}+ #[test]+ fn binary_office_templates_read_with_an_office_mime_and_graphviz_stays_text() {+ let ole = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1, 0, 0];+ for (ext, mime) in [+ ("dot", "application/msword"),+ ("pot", "application/vnd.ms-powerpoint"),+ ] {+ let path = temp_path("office-template").with_extension(ext);+ fs::write(&path, ole).unwrap();+ let (_state, entry) = attachment_entry(&path);+ assert_eq!(+ read_attachment_payload(&entry).unwrap().mime_type,+ mime,+ "{ext}"+ );+ let _ = fs::remove_file(path);+ }+ let path = temp_path("graph").with_extension("dot");+ fs::write(&path, b"digraph { a -> b }").unwrap();+ let (_state, entry) = attachment_entry(&path);+ assert_eq!(+ read_attachment_payload(&entry).unwrap().mime_type,+ "text/plain"+ );+ let _ = fs::remove_file(path);+ }++ #[test]+ fn a_large_template_uses_the_document_cap_and_large_text_keeps_the_text_cap() {+ let size = MAX_NATIVE_TEXT_BYTES as usize + 1;+ let path = temp_path("big-template").with_extension("dot");+ let mut ole = vec![0u8; size];+ ole[..8].copy_from_slice(&[0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]);+ fs::write(&path, &ole).unwrap();+ let (_state, entry) = attachment_entry(&path);+ assert_eq!(+ read_attachment_payload(&entry).unwrap().mime_type,+ "application/msword"+ );+ fs::write(&path, vec![b'a'; size]).unwrap();+ let (_state, entry) = attachment_entry(&path);+ assert!(read_attachment_payload(&entry).is_err());+ let _ = fs::remove_file(path);+ }+#[test]fn text_attachments_read_inline_with_their_own_cap() {for (ext, mime) in [diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rsindex 0c56f4c7bcc..4b95202e96f 100644--- a/studio/src-tauri/src/native_path_policy.rs+++ b/studio/src-tauri/src/native_path_policy.rs@@ -51,13 +51,14 @@ pub const ATTACHMENT_EXTS: &[&str] = &["pdf", "txt", "md", "markdown", "docx", "/// Office, Outlook and saved-page types RAG sources accept from a drop zone; chat drops take only the/// ones with a composer adapter (`DOC_EXTS` in `drop-paths.ts`).pub const OFFICE_ATTACHMENT_EXTS: &[&str] = &[- "doc", "xls", "xlsx", "xlsm", "xltx", "xltm", "ppt", "pptx", "pptm", "ppsx", "ott", "ots",- "otp", "msg", "mht", "mhtml", "xhtml", "xht",+ "doc", "xls", "xlt", "xlsx", "xlsm", "xltx", "xltm", "ppt", "pps", "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",+ "doc", "docm", "dotx", "dotm", "xls", "xlt", "xltx", "xltm", "ppt", "pps", "pptm", "potx",+ "potm", "ppsx", "ppsm", "odp", "ott", "ots", "otp", "msg", "mht", "mhtml", "epub", "xhtml",+ "xht",];pub fn is_server_document_attachment(path: &Path) -> bool {@@ -183,6 +184,8 @@ pub const TEXT_ATTACHMENT_EXTS: &[&str] = &["jsonc","json5","geojson",+ "kml",+ "gpx","har","avsc","xml",@@ -450,8 +453,57 @@ pub const TEXT_ATTACHMENT_EXTS: &[&str] = &["patch",];-/// Conventional extensionless names represented by dotted frontend accept tokens.-pub const TEXT_ATTACHMENT_NAMES: &[&str] = &["containerfile", "dockerfile", "makefile"];+/// Conventional extensionless names and dotfiles represented by dotted frontend accept tokens.+pub const TEXT_ATTACHMENT_NAMES: &[&str] = &[+ "containerfile",+ "dockerfile",+ "makefile",+ "gnumakefile",+ "justfile",+ "procfile",+ "jenkinsfile",+ "vagrantfile",+ "gemfile",+ "rakefile",+ "podfile",+ "brewfile",+ "pipfile",+ "caddyfile",+ "codeowners",+ "readme",+ "license",+ "licence",+ "copying",+ "notice",+ "authors",+ "contributors",+ "changelog",+ ".gitignore",+ ".gitattributes",+ ".gitmodules",+ ".dockerignore",+ ".npmignore",+ ".prettierignore",+ ".eslintignore",+ ".editorconfig",+ ".npmrc",+ ".nvmrc",+ ".yarnrc",+ ".prettierrc",+ ".eslintrc",+ ".babelrc",+ ".pylintrc",+ ".flake8",+ ".clang-format",+ ".python-version",+ ".tool-versions",+ ".bashrc",+ ".bash_profile",+ ".zshrc",+ ".profile",+ ".vimrc",+ ".htaccess",+];pub fn is_text_attachment_name(path: &Path) -> bool {path.file_name()@@ -576,11 +628,23 @@ fn has_soundtracker_pattern_data(bytes: &[u8], pattern_end: usize) -> bool {true}+/// The MIME a binary .dot/.pot is sent under: the composer reads it on the server, not as text.+pub fn office_template_mime_type(path: &Path) -> &'static str {+ if has_extension(path, "pot") {+ "application/vnd.ms-powerpoint"+ } else {+ "application/msword"+ }+}++pub fn has_office_template_extension(path: &Path) -> bool {+ has_extension(path, "dot") || has_extension(path, "pot")+}+/// Legacy Word `.dot` and PowerPoint `.pot` templates are OLE compound files,/// unlike Graphviz `.dot` and gettext `.pot`.pub fn is_binary_office_template(path: &Path, bytes: &[u8]) -> bool {- (has_extension(path, "dot") || has_extension(path, "pot"))- && bytes.starts_with(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1")+ has_office_template_extension(path) && bytes.starts_with(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1")}/// gfortran writes a compiled `.mod` module as gzip; text `go.mod` never is.@@ -684,14 +748,15 @@ pub const IMAGE_ATTACHMENT_EXTS: &[&str] = &[/// Chat audio attachments; keep in sync with `audio-attachment-adapter.ts` `accept`.pub const AUDIO_ATTACHMENT_EXTS: &[&str] = &["wav", "mp3", "m4a", "ogg", "oga", "opus", "flac", "aac", "aiff", "aif", "aifc", "caf", "wma",- "amr", "mp2",+ "amr", "mp2", "m4b", "weba", "mka",];/// Chat video attachments; keep in sync with `drop-paths.ts`/// `CHAT_VIDEO_DROP_ACCEPT`. llama-server decodes with ffmpeg, so this is what/// ffmpeg reads, not what the webview can play.pub const VIDEO_ATTACHMENT_EXTS: &[&str] = &[- "mp4", "m4v", "mov", "webm", "mkv", "avi", "mpg", "mpeg", "wmv", "flv", "3gp", "ogv", "m2ts",+ "mp4", "m4v", "mov", "webm", "mkv", "avi", "mpg", "mpeg", "wmv", "flv", "3gp", "3g2", "ogv",+ "m2ts",];fn accepted_attachment_exts() -> impl Iterator<Item = &'static &'static str> {