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: fix audio files being rejected when dropped on the chat (#8271)
Nilayaab5c2c980ce
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 6915815a329..fe00b2db31d 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -2168,6 +2168,17 @@ const Composer: FC<{);const [materializingDroppedImages, setMaterializingDroppedImages] =useState(false);+ const hasPendingAudioAttachments = useNativeIntentStore((s) =>+ Boolean(+ nativeAttachmentTargetKey &&+ (s.pendingAudioAttachments[nativeAttachmentTargetKey]?.length ?? 0) > 0,+ ),+ );+ const registeringAudioDrops = useNativeIntentStore(+ (s) => s.registeringAudioDrops > 0,+ );+ const [materializingDroppedAudio, setMaterializingDroppedAudio] =+ 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);@@ -2184,6 +2195,133 @@ const Composer: FC<{seenImageDropFailuresRef.current = imageDropFailures;cancelQueuedSendRef.current?.();}, [imageDropFailures]);+ const audioDropFailures = useNativeIntentStore(+ (s) => (nativeAttachmentTargetKey ? s.audioDropFailures[nativeAttachmentTargetKey] : 0) ?? 0,+ );+ const seenAudioDropFailuresRef = useRef(audioDropFailures);+ // Cancel the parked send before `endAudioDropRegistration` reopens the gate.+ useEffect(() => {+ if (seenAudioDropFailuresRef.current === audioDropFailures) return;+ seenAudioDropFailuresRef.current = audioDropFailures;+ cancelQueuedSendRef.current?.();+ }, [audioDropFailures]);+ // Registering and reading a dropped clip is async, so hold the send gate:+ // the composer sees nothing until `addAttachment` lands.+ useEffect(() => {+ if (!nativeAttachmentTargetKey) {+ return;+ }+ const targetKey = nativeAttachmentTargetKey;+ const identityAtSetup = composerIdentityRef.current;+ useNativeIntentStore+ .getState()+ .claimAudioAttachments(identityAtSetup, targetKey);+ let disposed = false;+ let draining = false;++ // A re-key follows the same composer; a thread switch parks the clip back.+ const stillThisComposer = () =>+ composerIdentityRef.current === identityAtSetup;+ // A remount hides the new key, so tag the batch; the next instance claims it.+ const requeue = (intents: NativeIntent[]) => {+ const key = stillThisComposer()+ ? (nativeAttachmentTargetKeyRef.current ?? targetKey)+ : targetKey;+ const store = useNativeIntentStore.getState();+ store.addAudioAttachments(key, intents);+ store.noteAudioDropOwner(key, identityAtSetup);+ };++ const drainPendingAudio = async () => {+ if (disposed || draining) return;+ draining = true;+ setMaterializingDroppedAudio(true);+ try {+ while (!disposed) {+ const intents = useNativeIntentStore+ .getState()+ .takeAudioAttachments(targetKey);+ if (intents.length === 0) break;+ for (const [index, intent] of intents.entries()) {+ if (disposed) {+ requeue(intents.slice(index));+ return;+ }+ let file: File;+ try {+ file = await nativeAttachmentIntentToFile(intent);+ } catch (error) {+ toast.error("Could not attach dropped audio", {+ description:+ error instanceof Error ? error.message : String(error),+ });+ // Do not let a send parked on this clip go out as bare text.+ if (stillThisComposer()) cancelQueuedSendRef.current?.();+ continue;+ }+ // The read is async; a chat switch in that window must not steal the clip.+ if (+ disposed ||+ nativeAttachmentTargetKeyRef.current !== targetKey+ ) {+ requeue(intents.slice(index));+ return;+ }+ try {+ await aui.composer().addAttachment(file);+ } catch {+ // Chat-wide, not per file (no audio model, too large, already+ // attached), and every adapter path toasted: stop quietly.+ if (stillThisComposer()) cancelQueuedSendRef.current?.();+ return;+ }+ }+ }+ } finally {+ draining = false;+ // A drain for a target already left must not touch the flag; cleanup+ // cleared it, and the live target may have set it again.+ if (!disposed) {+ // The early returns requeue mid-batch, and a drop can land while+ // `draining` gated the subscription.+ const pending =+ useNativeIntentStore.getState().pendingAudioAttachments[targetKey]+ ?.length ?? 0;+ // Only the instance still owning this composer re-drains; otherwise+ // the batch stays parked rather than looping here forever.+ if (pending > 0 && stillThisComposer()) {+ void drainPendingAudio();+ } else {+ setMaterializingDroppedAudio(false);+ }+ }+ }+ };++ const unsubscribe = useNativeIntentStore.subscribe((state) => {+ // A predecessor's requeue can land after setup, so keep watching.+ const orphaned = Object.entries(state.audioDropOwners).some(+ ([key, owner]) => owner === identityAtSetup && key !== targetKey,+ );+ if (orphaned) {+ useNativeIntentStore+ .getState()+ .claimAudioAttachments(identityAtSetup, targetKey);+ return;+ }+ if ((state.pendingAudioAttachments[targetKey]?.length ?? 0) > 0) {+ void drainPendingAudio();+ }+ });+ void drainPendingAudio();++ return () => {+ disposed = true;+ setMaterializingDroppedAudio(false);+ unsubscribe();+ };+ }, [nativeAttachmentTargetKey, aui]);+useEffect(() => {if (!nativeAttachmentTargetKey) {return;@@ -2321,6 +2459,10 @@ const Composer: FC<{registeringImageDrops ||hasPendingImageAttachments ||materializingDroppedImages;+ const hasMaterializingAudioAttachments =+ registeringAudioDrops ||+ hasPendingAudioAttachments ||+ materializingDroppedAudio;const threadIsRunning = useAuiState(({ thread }) => thread.isRunning);const threadListItemId = useAuiState(({ threadListItem }) => threadListItem.id,@@ -2361,6 +2503,7 @@ const Composer: FC<{!isComposing &&!hasPendingAttachments &&!hasMaterializingImageAttachments &&+ !hasMaterializingAudioAttachments &&!disabled &&!overlay;@@ -2847,14 +2990,16 @@ const Composer: FC<{cancelQueuedSendRef.current = cancelQueuedSend;const enqueueSend = useCallback(- (waitingOn: "indexing" | "images" = "indexing") => {+ (waitingOn: "indexing" | "images" | "audio" = "indexing") => {if (pendingSendRef.current) return;pendingSendRef.current = true;setPendingSend(true);const title =waitingOn === "images"? "Waiting for dropped images"- : "Waiting for documents to finish indexing";+ : waitingOn === "audio"+ ? "Waiting for dropped audio"+ : "Waiting for documents to finish indexing";waitToastRef.current = toast(title, {description: "Your message will send automatically once they are ready.",duration: Infinity,@@ -2864,24 +3009,25 @@ const Composer: FC<{[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(() => {+ // A materializing image or clip is a wait, not a refusal: park the send.+ // Both gates share this so they cannot disagree on what is recoverable.+ const parkIfWaitingOnAttachments = useCallback(() => {if (disabled ||overlay ||- !hasMaterializingImageAttachments ||+ (!hasMaterializingImageAttachments && !hasMaterializingAudioAttachments) ||!hasSendableContent ||isComposingRef.current ||hasPendingAttachments) {return;}- enqueueSend("images");+ enqueueSend(hasMaterializingImageAttachments ? "images" : "audio");}, [disabled,overlay,hasMaterializingImageAttachments,+ hasMaterializingAudioAttachments,hasSendableContent,hasPendingAttachments,isComposingRef,@@ -2893,8 +3039,10 @@ const Composer: FC<{!hasSendableContent ||isComposingRef.current ||hasPendingAttachments ||- hasMaterializingImageAttachments,+ hasMaterializingImageAttachments ||+ hasMaterializingAudioAttachments,[+ hasMaterializingAudioAttachments,hasMaterializingImageAttachments,hasPendingAttachments,hasSendableContent,@@ -2950,7 +3098,7 @@ const Composer: FC<{(event: { preventDefault: () => void }) => {if (disabled || shouldBlockSend()) {event.preventDefault();- parkIfWaitingOnImages();+ parkIfWaitingOnAttachments();return true;}if (indexingActive && !overlay) {@@ -2966,7 +3114,7 @@ const Composer: FC<{indexingActive,overlay,enqueueSend,- parkIfWaitingOnImages,+ parkIfWaitingOnAttachments,],);@@ -2981,7 +3129,8 @@ const Composer: FC<{!pendingSend ||!pendingSendRef.current ||indexingActive ||- hasMaterializingImageAttachments+ hasMaterializingImageAttachments ||+ hasMaterializingAudioAttachments) {return;}@@ -2997,6 +3146,7 @@ const Composer: FC<{pendingSend,indexingActive,hasMaterializingImageAttachments,+ hasMaterializingAudioAttachments,aui,clearStoredDraft,dismissWaitToast,@@ -3045,7 +3195,10 @@ const Composer: FC<{// a pending send when the composer changes under it after the press.const dictationBlocked = dictationSendBlocked({composerDisabled: Boolean(disabled),- uploading: hasPendingAttachments || hasMaterializingImageAttachments,+ uploading:+ hasPendingAttachments ||+ hasMaterializingImageAttachments ||+ hasMaterializingAudioAttachments,researchActive: isResearchActive,runActive: threadIsRunning || promptQueueActive,queueDisabled: Boolean(disableQueue),@@ -3120,7 +3273,7 @@ const Composer: FC<{}if (disabled || shouldBlockSend()) {event.preventDefault();- parkIfWaitingOnImages();+ parkIfWaitingOnAttachments();return;}@@ -3254,7 +3407,7 @@ const Composer: FC<{interceptSend,isResearchActive,overlay,- parkIfWaitingOnImages,+ parkIfWaitingOnAttachments,promptQueueActive,promptQueueThreadIds,preStreamThreadIds,diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex b2a67204a2a..d2ff6954481 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2625,6 +2625,12 @@ export function ChatPage({},[artifactViewKey],);+ const handleNativeAudioDrop = useCallback(+ (intents: NativeIntent[]) => {+ useNativeIntentStore.getState().addAudioAttachments(artifactViewKey, intents);+ },+ [artifactViewKey],+ );const nativeModelDropState = useNativeModelDrop({enabled: active && view.mode === "single",attachmentScope,@@ -2635,6 +2641,7 @@ export function ChatPage({onAutoLoad: handleNativeModelDropAutoLoad,onAttach: handleNativeAttachmentDrop,onAttachImages: handleNativeImageDrop,+ onAttachAudio: handleNativeAudioDrop,});const handleCheckpointChange = useCallback(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.tsxindex 81820a73ffb..2192d55fb45 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,14 +10,19 @@ function overlayCopy(state: NativeModelDropState): { title: string; description:};}if (state.status === "attach") {- // Only documents are indexed; images ride the next message, so mixed says both.+ // Only documents are indexed; images and audio ride the next message.const description =- state.kind === "images"+ state.kind === "images" || state.kind === "audio"? "Attached to your next message.": state.kind === "mixed"- ? "Documents indexed, images attached to your next message."+ ? "Documents indexed, attachments sent with your next message.": "Indexed for this chat.";- const noun = state.kind === "images" ? "image" : "file";+ const noun =+ state.kind === "images"+ ? "image"+ : state.kind === "audio"+ ? "audio file"+ : "file";return {title:state.count === 1diff --git a/studio/frontend/src/features/native-intents/drop-paths.ts b/studio/frontend/src/features/native-intents/drop-paths.tsindex 5c81d2ff1c4..564c1859652 100644--- a/studio/frontend/src/features/native-intents/drop-paths.ts+++ b/studio/frontend/src/features/native-intents/drop-paths.ts@@ -10,8 +10,13 @@ export const CHAT_IMAGE_DROP_ACCEPT = ".jpg,.jpeg,.png,.webp,.gif";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());+/** What the window actually takes, for the rejection toast and the overlay. */-export const SUPPORTED_DROP_HINT = `Supported files: ${RAG_UPLOAD_ACCEPT}, ${CHAT_IMAGE_DROP_ACCEPT}, or a single .gguf model.`;+export const SUPPORTED_DROP_HINT = `Supported files: ${RAG_UPLOAD_ACCEPT}, ${CHAT_IMAGE_DROP_ACCEPT}, one of ${CHAT_AUDIO_DROP_ACCEPT}, or a single .gguf model.`;function hasExt(path: string, ext: string): boolean {return path.toLowerCase().endsWith(ext);@@ -22,7 +27,8 @@ export type NativeDropClass =| { kind: "model"; path: string }| { kind: "docs"; paths: string[] }| { kind: "images"; paths: string[] }- | { kind: "attach"; docs: string[]; images: string[] }+ | { kind: "audio"; paths: string[] }+ | { kind: "attach"; docs: string[]; images: string[]; audio: string[] }| { kind: "unsupported" };/** What a native drag payload is, before any of it is registered with Rust. */@@ -39,13 +45,21 @@ export function classifyDropPaths(paths: string[]): NativeDropClass {const images = paths.filter((path) =>IMAGE_EXTS.some((ext) => hasExt(path, ext)),);- if (docs.length + images.length !== paths.length) {+ const audio = paths.filter((path) =>+ AUDIO_EXTS.some((ext) => hasExt(path, ext)),+ );+ if (docs.length + images.length + audio.length !== paths.length) {+ return { kind: "unsupported" };+ }+ // The audio adapter takes one clip per message; a larger batch never attaches.+ if (audio.length > 1) {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 };+ if (docs.length === 0 && images.length === 0 && audio.length === 0) {+ return { kind: "none" };}- return { kind: "attach", docs, images };+ if (images.length === 0 && audio.length === 0) return { kind: "docs", paths: docs };+ if (docs.length === 0 && audio.length === 0) return { kind: "images", paths: images };+ if (docs.length === 0 && images.length === 0) return { kind: "audio", paths: audio };+ return { kind: "attach", docs, images, audio };}diff --git a/studio/frontend/src/features/native-intents/store.ts b/studio/frontend/src/features/native-intents/store.tsindex bacafcd8de0..12cfe28f401 100644--- a/studio/frontend/src/features/native-intents/store.ts+++ b/studio/frontend/src/features/native-intents/store.ts@@ -12,26 +12,41 @@ interface NativeIntentState {// async Rust boundary, so the active chat may change before these arrive.pendingAttachments: PendingNativeAttachments;pendingImageAttachments: PendingNativeAttachments;+ pendingAudioAttachments: 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;+ // Same for audio: cover the register-and-read window or a fast submit+ // goes out without the clip.+ registeringAudioDrops: 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>;+ audioDropFailures: 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>;+ // Same for audio: a new chat re-keys mid-read, so the clip needs a note+ // to follow the composer.+ audioDropOwners: Record<string, string>;addIntent: (intent: NativeIntent) => void;addAttachments: (targetKey: string, intents: NativeIntent[]) => void;addImageAttachments: (targetKey: string, intents: NativeIntent[]) => void;+ addAudioAttachments: (targetKey: string, intents: NativeIntent[]) => void;takeAttachments: (targetKey: string) => NativeIntent[];takeImageAttachments: (targetKey: string) => NativeIntent[];+ takeAudioAttachments: (targetKey: string) => NativeIntent[];beginImageDropRegistration: () => void;endImageDropRegistration: () => void;+ beginAudioDropRegistration: () => void;+ endAudioDropRegistration: () => void;failImageDropRegistration: (targetKey: string) => void;+ failAudioDropRegistration: (targetKey: string) => void;noteImageDropOwner: (targetKey: string, identity: string) => void;claimImageAttachments: (identity: string, targetKey: string) => void;+ noteAudioDropOwner: (targetKey: string, identity: string) => void;+ claimAudioAttachments: (identity: string, targetKey: string) => void;clearModelIntent: (intentId?: string) => void;}@@ -39,9 +54,13 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({pendingModelIntent: null,pendingAttachments: {},pendingImageAttachments: {},+ pendingAudioAttachments: {},registeringImageDrops: 0,+ registeringAudioDrops: 0,imageDropFailures: {},+ audioDropFailures: {},imageDropOwners: {},+ audioDropOwners: {},addAttachments: (targetKey, intents) => {const current = get().pendingAttachments;const pendingAttachments = enqueueNativeAttachments(@@ -64,6 +83,28 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({set({ pendingImageAttachments });}},+ addAudioAttachments: (targetKey, intents) => {+ const current = get().pendingAudioAttachments;+ const pendingAudioAttachments = enqueueNativeAttachments(+ current,+ targetKey,+ intents,+ );+ if (pendingAudioAttachments !== current) {+ set({ pendingAudioAttachments });+ }+ },+ takeAudioAttachments: (targetKey) => {+ const current = get().pendingAudioAttachments;+ const [queued, pendingAudioAttachments] = dequeueNativeAttachments(+ current,+ targetKey,+ );+ if (pendingAudioAttachments !== current) {+ set({ pendingAudioAttachments });+ }+ return queued;+ },takeAttachments: (targetKey) => {const current = get().pendingAttachments;const [queued, pendingAttachments] = dequeueNativeAttachments(@@ -92,6 +133,12 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({endImageDropRegistration: () => {set({ registeringImageDrops: Math.max(0, get().registeringImageDrops - 1) });},+ beginAudioDropRegistration: () => {+ set({ registeringAudioDrops: get().registeringAudioDrops + 1 });+ },+ endAudioDropRegistration: () => {+ set({ registeringAudioDrops: Math.max(0, get().registeringAudioDrops - 1) });+ },failImageDropRegistration: (targetKey) => {const current = get().imageDropFailures;set({@@ -101,6 +148,15 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({},});},+ failAudioDropRegistration: (targetKey) => {+ const current = get().audioDropFailures;+ set({+ audioDropFailures: {+ ...current,+ [targetKey]: (current[targetKey] ?? 0) + 1,+ },+ });+ },noteImageDropOwner: (targetKey, identity) => {if (!identity) return;set({ imageDropOwners: { ...get().imageDropOwners, [targetKey]: identity } });@@ -132,6 +188,37 @@ export const useNativeIntentStore = create<NativeIntentState>((set, get) => ({for (const key of stale) delete nextOwners[key];set({ pendingImageAttachments, imageDropOwners: nextOwners });},+ noteAudioDropOwner: (targetKey, identity) => {+ if (!identity) return;+ set({ audioDropOwners: { ...get().audioDropOwners, [targetKey]: identity } });+ },+ claimAudioAttachments: (identity, targetKey) => {+ if (!identity) return;+ const owners = get().audioDropOwners;+ const stale = Object.keys(owners).filter(+ (key) => owners[key] === identity && key !== targetKey,+ );+ if (stale.length === 0) return;+ const queues = get().pendingAudioAttachments;+ let pendingAudioAttachments = queues;+ for (const key of stale) {+ const queued = queues[key] ?? [];+ if (queued.length > 0) {+ pendingAudioAttachments = enqueueNativeAttachments(+ pendingAudioAttachments,+ targetKey,+ queued,+ );+ }+ if (key in pendingAudioAttachments) {+ pendingAudioAttachments = { ...pendingAudioAttachments };+ delete pendingAudioAttachments[key];+ }+ }+ const nextOwners = { ...owners };+ for (const key of stale) delete nextOwners[key];+ set({ pendingAudioAttachments, audioDropOwners: 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.tsindex b615abf9280..4238ea66b86 100644--- a/studio/frontend/src/features/native-intents/use-native-drop.ts+++ b/studio/frontend/src/features/native-intents/use-native-drop.ts@@ -9,7 +9,7 @@ import type { NativeIntent } from "./types";export type NativeModelDropState =| { status: "idle" }| { status: "valid"; action: "load" | "replace" | "chip" }- | { status: "attach"; count: number; kind: "docs" | "images" | "mixed" }+ | { status: "attach"; count: number; kind: "docs" | "images" | "audio" | "mixed" }| { status: "invalid" };interface NativeModelDropOptions {@@ -23,6 +23,7 @@ interface NativeModelDropOptions {onAutoLoad?: (intent: NativeIntent) => Promise<void> | void;onAttach?: (intents: NativeIntent[]) => Promise<void> | void;onAttachImages?: (intents: NativeIntent[]) => Promise<void> | void;+ onAttachAudio?: (intents: NativeIntent[]) => Promise<void> | void;}function canAttachDocs(options: NativeModelDropOptions): boolean {@@ -33,6 +34,10 @@ function canAttachImages(options: NativeModelDropOptions): boolean {return Boolean(options.onAttachImages);}+function canAttachAudio(options: NativeModelDropOptions): boolean {+ return Boolean(options.onAttachAudio);+}+function canAutoLoadModel(options: NativeModelDropOptions): boolean {return (options.nativePathLeasesSupported &&@@ -42,11 +47,15 @@ function canAutoLoadModel(options: NativeModelDropOptions): boolean {}function attachmentCount(dropped: ReturnType<typeof classifyDropPaths>): number {- if (dropped.kind === "docs" || dropped.kind === "images") {+ if (+ dropped.kind === "docs" ||+ dropped.kind === "images" ||+ dropped.kind === "audio"+ ) {return dropped.paths.length;}if (dropped.kind === "attach") {- return dropped.docs.length + dropped.images.length;+ return dropped.docs.length + dropped.images.length + dropped.audio.length;}return 0;}@@ -67,11 +76,17 @@ function dropStateForPaths(? { status: "attach", count: dropped.paths.length, kind: "images" }: { status: "invalid" };}+ if (dropped.kind === "audio") {+ return canAttachAudio(options)+ ? { status: "attach", count: dropped.paths.length, kind: "audio" }+ : { 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+ const audioSupported = dropped.audio.length === 0 || canAttachAudio(options);+ return docsSupported && imagesSupported && audioSupported? { status: "attach", count: attachmentCount(dropped), kind: "mixed" }: { status: "invalid" };}@@ -88,8 +103,10 @@ function dropStateForPaths(interface RegisteredDrop {docs: NativeIntent[];images: NativeIntent[];+ audio: NativeIntent[];docsFailed: number;imagesFailed: number;+ audioFailed: number;error?: Error;}@@ -118,7 +135,7 @@ async function registerEach(paths: string[]) {async function registerDroppedAttachments(dropped: Extract<ReturnType<typeof classifyDropPaths>,- { kind: "docs" | "images" | "attach" }+ { kind: "docs" | "images" | "audio" | "attach" }>,): Promise<RegisteredDrop> {const docPaths =@@ -133,16 +150,25 @@ async function registerDroppedAttachments(: dropped.kind === "attach"? dropped.images: [];- const [docs, images] = await Promise.all([+ const audioPaths =+ dropped.kind === "audio"+ ? dropped.paths+ : dropped.kind === "attach"+ ? dropped.audio+ : [];+ const [docs, images, audio] = await Promise.all([registerEach(docPaths),registerEach(imagePaths),+ registerEach(audioPaths),]);return {docs: docs.intents,images: images.intents,+ audio: audio.intents,docsFailed: docs.failed,imagesFailed: images.failed,- error: docs.error ?? images.error,+ audioFailed: audio.failed,+ error: docs.error ?? images.error ?? audio.error,};}@@ -183,6 +209,7 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelif (dropped.kind === "docs" ||dropped.kind === "images" ||+ dropped.kind === "audio" ||dropped.kind === "attach") {const needsDocs =@@ -191,6 +218,9 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelconst needsImages =dropped.kind === "images" ||(dropped.kind === "attach" && dropped.images.length > 0);+ const needsAudio =+ dropped.kind === "audio" ||+ (dropped.kind === "attach" && dropped.audio.length > 0);if (needsDocs && !canAttachDocs(currentOptions)) {toast.error("Attaching files needs the desktop backend", {description: "Retry once Studio has finished starting up.",@@ -203,11 +233,18 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModel});return;}+ if (needsAudio && !canAttachAudio(currentOptions)) {+ toast.error("Attaching audio 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();+ if (needsAudio) store.beginAudioDropRegistration();try {const registered = await registerDroppedAttachments(dropped);const latestOptions = optionsRef.current;@@ -228,7 +265,24 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelif (registered.imagesFailed > 0 && failureKey) {store.failImageDropRegistration(failureKey);}- if (registered.docsFailed + registered.imagesFailed > 0) {+ if (registered.audioFailed > 0 && failureKey) {+ store.failAudioDropRegistration(failureKey);+ }+ // A failed document cancels a send parked behind the image or audio+ // gate too, or the draft goes out with only what survived.+ if (registered.docsFailed > 0 && failureKey) {+ if (needsImages) store.failImageDropRegistration(failureKey);+ if (needsAudio) store.failAudioDropRegistration(failureKey);+ }+ if (registered.audio.length > 0) {+ await attachOptions.onAttachAudio?.(registered.audio);+ }+ if (+ registered.docsFailed ++ registered.imagesFailed ++ registered.audioFailed >+ 0+ ) {toast.error("Could not attach dropped files", {description: registered.error?.message ?? "Some files were skipped.",});@@ -238,11 +292,15 @@ export function useNativeModelDrop(options: NativeModelDropOptions): NativeModelif (needsImages && failureKey) {store.failImageDropRegistration(failureKey);}+ if (needsAudio && failureKey) {+ store.failAudioDropRegistration(failureKey);+ }toast.error("Could not attach dropped files", {description: error instanceof Error ? error.message : String(error),});} finally {if (needsImages) store.endImageDropRegistration();+ if (needsAudio) store.endAudioDropRegistration();}return;}diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex 7937d6eb3bf..4679e8fd4c8 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -9,8 +9,9 @@ import {dequeueNativeAttachments,enqueueNativeAttachments,} from "../src/features/native-intents/attachment-queue.ts";-import { classifyDropPaths, CHAT_IMAGE_DROP_ACCEPT, SUPPORTED_DROP_HINT } from "../src/features/native-intents/drop-paths.ts";+import { classifyDropPaths, CHAT_AUDIO_DROP_ACCEPT, 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 { AUDIO_ACCEPT } from "../src/lib/audio-utils.ts";import { RAG_UPLOAD_ACCEPT } from "../src/features/rag/types/rag.ts";import { registerBundlerResolver } from "./helpers/kit.ts";@@ -23,6 +24,8 @@ const { useNativeIntentStore } = await import(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 RUST_AUDIO_ATTACHMENT_EXTS_RE = /AUDIO_ATTACHMENT_EXTS[^=]*=\s*&\[([^\]]+)\]/s;+const RUST_AUDIO_MIME_RE = /Some\("(audio\/[^"]+)"\)/g;const DOTTED_EXTENSION_RE = /"(\.[^"]+)"/g;const RUST_EXTENSION_RE = /"([^"]+)"/g;const RUST_MIME_ARM_RE = /Some\("(image\/[^"]+)"\)/g;@@ -344,15 +347,97 @@ test("ownership recorded after a claim is still picked up", () => {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(),- );+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]+ .flatMap((accept) => accept.split(","))+ .map((ext) => ext.trim().toLowerCase());assert.deepEqual(- images.filter((ext) => docs.includes(ext)),+ exts.filter((ext, index) => exts.indexOf(ext) !== index),[],);});++// A dropped clip has to reach the same adapter an upload does.+test("a single audio file routes to chat audio attachments", () => {+ const dropped = classifyDropPaths(["/clips/take.WAV"]);+ assert.equal(dropped.kind, "audio");+ assert.deepEqual(dropped.kind === "audio" ? dropped.paths : [], [+ "/clips/take.WAV",+ ]);+});++// One clip per message, so a larger batch is turned away before it is read.+test("multi-audio drops are rejected before they are routed", () => {+ const dropped = classifyDropPaths([+ "/clips/take.WAV",+ "/clips/note.mp3",+ "/clips/voice.flac",+ ]);+ assert.equal(dropped.kind, "unsupported");+});++test("a second clip alongside other attachments is rejected too", () => {+ const dropped = classifyDropPaths([+ "/docs/a.pdf",+ "/clips/note.mp3",+ "/clips/voice.flac",+ ]);+ assert.equal(dropped.kind, "unsupported");+});++test("documents, images and audio can be dropped together", () => {+ const dropped = classifyDropPaths([+ "/docs/a.pdf",+ "/photos/cat.png",+ "/clips/note.mp3",+ ]);+ assert.equal(dropped.kind, "attach");+ if (dropped.kind === "attach") {+ assert.deepEqual(dropped.docs, ["/docs/a.pdf"]);+ assert.deepEqual(dropped.images, ["/photos/cat.png"]);+ assert.deepEqual(dropped.audio, ["/clips/note.mp3"]);+ }+});++test("frontend and Rust accept the same chat audio extensions", () => {+ const frontend = CHAT_AUDIO_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_AUDIO_ATTACHMENT_EXTS_RE)?.[1]+ .matchAll(RUST_EXTENSION_RE) ?? []),+ ]+ .map((match) => `.${match[1]}`)+ .sort();++ assert.deepEqual(rust, frontend);+});++// Same seam as the vision check: an audio MIME the adapter does not claim+// lands nowhere.+test("every audio MIME Rust stamps is one the audio adapter claims", () => {+ const rustSource = readFileSync(+ new URL("../../src-tauri/src/native_intents.rs", import.meta.url),+ "utf8",+ );+ const claimed = new Set(+ AUDIO_ACCEPT.split(",").map((token) => token.trim().toLowerCase()),+ );+ const stamped = [+ ...(rustSource.match(MIME_MATCH_BODY_RE)?.[1] ?? "").matchAll(+ RUST_AUDIO_MIME_RE,+ ),+ ].map((match) => match[1]);++ assert.ok(stamped.length > 0, "Rust stamps no audio MIME types");+ for (const mime of stamped) {+ assert.ok(claimed.has(mime), `the audio adapter does not claim ${mime}`);+ }+});diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rsindex fb5742aa7e4..5ea1d8bb51c 100644--- a/studio/src-tauri/src/native_intents.rs+++ b/studio/src-tauri/src/native_intents.rs@@ -528,7 +528,11 @@ 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;+// Covers the largest client-side limit (audio, 25 MB).+const MAX_NATIVE_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;+// Images stop lower: the composer throws over 20 MB without a toast and the+// drain swallows it, so a larger read loses them silently.+const MAX_NATIVE_IMAGE_BYTES: u64 = 20 * 1024 * 1024;#[derive(Serialize)]#[serde(rename_all = "camelCase")]@@ -545,6 +549,11 @@ fn attachment_mime_type(path: &Path) -> Option<&'static str> {"png" => Some("image/png"),"webp" => Some("image/webp"),"gif" => Some("image/gif"),+ "wav" => Some("audio/wav"),+ "mp3" => Some("audio/mpeg"),+ "m4a" => Some("audio/mp4"),+ "ogg" | "oga" => Some("audio/ogg"),+ "flac" => Some("audio/flac"),_ => None,}}@@ -593,14 +602,19 @@ 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 attachments can be read for vision input.".to_string()+ "Only chat image and audio attachments can be read inline.".to_string()})?;+ let max_bytes = if mime_type.starts_with("image/") {+ MAX_NATIVE_IMAGE_BYTES+ } else {+ MAX_NATIVE_ATTACHMENT_BYTES+ };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());+ if !metadata.is_file() || metadata.len() > max_bytes {+ return Err("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.@@ -614,11 +628,11 @@ fn read_attachment_payload(entry: &NativePathEntry) -> Result<NativeAttachmentFi}// 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)+ file.take(max_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());+ .map_err(|e| format!("Could not read attachment: {e}"))?;+ if bytes.len() as u64 > max_bytes {+ return Err("Attachment is unavailable or too large.".to_string());}let name = path.file_name()@@ -678,6 +692,29 @@ mod tests {(state, entry)}+ // The reader maps its own mime types; an unmapped one refuses an accepted file.+ #[test]+ fn audio_read_round_trips_with_its_mime_type() {+ for (ext, mime) in [+ ("wav", "audio/wav"),+ ("mp3", "audio/mpeg"),+ ("m4a", "audio/mp4"),+ ("ogg", "audio/ogg"),+ ("oga", "audio/ogg"),+ ("flac", "audio/flac"),+ ] {+ let path = temp_path("clip").with_extension(ext);+ fs::write(&path, b"ID3AUDIO").unwrap();+ let (_state, entry) = attachment_entry(&path);+ let payload = read_attachment_payload(&entry)+ .unwrap_or_else(|error| panic!(".{ext} was unreadable: {error}"));+ assert_eq!(payload.mime_type, mime);+ assert_eq!(BASE64.decode(payload.base64).unwrap(), b"ID3AUDIO");+ assert!(payload.name.ends_with(&format!(".{ext}")));+ let _ = fs::remove_file(path);+ }+ }+#[test]fn image_read_round_trips_and_names_the_file() {let path = temp_path("photo").with_extension("png");@@ -698,7 +735,7 @@ mod tests {let Err(err) = read_attachment_payload(&entry) else {panic!("expected the read to be refused");};- assert!(err.contains("Only chat image attachments"));+ assert!(err.contains("Only chat image and audio attachments"));let _ = fs::remove_file(path);}@@ -715,9 +752,34 @@ mod tests {let _ = fs::remove_file(path);}+ // Reading past the image cap would make the file disappear instead of+ // reporting it.#[test]- fn image_read_refuses_more_than_the_cap() {+ fn image_read_refuses_more_than_the_image_cap() {let path = temp_path("huge").with_extension("png");+ fs::write(&path, vec![0u8; MAX_NATIVE_IMAGE_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);+ }++ // Audio keeps the larger cap: the caps are per kind, not one shared ceiling.+ #[test]+ fn audio_read_allows_more_than_the_image_cap() {+ let path = temp_path("clip").with_extension("wav");+ fs::write(&path, vec![0u8; MAX_NATIVE_IMAGE_BYTES as usize + 1]).unwrap();+ let (_state, entry) = attachment_entry(&path);+ let payload = read_attachment_payload(&entry).expect("audio under the audio cap reads");+ assert_eq!(payload.mime_type, "audio/wav");+ let _ = fs::remove_file(path);+ }++ #[test]+ fn audio_read_refuses_more_than_the_audio_cap() {+ let path = temp_path("huge").with_extension("wav");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 {diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rsindex 8482c16f713..9d1809ebad5 100644--- a/studio/src-tauri/src/native_path_policy.rs+++ b/studio/src-tauri/src/native_path_policy.rs@@ -51,21 +51,27 @@ 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"];+/// Chat audio attachments; keep in sync with `audio-attachment-adapter.ts` `accept`.+pub const AUDIO_ATTACHMENT_EXTS: &[&str] = &["wav", "mp3", "m4a", "ogg", "oga", "flac"];++fn accepted_attachment_exts() -> impl Iterator<Item = &'static &'static str> {+ ATTACHMENT_EXTS+ .iter()+ .chain(IMAGE_ATTACHMENT_EXTS.iter())+ .chain(AUDIO_ATTACHMENT_EXTS.iter())+}+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());}- let supported = ATTACHMENT_EXTS- .iter()- .chain(IMAGE_ATTACHMENT_EXTS.iter())+ let supported = accepted_attachment_exts().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())+ accepted_attachment_exts().map(|ext| format!(".{ext}")).collect::<Vec<_>>().join(", ")@@ -381,6 +387,22 @@ mod tests {let _ = fs::remove_file(path);}+ // The composer takes audio uploads, so a dropped one has to classify too.+ #[test]+ fn audio_attachments_are_accepted() {+ for ext in AUDIO_ATTACHMENT_EXTS {+ let path = temp_path("clip").with_extension(ext);+ fs::write(&path, b"ID3").unwrap();+ let classified = classify_native_attachment_path(&path)+ .unwrap_or_else(|error| panic!(".{ext} was rejected: {error}"));+ assert_eq!(classified.path_kind, NativePathKind::Attachment);+ assert!(classified+ .allowed_operations+ .contains(&NativePathOperation::Attach));+ let _ = fs::remove_file(path);+ }+ }+#[test]fn training_dataset_allows_import_and_reveal_only() {let path = temp_path("dataset").with_extension("jsonl");