Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: drag and drop files onto project sources and knowledge bases (#9147)
Maheswar Kumaraa738801ad85
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 04e8378f7d2..0b99c7381e3 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -15487,9 +15487,7 @@ class LlamaCppBackend:# explicit request counts at all: the estimator has always charged 0,# and adopting llama.cpp's default of 32 would move the fit for every# model.- _effective_ctx_checkpoints = resolve_ctx_checkpoints(- extra_args, ctx_checkpoints- )+ _effective_ctx_checkpoints = resolve_ctx_checkpoints(extra_args, ctx_checkpoints)# --embedding forces n_batch = n_ubatch, which aborts a load below the slots.if (self.is_embedding_gguf@@ -16209,9 +16207,7 @@ class LlamaCppBackend:# The control underneath them: emitted before the extras, so an# extra still last-wins and the reserve prices what will run._budget_draft_cache = (- spec_draft_cache_type.strip().lower()- if spec_draft_cache_type- else None+ spec_draft_cache_type.strip().lower() if spec_draft_cache_type else None)if _budget_draft_cache in _VALID_KV_CACHE_TYPES:_mtp_draft_ck = _mtp_draft_ck or _budget_draft_cachediff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex bbdc21845e3..c56db0af214 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -721,9 +721,7 @@ def parse_ctx_checkpoints_override(args: Optional[Iterable[str]]) -> Optional[inreturn max(0, parsed)-def resolve_ctx_checkpoints(- args: Optional[Iterable[str]], requested: Optional[int]-) -> int:+def resolve_ctx_checkpoints(args: Optional[Iterable[str]], requested: Optional[int]) -> int:"""The checkpoint count the launch will actually run: extras beat the field."""override = parse_ctx_checkpoints_override(args)return int(override if override is not None else (requested or 0))diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 5cfcbc33ac7..ab3475ac9f6 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1561,7 +1561,11 @@ def _openai_llama_admission_media_tokens(payload) -> int:def _openai_llama_admission_tokens(- payload, *, budget: Optional[int], capacity: int, tool_loop: bool = False+ payload,+ *,+ budget: Optional[int],+ capacity: int,+ tool_loop: bool = False,) -> Optional[int]:"""KV a request will occupy: what is sent, plus what it may generate.diff --git a/studio/backend/tests/test_llama_admission_kv_budget.py b/studio/backend/tests/test_llama_admission_kv_budget.pyindex 81208daa08f..64cdfc2a5c3 100644--- a/studio/backend/tests/test_llama_admission_kv_budget.py+++ b/studio/backend/tests/test_llama_admission_kv_budget.py@@ -474,6 +474,7 @@ class TestToolLoopsReserveTheirUpperBound:``enable_tools``, ``mcp_enabled``, the CLI policy and a checkpoint repair,none of which carry a client catalogue."""from types import SimpleNamespace+payload = SimpleNamespace(messages = [{"role": "user", "content": "hi"}],max_tokens = 16,@@ -524,6 +525,7 @@ class TestToolLoopsReserveTheirUpperBound:"""The passthrough and streaming /v1/responses run ONE generation per HTTPcall; the client sends the next round itself, with its own reservation."""from types import SimpleNamespace+payload = SimpleNamespace(messages = [{"role": "user", "content": "hi"}],max_tokens = 16,diff --git a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.pyindex 78ce39f10da..70bea0bedde 100644--- a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py+++ b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py@@ -81,9 +81,7 @@ class TestMediaIsCharged:capacity = 4,config = config,budget = 2048,- tokens = _openai_llama_admission_tokens(- payload, budget = 2048, capacity = 4- ),+ tokens = _openai_llama_admission_tokens(payload, budget = 2048, capacity = 4),)leases.append(reservation.lease_nowait())return leases@@ -116,10 +114,7 @@ class TestTheToolLoopReservesTheWholeCache:)assert getattr(payload, "tools", None) is Noneassert (- _openai_llama_admission_tokens(- payload, budget = 4096, capacity = 4, tool_loop = True- )- == 4096+ _openai_llama_admission_tokens(payload, budget = 4096, capacity = 4, tool_loop = True) == 4096)def test_a_passthrough_forwarding_tools_is_charged_its_own_round(self):@@ -149,7 +144,6 @@ class TestTheBudgetIsTheWholeCacheNotOneSlot:def test_the_partitioned_total_wins_over_one_slot(self):from routes.inference import _openai_llama_admission_budget-backend = _Payload(context_length = 4096, _kv_cache_context_total = 16384)assert _openai_llama_admission_budget(backend) == 16384@@ -169,5 +163,4 @@ class TestTheBudgetIsTheWholeCacheNotOneSlot:def test_a_backend_that_cannot_say_keeps_slot_only_admission(self):from routes.inference import _openai_llama_admission_budget-assert _openai_llama_admission_budget(_Payload()) is Nonediff --git a/studio/backend/tests/test_web_page_cap_fits_window.py b/studio/backend/tests/test_web_page_cap_fits_window.pyindex 642d45a0908..210324bbbc2 100644--- a/studio/backend/tests/test_web_page_cap_fits_window.py+++ b/studio/backend/tests/test_web_page_cap_fits_window.py@@ -258,16 +258,19 @@ class TestADenseResultIsSizedByWhatItCosts:"""# One paragraph of CJK prose with the wiki-style escaped links that come with it.- _CJK_PAGE = ("人工智能是一门研究如何使机器具备智能行为的学科,"- "涵盖[机器学习](/wiki/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0)、"- "[语言处理](/wiki/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86)"- "和[电脑视觉](/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89)。") * 200- _EN_PAGE = ("Artificial intelligence is the study of machines that perceive their "- "environment and take actions that maximise the chance of a goal. ") * 200+ _CJK_PAGE = (+ "人工智能是一门研究如何使机器具备智能行为的学科,"+ "涵盖[机器学习](/wiki/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0)、"+ "[语言处理](/wiki/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86)"+ "和[电脑视觉](/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%A7%86%E8%A7%89)。"+ ) * 200+ _EN_PAGE = (+ "Artificial intelligence is the study of machines that perceive their "+ "environment and take actions that maximise the chance of a goal. "+ ) * 200def _dense_tokens(self, text):from core.inference.context_window import estimate_messages_tokens_dense-return estimate_messages_tokens_dense([{"role": "tool", "content": text}])def test_a_cjk_page_is_cut_to_the_share_it_was_promised(self, monkeypatch):@@ -314,7 +317,9 @@ class TestADenseResultIsSizedByWhatItCosts:def test_an_unknown_window_leaves_a_dense_page_alone(self):"""Same rule as the char budget: not knowing must never shrink a fetch."""- assert tools._dense_char_limit(self._CJK_PAGE, tools._MAX_PAGE_CHARS) == tools._MAX_PAGE_CHARS+ assert (+ tools._dense_char_limit(self._CJK_PAGE, tools._MAX_PAGE_CHARS) == tools._MAX_PAGE_CHARS+ )def test_a_dense_terminal_result_is_sized_too(self, monkeypatch):"""The code tools print CJK and escaped URLs as readily as a page carries them."""diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex e6a33aa9d96..47ef9ffbcf0 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -2185,6 +2185,16 @@ const PendingAudioChip: FC = () => {);};+/** Keep a drop on a portaled child, such as a dialog or its overlay, from also+ * attaching to the composer. React routes portal events through the composer,+ * whose dropzone attaches in the capture phase before the dialog sees them. */+function claimPortaledDrop(event: ReactDragEvent): void {+ const target = event.target as Element | null;+ if (!target?.closest?.(".aui-composer-attachment-dropzone")) {+ event.preventDefault();+ }+}+const Composer: FC<{disabled?: boolean;placeholder?: string;@@ -4492,7 +4502,12 @@ const Composer: FC<{{composerContent}</div>) : (- <ComposerPrimitive.AttachmentDropzone className="group/dropzone aui-composer-attachment-dropzone unsloth-composer-surface relative z-10">+ <ComposerPrimitive.AttachmentDropzone+ className="group/dropzone aui-composer-attachment-dropzone unsloth-composer-surface relative z-10"+ onDragEnterCapture={claimPortaledDrop}+ onDragOverCapture={claimPortaledDrop}+ onDropCapture={claimPortaledDrop}+ >{composerContent}{/* Gemini-style drop affordance, shown while a file is dragged overthe composer. Absolute + pointer-events-none so the outline addsdiff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 93913dc5aa6..af6dce9e7ae 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -156,6 +156,7 @@ import {import {type CompositionEvent,type ClipboardEvent,+ type DragEvent as ReactDragEvent,type FC,type KeyboardEvent,type MutableRefObject,@@ -512,6 +513,13 @@ function PillGlyph({ children }: { children: ReactNode }) {);}+/** True when a drop reached this composer from a portaled child, such as a+ * dialog and its overlay, which React routes through here but which owns it. */+function isPortaledDrop(event: ReactDragEvent): boolean {+ const target = event.target as Element | null;+ return !target?.closest?.(".chat-composer-surface");+}+export function SharedComposer({handlesRef,model1,@@ -2047,7 +2055,7 @@ export function SharedComposer({<divclassName="chat-composer-surface"onDragOver={(e) => {- if (isTauri) return;+ if (isTauri || isPortaledDrop(e)) return;e.preventDefault();setDragging(true);}}@@ -2055,7 +2063,7 @@ export function SharedComposer({onDrop={(e) => {// Phase 1 native model drops own Tauri local-path drops. Restore// browser attachment drops in Tauri once Phase 1d adds token bridging.- if (isTauri) return;+ if (isTauri || isPortaledDrop(e)) return;e.preventDefault();setDragging(false);addFiles(e.dataTransfer.files);diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.tsindex 0b0b9a04421..c6308d2f259 100644--- a/studio/frontend/src/features/native-intents/drop-paths.ts+++ b/studio/frontend/src/features/native-intents/drop-paths.ts@@ -25,6 +25,12 @@ const VIDEO_EXTS = CHAT_VIDEO_DROP_ACCEPT.split(",").map((ext) => ext.trim().toL/** What the window actually takes, for the rejection toast and the overlay. */export const SUPPORTED_DROP_HINT = `Supported files: ${RAG_UPLOAD_ACCEPT}, ${CHAT_IMAGE_DROP_ACCEPT}, one of ${CHAT_AUDIO_DROP_ACCEPT}, one of ${CHAT_VIDEO_DROP_ACCEPT}, or a single .gguf model.`;+/** Last path segment of a native path, for display and extension checks. */+export function nativeFileName(path: string): string {+ const segments = path.split(/[\\/]/);+ return segments[segments.length - 1] || path;+}+function hasExt(path: string, ext: string): boolean {return path.toLowerCase().endsWith(ext);}diff --git a/studio/frontend/src/features/native-intents/index.ts b/studio/frontend/src/features/native-intents/index.tsindex 026fce3d9b3..0aa8746010b 100644--- a/studio/frontend/src/features/native-intents/index.ts+++ b/studio/frontend/src/features/native-intents/index.ts@@ -13,6 +13,7 @@ export {registerNativeDatasetPath,} from "./api";export type { NativeDocumentFolderSelection } from "./api";+export { nativeFileName } from "./drop-paths";export { nativeDropTargetAt } from "./native-drop-targets";export { nativeAttachmentIntentToFile } from "./native-attachment-file";export { useNativeDropTarget } from "./use-native-drop-target";diff --git a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsxindex 23082ca64c4..6be88320352 100644--- a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx+++ b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx@@ -33,6 +33,7 @@ import { Label } from "@/components/ui/label";import { Spinner } from "@/components/ui/spinner";import { Textarea } from "@/components/ui/textarea";import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";import {createKnowledgeBase,@@ -50,6 +51,7 @@ import {import { DocumentStatusChip } from "./document-status-chip";import { LinkedFoldersManager } from "./linked-folders-manager";import { useRagDocuments } from "./use-rag-documents";+import { useSourceDrop } from "./use-source-drop";type View =| { kind: "list" }@@ -342,9 +344,21 @@ function KnowledgeBaseDocuments({const handleLinkedSourcesChanged = useCallback(() => {void refresh({ quiet: true });}, [refresh]);+ const { dragging, dropProps, nativeDropTarget } = useSourceDrop({+ onItems: (items) => void upload(items),+ // upload() tracks one run at a time, so a second batch would clear the+ // in-flight guard the first one is still relying on.+ disabledReason: uploading+ ? "An upload is already running. Add these when it finishes."+ : undefined,+ });return (- <div className="flex min-w-0 flex-col gap-3">+ <div+ className="flex min-w-0 flex-col gap-3"+ ref={nativeDropTarget}+ {...dropProps}+ ><div className="flex items-center justify-between"><Button variant="ghost" size="sm" onClick={onBack}><ChevronLeftIcon className="size-4" />@@ -375,11 +389,22 @@ function KnowledgeBaseDocuments({<Spinner /></div>) : documents.length === 0 ? (- <div className="rounded-md border border-dashed py-6 text-center text-sm text-muted-foreground">- No documents yet. Upload a PDF, Markdown, DOCX, HTML, or text file.+ <div+ className={cn(+ "rounded-md border border-dashed py-6 text-center text-sm text-muted-foreground transition-colors",+ dragging && "border-primary/60 bg-primary/5 text-foreground",+ )}+ >+ No documents yet. Upload or drop a PDF, Markdown, DOCX, HTML, or text+ file.</div>) : (- <div className="flex max-h-[55dvh] flex-wrap gap-1.5 overflow-y-auto pr-0.5">+ <div+ className={cn(+ "flex max-h-[55dvh] flex-wrap gap-1.5 overflow-y-auto rounded-md pr-0.5 transition-colors",+ dragging && "bg-primary/5 ring-1 ring-primary/60",+ )}+ >{documents.map((doc) => (<DocumentStatusChipkey={doc.id}diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsxindex a291a9a96ea..2c87db30cee 100644--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx@@ -3,6 +3,7 @@import {consumeNativePathToken,+ nativeFileName,registerNativeAttachmentPath,useNativeDropTarget,} from "@/features/native-intents";@@ -19,6 +20,7 @@ import {uploadProjectDocument,} from "../api/rag-api";import { RAG_UPLOAD_ACCEPT } from "../types/rag";+import { partitionSupported } from "./source-drop-policy";import {addStagedSources,EXPIRY_GRACE_MS,@@ -32,11 +34,6 @@ import { resolveVisionOverrides } from "./vision-overrides";export type { StagedSource };-function nativeFileName(path: string): string {- const segments = path.split(/[\\/]/);- return segments[segments.length - 1] || path;-}-function formatSize(bytes: number): string {if (!Number.isFinite(bytes) || bytes <= 0) return "";const units = ["B", "KB", "MB", "GB"];@@ -53,19 +50,6 @@ function formatSize(bytes: number): string {return `${shown} ${units[unit]}`;}-const ACCEPTED_EXTS = new Set(- RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase()),-);--// `accept` only filters the picker, so a drop can carry anything. A folder-// arrives as an extension-less entry, which this rejects along with the types-// the backend would 400 on.-function isSupported(name: string): boolean {- const dot = name.lastIndexOf(".");- if (dot <= 0) return false;- return ACCEPTED_EXTS.has(name.slice(dot).toLowerCase());-}-// Projects created with staged files, so the landing can open on Sources.const projectsWithPendingSources = new Set<string>();@@ -267,11 +251,11 @@ export function ProjectSourceDropzone({const addFiles = useCallback((files: FileList | File[]) => {- const incoming = Array.from(files);- addSources(- incoming.filter((file) => isSupported(file.name)).map(stagedFromFile),- incoming.filter((file) => !isSupported(file.name)).map((file) => file.name),+ const { supported, unsupported } = partitionSupported(+ Array.from(files),+ (file) => file.name,);+ addSources(supported.map(stagedFromFile), unsupported);},[addSources],);@@ -279,10 +263,10 @@ export function ProjectSourceDropzone({const addNativePaths = useCallback(async (paths: string[]) => {const claimed = generation.current;- const supported = paths.filter((path) => isSupported(nativeFileName(path)));- const unsupported = paths- .filter((path) => !isSupported(nativeFileName(path)))- .map(nativeFileName);+ const { supported, unsupported } = partitionSupported(+ paths,+ nativeFileName,+ );// Per path, so one rejected file does not discard the rest of the drop.addPending(1);const settled = await Promise.allSettled(diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsxindex 65e90a98c28..25e645f1639 100644--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx@@ -17,8 +17,11 @@ import {import { RAG_UPLOAD_ACCEPT, isLinkedFolderManaged } from "../types/rag";import { DocumentStatusChip } from "./document-status-chip";import { LinkedFoldersManager } from "./linked-folders-manager";-import { fileItems, useRagDocuments } from "./use-rag-documents";-import type { RagUploadItem } from "./use-rag-documents";+import {+ type RagUploadItem,+ fileItems,+ useRagDocuments,+} from "./use-rag-documents";/** Project "Sources" tab: documents indexed for retrieval in every chat that* belongs to the project. */@@ -95,7 +98,11 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {// Tauri suppresses webview drop events, so the plain `onDrop` this panel// carried never fired on desktop: no border, file ignored (#9036).- const { ref: dropRef, dragging, dragHandlers } = useNativeFileDrop({+ const {+ ref: dropRef,+ dragging,+ dragHandlers,+ } = useNativeFileDrop({onFiles: handleFiles,onNativeIntents: handleNativeIntents,accept: RAG_UPLOAD_ACCEPT,@@ -114,7 +121,7 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {onChange={(e) => {const files = Array.from(e.target.files ?? []);e.target.value = "";- void handleFiles(files);+ void handleItems(fileItems(files));}}/><div className="mb-4 rounded-[22px] bg-muted/30 px-5 py-4">diff --git a/studio/frontend/src/features/rag/components/source-drop-policy.ts b/studio/frontend/src/features/rag/components/source-drop-policy.tsnew file mode 100644index 00000000000..8dc688c343c--- /dev/null+++ b/studio/frontend/src/features/rag/components/source-drop-policy.ts@@ -0,0 +1,20 @@+// 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 { isSupportedSourceName } from "../types/rag.ts";++/** Split a drop into what can be indexed and the names of what cannot, so the+ * caller can report the rejects instead of discarding them silently. */+export function partitionSupported<T>(+ entries: T[],+ nameOf: (entry: T) => string,+): { supported: T[]; unsupported: string[] } {+ const supported: T[] = [];+ const unsupported: string[] = [];+ for (const entry of entries) {+ const name = nameOf(entry);+ if (isSupportedSourceName(name)) supported.push(entry);+ else unsupported.push(name);+ }+ return { supported, unsupported };+}diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.tsindex 1a3d4e1d46d..bb96fde8974 100644--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts@@ -1,7 +1,10 @@// 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 { consumeNativePathToken } from "@/features/native-intents";+import {+ consumeNativePathToken,+ type NativeIntent,+} from "@/features/native-intents";import { toast } from "@/lib/toast";import { useCallback, useEffect, useRef, useState } from "react";import {@@ -49,6 +52,17 @@ export function fileItems(files: FileList | File[]): RagUploadItem[] {return Array.from(files).map((file) => ({ kind: "file" as const, file }));}+/** A registered desktop drop, addressed by path token rather than bytes. */+export function uploadItemFromIntent(intent: NativeIntent): RagUploadItem {+ return {+ kind: "native",+ token: intent.path.token,+ name: intent.displayLabel,+ sizeBytes: intent.path.sizeBytes,+ modifiedMs: intent.path.modifiedMs,+ };+}+function itemName(item: RagUploadItem): string {return item.kind === "file" ? item.file.name : item.name;}diff --git a/studio/frontend/src/features/rag/components/use-source-drop.ts b/studio/frontend/src/features/rag/components/use-source-drop.tsnew file mode 100644index 00000000000..035d5a18e9a--- /dev/null+++ b/studio/frontend/src/features/rag/components/use-source-drop.ts@@ -0,0 +1,170 @@+// 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 {+ nativeFileName,+ registerNativeAttachmentPath,+ useNativeDropTarget,+} from "@/features/native-intents";+import { toast } from "@/lib/toast";+import {+ type DragEvent as ReactDragEvent,+ useCallback,+ useRef,+ useState,+} from "react";+import { RAG_UPLOAD_ACCEPT } from "../types/rag";+import { partitionSupported } from "./source-drop-policy";+import { type RagUploadItem, uploadItemFromIntent } from "./use-rag-documents";++export interface SourceDropOptions {+ /** Receives what the drop yielded; never called with an empty list. */+ onItems: (items: RagUploadItem[]) => void;+ /** Set while the surface cannot take files, such as during an upload the+ * uploader would not keep separate from a second one. The drop is refused+ * with this message rather than started. */+ disabledReason?: string;+}++export interface SourceDropProps {+ onDragEnter: (event: ReactDragEvent) => void;+ onDragOver: (event: ReactDragEvent) => void;+ onDragLeave: (event: ReactDragEvent) => void;+ onDrop: (event: ReactDragEvent) => void;+}++export interface SourceDrop {+ dragging: boolean;+ dropProps: SourceDropProps;+ nativeDropTarget: (element: HTMLElement | null) => void;+}++function isFileDrag(event: ReactDragEvent): boolean {+ return Array.from(event.dataTransfer?.types ?? []).includes("Files");+}++/** Drop files onto a RAG surface, from the browser or from the desktop, where a+ * drop arrives as a path rather than bytes. */+export function useSourceDrop({+ onItems,+ disabledReason,+}: SourceDropOptions): SourceDrop {+ const disabled = disabledReason !== undefined;+ // A native drop registers its paths before upload() flips `uploading`, so+ // that window needs its own flag or a second drop starts a second upload.+ const registering = useRef(false);+ // Count enter/leave pairs: children fire dragleave on the parent.+ const dragDepth = useRef(0);+ const [dragging, setDragging] = useState(false);++ const reportUnsupported = useCallback((names: string[]) => {+ if (names.length === 0) return;+ toast.info(+ names.length === 1+ ? `Can't add ${names[0]}`+ : `Can't add ${names.length} files`,+ { description: `Supported types: ${RAG_UPLOAD_ACCEPT}` },+ );+ }, []);++ const addNativePaths = useCallback(+ async (paths: string[]) => {+ const { supported, unsupported } = partitionSupported(+ paths,+ nativeFileName,+ );+ reportUnsupported(unsupported);+ if (supported.length === 0) return;+ registering.current = true;+ // Per path, so one rejected file does not discard the rest of the drop.+ const settled = await Promise.allSettled(+ supported.map(registerNativeAttachmentPath),+ ).finally(() => {+ registering.current = false;+ });+ const items = settled.flatMap((result) =>+ result.status === "fulfilled"+ ? [uploadItemFromIntent(result.value)]+ : [],+ );+ const failed = settled.length - items.length;+ if (failed > 0) {+ toast.error(+ failed === 1+ ? "Couldn't add a dropped file"+ : `Couldn't add ${failed} dropped files`,+ );+ }+ if (items.length > 0) onItems(items);+ },+ [onItems, reportUnsupported],+ );++ /** Why a drop cannot be taken right now, or undefined when it can. */+ const refusal = useCallback(+ () =>+ disabledReason ??+ (registering.current+ ? "Still adding the last drop. Try again in a moment."+ : undefined),+ [disabledReason],+ );++ const nativeDropTarget = useNativeDropTarget({+ onDrop: (paths) => {+ const reason = refusal();+ if (reason !== undefined) {+ toast.info(reason);+ return;+ }+ void addNativePaths(paths);+ },+ onDragOver: (over) => setDragging(over && !disabled),+ });++ const endDrag = useCallback(() => {+ dragDepth.current = 0;+ setDragging(false);+ }, []);++ // Every drag is cancelled, not just a file one: nothing above these surfaces+ // cancels a link drop, so the browser would navigate away from Studio.+ const dropProps: SourceDropProps = {+ onDragEnter: (event) => {+ event.preventDefault();+ if (disabled || !isFileDrag(event)) return;+ dragDepth.current += 1;+ setDragging(true);+ },+ onDragOver: (event) => {+ event.preventDefault();+ if (disabled || !isFileDrag(event)) return;+ event.dataTransfer.dropEffect = "copy";+ },+ onDragLeave: (event) => {+ if (disabled || !isFileDrag(event)) return;+ dragDepth.current = Math.max(0, dragDepth.current - 1);+ if (dragDepth.current === 0) setDragging(false);+ },+ onDrop: (event) => {+ event.preventDefault();+ endDrag();+ if (!isFileDrag(event)) return;+ const reason = refusal();+ if (reason !== undefined) {+ toast.info(reason);+ return;+ }+ const { supported, unsupported } = partitionSupported(+ Array.from(event.dataTransfer.files ?? []),+ (file) => file.name,+ );+ reportUnsupported(unsupported);+ if (supported.length > 0) {+ onItems(supported.map((file) => ({ kind: "file" as const, file })));+ }+ },+ };++ return { dragging, dropProps, nativeDropTarget };+}diff --git a/studio/frontend/src/features/rag/types/rag.ts b/studio/frontend/src/features/rag/types/rag.tsindex 0ceafac9fe8..c476adf72ff 100644--- a/studio/frontend/src/features/rag/types/rag.ts+++ b/studio/frontend/src/features/rag/types/rag.ts@@ -181,3 +181,15 @@ export interface PreviewTarget {}export const RAG_UPLOAD_ACCEPT = ".pdf,.txt,.md,.markdown,.docx,.html,.htm";++const ACCEPTED_UPLOAD_EXTS = new Set(+ RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase()),+);++// `accept` only filters the picker, so a drop can carry anything, including an+// extension-less folder entry the backend would reject.+export function isSupportedSourceName(name: string): boolean {+ const dot = name.lastIndexOf(".");+ if (dot <= 0) return false;+ return ACCEPTED_UPLOAD_EXTS.has(name.slice(dot).toLowerCase());+}diff --git a/studio/frontend/tests/rag-source-drop-filter.test.ts b/studio/frontend/tests/rag-source-drop-filter.test.tsnew file mode 100644index 00000000000..a2141f161d8--- /dev/null+++ b/studio/frontend/tests/rag-source-drop-filter.test.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { partitionSupported } from "../src/features/rag/components/source-drop-policy.ts";+import {+ RAG_UPLOAD_ACCEPT,+ isSupportedSourceName,+} from "../src/features/rag/types/rag.ts";++test("every type the picker offers is accepted from a drop", () => {+ for (const ext of RAG_UPLOAD_ACCEPT.split(",")) {+ assert.equal(isSupportedSourceName(`notes${ext}`), true, ext);+ }+});++test("extensions match case-insensitively", () => {+ assert.equal(isSupportedSourceName("REPORT.PDF"), true);+ assert.equal(isSupportedSourceName("Readme.Md"), true);+});++// A dropped folder arrives as an extension-less entry, and uploading it 400s.+test("folders and unsupported types are rejected", () => {+ assert.equal(isSupportedSourceName("my-documents"), false);+ assert.equal(isSupportedSourceName("archive.zip"), false);+ assert.equal(isSupportedSourceName("model.gguf"), false);+});++// Leading dot means the whole name is the "extension"; treat it as no type.+test("dotfiles are rejected", () => {+ assert.equal(isSupportedSourceName(".md"), false);+ assert.equal(isSupportedSourceName(".gitignore"), false);+});++test("only the last extension counts", () => {+ assert.equal(isSupportedSourceName("notes.pdf.txt"), true);+ assert.equal(isSupportedSourceName("notes.txt.exe"), false);+});++// A drop carries whatever the user grabbed, so both halves have to survive the+// split: the indexable files to upload, the rest to name in the toast.+test("a mixed drop keeps the indexable files and names the rest", () => {+ const { supported, unsupported } = partitionSupported(+ ["notes.pdf", "photo.png", "readme.md", "archive.zip"],+ (name) => name,+ );+ assert.deepEqual(supported, ["notes.pdf", "readme.md"]);+ assert.deepEqual(unsupported, ["photo.png", "archive.zip"]);+});++test("the split reports names, not the entries it was given", () => {+ const { supported, unsupported } = partitionSupported(+ [{ path: "/tmp/a.pdf" }, { path: "/tmp/b.png" }],+ (entry) => entry.path,+ );+ assert.deepEqual(supported, [{ path: "/tmp/a.pdf" }]);+ assert.deepEqual(unsupported, ["/tmp/b.png"]);+});++test("an empty drop yields nothing to upload and nothing to report", () => {+ const { supported, unsupported } = partitionSupported(+ [],+ (name: string) => name,+ );+ assert.equal(supported.length, 0);+ assert.equal(unsupported.length, 0);+});diff --git a/tests/studio/test_ui_scripts_report_signals.py b/tests/studio/test_ui_scripts_report_signals.pyindex c89a6b67dc5..cf204dc3d98 100644--- a/tests/studio/test_ui_scripts_report_signals.py+++ b/tests/studio/test_ui_scripts_report_signals.py@@ -85,9 +85,9 @@ def test_the_snapshot_does_not_print_command_lines(script: str) -> None:"""body = _body(script)assert "pid,ppid,comm" in body, f"{script}'s process snapshot is not limited to names"- assert not re.search(r"ps\s+-o\s+[\w,]*args", body), (- f"{script} snapshots full command lines into a public log"- )+ assert not re.search(+ r"ps\s+-o\s+[\w,]*args", body+ ), f"{script} snapshots full command lines into a public log"def test_the_guard_reads_real_files() -> None: