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: route native drops to the drop zone under the cursor (#8265)

Nilayf4bd4e80409c
diff --git a/studio/frontend/src/components/image-dropzone.tsx b/studio/frontend/src/components/image-dropzone.tsx
index f01507457d2..7e5a71ae92a 100644
--- a/studio/frontend/src/components/image-dropzone.tsx
+++ b/studio/frontend/src/components/image-dropzone.tsx
@@ -1,7 +1,7 @@
// 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 { useCallback, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { Delete02Icon, ImageAdd02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -11,9 +11,18 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import {
+ readNativeAttachmentFile,
+ registerNativeAttachmentPath,
+ useNativeDropTarget,
+} from "@/features/native-intents";
import { cn } from "@/lib/utils";
import { toast } from "@/lib/toast";
+// All registerNativeAttachmentPath takes. The picker itself accepts image/*,
+// so name the droppable formats instead of surfacing the backend's refusal.
+const NATIVE_IMAGE_EXTS = ["jpg", "jpeg", "png", "webp", "gif"];
+
/** Shared image picker that returns a data URL. */
export function ImageDropzone({
value,
@@ -32,6 +41,27 @@ export function ImageDropzone({
}) {
const inputRef = useRef<HTMLInputElement | null>(null);
const [dragging, setDragging] = useState(false);
+ // File reads can finish after another picker action. Only the newest
+ // selection may update the shared field.
+ const selection = useRef(0);
+ // The sequence is per instance, so it cannot see a read outliving this
+ // picker: `onChange` is shared, and a late write lands on whoever holds it.
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+ // The reference slots are keyed by index, so removing one shifts a different
+ // image into a picker that stays mounted. A `value` this picker did not set
+ // means a read in flight is for the slot as it used to be.
+ const seen = useRef(value);
+ useEffect(() => {
+ if (seen.current === value) return;
+ seen.current = value;
+ selection.current += 1;
+ }, [value]);
const readFile = useCallback(
(file: File | undefined | null) => {
@@ -39,14 +69,51 @@ export function ImageDropzone({
if (file) toast.error("Please choose an image file");
return;
}
+ selection.current += 1;
+ const claimed = selection.current;
const reader = new FileReader();
- reader.onload = () => onChange(typeof reader.result === "string" ? reader.result : null);
+ reader.onload = () => {
+ if (claimed !== selection.current) return;
+ onChange(typeof reader.result === "string" ? reader.result : null);
+ };
reader.onerror = () => toast.error("Could not read the image");
reader.readAsDataURL(file);
},
[onChange],
);
+ // Tauri suppresses the webview drop event, so desktop drops arrive as paths
+ // that the native side registers and reads for this picker.
+ const readNativePath = useCallback(
+ async (path: string | undefined) => {
+ if (!path) return;
+ if (!NATIVE_IMAGE_EXTS.includes(path.split(".").pop()?.toLowerCase() ?? "")) {
+ toast.error("Drop a JPEG, PNG, WebP or GIF image", {
+ description: "Other image formats can still be chosen with the picker.",
+ });
+ return;
+ }
+ selection.current += 1;
+ const claimed = selection.current;
+ try {
+ const intent = await registerNativeAttachmentPath(path);
+ const file = await readNativeAttachmentFile(intent.path.token);
+ if (!mounted.current || claimed !== selection.current) return;
+ onChange(`data:${file.mimeType};base64,${file.base64}`);
+ } catch (error) {
+ toast.error("Could not read the image", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+ },
+ [onChange],
+ );
+
+ const nativeDropRef = useNativeDropTarget({
+ onDrop: (paths) => void readNativePath(paths[0]),
+ onDragOver: setDragging,
+ });
+
if (value) {
return (
<div className={cn("relative overflow-hidden rounded-[10px] border border-border", className)}>
@@ -60,6 +127,7 @@ export function ImageDropzone({
aria-label={removeLabel}
className="absolute right-1.5 top-1.5 size-7"
onClick={() => {
+ selection.current += 1;
onChange(null);
if (inputRef.current) inputRef.current.value = "";
}}
@@ -76,6 +144,7 @@ export function ImageDropzone({
return (
<button
type="button"
+ ref={nativeDropRef}
onClick={() => inputRef.current?.click()}
onDragOver={(e) => {
e.preventDefault();
diff --git a/studio/frontend/src/features/chat/components/new-project-dialog.tsx b/studio/frontend/src/features/chat/components/new-project-dialog.tsx
index 6aca3d36c35..1ba5916d5b8 100644
--- a/studio/frontend/src/features/chat/components/new-project-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/new-project-dialog.tsx
@@ -53,6 +53,9 @@ export function NewProjectDialog({
const [name, setName] = useState("");
const [staged, setStaged] = useState<StagedSource[]>([]);
const [busy, setBusy] = useState(false);
+ // A desktop drop reaches `staged` only once its native registration settles.
+ // Creating before then would upload without the files the user just dropped.
+ const [stagingDrop, setStagingDrop] = useState(false);
// Uploads outlive this component, so a slow one must not yank the user to the
// new project after they have navigated away.
const mounted = useRef(true);
@@ -68,6 +71,7 @@ export function NewProjectDialog({
function reset() {
setName("");
setStaged([]);
+ setStagingDrop(false);
}
// Every close path routes through here: callers keep this mounted, so a draft
@@ -80,7 +84,7 @@ export function NewProjectDialog({
async function commitCreate() {
const trimmed = name.trim();
- if (!trimmed || busy) return;
+ if (!trimmed || busy || stagingDrop) return;
setBusy(true);
// Sidebar callers keep this mounted across routes, so unmounting alone
// cannot tell whether the user has moved on during a slow upload.
@@ -157,6 +161,7 @@ export function NewProjectDialog({
staged={staged}
onChange={setStaged}
disabled={busy}
+ onPendingChange={setStagingDrop}
/>
<DialogFooter className="flex-wrap gap-2 sm:justify-end">
<Button type="button" variant="ghost" disabled={busy} onClick={close}>
@@ -165,9 +170,9 @@ export function NewProjectDialog({
<Button
type="button"
onClick={() => void commitCreate()}
- disabled={!name.trim() || busy}
+ disabled={!name.trim() || busy || stagingDrop}
>
- {busy ? "Creating…" : submitLabel}
+ {busy ? "Creating…" : stagingDrop ? "Adding sources…" : submitLabel}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/studio/frontend/src/features/native-intents/index.ts b/studio/frontend/src/features/native-intents/index.ts
index 5d6a6fa198c..822f17fac87 100644
--- a/studio/frontend/src/features/native-intents/index.ts
+++ b/studio/frontend/src/features/native-intents/index.ts
@@ -7,8 +7,12 @@ export {
consumeNativePathToken,
openModelsDir,
pickHuggingFaceCacheDir,
+ readNativeAttachmentFile,
+ registerNativeAttachmentPath,
registerNativeDatasetPath,
} from "./api";
+export { nativeDropTargetAt } from "./native-drop-targets";
+export { useNativeDropTarget } from "./use-native-drop-target";
export {
NativeAttachmentTargetContext,
useNativeAttachmentTargetKey,
diff --git a/studio/frontend/src/features/native-intents/native-drop-position.ts b/studio/frontend/src/features/native-intents/native-drop-position.ts
new file mode 100644
index 00000000000..14999367f91
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/native-drop-position.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Tauri types every drop position as physical, but wry only produces one on
+// WebView2 (ScreenToClient device pixels). macOS reports NSView points and GTK
+// reports widget coordinates, both of which are already CSS pixels.
+function isPhysicalDropPosition(): boolean {
+ return (
+ typeof navigator !== "undefined" && navigator.userAgent.includes("Windows")
+ );
+}
+
+// The DOM is measured in CSS pixels, not the logical window ones the monitor
+// scale gives, and webview zoom moves the two apart either way. Take
+// devicePixelRatio, which is physical per CSS by definition.
+function physicalPerCssPx(windowScaleFactor: number): number {
+ const ratio = typeof window === "undefined" ? NaN : window.devicePixelRatio;
+ if (Number.isFinite(ratio) && ratio > 0) return ratio;
+ return Number.isFinite(windowScaleFactor) && windowScaleFactor > 0
+ ? windowScaleFactor
+ : 1;
+}
+
+/** A drop position in the CSS pixels the DOM is measured in. */
+export function nativeDropPointToCss(
+ position: { x: number; y: number },
+ windowScaleFactor: number,
+): { x: number; y: number } {
+ if (!isPhysicalDropPosition()) return position;
+ const scale = physicalPerCssPx(windowScaleFactor);
+ return { x: position.x / scale, y: position.y / scale };
+}
diff --git a/studio/frontend/src/features/native-intents/native-drop-targets.ts b/studio/frontend/src/features/native-intents/native-drop-targets.ts
new file mode 100644
index 00000000000..e0b51735e4c
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/native-drop-targets.ts
@@ -0,0 +1,102 @@
+// 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 { isTauri } from "@/lib/api-base";
+import { nativeDropPointToCss } from "./native-drop-position.ts";
+
+export interface NativeDropTargetHandlers {
+ onDrop: (paths: string[]) => void;
+ onDragOver?: (over: boolean) => void;
+}
+
+// Tauri delivers OS drops window-wide with a physical position and suppresses
+// the webview's own drop events, so which element was dropped on has to be
+// resolved here instead of by DOM event routing.
+const targets = new Map<HTMLElement, NativeDropTargetHandlers>();
+
+let scaleFactor =
+ typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
+let hovered: HTMLElement | null = null;
+let listening = false;
+// Outside Tauri the DOM routes drops itself, so there is no listener to wait on.
+let ready = !isTauri;
+
+/** The innermost registered target under `position`, or null. */
+export function nativeDropTargetAt(position: {
+ x: number;
+ y: number;
+}): HTMLElement | null {
+ if (!ready || targets.size === 0 || typeof document === "undefined")
+ return null;
+ const { x, y } = nativeDropPointToCss(position, scaleFactor);
+ let node: Element | null = document.elementFromPoint(x, y);
+ while (node !== null) {
+ if (node instanceof HTMLElement && targets.has(node)) return node;
+ node = node.parentElement;
+ }
+ return null;
+}
+
+function setHovered(next: HTMLElement | null): void {
+ if (hovered === next) return;
+ if (hovered) targets.get(hovered)?.onDragOver?.(false);
+ hovered = next;
+ if (next) targets.get(next)?.onDragOver?.(true);
+}
+
+function listen(): void {
+ if (listening || !isTauri) return;
+ listening = true;
+ void import("@tauri-apps/api/window")
+ .then(async ({ getCurrentWindow }) => {
+ const currentWindow = getCurrentWindow();
+ await currentWindow.onDragDropEvent(({ payload }) => {
+ if (payload.type === "leave") {
+ setHovered(null);
+ return;
+ }
+ const target = nativeDropTargetAt(payload.position);
+ if (payload.type !== "drop") {
+ setHovered(target);
+ return;
+ }
+ setHovered(null);
+ if (target) targets.get(target)?.onDrop(payload.paths);
+ });
+ // Only now can a target be claimed: before this the window-wide handlers
+ // would step aside for a listener that cannot deliver, losing the drop.
+ ready = true;
+
+ // Scale is a refinement; the devicePixelRatio seed holds until it lands.
+ // Failing here must not reset `listening`, or the next registration would
+ // stack a second drop listener and double every drop.
+ let scaleReported = false;
+ await currentWindow
+ .onScaleChanged(({ payload }) => {
+ scaleReported = true;
+ scaleFactor = payload.scaleFactor;
+ })
+ .catch(() => undefined);
+ const initialScale = await currentWindow.scaleFactor().catch(() => null);
+ if (!scaleReported && initialScale !== null) scaleFactor = initialScale;
+ })
+ .catch(() => {
+ listening = false;
+ });
+}
+
+// Start the install now rather than on first registration, so the async window
+// above is spent during app start instead of under the user's first drop.
+listen();
+
+export function registerNativeDropTarget(
+ element: HTMLElement,
+ handlers: NativeDropTargetHandlers,
+): () => void {
+ targets.set(element, handlers);
+ listen();
+ return () => {
+ if (hovered === element) hovered = null;
+ targets.delete(element);
+ };
+}
diff --git a/studio/frontend/src/features/native-intents/use-native-drop-target.ts b/studio/frontend/src/features/native-intents/use-native-drop-target.ts
new file mode 100644
index 00000000000..0c941435220
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/use-native-drop-target.ts
@@ -0,0 +1,31 @@
+// 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 { isTauri } from "@/lib/api-base";
+import { useEffect, useRef, useState } from "react";
+import {
+ type NativeDropTargetHandlers,
+ registerNativeDropTarget,
+} from "./native-drop-targets";
+
+/** Claim native drops landing on the returned ref's element. Without this they
+ * all go to the chat-wide handler, which is how a file dropped on a dialog's
+ * own drop zone ended up attached to the chat behind it. */
+export function useNativeDropTarget(
+ options: NativeDropTargetHandlers & { enabled?: boolean },
+): (element: HTMLElement | null) => void {
+ const { enabled = true } = options;
+ const [element, setElement] = useState<HTMLElement | null>(null);
+ const latest = useRef(options);
+ latest.current = options;
+
+ useEffect(() => {
+ if (!isTauri || !enabled || !element) return;
+ return registerNativeDropTarget(element, {
+ onDrop: (paths) => latest.current.onDrop(paths),
+ onDragOver: (over) => latest.current.onDragOver?.(over),
+ });
+ }, [element, enabled]);
+
+ return setElement;
+}
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 4238ea66b86..ddc3756c9a2 100644
--- a/studio/frontend/src/features/native-intents/use-native-drop.ts
+++ b/studio/frontend/src/features/native-intents/use-native-drop.ts
@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from "react";
import { toast } from "@/lib/toast";
import { registerNativeAttachmentPath, registerNativeModelPath } from "./api";
import { classifyDropPaths, SUPPORTED_DROP_HINT } from "./drop-paths";
+import { nativeDropTargetAt } from "./native-drop-targets";
import { useNativeIntentStore } from "./store";
import type { NativeIntent } from "./types";
@@ -172,6 +173,17 @@ async function registerDroppedAttachments(
};
}
+function sameDropState(
+ a: NativeModelDropState,
+ b: NativeModelDropState,
+): boolean {
+ if (a.status !== b.status) return false;
+ if (a.status === "valid" && b.status === "valid") return a.action === b.action;
+ if (a.status === "attach" && b.status === "attach")
+ return a.count === b.count && a.kind === b.kind;
+ return true;
+}
+
export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelDropState {
const { enabled = true } = options;
const addIntent = useNativeIntentStore((state) => state.addIntent);
@@ -186,20 +198,36 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModel
}
let disposed = false;
let unlisten: (() => void) | undefined;
+ // "over" carries no paths, so the ones announced on "enter" are what the
+ // overlay keeps reading as the cursor moves across the window.
+ let draggedPaths: string[] = [];
+ // Tauri repeats "over" per cursor move, so a fresh object each time would
+ // rerender ChatPage at drag frequency. Returning `prev` makes React bail out.
+ const publish = (next: NativeModelDropState) =>
+ setDropState((prev) => (sameDropState(prev, next) ? prev : next));
void import("@tauri-apps/api/window")
.then(({ getCurrentWindow }) => getCurrentWindow().onDragDropEvent(async (event) => {
const currentOptions = optionsRef.current;
+ if (event.payload.type === "leave") {
+ draggedPaths = [];
+ publish({ status: "idle" });
+ return;
+ }
if (event.payload.type === "enter") {
- setDropState(dropStateForPaths(event.payload.paths, currentOptions));
+ draggedPaths = event.payload.paths;
+ }
+ // A drop zone under the cursor owns this drop; leave it alone.
+ if (nativeDropTargetAt(event.payload.position)) {
+ publish({ status: "idle" });
return;
}
- if (event.payload.type === "leave") {
- setDropState({ status: "idle" });
+ if (event.payload.type !== "drop") {
+ publish(dropStateForPaths(draggedPaths, currentOptions));
return;
}
- if (event.payload.type !== "drop") return;
- setDropState({ status: "idle" });
+ draggedPaths = [];
+ publish({ status: "idle" });
const dropped = classifyDropPaths(event.payload.paths);
if (dropped.kind === "none") return;
if (dropped.kind === "unsupported") {
diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
index 23af39bb358..0eb04d237ce 100644
--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
@@ -1,28 +1,38 @@
// 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,
+ registerNativeAttachmentPath,
+ useNativeDropTarget,
+} from "@/features/native-intents";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { File02Icon, FolderAddIcon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { XIcon } from "lucide-react";
-import { useCallback, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import {
invalidateProjectSources,
uploadProjectDocument,
} from "../api/rag-api";
import { RAG_UPLOAD_ACCEPT } from "../types/rag";
+import {
+ addStagedSources,
+ EXPIRY_GRACE_MS,
+ isExpired,
+ nativeExpiryMs,
+ type StagedSource,
+ stagedFromFile,
+ stagedFromIntent,
+} from "./staged-source";
import { resolveVisionOverrides } from "./vision-overrides";
-/** A file picked before the project exists, held until create commits. */
-export interface StagedSource {
- id: string;
- file: File;
-}
+export type { StagedSource };
-// Client-side dedup key; backend dedups authoritatively by content hash.
-function fileSignature(file: File): string {
- return `${file.name}|${file.size}|${file.lastModified}`;
+function nativeFileName(path: string): string {
+ const segments = path.split(/[\\/]/);
+ return segments[segments.length - 1] || path;
}
function formatSize(bytes: number): string {
@@ -48,39 +58,10 @@ const ACCEPTED_EXTS = new Set(
// `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(file: File): boolean {
- const dot = file.name.lastIndexOf(".");
+function isSupported(name: string): boolean {
+ const dot = name.lastIndexOf(".");
if (dot <= 0) return false;
- return ACCEPTED_EXTS.has(file.name.slice(dot).toLowerCase());
-}
-
-/** Merge a selection into the staged list. Returns the names it would not take,
- * so the caller can say so once instead of dropping them silently. */
-function addStagedSources(
- staged: StagedSource[],
- incoming: FileList | File[],
-): { next: StagedSource[]; unsupported: string[]; duplicates: string[] } {
- const seen = new Set(staged.map((entry) => fileSignature(entry.file)));
- const next = [...staged];
- const unsupported: string[] = [];
- const duplicates: string[] = [];
- for (const file of Array.from(incoming)) {
- if (!isSupported(file)) {
- unsupported.push(file.name);
- continue;
- }
- const signature = fileSignature(file);
- if (seen.has(signature)) {
- duplicates.push(file.name);
- continue;
- }
- seen.add(signature);
- next.push({
- id: `staged_${Math.random().toString(36).slice(2)}`,
- file,
- });
- }
- return { next, unsupported, duplicates };
+ return ACCEPTED_EXTS.has(name.slice(dot).toLowerCase());
}
// Projects created with staged files, so the landing can open on Sources.
@@ -113,15 +94,27 @@ export async function uploadStagedSources(
const { ocr, caption } = resolveVisionOverrides();
const documentIds = new Set<string>();
const merged: string[] = [];
- for (const { file } of staged) {
+ for (const entry of staged) {
try {
- const result = await uploadProjectDocument(projectId, file, ocr, caption);
+ if (isExpired(entry, Date.now())) {
+ throw new Error("The drop expired. Add it again from the project.");
+ }
+ // Leases are short-lived, so mint one per file as its turn comes up.
+ const source =
+ entry.upload instanceof File
+ ? entry.upload
+ : {
+ nativePathLease: (
+ await consumeNativePathToken(entry.upload.nativeToken, "attach")
+ ).nativePathLease,
+ };
+ const result = await uploadProjectDocument(projectId, source, ocr, caption);
// Same bytes under another name: the backend hashes content, so this is
// the document already uploaded. Say so rather than imply a new source.
- if (documentIds.has(result.documentId)) merged.push(file.name);
+ if (documentIds.has(result.documentId)) merged.push(entry.name);
else documentIds.add(result.documentId);
} catch (error) {
- toast.error(`Couldn't upload ${file.name}`, {
+ toast.error(`Couldn't upload ${entry.name}`, {
description: error instanceof Error ? error.message : String(error),
});
}
@@ -142,20 +135,98 @@ export function ProjectSourceDropzone({
staged,
onChange,
disabled = false,
+ onPendingChange,
}: {
staged: StagedSource[];
onChange: (next: StagedSource[]) => void;
disabled?: boolean;
+ /** Native drops register asynchronously and reach `onChange` only once they
+ * settle. Create must wait, or it commits without the files just dropped. */
+ onPendingChange?: (pending: boolean) => void;
}) {
const inputRef = useRef<HTMLInputElement>(null);
// Count enter/leave pairs: children fire dragleave on the parent.
const dragDepth = useRef(0);
const [dragging, setDragging] = useState(false);
+ // Registering a native drop is async, so the props captured when it started
+ // are stale by the time it resolves. Merge against these instead.
+ const stagedRef = useRef(staged);
+ stagedRef.current = staged;
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+ // Radix unmounts the dialog content on close, so a cancel takes this
+ // component down before the reset below reaches it. Set on setup, or
+ // StrictMode's replayed cleanup would leave it false forever.
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+ // The dialog can stay mounted across close, so an unmount flag alone cannot
+ // see a cancel. Any array this component did not hand off is an external
+ // reset, and a drop still registering is no longer wanted. Identity, not
+ // length: `reset()` swaps in a fresh array even when it was already empty.
+ const generation = useRef(0);
+ const handedOff = useRef<StagedSource[] | null>(null);
+ useEffect(() => {
+ if (staged === handedOff.current) return;
+ handedOff.current = staged;
+ generation.current += 1;
+ }, [staged]);
- const addFiles = useCallback(
- (files: FileList | File[]) => {
- const { next, unsupported, duplicates } = addStagedSources(staged, files);
- if (next.length !== staged.length) onChange(next);
+ /** Hand a list to the owner without reading it back as an external reset. */
+ const commit = useCallback((next: StagedSource[]) => {
+ // The ref too, not just on the next render: two drops settling in one tick
+ // would both merge against the old list and the second would lose the first.
+ stagedRef.current = next;
+ handedOff.current = next;
+ onChangeRef.current(next);
+ }, []);
+
+ const onPendingChangeRef = useRef(onPendingChange);
+ onPendingChangeRef.current = onPendingChange;
+ const pending = useRef(0);
+ const addPending = useCallback((delta: number) => {
+ pending.current += delta;
+ // A drop from a previous mount must not answer for the live dropzone: its
+ // "done" would re-enable Create while the current drop is still pending.
+ if (!mounted.current) return;
+ onPendingChangeRef.current?.(pending.current > 0);
+ }, []);
+
+ // Prune desktop drops whose token TTL has lapsed, so Create never commits a
+ // project against sources the native layer has already pruned.
+ useEffect(() => {
+ const expiries = staged
+ .map(nativeExpiryMs)
+ .filter((value): value is number => value !== null);
+ if (expiries.length === 0) return;
+ const timer = setTimeout(
+ () => {
+ const current = stagedRef.current;
+ const kept = current.filter((entry) => !isExpired(entry, Date.now()));
+ if (kept.length === current.length) return;
+ commit(kept);
+ const dropped = current.length - kept.length;
+ toast.info(
+ dropped === 1
+ ? "A dropped file expired"
+ : `${dropped} dropped files expired`,
+ { description: "Drag them in again to add them." },
+ );
+ },
+ Math.max(0, Math.min(...expiries) - EXPIRY_GRACE_MS - Date.now()),
+ );
+ return () => clearTimeout(timer);
+ }, [staged, commit]);
+
+ const addSources = useCallback(
+ (incoming: StagedSource[], unsupported: string[]) => {
+ const current = stagedRef.current;
+ const { next, duplicates } = addStagedSources(current, incoming);
+ if (next.length !== current.length) commit(next);
if (unsupported.length > 0) {
toast.info(
unsupported.length === 1
@@ -174,9 +245,59 @@ export function ProjectSourceDropzone({
);
}
},
- [staged, onChange],
+ [commit],
+ );
+
+ 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),
+ );
+ },
+ [addSources],
+ );
+
+ 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);
+ // Per path, so one rejected file does not discard the rest of the drop.
+ addPending(1);
+ const settled = await Promise.allSettled(
+ supported.map(registerNativeAttachmentPath),
+ ).finally(() => addPending(-1));
+ // Cleared or closed while registering: let the tokens lapse rather than
+ // refill a draft the next dialog would open on.
+ if (!mounted.current || claimed !== generation.current) return;
+ const staged = settled.flatMap((result) =>
+ result.status === "fulfilled" ? [stagedFromIntent(result.value)] : [],
+ );
+ addSources(staged, unsupported);
+ const failed = settled.length - staged.length;
+ if (failed > 0) {
+ toast.error(
+ failed === 1 ? "Couldn't add a dropped file" : `Couldn't add ${failed} dropped files`,
+ );
+ }
+ },
+ [addSources, addPending],
);
+ // Stay claimed while disabled: unregistering hands the drop to the chat-wide
+ // handler, which would attach it to the chat behind the dialog.
+ const nativeDropRef = useNativeDropTarget({
+ onDrop: (paths) => {
+ if (disabled) return;
+ void addNativePaths(paths);
+ },
+ onDragOver: (over) => setDragging(over && !disabled),
+ });
+
const endDrag = useCallback(() => {
dragDepth.current = 0;
setDragging(false);
@@ -188,6 +309,7 @@ export function ProjectSourceDropzone({
{/* Panel is the drop target; the inner button owns the click so staged
rows can carry their own remove buttons. */}
<div
+ ref={nativeDropRef}
// preventDefault runs even while disabled: nothing else on the page
// cancels a file drop, so the browser would navigate to the file and
// kill the uploads in flight.
@@ -262,19 +384,19 @@ export function ProjectSourceDropzone({
/>
<span
className="min-w-0 flex-1 truncate text-ui-14 text-foreground"
- title={entry.file.name}
+ title={entry.name}
>
- {entry.file.name}
+ {entry.name}
</span>
<span className="shrink-0 text-ui-11 text-muted-foreground">
- {formatSize(entry.file.size)}
+ {formatSize(entry.size)}
</span>
<button
type="button"
- aria-label={`Remove ${entry.file.name}`}
+ aria-label={`Remove ${entry.name}`}
disabled={disabled}
onClick={() =>
- onChange(staged.filter((row) => row.id !== entry.id))
+ commit(staged.filter((row) => row.id !== entry.id))
}
className="shrink-0 rounded-full text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"
>
diff --git a/studio/frontend/src/features/rag/components/staged-source.ts b/studio/frontend/src/features/rag/components/staged-source.ts
new file mode 100644
index 00000000000..f0bcb6e31c3
--- /dev/null
+++ b/studio/frontend/src/features/rag/components/staged-source.ts
@@ -0,0 +1,88 @@
+// 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 "@/features/native-intents";
+
+/** A source picked before the project exists, held until create commits. A
+ * desktop drop has no File, only a path token the backend redeems at upload. */
+export interface StagedSource {
+ id: string;
+ name: string;
+ size: number;
+ modifiedMs: number;
+ dedupKey: string;
+ upload: File | { nativeToken: string; expiresAtMs: number };
+}
+
+// Client-side dedup key; backend dedups authoritatively by content hash.
+export function sourceSignature(entry: StagedSource): string {
+ return entry.dedupKey;
+}
+
+function stagedId(): string {
+ return `staged_${Math.random().toString(36).slice(2)}`;
+}
+
+export function stagedFromFile(file: File): StagedSource {
+ return {
+ id: stagedId(),
+ name: file.name,
+ size: file.size,
+ modifiedMs: file.lastModified,
+ dedupKey: `${file.name}|${file.size}|${file.lastModified}`,
+ upload: file,
+ };
+}
+
+export function stagedFromIntent(intent: NativeIntent): StagedSource {
+ const { displayLabel, expiresAtMs, modifiedMs, sizeBytes, token } =
+ intent.path;
+ return {
+ id: stagedId(),
+ name: displayLabel,
+ size: sizeBytes ?? 0,
+ modifiedMs: modifiedMs ?? 0,
+ // Coercing absent metadata to 0 would collapse every same-named file into
+ // one key, so fall back to the token, which is unique per registration.
+ dedupKey:
+ sizeBytes == null || modifiedMs == null
+ ? `token:${token}`
+ : `${displayLabel}|${sizeBytes}|${modifiedMs}`,
+ upload: { nativeToken: token, expiresAtMs },
+ };
+}
+
+/** Native path tokens are pruned on a fixed TTL, so a staged desktop drop can
+ * go stale while the dialog sits open. Treat a token about to lapse as already
+ * gone rather than redeeming it and failing after the project exists. */
+export const EXPIRY_GRACE_MS = 30_000;
+
+export function nativeExpiryMs(entry: StagedSource): number | null {
+ return entry.upload instanceof File ? null : entry.upload.expiresAtMs;
+}
+
+export function isExpired(entry: StagedSource, now: number): boolean {
+ const expiry = nativeExpiryMs(entry);
+ return expiry !== null && expiry - EXPIRY_GRACE_MS <= now;
+}
+
+/** Merge a selection into the staged list, reporting what it would not take so
+ * the caller can say so once instead of dropping it silently. */
+export function addStagedSources(
+ staged: StagedSource[],
+ incoming: StagedSource[],
+): { next: StagedSource[]; duplicates: string[] } {
+ const seen = new Set(staged.map(sourceSignature));
+ const next = [...staged];
+ const duplicates: string[] = [];
+ for (const entry of incoming) {
+ const signature = sourceSignature(entry);
+ if (seen.has(signature)) {
+ duplicates.push(entry.name);
+ continue;
+ }
+ seen.add(signature);
+ next.push(entry);
+ }
+ return { next, duplicates };
+}
diff --git a/studio/frontend/src/features/studio/sections/use-dataset-uploads.ts b/studio/frontend/src/features/studio/sections/use-dataset-uploads.ts
index f6b976a3341..7d7b6d1e838 100644
--- a/studio/frontend/src/features/studio/sections/use-dataset-uploads.ts
+++ b/studio/frontend/src/features/studio/sections/use-dataset-uploads.ts
@@ -4,6 +4,7 @@
import { bumpInventoryVersion } from "@/features/hub";
import {
consumeNativePathToken,
+ nativeDropTargetAt,
registerNativeDatasetPath,
} from "@/features/native-intents";
import {
@@ -316,6 +317,10 @@ export function useDatasetUploads() {
stopScaleChanged?.();
};
const hitsTarget = (position: { x: number; y: number }) => {
+ // A registered drop zone owns this position outright: bounds alone would
+ // also fire this listener for a dialog opened over the upload button, so
+ // the same file would upload here and stage in the dialog.
+ if (nativeDropTargetAt(position) !== null) return false;
const target = document.getElementById(datasetDropTargetId);
return (
target != null &&
diff --git a/studio/frontend/src/features/training/lib/native-dataset-drop.ts b/studio/frontend/src/features/training/lib/native-dataset-drop.ts
index f416e4b5716..0362e572ffd 100644
--- a/studio/frontend/src/features/training/lib/native-dataset-drop.ts
+++ b/studio/frontend/src/features/training/lib/native-dataset-drop.ts
@@ -1,6 +1,8 @@
// 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 { nativeDropPointToCss } from "../../native-intents/native-drop-position.ts";
+
export const TRAINING_DATASET_UPLOAD_EXTENSIONS = [
".csv",
".jsonl",
@@ -79,10 +81,7 @@ export function nativeDropPositionHitsBounds(
scaleFactor: number,
bounds: { left: number; right: number; top: number; bottom: number },
): boolean {
- const scale =
- Number.isFinite(scaleFactor) && scaleFactor > 0 ? scaleFactor : 1;
- const x = position.x / scale;
- const y = position.y / scale;
+ const { x, y } = nativeDropPointToCss(position, scaleFactor);
return (
x >= bounds.left &&
x <= bounds.right &&
diff --git a/studio/frontend/tests/helpers/tauri-window-resolver.mjs b/studio/frontend/tests/helpers/tauri-window-resolver.mjs
new file mode 100644
index 00000000000..872635ccb25
--- /dev/null
+++ b/studio/frontend/tests/helpers/tauri-window-resolver.mjs
@@ -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
+
+// bundler-resolver's two rules, plus "@tauri-apps/api/window" -> a local stub,
+// because the real package only resolves inside a Tauri webview.
+import { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SRC = fileURLToPath(new URL("../../src/", import.meta.url));
+const WINDOW_STUB = new URL("./tauri-window-stub.mjs", import.meta.url).href;
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) return pathToFileURL(candidate).href;
+ }
+ return null;
+}
+
+export function resolve(specifier, context, next) {
+ if (specifier === "@tauri-apps/api/window") {
+ return next(WINDOW_STUB, context);
+ }
+ if (specifier.startsWith("@/")) {
+ const resolved = firstExisting(SRC + specifier.slice(2));
+ return next(resolved ?? specifier, context);
+ }
+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {
+ const resolved = firstExisting(
+ fileURLToPath(new URL(specifier, context.parentURL)),
+ );
+ if (resolved) return next(resolved, context);
+ }
+ return next(specifier, context);
+}
diff --git a/studio/frontend/tests/helpers/tauri-window-stub.mjs b/studio/frontend/tests/helpers/tauri-window-stub.mjs
new file mode 100644
index 00000000000..086ad825ad7
--- /dev/null
+++ b/studio/frontend/tests/helpers/tauri-window-stub.mjs
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Stands in for @tauri-apps/api/window, which only resolves inside a Tauri
+// webview. Control lives on globalThis so a test can hold the drag-drop install
+// unresolved and inspect the window before it completes.
+const control = (globalThis.__TAURI_WINDOW_STUB__ ??= {});
+
+export function getCurrentWindow() {
+ return {
+ onDragDropEvent: (handler) =>
+ new Promise((resolve) => {
+ control.deliver = handler;
+ control.installed = () => resolve(() => undefined);
+ }),
+ onScaleChanged: async () => () => undefined,
+ scaleFactor: async () => 1,
+ };
+}
diff --git a/studio/frontend/tests/native-drop-target-readiness.test.ts b/studio/frontend/tests/native-drop-target-readiness.test.ts
new file mode 100644
index 00000000000..db6d7d0b88b
--- /dev/null
+++ b/studio/frontend/tests/native-drop-target-readiness.test.ts
@@ -0,0 +1,73 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+
+class FakeElement {
+ parentElement: FakeElement | null = null;
+}
+
+const zone = new FakeElement();
+// The stub hands these back: `installed` settles the drag-drop install the
+// module awaits, `deliver` is the callback it registered.
+const control: {
+ installed?: () => void;
+ deliver?: (event: {
+ payload: { type: string; position: { x: number; y: number }; paths: string[] };
+ }) => void;
+} = {};
+
+Object.assign(globalThis, {
+ __TAURI_WINDOW_STUB__: control,
+ HTMLElement: FakeElement,
+ // lib/api-base reads this to decide it is running inside the desktop app.
+ window: {
+ __TAURI_INTERNALS__: {},
+ devicePixelRatio: 1,
+ location: { protocol: "http:" },
+ },
+ document: { elementFromPoint: () => zone },
+});
+
+register("./helpers/tauri-window-resolver.mjs", import.meta.url);
+
+const { nativeDropTargetAt, registerNativeDropTarget } = await import(
+ "../src/features/native-intents/native-drop-targets.ts"
+);
+
+/** The install runs through a dynamic import, so no fixed number of ticks says
+ * it is done. Wait for the condition itself. */
+async function until(condition: () => boolean, what: string) {
+ for (let i = 0; i < 500 && !condition(); i += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ assert.ok(condition(), `timed out waiting for ${what}`);
+}
+
+const dropped: string[][] = [];
+registerNativeDropTarget(zone as unknown as HTMLElement, {
+ onDrop: (paths) => dropped.push(paths),
+});
+
+// Registration is synchronous but the listener behind it is not. Claiming the
+// element early would make the chat-wide handler step aside for nothing, and
+// the drop would land nowhere at all.
+test("a target is not claimed until its listener is installed", async () => {
+ await until(() => control.installed !== undefined, "the drag-drop install");
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), null);
+});
+
+test("the same target is claimed once the listener is installed", async () => {
+ control.installed?.();
+ await until(
+ () => nativeDropTargetAt({ x: 10, y: 10 }) !== null,
+ "the target to be claimed",
+ );
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), zone as unknown as HTMLElement);
+ control.deliver?.({
+ payload: { type: "drop", position: { x: 10, y: 10 }, paths: ["/tmp/a.pdf"] },
+ });
+ assert.deepEqual(dropped, [["/tmp/a.pdf"]]);
+});
diff --git a/studio/frontend/tests/native-drop-targets.test.ts b/studio/frontend/tests/native-drop-targets.test.ts
new file mode 100644
index 00000000000..328cd013d9f
--- /dev/null
+++ b/studio/frontend/tests/native-drop-targets.test.ts
@@ -0,0 +1,213 @@
+// 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 { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+class FakeElement {
+ parentElement: FakeElement | null = null;
+}
+
+let hit: FakeElement | null = null;
+
+Object.assign(globalThis, {
+ HTMLElement: FakeElement,
+ // devicePixelRatio 2: a physical drop position is twice the CSS position the
+ // DOM is hit-tested in, which is the conversion this module owns.
+ window: { devicePixelRatio: 2, location: { protocol: "http:" } },
+ document: { elementFromPoint: () => hit },
+});
+
+const { nativeDropTargetAt, registerNativeDropTarget } = await import(
+ "../src/features/native-intents/native-drop-targets.ts"
+);
+
+const asElement = (value: FakeElement) => value as unknown as HTMLElement;
+
+test("no registered target means the window handler keeps the drop", () => {
+ hit = new FakeElement();
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), null);
+});
+
+test("a drop over a registered element resolves to it", () => {
+ const zone = new FakeElement();
+ hit = zone;
+ const unregister = registerNativeDropTarget(asElement(zone), {
+ onDrop: () => undefined,
+ });
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), asElement(zone));
+ unregister();
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), null);
+});
+
+test("a drop on a child resolves to its registered ancestor", () => {
+ const zone = new FakeElement();
+ const child = new FakeElement();
+ child.parentElement = zone;
+ hit = child;
+ const unregister = registerNativeDropTarget(asElement(zone), {
+ onDrop: () => undefined,
+ });
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), asElement(zone));
+ unregister();
+});
+
+// The bug: nested zones both matched by bounds, so the outer one could win and
+// swallow a drop meant for the dialog sitting inside it.
+test("the innermost registered ancestor wins", () => {
+ const outer = new FakeElement();
+ const inner = new FakeElement();
+ const child = new FakeElement();
+ inner.parentElement = outer;
+ child.parentElement = inner;
+ hit = child;
+ const stopOuter = registerNativeDropTarget(asElement(outer), {
+ onDrop: () => undefined,
+ });
+ const stopInner = registerNativeDropTarget(asElement(inner), {
+ onDrop: () => undefined,
+ });
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), asElement(inner));
+ stopInner();
+ assert.equal(nativeDropTargetAt({ x: 10, y: 10 }), asElement(outer));
+ stopOuter();
+});
+
+// wry reports CSS pixels on macOS (NSView points) and GTK (widget coords), and
+// device pixels only on WebView2. Scaling everything by devicePixelRatio put
+// every hit test at half the real position on a Retina Mac, so nothing matched.
+function pointSeenFor(userAgent: string): { x: number; y: number } {
+ const zone = new FakeElement();
+ const seen: Array<{ x: number; y: number }> = [];
+ hit = zone;
+ Object.defineProperty(globalThis, "navigator", {
+ value: { userAgent },
+ configurable: true,
+ });
+ Object.assign(globalThis.document, {
+ elementFromPoint: (x: number, y: number) => {
+ seen.push({ x, y });
+ return zone;
+ },
+ });
+ const unregister = registerNativeDropTarget(asElement(zone), {
+ onDrop: () => undefined,
+ });
+ nativeDropTargetAt({ x: 120, y: 80 });
+ unregister();
+ return seen[0];
+}
+
+test("a macOS drop position is hit-tested as-is", () => {
+ assert.deepEqual(pointSeenFor("Mozilla/5.0 (Macintosh; Intel Mac OS X)"), {
+ x: 120,
+ y: 80,
+ });
+});
+
+test("a Linux drop position is hit-tested as-is", () => {
+ assert.deepEqual(pointSeenFor("Mozilla/5.0 (X11; Linux x86_64)"), {
+ x: 120,
+ y: 80,
+ });
+});
+
+test("a Windows drop position is divided by the scale factor", () => {
+ assert.deepEqual(pointSeenFor("Mozilla/5.0 (Windows NT 10.0; Win64)"), {
+ x: 60,
+ y: 40,
+ });
+});
+
+// Webview zoom moves devicePixelRatio either side of the monitor scale, and
+// elementFromPoint wants CSS pixels. Zoomed in first, then out.
+for (const ratio of [3, 1.5]) {
+ test(`a Windows drop position follows a devicePixelRatio of ${ratio}`, () => {
+ globalThis.window.devicePixelRatio = ratio;
+ try {
+ assert.deepEqual(pointSeenFor("Mozilla/5.0 (Windows NT 10.0; Win64)"), {
+ x: 120 / ratio,
+ y: 80 / ratio,
+ });
+ } finally {
+ globalThis.window.devicePixelRatio = 2;
+ }
+ });
+}
+
+// The chat-wide handler has to ask before acting, or a drop aimed at a dialog's
+// own zone lands as a chat attachment behind it.
+test("the chat drop handler defers to a registered target", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/native-intents/use-native-drop.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /if \(nativeDropTargetAt\(event\.payload\.position\)\) \{\s*publish\(\{ status: "idle" \}\);\s*return;/,
+ );
+});
+
+test("the shared image picker owns native drops and ignores stale reads", async () => {
+ const source = await readFile(
+ new URL("../src/components/image-dropzone.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(source, /const nativeDropRef = useNativeDropTarget\(\{/);
+ assert.match(source, /ref=\{nativeDropRef\}/);
+ assert.match(source, /registerNativeAttachmentPath\(path\)/);
+ assert.match(source, /readNativeAttachmentFile\(intent\.path\.token\)/);
+ // A read outliving the picker would land on whoever holds `onChange` now, and
+ // the native policy takes fewer formats than the picker's own image/*.
+ assert.match(source, /if \(!mounted\.current \|\| claimed !== selection\.current\) return;/);
+ assert.match(source, /NATIVE_IMAGE_EXTS\.includes\(/);
+ // Index-keyed reference slots keep the picker mounted when one is removed.
+ assert.match(source, /if \(seen\.current === value\) return;\s*seen\.current = value;\s*selection\.current \+= 1;/);
+});
+
+// The picker rejects a format the native side would refuse anyway, so the two
+// lists have to stay in step or a droppable image starts being turned away.
+test("the picker's droppable formats match the native path policy", async () => {
+ const picker = await readFile(
+ new URL("../src/components/image-dropzone.tsx", import.meta.url),
+ "utf8",
+ );
+ const rust = await readFile(
+ new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),
+ "utf8",
+ );
+ const listed = (source: string, pattern: RegExp) =>
+ [...(source.match(pattern)?.[1].matchAll(/"([a-z0-9]+)"/g) ?? [])]
+ .map((match) => match[1])
+ .sort();
+
+ assert.deepEqual(
+ listed(picker, /NATIVE_IMAGE_EXTS\s*=\s*\[([^\]]+)\]/),
+ listed(rust, /IMAGE_ATTACHMENT_EXTS:\s*&\[&str\]\s*=\s*&\[([^\]]+)\]/),
+ );
+});
+
+// Tauri repeats "over" for every cursor move, and useNativeModelDrop sits in
+// ChatPage, so an unconditional setState there rerenders the page per event.
+test("the chat drop overlay only publishes a changed state", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/native-intents/use-native-drop.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /setDropState\(\(prev\) => \(sameDropState\(prev, next\) \? prev : next\)\)/,
+ );
+ assert.doesNotMatch(source, /payload\.type !== "drop"\) \{\s*setDropState\(/);
+});
diff --git a/studio/frontend/tests/native-training-dataset-drop.test.ts b/studio/frontend/tests/native-training-dataset-drop.test.ts
index afccdb17f7f..0f45820a2ca 100644
--- a/studio/frontend/tests/native-training-dataset-drop.test.ts
+++ b/studio/frontend/tests/native-training-dataset-drop.test.ts
@@ -111,7 +111,14 @@ test("classifies native drops before truncating long display filenames", () => {
});
});
-test("hit testing converts native physical coordinates to CSS pixels", () => {
+// Only WebView2 reports a device-pixel drop position; macOS and GTK already
+// report CSS pixels, so scaling those halved every hit test on a HiDPI display
+// and the zone never matched.
+test("hit testing scales a Windows drop position to CSS pixels", () => {
+ Object.defineProperty(globalThis, "navigator", {
+ value: { userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64)" },
+ configurable: true,
+ });
const bounds = { left: 100, right: 300, top: 50, bottom: 150 };
assert.equal(
nativeDropPositionHitsBounds({ x: 400, y: 200 }, 2, bounds),
@@ -123,6 +130,22 @@ test("hit testing converts native physical coordinates to CSS pixels", () => {
);
});
+test("hit testing takes a macOS drop position as-is", () => {
+ Object.defineProperty(globalThis, "navigator", {
+ value: { userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X)" },
+ configurable: true,
+ });
+ const bounds = { left: 100, right: 300, top: 50, bottom: 150 };
+ assert.equal(
+ nativeDropPositionHitsBounds({ x: 200, y: 100 }, 2, bounds),
+ true,
+ );
+ assert.equal(
+ nativeDropPositionHitsBounds({ x: 400, y: 200 }, 2, bounds),
+ false,
+ );
+});
+
test("native dataset drops track runtime window scale changes", () => {
const source = readFileSync(
new URL(
diff --git a/studio/frontend/tests/overlay-scrollbar-gutter.test.ts b/studio/frontend/tests/overlay-scrollbar-gutter.test.ts
index a0b0579db12..53b753092ed 100644
--- a/studio/frontend/tests/overlay-scrollbar-gutter.test.ts
+++ b/studio/frontend/tests/overlay-scrollbar-gutter.test.ts
@@ -293,6 +293,6 @@ test("right-edge action lists reserve the gutter they publish", async () => {
// Keep staged-source remove actions inside the gutter.
assert.match(
projectSourceDropzone,
- /<ul className="[^"]*overlay-scrollbar-gutter[^"]*max-h-52[^"]*overflow-y-auto[^"]*">[\s\S]{0,1000}aria-label={`Remove \${entry\.file\.name}`}/,
+ /<ul className="[^"]*overlay-scrollbar-gutter[^"]*max-h-52[^"]*overflow-y-auto[^"]*">[\s\S]{0,1000}aria-label={`Remove \${entry\.name}`}/,
);
});
diff --git a/studio/frontend/tests/staged-source-dedup.test.ts b/studio/frontend/tests/staged-source-dedup.test.ts
new file mode 100644
index 00000000000..f57f753a0b8
--- /dev/null
+++ b/studio/frontend/tests/staged-source-dedup.test.ts
@@ -0,0 +1,75 @@
+// 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 {
+ addStagedSources,
+ EXPIRY_GRACE_MS,
+ isExpired,
+ stagedFromIntent,
+} from "../src/features/rag/components/staged-source.ts";
+
+const intent = (
+ token: string,
+ displayLabel: string,
+ meta: { sizeBytes?: number | null; modifiedMs?: number | null } = {},
+) =>
+ ({
+ id: token,
+ kind: "attachment",
+ sourceKind: "drop",
+ displayLabel,
+ path: {
+ token,
+ kind: "attachment",
+ displayLabel,
+ allowedOperations: ["attach"],
+ expiresAtMs: 15 * 60_000,
+ sizeBytes: meta.sizeBytes,
+ modifiedMs: meta.modifiedMs,
+ },
+ }) as unknown as Parameters<typeof stagedFromIntent>[0];
+
+// The bug: absent size/mtime both defaulted to 0, so every same-named file
+// collapsed onto one signature and the second was rejected as a duplicate.
+test("two same-named drops without metadata both stage", () => {
+ const first = stagedFromIntent(intent("tok-a", "notes.pdf"));
+ const second = stagedFromIntent(intent("tok-b", "notes.pdf"));
+ const { next, duplicates } = addStagedSources([first], [second]);
+ assert.equal(next.length, 2);
+ assert.deepEqual(duplicates, []);
+});
+
+test("a drop missing only its mtime is still distinguishable", () => {
+ const first = stagedFromIntent(intent("tok-a", "notes.pdf", { sizeBytes: 12 }));
+ const second = stagedFromIntent(intent("tok-b", "notes.pdf", { sizeBytes: 12 }));
+ assert.equal(addStagedSources([first], [second]).next.length, 2);
+});
+
+test("complete metadata still dedups a genuine repeat", () => {
+ const meta = { sizeBytes: 12, modifiedMs: 99 };
+ const first = stagedFromIntent(intent("tok-a", "notes.pdf", meta));
+ const second = stagedFromIntent(intent("tok-b", "notes.pdf", meta));
+ const { next, duplicates } = addStagedSources([first], [second]);
+ assert.equal(next.length, 1);
+ assert.deepEqual(duplicates, ["notes.pdf"]);
+});
+
+// The bug: staged native tokens outlive the native layer's TTL, so Create
+// redeemed a pruned token and failed after the project already existed.
+test("a token past its TTL reads as expired", () => {
+ const entry = stagedFromIntent(intent("tok-a", "notes.pdf"));
+ assert.equal(isExpired(entry, 15 * 60_000 + 1), true);
+});
+
+test("a token inside the grace window is already treated as gone", () => {
+ const entry = stagedFromIntent(intent("tok-a", "notes.pdf"));
+ assert.equal(isExpired(entry, 15 * 60_000 - EXPIRY_GRACE_MS + 1), true);
+});
+
+test("a token with time left is kept", () => {
+ const entry = stagedFromIntent(intent("tok-a", "notes.pdf"));
+ assert.equal(isExpired(entry, 60_000), false);
+});