Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Desktop: attach dropped source files on desktop instead of refusing them (#9495)
Nilay9b24021925fb
diff --git a/studio/frontend/src/features/chat/attachment-content.ts b/studio/frontend/src/features/chat/attachment-content.tsindex f560c0e9e2e..bf7601539ef 100644--- a/studio/frontend/src/features/chat/attachment-content.ts+++ b/studio/frontend/src/features/chat/attachment-content.ts@@ -2,19 +2,22 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { type Unzipped, strFromU8, unzipSync, zipSync } from "fflate";+import { TEXT_ATTACHMENT_ACCEPT } from "./text-attachment-accept";-import {- OPEN_DOCUMENT_SPREADSHEET_MIME,- OPEN_DOCUMENT_TEXT_MIME,-} from "./open-document-accept";import {MAX_OPEN_DOCUMENT_ARCHIVE_BYTES,MAX_OPEN_DOCUMENT_XML_BYTES,readOpenDocumentAttachmentContent,} from "./open-document";+import {+ OPEN_DOCUMENT_SPREADSHEET_MIME,+ OPEN_DOCUMENT_TEXT_MIME,+} from "./open-document-accept";export type AttachmentTextLabel = "PDF" | "DOCX" | "HTML" | "ODS" | "ODT";+export { TEXT_ATTACHMENT_ACCEPT };+export type AttachmentText = {label: AttachmentTextLabel | null;text: string;@@ -36,19 +39,6 @@ const ATTACHMENT_TAG_CLOSE = "\n</attachment>";const MAX_ATTACHMENT_WRAPPER_LENGTH = 4096;const DOCX_MIME ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";-// Shared with TextAttachmentAdapter so the preview applies the same first-match-// dispatch before falling through to the document-specific adapters.-export const TEXT_ATTACHMENT_ACCEPT = [- "text/plain,text/markdown,text/csv,text/xml,text/json,text/css",- "application/json,application/xml,image/svg+xml",- ".txt,.text,.log,.md,.markdown,.mdx,.rst,.csv,.tsv",- ".json,.jsonl,.ndjson,.xml,.yaml,.yml,.toml,.ini,.cfg,.conf,.env,.properties",- ".css,.scss,.sass,.less,.svg",- ".js,.jsx,.mjs,.cjs,.ts,.tsx,.py,.pyi,.ipynb,.rb,.php,.go,.rs,.java,.kt,.kts,.scala,.swift",- ".c,.h,.cc,.cpp,.hpp,.cxx,.cs,.m,.mm",- ".sh,.bash,.zsh,.fish,.ps1,.bat,.lua,.pl,.pm,.r,.jl,.dart,.vue,.svelte,.astro",- ".sql,.graphql,.gql,.proto,.tf,.tfvars,.gradle,.dockerfile,.makefile,.cmake,.diff,.patch",-].join(",");// mammoth picks the parts it parses out of the relationships, not out of the// filenames, so a target may be called anything ("payload.bin") and still be// inflated and parsed as XML, while an .xml part nothing points at (customXml,@@ -242,7 +232,10 @@ const MAX_PREVIEW_TEXT_LENGTH = 200_000;const MAX_PREVIEW_TEXT_BYTES = MAX_PREVIEW_TEXT_LENGTH * 5;/** Own-property lookup: an extension or entity named "constructor" would otherwise resolve to a member of Object.prototype. */-function lookUp(table: Record<string, string>, key: string): string | undefined {+function lookUp(+ table: Record<string, string>,+ key: string,+): string | undefined {return Object.hasOwn(table, key) ? table[key] : undefined;}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 3caa066e0ea..ecf72fa49e6 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -2,7 +2,6 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { authFetch } from "@/features/auth";-import { chatModelLoaded } from "./lib/chat-model-loaded";import {AssistantRuntimeProvider,type Attachment,@@ -43,37 +42,28 @@ import {} from "./api/chat-adapter";import { CHAT_HISTORY_UPDATED_EVENT } from "./api/chat-api";import { getResearchThreadState } from "./api/research-api";-import { sanitizeThreadScopedSettings } from "./utils/thread-scoped-settings";import {- ingestResearchUpdate,- useResearchRunStore,-} from "./stores/research-run-store";+ TEXT_ATTACHMENT_ACCEPT,+ extractDocxAttachmentText,+ extractHtmlAttachmentText,+ extractPdfAttachmentText,+ getDocumentAttachmentSizeError,+ getDocxAttachmentError,+} from "./attachment-content";+import { AudioAttachmentAdapter } from "./audio-attachment-adapter";import {loadConnectionsEnabled,loadExternalProviders,parseExternalModelId,providerModelSupportsVision,} from "./external-providers";-import {- OPEN_DOCUMENT_ATTACHMENT_ACCEPT,- OPEN_DOCUMENT_SPREADSHEET_MIME,- OPEN_DOCUMENT_TEXT_MIME,-} from "./open-document-accept";+import { chatModelLoaded } from "./lib/chat-model-loaded";import {type OpenDocumentAttachmentContent,readActiveOpenDocumentAttachmentContent,readOpenDocumentAttachmentContent,} from "./open-document";-import {- extractDocxAttachmentText,- extractHtmlAttachmentText,- extractPdfAttachmentText,- getDocumentAttachmentSizeError,- getDocxAttachmentError,- TEXT_ATTACHMENT_ACCEPT,-} from "./attachment-content";-import { AudioAttachmentAdapter } from "./audio-attachment-adapter";-import { VideoAttachmentAdapter } from "./video-attachment-adapter";+import { OPEN_DOCUMENT_ATTACHMENT_ACCEPT } from "./open-document-accept";import {awaitThreadScopedSettingsWrite,beginThreadScopedPairing,@@ -81,35 +71,18 @@ import {releaseHeldThreadScopedEdits,useChatRuntimeStore,} from "./stores/chat-runtime-store";-import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";-import {- notifyPromptQueueRunFailed,- requestPromptQueueStop,- requestTemporaryPromptQueueStop,-} from "./utils/prompt-queue-boundary";import {- adoptPreStreamRunReservation,- claimPreStreamRunReservation,- findPreStreamRunReservation,- isPreStreamRunReservationCancelled,- preStreamRunThreadIdsForRuntime,- releasePreStreamRunReservation,-} from "./utils/pre-stream-run-reservation";+ ingestResearchUpdate,+ useResearchRunStore,+} from "./stores/research-run-store";+import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";import type { MessageRecord, ModelType, ThreadRecord } from "./types";import {chatContentPartAttachmentIdFromSignature,chatContentPartAttachmentSignature,onChatAttachmentDeleted,} from "./utils/chat-attachment-events";-import {- attachmentContentText,- attachmentsSample,- isPastedTextFile,-} from "./utils/pasted-text";-import {- refreshContextUsage,- setActiveBranchReader,-} from "./utils/refresh-context-usage";+import { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";import {awaitStoredChatThreadWrites,deleteStoredChatThreads,@@ -130,11 +103,34 @@ import {isChatThreadDeleted,markChatThreadDeleted,} from "./utils/chat-thread-tombstones";-import { chatHistoryClearBoundary } from "./utils/chat-history-clear-boundary";import { fallbackTitleFromUserText } from "./utils/chat-title";import { syncExportedRepositoryToBackend } from "./utils/delete-thread-message";import { getImageInputUnavailableReason } from "./utils/image-input-support";+import {+ attachmentContentText,+ attachmentsSample,+ isPastedTextFile,+} from "./utils/pasted-text";+import {+ adoptPreStreamRunReservation,+ claimPreStreamRunReservation,+ findPreStreamRunReservation,+ isPreStreamRunReservationCancelled,+ preStreamRunThreadIdsForRuntime,+ releasePreStreamRunReservation,+} from "./utils/pre-stream-run-reservation";+import {+ notifyPromptQueueRunFailed,+ requestPromptQueueStop,+ requestTemporaryPromptQueueStop,+} from "./utils/prompt-queue-boundary";+import {+ refreshContextUsage,+ setActiveBranchReader,+} from "./utils/refresh-context-usage";import { isAssistantLocalThreadId } from "./utils/thread-ids";+import { sanitizeThreadScopedSettings } from "./utils/thread-scoped-settings";+import { VideoAttachmentAdapter } from "./video-attachment-adapter";const pendingHistoryAppendByMessageId = new Map<string, Promise<void>>();// Resolves to the thread id assigned when this message's chat was first persisted.@@ -869,7 +865,9 @@ function createStudioDbAdapter(// while the creator is still queued. Use the same retry choke point as other mutations so a// temporarily missing row does not permanently skip first-turn title generation. A title is// cosmetic, so a row that never landed falls back to the default rather than rejecting here.- const thread = await ensureStoredChatThread(remoteId).catch(() => undefined);+ const thread = await ensureStoredChatThread(remoteId).catch(+ () => undefined,+ );const defaultTitle = "New Chat";function streamTitle(title: string) {@@ -932,10 +930,11 @@ function createStudioDbAdapter(const running = useChatRuntimeStore.getState().runningByThreadId;if (running[paired.id]) {setTimeout(() => {- void createStudioDbAdapter(modelType, pairId, projectId).generateTitle(- remoteId,- messages,- );+ void createStudioDbAdapter(+ modelType,+ pairId,+ projectId,+ ).generateTitle(remoteId, messages);}, 600);return streamTitle(thread.title || defaultTitle);}@@ -1032,7 +1031,9 @@ async function waitForRunStartHistoryAppend(return;}const runStartReady = pendingRunStartReadyByMessageId.get(userMessage.id);- const historyAppendReady = pendingHistoryAppendByMessageId.get(userMessage.id);+ const historyAppendReady = pendingHistoryAppendByMessageId.get(+ userMessage.id,+ );if (runStartReady === undefined && historyAppendReady === undefined) {return undefined;}@@ -1057,7 +1058,9 @@ async function waitForRunStartHistoryAppend(return adoptedThreadId;}-function createPersistedRunAdapter(adapter: ChatModelAdapter): ChatModelAdapter {+function createPersistedRunAdapter(+ adapter: ChatModelAdapter,+): ChatModelAdapter {return {...adapter,async *run(options) {@@ -1084,10 +1087,7 @@ function createPersistedRunAdapter(adapter: ChatModelAdapter): ChatModelAdapter};throwIfReservationCancelled();const persistedRunThreadIds = preStreamRunThreadIdsForRuntime(- [- ...reservationThreadIds,- ...trackedRunStartThreadIds,- ],+ [...reservationThreadIds, ...trackedRunStartThreadIds],undefined,);let adoptedThreadId: string | undefined;@@ -1225,8 +1225,7 @@ function useStudioRuntimeAdapters(...(Array.isArray(attachments)? {attachments: attachments.filter(- (attachment) =>- attachment.id !== attachmentId,+ (attachment) => attachment.id !== attachmentId,),}: {}),@@ -1249,9 +1248,7 @@ function useStudioRuntimeAdapters().attachments;if (Array.isArray(attachments) &&- attachments.some(- (attachment) => attachment.id === attachmentId,- )+ attachments.some((attachment) => attachment.id === attachmentId)) {changed = true;return {@@ -1432,9 +1429,7 @@ function useStudioRuntimeAdapters(const localThreadId = aui.threadListItem().getState().id;const historyClearGeneration = chatHistoryClearBoundary.capture();const throwIfHistoryWasCleared = async (remoteId: string) => {- if (- chatHistoryClearBoundary.capture() === historyClearGeneration- ) {+ if (chatHistoryClearBoundary.capture() === historyClearGeneration) {return;}markChatThreadDeleted(remoteId);@@ -1483,17 +1478,22 @@ function useStudioRuntimeAdapters(await throwIfHistoryWasCleared(remoteId);const content = cloneContent(message.content);const attachments =- message.role === "user" ? cloneAttachments(message.attachments) : [];+ message.role === "user"+ ? cloneAttachments(message.attachments)+ : [];const custom = message.metadata?.custom;const createdAt =existingMessage?.createdAt ??message.createdAt?.getTime?.() ??- Date.now();+ Date.now();const existingMetadata = existingMessage?.metadata;const incomingRevision = Number(- (custom as Record<string, unknown> | undefined)?.serverRevision ?? -1,+ (custom as Record<string, unknown> | undefined)?.serverRevision ??+ -1,+ );+ const existingRevision = Number(+ existingMetadata?.serverRevision ?? -1,);- const existingRevision = Number(existingMetadata?.serverRevision ?? -1);const incomingMetadata = custom as| Record<string, unknown>| undefined;@@ -1590,7 +1590,9 @@ function useRuntimeHook(}function createRuntimeHook(modelType: ModelType, pairId?: string) {- return function useConfiguredRuntimeHook(): ReturnType<typeof useLocalRuntime> {+ return function useConfiguredRuntimeHook(): ReturnType<+ typeof useLocalRuntime+ > {return useRuntimeHook(modelType, pairId);};}@@ -1682,7 +1684,14 @@ function ThreadNewChatSwitch({// runActive is a DEPENDENCY, not just a guard: refreshContextUsage declines while anything// generates, and nothing else re-fires this when the run ends. ThreadContextUsageRecount// cannot cover for it -- an unpersisted New Chat has no activeThreadId.- }, [checkpoint, ggufContextLength, isLoading, modelLoading, nonce, runActive]);+ }, [+ checkpoint,+ ggufContextLength,+ isLoading,+ modelLoading,+ nonce,+ runActive,+ ]);return null;}@@ -1848,7 +1857,9 @@ function ThreadScopedSettingsSync({// the response spells every omitted field as null, which is not a value to apply.applyThreadScopedSettings(activeThreadId,- thread.settings ? sanitizeThreadScopedSettings(thread.settings) : null,+ thread.settings+ ? sanitizeThreadScopedSettings(thread.settings)+ : null,);})// A failed read leaves the installation defaults up (dropped to above), not the@@ -1989,7 +2000,11 @@ function CancelRegistrar(): ReactElement | null {if (!mainThreadId) return;const runtime = aui.threads().__internal_getAssistantRuntime?.();const threadIds = Array.from(- new Set([mainThreadId, remoteThreadId].filter((id): id is string => Boolean(id))),+ new Set(+ [mainThreadId, remoteThreadId].filter((id): id is string =>+ Boolean(id),+ ),+ ),);const cancel = () => {for (const threadId of threadIds) {@@ -2030,9 +2045,7 @@ function CancelRegistrar(): ReactElement | null {return;}for (const threadId of threadIds) {- useChatRuntimeStore- .getState()- .clearThreadCancel(threadId, cancel);+ useChatRuntimeStore.getState().clearThreadCancel(threadId, cancel);}unsubscribe();});diff --git a/studio/frontend/src/features/chat/text-attachment-accept.ts b/studio/frontend/src/features/chat/text-attachment-accept.tsnew file mode 100644index 00000000000..1cfc678f91b--- /dev/null+++ b/studio/frontend/src/features/chat/text-attachment-accept.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Extensions `TextAttachmentAdapter` reads inline; shared with the drop path. */+export const TEXT_ATTACHMENT_EXTENSIONS = [+ ".txt",+ ".text",+ ".log",+ ".md",+ ".markdown",+ ".mdx",+ ".rst",+ ".csv",+ ".tsv",+ ".json",+ ".jsonl",+ ".ndjson",+ ".xml",+ ".yaml",+ ".yml",+ ".toml",+ ".ini",+ ".cfg",+ ".conf",+ ".env",+ ".properties",+ ".css",+ ".scss",+ ".sass",+ ".less",+ ".svg",+ ".js",+ ".jsx",+ ".mjs",+ ".cjs",+ ".ts",+ ".tsx",+ ".py",+ ".pyi",+ ".ipynb",+ ".rb",+ ".php",+ ".go",+ ".rs",+ ".java",+ ".kt",+ ".kts",+ ".scala",+ ".swift",+ ".c",+ ".h",+ ".cc",+ ".cpp",+ ".hpp",+ ".cxx",+ ".cs",+ ".m",+ ".mm",+ ".sh",+ ".bash",+ ".zsh",+ ".fish",+ ".ps1",+ ".bat",+ ".lua",+ ".pl",+ ".pm",+ ".r",+ ".jl",+ ".dart",+ ".vue",+ ".svelte",+ ".astro",+ ".sql",+ ".graphql",+ ".gql",+ ".proto",+ ".tf",+ ".tfvars",+ ".gradle",+ ".dockerfile",+ ".makefile",+ ".cmake",+ ".diff",+ ".patch",+];++// MIME is unreliable for source files, so match by extension too.+export const TEXT_ATTACHMENT_ACCEPT = [+ "text/plain,text/markdown,text/csv,text/xml,text/json,text/css",+ "application/json,application/xml,image/svg+xml",+ TEXT_ATTACHMENT_EXTENSIONS.join(","),+].join(",");diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.tsindex 9db6749dec6..04f719f769c 100644--- a/studio/frontend/src/features/native-intents/drop-paths.ts+++ b/studio/frontend/src/features/native-intents/drop-paths.ts@@ -5,29 +5,56 @@ import {OPEN_DOCUMENT_ATTACHMENT_EXTENSIONS,isOpenDocumentAttachmentName,} from "../chat/open-document-accept.ts";+import { TEXT_ATTACHMENT_EXTENSIONS } from "../chat/text-attachment-accept.ts";import { RAG_UPLOAD_ACCEPT } from "../rag/types/rag.ts";-const DOC_EXTS = RAG_UPLOAD_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase());+const DOC_EXTS = RAG_UPLOAD_ACCEPT.split(",").map((ext) =>+ ext.trim().toLowerCase(),+);++// RAG types are filtered out, so a dropped .txt/.md keeps being indexed.+const TEXT_EXTS = TEXT_ATTACHMENT_EXTENSIONS.map((ext) =>+ ext.toLowerCase(),+).filter((ext) => !DOC_EXTS.includes(ext));++/** Dropped paths with an inline adapter but no RAG parser. */+export function isComposerAttachmentName(path: string): boolean {+ return isOpenDocumentAttachmentName(path) || isTextDropName(path);+}++function isTextDropName(path: string): boolean {+ // Rust classifies on Path::extension, which a dotfile like ".env" has none of.+ const name = nativeFileName(path).toLowerCase();+ const dot = name.lastIndexOf(".");+ if (dot <= 0) return false;+ return TEXT_EXTS.includes(name.slice(dot));+}/** 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());+const IMAGE_EXTS = CHAT_IMAGE_DROP_ACCEPT.split(",").map((ext) =>+ ext.trim().toLowerCase(),+);/** Chat audio attachments; keep in sync with `audio-attachment-adapter.ts` `accept`. */export const CHAT_AUDIO_DROP_ACCEPT = ".wav,.mp3,.m4a,.ogg,.oga,.flac";-const AUDIO_EXTS = CHAT_AUDIO_DROP_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase());+const AUDIO_EXTS = CHAT_AUDIO_DROP_ACCEPT.split(",").map((ext) =>+ ext.trim().toLowerCase(),+);/** Chat video attachments; keep in sync with `native_path_policy.rs`* `VIDEO_ATTACHMENT_EXTS`. llama-server decodes with ffmpeg, so this is what* ffmpeg reads, not what the webview can play. */export const CHAT_VIDEO_DROP_ACCEPT = ".mp4,.mov,.webm,.mkv,.avi";-const VIDEO_EXTS = CHAT_VIDEO_DROP_ACCEPT.split(",").map((ext) => ext.trim().toLowerCase());+const VIDEO_EXTS = CHAT_VIDEO_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}, ${OPEN_DOCUMENT_ATTACHMENT_EXTENSIONS}, ${CHAT_IMAGE_DROP_ACCEPT}, one of ${CHAT_AUDIO_DROP_ACCEPT}, one of ${CHAT_VIDEO_DROP_ACCEPT}, or a single .gguf model.`;+export const SUPPORTED_DROP_HINT = `Supported files: ${RAG_UPLOAD_ACCEPT}, ${OPEN_DOCUMENT_ATTACHMENT_EXTENSIONS}, source and text files, ${CHAT_IMAGE_DROP_ACCEPT}, one of ${CHAT_AUDIO_DROP_ACCEPT}, one of ${CHAT_VIDEO_DROP_ACCEPT}, or a single .gguf model.`;/** Last path segment of a native path, for display and extension checks. */export function nativeFileName(path: string): string {@@ -68,7 +95,8 @@ export function classifyDropPaths(paths: string[]): NativeDropClass {const docs = paths.filter((path) =>DOC_EXTS.some((ext) => hasExt(path, ext)) ||- isOpenDocumentAttachmentName(path),+ isOpenDocumentAttachmentName(path) ||+ isTextDropName(path),);const images = paths.filter((path) =>IMAGE_EXTS.some((ext) => hasExt(path, ext)),diff --git a/studio/frontend/src/features/native-intents/use-native-drop.ts b/studio/frontend/src/features/native-intents/use-native-drop.tsindex 34a768ac44d..3021474fc21 100644--- a/studio/frontend/src/features/native-intents/use-native-drop.ts+++ b/studio/frontend/src/features/native-intents/use-native-drop.ts@@ -1,9 +1,12 @@import { isTauri } from "@/lib/api-base";-import { useEffect, useRef, useState } from "react";import { toast } from "@/lib/toast";-import { isOpenDocumentAttachmentName } from "../chat/open-document-accept";+import { useEffect, useRef, useState } from "react";import { registerNativeAttachmentPath, registerNativeModelPath } from "./api";-import { classifyDropPaths, SUPPORTED_DROP_HINT } from "./drop-paths";+import {+ SUPPORTED_DROP_HINT,+ classifyDropPaths,+ isComposerAttachmentName,+} from "./drop-paths";import { nativeDropTargetAt } from "./native-drop-targets";import { useNativeIntentStore } from "./store";import type { NativeIntent } from "./types";@@ -56,7 +59,7 @@ function canAttachDocumentPaths(options: NativeModelDropOptions,): boolean {return paths.every((path) =>- isOpenDocumentAttachmentName(path)+ isComposerAttachmentName(path)? canAttachOpenDocuments(options): canAttachDocs(options),);@@ -78,7 +81,9 @@ function canAutoLoadModel(options: NativeModelDropOptions): boolean {);}-function attachmentCount(dropped: ReturnType<typeof classifyDropPaths>): number {+function attachmentCount(+ dropped: ReturnType<typeof classifyDropPaths>,+): number {if (dropped.kind === "docs" ||dropped.kind === "images" ||@@ -139,8 +144,10 @@ function dropStateForPaths(const docsSupported = canAttachDocumentPaths(dropped.docs, options);const imagesSupported =dropped.images.length === 0 || canAttachImages(options);- const audioSupported = dropped.audio.length === 0 || canAttachAudio(options);- const videoSupported = dropped.video.length === 0 || canAttachVideo(options);+ const audioSupported =+ dropped.audio.length === 0 || canAttachAudio(options);+ const videoSupported =+ dropped.video.length === 0 || canAttachVideo(options);return docsSupported && imagesSupported && audioSupported && videoSupported? { status: "attach", count: attachmentCount(dropped), kind: "mixed" }: { status: "invalid" };@@ -157,7 +164,7 @@ function dropStateForPaths(interface RegisteredDrop {docs: NativeIntent[];- openDocuments: NativeIntent[];+ composerDocuments: NativeIntent[];images: NativeIntent[];audio: NativeIntent[];video: NativeIntent[];@@ -202,9 +209,9 @@ async function registerDroppedAttachments(: dropped.kind === "attach"? dropped.docs: [];- const openDocumentPaths = docPaths.filter(isOpenDocumentAttachmentName);+ const composerDocumentPaths = docPaths.filter(isComposerAttachmentName);const ragDocumentPaths = docPaths.filter(- (path) => !isOpenDocumentAttachmentName(path),+ (path) => !isComposerAttachmentName(path),);const imagePaths =dropped.kind === "images"@@ -224,26 +231,26 @@ async function registerDroppedAttachments(: dropped.kind === "attach"? dropped.video: [];- const [docs, openDocuments, images, audio, video] = await Promise.all([+ const [docs, composerDocuments, images, audio, video] = await Promise.all([registerEach(ragDocumentPaths),- registerEach(openDocumentPaths),+ registerEach(composerDocumentPaths),registerEach(imagePaths),registerEach(audioPaths),registerEach(videoPaths),]);return {docs: docs.intents,- openDocuments: openDocuments.intents,+ composerDocuments: composerDocuments.intents,images: images.intents,audio: audio.intents,video: video.intents,- docsFailed: docs.failed + openDocuments.failed,+ docsFailed: docs.failed + composerDocuments.failed,imagesFailed: images.failed,audioFailed: audio.failed,videoFailed: video.failed,error:docs.error ??- openDocuments.error ??+ composerDocuments.error ??images.error ??audio.error ??video.error,@@ -255,7 +262,8 @@ function sameDropState(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 === "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;if (a.status === "invalid" && b.status === "invalid")@@ -263,10 +271,14 @@ function sameDropState(return true;}-export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelDropState {+export function useNativeModelDrop(+ options: NativeModelDropOptions,+): NativeModelDropState {const { enabled = true } = options;const addIntent = useNativeIntentStore((state) => state.addIntent);- const [dropState, setDropState] = useState<NativeModelDropState>({ status: "idle" });+ const [dropState, setDropState] = useState<NativeModelDropState>({+ status: "idle",+ });const optionsRef = useRef(options);optionsRef.current = options;@@ -286,208 +298,223 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelsetDropState((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") {- 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 !== "drop") {- publish(dropStateForPaths(draggedPaths, currentOptions));- return;- }- draggedPaths = [];- publish({ status: "idle" });- const dropped = classifyDropPaths(event.payload.paths);- if (dropped.kind === "none") return;- if (dropped.kind === "unsupported") {- toast.error(SUPPORTED_DROP_HINT);- return;- }- // Before the model branch too: this view loads nothing, so a dropped- // GGUF must not replace the active model behind it.- if (currentOptions.dropsUnsupportedReason && isActionableKind(dropped)) {- toast.error(currentOptions.dropsUnsupportedReason);- return;- }- if (- dropped.kind === "docs" ||- dropped.kind === "images" ||- dropped.kind === "audio" ||- dropped.kind === "video" ||- dropped.kind === "attach"- ) {- const needsImages =- dropped.kind === "images" ||- (dropped.kind === "attach" && dropped.images.length > 0);- const documentPaths =- dropped.kind === "docs"- ? dropped.paths- : dropped.kind === "attach"- ? dropped.docs- : [];- const openDocumentPaths = documentPaths.filter(- isOpenDocumentAttachmentName,- );- const needsRagDocuments = documentPaths.some(- (path) => !isOpenDocumentAttachmentName(path),- );- const needsOpenDocuments = openDocumentPaths.length > 0;- const needsComposerAttachments = needsImages || needsOpenDocuments;- const needsAudio =- dropped.kind === "audio" ||- (dropped.kind === "attach" && dropped.audio.length > 0);- const needsVideo =- dropped.kind === "video" ||- (dropped.kind === "attach" && dropped.video.length > 0);- if (needsRagDocuments && !canAttachDocs(currentOptions)) {- toast.error("Attaching files needs the desktop backend", {- description: "Retry once Studio has finished starting up.",- });+ .then(({ getCurrentWindow }) =>+ getCurrentWindow().onDragDropEvent(async (event) => {+ const currentOptions = optionsRef.current;+ if (event.payload.type === "leave") {+ draggedPaths = [];+ publish({ status: "idle" });return;}- if (needsImages && !canAttachImages(currentOptions)) {- toast.error("Attaching images is unavailable right now", {- description: "Retry once this chat is ready for attachments.",- });+ if (event.payload.type === "enter") {+ 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 (- needsOpenDocuments &&- !canAttachOpenDocuments(currentOptions)- ) {- toast.error("Attaching files is unavailable right now", {- description: "Retry once this chat is ready for attachments.",- });+ if (event.payload.type !== "drop") {+ publish(dropStateForPaths(draggedPaths, currentOptions));return;}- if (needsAudio && !canAttachAudio(currentOptions)) {- toast.error("Attaching audio is unavailable right now", {- description: "Retry once this chat is ready for attachments.",- });+ draggedPaths = [];+ publish({ status: "idle" });+ const dropped = classifyDropPaths(event.payload.paths);+ if (dropped.kind === "none") return;+ if (dropped.kind === "unsupported") {+ toast.error(SUPPORTED_DROP_HINT);return;}- if (needsVideo && !canAttachVideo(currentOptions)) {- toast.error("Attaching video is unavailable right now", {- description: "Retry once this chat is ready for attachments.",- });+ // Before the model branch too: this view loads nothing, so a dropped+ // GGUF must not replace the active model behind it.+ if (+ currentOptions.dropsUnsupportedReason &&+ isActionableKind(dropped)+ ) {+ toast.error(currentOptions.dropsUnsupportedReason);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 attachment.- const store = useNativeIntentStore.getState();- if (needsComposerAttachments) store.beginImageDropRegistration();- if (needsAudio) store.beginAudioDropRegistration();- if (needsVideo) store.beginVideoDropRegistration();- try {- 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;- if (registered.docs.length > 0) {- await attachOptions.onAttach?.(registered.docs);- }- if (registered.images.length > 0) {- await attachOptions.onAttachImages?.(registered.images);+ if (+ dropped.kind === "docs" ||+ dropped.kind === "images" ||+ dropped.kind === "audio" ||+ dropped.kind === "video" ||+ dropped.kind === "attach"+ ) {+ const needsImages =+ dropped.kind === "images" ||+ (dropped.kind === "attach" && dropped.images.length > 0);+ const documentPaths =+ dropped.kind === "docs"+ ? dropped.paths+ : dropped.kind === "attach"+ ? dropped.docs+ : [];+ const composerDocumentPaths = documentPaths.filter(+ isComposerAttachmentName,+ );+ const needsRagDocuments = documentPaths.some(+ (path) => !isComposerAttachmentName(path),+ );+ const needsComposerDocuments = composerDocumentPaths.length > 0;+ const needsComposerAttachments =+ needsImages || needsComposerDocuments;+ const needsAudio =+ dropped.kind === "audio" ||+ (dropped.kind === "attach" && dropped.audio.length > 0);+ const needsVideo =+ dropped.kind === "video" ||+ (dropped.kind === "attach" && dropped.video.length > 0);+ if (needsRagDocuments && !canAttachDocs(currentOptions)) {+ toast.error("Attaching files needs the desktop backend", {+ description: "Retry once Studio has finished starting up.",+ });+ return;}- if (registered.openDocuments.length > 0) {- await attachOptions.onAttachOpenDocuments?.(- registered.openDocuments,- );+ if (needsImages && !canAttachImages(currentOptions)) {+ toast.error("Attaching images is unavailable right now", {+ description: "Retry once this chat is ready for attachments.",+ });+ return;}- const failureKey = attachOptions.attachmentTargetKey;- if (registered.imagesFailed > 0 && failureKey) {- store.failImageDropRegistration(failureKey);+ if (+ needsComposerDocuments &&+ !canAttachOpenDocuments(currentOptions)+ ) {+ toast.error("Attaching files is unavailable right now", {+ description: "Retry once this chat is ready for attachments.",+ });+ return;}- if (registered.audioFailed > 0 && failureKey) {- store.failAudioDropRegistration(failureKey);+ if (needsAudio && !canAttachAudio(currentOptions)) {+ toast.error("Attaching audio is unavailable right now", {+ description: "Retry once this chat is ready for attachments.",+ });+ return;}- if (registered.videoFailed > 0 && failureKey) {- store.failVideoDropRegistration(failureKey);+ if (needsVideo && !canAttachVideo(currentOptions)) {+ toast.error("Attaching video is unavailable right now", {+ description: "Retry once this chat is ready for attachments.",+ });+ return;}- // A failed document cancels a send parked behind the attachment, audio- // or video gates too, or the draft goes out with only what survived.- if (registered.docsFailed > 0 && failureKey) {- if (needsComposerAttachments) {+ // 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 attachment.+ const store = useNativeIntentStore.getState();+ if (needsComposerAttachments) store.beginImageDropRegistration();+ if (needsAudio) store.beginAudioDropRegistration();+ if (needsVideo) store.beginVideoDropRegistration();+ try {+ 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;+ if (registered.docs.length > 0) {+ await attachOptions.onAttach?.(registered.docs);+ }+ // Documents first: a vision-less model throws on the image and+ // aborts the batch, which would discard them.+ const composerAttachments = [+ ...registered.composerDocuments,+ ...registered.images,+ ];+ if (registered.composerDocuments.length > 0) {+ await attachOptions.onAttachOpenDocuments?.(+ composerAttachments,+ );+ } else if (registered.images.length > 0) {+ await attachOptions.onAttachImages?.(registered.images);+ }+ const failureKey = attachOptions.attachmentTargetKey;+ if (registered.imagesFailed > 0 && failureKey) {store.failImageDropRegistration(failureKey);}- if (needsAudio) store.failAudioDropRegistration(failureKey);- if (needsVideo) store.failVideoDropRegistration(failureKey);- }- if (registered.audio.length > 0) {- await attachOptions.onAttachAudio?.(registered.audio);- }- if (registered.video.length > 0) {- await attachOptions.onAttachVideo?.(registered.video);- }- if (- registered.docsFailed +- registered.imagesFailed +- registered.audioFailed +- registered.videoFailed >- 0- ) {+ if (registered.audioFailed > 0 && failureKey) {+ store.failAudioDropRegistration(failureKey);+ }+ if (registered.videoFailed > 0 && failureKey) {+ store.failVideoDropRegistration(failureKey);+ }+ // A failed document cancels a send parked behind the attachment, audio+ // or video gates too, or the draft goes out with only what survived.+ if (registered.docsFailed > 0 && failureKey) {+ if (needsComposerAttachments) {+ store.failImageDropRegistration(failureKey);+ }+ if (needsAudio) store.failAudioDropRegistration(failureKey);+ if (needsVideo) store.failVideoDropRegistration(failureKey);+ }+ if (registered.audio.length > 0) {+ await attachOptions.onAttachAudio?.(registered.audio);+ }+ if (registered.video.length > 0) {+ await attachOptions.onAttachVideo?.(registered.video);+ }+ if (+ registered.docsFailed ++ registered.imagesFailed ++ registered.audioFailed ++ registered.videoFailed >+ 0+ ) {+ toast.error("Could not attach dropped files", {+ description:+ registered.error?.message ?? "Some files were skipped.",+ });+ }+ } catch (error) {+ const failureKey = currentOptions.attachmentTargetKey;+ if (needsComposerAttachments && failureKey) {+ store.failImageDropRegistration(failureKey);+ }+ if (needsAudio && failureKey) {+ store.failAudioDropRegistration(failureKey);+ }+ if (needsVideo && failureKey) {+ store.failVideoDropRegistration(failureKey);+ }toast.error("Could not attach dropped files", {- description: registered.error?.message ?? "Some files were skipped.",+ description:+ error instanceof Error ? error.message : String(error),});+ } finally {+ if (needsComposerAttachments) store.endImageDropRegistration();+ if (needsAudio) store.endAudioDropRegistration();+ if (needsVideo) store.endVideoDropRegistration();}- } catch (error) {- const failureKey = currentOptions.attachmentTargetKey;- if (needsComposerAttachments && failureKey) {- store.failImageDropRegistration(failureKey);- }- if (needsAudio && failureKey) {- store.failAudioDropRegistration(failureKey);- }- if (needsVideo && failureKey) {- store.failVideoDropRegistration(failureKey);- }- toast.error("Could not attach dropped files", {- description: error instanceof Error ? error.message : String(error),- });- } finally {- if (needsComposerAttachments) store.endImageDropRegistration();- if (needsAudio) store.endAudioDropRegistration();- if (needsVideo) store.endVideoDropRegistration();- }- return;- }- try {- const intent = await registerNativeModelPath(dropped.path);- if (disposed) return;- if (!canAutoLoadModel(currentOptions)) {- addIntent(intent);return;}try {- await currentOptions.onAutoLoad?.(intent);+ const intent = await registerNativeModelPath(dropped.path);+ if (disposed) return;+ if (!canAutoLoadModel(currentOptions)) {+ addIntent(intent);+ return;+ }+ try {+ await currentOptions.onAutoLoad?.(intent);+ } catch (error) {+ addIntent(intent);+ toast.error("Could not load dropped model", {+ description:+ error instanceof Error ? error.message : String(error),+ });+ }} catch (error) {- addIntent(intent);- toast.error("Could not load dropped model", {- description: error instanceof Error ? error.message : String(error),+ toast.error("Could not use dropped model", {+ description:+ error instanceof Error ? error.message : String(error),});}- } catch (error) {- toast.error("Could not use dropped model", {- description: error instanceof Error ? error.message : String(error),- });- }- }))+ }),+ ).then((cleanup) => {if (disposed) {cleanup();diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex dacf3066a00..855951fcc77 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -9,6 +9,10 @@ import {OPEN_DOCUMENT_ATTACHMENT_ACCEPT,OPEN_DOCUMENT_ATTACHMENT_EXTENSIONS,} from "../src/features/chat/open-document-accept.ts";+import {+ TEXT_ATTACHMENT_ACCEPT,+ TEXT_ATTACHMENT_EXTENSIONS,+} from "../src/features/chat/text-attachment-accept.ts";import {dequeueNativeAttachments,enqueueNativeAttachments,@@ -19,6 +23,7 @@ import {CHAT_VIDEO_DROP_ACCEPT,SUPPORTED_DROP_HINT,classifyDropPaths,+ isComposerAttachmentName,} 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";@@ -37,16 +42,23 @@ const BACKEND_UPLOAD_EXTS_RE = /UPLOAD_EXTS\s*=\s*\{([^}]+)\}/s;const RUST_ATTACHMENT_EXTS_RE = /ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;const RUST_OPEN_DOCUMENT_ATTACHMENT_EXTS_RE =/OPEN_DOCUMENT_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;-const RUST_IMAGE_ATTACHMENT_EXTS_RE = /IMAGE_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;-const RUST_AUDIO_ATTACHMENT_EXTS_RE = /AUDIO_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;+const RUST_IMAGE_ATTACHMENT_EXTS_RE =+ /IMAGE_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;+const RUST_AUDIO_ATTACHMENT_EXTS_RE =+ /AUDIO_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;const RUST_AUDIO_MIME_RE = /Some\("(audio\/[^"]+)"\)/g;-const RUST_VIDEO_ATTACHMENT_EXTS_RE = /VIDEO_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;+const RUST_VIDEO_ATTACHMENT_EXTS_RE =+ /VIDEO_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;+const RUST_TEXT_ATTACHMENT_EXTS_RE =+ /TEXT_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;const RUST_VIDEO_MIME_RE = /Some\("(video\/[^"]+)"\)/g;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 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;@@ -54,13 +66,13 @@ const OPEN_DOCUMENT_EXTENSION_RE = /\.ods/;const OPEN_DOCUMENT_ADAPTER_ACCEPT_RE =/class OpenDocumentAttachmentAdapter[^{]*\{[\s\S]*?accept = OPEN_DOCUMENT_ATTACHMENT_ACCEPT;/;const OPEN_DOCUMENT_DROP_TO_COMPOSER_RE =- /await attachOptions\.onAttachImages\?\.\(registered\.images\)[\s\S]*?await attachOptions\.onAttachOpenDocuments\?\.\([\s\S]*?registered\.openDocuments/;+ /const composerAttachments = \[[\s\S]*?\.\.\.registered\.composerDocuments,[\s\S]*?\.\.\.registered\.images,[\s\S]*?await attachOptions\.onAttachOpenDocuments\?\.\([\s\S]*?composerAttachments/;const OPEN_DOCUMENT_REGISTRATION_CLASS_RE =- /const openDocumentPaths = docPaths\.filter\(isOpenDocumentAttachmentName\);[\s\S]*?const ragDocumentPaths = docPaths\.filter[\s\S]*?registerEach\(ragDocumentPaths\),[\s\S]*?registerEach\(openDocumentPaths\),[\s\S]*?openDocuments: openDocuments\.intents/;+ /const composerDocumentPaths = docPaths\.filter\(isComposerAttachmentName\);[\s\S]*?const ragDocumentPaths = docPaths\.filter[\s\S]*?registerEach\(ragDocumentPaths\),[\s\S]*?registerEach\(composerDocumentPaths\),[\s\S]*?composerDocuments: composerDocuments\.intents/;const OPEN_DOCUMENT_IMAGE_REGISTRATION_RE =- /const needsOpenDocuments = openDocumentPaths\.length > 0;[\s\S]*?const needsComposerAttachments = needsImages \|\| needsOpenDocuments;[\s\S]*?if \(needsComposerAttachments\) store\.beginImageDropRegistration\(\);[\s\S]*?finally \{[\s\S]*?if \(needsComposerAttachments\) store\.endImageDropRegistration\(\)/;+ /const needsComposerDocuments = composerDocumentPaths\.length > 0;[\s\S]*?const needsComposerAttachments =\s*needsImages \|\| needsComposerDocuments;[\s\S]*?if \(needsComposerAttachments\) store\.beginImageDropRegistration\(\);[\s\S]*?finally \{[\s\S]*?if \(needsComposerAttachments\) store\.endImageDropRegistration\(\)/;const OPEN_DOCUMENT_BACKEND_GATE_RE =- /function canAttachDocumentPaths[\s\S]*?isOpenDocumentAttachmentName\(path\)[\s\S]*?\? canAttachOpenDocuments\(options\)[\s\S]*?: canAttachDocs\(options\)[\s\S]*?const needsRagDocuments = documentPaths\.some[\s\S]*?if \(needsRagDocuments && !canAttachDocs\(currentOptions\)\)/;+ /function canAttachDocumentPaths[\s\S]*?isComposerAttachmentName\(path\)[\s\S]*?\? canAttachOpenDocuments\(options\)[\s\S]*?: canAttachDocs\(options\)[\s\S]*?const needsRagDocuments = documentPaths\.some[\s\S]*?if \(needsRagDocuments && !canAttachDocs\(currentOptions\)\)/;const OPEN_DOCUMENT_CHAT_QUEUE_RE =/const handleNativeOpenDocumentDrop = useCallback\([\s\S]*?addOpenDocumentAttachments\(artifactViewKey, intents\)[\s\S]*?onAttachOpenDocuments: handleNativeOpenDocumentDrop/;const OPEN_DOCUMENT_DRAIN_RE =@@ -316,7 +328,10 @@ test("every MIME type Rust stamps is one the vision adapter claims", () => {.map((type) => type.trim()).sort();- assert.ok(stamped.length > 0, "no image MIME arms found in native_intents.rs");+ assert.ok(+ stamped.length > 0,+ "no image MIME arms found in native_intents.rs",+ );assert.deepEqual(stamped, accepted);});@@ -342,7 +357,9 @@ test("every accepted image extension has a Rust MIME arm", () => {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]))+ .flatMap((match) =>+ [...match[1].matchAll(/"([^"]+)"/g)].map((ext) => ext[1]),+ ).sort();assert.ok(accepted.length > 0, "no IMAGE_ATTACHMENT_EXTS found");@@ -392,7 +409,8 @@ test("a remounted composer claims image and OpenDocument batches", () => {// A different composer must not take it.store.claimImageAttachments("composer-2", "single:other");assert.equal(- useNativeIntentStore.getState().pendingImageAttachments["single:new"]?.length,+ useNativeIntentStore.getState().pendingImageAttachments["single:new"]+ ?.length,1,);@@ -401,10 +419,9 @@ test("a remounted composer claims image and OpenDocument batches", () => {assert.equal(after.pendingImageAttachments["single:new"], undefined);assert.deepEqual(after.pendingImageAttachments["single:thread-7"], [intent]);assert.equal(after.pendingOpenDocumentAttachments["single:new"], undefined);- assert.deepEqual(- after.pendingOpenDocumentAttachments["single:thread-7"],- [openDocument],- );+ assert.deepEqual(after.pendingOpenDocumentAttachments["single:thread-7"], [+ openDocument,+ ]);assert.deepEqual(after.imageDropOwners, {});});@@ -430,7 +447,11 @@ test("ownership recorded after a claim is still picked up", () => {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");+ 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();@@ -455,7 +476,11 @@ test("image failures cannot consume queued OpenDocuments", () => {test("document, image and audio drop extensions stay disjoint", () => {// classifyDropPaths sums the three filters; an overlap double-counts and// turns a good drop into "unsupported".- const exts = [RAG_UPLOAD_ACCEPT, CHAT_IMAGE_DROP_ACCEPT, CHAT_AUDIO_DROP_ACCEPT]+ const exts = [+ RAG_UPLOAD_ACCEPT,+ CHAT_IMAGE_DROP_ACCEPT,+ CHAT_AUDIO_DROP_ACCEPT,+ ].flatMap((accept) => accept.split(",")).map((ext) => ext.trim().toLowerCase());assert.deepEqual(@@ -643,3 +668,78 @@ test("the native video cap is the raw limit the reference picker enforces", () =// The thing that made this wrong: the two differ by a third.assert.ok(rustCap < 96 * 1024 * 1024);});++test("a dropped source file attaches instead of being refused", () => {+ for (const path of ["/src/Program.cs", "/src/index.php", "/app/main.js"]) {+ assert.equal(classifyDropPaths([path]).kind, "docs", path);+ assert.equal(isComposerAttachmentName(path), true, path);+ }+ const mixed = classifyDropPaths(["/src/a.cs", "/notes/report.pdf"]);+ assert.equal(mixed.kind, "docs");+});++test("RAG documents keep their existing route", () => {+ for (const path of ["/docs/notes.txt", "/docs/notes.md", "/docs/paper.pdf"]) {+ assert.equal(classifyDropPaths([path]).kind, "docs", path);+ assert.equal(isComposerAttachmentName(path), false, path);+ }+});++test("a dotfile is not mistaken for a source file", () => {+ // Rust classifies on Path::extension, which ".env" does not have.+ for (const path of ["/p/.env", "/p/.properties", "/p/.log"]) {+ assert.equal(isComposerAttachmentName(path), false, path);+ assert.equal(classifyDropPaths([path]).kind, "unsupported", path);+ }+ assert.equal(isComposerAttachmentName("/p/app.env"), true);+});++test("an unreadable type is still refused", () => {+ assert.equal(classifyDropPaths(["/docs/archive.zip"]).kind, "unsupported");+ assert.equal(classifyDropPaths(["/bin/tool.exe"]).kind, "unsupported");+});++test("frontend and Rust accept the same dropped text extensions", () => {+ const docs = RAG_UPLOAD_ACCEPT.split(",").map((ext) =>+ ext.trim().toLowerCase(),+ );+ const frontend = TEXT_ATTACHMENT_EXTENSIONS.map((ext) => ext.toLowerCase())+ .filter((ext) => !docs.includes(ext))+ .sort();+ const rustSource = readFileSync(+ new URL("../../src-tauri/src/native_path_policy.rs", import.meta.url),+ "utf8",+ );+ const rust = [+ ...(rustSource+ .match(RUST_TEXT_ATTACHMENT_EXTS_RE)?.[1]+ .matchAll(RUST_EXTENSION_RE) ?? []),+ ]+ .map((match) => `.${match[1]}`)+ .sort();++ assert.deepEqual(rust, frontend);+});++test("the composer adapter reads the shared text accept list", () => {+ const src = readFileSync(+ new URL("../src/features/chat/runtime-provider.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /class TextAttachmentAdapter implements AttachmentAdapter \{[\s\S]*?accept = TEXT_ATTACHMENT_ACCEPT;/,+ );+ for (const ext of [".cs", ".php", ".js"]) {+ assert.ok(TEXT_ATTACHMENT_ACCEPT.includes(ext), ext);+ }++ const attachmentContentSource = readFileSync(+ new URL("../src/features/chat/attachment-content.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ attachmentContentSource,+ /import \{ TEXT_ATTACHMENT_ACCEPT \} from "\.\/text-attachment-accept";/,+ );+});diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rsindex 35d5a4db39d..d39a879a784 100644--- a/studio/src-tauri/src/native_intents.rs+++ b/studio/src-tauri/src/native_intents.rs@@ -596,11 +596,16 @@ pub fn open_path_token() -> Result<(), String> {ensure_main_window(&window)?;let entry = state.path_for_operation(&token, NativePathOperation::Open)?;- crate::process::open_detached(entry.canonical_path).map_err(|e| format!("Failed to open path: {e}"))+ crate::process::open_detached(entry.canonical_path)+ .map_err(|e| format!("Failed to open path: {e}"))}// Covers the generic client-side limit (audio, 25 MB).const MAX_NATIVE_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;++// Matches the clipboard reader, so a dropped source file and a pasted one+// accept the same sizes.+const MAX_NATIVE_TEXT_BYTES: u64 = 20 * 1024 * 1024;// OpenDocument archives use the composer's larger archive limit.const MAX_NATIVE_OPEN_DOCUMENT_BYTES: u64 = 50 * 1024 * 1024;// Images stop lower: the composer throws over 20 MB without a toast and the@@ -639,6 +644,14 @@ fn attachment_mime_type(path: &Path) -> Option<&'static str> {"avi" => Some("video/x-msvideo"),"ods" => Some("application/vnd.oasis.opendocument.spreadsheet"),"odt" => Some("application/vnd.oasis.opendocument.text"),+ // Stamped like native_clipboard.rs.+ "json" | "jsonl" | "ndjson" => Some("application/json"),+ "mdx" => Some("text/markdown"),+ "csv" => Some("text/csv"),+ "xml" => Some("application/xml"),+ other if crate::native_path_policy::TEXT_ATTACHMENT_EXTS.contains(&other) => {+ Some("text/plain")+ }_ => None,}}@@ -686,10 +699,16 @@ fn open_attachment_file(path: &Path) -> Result<fs::File, String> {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, audio and video attachments can be read inline.".to_string()- })?;- let max_bytes = if mime_type.starts_with("image/") {+ let mime_type = attachment_mime_type(path)+ .ok_or_else(|| "Only chat attachments can be read inline.".to_string())?;+ let is_text_attachment = path+ .extension()+ .and_then(|value| value.to_str())+ .map(|value| value.to_ascii_lowercase())+ .is_some_and(|ext| crate::native_path_policy::TEXT_ATTACHMENT_EXTS.contains(&ext.as_str()));+ let max_bytes = if is_text_attachment {+ MAX_NATIVE_TEXT_BYTES+ } else if mime_type.starts_with("image/") {MAX_NATIVE_IMAGE_BYTES} else if mime_type.starts_with("video/") {MAX_NATIVE_VIDEO_BYTES@@ -764,10 +783,12 @@ mod tests {.duration_since(UNIX_EPOCH).unwrap().as_nanos();- crate::native_path_policy::scratch_root().join(format!("unsloth-native-intents-{name}-{}-{nanos}", std::process::id()))+ crate::native_path_policy::scratch_root().join(format!(+ "unsloth-native-intents-{name}-{}-{nanos}",+ std::process::id()+ ))}-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()));@@ -840,10 +861,42 @@ mod tests {let Err(err) = read_attachment_payload(&entry) else {panic!("expected the read to be refused");};- assert!(err.contains("Only chat image, audio and video attachments"));+ assert!(err.contains("Only chat attachments can be read inline"));+ let _ = fs::remove_file(path);+ }++ #[test]+ fn text_attachments_read_inline_with_their_own_cap() {+ for (ext, mime) in [+ ("cs", "text/plain"),+ ("php", "text/plain"),+ ("js", "text/plain"),+ ("json", "application/json"),+ ("csv", "text/csv"),+ ] {+ let path = temp_path("source").with_extension(ext);+ fs::write(&path, b"sample").unwrap();+ let (_state, entry) = attachment_entry(&path);+ let payload = read_attachment_payload(&entry).unwrap();+ assert_eq!(payload.mime_type, mime, "{ext}");+ let _ = fs::remove_file(path);+ }++ let path = temp_path("huge").with_extension("cs");+ fs::write(&path, vec![b'x'; MAX_NATIVE_TEXT_BYTES as usize + 1]).unwrap();+ let (_state, entry) = attachment_entry(&path);+ assert!(read_attachment_payload(&entry).is_err());let _ = fs::remove_file(path);}+ #[test]+ fn every_text_extension_the_drop_accepts_has_a_mime_type() {+ for ext in crate::native_path_policy::TEXT_ATTACHMENT_EXTS {+ let path = PathBuf::from(format!("sample.{ext}"));+ assert!(attachment_mime_type(&path).is_some(), "{ext}");+ }+ }+#[test]fn image_read_rejects_a_file_swapped_in_after_validation() {let path = temp_path("swap").with_extension("png");diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rsindex 60e5f34bfe4..21114ae1da6 100644--- a/studio/src-tauri/src/native_path_policy.rs+++ b/studio/src-tauri/src/native_path_policy.rs@@ -52,6 +52,88 @@ pub const ATTACHMENT_EXTS: &[&str] = &["pdf", "txt", "md", "markdown", "docx", "pub const OPEN_DOCUMENT_ATTACHMENT_EXTS: &[&str] = &["ods", "odt"];pub const TRAINING_DATASET_EXTS: &[&str] = &["csv", "json", "jsonl", "parquet"];+/// Keep in sync with `text-attachment-accept.ts`. RAG types are absent so a+/// dropped .txt/.md keeps being indexed.+pub const TEXT_ATTACHMENT_EXTS: &[&str] = &[+ "text",+ "log",+ "mdx",+ "rst",+ "csv",+ "tsv",+ "json",+ "jsonl",+ "ndjson",+ "xml",+ "yaml",+ "yml",+ "toml",+ "ini",+ "cfg",+ "conf",+ "env",+ "properties",+ "css",+ "scss",+ "sass",+ "less",+ "svg",+ "js",+ "jsx",+ "mjs",+ "cjs",+ "ts",+ "tsx",+ "py",+ "pyi",+ "ipynb",+ "rb",+ "php",+ "go",+ "rs",+ "java",+ "kt",+ "kts",+ "scala",+ "swift",+ "c",+ "h",+ "cc",+ "cpp",+ "hpp",+ "cxx",+ "cs",+ "m",+ "mm",+ "sh",+ "bash",+ "zsh",+ "fish",+ "ps1",+ "bat",+ "lua",+ "pl",+ "pm",+ "r",+ "jl",+ "dart",+ "vue",+ "svelte",+ "astro",+ "sql",+ "graphql",+ "gql",+ "proto",+ "tf",+ "tfvars",+ "gradle",+ "dockerfile",+ "makefile",+ "cmake",+ "diff",+ "patch",+];+/// 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"];@@ -67,6 +149,7 @@ fn accepted_attachment_exts() -> impl Iterator<Item = &'static &'static str> {ATTACHMENT_EXTS.iter().chain(OPEN_DOCUMENT_ATTACHMENT_EXTS.iter())+ .chain(TEXT_ATTACHMENT_EXTS.iter()).chain(IMAGE_ATTACHMENT_EXTS.iter()).chain(AUDIO_ATTACHMENT_EXTS.iter()).chain(VIDEO_ATTACHMENT_EXTS.iter())@@ -77,8 +160,8 @@ pub fn classify_native_attachment_path(path: &Path) -> Result<ClassifiedPath, Stif classified.path_type != NativePathType::File {return Err("Only files can be attached to a chat.".to_string());}- let supported = accepted_attachment_exts()- .any(|ext| has_extension(&classified.canonical_path, ext));+ let supported =+ accepted_attachment_exts().any(|ext| has_extension(&classified.canonical_path, ext));if !supported {return Err(format!("Unsupported attachment type. Supported: {}",@@ -639,10 +722,12 @@ mod tests {.duration_since(UNIX_EPOCH).unwrap().as_nanos();- scratch_root().join(format!("unsloth-native-policy-{name}-{}-{nanos}", std::process::id()))+ scratch_root().join(format!(+ "unsloth-native-policy-{name}-{}-{nanos}",+ std::process::id()+ ))}-#[test]fn gguf_model_allows_validate_load_reveal() {let path = temp_path("model").with_extension("gguf");