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: make the gallery video link absolute so the desktop app can play and save it (#8173)
Daniel Hanb65cae5bd825
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex e8ce11858ef..23c828562e6 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -5,6 +5,7 @@ import { withBackgroundLoadNotice } from "@/lib/model-lifecycle-events";import { authFetch } from "@/features/auth";// Same plan shape as the images backend: both /download-plan routes share a response model.import type { DiffusionDownloadPlan } from "@/features/images/api";+import { apiUrl } from "@/lib/api-base";import { readFastApiError } from "@/lib/format-fastapi-error";// One Advanced control's resolved value + provenance for the "Auto: X" badges, same shape as the diffusion status.@@ -262,7 +263,9 @@ export async function fetchGalleryVideoSignedUrl(id: string): Promise<string> {if (!res.ok) throw new Error(await readFastApiError(res));const body = (await res.json()) as { url?: string };if (!body.url) throw new Error("The server returned no video link.");- return body.url;+ // Absolute because consumers bypass authFetch, and a relative path under Tauri+ // resolves against the webview origin. No-op in the browser (empty apiBase).+ return apiUrl(body.url);}/** Server-side transcode for the Download menu (WebM / GIF). The backend 501s with a readable message when the codec is unavailable. */diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex a09f61d590b..974d7a91013 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -72,6 +72,7 @@ import {routedGgufFilename,routedGgufLabel,} from "@/lib/diffusion-route-search";+import { downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";@@ -183,14 +184,16 @@ function saveLink(href: string, filename: string) {link.click();}-// MP4 saves the original file straight from its signed link; WebM / GIF are transcoded by the backend on demand (501 when the codec is absent).+// MP4 streams from its signed link to the chosen path: that link is cross-origin under Tauri,+// where an anchor no longer saves, and a clip is too big to hold in memory on the way past.+// WebM / GIF are transcoded by the backend on demand (501 when the codec is absent).async function downloadVideo(src: string,video: GalleryVideo,format: VideoExportFormat = "mp4",) {if (format === "mp4") {- saveLink(src, exportFilename(video, format));+ await downloadUrlStreaming(src, exportFilename(video, format));return;}const blob = await fetchGalleryVideoExport(video.id, format);@@ -863,7 +866,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const handleDownload = useCallback(async (src: string, video: GalleryVideo, format: "mp4" | "webm" | "gif") => {if (format === "mp4") {- void downloadVideo(src, video, format);+ void downloadVideo(src, video, format).catch((err) => {+ if (!isDownloadCancelled(err)) toast.error("Could not save video.");+ });return;}const toastId = toast.loading(`Converting to ${format.toUpperCase()}…`);@@ -872,6 +877,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {toast.dismiss(toastId);} catch (err) {toast.dismiss(toastId);+ if (isDownloadCancelled(err)) return;toast.error(err instanceof Error ? err.message : `Failed to export ${format}`,);diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.tsindex 1c5b92a54bf..e4e06c21ffc 100644--- a/studio/frontend/src/lib/native-files.ts+++ b/studio/frontend/src/lib/native-files.ts@@ -105,6 +105,29 @@ export async function urlToBlob(url: string): Promise<Blob> {return (await fetchDownload(url)).blob();}+/**+ * Save a local backend URL without holding it in memory. `downloadUrl` buffers the body+ * to cross the IPC boundary, which is the wrong shape for a gallery clip: here the+ * chooser opens first and Rust streams to the chosen path. The browser keeps its anchor.+ */+export async function downloadUrlStreaming(+ url: string,+ filename: string,+): Promise<void> {+ if (!isTauri) {+ browserUrlDownload(url, filename);+ return;+ }+ const { invoke } = await import("@tauri-apps/api/core");+ const savedPath = await invoke<string | null>("save_native_file_from_url", {+ url,+ fileName: filename,+ });+ if (savedPath === null) {+ throw new DownloadCancelledError();+ }+}+/** Resolve media before crossing the native save boundary. */export async function downloadUrl(url: string,diff --git a/studio/src-tauri/src/loopback_http.rs b/studio/src-tauri/src/loopback_http.rsindex 3e0242c6dc7..2dec4a633d1 100644--- a/studio/src-tauri/src/loopback_http.rs+++ b/studio/src-tauri/src/loopback_http.rs@@ -7,6 +7,22 @@ pub(crate) fn client(timeout: Duration) -> Result<reqwest::Client, reqwest::Erro.build()}+/// A client for streaming a body down. `read_timeout`, not `timeout`: a whole gallery clip+/// outlasts any sane total deadline, while a per-read one bounds the headers and then each+/// chunk, so a backend that accepts and goes quiet cannot hang the save. Redirects are refused+/// so a loopback URL cannot be bounced off-host after the check.+pub(crate) fn streaming_client(+ connect_timeout: Duration,+ read_timeout: Duration,+) -> Result<reqwest::Client, reqwest::Error> {+ reqwest::Client::builder()+ .no_proxy()+ .connect_timeout(connect_timeout)+ .read_timeout(read_timeout)+ .redirect(reqwest::redirect::Policy::none())+ .build()+}+#[cfg(test)]mod tests {use std::io::{Read, Write};diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 599c581a953..0dd439943bd 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -1171,6 +1171,7 @@ fn main() {native_clipboard::read_native_clipboard_files,native_clipboard::read_native_clipboard_png,native_file_dialogs::save_native_file,+ native_file_dialogs::save_native_file_from_url,native_file_dialogs::pick_native_chat_import,native_file_dialogs::pick_native_training_config,native_intents::drain_native_intents,diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rsindex 62e7f4f3549..e4ef7d03db7 100644--- a/studio/src-tauri/src/native_file_dialogs.rs+++ b/studio/src-tauri/src/native_file_dialogs.rs@@ -5,6 +5,7 @@ use std::borrow::Cow;use std::fs::{self, File};use std::io::{Read, Write};use std::path::{Path, PathBuf};+use std::time::Duration;use tauri::{AppHandle, WebviewWindow};use tauri_plugin_dialog::DialogExt;@@ -79,10 +80,11 @@ fn save_filter(file_name: &str) -> (&'static str, Vec<String>) {Some("svg") => ("SVG image", filter_extensions(["svg"])),Some("wav") => ("WAV audio", filter_extensions(["wav"])),Some("mp3") => ("MP3 audio", filter_extensions(["mp3"])),- Some("m4a") | Some("mp4") => ("MPEG-4 audio", filter_extensions(["m4a", "mp4"])),+ // Named for both tracks: the gallery saves .mp4 through this dialog too.+ Some("m4a") | Some("mp4") => ("MPEG-4 video or audio", filter_extensions(["m4a", "mp4"])),Some("ogg") | Some("oga") => ("Ogg audio", filter_extensions(["ogg", "oga"])),Some("flac") => ("FLAC audio", filter_extensions(["flac"])),- Some("webm") => ("WebM audio", filter_extensions(["webm"])),+ Some("webm") => ("WebM video or audio", filter_extensions(["webm"])),Some(extension) if is_safe_filter_extension(extension) => {("Export file", vec![extension.to_string()])}@@ -115,13 +117,8 @@ fn local_dialog_path(path: tauri_plugin_dialog::FilePath) -> Result<PathBuf, Str.map_err(|_| "Only local filesystem paths are supported.".to_string())}-fn save_selected_file(- selected_path: Option<PathBuf>,- content: &[u8],-) -> Result<Option<String>, String> {- let Some(path) = selected_path else {- return Ok(None);- };+/// Stage the write beside the destination so a partial file never replaces a real one.+fn staged_temp_file(path: &Path) -> Result<tempfile::NamedTempFile, String> {let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty())@@ -130,15 +127,32 @@ fn save_selected_file(#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;- let permissions = fs::metadata(&path)+ let permissions = fs::metadata(path).map(|metadata| metadata.permissions()).unwrap_or_else(|_| fs::Permissions::from_mode(0o666));builder.permissions(permissions);}- let mut temporary = builder+ builder.prefix(".unsloth-export-").tempfile_in(parent)- .map_err(|error| format!("Failed to prepare {}: {error}", path.display()))?;+ .map_err(|error| format!("Failed to prepare {}: {error}", path.display()))+}++fn saved_file_name(path: &Path) -> String {+ path.file_name()+ .and_then(|name| name.to_str())+ .unwrap_or("export")+ .to_string()+}++fn save_selected_file(+ selected_path: Option<PathBuf>,+ content: &[u8],+) -> Result<Option<String>, String> {+ let Some(path) = selected_path else {+ return Ok(None);+ };+ let mut temporary = staged_temp_file(&path)?;temporary.write_all(content).and_then(|()| temporary.as_file().sync_all())@@ -146,12 +160,33 @@ fn save_selected_file(temporary.persist(&path).map_err(|error| format!("Failed to save {}: {}", path.display(), error.error))?;- let file_name = path- .file_name()- .and_then(|name| name.to_str())- .unwrap_or("export")- .to_string();- Ok(Some(file_name))+ Ok(Some(saved_file_name(&path)))+}++/// Only the local backend, or the webview could write any host's reply to disk. Parsed+/// rather than sliced: in `http://127.0.0.1:[email protected]/clip` the loopback-looking part+/// is userinfo and the client would connect to `evil.test`.+fn require_loopback_url(url: &str) -> Result<(), String> {+ const REJECT: &str = "Only local http URLs can be saved.";+ let parsed = reqwest::Url::parse(url).map_err(|_| REJECT.to_string())?;+ if parsed.scheme() != "http" || !parsed.username().is_empty() || parsed.password().is_some() {+ return Err(REJECT.to_string());+ }+ let host = parsed.host_str().ok_or_else(|| REJECT.to_string())?;+ // host_str keeps the brackets on an IPv6 literal.+ let bare = host+ .strip_prefix('[')+ .and_then(|h| h.strip_suffix(']'))+ .unwrap_or(host);+ let loopback = bare+ .parse::<std::net::IpAddr>()+ .map(|ip| ip.is_loopback())+ .unwrap_or(host == "localhost");+ if loopback {+ Ok(())+ } else {+ Err(REJECT.to_string())+ }}fn read_selected_text_import(@@ -271,6 +306,83 @@ pub async fn save_native_file(save_selected_file(selected_path, content.as_ref())}+/// Save a backend URL by streaming it to the chosen path.+///+/// `save_native_file` carries the bytes through IPC, so the caller buffers the whole body+/// and the chooser waits on it. A clip is capped at 2048x2048 by 1024 frames, so this opens+/// the chooser first and writes the response chunk by chunk, leaving nothing resident.+#[tauri::command]+pub async fn save_native_file_from_url(+ window: WebviewWindow,+ app: AppHandle,+ url: String,+ file_name: String,+) -> Result<Option<String>, String> {+ crate::native_intents::ensure_main_window(&window)?;+ require_loopback_url(&url)?;+ let file_name = default_file_name(&file_name);+ let (filter_name, extensions) = save_filter(&file_name);+ let extension_refs = extensions.iter().map(String::as_str).collect::<Vec<_>>();+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.dialog()+ .file()+ .set_title("Save Unsloth export")+ .set_file_name(file_name)+ .add_filter(filter_name, &extension_refs)+ .save_file(move |path| {+ let _ = tx.send(path);+ });+ let selected_path = rx+ .await+ .map_err(|_| "Save dialog closed unexpectedly.".to_string())?+ .map(local_dialog_path)+ .transpose()?;+ let Some(path) = selected_path else {+ return Ok(None);+ };+ stream_url_to_path(&url, &path, DOWNLOAD_READ_TIMEOUT).await?;+ Ok(Some(saved_file_name(&path)))+}++/// A local backend that has accepted the request should never go quiet for this long, and a+/// clip that is still arriving resets it, so a large save is not cut short.+const DOWNLOAD_READ_TIMEOUT: Duration = Duration::from_secs(30);++async fn stream_url_to_path(url: &str, path: &Path, read_timeout: Duration) -> Result<(), String> {+ let mut response =+ crate::loopback_http::streaming_client(Duration::from_secs(10), read_timeout)+ .map_err(|error| format!("Download failed: {error}"))?+ .get(url)+ .send()+ .await+ .map_err(|error| format!("Download failed: {error}"))?;+ // Redirects are refused rather than followed, so a 3xx is a rejection here, not a hop.+ if !response.status().is_success() {+ return Err(format!(+ "Download failed with status {}.",+ response.status().as_u16()+ ));+ }+ let mut temporary = staged_temp_file(path)?;+ while let Some(chunk) = response+ .chunk()+ .await+ .map_err(|error| format!("Download failed: {error}"))?+ {+ temporary+ .write_all(&chunk)+ .map_err(|error| format!("Failed to save {}: {error}", path.display()))?;+ }+ temporary+ .as_file()+ .sync_all()+ .map_err(|error| format!("Failed to save {}: {error}", path.display()))?;+ temporary+ .persist(path)+ .map_err(|error| format!("Failed to save {}: {}", path.display(), error.error))?;+ Ok(())+}+#[tauri::command]pub async fn pick_native_chat_import(window: WebviewWindow,@@ -438,7 +550,171 @@ mod tests {assert_save_filter("photo.PNG", "PNG image", &["png"]);assert_save_filter("shot.jpeg", "JPEG image", &["jpg", "jpeg"]);assert_save_filter("clip.wav", "WAV audio", &["wav"]);- assert_save_filter("voice.webm", "WebM audio", &["webm"]);+ assert_save_filter("voice.webm", "WebM video or audio", &["webm"]);+ }++ /// A current-thread runtime: these tests need one task, not a worker per core.+ fn test_runtime() -> tokio::runtime::Runtime {+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ }++ /// A one-shot loopback server, so the streaming save is exercised over real HTTP.+ fn serve_once(body: Vec<u8>, status: &'static str) -> (String, std::thread::JoinHandle<()>) {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let handle = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut discard = [0_u8; 1024];+ let _ = std::io::Read::read(&mut stream, &mut discard);+ let header = format!(+ "HTTP/1.1 {status}\r\nContent-Length: {}\r\nContent-Type: video/mp4\r\n\r\n",+ body.len()+ );+ let _ = stream.write_all(header.as_bytes());+ let _ = stream.write_all(&body);+ });+ (format!("http://127.0.0.1:{port}/clip.mp4"), handle)+ }++ #[test]+ fn streaming_save_writes_the_whole_body_without_buffering_it() {+ // Larger than any single chunk, so the loop is what assembles the file.+ let body: Vec<u8> = (0..3_000_000_u32).map(|i| (i % 251) as u8).collect();+ let (url, server) = serve_once(body.clone(), "200 OK");+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("clip.mp4");+ test_runtime()+ .block_on(stream_url_to_path(&url, &dest, DOWNLOAD_READ_TIMEOUT))+ .unwrap();+ server.join().unwrap();+ assert_eq!(fs::read(&dest).unwrap(), body);+ // Nothing partial left beside it.+ let strays: Vec<_> = fs::read_dir(dir.path())+ .unwrap()+ .filter_map(|entry| entry.ok())+ .filter(|entry| entry.file_name() != std::ffi::OsStr::new("clip.mp4"))+ .collect();+ assert!(strays.is_empty(), "staging file left behind");+ }++ #[test]+ fn a_failed_download_leaves_no_file_behind() {+ let (url, server) = serve_once(b"nope".to_vec(), "401 Unauthorized");+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("clip.mp4");+ let error = test_runtime()+ .block_on(stream_url_to_path(&url, &dest, DOWNLOAD_READ_TIMEOUT))+ .unwrap_err();+ server.join().unwrap();+ assert!(error.contains("401"), "{error}");+ assert!(!dest.exists(), "a rejected link must not create the file");+ }++ #[test]+ fn streaming_save_only_accepts_the_local_backend() {+ for url in [+ "http://127.0.0.1:8888/api/inference/video/gallery/abc/file-signed?token=t",+ "http://localhost:8908/api/inference/video/gallery/abc/file-signed?token=t",+ "http://[::1]:8888/api/inference/video/gallery/abc/file",+ "http://127.0.0.1/api/inference/video/gallery/abc/file",+ ] {+ assert!(require_loopback_url(url).is_ok(), "should allow {url}");+ }+ // The userinfo forms are the ones a naive authority split accepts: everything+ // before the '@' is credentials, so the real host is what follows it.+ for url in [+ "http://evil.test/x.mp4",+ "https://127.0.0.1:8888/x.mp4",+ "file:///etc/passwd",+ "http://127.0.0.1.evil.test/x.mp4",+ "http://[email protected]/x.mp4",+ "http://127.0.0.1:[email protected]/video",+ "http://[email protected]/video",+ "http://localhost:[email protected]/video",+ "http://[::1]:[email protected]/video",+ "http://10.0.0.5/x.mp4",+ "http://169.254.169.254/latest/meta-data",+ "",+ ] {+ assert!(require_loopback_url(url).is_err(), "should reject {url}");+ }+ }++ #[test]+ fn a_backend_that_goes_quiet_mid_body_stops_the_save() {+ // Headers promise more than is sent, then the server holds the socket open. Without a+ // per-read timeout the invoke never resolves and the staging file stays behind.+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let (release, stalled) = std::sync::mpsc::channel::<()>();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut discard = [0_u8; 1024];+ let _ = std::io::Read::read(&mut stream, &mut discard);+ let _ = stream.write_all(+ b"HTTP/1.1 200 OK\r\nContent-Length: 1024\r\nContent-Type: video/mp4\r\n\r\nhalf",+ );+ let _ = stalled.recv(); // hold the connection open until the read has given up+ });+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("clip.mp4");+ let error = test_runtime()+ .block_on(stream_url_to_path(+ &format!("http://127.0.0.1:{port}/clip.mp4"),+ &dest,+ Duration::from_millis(250),+ ))+ .unwrap_err();+ drop(release);+ server.join().unwrap();+ assert!(error.starts_with("Download failed"), "{error}");+ assert!(!dest.exists(), "a stalled download must not leave a file");+ assert_eq!(+ fs::read_dir(dir.path()).unwrap().count(),+ 0,+ "the staging file must be cleaned up"+ );+ }++ #[test]+ fn a_redirect_off_loopback_is_refused_not_followed() {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ let server = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut discard = [0_u8; 1024];+ let _ = std::io::Read::read(&mut stream, &mut discard);+ let _ = stream.write_all(+ b"HTTP/1.1 302 Found\r\nLocation: http://evil.test/x.mp4\r\n\+ Content-Length: 0\r\nConnection: close\r\n\r\n",+ );+ });+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("clip.mp4");+ let error = test_runtime()+ .block_on(stream_url_to_path(+ &format!("http://127.0.0.1:{port}/clip.mp4"),+ &dest,+ DOWNLOAD_READ_TIMEOUT,+ ))+ .unwrap_err();+ server.join().unwrap();+ assert!(error.contains("302"), "{error}");+ assert!(!dest.exists(), "a redirect must not produce a file");+ }++ #[test]+ fn a_gallery_clip_offers_its_own_container() {+ // The gallery's MP4 is the only export that reaches this dialog; WebM and GIF+ // save from a blob. Both mp4 arms are named for video since #8173.+ assert_save_filter(+ "Unsloth_video_20260808-120000_1670009728.mp4",+ "MPEG-4 video or audio",+ &["m4a", "mp4"],+ );}#[test]diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex 2f9aafbbe7b..fad53337bbf 100644--- a/studio/src-tauri/tauri.conf.json+++ b/studio/src-tauri/tauri.conf.json@@ -16,7 +16,7 @@"app": {"withGlobalTauri": true,"security": {- "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https:; media-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'self' http://localhost:* http://127.0.0.1:*"+ "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https:; media-src 'self' data: blob: https: http://localhost:* http://127.0.0.1:*; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'self' http://localhost:* http://127.0.0.1:*"},"windows": [{diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex aa0f1da6d79..3e668995a38 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -42,6 +42,8 @@ APP_PROVIDER = FRONTEND / "app/provider.tsx"ROOT_ROUTE = FRONTEND / "app/routes/__root.tsx"IMAGES_PAGE = FRONTEND / "features/images/images-page.tsx"VIDEO_PAGE = FRONTEND / "features/video/video-page.tsx"+VIDEO_API = FRONTEND / "features/video/api.ts"+RAG_API = FRONTEND / "features/rag/api/rag-api.ts"REMOTE_ACCESS_SECTION = FRONTEND / "features/settings/components/remote-access-section.tsx"PASSWORD_DIALOG = FRONTEND / "features/settings/components/change-password-dialog.tsx"@@ -265,6 +267,62 @@ def test_generated_download_buttons_use_the_native_save_boundary():assert "isDownloadCancelled(error)" in source+def test_gallery_video_links_are_absolute_and_saved_natively():+ video_api = VIDEO_API.read_text(encoding = "utf-8")+ video_page = VIDEO_PAGE.read_text(encoding = "utf-8")+ rag_api = RAG_API.read_text(encoding = "utf-8")++ # The backend mints this link relative so a proxy can serve it. Its consumers are+ # <video src> and the download, none of which go through authFetch, so a relative+ # path under Tauri resolves against the webview and yields the SPA shell.+ assert "return apiUrl(body.url);" in video_api+ assert 'from "@/lib/api-base"' in video_api+ # The same fix the RAG document preview already carries.+ assert "return apiUrl(data.url);" in rag_api++ # An absolute link is cross-origin, where the download attribute stops saving, so the+ # MP4 goes native. Streaming, not downloadUrl: a clip is capped at 2048x2048 x 1024+ # frames, too big to buffer for IPC, and the chooser must not wait on the body.+ helper = NATIVE_FILES.read_text(encoding = "utf-8")+ assert "downloadUrlStreaming(src, exportFilename(video, format))" in video_page+ assert '"save_native_file_from_url"' in helper+ assert "isDownloadCancelled(err)" in video_page+ # WebM / GIF keep the blob-and-anchor route they already had; nothing forced a change.+ assert "URL.createObjectURL(blob)" in video_page++ # media-src, not just connect-src: the signed link is played by an element.+ tauri_config = (REPO / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8")+ assert (+ "media-src 'self' data: blob: https: http://localhost:* http://127.0.0.1:*" in tauri_config+ )++ # The save dialog now offers these to video, not just to the audio player, and the+ # streaming command is registered and pinned to the local backend.+ dialogs = NATIVE_DIALOGS.read_text(encoding = "utf-8")+ assert '("MPEG-4 video or audio", filter_extensions(["m4a", "mp4"]))' in dialogs+ assert '("WebM video or audio", filter_extensions(["webm"]))' in dialogs+ assert "async fn stream_url_to_path" in dialogs+ # Parsed, not sliced: in http://127.0.0.1:[email protected] the loopback part is userinfo.+ assert "reqwest::Url::parse(url)" in dialogs+ assert "parsed.username().is_empty()" in dialogs+ assert "parsed.password().is_some()" in dialogs+ # The chooser has to come first, or the user waits on the body before being asked where.+ streaming = dialogs[dialogs.index("pub async fn save_native_file_from_url") :]+ assert streaming.index(".save_file(") < streaming.index("stream_url_to_path(&url")+ # No proxy (the signed URL must not reach one) and no redirects (they would leave loopback+ # after the check). read_timeout, not timeout: it bounds each chunk, so a backend that goes+ # quiet cannot hang the save while a legitimately large clip still finishes.+ loopback = (REPO / "studio/src-tauri/src/loopback_http.rs").read_text(encoding = "utf-8")+ assert "fn streaming_client" in loopback+ assert "redirect(reqwest::redirect::Policy::none())" in loopback+ assert ".read_timeout(read_timeout)" in loopback+ assert ".timeout(" not in loopback.split("fn streaming_client")[1]+ assert loopback.count(".no_proxy()") == 2+ assert "loopback_http::streaming_client" in dialogs+ main_rs = (REPO / "studio/src-tauri/src/main.rs").read_text(encoding = "utf-8")+ assert "native_file_dialogs::save_native_file_from_url," in main_rs++def test_clipboard_file_paste_is_bounded_and_wired_to_both_composers():helper = CLIPBOARD_FILES.read_text(encoding = "utf-8")thread = THREAD.read_text(encoding = "utf-8")