Skip to content

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.

Desktop: drop documents into a chat instead of rejecting them as non-GGUF (#7661) (#7668)

Leo Borcherding21074d3aa51f
diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.py
index ae657121469..b078261cb22 100644
--- a/studio/backend/routes/rag.py
+++ b/studio/backend/routes/rag.py
@@ -57,9 +57,8 @@ def _sanitize_filename(name: str) -> str:
return stem[: 200 - len(ext)] + ext
-def _save_upload(file: UploadFile) -> tuple[str, str]:
- """Persist an upload; returns (stored_path, filename)."""
- filename = _sanitize_filename(file.filename or "document")
+def _persist_upload_stream(source, filename: str, *, empty_detail: str) -> tuple[str, str]:
+ """Copy a validated document stream into the managed uploads root."""
ext = os.path.splitext(filename)[1].lower()
if ext not in config.UPLOAD_EXTS:
raise HTTPException(
@@ -70,29 +69,82 @@ def _save_upload(file: UploadFile) -> tuple[str, str]:
stored_path = str(uploads / f"{uuid.uuid4().hex}{ext}")
size = 0
cap = config.MAX_UPLOAD_BYTES
- too_big = False
- with open(stored_path, "wb") as out:
- while True:
- block = file.file.read(1 << 20)
- if not block:
- break
- size += len(block)
- if cap and size > cap:
- too_big = True
- break
- out.write(block)
- if too_big:
- os.remove(stored_path)
+ try:
+ with open(stored_path, "wb") as out:
+ while True:
+ block = source.read(1 << 20)
+ if not block:
+ break
+ size += len(block)
+ if cap and size > cap:
+ break
+ out.write(block)
+ except OSError:
+ _remove_stored_upload(stored_path)
+ raise
+ if cap and size > cap:
+ _remove_stored_upload(stored_path)
raise HTTPException(
status_code = 413,
detail = f"File exceeds the {cap // (1024 * 1024)} MB upload limit.",
)
if size == 0:
- os.remove(stored_path)
- raise HTTPException(status_code = 400, detail = "Uploaded file is empty.")
+ _remove_stored_upload(stored_path)
+ raise HTTPException(status_code = 400, detail = empty_detail)
return stored_path, filename
+def _save_upload(file: UploadFile) -> tuple[str, str]:
+ """Persist a browser upload; returns (stored_path, filename)."""
+ filename = _sanitize_filename(file.filename or "document")
+ return _persist_upload_stream(
+ file.file,
+ filename,
+ empty_detail = "Uploaded file is empty.",
+ )
+
+
+def _save_native_path_upload(lease: str) -> tuple[str, str]:
+ """Persist a desktop drop; returns (stored_path, filename).
+
+ The webview never gets to name a path directly: Rust signs the path it saw and we
+ re-verify + re-stat that grant here before reading a byte.
+ """
+ from utils.native_path_leases import NativePathLeaseError, verify_native_path_lease
+
+ try:
+ grant = verify_native_path_lease(
+ lease,
+ operation = "attach",
+ expected_kind = "attachment",
+ expected_path_type = "file",
+ allowed_suffixes = sorted(config.UPLOAD_EXTS),
+ )
+ except NativePathLeaseError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+
+ filename = _sanitize_filename(grant.canonical_path.name)
+ try:
+ with open(grant.canonical_path, "rb") as source:
+ return _persist_upload_stream(
+ source,
+ filename,
+ empty_detail = "Dropped file is empty.",
+ )
+ except OSError as exc:
+ raise HTTPException(status_code = 400, detail = "Dropped file could not be read.") from exc
+
+
+def _resolve_document_upload(
+ file: UploadFile | None, native_path_lease: str | None
+) -> tuple[str, str]:
+ if native_path_lease:
+ return _save_native_path_upload(native_path_lease)
+ if file is None:
+ raise HTTPException(status_code = 400, detail = "No file was provided.")
+ return _save_upload(file)
+
+
def _remove_stored_upload(stored_path: str | None) -> None:
"""Best-effort cleanup for files saved by _save_upload."""
if not stored_path:
@@ -224,7 +276,8 @@ def delete_knowledge_base(kb_id: str, subject: str = Depends(get_current_subject
@router.post("/knowledge-bases/{kb_id}/documents")
async def upload_kb_document(
kb_id: str,
- file: UploadFile = File(...),
+ file: UploadFile | None = File(None),
+ native_path_lease: str | None = Form(None, alias = "nativePathLease"),
ocr: bool | None = Form(None),
caption: bool | None = Form(None),
subject: str = Depends(get_current_subject),
@@ -236,7 +289,7 @@ async def upload_kb_document(
raise HTTPException(status_code = 404, detail = "Knowledge base not found")
finally:
conn.close()
- stored_path, filename = _save_upload(file)
+ stored_path, filename = _resolve_document_upload(file, native_path_lease)
document_id, job_id = ingestion.start_ingestion(
store.kb_scope(kb_id), kb_id, None, filename, stored_path, ocr = ocr, caption = caption
)
@@ -257,13 +310,14 @@ def list_kb_documents(kb_id: str, subject: str = Depends(get_current_subject)) -
@router.post("/threads/{thread_id}/documents")
async def upload_thread_document(
thread_id: str,
- file: UploadFile = File(...),
+ file: UploadFile | None = File(None),
+ native_path_lease: str | None = Form(None, alias = "nativePathLease"),
ocr: bool | None = Form(None),
caption: bool | None = Form(None),
subject: str = Depends(get_current_subject),
) -> dict:
_require_rag()
- stored_path, filename = _save_upload(file)
+ stored_path, filename = _resolve_document_upload(file, native_path_lease)
document_id, job_id = ingestion.start_ingestion(
store.thread_scope(thread_id),
None,
@@ -290,7 +344,8 @@ def list_thread_documents(thread_id: str, subject: str = Depends(get_current_sub
@router.post("/projects/{project_id}/documents")
async def upload_project_document(
project_id: str,
- file: UploadFile = File(...),
+ file: UploadFile | None = File(None),
+ native_path_lease: str | None = Form(None, alias = "nativePathLease"),
ocr: bool | None = Form(None),
caption: bool | None = Form(None),
subject: str = Depends(get_current_subject),
@@ -300,7 +355,7 @@ async def upload_project_document(
if get_chat_project(project_id) is None:
raise HTTPException(status_code = 404, detail = "Project not found")
- stored_path, filename = _save_upload(file)
+ stored_path, filename = _resolve_document_upload(file, native_path_lease)
document_id, job_id = ingestion.start_ingestion(
store.project_scope(project_id),
None,
diff --git a/studio/backend/tests/test_rag_native_drop_upload.py b/studio/backend/tests/test_rag_native_drop_upload.py
new file mode 100644
index 00000000000..7e78401c47b
--- /dev/null
+++ b/studio/backend/tests/test_rag_native_drop_upload.py
@@ -0,0 +1,147 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Desktop drops reach the RAG ingest through a signed native path grant (#7661)."""
+
+import base64
+import hashlib
+import hmac
+import json
+import os
+import time
+
+import pytest
+from fastapi import HTTPException
+
+from core.rag import config
+import utils.native_path_leases as leases
+from routes.rag import _resolve_document_upload, _save_native_path_upload
+from utils.paths import rag_uploads_root
+
+SECRET = b"n" * 32
+
+
[email protected](autouse = True)
+def _lease_secret(monkeypatch):
+ monkeypatch.setenv(
+ leases.LEASE_SECRET_ENV,
+ base64.urlsafe_b64encode(SECRET).decode("ascii").rstrip("="),
+ )
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)
+ yield
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def _sign(
+ path,
+ *,
+ operation = "attach",
+ path_kind = "attachment",
+ nonce = None,
+ secret = SECRET,
+):
+ """Mint the grant Rust would sign for a dropped file."""
+ st = os.stat(path)
+ now_ms = int(time.time() * 1000)
+ payload = {
+ "version": 1,
+ "operation": operation,
+ "canonical_path": str(path),
+ "path_kind": path_kind,
+ "path_type": "file",
+ "source_kind": "drop",
+ "token_id_hash": hashlib.sha256(b"path_token").hexdigest(),
+ "issued_at_ms": now_ms,
+ "expires_at_ms": now_ms + 120_000,
+ "nonce": nonce or os.urandom(16).hex(),
+ "display_label": os.path.basename(path),
+ "size_bytes": st.st_size,
+ "modified_ms": int(st.st_mtime_ns // 1_000_000),
+ }
+ payload_b64 = _b64(json.dumps(payload).encode("utf-8"))
+ signature = hmac.new(secret, payload_b64.encode("ascii"), hashlib.sha256).digest()
+ return f"{payload_b64}.{_b64(signature)}"
+
+
+def _doc(
+ tmp_path,
+ name = "notes.txt",
+ body = "alpha bravo charlie",
+):
+ path = tmp_path / name
+ path.write_text(body, encoding = "utf-8")
+ return path
+
+
+def test_signed_drop_is_copied_into_the_uploads_root(rag_home, tmp_path):
+ source = _doc(tmp_path)
+ stored_path, filename = _save_native_path_upload(_sign(source))
+
+ assert filename == "notes.txt"
+ # Copied, not referenced: ingestion must not read from wherever the user dragged from.
+ assert os.path.realpath(stored_path) != os.path.realpath(source)
+ with open(stored_path, encoding = "utf-8") as handle:
+ assert handle.read() == "alpha bravo charlie"
+
+
+def test_forged_signature_is_rejected(rag_home, tmp_path):
+ source = _doc(tmp_path)
+ with pytest.raises(HTTPException) as excinfo:
+ _save_native_path_upload(_sign(source, secret = b"z" * 32))
+ assert excinfo.value.status_code == 400
+
+
+ "kwargs",
+ [
+ {"operation": "load-model"}, # a model grant cannot be spent as an attachment
+ {"path_kind": "model"},
+ ],
+)
+def test_grant_for_another_purpose_is_rejected(rag_home, tmp_path, kwargs):
+ source = _doc(tmp_path)
+ with pytest.raises(HTTPException):
+ _save_native_path_upload(_sign(source, **kwargs))
+
+
+def test_unsupported_extension_is_rejected(rag_home, tmp_path):
+ source = _doc(tmp_path, name = "payload.exe", body = "MZ")
+ with pytest.raises(HTTPException):
+ _save_native_path_upload(_sign(source))
+
+
+def test_empty_file_is_rejected(rag_home, tmp_path):
+ source = _doc(tmp_path, body = "")
+ with pytest.raises(HTTPException) as excinfo:
+ _save_native_path_upload(_sign(source))
+ assert excinfo.value.status_code == 400
+
+
+def test_native_drop_uses_the_shared_size_limit(rag_home, tmp_path, monkeypatch):
+ source = _doc(tmp_path, body = "x" * 4096)
+ monkeypatch.setattr(config, "MAX_UPLOAD_BYTES", 1024)
+
+ with pytest.raises(HTTPException) as excinfo:
+ _save_native_path_upload(_sign(source))
+
+ assert excinfo.value.status_code == 413
+ assert list(rag_uploads_root().glob("*.txt")) == []
+
+
+def test_grant_is_single_use(rag_home, tmp_path):
+ source = _doc(tmp_path)
+ lease = _sign(source)
+ _save_native_path_upload(lease)
+ # Replaying the same nonce must not mint a second read of the path.
+ with pytest.raises(HTTPException):
+ _save_native_path_upload(lease)
+
+
+def test_resolver_needs_one_of_file_or_lease(rag_home):
+ with pytest.raises(HTTPException) as excinfo:
+ _resolve_document_upload(None, None)
+ assert excinfo.value.status_code == 400
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 743abf45f53..80e5841f3b3 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -61,6 +61,7 @@ import {
} from "@/features/hub/download-manager";
import {
type NativeIntent,
+ NativeAttachmentTargetContext,
NativeModelChip,
NativeModelDropOverlay,
useChooseNativeModel,
@@ -2325,6 +2326,11 @@ export function ChatPage({
? `compare:${view.pairId}`
: `project:${view.projectId}`;
+ const attachmentScope =
+ view.mode === "single" && !search.thread && !search.new && !search.project
+ ? "single:implicit"
+ : artifactViewKey;
+
useEffect(() => {
clearAutoOpenedArtifacts();
closeArtifactSurface();
@@ -2564,12 +2570,22 @@ export function ChatPage({
shouldAutoLoad: canAutoLoadPickedNativeModel,
onAutoLoad: handleNativeModelPickerAutoLoad,
});
+ // Dropped documents go to the thread bar, which owns the RAG upload and can
+ // materialize a thread id for a chat that hasn't been sent to yet.
+ const handleNativeAttachmentDrop = useCallback(
+ (intents: NativeIntent[]) => {
+ useNativeIntentStore.getState().addAttachments(artifactViewKey, intents);
+ },
+ [artifactViewKey],
+ );
const nativeModelDropState = useNativeModelDrop({
enabled: active && view.mode === "single",
+ attachmentScope,
nativePathLeasesSupported,
hasActiveModel,
isModelLoading: Boolean(loadingModel) || modelLoading,
onAutoLoad: handleNativeModelDropAutoLoad,
+ onAttach: handleNativeAttachmentDrop,
});
const handleCheckpointChange = useCallback(
@@ -3459,15 +3475,17 @@ export function ChatPage({
// alive thread's runtime mounted) instead of remounting the provider and cutting
// it off; returning to that thread reattaches the live run rather than reloading
// a half-saved one.
- <SingleContent
- key={view.projectId ?? "single"}
- threadId={view.threadId}
- newThreadNonce={view.newThreadNonce}
- projectId={view.projectId}
- artifact={selectedArtifact}
- artifactSurface={artifactSurface}
- onCloseArtifact={closeArtifactSurface}
- />
+ <NativeAttachmentTargetContext.Provider value={artifactViewKey}>
+ <SingleContent
+ key={view.projectId ?? "single"}
+ threadId={view.threadId}
+ newThreadNonce={view.newThreadNonce}
+ projectId={view.projectId}
+ artifact={selectedArtifact}
+ artifactSurface={artifactSurface}
+ onCloseArtifact={closeArtifactSurface}
+ />
+ </NativeAttachmentTargetContext.Provider>
) : (
<CompareContent
key={view.pairId}
diff --git a/studio/frontend/src/features/native-intents/api.ts b/studio/frontend/src/features/native-intents/api.ts
index 98caa709b98..804c2c394d2 100644
--- a/studio/frontend/src/features/native-intents/api.ts
+++ b/studio/frontend/src/features/native-intents/api.ts
@@ -32,6 +32,10 @@ export async function registerNativeModelPath(path: string): Promise<NativeInten
return invokeNative<NativeIntent>("register_native_model_path", { path });
}
+export async function registerNativeAttachmentPath(path: string): Promise<NativeIntent> {
+ return invokeNative<NativeIntent>("register_native_attachment_path", { path });
+}
+
export async function consumeNativePathToken(
token: string,
operation: NativePathOperation,
diff --git a/studio/frontend/src/features/native-intents/attachment-queue.ts b/studio/frontend/src/features/native-intents/attachment-queue.ts
new file mode 100644
index 00000000000..4d3892c3c3d
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/attachment-queue.ts
@@ -0,0 +1,34 @@
+// 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 { NativeIntent } from "./types";
+
+export type PendingNativeAttachments = Record<string, NativeIntent[]>;
+
+export function enqueueNativeAttachments(
+ pending: PendingNativeAttachments,
+ targetKey: string,
+ intents: NativeIntent[],
+): PendingNativeAttachments {
+ const attachments = intents.filter((intent) => intent.kind === "attachment");
+ if (attachments.length === 0) {
+ return pending;
+ }
+ return {
+ ...pending,
+ [targetKey]: [...(pending[targetKey] ?? []), ...attachments],
+ };
+}
+
+export function dequeueNativeAttachments(
+ pending: PendingNativeAttachments,
+ targetKey: string,
+): [NativeIntent[], PendingNativeAttachments] {
+ const attachments = pending[targetKey] ?? [];
+ if (attachments.length === 0) {
+ return [[], pending];
+ }
+ const remaining = { ...pending };
+ delete remaining[targetKey];
+ return [attachments, remaining];
+}
diff --git a/studio/frontend/src/features/native-intents/attachment-target.ts b/studio/frontend/src/features/native-intents/attachment-target.ts
new file mode 100644
index 00000000000..ac451ae0596
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/attachment-target.ts
@@ -0,0 +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 { createContext, useContext } from "react";
+
+export const NativeAttachmentTargetContext = createContext<string | null>(null);
+
+export function useNativeAttachmentTargetKey(): string | null {
+ return useContext(NativeAttachmentTargetContext);
+}
diff --git a/studio/frontend/src/features/native-intents/components/native-model-drop-overlay.tsx b/studio/frontend/src/features/native-intents/components/native-model-drop-overlay.tsx
index 33b89347567..d7b8057f6a2 100644
--- a/studio/frontend/src/features/native-intents/components/native-model-drop-overlay.tsx
+++ b/studio/frontend/src/features/native-intents/components/native-model-drop-overlay.tsx
@@ -5,8 +5,14 @@ import type { NativeModelDropState } from "../use-native-drop";
function overlayCopy(state: NativeModelDropState): { title: string; description: string } {
if (state.status === "invalid") {
return {
- title: "GGUF models only",
- description: "Other files are not handled here yet.",
+ title: "Can't use these files",
+ description: "Drop a .gguf model, or documents to chat with.",
+ };
+ }
+ if (state.status === "attach") {
+ return {
+ title: state.count === 1 ? "Drop to attach file" : `Drop to attach ${state.count} files`,
+ description: "Indexed for this chat.",
};
}
if (state.status === "valid" && state.action === "replace") {
@@ -29,14 +35,16 @@ function overlayCopy(state: NativeModelDropState): { title: string; description:
export function NativeModelDropOverlay({ state }: { state: NativeModelDropState }) {
const isIdle = state.status === "idle";
- const isAutoLoad = state.status === "valid" && state.action !== "chip";
+ const isAutoLoad =
+ (state.status === "valid" && state.action !== "chip") || state.status === "attach";
const isInvalid = state.status === "invalid";
const { title, description } = overlayCopy(state);
return (
<div
className={cn(
- "pointer-events-none absolute left-1/2 top-4 z-50 w-[clamp(16rem,28vw,22rem)] max-w-[calc(100vw-1rem)] -translate-x-1/2 transition-all duration-200 ease-out",
+ // Clear the chat header, which owns the top of this container.
+ "pointer-events-none absolute left-1/2 top-[calc(var(--studio-content-top-inset,0px)+var(--studio-chat-header-height,48px)+0.5rem)] z-50 w-[clamp(16rem,28vw,22rem)] max-w-[calc(100vw-1rem)] -translate-x-1/2 transition-all duration-200 ease-out",
isIdle ? "-translate-y-1 opacity-0" : "translate-y-0 opacity-100",
)}
role="status"
diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.ts
new file mode 100644
index 00000000000..8390d85eaf2
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/drop-paths.ts
@@ -0,0 +1,34 @@
+// 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 { RAG_UPLOAD_ACCEPT } from "../rag/types/rag.ts";
+
+const DOC_EXTS = RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase());
+
+/** What the window actually takes, for the rejection toast and the overlay. */
+export const SUPPORTED_DROP_HINT = `Supported files: ${RAG_UPLOAD_ACCEPT}, or a single .gguf model.`;
+
+function hasExt(path: string, ext: string): boolean {
+ return path.toLowerCase().endsWith(ext);
+}
+
+export type NativeDropClass =
+ | { kind: "none" }
+ | { kind: "model"; path: string }
+ | { kind: "docs"; paths: string[] }
+ | { kind: "unsupported" };
+
+/** What a native drag payload is, before any of it is registered with Rust. */
+export function classifyDropPaths(paths: string[]): NativeDropClass {
+ if (paths.length === 0) return { kind: "none" };
+ const ggufs = paths.filter((path) => hasExt(path, ".gguf"));
+ // One model loads; a batch of models is ambiguous, so it isn't a drop target.
+ if (ggufs.length > 0) {
+ return paths.length === 1 && ggufs.length === 1
+ ? { kind: "model", path: ggufs[0] }
+ : { kind: "unsupported" };
+ }
+ const docs = paths.filter((path) => DOC_EXTS.some((ext) => hasExt(path, ext)));
+ if (docs.length === paths.length) return { kind: "docs", paths: docs };
+ return { kind: "unsupported" };
+}
diff --git a/studio/frontend/src/features/native-intents/index.ts b/studio/frontend/src/features/native-intents/index.ts
index 98b89f08f3f..5b9412a582a 100644
--- a/studio/frontend/src/features/native-intents/index.ts
+++ b/studio/frontend/src/features/native-intents/index.ts
@@ -3,7 +3,15 @@
export { NativeModelChip } from "./components/native-model-chip";
export { NativeModelDropOverlay } from "./components/native-model-drop-overlay";
-export { openModelsDir, pickHuggingFaceCacheDir } from "./api";
+export {
+ consumeNativePathToken,
+ openModelsDir,
+ pickHuggingFaceCacheDir,
+} from "./api";
+export {
+ NativeAttachmentTargetContext,
+ useNativeAttachmentTargetKey,
+} from "./attachment-target";
export { useNativeIntentStore } from "./store";
export type { NativeIntent } from "./types";
export { useChooseNativeModel } from "./use-native-dialogs";
diff --git a/studio/frontend/src/features/native-intents/store.ts b/studio/frontend/src/features/native-intents/store.ts
index a9cd9e79665..a7c9dfb1d96 100644
--- a/studio/frontend/src/features/native-intents/store.ts
+++ b/studio/frontend/src/features/native-intents/store.ts
@@ -1,23 +1,62 @@
import { create } from "zustand";
+import {
+ type PendingNativeAttachments,
+ dequeueNativeAttachments,
+ enqueueNativeAttachments,
+} from "./attachment-queue";
import type { NativeIntent } from "./types";
interface NativeIntentState {
pendingModelIntent: NativeIntent | null;
+ // Key each batch to the chat that received the OS drop. Registration crosses an
+ // async Rust boundary, so the active chat may change before these arrive.
+ pendingAttachments: PendingNativeAttachments;
addIntent: (intent: NativeIntent) => void;
+ addAttachments: (targetKey: string, intents: NativeIntent[]) => void;
+ takeAttachments: (targetKey: string) => NativeIntent[];
clearModelIntent: (intentId?: string) => void;
}
export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({
pendingModelIntent: null,
+ pendingAttachments: {},
+ addAttachments: (targetKey, intents) => {
+ const current = get().pendingAttachments;
+ const pendingAttachments = enqueueNativeAttachments(
+ current,
+ targetKey,
+ intents,
+ );
+ if (pendingAttachments !== current) {
+ set({ pendingAttachments });
+ }
+ },
+ takeAttachments: (targetKey) => {
+ const current = get().pendingAttachments;
+ const [queued, pendingAttachments] = dequeueNativeAttachments(
+ current,
+ targetKey,
+ );
+ if (pendingAttachments !== current) {
+ set({ pendingAttachments });
+ }
+ return queued;
+ },
addIntent: (intent) => {
- if (intent.kind !== "model") return;
+ if (intent.kind !== "model") {
+ return;
+ }
const current = get().pendingModelIntent;
- if (current?.path.token === intent.path.token) return;
+ if (current?.path.token === intent.path.token) {
+ return;
+ }
set({ pendingModelIntent: intent });
},
clearModelIntent: (intentId) => {
const current = get().pendingModelIntent;
- if (intentId && current?.id !== intentId) return;
+ if (intentId && current?.id !== intentId) {
+ return;
+ }
set({ pendingModelIntent: null });
},
}));
diff --git a/studio/frontend/src/features/native-intents/types.ts b/studio/frontend/src/features/native-intents/types.ts
index 268638559a5..a921e87f7c6 100644
--- a/studio/frontend/src/features/native-intents/types.ts
+++ b/studio/frontend/src/features/native-intents/types.ts
@@ -22,6 +22,8 @@ export interface NativePathRef {
displayLabel: string;
allowedOperations: NativePathOperation[];
expiresAtMs: number;
+ sizeBytes?: number | null;
+ modifiedMs?: number | null;
}
export interface NativeIntent {
diff --git a/studio/frontend/src/features/native-intents/use-native-drop.ts b/studio/frontend/src/features/native-intents/use-native-drop.ts
index 708c8324070..ab92aec86ce 100644
--- a/studio/frontend/src/features/native-intents/use-native-drop.ts
+++ b/studio/frontend/src/features/native-intents/use-native-drop.ts
@@ -1,31 +1,33 @@
import { isTauri } from "@/lib/api-base";
import { useEffect, useRef, useState } from "react";
import { toast } from "@/lib/toast";
-import { registerNativeModelPath } from "./api";
+import { registerNativeAttachmentPath, registerNativeModelPath } from "./api";
+import { classifyDropPaths, SUPPORTED_DROP_HINT } from "./drop-paths";
import { useNativeIntentStore } from "./store";
import type { NativeIntent } from "./types";
export type NativeModelDropState =
| { status: "idle" }
| { status: "valid"; action: "load" | "replace" | "chip" }
+ | { status: "attach"; count: number }
| { status: "invalid" };
interface NativeModelDropOptions {
enabled?: boolean;
+ attachmentScope?: string;
nativePathLeasesSupported: boolean;
hasActiveModel: boolean;
isModelLoading: boolean;
onAutoLoad?: (intent: NativeIntent) => Promise<void> | void;
+ onAttach?: (intents: NativeIntent[]) => Promise<void> | void;
}
-function ggufPaths(paths: string[]): string[] {
- return paths.filter((path) => path.toLowerCase().endsWith(".gguf"));
+function canAttachDocs(options: NativeModelDropOptions): boolean {
+ return options.nativePathLeasesSupported && Boolean(options.onAttach);
}
-function canAutoLoadPaths(paths: string[], options: NativeModelDropOptions): boolean {
+function canAutoLoadModel(options: NativeModelDropOptions): boolean {
return (
- paths.length === 1 &&
- ggufPaths(paths).length === 1 &&
options.nativePathLeasesSupported &&
!options.isModelLoading &&
Boolean(options.onAutoLoad)
@@ -36,14 +38,17 @@ function dropStateForPaths(
paths: string[],
options: NativeModelDropOptions,
): NativeModelDropState {
- if (paths.length === 0) {
- return { status: "idle" };
+ const dropped = classifyDropPaths(paths);
+ if (dropped.kind === "none") return { status: "idle" };
+ if (dropped.kind === "docs") {
+ // Unlike a browser upload, a document drop only reaches the ingest through a signed
+ // lease, so don't offer it as a target before the backend can verify one.
+ return canAttachDocs(options)
+ ? { status: "attach", count: dropped.paths.length }
+ : { status: "invalid" };
}
- const ggufs = ggufPaths(paths);
- if (paths.length !== 1 || ggufs.length !== 1) {
- return { status: "invalid" };
- }
- if (!canAutoLoadPaths(paths, options)) {
+ if (dropped.kind === "unsupported") return { status: "invalid" };
+ if (!canAutoLoadModel(options)) {
return { status: "valid", action: "chip" };
}
return {
@@ -80,22 +85,41 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModel
}
if (event.payload.type !== "drop") return;
setDropState({ status: "idle" });
- const ggufs = ggufPaths(event.payload.paths);
- if (event.payload.paths.length !== 1 || ggufs.length !== 1) {
- if (event.payload.paths.length > 0) {
- toast.error(
- ggufs.length === 0
- ? "Only .gguf model files can be dropped here."
- : "Drop a single .gguf model file.",
+ const dropped = classifyDropPaths(event.payload.paths);
+ if (dropped.kind === "none") return;
+ if (dropped.kind === "unsupported") {
+ toast.error(SUPPORTED_DROP_HINT);
+ return;
+ }
+ if (dropped.kind === "docs") {
+ if (!canAttachDocs(currentOptions)) {
+ toast.error("Attaching files needs the desktop backend", {
+ description: "Retry once Studio has finished starting up.",
+ });
+ return;
+ }
+ try {
+ const intents = await Promise.all(
+ dropped.paths.map(registerNativeAttachmentPath),
);
+ if (disposed) return;
+ const latestOptions = optionsRef.current;
+ const attachOptions =
+ latestOptions.attachmentScope === currentOptions.attachmentScope
+ ? latestOptions
+ : currentOptions;
+ await attachOptions.onAttach?.(intents);
+ } catch (error) {
+ toast.error("Could not attach dropped files", {
+ description: error instanceof Error ? error.message : String(error),
+ });
}
return;
}
- const ggufPath = ggufs[0];
try {
- const intent = await registerNativeModelPath(ggufPath);
+ const intent = await registerNativeModelPath(dropped.path);
if (disposed) return;
- if (!canAutoLoadPaths(event.payload.paths, currentOptions)) {
+ if (!canAutoLoadModel(currentOptions)) {
addIntent(intent);
return;
}
diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.ts
index c0d0266dbbe..3fd342a5cdc 100644
--- a/studio/frontend/src/features/rag/api/rag-api.ts
+++ b/studio/frontend/src/features/rag/api/rag-api.ts
@@ -41,14 +41,22 @@ async function ragRequest<T>(
return json as T;
}
+/** A desktop drop the webview can only name through a Rust-signed grant. */
+export interface NativeUploadRef {
+ nativePathLease: string;
+}
+
+export type UploadSource = File | NativeUploadRef;
+
async function ragUpload(
path: string,
- file: File,
+ source: UploadSource,
ocr?: boolean,
caption?: boolean,
): Promise<DocumentUploadResult> {
const form = new FormData();
- form.append("file", file);
+ if (source instanceof File) form.append("file", source);
+ else form.append("nativePathLease", source.nativePathLease);
// Per-upload overrides for the vision passes; omitted -> backend config default.
if (ocr !== undefined) form.append("ocr", String(ocr));
if (caption !== undefined) form.append("caption", String(caption));
@@ -112,7 +120,7 @@ export async function listKnowledgeBaseDocuments(
export function uploadKnowledgeBaseDocument(
kbId: string,
- file: File,
+ file: UploadSource,
ocr?: boolean,
caption?: boolean,
): Promise<DocumentUploadResult> {
@@ -135,7 +143,7 @@ export async function listThreadDocuments(
export function uploadThreadDocument(
threadId: string,
- file: File,
+ file: UploadSource,
ocr?: boolean,
caption?: boolean,
): Promise<DocumentUploadResult> {
@@ -158,7 +166,7 @@ export async function listProjectDocuments(
export function uploadProjectDocument(
projectId: string,
- file: File,
+ file: UploadSource,
ocr?: boolean,
caption?: boolean,
): Promise<DocumentUploadResult> {
diff --git a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
index 38677c27c40..51d3dee23e3 100644
--- a/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
+++ b/studio/frontend/src/features/rag/components/thread-documents-bar.tsx
@@ -7,6 +7,10 @@ import { AttachmentIcon, FileDatabaseIcon } from "@hugeicons/core-free-icons";
import { useAui } from "@assistant-ui/react";
import { cn } from "@/lib/utils";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import {
+ useNativeAttachmentTargetKey,
+ useNativeIntentStore,
+} from "@/features/native-intents";
import { toast } from "@/lib/toast";
import { listKnowledgeBases, listThreadDocuments } from "../api/rag-api";
import { RAG_UPLOAD_ACCEPT } from "../types/rag";
@@ -55,6 +59,8 @@ export function ThreadDocumentsBar({
}) {
const ragEnabled = useChatRuntimeStore((s) => s.ragEnabled);
const ragSource = useChatRuntimeStore((s) => s.ragSource);
+ const setRagSource = useChatRuntimeStore((s) => s.setRagSource);
+ const setRagEnabled = useChatRuntimeStore((s) => s.setRagEnabled);
const aui = useAui();
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -117,6 +123,60 @@ export function ThreadDocumentsBar({
return pending;
}, [aui, effectiveThreadId]);
+ // Desktop drops land in the native-intent store because the drop listener lives on
+ // the chat page; only the chat that received the OS drop may drain its batch.
+ const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();
+ const hasPendingAttachments = useNativeIntentStore((s) =>
+ Boolean(
+ nativeAttachmentTargetKey &&
+ (s.pendingAttachments[nativeAttachmentTargetKey]?.length ?? 0) > 0,
+ ),
+ );
+ useEffect(() => {
+ if (!hasPendingAttachments || !nativeAttachmentTargetKey) {
+ return;
+ }
+ // A KB-scoped chat uploads through the KB dialog, so a thread upload here would
+ // index into something this bar never shows.
+ if (ragEnabled && ragSource.type === "kb") {
+ useNativeIntentStore.getState().takeAttachments(nativeAttachmentTargetKey);
+ toast.error("This chat retrieves from a knowledge base", {
+ description: "Add these files to the knowledge base instead.",
+ });
+ return;
+ }
+ const intents = useNativeIntentStore
+ .getState()
+ .takeAttachments(nativeAttachmentTargetKey);
+ if (intents.length === 0) return;
+ // A stale KB preference is inactive while RAG is off; use thread retrieval.
+ if (!ragEnabled) {
+ setRagSource({ type: "thread" });
+ setRagEnabled(true);
+ }
+ void upload(
+ intents.map((intent) => ({
+ kind: "native" as const,
+ token: intent.path.token,
+ name: intent.displayLabel,
+ sizeBytes: intent.path.sizeBytes,
+ modifiedMs: intent.path.modifiedMs,
+ })),
+ ensureThreadId().then((id) =>
+ id ? ({ type: "thread", threadId: id } as const) : null,
+ ),
+ );
+ }, [
+ hasPendingAttachments,
+ nativeAttachmentTargetKey,
+ upload,
+ ensureThreadId,
+ ragEnabled,
+ ragSource,
+ setRagSource,
+ setRagEnabled,
+ ]);
+
const chipScrollRef = useRef<HTMLDivElement>(null);
const [chipsOverflow, setChipsOverflow] = useState(false);
const updateChipFade = useCallback(() => {
diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.ts
index bdab7b0518b..fb8375dd96b 100644
--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts
+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { toast } from "@/lib/toast";
+import { consumeNativePathToken } from "@/features/native-intents";
import { useCallback, useEffect, useRef, useState } from "react";
import {
deleteDocument,
@@ -18,9 +19,36 @@ export interface TrackedDocument extends RagDocument {
progress?: number | null;
}
-// Client-side dedup key; backend dedups authoritatively by content hash.
-function fileSignature(file: File): string {
- return `${file.name}|${file.size}|${file.lastModified}`;
+/** A browser File, or a desktop drop addressed by its native path token. */
+export type RagUploadItem =
+ | { kind: "file"; file: File }
+ | {
+ kind: "native";
+ token: string;
+ name: string;
+ sizeBytes?: number | null;
+ modifiedMs?: number | null;
+ };
+
+export function fileItems(files: FileList | File[]): RagUploadItem[] {
+ return Array.from(files).map((file) => ({ kind: "file" as const, file }));
+}
+
+function itemName(item: RagUploadItem): string {
+ return item.kind === "file" ? item.file.name : item.name;
+}
+
+// Client-side dedup key; backend dedups authoritatively by content hash. Native drops
+// carry the size/mtime Rust stat'd, so same-named files from different folders are
+// still distinct; without them the drop is never blocked client-side.
+function itemSignature(item: RagUploadItem): string {
+ if (item.kind === "file") {
+ return `${item.file.name}|${item.file.size}|${item.file.lastModified}`;
+ }
+ if (item.sizeBytes == null || item.modifiedMs == null) {
+ return `${item.name}|native|${item.token}`;
+ }
+ return `${item.name}|${item.sizeBytes}|${item.modifiedMs}`;
}
export type RagDocumentScope =
@@ -253,13 +281,23 @@ export function useRagDocuments(
// the chip if the backend deduped. `seenIds` holds ids present/added this batch.
const uploadOne = useCallback(
async (
- file: File,
+ item: RagUploadItem,
seenIds: Set<string>,
activeScope: RagDocumentScope,
tempId: string,
) => {
+ const name = itemName(item);
try {
const { ocr, caption } = resolveVisionOverrides();
+ // Leases are short-lived, so mint one per upload rather than at drop time.
+ const file =
+ item.kind === "file"
+ ? item.file
+ : {
+ nativePathLease: (
+ await consumeNativePathToken(item.token, "attach")
+ ).nativePathLease,
+ };
const result =
activeScope.type === "kb"
? await uploadKnowledgeBaseDocument(
@@ -281,12 +319,10 @@ export function useRagDocuments(
ocr,
caption,
);
- sigByDocId.current.set(result.documentId, fileSignature(file));
+ sigByDocId.current.set(result.documentId, itemSignature(item));
if (seenIds.has(result.documentId)) {
setDocuments((rows) => rows.filter((row) => row.id !== tempId));
- toast.info(
- `${result.filename || file.name} is already indexed - skipping`,
- );
+ toast.info(`${result.filename || name} is already indexed - skipping`);
return;
}
seenIds.add(result.documentId);
@@ -302,12 +338,12 @@ export function useRagDocuments(
: row,
),
);
- trackJob(result.jobId, result.documentId, result.filename || file.name);
+ trackJob(result.jobId, result.documentId, result.filename || name);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
// Drop the chip rather than show "Failed"; warn via toast.
setDocuments((rows) => rows.filter((row) => row.id !== tempId));
- toast.error(`Couldn't upload ${file.name}`, { description: message });
+ toast.error(`Couldn't upload ${name}`, { description: message });
}
},
[trackJob],
@@ -318,7 +354,7 @@ export function useRagDocuments(
// the hook scope.
const upload = useCallback(
async (
- files: FileList | File[],
+ files: FileList | File[] | RagUploadItem[],
overrideScope?: RagDocumentScope | Promise<RagDocumentScope | null>,
) => {
// Flip the in-flight guard synchronously, before awaiting a thread id that
@@ -330,23 +366,28 @@ export function useRagDocuments(
// Show an optimistic chip per file before awaiting the thread id;
// materialization is a round-trip and gating chips behind it makes a slow
// one look like nothing happened. Dedup re-selections up front.
- const fresh: Array<{ tempId: string; file: File }> = [];
- for (const file of Array.from(files)) {
- if (sigBlocksReupload(fileSignature(file))) {
- toast.info(`${file.name} is already indexed - skipping`);
+ const fresh: Array<{ tempId: string; item: RagUploadItem }> = [];
+ const entries: Array<File | RagUploadItem> = Array.isArray(files)
+ ? files
+ : Array.from(files);
+ for (const entry of entries) {
+ const item: RagUploadItem =
+ entry instanceof File ? { kind: "file", file: entry } : entry;
+ if (sigBlocksReupload(itemSignature(item))) {
+ toast.info(`${itemName(item)} is already indexed - skipping`);
continue;
}
fresh.push({
tempId: `pending_${Math.random().toString(36).slice(2)}`,
- file,
+ item,
});
}
if (fresh.length === 0) return;
setDocuments((rows) => [
...rows,
- ...fresh.map(({ tempId, file }) => ({
+ ...fresh.map(({ tempId, item }) => ({
id: tempId,
- filename: file.name,
+ filename: itemName(item),
status: "pending" as const,
progress: null,
})),
@@ -372,8 +413,8 @@ export function useRagDocuments(
.filter((d) => !d.id.startsWith("pending_"))
.map((d) => d.id),
);
- for (const { tempId, file } of fresh) {
- await uploadOne(file, seenIds, activeScope, tempId);
+ for (const { tempId, item } of fresh) {
+ await uploadOne(item, seenIds, activeScope, tempId);
}
} finally {
setUploading(false);
diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.ts
new file mode 100644
index 00000000000..c368941ab2f
--- /dev/null
+++ b/studio/frontend/tests/native-drop-paths.test.ts
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import {
+ dequeueNativeAttachments,
+ enqueueNativeAttachments,
+} from "../src/features/native-intents/attachment-queue.ts";
+import { classifyDropPaths } from "../src/features/native-intents/drop-paths.ts";
+import type { NativeIntent } from "../src/features/native-intents/types.ts";
+import { RAG_UPLOAD_ACCEPT } from "../src/features/rag/types/rag.ts";
+
+const BACKEND_UPLOAD_EXTS_RE = /UPLOAD_EXTS\s*=\s*\{([^}]+)\}/s;
+const RUST_ATTACHMENT_EXTS_RE = /ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;
+const DOTTED_EXTENSION_RE = /"(\.[^"]+)"/g;
+const RUST_EXTENSION_RE = /"([^"]+)"/g;
+
+function attachmentIntent(id: string): NativeIntent {
+ return {
+ id,
+ kind: "attachment",
+ sourceKind: "drop",
+ displayLabel: `${id}.txt`,
+ path: {
+ token: `token-${id}`,
+ kind: "attachment",
+ displayLabel: `${id}.txt`,
+ allowedOperations: ["attach", "reveal"],
+ expiresAtMs: Date.now() + 60_000,
+ },
+ };
+}
+
+test("a lone gguf is a model drop", () => {
+ assert.deepEqual(classifyDropPaths(["C:/models/qwen.gguf"]), {
+ kind: "model",
+ path: "C:/models/qwen.gguf",
+ });
+ // Extension casing comes from the filesystem, not from us.
+ assert.equal(classifyDropPaths(["/models/Qwen.GGUF"]).kind, "model");
+});
+
+test("documents are an attachment drop, one or many", () => {
+ const dropped = classifyDropPaths([
+ "/docs/a.pdf",
+ "/docs/b.MD",
+ "/docs/c.docx",
+ ]);
+ assert.equal(dropped.kind, "docs");
+ assert.equal(dropped.kind === "docs" ? dropped.paths.length : 0, 3);
+});
+
+test("a mixed or unsupported drop is rejected", () => {
+ // The regression in #7661: these used to be reported as "GGUF models only".
+ assert.equal(
+ classifyDropPaths(["/docs/a.pdf", "/models/q.gguf"]).kind,
+ "unsupported",
+ );
+ assert.equal(
+ classifyDropPaths(["/models/a.gguf", "/models/b.gguf"]).kind,
+ "unsupported",
+ );
+ assert.equal(
+ classifyDropPaths(["/docs/a.pdf", "/docs/b.zip"]).kind,
+ "unsupported",
+ );
+ assert.equal(classifyDropPaths(["/docs/notes.zip"]).kind, "unsupported");
+});
+
+test("an empty payload is not a drop target", () => {
+ assert.equal(classifyDropPaths([]).kind, "none");
+});
+
+test("attachment batches stay bound to the chat that received the drop", () => {
+ const queued = enqueueNativeAttachments({}, "single:thread-a", [
+ attachmentIntent("doc"),
+ ]);
+
+ const [wrongThread, afterWrongThread] = dequeueNativeAttachments(
+ queued,
+ "single:thread-b",
+ );
+ assert.deepEqual(wrongThread, []);
+ assert.equal(afterWrongThread, queued);
+
+ const [rightThread, remaining] = dequeueNativeAttachments(
+ afterWrongThread,
+ "single:thread-a",
+ );
+ assert.deepEqual(
+ rightThread.map((intent) => intent.id),
+ ["doc"],
+ );
+ assert.deepEqual(remaining, {});
+});
+
+test("frontend, backend, and Rust accept the same document extensions", () => {
+ const frontend = RAG_UPLOAD_ACCEPT.split(",").sort();
+ const backendSource = readFileSync(
+ new URL("../../backend/core/rag/config.py", import.meta.url),
+ "utf8",
+ );
+ const rustSource = readFileSync(
+ new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),
+ "utf8",
+ );
+ const backend = [
+ ...(backendSource
+ .match(BACKEND_UPLOAD_EXTS_RE)?.[1]
+ .matchAll(DOTTED_EXTENSION_RE) ?? []),
+ ]
+ .map((match) => match[1])
+ .sort();
+ const rust = [
+ ...(rustSource
+ .match(RUST_ATTACHMENT_EXTS_RE)?.[1]
+ .matchAll(RUST_EXTENSION_RE) ?? []),
+ ]
+ .map((match) => `.${match[1]}`)
+ .sort();
+
+ assert.deepEqual(backend, frontend);
+ assert.deepEqual(rust, frontend);
+});
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index fe12c6b44d8..8e55f2f3420 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -332,6 +332,7 @@ fn main() {
native_file_dialogs::pick_native_chat_import,
native_intents::drain_native_intents,
native_intents::register_native_model_path,
+ native_intents::register_native_attachment_path,
native_intents::pick_native_model,
native_intents::pick_hugging_face_cache_dir,
native_intents::consume_native_path_token,
@@ -356,6 +357,13 @@ fn main() {
Ok(())
})
.on_window_event(|window, event| {
+ // Record real drops here, in Rust, so the renderer can only register paths the
+ // OS actually handed us (see native_intents::register_native_attachment_path).
+ if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
+ window
+ .state::<native_intents::NativeIntakeState>()
+ .note_dropped_paths(paths);
+ }
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
// Hide window instead of closing, because this is a tray app.
// Processes keep running so the backend stays available.
diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rs
index 006babfaa7e..d13e637f5b2 100644
--- a/studio/src-tauri/src/native_intents.rs
+++ b/studio/src-tauri/src/native_intents.rs
@@ -3,8 +3,8 @@ use crate::native_backend_lease::{
NativePathLeaseResponse, NativePathOperation, NativePathSourceKind, NativePathType,
};
use crate::native_path_policy::{
- classify_artifact_path, classify_native_model_path, reveal_target, ClassifiedPath,
- NativeArtifactKind,
+ classify_artifact_path, classify_native_attachment_path, classify_native_model_path,
+ reveal_target, ClassifiedPath, NativeArtifactKind,
};
use serde::Serialize;
use std::collections::{HashMap, VecDeque};
@@ -15,6 +15,8 @@ use tauri::{AppHandle, WebviewWindow};
use tauri_plugin_dialog::DialogExt;
const TOKEN_TTL: Duration = Duration::from_secs(15 * 60);
+// How long after the OS reports a drop the renderer may still register those paths.
+const DROP_GRACE: Duration = Duration::from_secs(2 * 60);
fn normalize_windows_verbatim_path(path: String) -> String {
if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
@@ -53,6 +55,7 @@ struct NativePathEntry {
#[derive(Clone, Copy, Debug)]
enum NativePathValidationPolicy {
Model,
+ Attachment,
Artifact(NativeArtifactKind),
}
@@ -64,6 +67,9 @@ pub struct NativePathRef {
display_label: String,
allowed_operations: Vec<NativePathOperation>,
expires_at_ms: u64,
+ // The frontend dedups uploads on these the way it does on a File's size/mtime.
+ size_bytes: Option<u64>,
+ modified_ms: Option<u64>,
}
#[derive(Clone, Debug, Serialize)]
@@ -80,6 +86,9 @@ pub struct NativeIntent {
struct NativeIntakeInner {
tokens: HashMap<String, NativePathEntry>,
queued_intents: VecDeque<NativeIntent>,
+ // Paths Rust itself saw land on the window, so the renderer can only register
+ // what the user actually dropped. Expiry keeps a stale drop from being spent later.
+ recent_drops: HashMap<PathBuf, u64>,
}
pub struct NativeIntakeState {
@@ -120,6 +129,45 @@ impl NativeIntakeState {
self.register_classified_path(classified, source_kind, NativePathValidationPolicy::Model)
}
+ /// Record what the OS dropped on the window. Called from the window event handler,
+ /// never from the renderer.
+ pub fn note_dropped_paths(&self, paths: &[PathBuf]) {
+ let Ok(mut inner) = self.inner.lock() else { return };
+ let now = now_ms();
+ inner.recent_drops.retain(|_, expires| *expires > now);
+ let expires_at = now + DROP_GRACE.as_millis() as u64;
+ for path in paths {
+ if let Ok(canonical) = path.canonicalize() {
+ inner.recent_drops.insert(canonical, expires_at);
+ }
+ }
+ }
+
+ fn was_recently_dropped(&self, canonical: &Path) -> Result<bool, String> {
+ let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
+ let now = now_ms();
+ inner.recent_drops.retain(|_, expires| *expires > now);
+ Ok(inner.recent_drops.contains_key(canonical))
+ }
+
+ fn register_attachment_path(
+ &self,
+ path: impl AsRef<Path>,
+ source_kind: NativePathSourceKind,
+ ) -> Result<NativeIntent, String> {
+ let classified = classify_native_attachment_path(path.as_ref())?;
+ // The renderer hands us a path string, so a script in the webview could name any
+ // readable document. Only paths the user actually dropped can be registered.
+ if !self.was_recently_dropped(&classified.canonical_path)? {
+ return Err("Attachments must come from a file dropped on the window.".to_string());
+ }
+ self.register_classified_path(
+ classified,
+ source_kind,
+ NativePathValidationPolicy::Attachment,
+ )
+ }
+
fn register_artifact(
&self,
kind: NativeArtifactKind,
@@ -237,6 +285,9 @@ fn validate_entry_path(
) -> Result<(), String> {
let classified = match entry.validation_policy {
NativePathValidationPolicy::Model => classify_native_model_path(&entry.canonical_path)?,
+ NativePathValidationPolicy::Attachment => {
+ classify_native_attachment_path(&entry.canonical_path)?
+ }
NativePathValidationPolicy::Artifact(kind) => {
classify_artifact_path(kind, &entry.canonical_path)?
}
@@ -265,6 +316,8 @@ impl NativePathEntry {
display_label: self.display_label.clone(),
allowed_operations: self.allowed_operations.clone(),
expires_at_ms: self.expires_at_ms,
+ size_bytes: self.size_bytes,
+ modified_ms: self.modified_ms,
}
}
}
@@ -304,6 +357,16 @@ pub fn register_native_model_path(
state.register_model_path(path, NativePathSourceKind::Drop)
}
+#[tauri::command]
+pub fn register_native_attachment_path(
+ window: WebviewWindow,
+ state: tauri::State<'_, NativeIntakeState>,
+ path: String,
+) -> Result<NativeIntent, String> {
+ ensure_main_window(&window)?;
+ state.register_attachment_path(path, NativePathSourceKind::Drop)
+}
+
#[tauri::command]
pub async fn pick_native_model(
window: WebviewWindow,
@@ -498,6 +561,48 @@ mod tests {
let _ = fs::remove_file(path);
}
+ #[test]
+ fn attachment_registration_needs_a_real_drop() {
+ let state = new_native_intake_state();
+ let path = temp_path("attachment").with_extension("txt");
+ fs::write(&path, b"notes").unwrap();
+
+ // A renderer naming a path we never saw dropped gets nothing.
+ let err = state
+ .register_attachment_path(&path, NativePathSourceKind::Drop)
+ .unwrap_err();
+ assert!(err.contains("dropped on the window"));
+
+ state.note_dropped_paths(&[path.clone()]);
+ let intent = state
+ .register_attachment_path(&path, NativePathSourceKind::Drop)
+ .unwrap();
+ assert_eq!(intent.kind, NativePathKind::Attachment);
+ assert!(intent
+ .path
+ .allowed_operations
+ .contains(&NativePathOperation::Attach));
+ // The fingerprint the frontend dedups on comes from the stat, not the label.
+ assert_eq!(intent.path.size_bytes, Some(5));
+ let _ = fs::remove_file(path);
+ }
+
+ #[test]
+ fn a_drop_does_not_unlock_its_neighbours() {
+ let state = new_native_intake_state();
+ let dropped = temp_path("dropped").with_extension("txt");
+ let sibling = temp_path("sibling").with_extension("txt");
+ fs::write(&dropped, b"dropped").unwrap();
+ fs::write(&sibling, b"sibling").unwrap();
+
+ state.note_dropped_paths(&[dropped.clone()]);
+ assert!(state
+ .register_attachment_path(&sibling, NativePathSourceKind::Drop)
+ .is_err());
+ let _ = fs::remove_file(dropped);
+ let _ = fs::remove_file(sibling);
+ }
+
#[test]
fn windows_verbatim_paths_are_portable() {
assert_eq!(
diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rs
index 26d4cdb61ae..ac4419446c7 100644
--- a/studio/src-tauri/src/native_path_policy.rs
+++ b/studio/src-tauri/src/native_path_policy.rs
@@ -44,6 +44,34 @@ pub fn classify_native_model_path(path: &Path) -> Result<ClassifiedPath, String>
})
}
+/// Document types the RAG ingest accepts; keep in sync with `config.UPLOAD_EXTS`.
+pub const ATTACHMENT_EXTS: &[&str] = &["pdf", "txt", "md", "markdown", "docx", "html", "htm"];
+
+pub fn classify_native_attachment_path(path: &Path) -> Result<ClassifiedPath, String> {
+ let classified = classify_existing_path(path)?;
+ if classified.path_type != NativePathType::File {
+ return Err("Only files can be attached to a chat.".to_string());
+ }
+ if !ATTACHMENT_EXTS
+ .iter()
+ .any(|ext| has_extension(&classified.canonical_path, ext))
+ {
+ return Err(format!(
+ "Unsupported attachment type. Supported: {}",
+ ATTACHMENT_EXTS
+ .iter()
+ .map(|ext| format!(".{ext}"))
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+ Ok(ClassifiedPath {
+ path_kind: NativePathKind::Attachment,
+ allowed_operations: vec![NativePathOperation::Attach, NativePathOperation::Reveal],
+ ..classified
+ })
+}
+
pub fn classify_artifact_path(
kind: NativeArtifactKind,
path: &Path,
@@ -288,4 +316,27 @@ mod tests {
assert!(classify_native_model_path(&path).is_err());
let _ = fs::remove_file(path);
}
+
+ #[test]
+ fn document_allows_attach_and_reveal_only() {
+ let path = temp_path("doc").with_extension("pdf");
+ fs::write(&path, b"%PDF-1.4").unwrap();
+ let classified = classify_native_attachment_path(&path).unwrap();
+ assert_eq!(classified.path_kind, NativePathKind::Attachment);
+ assert!(classified
+ .allowed_operations
+ .contains(&NativePathOperation::Attach));
+ assert!(!classified
+ .allowed_operations
+ .contains(&NativePathOperation::LoadModel));
+ let _ = fs::remove_file(path);
+ }
+
+ #[test]
+ fn unsupported_attachment_type_is_rejected() {
+ let path = temp_path("doc").with_extension("exe");
+ fs::write(&path, b"MZ").unwrap();
+ assert!(classify_native_attachment_path(&path).is_err());
+ let _ = fs::remove_file(path);
+ }
}