Repository navigation
Studio: read more chat attachment formats, and hand the rest to the python tool - #11379
Conversation
Workbooks and workbook templates become tab-separated text per visible sheet, read in the browser with fflate and DOMParser like OpenDocument files: shared and inline strings, booleans, errors, and dates, times and durations by their number format. Hidden sheets, rows and columns are skipped, and inflate size and extracted text are bounded. The OpenDocument composer adapter is generalised so both formats share its read-on-add lifecycle, and desktop drop and paste route the new types to the composer.
Slides are read in deck order as [Slide N] text blocks, skipping hidden slides and shapes and the Fallback copy of mc:AlternateContent. Relationship ids are now matched by namespace, since <p:sldId> also carries a plain numeric id. Desktop drop and paste accept the new extensions.
A small in-house RTF reader turns the document body into text: font, colour and style tables, metadata, pictures, field codes, headers and footers are skipped, and tables become tab-separated rows. Escaped bytes decode by the current font's charset, falling back to the ANSI code page, since macOS TextEdit writes cp1252 bytes under \ansicpg936 on Chinese systems; a byte written literally after an escaped double-byte lead joins it. Desktop drop and paste accept .rtf.
Model backends take JPEG, PNG, WebP and GIF, so these formats are re-encoded in the webview before they are attached: HEIC/HEIF to JPEG, the rest to lossless PNG. A webview that cannot decode a format says so and names the file. Conversion is held against send in both composers, a failed or removed conversion never sends the source file, and a desktop drop converts per file so one unreadable image does not stop the batch. Desktop drop and paste accept the new extensions.
Blu-ray and AVCHD camcorder clips are accepted by extension on every chat video path. The video/mp2t MIME is not claimed, because browsers also give TypeScript .ts files that type and the video adapter is matched before the text one.
e18d016 to
cd4a80d
Compare
An MPEG transport stream named .mts or .ts was accepted as TypeScript and read as UTF-8 text. The composer, desktop drop and clipboard readers now look for the 0x47 sync byte at the start of three consecutive 188-byte packets (192 bytes for M2TS) and send a stream down the video path as video/mp2t, while TypeScript files stay text, including those the browser labels video/mp2t. The native readers take .ts and .mts under the video cap and reapply the text cap once the bytes say TypeScript. The video reference slot offers .ts and .mts too, and refuses TypeScript once it has read the file.
iWork 2013 and later save a document as a zip of Snappy-compressed protobuf archives (Index/*.iwa) with no published schema. A small reader unpacks those archives under the Office reader's size caps, resolves object references, and returns the Pages body text with inline-object placeholders dropped. Desktop drop and paste accept .pages.
The iWork reader walks a Keynote deck's slide tree in order and reads each slide's title and body placeholders, then its drawables, following object references from them. Skipped slides keep their number, and builds, template slides and speaker notes are left out, as the PPTX reader does. Every object is walked at most once per document, so shared structure, a slide shared by two nodes or a node listed twice cannot multiply the work. Desktop drop and paste accept .key.
The iWork reader reads each Numbers sheet's text boxes and tables in order: table rows come from the table's tiles, cells from the version-5 cell storage (numbers kept exact from their decimal128 form, dates, booleans, durations, errors) and the table's string and rich-text lists. Rows become tab-separated lines under the attachment text budget, and table rows and list entries are charged against a size budget so a flood of tiny ones is refused. Keynote tables read the same way. Desktop drop and paste accept .numbers.
Adds POST /api/chat/attachment-files, a per-account content-addressed store for the original bytes of chat attachments (200 MB cap, streamed past the body buffer). Re-uploading the same bytes renews the file. A sweep at startup and after chat, project and attachment deletion removes files not uploaded for 24 hours that no stored message references; uploads and the sweep share a lock so a renewal cannot race a deletion.
A chat request can name stored attachments in sandbox_attachments. When the python tool is enabled, they are copied into the session sandbox under .unsloth_attachments/<id prefix>/<name> before the request reaches any backend, without following links and without replacing a file already there, so the model's edits survive later turns. The upload response returns that path. An unmodified copy does not count as the user's file when a chat is deleted.
Document attachments (text, HTML, PDF, DOCX, OpenDocument, Office Open XML, RTF, iWork) upload their original file at send, alongside the inline text they already carry; the stored reference is saved with the message. On each turn where the python tool runs in Unsloth Studio, every stored attachment in the history names its sandbox path and the request asks for the copies. Other turns are unchanged, so models without tools still read the inline text. An upload failure keeps the attachment inline-only. The attachment download serves the stored original when it exists.
Adds .parquet, .feather, .arrow, .orc, .sqlite, .sqlite3, .db, .zip, .tar, .gz, .tgz, .bz2, .xz, .npy, .npz, .epub, .mobi, .xps, .oxps, .docm, .dotx, .odp and .odg to the chat composer, paste and desktop drop. The browser cannot read these, so the file is uploaded while it sits in the composer and reaches the model only as a copy in the python tool's working directory. They are refused unless the selected model runs Unsloth Studio's python tool, and a preview shows a short note instead of decoding the bytes.
… install can open Widens the tool-only attachment list to data, database, archive, ebook, Office template and macro, 3D, font and image formats that libraries shipped with every install (pandas, pyarrow, scipy, duckdb, PyMuPDF, fontTools, Pillow, safetensors and the standard library) can open.
The sandbox note for a stored attachment now names a call that opens it with an installed library, such as fitz.open(path), sqlite3.connect(path) or zipfile.ZipFile(path) for Excel workbooks, so the model does not guess a package that refuses the file or is missing. Calls take a path variable because the sandbox scanner reads a string literal passed to .connect() as a network host.
The attachment upload now returns a preview for tool-only images, documents and drawings, so the message can carry what the file holds instead of only its sandbox path: images the vision path cannot show become a PNG with a description, PyMuPDF documents become their text, and ODP, ODG and VSDX become the text of their pages. Nothing reads the preview yet. A preview runs in a spawned child that is killed after ten seconds, because MuPDF lays out one long paragraph in quadratic time and no bound on the input catches that; a timeout, a dead child or a reader error all mean no preview, and the upload still succeeds. Inside the child each reader is bounded by what its library actually loads. Images open only as the format their extension names, since Pillow otherwise picks a decoder from the bytes and icons decode their embedded frames while opening, so each frame's own header is read first. Documents are told their format rather than letting MuPDF guess from the stored file's hash name, and a document that is a zip is refused when its central directory or any member is too large for the reader to take whole. Pages, XML bytes and the text built from them have their own budgets, each marked in the text when it cuts.
…ool can read Zip and tar archives now preview as a listing of their entries with the text of the small ones, and a single compressed file as its text, or an outline of its size when the content is not text. Both are built in the same bounded child as the other previews, and nothing reads the preview yet. Each reader is bounded by what its library actually reads rather than by the file's size. A zip's central directory is sized with the end record ZipFile itself locates, so an archive whose directory is too large to parse is listed as such instead. Only stored and deflated members are read, because ZipFile limits what one read inflates for deflate alone. A tar is read in one streaming pass over a capped decompressed stream, which bounds its extended headers as well as the member data skipped along the way, and the listing says it is incomplete whenever that cap is reached; member names that are not UTF-8 are replaced rather than surrogate-escaped, which the response could not encode. A compressed file reads up to the text cap plus one byte and marks the text when the cut falls short of that many characters.
Chat attachments that only the python tool can open now carry an outline for the remaining data formats: Parquet, Arrow IPC and Feather, ORC, Stata, SAS (`.sas7bdat` and `.xpt`), NumPy `.npy` and `.npz`, and safetensors. The message a model receives says what the file holds - its shape, its columns, its first rows, or the arrays and tensors inside it - rather than only where the file is. Every reader is bounded by what the file itself states it would make its library read, and each budget cut is marked in the output, because a preview must cost about the same for a large attachment as for a small one: - Parquet decodes a page at a time, so the bound is the uncompressed size each row group states, checked for every group the five-row sample fills from. - ORC and Arrow IPC materialise a whole stripe or batch and state nothing about how large it is, so they are read through `pyarrow.dataset`, whose row count comes from the footer, and sampled only when the file is small, the cells fit the budget and no column is nested. - Stata decodes its long-string table whole on the first row read, and every value label with it. Both sizes come from the file's own map, which is walked by the lengths the header states rather than searched, because a dataset label is free text that can hold the same tags. A table too large to read through leaves the values as their stored codes, or leaves the sample out when the rows cannot be read without it. - A sas7bdat states the header and page lengths pandas asks for before it has read anything, and Python reserves the whole buffer even for a read a short file cannot fill, so those claims are checked first. Character columns are decoded with the encoding the file names when Python has that codec. - Arrays over the budget are described from their header alone, and `numpy` is given this module's header budget rather than its own default, which a wide structured dtype exceeds in an otherwise small file. Formats are taken from the attachment's filename, never from the stored path, which is a hash with no extension. Text that cannot survive a round trip through UTF-8 is replaced before it leaves the reader, because a name inside a file can hold a lone surrogate that the JSON response cannot encode. Nothing reads these previews yet; the frontend change follows.
SQLite databases, STL, PLY, GLB, 3MF and KMZ models and TTF/OTF/TTC fonts previously reached the model as a tool-only note, so a message carried nothing about what the file held. Each now outlines what the file states about itself: a database its tables with their columns, row counts and first rows; a mesh its triangle or element counts and the name it carries; a glTF its scene counts, generator and mesh names; a 3MF or KMZ the model or map inside the container over the container's own listing; a font its name, glyph count and fixed pitch. Every reader stays inside what the file says reading it would cost, and says so whenever a budget cuts what it shows. - A SQLite cell is loaded whole by any select that returns it, so cells are measured with octet_length, which answers from the record header, and a cell too large to show is described by its type and size instead. Builds without octet_length cannot size a cell without reading it, so they report no rows rather than read one. - Views and virtual tables compute what they hand back, so nothing in the file states what five rows of one would cost. They are listed but never sampled, identified by having no b-tree of their own rather than by the schema text, which can be written to say anything. - Opening any table parses every CREATE in the file, which a file can be written to make expensive several times over. The preview process therefore carries a limit on what SQLite may allocate; the limit can be lowered but never lifted, so it belongs to that process and a reader only asks whether one is in force. - A model or map inside a container is found through what the package declares, falling back to the conventional name, and is read only when the directory's stated size is within the XML budget. - Header windows, listings and element text all mark what they leave out, including where the text strips back short enough that the outline cap would otherwise stay silent.
A file only the python tool can read reached the model as one line naming it, so the model had to open it with the tool before it knew what was in it. The upload response already carries a preview of such a file — an image, the document's text, or an outline — and this puts that preview in the message. `uploadAttachmentFile` now returns the preview, shape-checked the way the response's other fields already were, and `toolOnlyAttachmentContent` turns it into the attachment's content: an image part with a description line, the document's text under a `[FORMAT: name]` header, or an outline under `[Outline of name]`. A file with no preview reads exactly as it did before, as does a failed upload. The image part is added only when the chat model takes images. That check was a thirty-line block inside `VisionImageAdapter.add`; it is now `imageInputUnavailableReason()`, called from both places, so the two cannot drift apart. What the message persists is `storedAttachmentFile(upload)` rather than the upload itself: the preview's bytes are already in the message's content, so storing them again would put the same text, or the same image, in the history twice. It keeps one thing the preview decided — whether the file's own text is inline — because the note that tells the model where the file lives says "its text is below, so answer from it" only when that text really is below. An outline is not the whole file, so outlines and images keep the note that points at the python tool. No change was needed where the request is built: the parts of every attachment are already walked whatever the attachment's type. One behaviour follows from sending the image: a thread that carries an image cannot be continued on a text-only model, which is how the chat already treats images, and a tool-only image attachment now joins them.
cd4a80d to
b2809eb
Compare
Automated reviewThe Codex connector does not fire on this repository, so the review ran on a staging pull request carrying a byte-identical diff against a base pinned to this PR's merge base. It converged on
Across four rounds it raised nine findings. Four were fixed — the sandbox-attachment cap now carries a thread's most recent files instead of its first ones, the abandoned-upload sweep is throttled per account rather than per process, and two regressions in the first round's own fixes. Five were closed as not worth acting on, each with the reasoning left in its thread: image dimension checks that belong on the unconverted image path this PR does not touch, revalidating the python tool at send time (which would discard the user's file to prevent a degraded-but-correct preview), persisting The staging pull request is now closed. CIOn The failure was |
# Conflicts: # studio/frontend/src/components/assistant-ui/attachment-document-dialog.tsx
…e DOM lookups in the Office reader
…chment-formats Takes the Library stack as the new base; the next commit re-applies this PR as a layer on top of it.
…r the python tool
unslothai#12001 and unslothai#12017 landed on main; this keeps only this PR's layer on top.
… names in sandbox copies, strip RTF labels from stored text
…e originals grace
|
Review record for #11379, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#166. Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found. Round 1: reviewed mirror
|
…ython tool (unslothai#11379) * feat(studio): read .xlsx, .xlsm, .xltx and .xltm chat attachments Workbooks and workbook templates become tab-separated text per visible sheet, read in the browser with fflate and DOMParser like OpenDocument files: shared and inline strings, booleans, errors, and dates, times and durations by their number format. Hidden sheets, rows and columns are skipped, and inflate size and extracted text are bounded. The OpenDocument composer adapter is generalised so both formats share its read-on-add lifecycle, and desktop drop and paste route the new types to the composer. * feat(studio): read .pptx, .pptm and .ppsx chat attachments Slides are read in deck order as [Slide N] text blocks, skipping hidden slides and shapes and the Fallback copy of mc:AlternateContent. Relationship ids are now matched by namespace, since <p:sldId> also carries a plain numeric id. Desktop drop and paste accept the new extensions. * feat(studio): read .rtf chat attachments A small in-house RTF reader turns the document body into text: font, colour and style tables, metadata, pictures, field codes, headers and footers are skipped, and tables become tab-separated rows. Escaped bytes decode by the current font's charset, falling back to the ANSI code page, since macOS TextEdit writes cp1252 bytes under \ansicpg936 on Chinese systems; a byte written literally after an escaped double-byte lead joins it. Desktop drop and paste accept .rtf. * feat(studio): attach HEIC, HEIF, AVIF, BMP and TIFF images Model backends take JPEG, PNG, WebP and GIF, so these formats are re-encoded in the webview before they are attached: HEIC/HEIF to JPEG, the rest to lossless PNG. A webview that cannot decode a format says so and names the file. Conversion is held against send in both composers, a failed or removed conversion never sends the source file, and a desktop drop converts per file so one unreadable image does not stop the batch. Desktop drop and paste accept the new extensions. * feat(studio): attach .m2ts video Blu-ray and AVCHD camcorder clips are accepted by extension on every chat video path. The video/mp2t MIME is not claimed, because browsers also give TypeScript .ts files that type and the video adapter is matched before the text one. * fix(studio): attach camcorder .mts and broadcast .ts clips as video An MPEG transport stream named .mts or .ts was accepted as TypeScript and read as UTF-8 text. The composer, desktop drop and clipboard readers now look for the 0x47 sync byte at the start of three consecutive 188-byte packets (192 bytes for M2TS) and send a stream down the video path as video/mp2t, while TypeScript files stay text, including those the browser labels video/mp2t. The native readers take .ts and .mts under the video cap and reapply the text cap once the bytes say TypeScript. The video reference slot offers .ts and .mts too, and refuses TypeScript once it has read the file. * feat(studio): read .pages chat attachments iWork 2013 and later save a document as a zip of Snappy-compressed protobuf archives (Index/*.iwa) with no published schema. A small reader unpacks those archives under the Office reader's size caps, resolves object references, and returns the Pages body text with inline-object placeholders dropped. Desktop drop and paste accept .pages. * feat(studio): read .key chat attachments The iWork reader walks a Keynote deck's slide tree in order and reads each slide's title and body placeholders, then its drawables, following object references from them. Skipped slides keep their number, and builds, template slides and speaker notes are left out, as the PPTX reader does. Every object is walked at most once per document, so shared structure, a slide shared by two nodes or a node listed twice cannot multiply the work. Desktop drop and paste accept .key. * feat(studio): read .numbers chat attachments The iWork reader reads each Numbers sheet's text boxes and tables in order: table rows come from the table's tiles, cells from the version-5 cell storage (numbers kept exact from their decimal128 form, dates, booleans, durations, errors) and the table's string and rich-text lists. Rows become tab-separated lines under the attachment text budget, and table rows and list entries are charged against a size budget so a flood of tiny ones is refused. Keynote tables read the same way. Desktop drop and paste accept .numbers. * feat(studio): store chat attachment files for tool access Adds POST /api/chat/attachment-files, a per-account content-addressed store for the original bytes of chat attachments (200 MB cap, streamed past the body buffer). Re-uploading the same bytes renews the file. A sweep at startup and after chat, project and attachment deletion removes files not uploaded for 24 hours that no stored message references; uploads and the sweep share a lock so a renewal cannot race a deletion. * feat(studio): copy chat attachments into the tool sandbox A chat request can name stored attachments in sandbox_attachments. When the python tool is enabled, they are copied into the session sandbox under .unsloth_attachments/<id prefix>/<name> before the request reaches any backend, without following links and without replacing a file already there, so the model's edits survive later turns. The upload response returns that path. An unmodified copy does not count as the user's file when a chat is deleted. * feat(studio): give the python tool the original attachment files Document attachments (text, HTML, PDF, DOCX, OpenDocument, Office Open XML, RTF, iWork) upload their original file at send, alongside the inline text they already carry; the stored reference is saved with the message. On each turn where the python tool runs in Unsloth Studio, every stored attachment in the history names its sandbox path and the request asks for the copies. Other turns are unchanged, so models without tools still read the inline text. An upload failure keeps the attachment inline-only. The attachment download serves the stored original when it exists. * feat(studio): attach files only the python tool can read Adds .parquet, .feather, .arrow, .orc, .sqlite, .sqlite3, .db, .zip, .tar, .gz, .tgz, .bz2, .xz, .npy, .npz, .epub, .mobi, .xps, .oxps, .docm, .dotx, .odp and .odg to the chat composer, paste and desktop drop. The browser cannot read these, so the file is uploaded while it sits in the composer and reaches the model only as a copy in the python tool's working directory. They are refused unless the selected model runs Unsloth Studio's python tool, and a preview shows a short note instead of decoding the bytes. * feat(studio): let the python tool read every format an Unsloth Studio install can open Widens the tool-only attachment list to data, database, archive, ebook, Office template and macro, 3D, font and image formats that libraries shipped with every install (pandas, pyarrow, scipy, duckdb, PyMuPDF, fontTools, Pillow, safetensors and the standard library) can open. * feat(studio): tell the model which call opens each sandboxed attachment The sandbox note for a stored attachment now names a call that opens it with an installed library, such as fitz.open(path), sqlite3.connect(path) or zipfile.ZipFile(path) for Excel workbooks, so the model does not guess a package that refuses the file or is missing. Calls take a path variable because the sandbox scanner reads a string literal passed to .connect() as a network host. * feat(studio): preview images and documents only the python tool can read The attachment upload now returns a preview for tool-only images, documents and drawings, so the message can carry what the file holds instead of only its sandbox path: images the vision path cannot show become a PNG with a description, PyMuPDF documents become their text, and ODP, ODG and VSDX become the text of their pages. Nothing reads the preview yet. A preview runs in a spawned child that is killed after ten seconds, because MuPDF lays out one long paragraph in quadratic time and no bound on the input catches that; a timeout, a dead child or a reader error all mean no preview, and the upload still succeeds. Inside the child each reader is bounded by what its library actually loads. Images open only as the format their extension names, since Pillow otherwise picks a decoder from the bytes and icons decode their embedded frames while opening, so each frame's own header is read first. Documents are told their format rather than letting MuPDF guess from the stored file's hash name, and a document that is a zip is refused when its central directory or any member is too large for the reader to take whole. Pages, XML bytes and the text built from them have their own budgets, each marked in the text when it cuts. * feat(studio): preview archives and compressed files only the python tool can read Zip and tar archives now preview as a listing of their entries with the text of the small ones, and a single compressed file as its text, or an outline of its size when the content is not text. Both are built in the same bounded child as the other previews, and nothing reads the preview yet. Each reader is bounded by what its library actually reads rather than by the file's size. A zip's central directory is sized with the end record ZipFile itself locates, so an archive whose directory is too large to parse is listed as such instead. Only stored and deflated members are read, because ZipFile limits what one read inflates for deflate alone. A tar is read in one streaming pass over a capped decompressed stream, which bounds its extended headers as well as the member data skipped along the way, and the listing says it is incomplete whenever that cap is reached; member names that are not UTF-8 are replaced rather than surrogate-escaped, which the response could not encode. A compressed file reads up to the text cap plus one byte and marks the text when the cut falls short of that many characters. * feat(studio): outline data files only the python tool can read Chat attachments that only the python tool can open now carry an outline for the remaining data formats: Parquet, Arrow IPC and Feather, ORC, Stata, SAS (`.sas7bdat` and `.xpt`), NumPy `.npy` and `.npz`, and safetensors. The message a model receives says what the file holds - its shape, its columns, its first rows, or the arrays and tensors inside it - rather than only where the file is. Every reader is bounded by what the file itself states it would make its library read, and each budget cut is marked in the output, because a preview must cost about the same for a large attachment as for a small one: - Parquet decodes a page at a time, so the bound is the uncompressed size each row group states, checked for every group the five-row sample fills from. - ORC and Arrow IPC materialise a whole stripe or batch and state nothing about how large it is, so they are read through `pyarrow.dataset`, whose row count comes from the footer, and sampled only when the file is small, the cells fit the budget and no column is nested. - Stata decodes its long-string table whole on the first row read, and every value label with it. Both sizes come from the file's own map, which is walked by the lengths the header states rather than searched, because a dataset label is free text that can hold the same tags. A table too large to read through leaves the values as their stored codes, or leaves the sample out when the rows cannot be read without it. - A sas7bdat states the header and page lengths pandas asks for before it has read anything, and Python reserves the whole buffer even for a read a short file cannot fill, so those claims are checked first. Character columns are decoded with the encoding the file names when Python has that codec. - Arrays over the budget are described from their header alone, and `numpy` is given this module's header budget rather than its own default, which a wide structured dtype exceeds in an otherwise small file. Formats are taken from the attachment's filename, never from the stored path, which is a hash with no extension. Text that cannot survive a round trip through UTF-8 is replaced before it leaves the reader, because a name inside a file can hold a lone surrogate that the JSON response cannot encode. Nothing reads these previews yet; the frontend change follows. * feat(studio): preview databases, 3D models and fonts in chat attachments SQLite databases, STL, PLY, GLB, 3MF and KMZ models and TTF/OTF/TTC fonts previously reached the model as a tool-only note, so a message carried nothing about what the file held. Each now outlines what the file states about itself: a database its tables with their columns, row counts and first rows; a mesh its triangle or element counts and the name it carries; a glTF its scene counts, generator and mesh names; a 3MF or KMZ the model or map inside the container over the container's own listing; a font its name, glyph count and fixed pitch. Every reader stays inside what the file says reading it would cost, and says so whenever a budget cuts what it shows. - A SQLite cell is loaded whole by any select that returns it, so cells are measured with octet_length, which answers from the record header, and a cell too large to show is described by its type and size instead. Builds without octet_length cannot size a cell without reading it, so they report no rows rather than read one. - Views and virtual tables compute what they hand back, so nothing in the file states what five rows of one would cost. They are listed but never sampled, identified by having no b-tree of their own rather than by the schema text, which can be written to say anything. - Opening any table parses every CREATE in the file, which a file can be written to make expensive several times over. The preview process therefore carries a limit on what SQLite may allocate; the limit can be lowered but never lifted, so it belongs to that process and a reader only asks whether one is in force. - A model or map inside a container is found through what the package declares, falling back to the conventional name, and is read only when the directory's stated size is within the XML budget. - Header windows, listings and element text all mark what they leave out, including where the text strips back short enough that the outline cap would otherwise stay silent. * feat(studio): send attachment previews to the model in chat A file only the python tool can read reached the model as one line naming it, so the model had to open it with the tool before it knew what was in it. The upload response already carries a preview of such a file — an image, the document's text, or an outline — and this puts that preview in the message. `uploadAttachmentFile` now returns the preview, shape-checked the way the response's other fields already were, and `toolOnlyAttachmentContent` turns it into the attachment's content: an image part with a description line, the document's text under a `[FORMAT: name]` header, or an outline under `[Outline of name]`. A file with no preview reads exactly as it did before, as does a failed upload. The image part is added only when the chat model takes images. That check was a thirty-line block inside `VisionImageAdapter.add`; it is now `imageInputUnavailableReason()`, called from both places, so the two cannot drift apart. What the message persists is `storedAttachmentFile(upload)` rather than the upload itself: the preview's bytes are already in the message's content, so storing them again would put the same text, or the same image, in the history twice. It keeps one thing the preview decided — whether the file's own text is inline — because the note that tells the model where the file lives says "its text is below, so answer from it" only when that text really is below. An outline is not the whole file, so outlines and images keep the note that points at the python tool. No change was needed where the request is built: the parts of every attachment are already walked whatever the attachment's type. One behaviour follows from sending the image: a thread that carries an image cannot be continued on a text-only model, which is how the chat already treats images, and a tool-only image attachment now joins them. * Studio: document viewer for PDF, Word, Excel and PowerPoint, with origin links in Library * Studio: smaller corner radius on the file viewer * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: show chat CSV and markdown attachments without the chat wrapper * Studio: Library grid and sort polish, edge to edge document pages * Studio: address review on originals sweep, 1904 dates, slide tables and text downloads * Studio: Excel formats, formula cells, Office text cap and extensionless originals * Studio: Excel date tokens and built-in time formats, hidden rows and slides, originals sweep on message removal * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: workbook cell cap, early 1900 dates, fraction formats, virtualized PDF pages, large DOCX images * Studio: Excel digit placeholders, slide charts, Office checks at attach, run origins under outputs * Studio: conditional Excel formats, virtualized slides, Office read at attach, whole-text downloads * Studio: shared formulas, chart and line-break reading, originals save and sweep lock, deduplicated storage * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: faster document viewer, open review fixes Spreadsheets - Read sheet XML as text instead of through DOMParser, and only up to the rows kept. Unpack only the parts the workbook uses, so custom XML and pivot caches are skipped. Shared strings decode lazily. - Parse each number format once per workbook instead of once per cell. - Grid renders only the columns in view, with memoized rows. - Quoted semicolons no longer split format sections, scientific formats keep their literals, and elapsed times show fractional seconds. Presentations - Pictures stay as Blobs with object URLs made per mounted slide, instead of base64 data URLs for the whole deck. Video and audio are not unpacked. - Native tables are capped like chart tables. SmartArt labels are read. Word - Rendering stops after 50,000 elements, with a note. Chat - Office text for the model is budgeted in UTF-8 bytes, delimiters included. - Attaching an XLSX or PPTX reads the file once. Chat originals - Sweeps no longer create the originals folder, so a late sweep cannot recreate a deleted account's workspace. - Startup sweeps every account. Deleting an attachment from the Library sweeps too. * Studio: slim down document viewer and chat originals tests * Studio: fraction sign, text format sections, lazy shared strings - A negative value in its own fraction section, such as (# ?/?), no longer gets an extra minus. - String cells use the format's text section: the fourth section, or a single section with @. ABC in 0;0;0;"SKU-"@ shows SKU-ABC. - Shared strings are scanned from the part's bytes only up to the highest index a cell uses, and decoded one at a time, instead of building the whole table. * Studio: let a full 5,000 by 200 sheet fit the workbook cell budget * Studio: chat attachment cards, chips and the Library viewer * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: tighter Office reader bounds, built-in currency formats - A worksheet whose first row runs past the 64 MB XML cap is truncated instead of decoded whole. - At most 100 visible sheets are read, so empty sheets cannot add unbounded tabs and unzip passes. - PPTX inflates only what visible slides use: their XML and rels, charts, SmartArt data and, for the viewer, their pictures. Notes, comments, masters and unused media are skipped. - Each slide mounts at most 10,000 paragraphs, table cells and pictures, ending with a "…" when cut. - Built-in formats files leave out are filled in: currency (5 to 8), fractions (12, 13), accounting (41 to 44) and 48. East Asian date and time IDs fall back to the standard ones. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: five attachment cards per row, borderless image cards, dark cards keep their edge * Studio: count extracted text in storage, keep elapsed-time literals - The attachment inventory records the extracted text size of documents with a kept original (inventory version 5). Disk usage counts that text for every message, and the original only once and only while on disk. - Elapsed-time formats replace parsed placeholders only, so quoted or escaped text stays as written: [h]:mm "hours" shows 1:00 hours. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: slide cap, elapsed sign, temporary chat documents, export origins - PPTX slides are parsed one at a time instead of all held as DOMs, hidden slides are found from the root tag, and at most 500 slides are read with a note when more follow. - Negative elapsed times in their own section use that section's sign, so [h]:mm;([h]:mm) shows (1:00). - Documents sent in a temporary chat keep their file in memory, so they still open as pages, grids or slides. Saving the chat uploads them as originals. Serialized attachments never carry the File. - Exports record their source checkpoint, and Library links an export to a training run only through that metadata. Older Studio exports fall back to their folder name; folders with no export metadata get no run link. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: XLSM by MIME, format literals, bounded styles and DOCX parts - The macro-enabled workbook MIME key is lowercase, as lookups are, so an XLSM picked without its extension keeps its original and opens as a grid. - Padding, fill and bracket tags are removed only outside quoted and escaped text: "A_B"0 shows A_B1. Currency symbols stay literal, so [$kr.-41D] no longer reads its dot as a decimal point. - Only the number format, font and cell format sections of styles.xml are decoded, each found by a byte scan and capped at 16 MB. - The DOCX viewer keeps oversized images only, not other large parts. - When a sent document's original is gone, its stored text stays downloadable, as a .txt file. * Studio: index Office archives once, percent in scientific formats, MIME-only CSV, sweep after upserts * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: attachment viewers mount on first open, sent text downloads whole - Every attachment tile mounted a MediaViewer up front, whose project menu subscribes to and refetches the project list. The viewer now mounts on first open and stays for its close animation, so a long thread pays nothing for tiles never opened. - A sent text file's Download and Chat about this used the capped preview text; they now cut the whole body from the stored text, as the document viewer does. - A failed read for Chat about this or Download shows a toast instead of rejecting silently. - The audio viewer offers Download only when there is a clip to build it from. * Studio: cap slides before inflating them, elapsed placeholder widths, percent fractions * Studio: parse each slide as it is read, grouped shape frames, CDATA-safe sheet scan, scaled fractions, finished runs first * Studio: bound cell text and DOCX paragraphs before parsing, slide paragraph budget, hidden shared-formula masters, quoted fraction literals, repeated percent, false font flags * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: compact shared-string offsets, capped CSV fields and slide XML, engineering notation, group flips and rotation, MIME-only CSV in Library * Studio: bound every DOM-parsed Office part, read slide charts and pictures per frame * Studio: one sweep scheduler thread, deck text and chart budgets, ZIP64 part sizes, DOCX images by content type, whole-row and column formula shifts * Studio: slide shapes in document order, own flips, picture budget and declared types, clipped table cells, lazy workbook support parts, quoted sheet names * Fix cached empty string formula results in document viewer * Keep out-of-range date cells from aborting document previews * Studio: bounded worksheet inflation, deck text charged per box, fraction search by continued fractions, PDF canvas bounds, main part from package rels, Markdown by MIME * Studio attachments: play videos in the viewer, keep local display settings on legacy records - Sent and composer videos open a video player in the Library viewer instead of falling through to the text viewer; composer clips are labelled and iconed as video rather than audio by their .mp4 name. - Personalization reports whether composerAttachments / sentAttachments were saved, so a record written before they existed keeps the browser's values instead of the server defaults. * Studio viewer: ZIP64 and streamed shared strings, referenced DOCX images, picture crop, PDF text layer bound * Studio viewer: inflate only the DOCX relationships read, bound PDF image size * Studio viewer: cap ZIP entries, mark sheets cut past the shared strings bound, bound picture pixels * Studio viewer: bound DOCX picture pixels, refuse SVGs that embed rasters, cap DOCX entries * Studio viewer: mark sheets cut when styles are past their bound, release a document when its viewer closes * Studio viewer: bound PDF page operations, bound format precision, read the hidden flag from the slide root * Studio viewer: cap shared strings indexed, keep structured references, bound format codes; recheck an original before removing it * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio viewer: pixel budgets per slide and document, cut DOCX markup before parsing, release PDF pages, cap listed pages and style tags, bound export metadata * Trim comments in document viewer and chat originals * Drop redundant comments across attachment viewer changes * Keep comments that record non-obvious invariants in the viewer * Declare contentType on the attachment selectAttachmentSource reads * Trim attachment display comments * Studio viewer: show the integer in formats without whole digits, read lowercase cell references, prefix DOCX ids * Studio attachments: drop a viewer load or chat handoff that finishes after a sign-out * Revert the sign-out fence on viewer actions: loads resolve from memory and an account switch reloads the page * Re-measure the startup bundle budget for the chat attachment cards * Studio: trim comments in attachment format changes * Studio: fix attachment sweep cost, sandbox name round trip, original downloads - Sweep reads every referenced blob id in one query instead of one LIKE scan per stored file under the global store lock. - sandbox_attachment_path strips a trailing space or dot left by byte truncation, so the basename the frontend sends back derives the same path the file was copied to. - Uploaded files dialog on web saves a kept original under its name instead of opening a nameless octet-stream tab. - Numbers cells print doubles at 15 significant digits, matching the xlsx reader. - Library chat handoff retries held files when Code or tool support changes. * Keep aui-attachment-root on composer attachment cards, which studiobench counts * Studio viewer: decode a composer Markdown file as its attachment adapter does * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: upload attachment originals only for python tool turns, native DOM lookups in the Office reader * Write the export metadata fixture with json.dumps so Windows paths stay valid JSON * Studio: RTF, HEIC and transport stream attachments, and chat files for the python tool * Studio: simplify attachment format changes * Studio: keep temporary chat files in memory on python turns, skip malformed stored hashes * Studio: downscale converted images past 16.7 MP, avoid Windows device names in sandbox copies, strip RTF labels from stored text * Studio: store a python-kept document when a temporary chat is saved * Studio: upload a tool-only file again when it sat staged past half the originals grace * Studio: admit tool-only files on the effective Code state, as the send path does --------- Co-authored-by: Michael Han <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: imagineer99 <[email protected]> Co-authored-by: Michael Han <[email protected]> Co-authored-by: danielhanchen <[email protected]> Co-authored-by: Daniel Han <[email protected]>
Built on #12001 and #12017
This PR is a layer on top of the Library work in #12001 (document viewer) and #12017 (attachment cards and chips), both now merged into
main.Rebuilt so it no longer duplicates the stack:
chat_originalsstore instead of a second attachment store. Documents Studio: document viewer for PDF, Word, Excel and PowerPoint, with origin links in Library #12001 does not already upload are uploaded only when the selected model runs the python tool, so other turns get no extra send latency..pages,.numbers,.key) and the server-side previews of tool-only files are left out, to be proposed separately.What this layer adds:
.m2tsvideo, and.ts/.mtsfiles told apart by their bytes, so TypeScript stays text and MPEG transport streams go down the video path.The description below is the original one and still mentions the parts that were moved out.
Summary
Unsloth Studio chat rejected many common files: Excel workbooks and templates, PowerPoint decks, RTF, Pages/Numbers/Keynote documents, iPhone photos (HEIC), AVIF/BMP/TIFF images, Blu-ray
.m2tsclips, and data or archive files such as.parquet,.sqliteor.zip. Dropping one showed an "unsupported" toast. Camcorder.mtsand broadcast.tsvideo was worse: it was accepted as TypeScript and sent to the model as garbled UTF-8 text. This PR accepts them through the file picker, paste, and desktop drag-and-drop/paste, using two routes:What changed
Inline formats
.xlsx/.xlsm/.xltx/.xltm: sheets in workbook order, hidden sheets/rows/columns skipped, shared and inline strings, booleans, errors, dates and times from number formats (including the 1904 date system). Read in-house with fflate + DOMParser, reusing the OpenDocument archive and XML size caps..pptx/.pptm/.ppsx: visible slides in deck order, text frames and tables,[Slide N]headers..rtf: groups, control words, hex and\uescapes, fields and tables.\'xxbytes decode by the current font's\fcharset, falling back to\ansicpg, because TextEdit writes\ansicpg936with cp1252 bytes..pages/.numbers/.key(iWork 2013 and later): a small in-house reader for the zip of Snappy-compressed protobuf archives (Index/*.iwa) iWork writes, which has no published schema. Pages gives the body text; Keynote gives visible slides in deck order with[Slide N]headers (builds, templates and speaker notes left out, as for PPTX); Numbers gives each sheet's text boxes and tables as tab-separated rows, with numbers printed exactly from their decimal128 form, dates, booleans and rich-text cells. The reader keeps the Office archive caps and bounds every allocation and every walk by input size: one Snappy output buffer per archive, a per-object and per-row charge against size budgets, each object walked at most once per document, and table rows read only while the text budget lasts, so floods of empty chunks, records, references, shared slides, list entries or blank rows are refused or cut short instead of exhausting memory or freezing the composer..m2tsvideo, matched by extension only: browsers give TypeScript.tsfiles the samevideo/mp2tMIME type..mts/.tsfix: a file is treated as an MPEG transport stream when three consecutive 188-byte packets (192 for M2TS) start with the 0x47 sync byte, in the composer, desktop drop and clipboard readers. Streams go down the video path asvideo/mp2t; TypeScript stays text, including files the browser labelsvideo/mp2t. The native readers take.ts/.mtsunder the video cap and reapply the text cap once the bytes say TypeScript, and the video reference slot accepts both.Python-tool route
POST /api/chat/attachment-files: an account-scoped, content-addressed store (sha256, 200 MB cap), exempt from the/api/chatbody buffering. Unreferenced blobs are swept after a 24 h grace period, at startup and after thread, project or attachment deletion.sandbox_attachmentson chat completions: when the python tool is enabled, the backend copies each stored file to.unsloth_attachments/<id>/<sanitised name>in the session sandbox before the request is dispatched. The copy is symlink-safe and never overwrites; names are capped at 80 UTF-8 bytes. Unmodified copies do not count as user files when a chat is deleted.Frontend: document adapters upload the original at send time, in parallel with the existing extraction. The reference is stored with the message, and each request decides whether to add the sandbox paths, so switching model or tools mid-thread does the right thing. If the upload fails, the attachment silently stays inline-only.
Downloading an attachment serves the original file when it was stored.
Tool-only formats, limited to what libraries shipped with every install can open (pandas, pyarrow, scipy, duckdb, PyMuPDF, fontTools via matplotlib, Pillow, safetensors, the standard library):
.parquet .feather .arrow .orc .dta .sas7bdat .xpt .mat .npy .npz .safetensors.sqlite .sqlite3 .db .gpkg .mbtiles .duckdb.zip .jar .whl .apk .tar .gz .tgz .bz2 .tbz2 .tbz .xz .txz .lzma.epub .mobi .fb2 .cbz .xps .oxps .docm .dotx .dotm .potx .potm .ppsm .odp .odg .vsdx.stl .3mf .ply .glb .kmz .ttf .otf .ttc .woff.psd .ico .icns .cur .tga .dds .pcx .ppm .pgm .pbm .pnm .qoi .jp2 .j2k .xbm .xpm .sgi .fitsThe file is uploaded while it sits in the composer. It is refused unless the selected model runs Unsloth Studio's python tool (the same placement the chat request uses: not when a provider hosts code execution). Left out on purpose: pickle-based formats (
.pt,.pkl), formats whose reader some installs lack (.msgpack,.woff2,.h5/.nc),.xls, which nothing installed can open, and.rar, whose format is not open.One note per file, worded for small models. A tool-only file gets
[<name> is saved at <path> in the python tool's working directory; open it with <call>, where path = "<path>"]. An attachment whose text is already inline gets[<name>: its text is below, so answer from it. For calculations, the python tool has the file at path = "<path>"], so the model does not reopen a file it has already read. The call is, for example,fitz.open(path)for.docm/.pptx/.epub,sqlite3.connect(path),zipfile.ZipFile(path)for.ziporPIL.Image.open(path). Without it, models tend to reach for python-docx (which refuses.docm) or for openpyxl, python-pptx and odfpy, which are not installed. Excel, iWork,.odsand.odtget no call: their text is inline, pandas' Excel engines are not installed, nothing in Python decodes iWork, and pointing small models at the raw zip sent them into the XML. Calls take apathvariable because the sandbox's static scanner reads a string literal passed to any.connect()(includingsqlite3.connect("a.db")) as a network host.Previews of files only the python tool can read
Naming the file and the call that opens it still left the model guessing what was in it, so it explored with the tool: 833 tool calls over 73 cases, and 53 of them answered correctly. The upload response now also carries a preview, built server-side right after the file is stored, and the message carries it:
.psd,.ico,.fits, …): a PNG thumbnail capped at 1024 px on the long side, plus a description. The image part is added only when the chat model takes images — the same check the vision adapter makes — and otherwise only the description goes..epub,.docm,.odp,.vsdx, a single compressed text file, …): the text, under a[FORMAT: name]header. Such an attachment then gets the "its text is below, so answer from it" note instead of the one pointing at the tool, because the text really is below.{archives, data files, databases, arrays, 3D models, fonts}): what the file states about itself — a zip's entries with small member texts, a table's rows, columns, types and first rows, a database's tables and two sample rows, a mesh's counts, a font's name and glyph count.Every reader is bounded by what the file itself declares, and each preview is built in a spawned child killed after 10 seconds, so a large or hostile file costs little and a failure is simply no preview: the attachment then reads exactly as it did before. The preview is not stored twice — it becomes the message's content, and the history keeps only the reference.
Relation to #7700
#7700 (draft) adds
.xlsxthroughread-excel-file, without drag-and-drop. This PR covers.xlsxwithout a new dependency, including drag-and-drop, and reuses the same OOXML plumbing for.pptx. It supersedes #7700 for.xlsx. Thanks to @Imagineer99 for the original work.Risks and tradeoffs
Validation
pythonwas among the enabled tools;.m2tsfrom a pipe;.mts/.tsdetection checked against real ffmpeg streams and 17,417 real TypeScript files, with no false positives;Before and after
Merge base
1759e6458vs head0f9eb73d2, both installs built fresh, same fixture files (book.xlsx, notes.rtf, photo.bmp) picked through the composer's file menu. book.xlsx is the control: main already reads it.Composer after picking the three files: main keeps only book.xlsx; this PR also attaches notes.rtf and the bitmap, converted to photo.png before it reaches the model.
Opening the notes.rtf card on the head shows the text extracted in the browser.