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
add folder picking and drag-drop for paired image and caption datasets (#8216)
Maheswar Kumarc2c04a486709
diff --git a/studio/frontend/src/features/images/train/dataset-files.ts b/studio/frontend/src/features/images/train/dataset-files.tsnew file mode 100644index 00000000000..a17296364c4--- /dev/null+++ b/studio/frontend/src/features/images/train/dataset-files.ts@@ -0,0 +1,282 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// mirrors _DIFFUSION_DATASET_IMAGE_EXTS and _DIFFUSION_DATASET_TEXT_EXTS in backend/routes/training.py.+export const DATASET_IMAGE_EXTS = [".png", ".jpg", ".jpeg", ".webp", ".bmp"];+export const DATASET_TEXT_EXTS = [".txt", ".caption", ".jsonl"];+export const DATASET_FILE_ACCEPT = [...DATASET_IMAGE_EXTS, ...DATASET_TEXT_EXTS].join(",");++const ACCEPTED = new Set([...DATASET_IMAGE_EXTS, ...DATASET_TEXT_EXTS]);++// a caption jsonl runs to kilobytes, so scan a prefix rather than decoding the whole upload.+const METADATA_SCAN_BYTES = 1024 * 1024;++// starlette caps a multipart body at 1000 file parts and fastapi does not raise it, so a larger+// selection is sent in slices; the endpoint accumulates repeat uploads into the same folder.+export const DATASET_UPLOAD_CHUNK = 500;++/** slice `files` so no request exceeds the part cap or `maxBytes`, keeping casefold-equal+ * names together and sending those groups first: the backend can only compare names inside+ * one request, and splitting a group is exactly what lets the second request overwrite the+ * first. Such a group ships whole even over `maxBytes`; `oversizedChunk` catches that. */+export function chunkDatasetUpload(files: File[], maxBytes: number): File[][] {+ const groups = new Map<string, File[]>();+ for (const file of files) {+ const key = destinationName(file).toLowerCase();+ const group = groups.get(key);+ if (group) group.push(file);+ else groups.set(key, [file]);+ }+ // a group of more than one is a case-variant set, which the backend refuses outright on a+ // case-insensitive dataset folder. Send those first so that refusal lands while there is+ // still nothing committed, rather than behind slices that have already been written.+ const all = [...groups.values()];+ const chunks: File[][] = [];+ let current: File[] = [];+ let bytes = 0;+ for (const group of [...all.filter((g) => g.length > 1), ...all.filter((g) => g.length === 1)]) {+ const groupBytes = group.reduce((sum, f) => sum + f.size, 0);+ const overCount = current.length + group.length > DATASET_UPLOAD_CHUNK;+ const overBytes = current.length > 0 && bytes + groupBytes > maxBytes;+ if (current.length > 0 && (overCount || overBytes)) {+ chunks.push(current);+ current = [];+ bytes = 0;+ }+ current.push(...group);+ bytes += groupBytes;+ }+ if (current.length > 0) chunks.push(current);+ return chunks;+}++/** the destination name in the first chunk no split can fit under `maxBytes`, or null.+ *+ * uploads accumulate, so a chunk the endpoint 413s leaves every chunk before it on disk. */+export function oversizedChunk(chunks: File[][], maxBytes: number): string | null {+ for (const chunk of chunks) {+ if (chunk.reduce((sum, f) => sum + f.size, 0) > maxBytes) return destinationName(chunk[0]);+ }+ return null;+}++/** the first metadata file whose captions are keyed on a subfolder path, or null. a folder pick+ * flattens the tree, so rows keyed "images/001.png" silently resolve to no caption at all. */+export async function metadataKeyedOnSubfolders(files: File[]): Promise<string | null> {+ for (const file of files) {+ if (!file.name.toLowerCase().endsWith(".jsonl")) continue;+ let text: string;+ try {+ text = await file.slice(0, METADATA_SCAN_BYTES).text();+ } catch {+ continue; // unreadable here is the backend's problem, not a reason to block the upload+ }+ for (const line of text.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ let row: unknown;+ try {+ row = JSON.parse(trimmed);+ } catch {+ continue;+ }+ if (!row || typeof row !== "object") continue;+ const record = row as Record<string, unknown>;+ const key = record.file_name || record.image || record.file;+ if (typeof key === "string" && (key.includes("/") || key.includes("\\"))) {+ return file.name;+ }+ }+ }+ return null;+}++// str.strip() is not trim(): Python keeps U+FEFF and strips U+001C-001F and U+0085. trim() read+// a name ending in U+FEFF as an accepted "cat.png", but the multipart part carries the name+// whole, so the endpoint saw a suffix with the U+FEFF still on it and refused the slice.+// This class is exactly str.isspace() over the BMP; NUL is stripped separately, as it is there.+const PY_SPACE_CLASS =+ "\\t\\n\\v\\f\\r\\u001c-\\u001f\\u0020\\u0085\\u00a0\\u1680" ++ "\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";+const PY_STRIP = new RegExp(`^[${PY_SPACE_CLASS}]+|[${PY_SPACE_CLASS}]+$`, "g");++/** the name the upload stores this file under, matching the normalisation in training.py. */+export function destinationName(file: File): string {+ const base = file.name.replace(/\\/g, "/").split("/").pop() ?? "";+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the backend strips nulls here too+ return base.replace(PY_STRIP, "").replace(/\0/g, "");+}++// mirrors Path(name).suffix.lower(): a leading dot starts the stem, so ".png" has no suffix.+function extensionOf(name: string): string {+ const dot = name.lastIndexOf(".");+ return dot < 1 ? "" : name.slice(dot).toLowerCase();+}++/** where a picked file sat: the folder-relative path when a folder pick supplied one. */+function displayPath(file: File): string {+ return (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;+}++function isHidden(name: string): boolean {+ return name.startsWith(".");+}++// a dataset folder holds a .thumbs cache whose jpegs would re-upload as training images.+function inHiddenPath(file: File): boolean {+ const relative = (file as File & { webkitRelativePath?: string }).webkitRelativePath;+ // a name typed into a dialog, and segment 0 (the picked folder itself), are the user's choice.+ return relative ? relative.split("/").slice(1).some(isHidden) : false;+}++/** whether two image names resolve to one `<stem>.txt` sidecar, as `_shares_sidecar` does:+ * the stems clash on an exact match, so only an extension-case pair of one spelling is exempt. */+function sharesSidecar(other: string, name: string): boolean {+ const otherExt = extensionOf(other);+ if (other === name || !DATASET_IMAGE_EXTS.includes(otherExt)) return false;+ const otherStem = other.slice(0, other.length - otherExt.length);+ const stem = name.slice(0, name.length - extensionOf(name).length);+ if (otherStem.toLowerCase() !== stem.toLowerCase()) return false;+ return otherStem === stem || other.toLowerCase() !== name.toLowerCase();+}++/** two picked paths the flat dataset folder cannot hold apart; `kind` picks the wording. */+export interface DatasetCollision {+ kind: "name" | "stem";+ first: string;+ second: string;+}++export interface DatasetFileSelection {+ /** the files to upload, in picked order. */+ files: File[];+ imageCount: number;+ captionCount: number;+ /** files left out because the endpoint does not accept their extension. */+ skipped: number;+ collisions: DatasetCollision[];+}++/** filters a picked or dropped batch down to what the dataset endpoint accepts. */+export function selectDatasetFiles(input: File[]): DatasetFileSelection {+ const files: File[] = [];+ const collisions: DatasetCollision[] = [];+ const seen = new Map<string, string>();+ const imageStems = new Map<string, Array<{ name: string; path: string }>>();+ let imageCount = 0;+ let captionCount = 0;+ let skipped = 0;++ for (const file of input) {+ if (inHiddenPath(file)) continue;+ // keyed on the stored name, so " cat.png" and "cat.png" are seen as one destination+ const dest = destinationName(file);+ const ext = extensionOf(dest);+ if (!dest || dest.includes("..") || !ACCEPTED.has(ext)) {+ skipped += 1;+ continue;+ }+ // a dataset folder is flat, so two tree paths sharing a basename are one destination.+ // matched exactly: only the backend knows whether the dataset filesystem folds case.+ const path = displayPath(file);+ const previous = seen.get(dest);+ if (previous !== undefined) {+ collisions.push({ kind: "name", first: previous, second: path });+ continue;+ }+ const isImage = DATASET_IMAGE_EXTS.includes(ext);+ // two images sharing a stem resolve to one <stem>.txt caption, which the backend refuses.+ // every accepted variant is kept and compared, since the exemption is not transitive.+ if (isImage) {+ const key = dest.slice(0, dest.length - ext.length).toLowerCase();+ const variants = imageStems.get(key) ?? [];+ const clash = variants.find((v) => sharesSidecar(v.name, dest));+ if (clash !== undefined) {+ collisions.push({ kind: "stem", first: clash.path, second: path });+ continue;+ }+ variants.push({ name: dest, path });+ imageStems.set(key, variants);+ }+ seen.set(dest, path);+ files.push(file);+ if (isImage) imageCount += 1;+ else captionCount += 1;+ }++ return { files, imageCount, captionCount, skipped, collisions };+}++/** the first selected image the dataset folder already holds under a sidecar-sharing name, or+ * null. the backend compares each upload against the folder, so on a chunked top-up that 400+ * lands with the slices before it already written. `existing` is the folder's image names. */+export function existingStemClash(files: File[], existing: string[]): DatasetCollision | null {+ for (const file of files) {+ const dest = destinationName(file);+ if (!DATASET_IMAGE_EXTS.includes(extensionOf(dest))) continue;+ const clash = existing.find((name) => sharesSidecar(name, dest));+ if (clash !== undefined) return { kind: "stem", first: clash, second: displayPath(file) };+ }+ return null;+}++// readEntries yields at most 100 entries per call and ends with an empty batch.+function readAllEntries(reader: FileSystemDirectoryReader): Promise<FileSystemEntry[]> {+ return new Promise((resolve, reject) => {+ const all: FileSystemEntry[] = [];+ const next = () =>+ reader.readEntries((batch) => {+ if (batch.length === 0) {+ resolve(all);+ return;+ }+ all.push(...batch);+ next();+ }, reject);+ next();+ });+}++function fileOf(entry: FileSystemFileEntry): Promise<File> {+ return new Promise((resolve, reject) => entry.file(resolve, reject));+}++async function walkEntry(entry: FileSystemEntry, out: File[], prefix = ""): Promise<void> {+ const path = prefix + entry.name;+ if (entry.isFile) {+ const file = await fileOf(entry as FileSystemFileEntry);+ // a dropped File has no webkitRelativePath, so stand one in and messages can name the tree.+ Object.defineProperty(file, "webkitRelativePath", { value: path, configurable: true });+ out.push(file);+ return;+ }+ if (!entry.isDirectory) return;+ const reader = (entry as FileSystemDirectoryEntry).createReader();+ for (const child of await readAllEntries(reader)) {+ // a dropped entry carries no relative path, so nested hidden names are filtered here.+ if (isHidden(child.name)) continue;+ await walkEntry(child, out, `${path}/`);+ }+}++/** every file in a drop, descending into any dropped folders; throws if the walk cannot finish. */+export async function filesFromDataTransfer(transfer: DataTransfer): Promise<File[]> {+ const entries: FileSystemEntry[] = [];+ let fileItems = 0;+ for (const item of Array.from(transfer.items ?? [])) {+ if (item.kind !== "file") continue;+ fileItems += 1;+ const entry = item.webkitGetAsEntry?.();+ if (entry) entries.push(entry);+ }+ // still synchronous here, so the drag data store is readable; it is protected once drop yields.+ if (entries.length === 0) return Array.from(transfer.files ?? []);+ if (entries.length < fileItems) {+ // some items resolved and some did not, so the walk would quietly upload part of the drop.+ throw new Error("Some dropped items could not be read.");+ }+ const out: File[] = [];+ // no partial result: a half-walked folder would upload as if it were the whole dataset.+ for (const entry of entries) await walkEntry(entry, out);+ return out;+}diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsxindex 7c699da1b6c..fa55056c53d 100644--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx@@ -1,9 +1,21 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ type DragEvent,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";-import { Settings02Icon, Upload01Icon } from "@hugeicons/core-free-icons";+import {+ FolderAddIcon,+ Settings02Icon,+ Upload01Icon,+} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";@@ -23,6 +35,11 @@ import { InfoHint } from "@/components/ui/info-hint";import { useScrollFades } from "@/hooks/use-scroll-fades";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";import {Select,SelectContent,@@ -36,6 +53,11 @@ import type { TrainingSeriesPoint } from "@/features/training";// eslint-disable-next-line no-restricted-imports -- matches images-page.tsx's token accessimport { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";import { cn } from "@/lib/utils";+import {+ getCachedUploadLimitLabel,+ loadUploadLimitSettings,+} from "@/features/settings/api/upload-limit";+import { isTauri } from "@/lib/api-base";import { toast } from "@/lib/toast";import {@@ -49,12 +71,23 @@ import {getDiffusionTrainingRun,getDiffusionTrainingStatus,listDiffusionDatasetExamples,+ listDiffusionDatasetImages,listDiffusionTrainingRuns,startDiffusionTraining,stopDiffusionTraining,uploadDiffusionDataset,} from "../api";import { DatasetLabelingGrid, LabelingGridToggle } from "./dataset-labeling-grid";+import {+ DATASET_FILE_ACCEPT,+ DATASET_IMAGE_EXTS,+ chunkDatasetUpload,+ existingStemClash,+ filesFromDataTransfer,+ metadataKeyedOnSubfolders,+ oversizedChunk,+ selectDatasetFiles,+} from "./dataset-files";import { DatasetShowcase } from "./dataset-showcase";import { DiffusionCharts } from "./diffusion-charts";import {@@ -135,7 +168,6 @@ function repoIsPrequantized(baseModel: string): boolean {}// Dataset-select option value prefix for a not-yet-imported example; picking it imports.const EXAMPLE_PREFIX = "example:";-const DATASET_FILE_ACCEPT = ".png,.jpg,.jpeg,.webp,.bmp,.txt,.caption,.jsonl";// min-w-0 + a truncating value: a long option would otherwise set the grid column min width and push into its neighbour.const selectClass ="h-8 w-full min-w-0 text-xs *:data-[slot=select-value]:min-w-0 *:data-[slot=select-value]:truncate";@@ -145,6 +177,34 @@ const selectClass =// (150px for the run-length pair) and the cell painted over the next column.const fieldClass = "grid grid-cols-1 min-w-0 gap-2";+/** opens the folder picker; icon-only because the 416px rail already holds the select and the file-pick button. */+function FolderPickButton({+ disabled,+ onPick,+}: {+ disabled: boolean;+ onPick: () => void;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <Button+ type="button"+ size="icon"+ variant="outline"+ aria-label="Add a folder of images"+ className="size-8 shrink-0"+ onClick={onPick}+ disabled={disabled}+ >+ <HugeiconsIcon icon={FolderAddIcon} className="size-3.5" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Add a whole folder of images</TooltipContent>+ </Tooltip>+ );+}+/** A field's label with its guidance behind an "i" tooltip, keeping the grid scannable.* Only facts a user must act on stay on the page as text. */function FieldLabel({@@ -346,6 +406,12 @@ export function DiffusionTrainPanel({const fileInputRef = useRef<HTMLInputElement | null>(null);// Adds to the selected set; the other input creates a new one.const addInputRef = useRef<HTMLInputElement | null>(null);+ // one folder picker serves both targets, so the destination is captured when it opens.+ const folderInputRef = useRef<HTMLInputElement | null>(null);+ const folderTarget = useRef("");+ const [dropActive, setDropActive] = useState(false);+ // the authoritative in-flight guard: `uploading` is render state and reads stale in a closure.+ const uploadInFlight = useRef(false);const [gridOpen, setGridOpen] = useState(false);const [gridRefresh, setGridRefresh] = useState(0);const [examples, setExamples] = useState<DiffusionDatasetExample[]>([]);@@ -673,30 +739,215 @@ export function DiffusionTrainPanel({}, [viewRun?.metric_history]);// Uploads accumulate, so the same call both creates a folder and adds to an existing one.+ // `picked` can come from a file pick, a folder pick or a drop, so it is filtered here.const uploadTo = useCallback(- async (name: string, files: File[]) => {- if (files.length === 0) return; // the picker was cancelled+ async (name: string, picked: File[]) => {+ if (picked.length === 0) return; // the picker was cancelledif (!name) {toast.error("Give the dataset a folder name, e.g. my-style-photos.");return;}+ const { files, imageCount, skipped, collisions } = selectDatasetFiles(picked);+ if (collisions.length > 0) {+ const { kind, first, second } = collisions[0];+ const more =+ collisions.length > 1+ ? ` ${collisions.length - 1} other pair${collisions.length === 2 ? "" : "s"} clash too.`+ : "";+ toast.error(+ (kind === "name"+ ? `"${first}" and "${second}" have the same file name, and a dataset folder is ` ++ "flat, so one would overwrite the other."+ : `"${first}" and "${second}" differ only by extension, so they would share one ` ++ "caption file.") + `${more} Rename them and upload again.`,+ );+ return;+ }+ if (files.length === 0) {+ toast.error(+ `Nothing to upload. Pick images (${DATASET_IMAGE_EXTS.join(", ")}) and, ` ++ "optionally, a caption file beside each one.",+ );+ return;+ }+ // /diffusion/info only lists folders holding an image, so say why the set will not+ // appear yet rather than refusing a captions-first upload.+ const newCaptionsOnly =+ imageCount === 0 && !(info?.datasets ?? []).some((d) => d.name === name);+ if (uploadInFlight.current) {+ toast.error("An upload is already running. Wait for it to finish, then try again.");+ return;+ }+ uploadInFlight.current = true;setUploading(true);try {- const res = await uploadDiffusionDataset(name, files);- toast.success(- `Uploaded ${res.uploaded} file${res.uploaded === 1 ? "" : "s"} - ` +- `"${res.name}" now has ${res.image_count} images`,- );+ const misKeyed = await metadataKeyedOnSubfolders(files);+ // the endpoint accumulates into the same folder, so a tree past the multipart part or+ // byte cap goes up in slices rather than being refused outright.+ // the cap decides where the slices fall, so a guess makes the refusal below either too+ // strict or useless. Forced past the cache, which another tab can leave behind, and a+ // cap that cannot be read stops the upload.+ let maxBytes: number;+ try {+ maxBytes = (await loadUploadLimitSettings({ force: true })).maxUploadSizeBytes;+ } catch (e) {+ toast.error(+ "Could not read the upload size limit, so nothing was uploaded: " ++ `${e instanceof Error ? e.message : "the limit could not be read"}. Try again.`,+ );+ return;+ }+ const chunks = chunkDatasetUpload(files, maxBytes);+ // a slice no split can fit under the cap 413s, so refuse before the first request:+ // otherwise the slices ahead of it are already committed.+ const over = oversizedChunk(chunks, maxBytes);+ if (over) {+ toast.error(+ `"${over}" is over the ${getCachedUploadLimitLabel()} upload limit, so nothing was ` ++ "uploaded. Raise the limit in Settings, or leave that file out.",+ );+ return;+ }+ // one request is all-or-nothing on the backend, so only a split top-up needs the folder+ // checked as well: there a stem it already holds would 400 a later slice, mid-commit.+ if (chunks.length > 1) {+ // the list held here is the one from mount, so it cannot say the folder is new.+ // One more GET is nothing against a selection already going up in several requests.+ const known = await refreshInfo();+ if (!known) {+ toast.error(+ "Could not read the dataset list, so nothing was uploaded. Try again.",+ );+ return;+ }+ // a case-insensitive dataset root resolves "photos" onto an existing "Photos", so an+ // exact match would call that folder new and skip the check. Fall back to a folded+ // match and list the folder under the name the backend reports.+ const folder =+ known.datasets.find((d) => d.name === name) ??+ known.datasets.find((d) => d.name.toLowerCase() === name.toLowerCase());+ if (folder) {+ // no listing, no guarantee: skipping the check would upload the slices it exists to+ // hold back, so a failure here stops the upload rather than proceeding blind.+ let held: Awaited<ReturnType<typeof listDiffusionDatasetImages>>;+ try {+ held = await listDiffusionDatasetImages(folder.name);+ } catch (e) {+ toast.error(+ `Could not read what "${folder.name}" already holds, so nothing was uploaded: ` ++ `${e instanceof Error ? e.message : "the dataset could not be listed"}. Try again.`,+ );+ return;+ }+ const clash = existingStemClash(files, held.images.map((i) => i.filename));+ if (clash) {+ toast.error(+ `"${clash.second}" and "${clash.first}", already in "${folder.name}", differ only by ` ++ "extension, so they would share one caption file. Nothing was uploaded; " ++ "rename it and try again.",+ );+ return;+ }+ }+ }+ let res = await uploadDiffusionDataset(name, chunks[0]);+ let sent = res.uploaded;+ let stopped: string | null = null;+ for (const chunk of chunks.slice(1)) {+ try {+ res = await uploadDiffusionDataset(name, chunk);+ sent += res.uploaded;+ } catch (e) {+ stopped = e instanceof Error ? e.message : "upload failed";+ break;+ }+ }+ // caption_count is the folder total the backend resolves over sidecars and metadata alike.+ if (stopped) {+ toast.error(+ `Uploaded ${sent} of ${files.length} files into "${res.name}", then stopped: ` ++ `${stopped}`,+ );+ } else {+ toast.success(+ `Uploaded ${sent} file${sent === 1 ? "" : "s"} - ` ++ `"${res.name}" now has ${res.image_count} images, ` ++ `${res.caption_count} captioned`,+ );+ }+ if (skipped > 0) {+ toast.info(+ `Skipped ${skipped} file${skipped === 1 ? "" : "s"} that ` ++ `${skipped === 1 ? "was" : "were"} neither an image nor a caption.`,+ );+ }+ if (newCaptionsOnly) {+ toast.info(+ `"${res.name}" holds captions but no images yet, so it stays out of the dataset ` ++ "picker until you add some.",+ );+ }+ if (misKeyed) {+ toast.info(+ `${misKeyed} keys its captions on subfolder paths, and a dataset folder is flat, ` ++ "so those rows will not match. A .txt beside each image always will.",+ );+ }await refreshInfo();setDataset(res.name);setGridRefresh((k) => k + 1);} catch (e) {toast.error(e instanceof Error ? e.message : "Upload failed");} finally {+ uploadInFlight.current = false;setUploading(false);}},- [refreshInfo],+ [info, refreshInfo],+ );++ const pickFolder = useCallback((name: string) => {+ folderTarget.current = name;+ folderInputRef.current?.click();+ }, []);++ // a drop lands on whichever set the field is showing, filling a new folder or topping up the selected one.+ const dropTarget = uploadMode ? uploadName.trim() : dataset;+ const onDrop = useCallback(+ async (event: DragEvent) => {+ if (isTauri) return;+ // only claim file drops: preventDefault on a text drag kills editing in the caption boxes.+ if (!event.dataTransfer.types.includes("Files")) return;+ event.preventDefault();+ setDropActive(false);+ if (uploadInFlight.current) {+ toast.error("An upload is already running. Wait for it to finish, then drop again.");+ return;+ }+ let dropped: File[];+ // held across the walk too: a big tree takes seconds, and every control is live until then.+ uploadInFlight.current = true;+ setUploading(true);+ try {+ dropped = await filesFromDataTransfer(event.dataTransfer);+ } catch {+ toast.error(+ "Could not read every file in that folder, so nothing was uploaded. Try the folder " ++ "button instead.",+ );+ return;+ } finally {+ // uploadTo re-takes it synchronously below, so no await sits in the gap.+ uploadInFlight.current = false;+ setUploading(false);+ }+ if (dropped.length === 0) {+ toast.error("That drop had no files in it.");+ return;+ }+ await uploadTo(dropTarget, dropped);+ },+ [dropTarget, uploadTo],);const onStart = useCallback(async () => {@@ -1202,7 +1453,29 @@ export function DiffusionTrainPanel({</div>{/* Dataset */}- <div className={fieldClass}>+ {/* the whole field is the drop zone, so a folder can land on the picker, the thumbnails or the caption grid. */}+ <div+ className={cn(+ fieldClass,+ "rounded-lg transition-colors",+ dropActive && "outline-2 outline-dashed outline-offset-4 outline-primary/60",+ )}+ onDragOver={(e) => {+ // tauri consumes os drags before the webview, as the chat composer notes.+ if (isTauri) return;+ // files only: without this a text-selection drag also arms the zone.+ if (!e.dataTransfer.types.includes("Files")) return;+ e.preventDefault();+ setDropActive(true);+ }}+ onDragLeave={(e) => {+ // dragging onto a child fires leave on the parent, so ignore inner moves.+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {+ setDropActive(false);+ }+ }}+ onDrop={(e) => void onDrop(e)}+ ><FieldLabel hint="The set the LoRA learns from. 10-50 images is plenty, and captions are optional.">Training images</FieldLabel>@@ -1270,9 +1543,24 @@ export function DiffusionTrainPanel({<HugeiconsIcon icon={Upload01Icon} className="size-3.5" />{uploading ? "Uploading..." : "Add"}</Button>+ <FolderPickButton disabled={uploading} onPick={() => pickFolder(dataset)} /></>)}</div>+ {/* a folder pick carries the whole tree, so an images-plus-captions set arrives paired in one go. */}+ <input+ ref={folderInputRef}+ type="file"+ multiple+ {...({ webkitdirectory: "", directory: "" } as object)}+ className="hidden"+ aria-label="Training image folder"+ onChange={(e) => {+ const files = Array.from(e.target.files ?? []);+ e.target.value = "";+ void uploadTo(folderTarget.current, files);+ }}+ />{importingId && (<p className="text-ui-11 text-muted-foreground">Importing {examples.find((e) => e.id === importingId)?.label ?? "example"}...@@ -1325,7 +1613,22 @@ export function DiffusionTrainPanel({<HugeiconsIcon icon={Upload01Icon} className="size-3.5" />{uploading ? "Uploading..." : "Upload"}</Button>+ <FolderPickButton+ disabled={uploading}+ onPick={() => {+ if (!uploadName.trim()) {+ toast.error("Give the dataset a folder name, e.g. my-style-photos.");+ return;+ }+ pickFolder(uploadName.trim());+ }}+ /></div>+ <p className="text-ui-11 leading-snug text-muted-foreground">+ {isTauri ? "Pick files or a folder." : "Pick files or a folder, or drop them here."}{" "}+ A caption file beside an image (cat.png and cat.txt) is read as that image's+ caption.+ </p></div>) : (selectedDataset && (diff --git a/studio/frontend/src/features/settings/api/upload-limit.ts b/studio/frontend/src/features/settings/api/upload-limit.tsindex 2ef0458286b..be13120f767 100644--- a/studio/frontend/src/features/settings/api/upload-limit.ts+++ b/studio/frontend/src/features/settings/api/upload-limit.ts@@ -87,8 +87,11 @@ async function fetchUploadLimitSettings(): Promise<UploadLimitSettings> {return fromApi(await res.json());}-export async function loadUploadLimitSettings() {- if (cachedUploadLimit) {+/** The cached limit, fetching it once if needed. `force` refetches instead of reading the+ * cache, for a caller that must agree with the server rather than merely show a number: the+ * setting can be changed from another tab or process, which no event here reaches. */+export async function loadUploadLimitSettings({ force = false } = {}) {+ if (cachedUploadLimit && !force) {return cachedUploadLimit;}inFlightUploadLimit ??= fetchUploadLimitSettings()diff --git a/studio/frontend/tests/dataset-file-selection.test.ts b/studio/frontend/tests/dataset-file-selection.test.tsnew file mode 100644index 00000000000..e75a3d75197--- /dev/null+++ b/studio/frontend/tests/dataset-file-selection.test.ts@@ -0,0 +1,424 @@+// 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 { readFile } from "node:fs/promises";+import test from "node:test";++import {+ DATASET_IMAGE_EXTS,+ DATASET_TEXT_EXTS,+ chunkDatasetUpload,+ existingStemClash,+ filesFromDataTransfer,+ metadataKeyedOnSubfolders,+ oversizedChunk,+ selectDatasetFiles,+} from "../src/features/images/train/dataset-files.ts";++/** a picked file of a given byte size. chunking reads only `size`, so the payload is stubbed:+ * materializing it made these cases allocate over a gigabyte between them. */+function sized(name: string, bytes: number): File {+ const file = new File([], name);+ Object.defineProperty(file, "size", { value: bytes });+ return file;+}++/** a picked file; `path` stands in for the webkitRelativePath a folder pick carries. */+function picked(name: string, path?: string): File {+ const file = new File(["x"], name);+ if (path !== undefined) {+ Object.defineProperty(file, "webkitRelativePath", { value: path });+ }+ return file;+}++test("accepts exactly the extensions the backend accepts", async () => {+ const source = await readFile(+ new URL("../../backend/routes/training.py", import.meta.url),+ "utf8",+ );+ const literals = (name: string) => {+ const match = new RegExp(`${name}\\s*=\\s*\\{([^}]+)\\}`).exec(source);+ assert.ok(match, `${name} not found in training.py`);+ return [...match[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]).sort();+ };++ // .caption sidecars and metadata/captions .jsonl are older caption formats the trainer+ // still reads, so a backend that widens either list must widen the picker with it.+ assert.deepEqual([...DATASET_IMAGE_EXTS].sort(), literals("_DIFFUSION_DATASET_IMAGE_EXTS"));+ assert.deepEqual([...DATASET_TEXT_EXTS].sort(), literals("_DIFFUSION_DATASET_TEXT_EXTS"));+});++test("keeps images alongside the caption files paired to them", () => {+ const result = selectDatasetFiles([+ picked("cat.png"),+ picked("cat.txt"),+ picked("dog.JPEG"),+ picked("dog.caption"),+ picked("metadata.jsonl"),+ ]);++ assert.equal(result.files.length, 5);+ assert.equal(result.imageCount, 2);+ assert.equal(result.captionCount, 3);+ assert.equal(result.skipped, 0);+ assert.deepEqual(result.collisions, []);+});++test("drops files the upload endpoint would reject, and counts them", () => {+ const result = selectDatasetFiles([+ picked("cat.png"),+ picked("notes.pdf"),+ picked("clip.mp4"),+ picked("README"),+ ]);++ assert.deepEqual(result.files.map((f) => f.name), ["cat.png"]);+ assert.equal(result.skipped, 3);+});++test("reports basenames a folder pick would flatten together", () => {+ // a dataset folder is flat, so both of these would be stored as cat.png.+ const result = selectDatasetFiles([+ picked("cat.png", "set/train/cat.png"),+ picked("cat.png", "set/val/cat.png"),+ ]);++ assert.equal(result.files.length, 1);+ assert.deepEqual(result.collisions, [+ { kind: "name", first: "set/train/cat.png", second: "set/val/cat.png" },+ ]);+});++test("reports two images sharing a stem, which would share one caption sidecar", () => {+ // training.py refuses the whole batch on this; catching it here keeps the upload honest.+ const result = selectDatasetFiles([picked("cat.png"), picked("cat.jpg"), picked("cat.txt")]);++ assert.deepEqual(result.files.map((f) => f.name), ["cat.png", "cat.txt"]);+ assert.deepEqual(result.collisions, [{ kind: "stem", first: "cat.png", second: "cat.jpg" }]);+});++test("leaves case-variant names to the backend, which knows if the filesystem folds case", () => {+ // on ext4 these are two distinct files the upload accepts; refusing here would block a+ // legitimate dataset and give a reason that is false for that filesystem.+ const result = selectDatasetFiles([picked("Cat.png"), picked("cat.PNG")]);++ assert.equal(result.files.length, 2);+ assert.deepEqual(result.collisions, []);+});++test("folds case on the stem rule, which training.py applies whatever the filesystem does", () => {+ const result = selectDatasetFiles([picked("Cat.png"), picked("cat.jpg")]);++ assert.deepEqual(result.collisions, [{ kind: "stem", first: "Cat.png", second: "cat.jpg" }]);+});++test("clashes an extension-case pair of one stem spelling, as _shares_sidecar does", () => {+ // cat.png and cat.PNG share the exact stem, so both resolve to cat.txt and the backend+ // rejects them on every filesystem. Cat.png and cat.PNG differ in stem case and are exempt.+ assert.deepEqual(selectDatasetFiles([picked("cat.png"), picked("cat.PNG")]).collisions, [+ { kind: "stem", first: "cat.png", second: "cat.PNG" },+ ]);+ assert.deepEqual(selectDatasetFiles([picked("Cat.png"), picked("cat.PNG")]).collisions, []);+});++test("compares every accepted variant, since the stem exemption is not transitive", () => {+ // Cat.png exempts cat.PNG and cat.png individually, but those two share an exact stem and+ // training.py compares each new name against every earlier one.+ const result = selectDatasetFiles([picked("Cat.png"), picked("cat.PNG"), picked("cat.png")]);++ assert.deepEqual(result.collisions, [+ { kind: "stem", first: "cat.PNG", second: "cat.png" },+ ]);+});++test("skips names the upload refuses outright, before any slice is committed", () => {+ // Path(".png").suffix is empty and the endpoint rejects any name holding "..", so accepting+ // either here would commit earlier slices and then fail on a later one.+ const result = selectDatasetFiles([+ picked("cat.png"),+ picked(".png"),+ picked("photo..png"),+ ]);++ assert.deepEqual(result.files.map((f) => f.name), ["cat.png"]);+ assert.equal(result.skipped, 2);+});++test("keeps a dotfile named in the file dialog, where the user chose it deliberately", () => {+ // no webkitRelativePath means a plain multi-select, unlike a tree walk that surfaces .thumbs.+ const result = selectDatasetFiles([picked(".cover.png"), picked("cat.png")]);++ assert.deepEqual(result.files.map((f) => f.name), [".cover.png", "cat.png"]);+ assert.equal(result.skipped, 0);+});++test("ignores dot-directories, so re-picking a dataset folder skips its .thumbs cache", () => {+ const result = selectDatasetFiles([+ picked("cat.png", "my-photos/cat.png"),+ picked("cat.png_256.jpg", "my-photos/.thumbs/cat.png_256.jpg"),+ picked(".DS_Store", "my-photos/.DS_Store"),+ ]);++ assert.deepEqual(result.files.map((f) => f.name), ["cat.png"]);+ // hidden entries are not "unsupported", so they are not reported as skipped.+ assert.equal(result.skipped, 0);+ assert.deepEqual(result.collisions, []);+});++test("keeps a picked folder whose own name starts with a dot", () => {+ // webkitRelativePath is rooted at the folder the user chose, so its name is not a reason to skip.+ const result = selectDatasetFiles([+ picked("cat.png", ".photos/cat.png"),+ picked("dog.png", ".photos/nested/dog.png"),+ ]);++ assert.deepEqual(result.files.map((f) => f.name), ["cat.png", "dog.png"]);+});++test("an empty or fully rejected pick yields no files", () => {+ assert.equal(selectDatasetFiles([]).files.length, 0);+ assert.equal(selectDatasetFiles([picked("notes.pdf")]).files.length, 0);+});++// -- drop handling -------------------------------------------------------------------------++/** a FileSystemFileEntry over one File. */+function fileEntry(name: string, onFile?: () => void) {+ return {+ isFile: true,+ isDirectory: false,+ name,+ file(resolve: (f: File) => void, reject: (e: Error) => void) {+ onFile?.();+ if (name === "explode.png") reject(new Error("unreadable"));+ else resolve(new File(["x"], name));+ },+ } as unknown as FileSystemEntry;+}++/** a FileSystemDirectoryEntry whose reader hands back `children` in 100-entry batches. */+function dirEntry(name: string, children: FileSystemEntry[]) {+ return {+ isFile: false,+ isDirectory: true,+ name,+ createReader() {+ let cursor = 0;+ return {+ readEntries(resolve: (batch: FileSystemEntry[]) => void) {+ // mirrors Chrome, which never returns more than 100 entries per call.+ const batch = children.slice(cursor, cursor + 100);+ cursor += batch.length;+ resolve(batch);+ },+ };+ },+ } as unknown as FileSystemEntry;+}++function transfer(entries: FileSystemEntry[], files: File[] = []): DataTransfer {+ return {+ items: entries.map((entry) => ({ kind: "file", webkitGetAsEntry: () => entry })),+ files,+ } as unknown as DataTransfer;+}++test("reads a dropped folder past the 100-entry readEntries batch limit", async () => {+ const children = Array.from({ length: 250 }, (_, i) => fileEntry(`img_${i}.png`));+ const out = await filesFromDataTransfer(transfer([dirEntry("set", children)]));++ // a single readEntries call would stop at 100 and silently drop the rest.+ assert.equal(out.length, 250);+});++test("gives dropped files their folder path, so a collision names both sides", async () => {+ const out = await filesFromDataTransfer(+ transfer([+ dirEntry("set", [+ dirEntry("train", [fileEntry("cat.png")]),+ dirEntry("val", [fileEntry("cat.png")]),+ ]),+ ]),+ );++ assert.deepEqual(+ out.map((f) => (f as File & { webkitRelativePath?: string }).webkitRelativePath),+ ["set/train/cat.png", "set/val/cat.png"],+ );+ assert.deepEqual(selectDatasetFiles(out).collisions, [+ { kind: "name", first: "set/train/cat.png", second: "set/val/cat.png" },+ ]);+});++test("normalizes to the stored name, so a leading space is not a second destination", () => {+ // training.py stores Path(name).name.strip(), so " cat.png" and "cat.png" are one file.+ const result = selectDatasetFiles([picked(" cat.png"), picked("cat.png")]);++ assert.equal(result.files.length, 1);+ assert.equal(result.collisions.length, 1);++ // and the same normalisation groups them into one request rather than two repeat uploads.+ const chunks = chunkDatasetUpload([sized(" cat.png", 1), sized("cat.png", 1)], 1024 * 1024);+ assert.equal(chunks.length, 1);+});++test("rejects a drop whose items do not all resolve to entries", async () => {+ // a partly resolvable drop would otherwise upload a subset under an all-or-nothing contract.+ const dt = {+ items: [+ { kind: "file", webkitGetAsEntry: () => fileEntry("ok.png") },+ { kind: "file", webkitGetAsEntry: () => null },+ ],+ files: [new File(["x"], "ok.png"), new File(["x"], "ghost.png")],+ } as unknown as DataTransfer;++ await assert.rejects(filesFromDataTransfer(dt), /could not be read/);+});++test("keeps casefold-equal names in one request, which the backend can only compare there", () => {+ const files = [+ ...Array.from({ length: 499 }, (_, i) => sized(`img_${i}.png`, 1)),+ sized("Cat.png", 1),+ sized("cat.png", 1),+ ];+ const chunks = chunkDatasetUpload(files, 1024 * 1024 * 1024);++ // a plain 500-file slice would put Cat.png and cat.png in separate repeat uploads, where the+ // second silently replaces the first on a case-insensitive dataset folder.+ const holding = chunks.filter((c) => c.some((f) => f.name.toLowerCase() === "cat.png"));+ assert.equal(holding.length, 1);+ assert.equal(holding[0].filter((f) => f.name.toLowerCase() === "cat.png").length, 2);+ for (const chunk of chunks) assert.ok(chunk.length <= 500 + 1);+});++test("splits on the byte cap too, not only the part count", () => {+ const mb = 1024 * 1024;+ const files = Array.from({ length: 300 }, (_, i) => sized(`img_${i}.png`, 2 * mb));+ const chunks = chunkDatasetUpload(files, 500 * mb);++ assert.ok(chunks.length > 1, "600MB under the part cap must still be split");+ for (const chunk of chunks) {+ assert.ok(chunk.reduce((n, f) => n + f.size, 0) <= 500 * mb);+ }+ assert.equal(chunks.flat().length, 300);+});++test("strips what Python strips, so a name the endpoint refuses is not read as accepted", () => {+ // trim() also removes U+FEFF, which str.strip() keeps: the part carries "cat.png" and+ // the endpoint reads its suffix as ".png", so the client must not see a plain image.+ const bom = selectDatasetFiles([picked("cat.png\ufeff")]);+ assert.deepEqual(bom.files, []);+ assert.equal(bom.skipped, 1);++ // ...and the other direction: str.strip() removes these, trim() does not, so the endpoint+ // stores a plain "cat.png" and the client must not drop the file as unsupported.+ for (const ch of ["\u001c", "\u001d", "\u001e", "\u001f", "\u0085"]) {+ const sel = selectDatasetFiles([picked(`cat.png${ch}`)]);+ assert.equal(sel.imageCount, 1, `U+${ch.codePointAt(0)?.toString(16)} must be stripped`);+ assert.equal(sel.skipped, 0);+ }++ // ordinary whitespace both agree on, still folded onto one destination+ assert.equal(selectDatasetFiles([picked(" cat.png\t")]).imageCount, 1);+});++test("sends case-variant groups first, so their refusal lands before anything commits", () => {+ const mb = 1024 * 1024;+ const files = [+ ...Array.from({ length: 499 }, (_, i) => sized(`img_${i}.png`, mb)),+ sized("Cat.png", mb),+ sized("cat.png", mb),+ ];+ const chunks = chunkDatasetUpload(files, 500 * mb);++ // a case-insensitive dataset folder refuses the pair, so it must ride in the first request:+ // refused there, nothing has been committed. Keeping it whole is what lets the backend+ // compare both names at all.+ assert.deepEqual(+ chunks[0].slice(0, 2).map((f) => f.name),+ ["Cat.png", "cat.png"],+ "the case-variant group must lead the first chunk",+ );+ assert.ok(chunks.length > 1, "501 files must still split on the part cap");+ assert.equal(chunks.flat().length, 501);+ assert.equal(new Set(chunks.flat()).size, 501);+});++test("names a chunk no split can fit, so the slices before it are never committed", () => {+ const mb = 1024 * 1024;+ const files = [+ ...Array.from({ length: 20 }, (_, i) => sized(`img_${i}.png`, 2 * mb)),+ sized("huge.png", 600 * mb),+ ];+ const chunks = chunkDatasetUpload(files, 500 * mb);++ assert.deepEqual(+ chunks.map((c) => c.length),+ [20, 1],+ "the oversized file must sit in a slice the endpoint would 413",+ );+ assert.equal(oversizedChunk(chunks, 500 * mb), "huge.png");+ assert.equal(oversizedChunk(chunks.slice(0, 1), 500 * mb), null);+});++test("reports a stem the dataset folder already holds, which a split top-up would 400", () => {+ const held = ["cat.png", "dog.png"];++ assert.deepEqual(existingStemClash([picked("cat.jpg", "top-up/cat.jpg")], held), {+ kind: "stem",+ first: "cat.png",+ second: "top-up/cat.jpg",+ });+ // a repeat upload of the same name is how the endpoint accumulates, so it must stay allowed+ assert.equal(existingStemClash([picked("cat.png")], held), null);+ // an exact stem match still clashes, extension case notwithstanding+ assert.equal(existingStemClash([picked("cat.PNG")], held)?.first, "cat.png");+ // only a differing stem case is exempt, which is where _shares_sidecar stops+ assert.equal(existingStemClash([picked("Cat.png")], held), null);+ // a caption never shares a sidecar with an image+ assert.equal(existingStemClash([picked("cat.txt")], held), null);+ assert.equal(existingStemClash([picked("bird.png")], held), null);+});++test("flags metadata keyed on a subfolder, which flattening would silently unmatch", async () => {+ const meta = new File(+ ['{"file_name": "images/001.png", "text": "a cat"}\n{"file_name": "images/002.png"}\n'],+ "metadata.jsonl",+ );+ assert.equal(await metadataKeyedOnSubfolders([meta]), "metadata.jsonl");++ const flat = new File(['{"file_name": "001.png", "text": "a cat"}\n'], "metadata.jsonl");+ assert.equal(await metadataKeyedOnSubfolders([flat]), null);++ // metadata written on windows keys rows with a backslash+ const win = new File(['{"file_name": "images\\\\001.png"}\n'], "metadata.jsonl");+ assert.equal(await metadataKeyedOnSubfolders([win]), "metadata.jsonl");++ // _load_metadata_captions falls back on the first TRUTHY key, so an empty file_name defers+ const blank = new File(+ ['{"file_name": "", "image": "images/001.png"}\n'],+ "metadata.jsonl",+ );+ assert.equal(await metadataKeyedOnSubfolders([blank]), "metadata.jsonl");+});++test("refuses a partly read folder instead of uploading it as complete", async () => {+ await assert.rejects(+ filesFromDataTransfer(+ transfer([dirEntry("set", [fileEntry("ok.png"), fileEntry("explode.png")])], []),+ ),+ /unreadable/,+ );+});++test("uses the flat list when the entries API is unavailable", async () => {+ const flat = [new File(["x"], "a.png"), new File(["x"], "b.png")];+ const out = await filesFromDataTransfer({+ items: [{ kind: "file", webkitGetAsEntry: () => null }],+ files: flat,+ } as unknown as DataTransfer);++ assert.deepEqual(out.map((f) => f.name), ["a.png", "b.png"]);+});