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
Studio: surface API errors and align audio limits (#7946)
oobaboogabb2bab70a377
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex e7b6b781c89..92ed93001f0 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -2103,7 +2103,7 @@ const Composer: FC<{},() =>toast.error("Could not paste files.", {- description: "The clipboard item is unsupported, unreadable, or over 20 MB.",+ description: "The clipboard item is unsupported, unreadable, or exceeds its size limit.",}),);},diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 87963f24ca4..a98e27a7fc8 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -10,7 +10,7 @@ import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";import { isHuggingFaceOffline } from "@/features/hub/lib/network";// eslint-disable-next-line no-restricted-importsimport { consumeNativePathToken } from "@/features/native-intents/api";-import { formatFastApiDetail } from "@/lib/format-fastapi-error";+import { formatApiErrorBody } from "@/lib/format-fastapi-error";import type {MessageRecord,ModelType,@@ -84,14 +84,7 @@ function notifyChatProjectsUpdated(): void {}function parseErrorText(status: number, body: unknown): string {- if (body && typeof body === "object") {- const detail = (body as { detail?: unknown }).detail;- const formatted = formatFastApiDetail(detail);- if (formatted) return formatted;- const message = (body as { message?: unknown }).message;- if (typeof message === "string" && message) return message;- }- return `Request failed (${status})`;+ return formatApiErrorBody(body) ?? `Request failed (${status})`;}/**diff --git a/studio/frontend/src/features/chat/audio-attachment-adapter.ts b/studio/frontend/src/features/chat/audio-attachment-adapter.tsindex 99a26ed1783..40d4a36a3db 100644--- a/studio/frontend/src/features/chat/audio-attachment-adapter.ts+++ b/studio/frontend/src/features/chat/audio-attachment-adapter.ts@@ -3,8 +3,8 @@import {AUDIO_ACCEPT,- MAX_AUDIO_SIZE,fileToBase64,+ getAudioSizeError,} from "@/lib/audio-utils";import type {Attachment,@@ -51,8 +51,8 @@ export class AudioAttachmentAdapter implements AttachmentAdapter {toast.error(unavailableReason);throw new Error(unavailableReason);}- if (file.size > MAX_AUDIO_SIZE) {- const sizeReason = "Audio size exceeds 50MB limit";+ const sizeReason = getAudioSizeError(file.size);+ if (sizeReason) {toast.error(sizeReason);throw new Error(sizeReason);}diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 58f15347a9b..be979bf8f4f 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -32,7 +32,11 @@ import {} from "@/features/chat/adapters/studio-dictation-adapter";import type { StudioDictationSession } from "@/features/chat/adapters/studio-web-speech-dictation-adapter";import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";-import { AUDIO_ACCEPT, MAX_AUDIO_SIZE, fileToBase64 } from "@/lib/audio-utils";+import {+ AUDIO_ACCEPT,+ fileToBase64,+ getAudioSizeError,+} from "@/lib/audio-utils";import { isTauri } from "@/lib/api-base";import { isDownloadCancelled } from "@/lib/native-files";import { isMultimodalResponse } from "./types/api";@@ -900,11 +904,17 @@ export function SharedComposer({if (!files?.length) return;const next: PendingImage[] = [];let droppedImageForUnavailable = false;+ let audioSizeError: string | null = null;for (let i = 0; i < files.length; i++) {const file = files[i];if (!file) continue;// Handle audio files- if (file.type.match(/^audio\//i) && file.size <= MAX_AUDIO_SIZE) {+ if (file.type.match(/^audio\//i)) {+ const sizeError = getAudioSizeError(file.size);+ if (sizeError) {+ audioSizeError ??= sizeError;+ continue;+ }fileToBase64(file).then((base64) => {setPendingAudio({ name: file.name, base64, contentType: file.type });setPendingAudioStore(base64, file.name);@@ -923,6 +933,9 @@ export function SharedComposer({if (droppedImageForUnavailable && attachUnavailableReason) {toast.error(attachUnavailableReason);}+ if (audioSizeError) {+ toast.error(audioSizeError);+ }setPendingImages((prev) => [...prev, ...next]);},[setPendingAudioStore, attachUnavailableReason],@@ -933,9 +946,10 @@ export function SharedComposer({pasteClipboardFiles(event,async (files) => {+ // Let addFiles report audio size errors.const supported = files.some((file) =>- (file.type.match(/^audio\//i) && file.size <= MAX_AUDIO_SIZE) ||+ file.type.match(/^audio\//i) ||(file.type.match(/^image\/(jpeg|png|webp|gif)$/i) &&file.size <= MAX_IMAGE_SIZE),);diff --git a/studio/frontend/src/features/chat/utils/clipboard-files.ts b/studio/frontend/src/features/chat/utils/clipboard-files.tsindex c3ced7765e0..b2920d1497c 100644--- a/studio/frontend/src/features/chat/utils/clipboard-files.ts+++ b/studio/frontend/src/features/chat/utils/clipboard-files.ts@@ -2,10 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { isTauri } from "@/lib/api-base";+import { MAX_AUDIO_SIZE } from "@/lib/audio-utils";const MAX_NATIVE_IMAGE_DIMENSION = 8192;const MAX_NATIVE_IMAGE_RGBA_BYTES = 64 * 1024 * 1024;-const MAX_CLIPBOARD_BYTES = 20 * 1024 * 1024;+const MAX_CLIPBOARD_BYTES = MAX_AUDIO_SIZE;+const MAX_CLIPBOARD_NON_AUDIO_BYTES = 20 * 1024 * 1024;const MAX_CLIPBOARD_FILES = 8;type ClipboardPasteEvent = {@@ -93,20 +95,27 @@ async function readNativeClipboardFiles(): Promise<File[]> {let totalBytes = 0;const files: File[] = [];for (const file of nativeFiles) {+ if (file.base64.length === 0) continue;if (!file.name ||file.name.length > 255 ||file.name.includes("/") ||- file.name.includes("\0") ||- file.base64.length > Math.ceil((MAX_CLIPBOARD_BYTES * 4) / 3) + 4+ file.name.includes("\0")) {return [];}+ const maxFileBytes = file.mimeType.startsWith("audio/")+ ? MAX_AUDIO_SIZE+ : MAX_CLIPBOARD_NON_AUDIO_BYTES;+ if (file.base64.length > Math.ceil((maxFileBytes * 4) / 3) + 4) {+ return [];+ }const binary = globalThis.atob(file.base64);const bytes = new Uint8Array(binary.length);for (let index = 0; index < binary.length; index += 1) {bytes[index] = binary.charCodeAt(index);}+ if (bytes.byteLength > maxFileBytes) return [];totalBytes += bytes.byteLength;if (totalBytes > MAX_CLIPBOARD_BYTES) return [];files.push(@@ -123,7 +132,9 @@ async function readLinuxClipboardImage(): Promise<File | null> {const { invoke } = await import("@tauri-apps/api/core");const raw = await invoke<ArrayBuffer | Uint8Array>("read_native_clipboard_png");const png = Uint8Array.from(raw instanceof Uint8Array ? raw : new Uint8Array(raw));- if (png.byteLength === 0 || png.byteLength > MAX_CLIPBOARD_BYTES) return null;+ if (png.byteLength === 0 || png.byteLength > MAX_CLIPBOARD_NON_AUDIO_BYTES) {+ return null;+ }return new File([png], "pasted-image.png", {type: "image/png",lastModified: Date.now(),@@ -161,7 +172,7 @@ async function readNativeClipboardImage(): Promise<File | null> {);context.putImageData(new ImageData(pixels, width, height), 0, 0);const blob = await canvasPng(canvas);- if (!blob || blob.size === 0 || blob.size > MAX_CLIPBOARD_BYTES) {+ if (!blob || blob.size === 0 || blob.size > MAX_CLIPBOARD_NON_AUDIO_BYTES) {return null;}return new File([blob], "pasted-image.png", {diff --git a/studio/frontend/src/lib/audio-utils.ts b/studio/frontend/src/lib/audio-utils.tsindex 63efc266f50..0a443b8d21b 100644--- a/studio/frontend/src/lib/audio-utils.ts+++ b/studio/frontend/src/lib/audio-utils.ts@@ -2,7 +2,16 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export const AUDIO_ACCEPT = "audio/wav,audio/mpeg,audio/webm,audio/ogg,audio/flac,audio/mp4";-export const MAX_AUDIO_SIZE = 50 * 1024 * 1024;+// Keep in sync with STT_AUDIO_RAW_MAX_BYTES in the backend upload limits.+const MAX_AUDIO_SIZE_MB = 25;+export const MAX_AUDIO_SIZE = MAX_AUDIO_SIZE_MB * 1024 * 1024;+export const MAX_AUDIO_SIZE_LABEL = `${MAX_AUDIO_SIZE_MB}MB`;++export function getAudioSizeError(size: number): string | null {+ return size > MAX_AUDIO_SIZE+ ? `Audio size exceeds ${MAX_AUDIO_SIZE_LABEL} limit`+ : null;+}export function fileToBase64(file: File): Promise<string> {return new Promise((resolve, reject) => {diff --git a/studio/frontend/src/lib/format-fastapi-error.ts b/studio/frontend/src/lib/format-fastapi-error.tsindex 79d53f469d3..1b4bbabe37d 100644--- a/studio/frontend/src/lib/format-fastapi-error.ts+++ b/studio/frontend/src/lib/format-fastapi-error.ts@@ -35,6 +35,46 @@ export function formatFastApiDetail(detail: unknown): string | null {return parts.length > 0 ? parts.join("; ") : null;}+// Cap recursion for malformed responses.+const MAX_ERROR_BODY_DEPTH = 4;++function formatErrorBody(body: unknown, depth: number): string | null {+ if (!body || typeof body !== "object") return null;++ const payload = body as {+ detail?: unknown;+ message?: unknown;+ error?: unknown;+ };+ const formatted = formatFastApiDetail(payload.detail);+ if (formatted) return formatted;+ // The same route may return a flat envelope or nest it inside `detail`.+ if (+ depth < MAX_ERROR_BODY_DEPTH &&+ payload.detail &&+ typeof payload.detail === "object" &&+ !Array.isArray(payload.detail)+ ) {+ const nested = formatErrorBody(payload.detail, depth + 1);+ if (nested) return nested;+ }+ if (typeof payload.message === "string" && payload.message) {+ return payload.message;+ }+ if (payload.error && typeof payload.error === "object") {+ const message = (payload.error as { message?: unknown }).message;+ if (typeof message === "string" && message) {+ return message;+ }+ }+ return null;+}++/** Render FastAPI and OpenAI-compatible error bodies into a message. */+export function formatApiErrorBody(body: unknown): string | null {+ return formatErrorBody(body, 0);+}+/*** Convert a (likely non-ok) Response into the best human-readable error* message. Used by *-api.ts wrappers so toasts read `field: msg` instead@@ -45,15 +85,8 @@ export async function readFastApiError(fallbackPrefix: string = "Request failed",): Promise<string> {try {- const payload = (await response.json()) as {- detail?: unknown;- message?: string;- };- const formatted = formatFastApiDetail(payload.detail);+ const formatted = formatApiErrorBody(await response.json());if (formatted) return formatted;- if (typeof payload.message === "string" && payload.message) {- return payload.message;- }} catch {// fall through}diff --git a/studio/frontend/tests/audio-utils.test.ts b/studio/frontend/tests/audio-utils.test.tsnew file mode 100644index 00000000000..b5e77e05686--- /dev/null+++ b/studio/frontend/tests/audio-utils.test.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ MAX_AUDIO_SIZE,+ MAX_AUDIO_SIZE_LABEL,+ getAudioSizeError,+} from "../src/lib/audio-utils.ts";++test("chat audio uses the backend's raw upload limit", () => {+ const backendLimits = readFileSync(+ new URL("../../backend/utils/upload_limits.py", import.meta.url),+ "utf8",+ );+ const limitMb = Number(+ backendLimits.match(+ /STT_AUDIO_RAW_MAX_BYTES\s*=\s*(\d+)\s*\*\s*_BYTES_PER_MB/,+ )?.[1],+ );++ assert.ok(Number.isInteger(limitMb));+ assert.equal(MAX_AUDIO_SIZE, limitMb * 1024 * 1024);+ assert.equal(MAX_AUDIO_SIZE_LABEL, `${limitMb}MB`);+});++test("chat audio accepts the exact limit and explains oversized files", () => {+ assert.equal(getAudioSizeError(MAX_AUDIO_SIZE), null);+ assert.equal(+ getAudioSizeError(MAX_AUDIO_SIZE + 1),+ `Audio size exceeds ${MAX_AUDIO_SIZE_LABEL} limit`,+ );+});diff --git a/studio/frontend/tests/format-fastapi-error.test.ts b/studio/frontend/tests/format-fastapi-error.test.tsnew file mode 100644index 00000000000..5e17a48136c--- /dev/null+++ b/studio/frontend/tests/format-fastapi-error.test.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import {+ formatApiErrorBody,+ readFastApiError,+} from "../src/lib/format-fastapi-error.ts";++test("formats an OpenAI-compatible error envelope", () => {+ assert.equal(+ formatApiErrorBody({+ error: {+ message: "Audio file is too large (max ~25 MB).",+ type: "invalid_request_error",+ },+ }),+ "Audio file is too large (max ~25 MB).",+ );+});++test("formats an Anthropic-compatible error envelope", () => {+ assert.equal(+ formatApiErrorBody({+ type: "error",+ error: { type: "rate_limit_error", message: "Try again later." },+ }),+ "Try again later.",+ );+});++test("keeps FastAPI detail and top-level message support", () => {+ assert.equal(+ formatApiErrorBody({ detail: "Invalid request" }),+ "Invalid request",+ );+ assert.equal(+ formatApiErrorBody({ message: "Provider failed" }),+ "Provider failed",+ );+ assert.equal(+ formatApiErrorBody({+ detail: [{ loc: ["body", "messages"], msg: "Field required" }],+ }),+ "messages: Field required",+ );+});++test("unwraps an envelope nested in FastAPI's detail", () => {+ const flat = { error: { message: "Audio file is too large (max ~25 MB)." } };+ assert.equal(+ formatApiErrorBody({ detail: flat }),+ "Audio file is too large (max ~25 MB).",+ );+ assert.equal(formatApiErrorBody(flat), formatApiErrorBody({ detail: flat }));+ assert.equal(+ formatApiErrorBody({+ detail: {+ error: {+ message: "n > 1 is not supported for GGUF tool chat completions.",+ code: "unsupported_parameter",+ param: "n",+ },+ },+ }),+ "n > 1 is not supported for GGUF tool chat completions.",+ );+ assert.equal(+ formatApiErrorBody({ detail: { message: "Nested plain message" } }),+ "Nested plain message",+ );+});++test("prefers a string detail over anything nested under it", () => {+ assert.equal(+ formatApiErrorBody({ detail: "Audio is too large." }),+ "Audio is too large.",+ );+ assert.equal(formatApiErrorBody({ detail: {} }), null);+ assert.equal(formatApiErrorBody({ detail: { error: {} } }), null);+ assert.equal(formatApiErrorBody({ detail: [] }), null);+});++test("reads an envelope nested in detail off a response", async () => {+ const response = new Response(+ JSON.stringify({+ detail: { error: { message: "Audio file is too large (max ~25 MB)." } },+ }),+ { status: 413, headers: { "Content-Type": "application/json" } },+ );+ assert.equal(+ await readFastApiError(response),+ "Audio file is too large (max ~25 MB).",+ );+});++test("does not recurse without bound on a deeply nested detail", () => {+ let body: unknown = { error: { message: "too deep to reach" } };+ for (let i = 0; i < 50; i++) body = { detail: body };+ assert.equal(formatApiErrorBody(body), null);+});++test("reads an OpenAI-compatible error response", async () => {+ const response = new Response(+ JSON.stringify({ error: { message: "Context limit exceeded" } }),+ { status: 400, headers: { "Content-Type": "application/json" } },+ );+ assert.equal(await readFastApiError(response), "Context limit exceeded");+});++test("falls back for malformed or empty error bodies", async () => {+ for (const body of [+ null,+ {},+ { error: null },+ { error: {} },+ { error: { message: 3 } },+ ]) {+ assert.equal(formatApiErrorBody(body), null);+ }++ const response = new Response("not JSON", { status: 503 });+ assert.equal(await readFastApiError(response, "HTTP"), "HTTP (503)");+});diff --git a/studio/src-tauri/src/native_clipboard.rs b/studio/src-tauri/src/native_clipboard.rsindex 8d27da02228..810773ee1ee 100644--- a/studio/src-tauri/src/native_clipboard.rs+++ b/studio/src-tauri/src/native_clipboard.rs@@ -11,7 +11,8 @@ const MAX_CLIPBOARD_IMAGE_DIMENSION: i32 = 8192;const MAX_CLIPBOARD_RGBA_BYTES: u64 = 64 * 1024 * 1024;const MAX_CLIPBOARD_PNG_BYTES: usize = 20 * 1024 * 1024;const MAX_CLIPBOARD_SOURCE_BYTES: u64 = 20 * 1024 * 1024;-const MAX_CLIPBOARD_TOTAL_BYTES: u64 = 20 * 1024 * 1024;+const MAX_CLIPBOARD_AUDIO_BYTES: u64 = 25 * 1024 * 1024;+const MAX_CLIPBOARD_TOTAL_BYTES: u64 = MAX_CLIPBOARD_AUDIO_BYTES;const MAX_CLIPBOARD_FILES: usize = 8;const MAX_CLIPBOARD_CANDIDATES: usize = 32;#[cfg(target_os = "linux")]@@ -100,6 +101,14 @@ fn clipboard_file_mime_type(path: &Path) -> Option<&'static str> {Some(mime_type)}+fn clipboard_file_max_bytes(mime_type: &str) -> u64 {+ if mime_type.starts_with("audio/") {+ MAX_CLIPBOARD_AUDIO_BYTES+ } else {+ MAX_CLIPBOARD_SOURCE_BYTES+ }+}+fn open_regular_clipboard_file(path: &Path) -> Option<File> {let metadata = std::fs::symlink_metadata(path).ok()?;if metadata.file_type().is_symlink() || !metadata.is_file() {@@ -143,12 +152,15 @@ fn read_clipboard_files(paths: Vec<PathBuf>) -> Result<Vec<NativeClipboardFile>,let Ok(metadata) = source.metadata() else {continue;};- let limit = MAX_CLIPBOARD_SOURCE_BYTES.min(remaining);- if !metadata.is_file() || metadata.len() > limit {+ let limit = clipboard_file_max_bytes(mime_type).min(remaining);+ if !metadata.is_file() || metadata.len() == 0 || metadata.len() > limit {continue;}let mut bytes = Vec::with_capacity(metadata.len() as usize);- if source.take(limit + 1).read_to_end(&mut bytes).is_err() || bytes.len() as u64 > limit {+ if source.take(limit + 1).read_to_end(&mut bytes).is_err()+ || bytes.is_empty()+ || bytes.len() as u64 > limit+ {continue;}remaining -= bytes.len() as u64;@@ -389,6 +401,9 @@ mod tests {let directory = tempfile::tempdir().unwrap();let path = directory.path().join("notes.md");std::fs::write(&path, b"clipboard text").unwrap();++ let empty = directory.path().join("empty.md");+ File::create(&empty).unwrap();let oversized = directory.path().join("oversized.md");File::create(&oversized).unwrap()@@ -396,7 +411,8 @@ mod tests {.unwrap();let files =- read_clipboard_files(vec![directory.path().to_path_buf(), oversized, path]).unwrap();+ read_clipboard_files(vec![directory.path().to_path_buf(), empty, oversized, path])+ .unwrap();assert_eq!(files.len(), 1);assert_eq!(files[0].name, "notes.md");assert_eq!(files[0].mime_type, "text/markdown");@@ -404,6 +420,35 @@ mod tests {assert_eq!(BASE64.decode(&files[0].base64).unwrap(), b"clipboard text");}+ #[test]+ fn clipboard_audio_uses_the_chat_upload_boundary() {+ assert_eq!(clipboard_file_max_bytes("audio/mpeg"), 25 * 1024 * 1024);+ assert_eq!(+ clipboard_file_max_bytes("text/markdown"),+ MAX_CLIPBOARD_SOURCE_BYTES+ );++ let directory = tempfile::tempdir().unwrap();+ let accepted = directory.path().join("accepted.mp3");+ File::create(&accepted)+ .unwrap()+ .set_len(MAX_CLIPBOARD_AUDIO_BYTES)+ .unwrap();+ let oversized = directory.path().join("oversized.mp3");+ File::create(&oversized)+ .unwrap()+ .set_len(MAX_CLIPBOARD_AUDIO_BYTES + 1)+ .unwrap();++ let files = read_clipboard_files(vec![oversized, accepted]).unwrap();+ assert_eq!(files.len(), 1);+ assert_eq!(files[0].name, "accepted.mp3");+ assert_eq!(+ BASE64.decode(&files[0].base64).unwrap().len() as u64,+ MAX_CLIPBOARD_AUDIO_BYTES+ );+ }+#[cfg(unix)]#[test]fn clipboard_file_reads_reject_symlinks() {