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.

Fix desktop image drops for chat attachments (#7982)

Souravrajvi0f8497dc32848
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index bc6c396552b..dc9199cfe16 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -88,6 +88,12 @@ import {
DeepResearchComposerButton,
DeepResearchWebsiteAccessDialog,
} from "@/features/chat/components/deep-research-composer-button";
+import {
+ type NativeIntent,
+ useNativeAttachmentTargetKey,
+ useNativeIntentStore,
+} from "@/features/native-intents";
+import { nativeAttachmentIntentToFile } from "@/features/native-intents/native-attachment-file";
import { cancelResearchRun } from "@/features/chat/api/research-api";
import {
ingestResearchUpdate,
@@ -2145,6 +2151,173 @@ const Composer: FC<{
const hasPendingAudio = useChatRuntimeStore((s) =>
Boolean(s.pendingAudioName),
);
+ const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();
+ const nativeAttachmentTargetKeyRef = useRef(nativeAttachmentTargetKey);
+ nativeAttachmentTargetKeyRef.current = nativeAttachmentTargetKey;
+ const hasPendingImageAttachments = useNativeIntentStore((s) =>
+ Boolean(
+ nativeAttachmentTargetKey &&
+ (s.pendingImageAttachments[nativeAttachmentTargetKey]?.length ?? 0) > 0,
+ ),
+ );
+ const registeringImageDrops = useNativeIntentStore(
+ (s) => s.registeringImageDrops > 0,
+ );
+ const [materializingDroppedImages, setMaterializingDroppedImages] =
+ useState(false);
+ // A parked send must not fire on a failed drop: the user is owed the toast and
+ // their text, not a send of the text alone. Assigned below, once the callback exists.
+ const cancelQueuedSendRef = useRef<(() => void) | null>(null);
+ // Which composer is mounted, for deciding where a drain puts work back.
+ const composerIdentityRef = useRef("");
+ const imageDropFailures = useNativeIntentStore(
+ (s) => (nativeAttachmentTargetKey ? s.imageDropFailures[nativeAttachmentTargetKey] : 0) ?? 0,
+ );
+ const seenImageDropFailuresRef = useRef(imageDropFailures);
+ // Registration fails before an intent exists, so the drain never sees it.
+ // Cancel here or the parked send goes out with the text alone.
+ useEffect(() => {
+ if (seenImageDropFailuresRef.current === imageDropFailures) return;
+ seenImageDropFailuresRef.current = imageDropFailures;
+ cancelQueuedSendRef.current?.();
+ }, [imageDropFailures]);
+ useEffect(() => {
+ if (!nativeAttachmentTargetKey) {
+ return;
+ }
+ const targetKey = nativeAttachmentTargetKey;
+ const identityAtSetup = composerIdentityRef.current;
+ useNativeIntentStore
+ .getState()
+ .claimImageAttachments(identityAtSetup, targetKey);
+ let disposed = false;
+ let draining = false;
+
+ // A fresh chat re-keys from "single:new" to its thread id under the same
+ // composer, so follow it; a real thread switch keeps the original target.
+ const stillThisComposer = () =>
+ composerIdentityRef.current === identityAtSetup;
+ const requeueKey = () =>
+ stillThisComposer()
+ ? (nativeAttachmentTargetKeyRef.current ?? targetKey)
+ : targetKey;
+ // A fresh chat persisting remounts this composer, so the key it moves to is
+ // not visible here. Tag the batch instead; the next instance claims it.
+ const requeue = (intents: NativeIntent[]) => {
+ const key = requeueKey();
+ const store = useNativeIntentStore.getState();
+ store.addImageAttachments(key, intents);
+ store.noteImageDropOwner(key, identityAtSetup);
+ };
+
+ const drainPendingImages = async () => {
+ if (disposed || draining) {
+ return;
+ }
+ draining = true;
+ setMaterializingDroppedImages(true);
+ let readFailures = 0;
+ let lastReadError: unknown;
+ try {
+ while (!disposed) {
+ const intents = useNativeIntentStore
+ .getState()
+ .takeImageAttachments(targetKey);
+ if (intents.length === 0) {
+ break;
+ }
+ for (let index = 0; index < intents.length; index += 1) {
+ if (disposed) {
+ requeue(intents.slice(index));
+ return;
+ }
+ const intent = intents[index]!;
+ let file: File;
+ try {
+ file = await nativeAttachmentIntentToFile(intent);
+ } catch (error) {
+ // Report once below rather than one toast per file: a whole batch
+ // can go unreadable at once (volume ejected, tokens expired).
+ readFailures += 1;
+ lastReadError = error;
+ continue;
+ }
+ if (
+ disposed ||
+ nativeAttachmentTargetKeyRef.current !== targetKey
+ ) {
+ requeue(intents.slice(index));
+ return;
+ }
+ try {
+ await aui.composer().addAttachment(file);
+ } catch {
+ // Chat-wide, not per file (no vision model, or none loaded). The
+ // adapter toasted, and the rest would fail alike: stop quietly.
+ if (stillThisComposer()) cancelQueuedSendRef.current?.();
+ return;
+ }
+ }
+ }
+ } finally {
+ draining = false;
+ if (readFailures > 0) {
+ toast.error("Could not attach dropped images", {
+ description:
+ lastReadError instanceof Error
+ ? lastReadError.message
+ : String(lastReadError),
+ });
+ // A re-key still owns the parked send; a real thread switch does not.
+ if (stillThisComposer()) cancelQueuedSendRef.current?.();
+ }
+ // A drain for a target the composer has already left must not touch the
+ // flag: cleanup cleared it, and the live target may have set it again.
+ if (disposed) {
+ return;
+ }
+ const pending =
+ useNativeIntentStore.getState().pendingImageAttachments[targetKey]
+ ?.length ?? 0;
+ if (pending > 0) {
+ void drainPendingImages();
+ } else {
+ setMaterializingDroppedImages(false);
+ }
+ }
+ };
+
+ const unsubscribe = useNativeIntentStore.subscribe((state) => {
+ // The predecessor's requeue can land after the claim at setup, so keep
+ // watching rather than claiming once.
+ const orphaned = Object.entries(state.imageDropOwners).some(
+ ([key, owner]) => owner === identityAtSetup && key !== targetKey,
+ );
+ if (orphaned) {
+ useNativeIntentStore
+ .getState()
+ .claimImageAttachments(identityAtSetup, targetKey);
+ return;
+ }
+ const pending =
+ state.pendingImageAttachments[targetKey]?.length ?? 0;
+ if (pending > 0) {
+ void drainPendingImages();
+ }
+ });
+
+ void drainPendingImages();
+
+ return () => {
+ disposed = true;
+ setMaterializingDroppedImages(false);
+ unsubscribe();
+ };
+ }, [nativeAttachmentTargetKey, aui]);
+ const hasMaterializingImageAttachments =
+ registeringImageDrops ||
+ hasPendingImageAttachments ||
+ materializingDroppedImages;
const threadIsRunning = useAuiState(({ thread }) => thread.isRunning);
const threadListItemId = useAuiState(
({ threadListItem }) => threadListItem.id,
@@ -2184,6 +2357,7 @@ const Composer: FC<{
!hasPendingAudio &&
!isComposing &&
!hasPendingAttachments &&
+ !hasMaterializingImageAttachments &&
!disabled &&
!overlay;
@@ -2654,28 +2828,75 @@ const Composer: FC<{
}
}, []);
+ // Declared here because cancelQueuedSend has to clear the dictation hold too.
+ const sendAfterDictationRef = useRef(false);
+ // Composer text while a send waits on dictationBlocked, so an edit can drop it.
+ const heldTextRef = useRef<string | null>(null);
+
const cancelQueuedSend = useCallback(() => {
pendingSendRef.current = false;
setPendingSend(false);
+ // A dictation send held behind the same block would otherwise fire alone.
+ sendAfterDictationRef.current = false;
+ heldTextRef.current = null;
dismissWaitToast();
}, [dismissWaitToast]);
+ cancelQueuedSendRef.current = cancelQueuedSend;
+
+ const enqueueSend = useCallback(
+ (waitingOn: "indexing" | "images" = "indexing") => {
+ if (pendingSendRef.current) return;
+ pendingSendRef.current = true;
+ setPendingSend(true);
+ const title =
+ waitingOn === "images"
+ ? "Waiting for dropped images"
+ : "Waiting for documents to finish indexing";
+ waitToastRef.current = toast(title, {
+ description: "Your message will send automatically once they are ready.",
+ duration: Infinity,
+ cancel: { label: "Cancel", onClick: cancelQueuedSend },
+ });
+ },
+ [cancelQueuedSend],
+ );
- const enqueueSend = useCallback(() => {
- if (pendingSendRef.current) return;
- pendingSendRef.current = true;
- setPendingSend(true);
- waitToastRef.current = toast("Waiting for documents to finish indexing", {
- description:
- "Your message will send automatically once indexing finishes.",
- duration: Infinity,
- cancel: { label: "Cancel", onClick: cancelQueuedSend },
- });
- }, [cancelQueuedSend]);
+ // A materializing image is a wait, not a refusal: park the send. Both gates
+ // route through here so they cannot disagree on what is recoverable.
+ const parkIfWaitingOnImages = useCallback(() => {
+ if (
+ disabled ||
+ overlay ||
+ !hasMaterializingImageAttachments ||
+ !hasSendableContent ||
+ isComposingRef.current ||
+ hasPendingAttachments
+ ) {
+ return;
+ }
+ enqueueSend("images");
+ }, [
+ disabled,
+ overlay,
+ hasMaterializingImageAttachments,
+ hasSendableContent,
+ hasPendingAttachments,
+ isComposingRef,
+ enqueueSend,
+ ]);
const shouldBlockSend = useCallback(
() =>
- !hasSendableContent || isComposingRef.current || hasPendingAttachments,
- [hasPendingAttachments, hasSendableContent, isComposingRef],
+ !hasSendableContent ||
+ isComposingRef.current ||
+ hasPendingAttachments ||
+ hasMaterializingImageAttachments,
+ [
+ hasMaterializingImageAttachments,
+ hasPendingAttachments,
+ hasSendableContent,
+ isComposingRef,
+ ],
);
const sendReservedComposer = useCallback(() => {
@@ -2726,6 +2947,7 @@ const Composer: FC<{
(event: { preventDefault: () => void }) => {
if (disabled || shouldBlockSend()) {
event.preventDefault();
+ parkIfWaitingOnImages();
return true;
}
if (indexingActive && !overlay) {
@@ -2735,13 +2957,31 @@ const Composer: FC<{
}
return false;
},
- [disabled, shouldBlockSend, indexingActive, overlay, enqueueSend],
+ [
+ disabled,
+ shouldBlockSend,
+ indexingActive,
+ overlay,
+ enqueueSend,
+ parkIfWaitingOnImages,
+ ],
);
// Fire the parked send once indexing clears, unless the user emptied the
- // composer while waiting (then drop it quietly).
+ // composer while waiting (then drop it quietly). An image dropped after the
+ // send was parked has to land first, or indexing finishing early sends the
+ // text without it and the image attaches to the next draft.
useEffect(() => {
- if (!pendingSend || indexingActive) return;
+ // pendingSendRef too: a cancel earlier in this same commit has already
+ // dropped the send, while `pendingSend` still reads true from this render.
+ if (
+ !pendingSend ||
+ !pendingSendRef.current ||
+ indexingActive ||
+ hasMaterializingImageAttachments
+ ) {
+ return;
+ }
const { text, attachments } = aui.composer().getState();
pendingSendRef.current = false;
setPendingSend(false);
@@ -2753,6 +2993,7 @@ const Composer: FC<{
}, [
pendingSend,
indexingActive,
+ hasMaterializingImageAttachments,
aui,
clearStoredDraft,
dismissWaitToast,
@@ -2772,7 +3013,6 @@ const Composer: FC<{
// lands. Going through the form keeps queueing, indexing holds and draft
// clearing identical to a typed send.
const formRef = useRef<HTMLFormElement | null>(null);
- const sendAfterDictationRef = useRef(false);
const dictationBaseTextRef = useRef("");
const dictationComposerRef = useRef("");
// Thread switches reuse this composer, so the send has to know where it
@@ -2780,6 +3020,7 @@ const Composer: FC<{
// id, not referenceThreadId: that one moves from null to the remote id when
// a new chat first persists, which is the same composer.
const composerIdentity = threadListItemId ?? "";
+ composerIdentityRef.current = composerIdentity;
const sendAfterDictation = useCallback(() => {
sendAfterDictationRef.current = true;
dictationComposerRef.current = composerIdentity;
@@ -2790,7 +3031,7 @@ const Composer: FC<{
// a pending send when the composer changes under it after the press.
const dictationBlocked = dictationSendBlocked({
composerDisabled: Boolean(disabled),
- uploading: hasPendingAttachments,
+ uploading: hasPendingAttachments || hasMaterializingImageAttachments,
researchActive: isResearchActive,
runActive: threadIsRunning || promptQueueActive,
queueDisabled: Boolean(disableQueue),
@@ -2799,8 +3040,6 @@ const Composer: FC<{
hasPendingAudio,
});
const wasDictatingRef = useRef(false);
- // Composer text while a send waits on dictationBlocked, so an edit can drop it.
- const heldTextRef = useRef<string | null>(null);
useEffect(() => {
if (isDictating) {
if (wasDictatingRef.current) return;
@@ -2867,6 +3106,7 @@ const Composer: FC<{
}
if (disabled || shouldBlockSend()) {
event.preventDefault();
+ parkIfWaitingOnImages();
return;
}
@@ -3000,6 +3240,7 @@ const Composer: FC<{
interceptSend,
isResearchActive,
overlay,
+ parkIfWaitingOnImages,
promptQueueActive,
promptQueueThreadIds,
preStreamThreadIds,
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index d2621473b66..4941ef7fbd9 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -2598,14 +2598,22 @@ export function ChatPage({
},
[artifactViewKey],
);
+ const handleNativeImageDrop = useCallback(
+ (intents: NativeIntent[]) => {
+ useNativeIntentStore.getState().addImageAttachments(artifactViewKey, intents);
+ },
+ [artifactViewKey],
+ );
const nativeModelDropState = useNativeModelDrop({
enabled: active && view.mode === "single",
attachmentScope,
+ attachmentTargetKey: artifactViewKey,
nativePathLeasesSupported,
hasActiveModel,
isModelLoading: Boolean(loadingModel) || modelLoading,
onAutoLoad: handleNativeModelDropAutoLoad,
onAttach: handleNativeAttachmentDrop,
+ onAttachImages: handleNativeImageDrop,
});
const handleCheckpointChange = useCallback(
diff --git a/studio/frontend/src/features/native-intents/api.ts b/studio/frontend/src/features/native-intents/api.ts
index 43eb6c76d0e..a89d04eebd4 100644
--- a/studio/frontend/src/features/native-intents/api.ts
+++ b/studio/frontend/src/features/native-intents/api.ts
@@ -40,6 +40,15 @@ export async function registerNativeDatasetPath(path: string): Promise<NativeInt
return invokeNative<NativeIntent>("register_native_dataset_path", { path });
}
+export async function readNativeAttachmentFile(
+ token: string,
+): Promise<{ name: string; mimeType: string; base64: string }> {
+ return invokeNative<{ name: string; mimeType: string; base64: string }>(
+ "read_native_attachment_file",
+ { token },
+ );
+}
+
export async function consumeNativePathToken(
token: string,
operation: NativePathOperation,
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 d7b8057f6a2..81820a73ffb 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
@@ -10,9 +10,20 @@ function overlayCopy(state: NativeModelDropState): { title: string; description:
};
}
if (state.status === "attach") {
+ // Only documents are indexed; images ride the next message, so mixed says both.
+ const description =
+ state.kind === "images"
+ ? "Attached to your next message."
+ : state.kind === "mixed"
+ ? "Documents indexed, images attached to your next message."
+ : "Indexed for this chat.";
+ const noun = state.kind === "images" ? "image" : "file";
return {
- title: state.count === 1 ? "Drop to attach file" : `Drop to attach ${state.count} files`,
- description: "Indexed for this chat.",
+ title:
+ state.count === 1
+ ? `Drop to attach ${noun}`
+ : `Drop to attach ${state.count} ${noun}s`,
+ description,
};
}
if (state.status === "valid" && state.action === "replace") {
diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.ts
index 8390d85eaf2..5c81d2ff1c4 100644
--- a/studio/frontend/src/features/native-intents/drop-paths.ts
+++ b/studio/frontend/src/features/native-intents/drop-paths.ts
@@ -5,8 +5,13 @@ import { RAG_UPLOAD_ACCEPT } from "../rag/types/rag.ts";
const DOC_EXTS = RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase());
+/** Vision chat attachments; keep in sync with `shared-composer` `IMAGE_ACCEPT`. */
+export const CHAT_IMAGE_DROP_ACCEPT = ".jpg,.jpeg,.png,.webp,.gif";
+
+const IMAGE_EXTS = CHAT_IMAGE_DROP_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.`;
+export const SUPPORTED_DROP_HINT = `Supported files: ${RAG_UPLOAD_ACCEPT}, ${CHAT_IMAGE_DROP_ACCEPT}, or a single .gguf model.`;
function hasExt(path: string, ext: string): boolean {
return path.toLowerCase().endsWith(ext);
@@ -16,6 +21,8 @@ export type NativeDropClass =
| { kind: "none" }
| { kind: "model"; path: string }
| { kind: "docs"; paths: string[] }
+ | { kind: "images"; paths: string[] }
+ | { kind: "attach"; docs: string[]; images: string[] }
| { kind: "unsupported" };
/** What a native drag payload is, before any of it is registered with Rust. */
@@ -29,6 +36,16 @@ export function classifyDropPaths(paths: string[]): NativeDropClass {
: { 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" };
+ const images = paths.filter((path) =>
+ IMAGE_EXTS.some((ext) => hasExt(path, ext)),
+ );
+ if (docs.length + images.length !== paths.length) {
+ return { kind: "unsupported" };
+ }
+ if (docs.length === 0 && images.length === 0) return { kind: "none" };
+ if (docs.length > 0 && images.length === 0) return { kind: "docs", paths: docs };
+ if (images.length > 0 && docs.length === 0) {
+ return { kind: "images", paths: images };
+ }
+ return { kind: "attach", docs, images };
}
diff --git a/studio/frontend/src/features/native-intents/native-attachment-file.ts b/studio/frontend/src/features/native-intents/native-attachment-file.ts
new file mode 100644
index 00000000000..41b6f7d11d4
--- /dev/null
+++ b/studio/frontend/src/features/native-intents/native-attachment-file.ts
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { readNativeAttachmentFile } from "./api";
+import type { NativeIntent } from "./types";
+
+export async function nativeAttachmentIntentToFile(
+ intent: NativeIntent,
+): Promise<File> {
+ const payload = await readNativeAttachmentFile(intent.path.token);
+ const binary = globalThis.atob(payload.base64);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index += 1) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+ return new File([bytes], payload.name, {
+ type: payload.mimeType,
+ lastModified: intent.path.modifiedMs ?? Date.now(),
+ });
+}
diff --git a/studio/frontend/src/features/native-intents/store.ts b/studio/frontend/src/features/native-intents/store.ts
index a7c9dfb1d96..bacafcd8de0 100644
--- a/studio/frontend/src/features/native-intents/store.ts
+++ b/studio/frontend/src/features/native-intents/store.ts
@@ -11,15 +11,37 @@ interface NativeIntentState {
// 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;
+ pendingImageAttachments: PendingNativeAttachments;
+ // Image drops registering with Rust, before they have a queue to sit in. Not
+ // keyed: until the intents land there is no settled target, and the OS drop
+ // went to the window, which has one composer to send from.
+ registeringImageDrops: number;
+ // Bumped, per chat, when a drop fails before it reaches a queue. The composer
+ // watches its own key so a failure elsewhere cannot cancel its parked send.
+ imageDropFailures: Record<string, number>;
+ // Owner of a queued image batch, by composer identity. A remount means the
+ // outgoing instance cannot hand the batch over itself, so it leaves a note.
+ imageDropOwners: Record<string, string>;
addIntent: (intent: NativeIntent) => void;
addAttachments: (targetKey: string, intents: NativeIntent[]) => void;
+ addImageAttachments: (targetKey: string, intents: NativeIntent[]) => void;
takeAttachments: (targetKey: string) => NativeIntent[];
+ takeImageAttachments: (targetKey: string) => NativeIntent[];
+ beginImageDropRegistration: () => void;
+ endImageDropRegistration: () => void;
+ failImageDropRegistration: (targetKey: string) => void;
+ noteImageDropOwner: (targetKey: string, identity: string) => void;
+ claimImageAttachments: (identity: string, targetKey: string) => void;
clearModelIntent: (intentId?: string) => void;
}
export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({
pendingModelIntent: null,
pendingAttachments: {},
+ pendingImageAttachments: {},
+ registeringImageDrops: 0,
+ imageDropFailures: {},
+ imageDropOwners: {},
addAttachments: (targetKey, intents) => {
const current = get().pendingAttachments;
const pendingAttachments = enqueueNativeAttachments(
@@ -31,6 +53,17 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({
set({ pendingAttachments });
}
},
+ addImageAttachments: (targetKey, intents) => {
+ const current = get().pendingImageAttachments;
+ const pendingImageAttachments = enqueueNativeAttachments(
+ current,
+ targetKey,
+ intents,
+ );
+ if (pendingImageAttachments !== current) {
+ set({ pendingImageAttachments });
+ }
+ },
takeAttachments: (targetKey) => {
const current = get().pendingAttachments;
const [queued, pendingAttachments] = dequeueNativeAttachments(
@@ -42,6 +75,63 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({
}
return queued;
},
+ takeImageAttachments: (targetKey) => {
+ const current = get().pendingImageAttachments;
+ const [queued, pendingImageAttachments] = dequeueNativeAttachments(
+ current,
+ targetKey,
+ );
+ if (pendingImageAttachments !== current) {
+ set({ pendingImageAttachments });
+ }
+ return queued;
+ },
+ beginImageDropRegistration: () => {
+ set({ registeringImageDrops: get().registeringImageDrops + 1 });
+ },
+ endImageDropRegistration: () => {
+ set({ registeringImageDrops: Math.max(0, get().registeringImageDrops - 1) });
+ },
+ failImageDropRegistration: (targetKey) => {
+ const current = get().imageDropFailures;
+ set({
+ imageDropFailures: {
+ ...current,
+ [targetKey]: (current[targetKey] ?? 0) + 1,
+ },
+ });
+ },
+ noteImageDropOwner: (targetKey, identity) => {
+ if (!identity) return;
+ set({ imageDropOwners: { ...get().imageDropOwners, [targetKey]: identity } });
+ },
+ claimImageAttachments: (identity, targetKey) => {
+ if (!identity) return;
+ const owners = get().imageDropOwners;
+ const stale = Object.keys(owners).filter(
+ (key) => owners[key] === identity && key !== targetKey,
+ );
+ if (stale.length === 0) return;
+ const queues = get().pendingImageAttachments;
+ let pendingImageAttachments = queues;
+ for (const key of stale) {
+ const queued = queues[key] ?? [];
+ if (queued.length > 0) {
+ pendingImageAttachments = enqueueNativeAttachments(
+ pendingImageAttachments,
+ targetKey,
+ queued,
+ );
+ }
+ if (key in pendingImageAttachments) {
+ pendingImageAttachments = { ...pendingImageAttachments };
+ delete pendingImageAttachments[key];
+ }
+ }
+ const nextOwners = { ...owners };
+ for (const key of stale) delete nextOwners[key];
+ set({ pendingImageAttachments, imageDropOwners: nextOwners });
+ },
addIntent: (intent) => {
if (intent.kind !== "model") {
return;
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 ab92aec86ce..b615abf9280 100644
--- a/studio/frontend/src/features/native-intents/use-native-drop.ts
+++ b/studio/frontend/src/features/native-intents/use-native-drop.ts
@@ -9,23 +9,30 @@ import type { NativeIntent } from "./types";
export type NativeModelDropState =
| { status: "idle" }
| { status: "valid"; action: "load" | "replace" | "chip" }
- | { status: "attach"; count: number }
+ | { status: "attach"; count: number; kind: "docs" | "images" | "mixed" }
| { status: "invalid" };
interface NativeModelDropOptions {
enabled?: boolean;
attachmentScope?: string;
+ // Where a drop on this window belongs, for reporting a failure back to it.
+ attachmentTargetKey?: string;
nativePathLeasesSupported: boolean;
hasActiveModel: boolean;
isModelLoading: boolean;
onAutoLoad?: (intent: NativeIntent) => Promise<void> | void;
onAttach?: (intents: NativeIntent[]) => Promise<void> | void;
+ onAttachImages?: (intents: NativeIntent[]) => Promise<void> | void;
}
function canAttachDocs(options: NativeModelDropOptions): boolean {
return options.nativePathLeasesSupported && Boolean(options.onAttach);
}
+function canAttachImages(options: NativeModelDropOptions): boolean {
+ return Boolean(options.onAttachImages);
+}
+
function canAutoLoadModel(options: NativeModelDropOptions): boolean {
return (
options.nativePathLeasesSupported &&
@@ -34,6 +41,16 @@ function canAutoLoadModel(options: NativeModelDropOptions): boolean {
);
}
+function attachmentCount(dropped: ReturnType<typeof classifyDropPaths>): number {
+ if (dropped.kind === "docs" || dropped.kind === "images") {
+ return dropped.paths.length;
+ }
+ if (dropped.kind === "attach") {
+ return dropped.docs.length + dropped.images.length;
+ }
+ return 0;
+}
+
function dropStateForPaths(
paths: string[],
options: NativeModelDropOptions,
@@ -41,10 +58,21 @@ function dropStateForPaths(
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: "attach", count: dropped.paths.length, kind: "docs" }
+ : { status: "invalid" };
+ }
+ if (dropped.kind === "images") {
+ return canAttachImages(options)
+ ? { status: "attach", count: dropped.paths.length, kind: "images" }
+ : { status: "invalid" };
+ }
+ if (dropped.kind === "attach") {
+ const docsSupported = dropped.docs.length === 0 || canAttachDocs(options);
+ const imagesSupported =
+ dropped.images.length === 0 || canAttachImages(options);
+ return docsSupported && imagesSupported
+ ? { status: "attach", count: attachmentCount(dropped), kind: "mixed" }
: { status: "invalid" };
}
if (dropped.kind === "unsupported") return { status: "invalid" };
@@ -57,6 +85,67 @@ function dropStateForPaths(
};
}
+interface RegisteredDrop {
+ docs: NativeIntent[];
+ images: NativeIntent[];
+ docsFailed: number;
+ imagesFailed: number;
+ error?: Error;
+}
+
+// Per path, not all-or-nothing: one bad file in a batch used to discard every
+// sibling that had already registered, leaving their leases to expire unused.
+async function registerEach(paths: string[]) {
+ const settled = await Promise.allSettled(
+ paths.map(registerNativeAttachmentPath),
+ );
+ const intents = settled.flatMap((result) =>
+ result.status === "fulfilled" ? [result.value] : [],
+ );
+ const rejection = settled.find((result) => result.status === "rejected");
+ return {
+ intents,
+ failed: settled.length - intents.length,
+ error:
+ rejection && rejection.status === "rejected"
+ ? rejection.reason instanceof Error
+ ? rejection.reason
+ : new Error(String(rejection.reason))
+ : undefined,
+ };
+}
+
+async function registerDroppedAttachments(
+ dropped: Extract<
+ ReturnType<typeof classifyDropPaths>,
+ { kind: "docs" | "images" | "attach" }
+ >,
+): Promise<RegisteredDrop> {
+ const docPaths =
+ dropped.kind === "docs"
+ ? dropped.paths
+ : dropped.kind === "attach"
+ ? dropped.docs
+ : [];
+ const imagePaths =
+ dropped.kind === "images"
+ ? dropped.paths
+ : dropped.kind === "attach"
+ ? dropped.images
+ : [];
+ const [docs, images] = await Promise.all([
+ registerEach(docPaths),
+ registerEach(imagePaths),
+ ]);
+ return {
+ docs: docs.intents,
+ images: images.intents,
+ docsFailed: docs.failed,
+ imagesFailed: images.failed,
+ error: docs.error ?? images.error,
+ };
+}
+
export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelDropState {
const { enabled = true } = options;
const addIntent = useNativeIntentStore((state) => state.addIntent);
@@ -91,28 +180,69 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModel
toast.error(SUPPORTED_DROP_HINT);
return;
}
- if (dropped.kind === "docs") {
- if (!canAttachDocs(currentOptions)) {
+ if (
+ dropped.kind === "docs" ||
+ dropped.kind === "images" ||
+ dropped.kind === "attach"
+ ) {
+ const needsDocs =
+ dropped.kind === "docs" ||
+ (dropped.kind === "attach" && dropped.docs.length > 0);
+ const needsImages =
+ dropped.kind === "images" ||
+ (dropped.kind === "attach" && dropped.images.length > 0);
+ if (needsDocs && !canAttachDocs(currentOptions)) {
toast.error("Attaching files needs the desktop backend", {
description: "Retry once Studio has finished starting up.",
});
return;
}
+ if (needsImages && !canAttachImages(currentOptions)) {
+ toast.error("Attaching images is unavailable right now", {
+ description: "Retry once this chat is ready for attachments.",
+ });
+ return;
+ }
+ // Hold the send gate across registration too. Between the drop and the
+ // intents reaching the queue there is nothing for the composer to see,
+ // so an Enter in that window would send the text without the image.
+ const store = useNativeIntentStore.getState();
+ if (needsImages) store.beginImageDropRegistration();
try {
- const intents = await Promise.all(
- dropped.paths.map(registerNativeAttachmentPath),
- );
- if (disposed) return;
+ const registered = await registerDroppedAttachments(dropped);
const latestOptions = optionsRef.current;
+ // Both callbacks only enqueue against a target key, so a drop that
+ // outlived this listener still reaches the chat it landed on.
const attachOptions =
+ !disposed &&
latestOptions.attachmentScope === currentOptions.attachmentScope
? latestOptions
: currentOptions;
- await attachOptions.onAttach?.(intents);
+ if (registered.docs.length > 0) {
+ await attachOptions.onAttach?.(registered.docs);
+ }
+ if (registered.images.length > 0) {
+ await attachOptions.onAttachImages?.(registered.images);
+ }
+ const failureKey = attachOptions.attachmentTargetKey;
+ if (registered.imagesFailed > 0 && failureKey) {
+ store.failImageDropRegistration(failureKey);
+ }
+ if (registered.docsFailed + registered.imagesFailed > 0) {
+ toast.error("Could not attach dropped files", {
+ description: registered.error?.message ?? "Some files were skipped.",
+ });
+ }
} catch (error) {
+ const failureKey = currentOptions.attachmentTargetKey;
+ if (needsImages && failureKey) {
+ store.failImageDropRegistration(failureKey);
+ }
toast.error("Could not attach dropped files", {
description: error instanceof Error ? error.message : String(error),
});
+ } finally {
+ if (needsImages) store.endImageDropRegistration();
}
return;
}
diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.ts
index c368941ab2f..7937d6eb3bf 100644
--- a/studio/frontend/tests/native-drop-paths.test.ts
+++ b/studio/frontend/tests/native-drop-paths.test.ts
@@ -9,14 +9,28 @@ import {
dequeueNativeAttachments,
enqueueNativeAttachments,
} from "../src/features/native-intents/attachment-queue.ts";
-import { classifyDropPaths } from "../src/features/native-intents/drop-paths.ts";
+import { classifyDropPaths, CHAT_IMAGE_DROP_ACCEPT, SUPPORTED_DROP_HINT } 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";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { useNativeIntentStore } = await import(
+ "../src/features/native-intents/store.ts"
+);
const BACKEND_UPLOAD_EXTS_RE = /UPLOAD_EXTS\s*=\s*\{([^}]+)\}/s;
const RUST_ATTACHMENT_EXTS_RE = /ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;
+const RUST_IMAGE_ATTACHMENT_EXTS_RE = /IMAGE_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;
const DOTTED_EXTENSION_RE = /"(\.[^"]+)"/g;
const RUST_EXTENSION_RE = /"([^"]+)"/g;
+const RUST_MIME_ARM_RE = /Some\("(image\/[^"]+)"\)/g;
+const MIME_MATCH_BODY_RE = /fn attachment_mime_type[\s\S]*?match ext\.as_str\(\) \{([\s\S]*?)\n {4}\}/;
+const MIME_ARM_EXTENSION_RE = /^\s*((?:"[^"]+"\s*\|?\s*)+)=>\s*Some\("image\//gm;
+const COMPOSER_IMAGE_ACCEPT_RE = /const IMAGE_ACCEPT\s*=\s*"([^"]+)"/;
+const VISION_ADAPTER_ACCEPT_RE =
+ /class VisionImageAdapter[^{]*\{\s*accept\s*=\s*"([^"]+)"/s;
function attachmentIntent(id: string): NativeIntent {
return {
@@ -53,6 +67,25 @@ test("documents are an attachment drop, one or many", () => {
assert.equal(dropped.kind === "docs" ? dropped.paths.length : 0, 3);
});
+test("images route to chat vision attachments, one or many", () => {
+ const dropped = classifyDropPaths([
+ "/photos/cat.PNG",
+ "/photos/dog.jpeg",
+ "/photos/icon.webp",
+ ]);
+ assert.equal(dropped.kind, "images");
+ assert.equal(dropped.kind === "images" ? dropped.paths.length : 0, 3);
+});
+
+test("documents and images can be dropped together", () => {
+ const dropped = classifyDropPaths(["/docs/a.pdf", "/photos/cat.png"]);
+ assert.equal(dropped.kind, "attach");
+ if (dropped.kind === "attach") {
+ assert.deepEqual(dropped.docs, ["/docs/a.pdf"]);
+ assert.deepEqual(dropped.images, ["/photos/cat.png"]);
+ }
+});
+
test("a mixed or unsupported drop is rejected", () => {
// The regression in #7661: these used to be reported as "GGUF models only".
assert.equal(
@@ -74,6 +107,11 @@ test("an empty payload is not a drop target", () => {
assert.equal(classifyDropPaths([]).kind, "none");
});
+test("the rejection hint mentions images without widening RAG upload accept", () => {
+ assert.match(SUPPORTED_DROP_HINT, /\.png/);
+ assert.doesNotMatch(RAG_UPLOAD_ACCEPT, /\.png/);
+});
+
test("attachment batches stay bound to the chat that received the drop", () => {
const queued = enqueueNativeAttachments({}, "single:thread-a", [
attachmentIntent("doc"),
@@ -97,6 +135,28 @@ test("attachment batches stay bound to the chat that received the drop", () => {
assert.deepEqual(remaining, {});
});
+// Registration crosses into Rust before the queue exists, and a send in that gap
+// would go out without the image.
+test("registering image drops hold the gate before the queue can", () => {
+ const store = useNativeIntentStore.getState();
+ assert.equal(store.registeringImageDrops, 0);
+
+ store.beginImageDropRegistration();
+ assert.equal(useNativeIntentStore.getState().registeringImageDrops, 1);
+
+ // Two drops can be in flight at once; the first to finish can't open the gate.
+ store.beginImageDropRegistration();
+ store.endImageDropRegistration();
+ assert.equal(useNativeIntentStore.getState().registeringImageDrops, 1);
+
+ store.endImageDropRegistration();
+ assert.equal(useNativeIntentStore.getState().registeringImageDrops, 0);
+
+ // A stray end can't drive it negative and wedge the gate shut.
+ store.endImageDropRegistration();
+ assert.equal(useNativeIntentStore.getState().registeringImageDrops, 0);
+});
+
test("frontend, backend, and Rust accept the same document extensions", () => {
const frontend = RAG_UPLOAD_ACCEPT.split(",").sort();
const backendSource = readFileSync(
@@ -125,3 +185,174 @@ test("frontend, backend, and Rust accept the same document extensions", () => {
assert.deepEqual(backend, frontend);
assert.deepEqual(rust, frontend);
});
+
+test("frontend and Rust accept the same chat image extensions", () => {
+ const frontend = CHAT_IMAGE_DROP_ACCEPT.split(",")
+ .map((ext) => ext.trim().toLowerCase())
+ .sort();
+ const rustSource = readFileSync(
+ new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),
+ "utf8",
+ );
+ const rust = [
+ ...(rustSource
+ .match(RUST_IMAGE_ATTACHMENT_EXTS_RE)?.[1]
+ .matchAll(RUST_EXTENSION_RE) ?? []),
+ ]
+ .map((match) => `.${match[1]}`)
+ .sort();
+
+ assert.deepEqual(rust, frontend);
+});
+
+// One more seam of #7963's shape: Rust stamps the File's MIME type and the
+// composer routes by MIME, so a type VisionImageAdapter does not claim lands on
+// the wrong adapter or nowhere.
+test("every MIME type Rust stamps is one the vision adapter claims", () => {
+ const rustSource = readFileSync(
+ new URL("../../src-tauri/src/native_intents.rs", import.meta.url),
+ "utf8",
+ );
+ const stamped = [
+ ...new Set(
+ [...rustSource.matchAll(RUST_MIME_ARM_RE)].map((match) => match[1]),
+ ),
+ ].sort();
+
+ const providerSource = readFileSync(
+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),
+ "utf8",
+ );
+ const accepted = providerSource
+ .match(VISION_ADAPTER_ACCEPT_RE)?.[1]
+ .split(",")
+ .map((type) => type.trim())
+ .sort();
+
+ assert.ok(stamped.length > 0, "no image MIME arms found in native_intents.rs");
+ assert.deepEqual(stamped, accepted);
+});
+
+// The join between the two tests above: without it an extension can reach both
+// allow-lists with no MIME arm, and the reader refuses it after the drop.
+test("every accepted image extension has a Rust MIME arm", () => {
+ const policySource = readFileSync(
+ new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),
+ "utf8",
+ );
+ const accepted = [
+ ...(policySource
+ .match(RUST_IMAGE_ATTACHMENT_EXTS_RE)?.[1]
+ .matchAll(RUST_EXTENSION_RE) ?? []),
+ ]
+ .map((match) => match[1])
+ .sort();
+
+ const intentsSource = readFileSync(
+ new URL("../../src-tauri/src/native_intents.rs", import.meta.url),
+ "utf8",
+ );
+ const body = intentsSource.match(MIME_MATCH_BODY_RE)?.[1];
+ assert.ok(body, "attachment_mime_type match block not found");
+ const mapped = [...body.matchAll(MIME_ARM_EXTENSION_RE)]
+ .flatMap((match) => [...match[1].matchAll(/"([^"]+)"/g)].map((ext) => ext[1]))
+ .sort();
+
+ assert.ok(accepted.length > 0, "no IMAGE_ATTACHMENT_EXTS found");
+ assert.deepEqual(mapped, accepted);
+});
+
+// The one constant drop-paths.ts names in its own "keep in sync" comment.
+test("the drop image list matches the composer's file picker", () => {
+ const composerSource = readFileSync(
+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),
+ "utf8",
+ );
+ const picker = composerSource
+ .match(COMPOSER_IMAGE_ACCEPT_RE)?.[1]
+ .split(",")
+ .map((type) => type.trim().replace("image/", ""))
+ .sort();
+ const dropped = CHAT_IMAGE_DROP_ACCEPT.split(",")
+ .map((ext) => ext.trim().toLowerCase().replace(".", ""))
+ .map((ext) => (ext === "jpg" ? "jpeg" : ext))
+ .sort();
+
+ assert.ok(picker, "IMAGE_ACCEPT not found in shared-composer.tsx");
+ assert.deepEqual([...new Set(dropped)], picker);
+});
+
+// A remount means the instance that queued the batch cannot hand it over.
+test("a remounted composer claims the batch its predecessor left behind", () => {
+ const store = useNativeIntentStore.getState();
+ const intent = {
+ id: "i1",
+ kind: "attachment",
+ path: {
+ token: "t1",
+ kind: "attachment",
+ displayLabel: "a.png",
+ allowedOperations: ["attach"],
+ expiresAtMs: Date.now() + 60_000,
+ },
+ } as unknown as NativeIntent;
+
+ store.addImageAttachments("single:new", [intent]);
+ store.noteImageDropOwner("single:new", "composer-1");
+
+ // A different composer must not take it.
+ store.claimImageAttachments("composer-2", "single:other");
+ assert.equal(
+ useNativeIntentStore.getState().pendingImageAttachments["single:new"]?.length,
+ 1,
+ );
+
+ store.claimImageAttachments("composer-1", "single:thread-7");
+ const after = useNativeIntentStore.getState();
+ assert.equal(after.pendingImageAttachments["single:new"], undefined);
+ assert.deepEqual(after.pendingImageAttachments["single:thread-7"], [intent]);
+ assert.deepEqual(after.imageDropOwners, {});
+});
+
+// The predecessor's requeue can land after the replacement has claimed once.
+test("ownership recorded after a claim is still picked up", () => {
+ const store = useNativeIntentStore.getState();
+ const intent = {
+ id: "i2",
+ kind: "attachment",
+ path: {
+ token: "t2",
+ kind: "attachment",
+ displayLabel: "late.png",
+ allowedOperations: ["attach"],
+ expiresAtMs: Date.now() + 60_000,
+ },
+ } as unknown as NativeIntent;
+
+ // The replacement composer claims first, finding nothing.
+ store.claimImageAttachments("composer-3", "single:thread-9");
+ // Only then does the outgoing drain put its batch back and tag it.
+ store.addImageAttachments("single:new", [intent]);
+ store.noteImageDropOwner("single:new", "composer-3");
+
+ const owners = useNativeIntentStore.getState().imageDropOwners;
+ assert.equal(owners["single:new"], "composer-3", "the note survives for a later claim");
+
+ store.claimImageAttachments("composer-3", "single:thread-9");
+ const after = useNativeIntentStore.getState();
+ assert.equal(after.pendingImageAttachments["single:new"], undefined);
+ assert.deepEqual(after.pendingImageAttachments["single:thread-9"], [intent]);
+});
+
+test("document and image drop extensions stay disjoint", () => {
+ // classifyDropPaths sums the two filters, so an overlap silently turns a
+ // perfectly good drop into "unsupported".
+ const docs = RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase());
+ const images = CHAT_IMAGE_DROP_ACCEPT.split(",").map((ext) =>
+ ext.trim().toLowerCase(),
+ );
+ assert.deepEqual(
+ images.filter((ext) => docs.includes(ext)),
+ [],
+ );
+});
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index fc3f0172187..bd8dad5d804 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1046,6 +1046,7 @@ fn main() {
native_intents::register_native_model_path,
native_intents::register_native_attachment_path,
native_intents::register_native_dataset_path,
+ native_intents::read_native_attachment_file,
native_intents::pick_native_model,
native_intents::pick_hugging_face_cache_dir,
native_intents::consume_native_path_token,
diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rs
index f0f042c6a84..ba331d07423 100644
--- a/studio/src-tauri/src/native_intents.rs
+++ b/studio/src-tauri/src/native_intents.rs
@@ -8,12 +8,16 @@ use crate::native_path_policy::{
};
use serde::Serialize;
use std::collections::{HashMap, VecDeque};
+use std::fs;
+use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::Duration;
use tauri::{AppHandle, WebviewWindow};
use tauri_plugin_dialog::DialogExt;
+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
+
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);
@@ -520,6 +524,127 @@ pub fn open_path_token(
open::that_detached(entry.canonical_path).map_err(|e| format!("Failed to open path: {e}"))
}
+const MAX_NATIVE_ATTACHMENT_BYTES: u64 = 20 * 1024 * 1024;
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NativeAttachmentFile {
+ name: String,
+ mime_type: String,
+ base64: String,
+}
+
+fn attachment_mime_type(path: &Path) -> Option<&'static str> {
+ let ext = path.extension()?.to_str()?.to_ascii_lowercase();
+ match ext.as_str() {
+ "jpg" | "jpeg" => Some("image/jpeg"),
+ "png" => Some("image/png"),
+ "webp" => Some("image/webp"),
+ "gif" => Some("image/gif"),
+ _ => None,
+ }
+}
+
+// Same shape as the clipboard reader: never traverse a link swapped in after
+// the path was validated, and never block the caller on a FIFO.
+fn open_attachment_file(path: &Path) -> Result<fs::File, String> {
+ let unavailable = || "Path is no longer available.".to_string();
+ let metadata = fs::symlink_metadata(path).map_err(|_| unavailable())?;
+ if metadata.file_type().is_symlink() || !metadata.is_file() {
+ return Err(unavailable());
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
+ .open(path)
+ .map_err(|_| unavailable())
+ }
+ // Windows analogue: open the reparse point itself, then refuse it. Literals
+ // because windows-sys is not built with Win32_Storage_FileSystem here.
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
+ const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
+ let file = fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
+ .open(path)
+ .map_err(|_| unavailable())?;
+ let opened = file.metadata().map_err(|_| unavailable())?;
+ if opened.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 || !opened.is_file() {
+ return Err(unavailable());
+ }
+ Ok(file)
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ fs::File::open(path).map_err(|_| unavailable())
+ }
+}
+
+fn read_attachment_payload(entry: &NativePathEntry) -> Result<NativeAttachmentFile, String> {
+ let path = &entry.canonical_path;
+ let mime_type = attachment_mime_type(path).ok_or_else(|| {
+ "Only chat image attachments can be read for vision input.".to_string()
+ })?;
+ let file = open_attachment_file(path)?;
+ let metadata = file
+ .metadata()
+ .map_err(|e| format!("Path is no longer available: {e}"))?;
+ if !metadata.is_file() || metadata.len() > MAX_NATIVE_ATTACHMENT_BYTES {
+ return Err("Image attachment is unavailable or too large.".to_string());
+ }
+ // path_for_operation validated a fingerprint against the path; bind the
+ // handle we are about to read to that same one, or a swap in between wins.
+ let modified_ms = metadata
+ .modified()
+ .ok()
+ .and_then(|value| value.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|value| value.as_millis() as u64);
+ if Some(metadata.len()) != entry.size_bytes || modified_ms != entry.modified_ms {
+ return Err("Native path changed after it was selected.".to_string());
+ }
+ // The file can grow between the stat and the read, so cap the reader itself.
+ let mut bytes = Vec::with_capacity(metadata.len() as usize);
+ file.take(MAX_NATIVE_ATTACHMENT_BYTES + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|e| format!("Could not read image attachment: {e}"))?;
+ if bytes.len() as u64 > MAX_NATIVE_ATTACHMENT_BYTES {
+ return Err("Image attachment is unavailable or too large.".to_string());
+ }
+ let name = path
+ .file_name()
+ .map(|value| value.to_string_lossy().into_owned())
+ .unwrap_or_else(|| entry.display_label.clone());
+ Ok(NativeAttachmentFile {
+ name,
+ mime_type: mime_type.to_string(),
+ base64: BASE64.encode(bytes),
+ })
+}
+
+// Async: a sync command would base64 up to 20 MiB on the main thread. Only the
+// token lookup stays here; State is not 'static and validation hits the disk.
+#[tauri::command]
+pub async fn read_native_attachment_file(
+ window: WebviewWindow,
+ state: tauri::State<'_, NativeIntakeState>,
+ token: String,
+) -> Result<NativeAttachmentFile, String> {
+ ensure_main_window(&window)?;
+ let entry = state.entry_for_operation(&token, NativePathOperation::Attach)?;
+ tokio::task::spawn_blocking(move || {
+ validate_entry_path(&entry, NativePathOperation::Attach)?;
+ read_attachment_payload(&entry)
+ })
+ .await
+ .map_err(|_| "Image attachment reader stopped unexpectedly.".to_string())?
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -537,6 +662,67 @@ mod tests {
))
}
+ fn attachment_entry(path: &Path) -> (NativeIntakeState, NativePathEntry) {
+ let state = new_native_intake_state();
+ state.note_dropped_paths(std::slice::from_ref(&path.to_path_buf()));
+ let intent = state
+ .register_attachment_path(path, NativePathSourceKind::Drop)
+ .unwrap();
+ let entry = state
+ .path_for_operation(&intent.path.token, NativePathOperation::Attach)
+ .unwrap();
+ (state, entry)
+ }
+
+ #[test]
+ fn image_read_round_trips_and_names_the_file() {
+ let path = temp_path("photo").with_extension("png");
+ fs::write(&path, b"\x89PNG\r\n\x1a\n").unwrap();
+ let (_state, entry) = attachment_entry(&path);
+ let payload = read_attachment_payload(&entry).unwrap();
+ assert_eq!(payload.mime_type, "image/png");
+ assert_eq!(BASE64.decode(payload.base64).unwrap(), b"\x89PNG\r\n\x1a\n");
+ assert!(payload.name.ends_with(".png"));
+ let _ = fs::remove_file(path);
+ }
+
+ #[test]
+ fn document_token_is_refused_by_the_image_reader() {
+ let path = temp_path("note").with_extension("pdf");
+ fs::write(&path, b"%PDF-1.4").unwrap();
+ let (_state, entry) = attachment_entry(&path);
+ let Err(err) = read_attachment_payload(&entry) else {
+ panic!("expected the read to be refused");
+ };
+ assert!(err.contains("Only chat image attachments"));
+ let _ = fs::remove_file(path);
+ }
+
+ #[test]
+ fn image_read_rejects_a_file_swapped_in_after_validation() {
+ let path = temp_path("swap").with_extension("png");
+ fs::write(&path, b"the dropped image").unwrap();
+ let (_state, entry) = attachment_entry(&path);
+ fs::write(&path, b"a different file entirely").unwrap();
+ let Err(err) = read_attachment_payload(&entry) else {
+ panic!("expected the read to be refused");
+ };
+ assert!(err.contains("changed"), "unexpected error: {err}");
+ let _ = fs::remove_file(path);
+ }
+
+ #[test]
+ fn image_read_refuses_more_than_the_cap() {
+ let path = temp_path("huge").with_extension("png");
+ fs::write(&path, vec![0u8; MAX_NATIVE_ATTACHMENT_BYTES as usize + 1]).unwrap();
+ let (_state, entry) = attachment_entry(&path);
+ let Err(err) = read_attachment_payload(&entry) else {
+ panic!("expected the read to be refused");
+ };
+ assert!(err.contains("too large"), "unexpected error: {err}");
+ let _ = fs::remove_file(path);
+ }
+
#[test]
fn model_token_issues_distinct_validate_and_load_grants() {
let state = new_native_intake_state();
diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rs
index cfb33b2eb17..8482c16f713 100644
--- a/studio/src-tauri/src/native_path_policy.rs
+++ b/studio/src-tauri/src/native_path_policy.rs
@@ -48,19 +48,24 @@ pub fn classify_native_model_path(path: &Path) -> Result<ClassifiedPath, String>
pub const ATTACHMENT_EXTS: &[&str] = &["pdf", "txt", "md", "markdown", "docx", "html", "htm"];
pub const TRAINING_DATASET_EXTS: &[&str] = &["csv", "json", "jsonl", "parquet"];
+/// Vision chat image attachments; keep in sync with `drop-paths.ts` `CHAT_IMAGE_DROP_ACCEPT`.
+pub const IMAGE_ATTACHMENT_EXTS: &[&str] = &["jpg", "jpeg", "png", "webp", "gif"];
+
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
+ let supported = ATTACHMENT_EXTS
.iter()
- .any(|ext| has_extension(&classified.canonical_path, ext))
- {
+ .chain(IMAGE_ATTACHMENT_EXTS.iter())
+ .any(|ext| has_extension(&classified.canonical_path, ext));
+ if !supported {
return Err(format!(
"Unsupported attachment type. Supported: {}",
ATTACHMENT_EXTS
.iter()
+ .chain(IMAGE_ATTACHMENT_EXTS.iter())
.map(|ext| format!(".{ext}"))
.collect::<Vec<_>>()
.join(", ")
@@ -356,6 +361,18 @@ mod tests {
let _ = fs::remove_file(path);
}
+ #[test]
+ fn image_allows_attach_and_reveal_only() {
+ let path = temp_path("photo").with_extension("png");
+ fs::write(&path, b"\x89PNG\r\n").unwrap();
+ let classified = classify_native_attachment_path(&path).unwrap();
+ assert_eq!(classified.path_kind, NativePathKind::Attachment);
+ assert!(classified
+ .allowed_operations
+ .contains(&NativePathOperation::Attach));
+ let _ = fs::remove_file(path);
+ }
+
#[test]
fn unsupported_attachment_type_is_rejected() {
let path = temp_path("doc").with_extension("exe");