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.

fix(create): survive ComfyUI 0.19+ origin checks — WS via Rust proxy, proxied media fallback, CORS banner (#75)

purpleb31130dc6958
diff --git a/src-tauri/src/commands/comfy_ws.rs b/src-tauri/src/commands/comfy_ws.rs
new file mode 100644
index 00000000..8787b8bd
--- /dev/null
+++ b/src-tauri/src/commands/comfy_ws.rs
@@ -0,0 +1,122 @@
+// WebSocket proxy for the ComfyUI progress stream (2.5.8, GH #75 family).
+//
+// ComfyUI 0.19+ ships an origin-check middleware (upstream commit 76b75f3)
+// that 403s every cross-site request — including the WebView's
+// `ws://host:port/ws` upgrade from `http://tauri.localhost`, which killed the
+// live progress bar unless the user passed `--enable-cors-header`. HTTP
+// already goes through the Rust localhost proxy (no browser Origin header →
+// passes); this gives the progress WebSocket the same treatment: the frontend
+// asks Rust to open the socket, Rust connects with a plain client handshake
+// (tokio-tungstenite sends no Origin) and relays every text frame to the
+// WebView as a `comfy-ws-message` Tauri event.
+//
+// Receive-only by design: the frontend never sends application frames on this
+// socket (see src/api/comfyui-ws.ts), so no send command is exposed. Binary
+// frames (live preview images) are skipped — the old direct-WS path dropped
+// them too (JSON.parse on a Blob throws → ignored). Host + port come from
+// AppState (same user-validated values the HTTP proxy allow-lists), never
+// from the frontend, so this opens no new SSRF surface.
+
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::Duration;
+
+use futures_util::StreamExt;
+use once_cell::sync::Lazy;
+use tauri::{AppHandle, Emitter, State};
+use tokio_tungstenite::tungstenite::Message;
+
+use crate::state::AppState;
+
+struct ConnHandle {
+ generation: u64,
+ task: tauri::async_runtime::JoinHandle<()>,
+}
+
+/// Single managed upstream connection — mirrors the frontend singleton
+/// (`comfyWS` / one CLIENT_ID per app run). A new connect replaces the old
+/// socket; generations keep a superseded reader from clobbering its
+/// replacement's registration or emitting a stale close event.
+static CONN: Lazy<tokio::sync::Mutex<Option<ConnHandle>>> =
+ Lazy::new(|| tokio::sync::Mutex::new(None));
+static NEXT_GEN: AtomicU64 = AtomicU64::new(1);
+
+/// Open (or replace) the proxied ComfyUI progress socket. Resolves once the
+/// upstream handshake succeeded — the frontend treats resolution like
+/// `ws.onopen` and rejection like `ws.onerror` (falls back to /history
+/// polling), so this must always settle; the timeout guarantees that.
+#[tauri::command]
+pub async fn comfy_ws_connect(
+ app: AppHandle,
+ state: State<'_, AppState>,
+ client_id: String,
+) -> Result<(), String> {
+ // Read the user-configured target before any await — these are std
+ // Mutexes and must not be held across suspension points.
+ let (host, port) = {
+ let host = state.comfy_host.lock().unwrap().clone();
+ let port = *state.comfy_port.lock().unwrap();
+ (host, port)
+ };
+ let url = format!(
+ "ws://{}:{}/ws?clientId={}",
+ host,
+ port,
+ urlencoding::encode(&client_id)
+ );
+
+ let (stream, _resp) = tokio::time::timeout(
+ Duration::from_secs(5),
+ tokio_tungstenite::connect_async(&url),
+ )
+ .await
+ .map_err(|_| "ComfyUI WebSocket connect timeout".to_string())?
+ .map_err(|e| format!("ComfyUI WebSocket connect failed: {}", e))?;
+
+ let generation = NEXT_GEN.fetch_add(1, Ordering::Relaxed);
+
+ // Hold the registry lock across spawn+insert so the reader's shutdown
+ // path (which also takes this lock) can never observe a half-registered
+ // connection, even if the socket dies instantly.
+ let mut guard = CONN.lock().await;
+ if let Some(old) = guard.take() {
+ old.task.abort();
+ }
+
+ let task = tauri::async_runtime::spawn(async move {
+ // The unsplit stream auto-handles ping/pong on poll; we never write.
+ let mut stream = stream;
+ loop {
+ match stream.next().await {
+ Some(Ok(Message::Text(text))) => {
+ let _ = app.emit("comfy-ws-message", text.as_str());
+ }
+ Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break,
+ // Binary previews, ping/pong, raw frames: intentionally dropped.
+ Some(Ok(_)) => {}
+ }
+ }
+ // Announce the close only if this reader is still the live one —
+ // a replaced/aborted reader must stay silent so it can't trigger a
+ // spurious frontend reconnect against the connection that replaced it.
+ let mut guard = CONN.lock().await;
+ if guard.as_ref().map(|c| c.generation) == Some(generation) {
+ *guard = None;
+ let _ = app.emit("comfy-ws-closed", ());
+ }
+ });
+
+ *guard = Some(ConnHandle { generation, task });
+ Ok(())
+}
+
+/// Tear down the proxied socket, if any. Deliberately emits no close event:
+/// the frontend only calls this from its own `disconnect()`, which already
+/// resets its state (mirrors the old `ws.onclose = null; ws.close()`).
+#[tauri::command]
+pub async fn comfy_ws_disconnect() -> Result<(), String> {
+ let mut guard = CONN.lock().await;
+ if let Some(old) = guard.take() {
+ old.task.abort();
+ }
+ Ok(())
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 611ea95c..7e2f79c8 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -2,6 +2,7 @@ pub mod agent;
pub mod bg_tasks;
pub mod repo_map;
pub mod claude_code;
+pub mod comfy_ws;
pub mod download;
pub mod engine;
pub mod filesystem;
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 3b2d62dd..a0d4002a 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -97,7 +97,6 @@ fn main() {
// Process management
commands::process::start_ollama,
commands::process::start_comfyui,
- commands::process::check_flash_attention,
commands::process::stop_comfyui,
commands::process::comfyui_status,
commands::process::find_comfyui,
@@ -110,6 +109,9 @@ fn main() {
commands::process::set_ollama_host,
commands::process::get_ollama_host,
commands::process::offload_local_models,
+ // ComfyUI progress WebSocket via Rust (0.19+ origin-check bypass)
+ commands::comfy_ws::comfy_ws_connect,
+ commands::comfy_ws::comfy_ws_disconnect,
// Installation
commands::install::install_comfyui,
commands::install::install_comfyui_status,
diff --git a/src/api/comfyui-ws.ts b/src/api/comfyui-ws.ts
index 0fa3f4c2..432ba6c8 100644
--- a/src/api/comfyui-ws.ts
+++ b/src/api/comfyui-ws.ts
@@ -9,7 +9,7 @@
import { v4 as uuid } from 'uuid'
import { log } from '../lib/logger'
-import { comfyuiWsUrl } from './backend'
+import { comfyuiWsUrl, isTauri } from './backend'
export type ComfyWSEvent =
| { type: 'status'; data: { queue_remaining: number } }
@@ -51,17 +51,84 @@ class ComfyWSClient {
private maxReconnectDelay = 30000
private _connected = false
private connectPromise: Promise<void> | null = null
+ private tauriListenersReady: Promise<void> | null = null
get connected() { return this._connected }
- /** Connect and return a promise that resolves when the WS is open */
+ /**
+ * Connect and return a promise that resolves when the WS is open.
+ *
+ * Desktop (Tauri) connects through the Rust WS proxy instead of a raw
+ * browser WebSocket: ComfyUI 0.19+ rejects the WebView's cross-origin
+ * upgrade from http://tauri.localhost unless the user passes
+ * `--enable-cors-header`, which silently killed the live progress bar.
+ * Rust's client handshake carries no Origin header, so it always passes —
+ * same reason all ComfyUI HTTP already goes through the Rust proxy.
+ * The web build keeps the raw WebSocket (Vite dev proxy / same-origin).
+ */
connect(timeoutMs = 3000): Promise<void> {
- if (this._connected && this.ws?.readyState === WebSocket.OPEN) {
+ if (this._connected && (isTauri() || this.ws?.readyState === WebSocket.OPEN)) {
return Promise.resolve()
}
if (this.connectPromise) return this.connectPromise
- this.connectPromise = new Promise<void>((resolve, reject) => {
+ this.connectPromise = isTauri() ? this.connectViaProxy() : this.connectRaw(timeoutMs)
+ return this.connectPromise
+ }
+
+ /** Tauri: open the socket Rust-side; resolve = onopen, reject = onerror. */
+ private async connectViaProxy(): Promise<void> {
+ try {
+ await this.ensureTauriListeners()
+ const { invoke } = await import('@tauri-apps/api/core')
+ // Rust settles within 5s (internal handshake timeout), so no extra
+ // JS-side timer is needed — the promise can never hang (see the
+ // onerror comment below for why settling is critical).
+ await invoke('comfy_ws_connect', { clientId: CLIENT_ID })
+ this._connected = true
+ this.reconnectDelay = 1000
+ log.info('[ComfyWS] Connected (Rust proxy)')
+ } catch (e) {
+ // Raw path gets its retry loop from onclose firing after onerror;
+ // mirror that here so a down ComfyUI keeps the same backoff-retry.
+ this.scheduleReconnect()
+ throw new Error(`WebSocket connection error: ${e}`)
+ } finally {
+ this.connectPromise = null
+ }
+ }
+
+ /** One-time registration of the Tauri event bridge for proxied frames. */
+ private ensureTauriListeners(): Promise<void> {
+ if (this.tauriListenersReady) return this.tauriListenersReady
+ this.tauriListenersReady = (async () => {
+ const { listen } = await import('@tauri-apps/api/event')
+ await listen<string>('comfy-ws-message', (ev) => {
+ try {
+ const msg = JSON.parse(ev.payload)
+ if (msg.type && msg.data) {
+ const event = msg as ComfyWSEvent
+ for (const listener of this.listeners) {
+ listener(event)
+ }
+ }
+ } catch { /* ignore non-JSON messages */ }
+ })
+ await listen('comfy-ws-closed', () => {
+ // Upstream socket died (ComfyUI stopped/restarted) — mirror onclose.
+ if (!this._connected) return
+ this._connected = false
+ this.scheduleReconnect()
+ })
+ })()
+ // If registration itself fails, allow a retry on the next connect()
+ this.tauriListenersReady.catch(() => { this.tauriListenersReady = null })
+ return this.tauriListenersReady
+ }
+
+ /** Web build: raw browser WebSocket (unchanged legacy path). */
+ private connectRaw(timeoutMs: number): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
this.connectPromise = null
reject(new Error('WebSocket connect timeout'))
@@ -122,8 +189,6 @@ class ComfyWSClient {
reject(new Error('WebSocket creation failed'))
}
})
-
- return this.connectPromise
}
private scheduleReconnect() {
@@ -146,6 +211,13 @@ class ComfyWSClient {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
}
+ if (isTauri()) {
+ // Fire-and-forget: abort the Rust-side socket. Rust emits no close
+ // event for a requested disconnect, so no reconnect gets scheduled.
+ import('@tauri-apps/api/core')
+ .then(({ invoke }) => invoke('comfy_ws_disconnect'))
+ .catch(() => { /* app teardown — nothing to recover */ })
+ }
if (this.ws) {
this.ws.onclose = null
this.ws.close()
diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsx
index d77fe4d9..f3a9440c 100644
--- a/src/components/create/experimental/CreateExperimental.tsx
+++ b/src/components/create/experimental/CreateExperimental.tsx
@@ -29,6 +29,8 @@ function CreateExperimentalInner() {
const error = useCreateStore((s) => s.error)
const setError = useCreateStore((s) => s.setError)
const backend = useCreateStore((s) => s.backend)
+ const comfyCorsBlocked = useCreateStore((s) => s.comfyCorsBlocked)
+ const setComfyCorsBlocked = useCreateStore((s) => s.setComfyCorsBlocked)
const { modelLoadError, connected, comfyOnCpu } = useCreateExp()
const [shownId, setShownId] = useState<string | null>(null)
@@ -129,6 +131,25 @@ function CreateExperimentalInner() {
</div>
)}
+ {/* Cross-origin block (#75, cinemazverev): a user-managed ComfyUI 0.19+
+ answers the WebView's media/WS requests with a Sec-Fetch 403, so results
+ couldn't be viewed. LU now proxies the bytes so they still display, but
+ the live progress bar + native video seeking degrade — point the user at
+ the one-line launch fix. Local only, dismissible. */}
+ {backend === 'local' && comfyCorsBlocked && (
+ <div className="flex items-start gap-2 px-4 py-2 bg-yellow-500/5 border-b border-yellow-500/10 text-yellow-300 text-xs shrink-0">
+ <AlertTriangle size={12} className="shrink-0 mt-0.5" />
+ <span className="flex-1 min-w-0">
+ Your ComfyUI blocks cross-origin apps (v0.19+), so LU is showing results through a fallback. To restore fast preview and the live progress bar, add{' '}
+ <code className="px-1 rounded bg-white/10">--enable-cors-header http://tauri.localhost</code>{' '}
+ to ComfyUI's launch (its run .bat / .sh), then restart ComfyUI.
+ </span>
+ <button onClick={() => setComfyCorsBlocked(false)} className="shrink-0 text-yellow-300/70 hover:text-yellow-100" title="Dismiss">
+ <X size={14} />
+ </button>
+ </div>
+ )}
+
{/* The viewer (Stage) and the Gallery bubble share ONE row, so they're
always the exact same height; the prompt window spans the full width
beneath them. (Previously the Gallery ran full-height alongside both the
diff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsx
index 725fde06..5bfba2de 100644
--- a/src/components/create/experimental/CreatePanel.tsx
+++ b/src/components/create/experimental/CreatePanel.tsx
@@ -1,8 +1,9 @@
import { motion, AnimatePresence } from 'framer-motion'
import { Images, Play, PanelRightClose, PanelRightOpen, Trash2, Download, MonitorOff } from 'lucide-react'
import { downloadMediaUrl } from '../../../lib/download-media'
-import { useCreateStore } from '../../../stores/createStore'
-import { galleryItemUrl, markGalleryItemAvailable, recoverGalleryUrl } from './galleryUrl'
+import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
+import { galleryItemUrl } from './galleryUrl'
+import { useComfyMedia } from './useComfyMedia'
import { cn } from '../ui/cn'
interface Props {
@@ -96,14 +97,7 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
g.intent === 'removebg' && 'lu-checker',
)}
>
- {g.type === 'video' ? (
- <>
- <video src={galleryItemUrl(g)} muted playsInline onError={() => recoverGalleryUrl(g)} onLoadedData={() => markGalleryItemAvailable(g)} className="w-full h-full object-cover" />
- <span className="absolute inset-0 flex items-center justify-center bg-black/20"><Play size={16} className="text-white/90" /></span>
- </>
- ) : (
- <img src={galleryItemUrl(g)} alt="" onError={() => recoverGalleryUrl(g)} onLoad={() => markGalleryItemAvailable(g)} className="w-full h-full object-cover" />
- )}
+ <GalleryThumb g={g} />
{g.unavailable && (
<span
className="absolute inset-0 flex items-center justify-center bg-black/50 text-gray-500"
@@ -137,3 +131,18 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
</AnimatePresence>
)
}
+
+// One thumbnail. Its own component so it can use the useComfyMedia hook (which
+// falls back to the Rust proxy when a user-managed ComfyUI 0.19+ 403s the
+// direct /view load, #75) — hooks can't run inside the gallery .map().
+function GalleryThumb({ g }: { g: GalleryItem }) {
+ const { src, onError, onLoad } = useComfyMedia(g)
+ return g.type === 'video' ? (
+ <>
+ <video src={src} muted playsInline onError={onError} onLoadedData={onLoad} className="w-full h-full object-cover" />
+ <span className="absolute inset-0 flex items-center justify-center bg-black/20"><Play size={16} className="text-white/90" /></span>
+ </>
+ ) : (
+ <img src={src} alt="" onError={onError} onLoad={onLoad} className="w-full h-full object-cover" />
+ )
+}
diff --git a/src/components/create/experimental/Lightbox.tsx b/src/components/create/experimental/Lightbox.tsx
index 2c934775..6eda8c4d 100644
--- a/src/components/create/experimental/Lightbox.tsx
+++ b/src/components/create/experimental/Lightbox.tsx
@@ -4,13 +4,14 @@ import { X, Sparkles } from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
import { runCredits } from '../../../stores/cloudCatalogStore'
import { useCreateExp } from './CreateContext'
-import { galleryItemUrl, recoverGalleryUrl } from './galleryUrl'
+import { useComfyMedia } from './useComfyMedia'
import { cn } from '../ui/cn'
export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose: () => void }) {
const backend = useCreateStore((s) => s.backend)
const isGenerating = useCreateStore((s) => s.isGenerating)
const { enhanceVideo, quota } = useCreateExp()
+ const { src: mediaUrl, onError: onMediaError } = useComfyMedia(item)
useEffect(() => {
if (!item) return
@@ -72,11 +73,11 @@ export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose:
initial={{ scale: 0.95 }}
animate={{ scale: 1 }}
exit={{ scale: 0.95 }}
- src={galleryItemUrl(item)}
+ src={mediaUrl}
controls
autoPlay
loop
- onError={() => recoverGalleryUrl(item)}
+ onError={onMediaError}
onClick={(e) => e.stopPropagation()}
className="max-w-full max-h-full object-contain rounded-lg"
/>
@@ -85,9 +86,9 @@ export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose:
initial={{ scale: 0.95 }}
animate={{ scale: 1 }}
exit={{ scale: 0.95 }}
- src={galleryItemUrl(item)}
+ src={mediaUrl}
alt={item.prompt}
- onError={() => recoverGalleryUrl(item)}
+ onError={onMediaError}
onClick={(e) => e.stopPropagation()}
className={cn('max-w-full max-h-full object-contain rounded-lg', item.intent === 'removebg' && 'lu-checker')}
/>
diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsx
index cec0cc8e..521919d3 100644
--- a/src/components/create/experimental/OutputView.tsx
+++ b/src/components/create/experimental/OutputView.tsx
@@ -3,7 +3,8 @@ import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff } from
import { useCreateStore, type GalleryItem, type ProgressPhase } from '../../../stores/createStore'
import { downloadComfyFile, isTauri } from '../../../api/backend'
import { refreshResultUrl } from '../../../api/cloud/jobs'
-import { galleryItemUrl, markGalleryItemAvailable, recoverGalleryUrl } from './galleryUrl'
+import { markGalleryItemAvailable } from './galleryUrl'
+import { useComfyMedia } from './useComfyMedia'
import { cn } from '../ui/cn'
function phaseIcon(phase: ProgressPhase) {
@@ -139,7 +140,7 @@ function reconcileDims(item: GalleryItem, w: number, h: number) {
}
export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps) {
- const url = galleryItemUrl(item)
+ const { src: url, onError } = useComfyMedia(item)
const download = () => void downloadGalleryItem(item)
const isVideo = item.type === 'video'
return (
@@ -153,7 +154,7 @@ export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps)
loop
autoPlay
muted
- onError={() => recoverGalleryUrl(item)}
+ onError={onError}
onLoadedData={(e) => { markGalleryItemAvailable(item); reconcileDims(item, e.currentTarget.videoWidth, e.currentTarget.videoHeight) }}
className="max-w-full max-h-[62vh] object-contain rounded-[var(--radius-panel)] border border-white/[0.06]"
/>
@@ -161,7 +162,7 @@ export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps)
<img
src={url}
alt={item.prompt}
- onError={() => recoverGalleryUrl(item)}
+ onError={onError}
onLoad={(e) => { markGalleryItemAvailable(item); reconcileDims(item, e.currentTarget.naturalWidth, e.currentTarget.naturalHeight) }}
className={cn('max-w-full max-h-[62vh] object-contain rounded-[var(--radius-panel)] border border-white/[0.06]', item.intent === 'removebg' && 'lu-checker')}
/>
diff --git a/src/components/create/experimental/galleryUrl.ts b/src/components/create/experimental/galleryUrl.ts
index ae16a4df..bea41f51 100644
--- a/src/components/create/experimental/galleryUrl.ts
+++ b/src/components/create/experimental/galleryUrl.ts
@@ -1,5 +1,6 @@
import { getImageUrl } from '../../../api/comfyui'
import { refreshResultUrl } from '../../../api/cloud/jobs'
+import { fetchLocalhostBytes, isTauri } from '../../../api/backend'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
/** Resolve a gallery item's display URL. Priority mirrors MediaViewer/Gallery:
@@ -48,6 +49,40 @@ export function markGalleryItemAvailable(item: GalleryItem): void {
if (item.unavailable) useCreateStore.getState().updateGalleryItem(item.id, { unavailable: undefined })
}
+function guessMime(filename: string): string {
+ const ext = filename.toLowerCase().split('.').pop() || ''
+ if (ext === 'mp4') return 'video/mp4'
+ if (ext === 'webm') return 'video/webm'
+ if (ext === 'gif') return 'image/gif'
+ if (ext === 'webp') return 'image/webp'
+ if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'
+ return 'image/png'
+}
+
+/**
+ * ComfyUI 0.19+ (portable, user-managed) blocks the WebView's cross-origin
+ * `<video>`/`<img>` /view load with a Sec-Fetch-Site 403, while download +
+ * history keep working because those ride the Rust proxy (no Origin header).
+ * The user sees "can't view the result" even though the render exists (#75,
+ * cinemazverev). Re-fetch the bytes THROUGH the proxy (no Origin → not blocked)
+ * and hand back a blob: URL the element can display. Local items only — cloud
+ * media has its own re-sign path (recoverGalleryUrl). Returns null when the
+ * fallback doesn't apply or the proxy fetch fails.
+ *
+ * Tradeoff: a blob loads the whole clip into memory (no native Range/seek), so
+ * this is a recovery path, not the default — the fast direct <video> stays in
+ * use whenever ComfyUI allows the origin.
+ */
+export async function proxiedComfyBlobUrl(item: GalleryItem): Promise<string | null> {
+ if (!isTauri() || item.jobId || item.remoteUrl || item.dataUrl) return null
+ try {
+ const bytes = await fetchLocalhostBytes(getImageUrl(item.filename, item.subfolder))
+ return URL.createObjectURL(new Blob([bytes], { type: guessMime(item.filename) }))
+ } catch {
+ return null
+ }
+}
+
/** Fetch a gallery item's media bytes for adoption as an op source.
*
* The naive `fetch(galleryItemUrl(item))` was the "failed to fetch" behind
diff --git a/src/components/create/experimental/useComfyMedia.ts b/src/components/create/experimental/useComfyMedia.ts
new file mode 100644
index 00000000..21fa8abe
--- /dev/null
+++ b/src/components/create/experimental/useComfyMedia.ts
@@ -0,0 +1,59 @@
+import { useState, useEffect, useRef, useCallback } from 'react'
+import { galleryItemUrl, proxiedComfyBlobUrl, recoverGalleryUrl, markGalleryItemAvailable } from './galleryUrl'
+import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
+
+/**
+ * Display src for a gallery item's `<img>`/`<video>` with a ComfyUI-0.19+
+ * cross-origin fallback (#75). The direct /view load is fast but a user-managed
+ * ComfyUI ≥0.19 answers the WebView's cross-origin request with a Sec-Fetch 403
+ * (video especially — its Range requests carry an Origin), so the element errors
+ * even though the render exists. On that error we re-fetch the bytes through the
+ * Rust proxy (no Origin header → not blocked) and swap to a blob: URL, and flag
+ * `comfyCorsBlocked` so the tab can surface the exact --enable-cors-header fix.
+ * Only if the proxy ALSO fails do we fall back to the "engine offline" state.
+ */
+export function useComfyMedia(item: GalleryItem | null) {
+ const base = item ? galleryItemUrl(item) : ''
+ const [src, setSrc] = useState(base)
+ const blobRef = useRef<string | null>(null)
+ const triedProxy = useRef(false)
+
+ // Reset when the underlying URL changes (e.g. a cloud re-sign swaps remoteUrl).
+ useEffect(() => {
+ triedProxy.current = false
+ if (blobRef.current) {
+ URL.revokeObjectURL(blobRef.current)
+ blobRef.current = null
+ }
+ setSrc(base)
+ }, [base])
+
+ // Release the blob when the element unmounts.
+ useEffect(() => () => {
+ if (blobRef.current) URL.revokeObjectURL(blobRef.current)
+ }, [])
+
+ const onError = useCallback(() => {
+ if (!item) return
+ if (triedProxy.current) {
+ recoverGalleryUrl(item)
+ return
+ }
+ triedProxy.current = true
+ void proxiedComfyBlobUrl(item).then((blob) => {
+ if (blob) {
+ blobRef.current = blob
+ setSrc(blob)
+ // Proxy rescued a /view the direct load couldn't reach → it's a
+ // cross-origin block, not a down engine. Surface the actionable hint.
+ useCreateStore.getState().setComfyCorsBlocked(true)
+ } else {
+ recoverGalleryUrl(item)
+ }
+ })
+ }, [item])
+
+ const onLoad = useCallback(() => { if (item) markGalleryItemAvailable(item) }, [item])
+
+ return { src, onError, onLoad }
+}
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index d994b961..c7435b60 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -184,6 +184,11 @@ interface CreateState {
caps: Record<'rmbg' | 'inpaint-nodes', boolean>
isGenerating: boolean
+ /** Runtime-only: the user-managed ComfyUI (0.19+) blocked the WebView's
+ * cross-origin media/WS with a Sec-Fetch 403. Set when the proxy blob
+ * fallback rescues a /view that the direct <video>/<img> couldn't load, so
+ * the Create tab can show the exact --enable-cors-header fix (#75). */
+ comfyCorsBlocked: boolean
progress: number
progressText: string
progressPhase: ProgressPhase
@@ -247,6 +252,7 @@ interface CreateState {
resetParamsToModelDefaults: () => void
setIsGenerating: (generating: boolean) => void
+ setComfyCorsBlocked: (blocked: boolean) => void
setProgress: (progress: number, text?: string) => void
setProgressPhase: (phase: ProgressPhase) => void
setCurrentPromptId: (id: string | null) => void
@@ -319,6 +325,7 @@ export const useCreateStore = create<CreateState>()(
caps: { rmbg: false, 'inpaint-nodes': false } as Record<'rmbg' | 'inpaint-nodes', boolean>,
isGenerating: false,
+ comfyCorsBlocked: false,
progress: 0,
progressText: '',
progressPhase: 'idle' as ProgressPhase,
@@ -471,6 +478,7 @@ export const useCreateStore = create<CreateState>()(
},
setIsGenerating: (generating) => set({ isGenerating: generating, ...(generating ? {} : { progressPhase: 'idle' as ProgressPhase }) }),
+ setComfyCorsBlocked: (blocked) => set({ comfyCorsBlocked: blocked }),
setProgress: (progress, text) => set({ progress, progressText: text ?? '' }),
setProgressPhase: (phase) => set({ progressPhase: phase }),
setCurrentPromptId: (id) => set({ currentPromptId: id }),
@@ -534,7 +542,7 @@ export const useCreateStore = create<CreateState>()(
// not flip the backend axis or inject a stale source/mask), backfill
// missing keys from defaults, and fix up legacy pre-version blobs
// ('i2i' mode from the v2.3.0 refactor).
- const { backend, source, mask, caps, isGenerating, ...safe } =
+ const { backend, source, mask, caps, isGenerating, comfyCorsBlocked, ...safe } =
persisted ?? {}
const merged = { ...current, ...safe }
if (merged.mode === 'i2i') {