Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(mlx-video): in-process playback via read_media_file + blob URL

purple7516f4125610
diff --git a/src-tauri/src/commands/media_cmds.rs b/src-tauri/src/commands/media_cmds.rs
index ca716309..20ba938c 100644
--- a/src-tauri/src/commands/media_cmds.rs
+++ b/src-tauri/src/commands/media_cmds.rs
@@ -16,7 +16,9 @@
//! like the existing ComfyUI/whisper sidecars.
use crate::state::AppState;
+use base64::Engine;
use serde_json::Value;
+use std::path::PathBuf;
use tauri::State;
// ── MLX image (MLX-Stable-Diffusion) ────────────────────────────────────
@@ -122,3 +124,56 @@ pub fn video_progress(state: State<'_, AppState>, args: Value) -> Result<Value,
pub fn video_cancel(state: State<'_, AppState>, args: Value) -> Result<Value, String> {
crate::commands::video::video_cancel(state.inner(), &args)
}
+
+// ── Media playback (video → blob URL) ───────────────────────────────────
+//
+// MLX video never touches the sidecar HTTP surface the image path uses
+// (`mlx_generate` proxies to :47712 and returns base64 straight from the
+// response body) — `video_generate` runs `mlx_video.*.generate` as a bare
+// subprocess and writes an mp4 to disk (`commands::video::outputs_root()`).
+// With the lu-bridge daemon gone there is nothing serving that file at
+// :47711/videos/<file> anymore, and the CSP's `media-src` has no `file:`
+// grant (only `'self' blob: http://localhost:* http://127.0.0.1:*`), so a
+// `<video src="file:///...">` would just be blocked. Read the bytes here
+// and let the frontend build a `blob:` URL instead — that's an origin the
+// CSP already allows.
+
+/// Roots `read_media_file` is allowed to serve bytes from. Only MLX video
+/// output today (MLX images are never written to disk — see above); add
+/// more roots here if a future in-process media backend gains one.
+fn allowed_media_roots() -> Vec<PathBuf> {
+ vec![crate::commands::video::outputs_root()]
+}
+
+/// Read a file from one of the app's own media output directories and
+/// return its bytes as base64, so the frontend can turn it into a
+/// `Blob`/`URL.createObjectURL` blob: URL for `<video>` playback and
+/// Download.
+///
+/// Path-traversal guard: canonicalizes both `path` and every allowed root
+/// (resolving `..` and symlinks) and rejects anything whose canonical form
+/// doesn't fall under an allowed root — this is NOT a general-purpose file
+/// read, it only ever serves the app's own generated media.
+#[tauri::command]
+pub fn read_media_file(path: String) -> Result<String, String> {
+ let candidate = PathBuf::from(&path);
+ let canonical = candidate
+ .canonicalize()
+ .map_err(|e| format!("read_media_file: {}: {e}", candidate.display()))?;
+
+ let allowed = allowed_media_roots().into_iter().any(|root| {
+ root.canonicalize()
+ .map(|r| canonical.starts_with(&r))
+ .unwrap_or(false)
+ });
+ if !allowed {
+ return Err(format!(
+ "read_media_file: path escapes the allowed media directories: {}",
+ canonical.display()
+ ));
+ }
+
+ let bytes = std::fs::read(&canonical)
+ .map_err(|e| format!("read_media_file: {}: {e}", canonical.display()))?;
+ Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index eba9ec68..60a915f6 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -215,6 +215,7 @@ fn main() {
commands::media_cmds::video_generate,
commands::media_cmds::video_progress,
commands::media_cmds::video_cancel,
+ commands::media_cmds::read_media_file,
// Provider API-key keychain (H5)
commands::secret::secret_set,
commands::secret::secret_get,
diff --git a/src/api/mlx-video.ts b/src/api/mlx-video.ts
index 15cbba97..d555e37f 100644
--- a/src/api/mlx-video.ts
+++ b/src/api/mlx-video.ts
@@ -132,6 +132,21 @@ export async function cancelVideo(): Promise<{ ok: boolean }> {
return invokeMedia<{ ok: boolean }>('video_cancel')
}
+/** Read a finished MLX video's bytes (via the `read_media_file` Rust command,
+ * guarded to the app's own video output dir) and turn them into a `blob:`
+ * URL — the CSP's `media-src` allows `blob:` but not `data:`, so this is
+ * the only way to get `<video>` playback + Download working now that the
+ * old lu-bridge (:47711/videos/<file>) is gone. Caller owns the returned
+ * URL's lifetime (revoke it when the gallery item is dropped, if ever). */
+export async function readVideoAsBlobUrl(path: string): Promise<string> {
+ const b64 = await backendCall<string>('read_media_file', { path })
+ const binary = atob(b64)
+ const bytes = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
+ const blob = new Blob([bytes], { type: 'video/mp4' })
+ return URL.createObjectURL(blob)
+}
+
// ── Create-tab wiring (mirrors mlx-image.ts's synthetic-model pattern) ──
//
// On macOS the video picker shows the installed MLX catalog directly — there
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 67868267..e438f0a9 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -40,7 +40,7 @@ import {
} from '../api/mlx-image'
import {
getVideoStatus, listVideoModels, generateVideo, getVideoProgress, cancelVideo,
- buildMlxVideoModels, mlxVideoModelIdFor,
+ buildMlxVideoModels, mlxVideoModelIdFor, readVideoAsBlobUrl,
} from '../api/mlx-video'
export function useCreate() {
@@ -430,10 +430,24 @@ export function useCreate() {
if (prog.status === 'complete') {
setProgress(100, 'Complete!')
useCreateStore.getState().setLastGenTime(`${elapsed}s`)
+ // The mp4 lives on disk only (no lu-bridge :47711/videos/<file>
+ // route anymore) — read it via the guarded `read_media_file`
+ // Rust command and hand the frontend a `blob:` URL, which the
+ // CSP's media-src allows (unlike `data:`). Reuse `dataUrl`:
+ // galleryItemUrl()/OutputView/Lightbox/download already prefer
+ // it over the ComfyUI /view path, and a blob: URL is just a
+ // string src as far as <video>/fetch are concerned.
+ let dataUrl: string | undefined
+ try {
+ dataUrl = await readVideoAsBlobUrl(result.output)
+ } catch (e) {
+ console.error('read_media_file failed for MLX video output', e)
+ }
addToGallery({
id: uuid(), type: 'video', filename: '', subfolder: '',
- // No in-process route serves MLX video output yet (unlike the
- // image sidecar's :47712) — see GalleryItem.localPath's TODO.
+ dataUrl,
+ // Keep the real on-disk path too, in case a future
+ // download-to-disk path wants to reference it directly.
localPath: result.output,
prompt, negativePrompt, model: videoModel, modelType: 'wan',
seed: seed === -1 ? 0 : seed, steps, cfgScale, sampler, scheduler,
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index ed3b54de..72b30873 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -110,10 +110,14 @@ export interface GalleryItem {
builderUsed?: 'dynamic' | 'legacy' | 'custom'
resolvedVAE?: string
resolvedCLIP?: string
- /** Self-contained PNG data URL for backends that don't serve files over
- * ComfyUI's /view route (e.g. MLX on Apple Silicon). When set, display +
- * download read from this instead of filename/subfolder. In-memory only —
- * partialize strips it so media bytes never hit the localStorage quota. */
+ /** Self-contained media URL for backends that don't serve files over
+ * ComfyUI's /view route (e.g. MLX on Apple Silicon): a `data:` PNG URL for
+ * MLX images, or a `blob:` URL for MLX video (built from bytes read via
+ * the `read_media_file` Tauri command — the CSP's media-src allows
+ * `blob:` but not `data:` for video). When set, display + download read
+ * from this instead of filename/subfolder. In-memory only — partialize
+ * strips it so media bytes never hit the localStorage quota (and a
+ * blob: URL wouldn't survive a reload anyway). */
dataUrl?: string
/** Cloud jobs: signed result URL from the render queue. Display prefers
* `remoteUrl` → `dataUrl` → the ComfyUI /view path (filename/subfolder). */
@@ -125,12 +129,10 @@ export interface GalleryItem {
/** Which redesign intent produced this item (gallery tagging). */
intent?: CreateIntent
/** MLX video (Mac, Apple Silicon): absolute filesystem path of the finished
- * mp4, as returned by `video_generate`'s `output` field. TODO(mlx-video-
- * playback): there is no in-process HTTP route or asset-protocol scope
- * serving this yet (unlike the MLX image sidecar on :47712), and the CSP
- * `media-src` doesn't allow `file:` — so `<video>` can't play it inline
- * today. Wire a served route or Tauri asset scope, then point display/
- * download at that URL instead of leaving this as a dead-end path. */
+ * mp4, as returned by `video_generate`'s `output` field. Playback/download
+ * go through `dataUrl` (a blob: URL, see above) instead — this is kept
+ * around as the real on-disk path for any future save-to-disk flow that
+ * wants to reference the file directly instead of re-encoding the blob. */
localPath?: string
/** Runtime-only (stripped by partialize): the item's media failed to load
* and can't be recovered right now — a local ComfyUI item while the engine