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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(audit): desktop-100 round 2 — 27 findings from the fix-round diff review + fresh sweep
purpleae32443f32a7
diff --git a/src-tauri/src/commands/oauth.rs b/src-tauri/src/commands/oauth.rsindex af2cf10c..296229d1 100644--- a/src-tauri/src/commands/oauth.rs+++ b/src-tauri/src/commands/oauth.rs@@ -38,8 +38,9 @@ pub struct OauthPending(pub Mutex<HashMap<u16, PendingLogin>>);const CALLBACK_BODY: &str = "<!doctype html><html><body style=\"font-family:-apple-system,system-ui,sans-serif;background:#161616;color:#e5e5e5;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Signed in — you can close this tab and return to LU.</p></body></html>";const DENIED_BODY: &str = "<!doctype html><html><body style=\"font-family:-apple-system,system-ui,sans-serif;background:#161616;color:#e5e5e5;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Sign-in didn't complete — you can close this tab and try again in LU.</p></body></html>";-/// Bind the first free ladder port and arm a single-shot accept. Returns the-/// port so the frontend can build the redirect URI before opening the browser.+/// Bind the first free ladder port and arm an accept loop that serves exactly+/// one callback (strays get a 404). Returns the port so the frontend can build+/// the redirect URI before opening the browser.#[tauri::command]pub async fn oauth_start(state: tauri::State<'_, OauthPending>) -> Result<u16, String> {// Only one sign-in flow at a time: abort every stale attempt first so an@@ -58,34 +59,64 @@ pub async fn oauth_start(state: tauri::State<'_, OauthPending>) -> Result<u16, S};let (tx, rx) = oneshot::channel::<String>();let task = tauri::async_runtime::spawn(async move {- // One request only; the listener drops with this task. If oauth_wait- // times out first, tx.send just errs into the void — harmless.- let Ok((mut stream, _)) = listener.accept().await else { return };- let mut buf = vec![0u8; 8192];- let n = stream.read(&mut buf).await.unwrap_or(0);- let req = String::from_utf8_lossy(&buf[..n]);- // Request line: GET /callback?code=…&state=… HTTP/1.1- let query = req- .lines()- .next()- .and_then(|l| l.split_whitespace().nth(1))- .and_then(|path| path.split_once('?').map(|(_, q)| q.to_string()))- .unwrap_or_default();- // Provider denial arrives as error=…&error_description=… — be- // honest in the tab; the frontend gets the raw query either way.- let body = if query.split('&').any(|kv| kv.starts_with("error=")) {- DENIED_BODY- } else {- CALLBACK_BODY- };- let resp = format!(- "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",- body.len(),- body- );- let _ = stream.write_all(resp.as_bytes()).await;- let _ = stream.shutdown().await;- let _ = tx.send(query);+ // Accept until a request actually carries the callback query+ // (code=… or error=…). Strays — browser preconnects that send no+ // bytes, favicon fetches, localhost port probes — get a 404 and+ // the armed window stays open for the real redirect. oauth_wait's+ // timeout/abort bounds the loop's lifetime; the listener drops+ // with this task. If oauth_wait times out first, tx.send just+ // errs into the void — harmless.+ loop {+ let Ok((mut stream, _)) = listener.accept().await else { return };+ let mut buf = vec![0u8; 8192];+ // Short read deadline so an idle preconnect socket can't park+ // the loop while the real callback waits in the backlog.+ let n = match tokio::time::timeout(+ std::time::Duration::from_secs(2),+ stream.read(&mut buf),+ )+ .await+ {+ Ok(Ok(n)) => n,+ _ => 0,+ };+ let req = String::from_utf8_lossy(&buf[..n]);+ // Request line: GET /callback?code=…&state=… HTTP/1.1+ let query = req+ .lines()+ .next()+ .and_then(|l| l.split_whitespace().nth(1))+ .and_then(|path| path.split_once('?').map(|(_, q)| q.to_string()))+ .unwrap_or_default();+ let is_callback = query+ .split('&')+ .any(|kv| kv.starts_with("code=") || kv.starts_with("error="));+ if !is_callback {+ let _ = stream+ .write_all(+ b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",+ )+ .await;+ let _ = stream.shutdown().await;+ continue;+ }+ // Provider denial arrives as error=…&error_description=… — be+ // honest in the tab; the frontend gets the raw query either way.+ let body = if query.split('&').any(|kv| kv.starts_with("error=")) {+ DENIED_BODY+ } else {+ CALLBACK_BODY+ };+ let resp = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ body.len(),+ body+ );+ let _ = stream.write_all(resp.as_bytes()).await;+ let _ = stream.shutdown().await;+ let _ = tx.send(query);+ return;+ }});let id = NEXT_ATTEMPT.fetch_add(1, Ordering::Relaxed);statediff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 01fceb19..0dde6443 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -3797,6 +3797,13 @@ fn ensure_lan_firewall_rule(port: u16) {use std::process::Command;const CREATE_NO_WINDOW: u32 = 0x08000000;let name = format!("LU Remote {}", port);+ // One-release legacy sweep: <=2.5.6 created the rule under the old brand+ // name and no uninstall path removes it, so clear it here best-effort.+ let legacy = format!("Locally Uncensored Remote {}", port);+ let _ = Command::new("netsh")+ .args(["advfirewall", "firewall", "delete", "rule", &format!("name={}", legacy)])+ .creation_flags(CREATE_NO_WINDOW)+ .output();// Idempotent: drop any prior rule for this name, then add a fresh inbound allow.let _ = Command::new("netsh").args(["advfirewall", "firewall", "delete", "rule", &format!("name={}", name)])diff --git a/src-tauri/src/commands/secret.rs b/src-tauri/src/commands/secret.rsindex 0dd90a9c..da29e5d7 100644--- a/src-tauri/src/commands/secret.rs+++ b/src-tauri/src/commands/secret.rs@@ -1,4 +1,5 @@-//! OS keychain storage for provider API keys (security fix H5).+//! OS keychain storage for provider API keys (security fix H5) and the LU+//! Cloud session.//!//! Provider keys used to live in localStorage under reversible base64//! (providerStore.ts). On Windows + macOS we store them in the OS credential@@ -6,6 +7,15 @@//! `keyring` crate. Both backends ship with the OS, so no extra system library//! is pulled in, and the secret is bound to the user's login.//!+//! Windows caps a single credential blob at CRED_MAX_CREDENTIAL_BLOB_SIZE+//! (2560 bytes = 1280 UTF-16 units) and keyring pre-flights every write+//! against it, so the ~2–4 KB supabase session JSON can never fit in one+//! entry. Values over the per-entry budget are therefore split across+//! `account#0`, `account#1`, … with a short `__lu_chunks__:<n>` marker under+//! the base account. macOS has no such limit and keeps single-entry writes;+//! short values are stored identically on both platforms, and plain values+//! written by older builds read back unchanged.+//!//! Linux desktop and the web build have no robust uniform secret store here//! (the secret-service backend needs libdbus/gnome-keyring and breaks on//! headless/minimal setups), so those keep the obfuscated-localStorage path:@@ -17,42 +27,148 @@#[cfg(any(target_os = "windows", target_os = "macos"))]const SERVICE: &str = "com.locallyuncensored.providerkeys";+#[cfg(any(target_os = "windows", target_os = "macos"))]+mod chunked {+ use super::SERVICE;++ /// Per-entry budget in UTF-16 units. keyring's windows-native backend+ /// rejects blobs over 2560 bytes (1280 units) — stay comfortably under.+ /// macOS has no limit, so it never chunks and writes stay single-entry.+ const MAX_UNITS: usize = if cfg!(target_os = "windows") { 1000 } else { usize::MAX };++ /// Head marker for a chunked value. No provider key or session JSON ever+ /// starts with this, so plain pre-existing entries read back unchanged.+ const MARKER: &str = "__lu_chunks__:";++ fn entry(account: &str) -> Result<keyring::Entry, String> {+ keyring::Entry::new(SERVICE, account).map_err(|e| e.to_string())+ }++ fn chunk_account(account: &str, i: usize) -> String {+ format!("{account}#{i}")+ }++ fn delete_entry(account: &str) -> Result<(), String> {+ match entry(account)?.delete_credential() {+ Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),+ Err(e) => Err(e.to_string()),+ }+ }++ /// Chunk count recorded in the head entry; 0 when absent or plain.+ fn stored_chunks(account: &str) -> Result<usize, String> {+ match entry(account)?.get_password() {+ Ok(head) => Ok(parse_marker(&head).unwrap_or(0)),+ Err(keyring::Error::NoEntry) => Ok(0),+ Err(e) => Err(e.to_string()),+ }+ }++ pub(super) fn parse_marker(head: &str) -> Option<usize> {+ head.strip_prefix(MARKER)?.parse().ok()+ }++ /// Split at char boundaries so every piece stays within `max_units`+ /// UTF-16 units — the unit keyring measures the blob size in.+ pub(super) fn split_units(value: &str, max_units: usize) -> Vec<String> {+ let mut chunks = Vec::new();+ let mut cur = String::new();+ let mut units = 0usize;+ for ch in value.chars() {+ let n = ch.len_utf16();+ if units + n > max_units && !cur.is_empty() {+ chunks.push(std::mem::take(&mut cur));+ units = 0;+ }+ cur.push(ch);+ units += n;+ }+ if !cur.is_empty() {+ chunks.push(cur);+ }+ chunks+ }++ pub fn set(account: &str, value: &str) -> Result<(), String> {+ // Best-effort read of the previous layout so a shrinking value leaves+ // no orphaned chunk entries behind.+ let old = stored_chunks(account).unwrap_or(0);+ if value.encode_utf16().count() <= MAX_UNITS {+ entry(account)?.set_password(value).map_err(|e| e.to_string())?;+ for i in 0..old {+ let _ = delete_entry(&chunk_account(account, i));+ }+ return Ok(());+ }+ // Chunks first, marker last — a torn write keeps the old head (and+ // thus the old value) readable.+ let parts = split_units(value, MAX_UNITS);+ for (i, part) in parts.iter().enumerate() {+ entry(&chunk_account(account, i))?+ .set_password(part)+ .map_err(|e| e.to_string())?;+ }+ entry(account)?+ .set_password(&format!("{MARKER}{}", parts.len()))+ .map_err(|e| e.to_string())?;+ for i in parts.len()..old {+ let _ = delete_entry(&chunk_account(account, i));+ }+ Ok(())+ }++ pub fn get(account: &str) -> Result<Option<String>, String> {+ let head = match entry(account)?.get_password() {+ Ok(v) => v,+ Err(keyring::Error::NoEntry) => return Ok(None),+ Err(e) => return Err(e.to_string()),+ };+ let Some(count) = parse_marker(&head) else {+ return Ok(Some(head));+ };+ let mut value = String::new();+ for i in 0..count {+ match entry(&chunk_account(account, i))?.get_password() {+ Ok(part) => value.push_str(&part),+ // A missing chunk is a torn write — report absent, not corrupt.+ Err(keyring::Error::NoEntry) => return Ok(None),+ Err(e) => return Err(e.to_string()),+ }+ }+ Ok(Some(value))+ }++ pub fn delete(account: &str) -> Result<(), String> {+ let count = stored_chunks(account)?;+ delete_entry(account)?;+ for i in 0..count {+ delete_entry(&chunk_account(account, i))?;+ }+ Ok(())+ }+}+#[cfg(any(target_os = "windows", target_os = "macos"))]#[tauri::command]pub fn secret_set(account: String, value: String) -> Result<(), String> {- let entry = keyring::Entry::new(SERVICE, &account).map_err(|e| e.to_string())?;// An empty value means "no key" — delete rather than store an empty secret,// so a cleared key never lingers in the vault.if value.is_empty() {- return match entry.delete_credential() {- Ok(()) => Ok(()),- Err(keyring::Error::NoEntry) => Ok(()),- Err(e) => Err(e.to_string()),- };+ return chunked::delete(&account);}- entry.set_password(&value).map_err(|e| e.to_string())+ chunked::set(&account, &value)}#[cfg(any(target_os = "windows", target_os = "macos"))]#[tauri::command]pub fn secret_get(account: String) -> Result<Option<String>, String> {- let entry = keyring::Entry::new(SERVICE, &account).map_err(|e| e.to_string())?;- match entry.get_password() {- Ok(v) => Ok(Some(v)),- Err(keyring::Error::NoEntry) => Ok(None),- Err(e) => Err(e.to_string()),- }+ chunked::get(&account)}#[cfg(any(target_os = "windows", target_os = "macos"))]#[tauri::command]pub fn secret_delete(account: String) -> Result<(), String> {- let entry = keyring::Entry::new(SERVICE, &account).map_err(|e| e.to_string())?;- match entry.delete_credential() {- Ok(()) => Ok(()),- Err(keyring::Error::NoEntry) => Ok(()),- Err(e) => Err(e.to_string()),- }+ chunked::delete(&account)}// ── Non-keychain platforms (Linux desktop) ──────────────────────────────@@ -77,3 +193,31 @@ pub fn secret_get(_account: String) -> Result<Option<String>, String> {pub fn secret_delete(_account: String) -> Result<(), String> {Err("keychain unsupported on this platform".into())}++#[cfg(all(test, any(target_os = "windows", target_os = "macos")))]+mod tests {+ use super::chunked::{parse_marker, split_units};++ #[test]+ fn short_value_stays_whole() {+ assert_eq!(split_units("abc", 1000), vec!["abc".to_string()]);+ assert!(split_units("", 1000).is_empty());+ }++ #[test]+ fn split_respects_utf16_budget_and_rejoins_losslessly() {+ // Multi-unit chars near the boundary must not be torn apart.+ let value = format!("{}é🦀 tail", "x".repeat(2500));+ let parts = split_units(&value, 1000);+ assert!(parts.len() >= 3);+ assert!(parts.iter().all(|p| p.encode_utf16().count() <= 1000));+ assert_eq!(parts.concat(), value);+ }++ #[test]+ fn marker_parses_and_plain_values_pass_through() {+ assert_eq!(parse_marker("__lu_chunks__:4"), Some(4));+ assert_eq!(parse_marker("__lu_chunks__:x"), None);+ assert_eq!(parse_marker("eyJhbGciOiJIUzI1NiJ9.payload.sig"), None);+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex d7398c3b..bf4152dd 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -7,7 +7,7 @@ mod state;use state::AppState;use tauri::{- Manager,+ Emitter, Manager,menu::{Menu, MenuItem},tray::TrayIconBuilder,image::Image,@@ -336,6 +336,12 @@ fn main() {window.on_window_event(move |event| {if let tauri::WindowEvent::CloseRequested { api, .. } = event {api.prevent_close();+ // The hidden webview stays fully alive — read-aloud+ // would keep talking and a running dictation would+ // keep the mic hot behind a window the user believes+ // is closed. Tell the frontend (useVoice) to stop+ // both before the window goes to the tray.+ let _ = w.emit("app:hidden", ());let _ = w.hide();}});diff --git a/src/api/cloud/jobs.ts b/src/api/cloud/jobs.tsindex 56b81261..e11535f2 100644--- a/src/api/cloud/jobs.ts+++ b/src/api/cloud/jobs.ts@@ -21,7 +21,7 @@ export interface CloudJobParams {source_path?: stringmask_path?: stringsource_url?: string // video enhance: URL of the clip to upscale- target_resolution?: string // upscale target (image 2k|4k|8k, video 720p|1080p|2k|4k)+ target_resolution?: string // upscale target (image 2k|4k|8k, video 720p|1080p)}export interface CloudJobSubmit {diff --git a/src/api/cloud/supabase.ts b/src/api/cloud/supabase.tsindex a2b9b511..28e567dd 100644--- a/src/api/cloud/supabase.ts+++ b/src/api/cloud/supabase.ts@@ -15,10 +15,20 @@ import { SUPABASE_URL, SUPABASE_ANON_KEY } from './config'const SESSION_ACCOUNT = 'lu-cloud-session'const LOCAL_KEY = 'lu-cloud-session'-// Keychain-first async storage adapter. A single failed keychain call flips-// the adapter to localStorage for the rest of the session (Linux, web dev).+// Keychain-first async storage adapter. Only a *permanent* keychain absence+// (web build, Linux stub) latches the adapter to localStorage — a transient+// failure (keychain locked at wake, dismissed unlock prompt, Credential+// Manager hiccup) falls back for that call only and retries the keychain on+// the next operation. Latching on a transient error would strand rotated+// refresh tokens in localStorage while the keychain keeps the rotated-out+// session, which kills the sign-in on the next launch.let keychainBroken = false+function keychainMissing(err: unknown): boolean {+ const msg = err instanceof Error ? err.message : String(err)+ return msg.includes('keychain unavailable') || msg.includes('keychain unsupported')+}+// The PKCE flow stores TWO keys through this adapter: the session under the// storageKey and the code verifier under `${storageKey}-code-verifier`. Map// each supabase key to its own keychain account (suffix-preserving, so the@@ -32,9 +42,15 @@ const keychainStorage = {async getItem(key: string): Promise<string | null> {if (!keychainBroken) {try {- return await secretGet(keychainAccount(key))- } catch {- keychainBroken = true+ const fromKeychain = await secretGet(keychainAccount(key))+ // A localStorage copy only exists when a later write missed the+ // keychain (transient failure, keychain-less build) — when both+ // stores hold the key, localStorage is the newer one. A clean+ // keychain miss must also consult it, or a fallback-written session+ // is invisible on the next launch and the user is signed out.+ return localStorage.getItem(key) ?? fromKeychain+ } catch (err) {+ if (keychainMissing(err)) keychainBroken = true}}return localStorage.getItem(key)@@ -43,9 +59,12 @@ const keychainStorage = {if (!keychainBroken) {try {await secretSet(keychainAccount(key), value)+ // Drop any stale fallback copy so the two stores can't diverge and+ // no refresh token lingers in plaintext once the keychain works.+ localStorage.removeItem(key)return- } catch {- keychainBroken = true+ } catch (err) {+ if (keychainMissing(err)) keychainBroken = true}}localStorage.setItem(key, value)@@ -54,11 +73,12 @@ const keychainStorage = {if (!keychainBroken) {try {await secretDelete(keychainAccount(key))- return- } catch {- keychainBroken = true+ } catch (err) {+ if (keychainMissing(err)) keychainBroken = true}}+ // Always clear the fallback copy too — sign-out must never leave a+ // resurrectable session (or plaintext refresh token) in localStorage.localStorage.removeItem(key)},}diff --git a/src/api/rag.ts b/src/api/rag.tsindex 15631c80..c0ad6c8b 100644--- a/src/api/rag.ts+++ b/src/api/rag.ts@@ -1,7 +1,7 @@import { v4 as uuid } from "uuid"import type { DocumentMeta, TextChunk, RAGContext, VectorSearchResult } from "../types/rag"import { ollamaUrl, localFetch } from "./backend"-import { isManagedBuiltinActive, embedBaseUrl } from "./engine"+import { isManagedBuiltinActive, embedBaseUrl, bundledEmbedStatus } from "./engine"export async function extractText(file: File): Promise<string> {const ext = file.name.split(".").pop()?.toLowerCase()@@ -67,11 +67,18 @@ export async function generateEmbeddings(): Promise<number[][]> {// P5: when the app-managed built-in engine is the active backend, embed// against the bundled `llama-server --embeddings` (OpenAI `/v1/embeddings`)- // so Document-Chat/RAG works with zero Ollama. Otherwise fall back to the+ // so Document-Chat/RAG works with zero Ollama. The bundled embed server also+ // serves LM Studio/openai-compat setups that downloaded the embed GGUF in+ // onboarding — use it whenever it is running. Otherwise fall back to the// Ollama `/api/embed` path (still supported as an "Advanced" backend).if (isManagedBuiltinActive()) {return embedViaBuiltin(texts, model)}+ try {+ if ((await bundledEmbedStatus()).running) {+ return embedViaBuiltin(texts, model)+ }+ } catch { /* engine command unavailable — fall through to Ollama */ }return embedViaOllama(texts, model)}diff --git a/src/components/chat/VoiceButton.tsx b/src/components/chat/VoiceButton.tsxindex ecbe9262..e7329668 100644--- a/src/components/chat/VoiceButton.tsx+++ b/src/components/chat/VoiceButton.tsx@@ -1,7 +1,8 @@-import { useEffect } from "react"+import { useEffect, useRef } from "react"import { motion } from "framer-motion"import { Mic, MicOff, Loader2 } from "lucide-react"import { useVoice } from "../../hooks/useVoice"+import { useVoiceStore } from "../../stores/voiceStore"interface Props {onTranscript: (text: string) => void@@ -12,7 +13,12 @@ interface Props {}export function VoiceButton({ onTranscript, onInterim, onRecordingChange, disabled }: Props) {- const { isRecording, isTranscribing, sttSupported, sttError, clearSttError, startRecording, stopRecording, recheckStt } = useVoice()+ const { isRecording, isTranscribing, sttSupported, sttError, clearSttError, startRecording, stopRecording, recheckStt, maxRecordingMs } = useVoice()+ // Auto-stop timer for cloud dictation — the transcribe route rejects takes+ // past ~6.5 min (12 MiB) with a 413 that loses the WHOLE recording, so the+ // take is stopped and transcribed just under the cap instead.+ const autoStopRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const wasRecordingRef = useRef(false)useEffect(() => {// The startup probe (App.tsx) can run before the persistent Whisper server@@ -30,22 +36,52 @@ export function VoiceButton({ onTranscript, onInterim, onRecordingChange, disablreturn () => clearTimeout(t)}, [sttError, clearSttError])+ // Recording can end outside handleClick (close-to-tray teardown, unmount+ // recovery) — mirror the transition to the composer so "Recording…" never+ // sticks, and drop a pending auto-stop timer so it can't fire on a dead take.+ useEffect(() => {+ if (wasRecordingRef.current && !isRecording) {+ if (autoStopRef.current) { clearTimeout(autoStopRef.current); autoStopRef.current = null }+ onRecordingChange?.(false)+ }+ wasRecordingRef.current = isRecording+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isRecording])++ useEffect(() => () => { if (autoStopRef.current) clearTimeout(autoStopRef.current) }, [])++ const finishRecording = async () => {+ if (autoStopRef.current) { clearTimeout(autoStopRef.current); autoStopRef.current = null }+ onRecordingChange?.(false)+ const transcript = await stopRecording()+ if (transcript.trim()) {+ onTranscript(transcript.trim())+ }+ }+const handleClick = async () => {if (disabled || isTranscribing) returnif (isRecording) {- onRecordingChange?.(false)- const transcript = await stopRecording()- if (transcript.trim()) {- onTranscript(transcript.trim())- }+ await finishRecording()} else {onRecordingChange?.(true)const ok = await startRecording((interim) => onInterim?.(interim))// Roll back the composer's "Recording…" state when the mic never// started (permission denied / no input device) — otherwise Enter-to-// send stays blocked with no recovery path.- if (!ok) onRecordingChange?.(false)+ if (!ok) {+ onRecordingChange?.(false)+ return+ }+ if (maxRecordingMs) {+ autoStopRef.current = setTimeout(() => {+ autoStopRef.current = null+ if (!useVoiceStore.getState().isRecording) return+ useVoiceStore.getState().setSttError("Dictation limit reached — transcribing what was recorded so far")+ void finishRecording()+ }, maxRecordingMs)+ }}}diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsxindex 1172600b..8de214df 100644--- a/src/components/create/experimental/CreateContext.tsx+++ b/src/components/create/experimental/CreateContext.tsx@@ -1,6 +1,6 @@import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react'import { useCreate } from '../../../hooks/useCreate'-import { useCloudCreate } from '../../../hooks/useCloudCreate'+import { useCloudCreate, hasActiveCloudRun } from '../../../hooks/useCloudCreate'import { useCloudSession } from '../../../hooks/useCloudSession'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'import { useUIStore } from '../../../stores/uiStore'@@ -19,7 +19,7 @@ interface CreateExpValue {generate: () => void | Promise<void>cancel: () => void | Promise<void>/** Video super-resolution on a finished cloud render (Lightbox "Enhance"). */- enhanceVideo: (item: GalleryItem, targetResolution?: '720p' | '1080p' | '2k' | '4k') => Promise<void>+ enhanceVideo: (item: GalleryItem, targetResolution?: '720p' | '1080p') => Promise<void>/** ComfyUI /object_info sampler + scheduler names (fallback lists until loaded). */samplerList: string[]schedulerList: string[]@@ -118,7 +118,11 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {const value: CreateExpValue = {generate: backend === 'cloud' ? cloud.generate : generate,- cancel: backend === 'cloud' ? cloud.cancel : cancel,+ // Cancel routes by the backend that STARTED the run, not the current axis:+ // the header switch (or the license probe) can flip local/cloud mid-render,+ // and routing by the live value would abort a null handle while the real+ // run keeps going (a cloud job keeps billing; a local job keeps rendering).+ cancel: () => (hasActiveCloudRun() ? cloud.cancel() : cancel()),enhanceVideo: cloud.enhanceVideo,samplerList, schedulerList, loraList, vaeList,connected, modelsLoaded, modelLoadError, installCapability,diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsxindex ca40c003..3cc683f3 100644--- a/src/components/create/experimental/CreateExperimental.tsx+++ b/src/components/create/experimental/CreateExperimental.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import { AnimatePresence, motion } from 'framer-motion'import { AlertTriangle, X } from 'lucide-react'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'@@ -10,6 +10,9 @@ import { GalleryStrip } from './GalleryStrip'import { Lightbox } from './Lightbox'import { AdvancedDrawer } from './AdvancedDrawer'import { MaskEditor } from './MaskEditor'+import { INTENT_MAP } from './intents'+import { galleryItemUrl } from './galleryUrl'+import { loadImageRef } from './loadImage'/** The redesigned Create surface. Mounted by AppShell for currentView==='create'. */export function CreateExperimental() {@@ -42,6 +45,46 @@ function CreateExperimentalInner() {const displayed = (pinnedId ? gallery.find((g) => g.id === pinnedId) : undefined) ?? gallery[0]const banner = error ?? modelLoadError+ // Pull a finished result back in as the working source (ImageRef). Needed+ // because a text-to-image run leaves `source` empty — without this, "Edit+ // with mask" on a result and switching to Edit/Upscale/Eraser/Animate were+ // no-ops that demanded a download + re-upload of the app's own output.+ const adoptResult = useCallback(async (item: GalleryItem) => {+ const res = await fetch(galleryItemUrl(item))+ const blob = await res.blob()+ const file = new File([blob], item.filename || 'result.png', { type: blob.type || 'image/png' })+ return loadImageRef(file)+ }, [])++ const editResultWithMask = useCallback(async (item: GalleryItem) => {+ useCreateStore.getState().setIntent('edit')+ try {+ useCreateStore.getState().setSource(await adoptResult(item))+ setMaskOpen(true)+ } catch (err) {+ setError(`Could not load the result for editing: ${err instanceof Error ? err.message : String(err)}`)+ }+ }, [adoptResult, setError])++ // Switching to a source-needing intent while an image result is in the+ // gallery adopts the newest image as the input instead of demanding a+ // re-upload. Every source-needing intent takes an *image* input, so always+ // pull the newest image — never a video.+ const intent = useCreateStore((s) => s.intent())+ const source = useCreateStore((s) => s.source)+ useEffect(() => {+ const meta = INTENT_MAP[intent]+ if (!meta.needsSource || source) return+ const img = gallery.find((g) => g.type === 'image')+ if (!img) return+ let cancelled = false+ adoptResult(img)+ .then((ref) => { if (!cancelled) useCreateStore.getState().setSource(ref) })+ .catch(() => { /* upload slot stays — user can drop a file */ })+ return () => { cancelled = true }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [intent])+return (<div className="h-full w-full flex flex-col bg-[#141414] text-gray-200 overflow-hidden"><IntentBar />@@ -72,6 +115,7 @@ function CreateExperimentalInner() {<Stagedisplayed={displayed}onOpenMaskEditor={() => setMaskOpen(true)}+ onEditResult={(it) => { void editResultWithMask(it) }}onFullscreen={(it) => setLightbox(it)}/><GalleryStrip activeId={pinnedId} onSelect={setPinnedId} />diff --git a/src/components/create/experimental/GalleryStrip.tsx b/src/components/create/experimental/GalleryStrip.tsxindex ee5731ae..7cda479e 100644--- a/src/components/create/experimental/GalleryStrip.tsx+++ b/src/components/create/experimental/GalleryStrip.tsx@@ -1,7 +1,7 @@import { motion } from 'framer-motion'-import { Trash2, Play } from 'lucide-react'+import { Trash2, Play, MonitorOff } from 'lucide-react'import { useCreateStore } from '../../../stores/createStore'-import { galleryItemUrl, recoverGalleryUrl } from './galleryUrl'+import { galleryItemUrl, markGalleryItemAvailable, recoverGalleryUrl } from './galleryUrl'import { cn } from '../ui/cn'interface Props {@@ -38,11 +38,19 @@ export function GalleryStrip({ activeId, onSelect }: Props) {>{g.type === 'video' ? (<>- <video src={galleryItemUrl(g)} muted playsInline onError={() => recoverGalleryUrl(g)} className="w-full h-full object-cover" />+ <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={14} className="text-white/90" /></span></>) : (- <img src={galleryItemUrl(g)} alt="" onError={() => recoverGalleryUrl(g)} className="w-full h-full object-cover" />+ <img src={galleryItemUrl(g)} alt="" onError={() => recoverGalleryUrl(g)} onLoad={() => markGalleryItemAvailable(g)} className="w-full h-full object-cover" />+ )}+ {g.unavailable && (+ <span+ className="absolute inset-0 flex items-center justify-center bg-black/50 text-gray-500"+ title="Local render — the local engine isn't reachable"+ >+ <MonitorOff size={14} />+ </span>)}</button><buttondiff --git a/src/components/create/experimental/Lightbox.tsx b/src/components/create/experimental/Lightbox.tsxindex 64806cea..2c934775 100644--- a/src/components/create/experimental/Lightbox.tsx+++ b/src/components/create/experimental/Lightbox.tsx@@ -2,6 +2,7 @@ import { useEffect } from 'react'import { motion, AnimatePresence } from 'framer-motion'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 { cn } from '../ui/cn'@@ -9,7 +10,7 @@ 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 } = useCreateExp()+ const { enhanceVideo, quota } = useCreateExp()useEffect(() => {if (!item) return@@ -21,6 +22,15 @@ export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose:// Video super-resolution: only for finished CLOUD renders (jobId = the// clip lives in the user's render storage, which the enhance op requires).const canEnhance = item?.type === 'video' && !!item.jobId && backend === 'cloud' && !isGenerating+ // Gate on the run's cost like the Composer does — Enhance is a paid action+ // too, and without the gate the only feedback was a server 429 after the+ // progress bar had already started. Clip length is unknown client-side, so+ // runCredits mirrors the server's 8 s default.+ const enhanceCredits =+ canEnhance && quota != null+ ? runCredits('video', 'upscale', item.model || '', undefined, quota.costs.video)+ : null+ const enhanceOk = enhanceCredits !== null && quota != null && quota.remaining.credits >= enhanceCreditsreturn (<AnimatePresence>@@ -39,11 +49,20 @@ export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose:<buttononClick={(e) => {e.stopPropagation()+ if (!enhanceOk) returnonClose()void enhanceVideo(item)}}- title="Upscale this clip to 1080p on the cloud fleet"- className="absolute top-4 right-16 h-9 px-3 flex items-center gap-1.5 rounded-lg bg-white/10 text-gray-200 hover:bg-white/20 text-[0.7rem] font-medium"+ disabled={!enhanceOk}+ title={+ enhanceOk+ ? 'Upscale this clip to 1080p on the cloud fleet'+ : 'Not enough credits left this month for a video enhance'+ }+ className={cn(+ 'absolute top-4 right-16 h-9 px-3 flex items-center gap-1.5 rounded-lg text-[0.7rem] font-medium',+ enhanceOk ? 'bg-white/10 text-gray-200 hover:bg-white/20' : 'bg-white/5 text-gray-500 cursor-not-allowed',+ )}><Sparkles size={13} /> Enhance</button>diff --git a/src/components/create/experimental/MaskEditor.tsx b/src/components/create/experimental/MaskEditor.tsxindex 40ee51d1..0b6e72c0 100644--- a/src/components/create/experimental/MaskEditor.tsx+++ b/src/components/create/experimental/MaskEditor.tsx@@ -13,6 +13,12 @@ import { cn } from '../ui/cn'export function MaskEditor({ open, onClose }: { open: boolean; onClose: () => void }) {const source = useCreateStore((s) => s.source)+ // Opened without a source, nothing mounts below — and onClose only exists+ // inside the never-mounted Inner, so `open` would latch true and pop the+ // editor uninvited the moment a source appears later. Reset immediately.+ useEffect(() => {+ if (open && !source) onClose()+ }, [open, source, onClose])return (<AnimatePresence>{open && source && <MaskEditorInner key={source.filename} onClose={onClose} />}diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsxindex 0b62705f..0435bb8f 100644--- a/src/components/create/experimental/OutputView.tsx+++ b/src/components/create/experimental/OutputView.tsx@@ -1,9 +1,9 @@import { motion } from 'framer-motion'-import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2 } from 'lucide-react'+import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff } from 'lucide-react'import { useCreateStore, type GalleryItem, type ProgressPhase } from '../../../stores/createStore'import { downloadComfyFile, isTauri } from '../../../api/backend'import { refreshResultUrl } from '../../../api/cloud/jobs'-import { galleryItemUrl, recoverGalleryUrl } from './galleryUrl'+import { galleryItemUrl, markGalleryItemAvailable, recoverGalleryUrl } from './galleryUrl'import { cn } from '../ui/cn'function phaseIcon(phase: ProgressPhase) {@@ -78,8 +78,17 @@ function extFor(contentType: string, kind: 'image' | 'video'): string {// Save-As dialog (WebView2 blob-anchors are unreliable); failures surface via// setError instead of a silent no-op.async function downloadGalleryItem(item: GalleryItem): Promise<void> {- if (item.filename) return downloadComfyFile(item.filename, item.subfolder)+ if (item.filename && item.unavailable) {+ // The item's media already failed to load — the ComfyUI fetch would only+ // fail again (and downloadComfyFile swallows its errors). Be honest.+ useCreateStore.getState().setError('Download needs the local engine — start it and try again.')+ return+ }try {+ if (item.filename) {+ await downloadComfyFile(item.filename, item.subfolder)+ return+ }let url = item.dataUrl ?? item.remoteUrlif (!item.dataUrl && item.jobId) {url = (await refreshResultUrl(item.jobId)) ?? url@@ -131,6 +140,7 @@ export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps)autoPlaymutedonError={() => recoverGalleryUrl(item)}+ onLoadedData={() => markGalleryItemAvailable(item)}className="max-w-full max-h-[62vh] object-contain rounded-[var(--radius-panel)] border border-white/[0.06]"/>) : (@@ -138,14 +148,27 @@ export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps)src={url}alt={item.prompt}onError={() => recoverGalleryUrl(item)}+ onLoad={() => markGalleryItemAvailable(item)}className={cn('max-w-full max-h-[62vh] object-contain rounded-[var(--radius-panel)] border border-white/[0.06]', item.intent === 'removebg' && 'lu-checker')}/>)}+ {item.unavailable && (+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-[var(--radius-panel)] bg-black/60 text-gray-400 p-6 text-center">+ <MonitorOff size={20} strokeWidth={1.5} />+ <span className="t-body">This render lives on the local engine, which isn't reachable right now.</span>+ </div>+ )}<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">- {onSendToEditor && !isVideo && (+ {onSendToEditor && !isVideo && !item.unavailable && (<IconBtn title="Edit with mask" onClick={onSendToEditor}><Wand2 size={14} /></IconBtn>)}- <IconBtn title="Download" onClick={download}><Download size={14} /></IconBtn>+ <IconBtn+ title={item.unavailable ? 'Download needs the local engine' : 'Download'}+ disabled={item.unavailable}+ onClick={download}+ >+ <Download size={14} />+ </IconBtn><IconBtn title="Fullscreen" onClick={onFullscreen}><Maximize2 size={14} /></IconBtn></div></div>@@ -160,9 +183,17 @@ export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps))}-function IconBtn({ children, title, onClick }: { children: React.ReactNode; title: string; onClick: () => void }) {+function IconBtn({ children, title, onClick, disabled }: { children: React.ReactNode; title: string; onClick: () => void; disabled?: boolean }) {return (- <button onClick={onClick} title={title} className="w-7 h-7 flex items-center justify-center rounded-lg bg-black/50 backdrop-blur text-gray-200 hover:text-white hover:bg-black/70 transition-colors">+ <button+ onClick={onClick}+ title={title}+ disabled={disabled}+ className={cn(+ 'w-7 h-7 flex items-center justify-center rounded-lg bg-black/50 backdrop-blur transition-colors',+ disabled ? 'text-gray-600 cursor-not-allowed' : 'text-gray-200 hover:text-white hover:bg-black/70',+ )}+ >{children}</button>)diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxindex 717cfa11..6329f2f3 100644--- a/src/components/create/experimental/Stage.tsx+++ b/src/components/create/experimental/Stage.tsx@@ -13,10 +13,13 @@ import { loadImageRef } from './loadImage'interface Props {displayed?: GalleryItemonOpenMaskEditor: () => void+ /** Adopt a finished result as the edit source, THEN open the mask editor —+ * a t2i run leaves `source` empty, and the editor always reads `source`. */+ onEditResult: (item: GalleryItem) => voidonFullscreen: (item: GalleryItem) => void}-export function Stage({ displayed, onOpenMaskEditor, onFullscreen }: Props) {+export function Stage({ displayed, onOpenMaskEditor, onEditResult, onFullscreen }: Props) {const intent = useCreateStore((s) => s.intent())const meta = INTENT_MAP[intent]const isGenerating = useCreateStore((s) => s.isGenerating)@@ -50,7 +53,7 @@ export function Stage({ displayed, onOpenMaskEditor, onFullscreen }: Props) {<ResultViewitem={displayed}onFullscreen={() => onFullscreen(displayed)}- onSendToEditor={!meta.isVideo ? onOpenMaskEditor : undefined}+ onSendToEditor={displayed.type === 'image' ? () => onEditResult(displayed) : undefined}/>)} else {@@ -111,8 +114,10 @@ function InputSlot() {const handleFile = async (file: File) => {// Drag&drop bypasses the input's accept filter — validate here so a- // stray .txt/.pdf gets a message instead of a silent no-op.- if (!/^image\/(png|jpe?g|webp)$/i.test(file.type)) {+ // stray .txt/.pdf gets a message instead of a silent no-op. Exotic image+ // containers (HEIC/AVIF/GIF) pass: loadImageRef re-encodes them to PNG,+ // and throws honestly when the WebView can't decode them.+ if (!file.type.startsWith('image/')) {setError('That file type is not supported — use PNG, JPG or WebP.')return}@@ -198,11 +203,27 @@ function SourcePreview({ onOpenMaskEditor }: { onOpenMaskEditor: () => void }) {}function ChangeImageButton({ onChange }: { onChange: (r: Awaited<ReturnType<typeof loadImageRef>>) => void }) {+ const setError = useCreateStore((s) => s.setError)const inputRef = useRef<HTMLInputElement>(null)+ // Same validation + error surface as the drop zone — this picker used to+ // hand the raw file straight to loadImageRef, so a .heic/.avif previewed+ // fine and then 415ed at submit (and a decode failure rejected unhandled).+ const handleFile = async (file: File) => {+ if (!file.type.startsWith('image/')) {+ setError('That file type is not supported — use PNG, JPG or WebP.')+ return+ }+ setError(null)+ try {+ onChange(await loadImageRef(file))+ } catch (err) {+ setError(`Could not load the image: ${err instanceof Error ? err.message : String(err)}`)+ }+ }return (<><Button variant="ghost" icon={ImagePlus} onClick={() => inputRef.current?.click()}>Change image</Button>- <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={async (e) => { const f = e.target.files?.[0]; if (f) onChange(await loadImageRef(f)) }} />+ <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) void handleFile(f) }} /></>)}diff --git a/src/components/create/experimental/galleryUrl.ts b/src/components/create/experimental/galleryUrl.tsindex 2a66b5b6..038a1766 100644--- a/src/components/create/experimental/galleryUrl.ts+++ b/src/components/create/experimental/galleryUrl.ts@@ -10,16 +10,40 @@ export function galleryItemUrl(item: GalleryItem): string {}// Cloud signed URLs expire ~1 h after the last read, so a persisted item's-// media errors on the next session. Re-sign once per item per session (the-// guard stops an error → refresh → error loop when the job's file is gone-// for good) and patch the gallery entry so every surface re-renders with-// the fresh URL.-const recovered = new Set<string>()+// media errors on the next session. Re-sign lazily and patch the gallery+// entry so every surface re-renders with the fresh URL. The per-item guard+// stops an error → refresh → error loop when the job's file is gone for good+// (a successful re-sign yields a NEW URL each time, so onError would re-fire+// every cycle): after a success the item stays blocked for RESIGN_TTL_MS —+// long sessions can re-sign a second expiry — while a FAILED refresh (offline+// launch, transient 5xx) releases the guard so the next remount retries+// instead of leaving the media broken for the whole session.+const RESIGN_TTL_MS = 50 * 60_000+/** item.id → last successful re-sign epoch ms; 0 = refresh in flight. */+const recovered = new Map<string, number>()export function recoverGalleryUrl(item: GalleryItem): void {- if (!item.jobId || recovered.has(item.id)) return- recovered.add(item.id)+ if (!item.jobId) {+ // Local ComfyUI item whose /view fetch failed (engine not running /+ // output pruned) — nothing to re-sign. Flag it so the tiles can render+ // an honest "engine offline" state instead of a silently dead <img>.+ if (!item.unavailable) useCreateStore.getState().updateGalleryItem(item.id, { unavailable: true })+ return+ }+ const last = recovered.get(item.id)+ if (last !== undefined && (last === 0 || Date.now() - last < RESIGN_TTL_MS)) return+ recovered.set(item.id, 0)void refreshResultUrl(item.jobId).then((url) => {- if (url) useCreateStore.getState().updateGalleryItem(item.id, { remoteUrl: url })+ if (url) {+ recovered.set(item.id, Date.now())+ useCreateStore.getState().updateGalleryItem(item.id, { remoteUrl: url, unavailable: undefined })+ } else {+ recovered.delete(item.id)+ }})}++/** Clear a tile's offline flag once its media actually loads (onLoad). */+export function markGalleryItemAvailable(item: GalleryItem): void {+ if (item.unavailable) useCreateStore.getState().updateGalleryItem(item.id, { unavailable: undefined })+}diff --git a/src/components/create/experimental/loadImage.ts b/src/components/create/experimental/loadImage.tsindex 02e64733..c6a9ead3 100644--- a/src/components/create/experimental/loadImage.ts+++ b/src/components/create/experimental/loadImage.ts@@ -20,16 +20,51 @@ function imageSize(url: string): Promise<{ width: number; height: number }> {})}+/** Containers the cloud upload accepts (uselu /api/jobs/upload sniffs magic+ * bytes and 415s everything else). */+const UPLOAD_SAFE = /^image\/(png|jpe?g|webp)$/i++function decodeImage(url: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const img = new Image()+ img.onload = () => resolve(img)+ img.onerror = () => reject(new Error('the image could not be decoded — use PNG, JPG or WebP'))+ img.src = url+ })+}+/** File → ImageRef. Always reads a data URL for preview (and for the cloud* path, which re-uploads from it at submit time). On the local backend the* file is additionally uploaded to ComfyUI (/upload/image) to obtain the* input/ filename the local workflow uses — on cloud there may be no- * ComfyUI at all, so that step is skipped and filename stays ''. */+ * ComfyUI at all, so that step is skipped and filename stays ''.+ *+ * The backends only accept PNG/JPEG/WebP, but the WebView decodes more+ * (HEIC on macOS — the iPhone default — AVIF, GIF): anything else the+ * engine can decode is re-encoded to PNG via canvas, so the preview, the+ * mask resolution and the upload all agree. Undecodable files throw an+ * honest error instead of a server 415 after the prep work is done. */export async function loadImageRef(file: File): Promise<ImageRef> {- const url = await readDataUrl(file)- const { width, height } = await imageSize(url)+ let upload: File = file+ let url = await readDataUrl(file)+ let width: number+ let height: number+ if (UPLOAD_SAFE.test(file.type)) {+ ;({ width, height } = await imageSize(url))+ } else {+ const img = await decodeImage(url)+ width = img.naturalWidth || 1024+ height = img.naturalHeight || 1024+ const canvas = document.createElement('canvas')+ canvas.width = width+ canvas.height = height+ canvas.getContext('2d')!.drawImage(img, 0, 0)+ url = canvas.toDataURL('image/png')+ const blob = await (await fetch(url)).blob()+ upload = new File([blob], file.name.replace(/\.[^.]+$/, '') + '.png', { type: 'image/png' })+ }const backend = useCreateStore.getState().backend- const filename = backend === 'cloud' ? '' : await uploadImage(file)+ const filename = backend === 'cloud' ? '' : await uploadImage(upload)return { filename, url, width, height }}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex d7aa099d..3538d5d6 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -207,8 +207,18 @@ export function AppShell() {let restored = 0for (const [key, value] of Object.entries(parsed)) {if (STORE_KEYS_SET.has(key) && typeof value === 'string' && value) {- localStorage.setItem(key, value)- restored+++ // IDB-backed keys go back to IndexedDB — the chat blob can+ // exceed the ~5 MB localStorage quota (that's why those+ // stores moved to IDB), and hydration reads them from there.+ // Per-key try/catch: one failing key must not abort the rest.+ try {+ if (IDB_STORE_KEYS.has(key)) {+ await Promise.resolve(idbStorage.setItem(key, value))+ } else {+ localStorage.setItem(key, value)+ }+ restored+++ } catch { /* skip this key, keep restoring the rest */ }}}if (restored > 0) {@@ -291,6 +301,11 @@ export function AppShell() {if (disposed) returnlet backupInflight = false+ // In-memory mirror of the IDB-backed values, refreshed by every doBackup+ // run. beforeunload can't await IndexedDB (the page is tearing down), so+ // the sync flush below reads from this cache instead — at most one+ // debounce-cycle stale, same freshness the old sync handler had.+ const idbCache: Record<string, string> = {}const doBackup = async () => {// Inflight guard: the 1 s debounce and the 5 s interval can overlap// now that the snapshot awaits IndexedDB reads.@@ -302,7 +317,10 @@ export function AppShell() {const val = IDB_STORE_KEYS.has(key)? await Promise.resolve(idbStorage.getItem(key)): localStorage.getItem(key)- if (val) snapshot[key] = val+ if (val) {+ snapshot[key] = val+ if (IDB_STORE_KEYS.has(key)) idbCache[key] = val+ }}// Always fire — we want backup even if snapshot is mostly empty, and the// sentinel tells the restore-flow this is a valid backup.@@ -368,11 +386,30 @@ export function AppShell() {}const unsubChat = useChatStore.subscribe(scheduleBackup)+ // Synchronous "last write" flush for beforeunload: doBackup awaits+ // IndexedDB reads, and an await during page teardown means the trailing+ // backup_stores invoke may never fire. Build the snapshot synchronously+ // from localStorage + the idbCache mirror instead — no await before the+ // invoke, restoring the pre-async guarantee.+ const flushSyncBackup = () => {+ try {+ const snapshot: Record<string, string> = { __ts: new Date().toISOString() }+ for (const key of STORE_KEYS) {+ const val = IDB_STORE_KEYS.has(key)+ ? (idbCache[key] ?? null)+ : localStorage.getItem(key)+ if (val) snapshot[key] = val+ }+ localStorage.setItem('lu-restore-complete', '1')+ backendCall('backup_stores', { data: JSON.stringify(snapshot) }).catch(() => {})+ } catch { /* best-effort */ }+ }+const onBeforeUnload = () => {- // Best-effort fire-and-forget — the page is going away, we can't- // await. The 5 s / 30 s intervals cover the common case; this is the- // "last write" insurance for changes since the previous interval.- void doBackup()+ // The 5 s / 30 s intervals cover the common case; this is the "last+ // write" insurance for changes since the previous interval. Must stay+ // synchronous — see flushSyncBackup.+ flushSyncBackup()void doRagBackup()}window.addEventListener('beforeunload', onBeforeUnload)diff --git a/src/components/layout/__tests__/AppShell-backup-triad.test.ts b/src/components/layout/__tests__/AppShell-backup-triad.test.tsindex 48175f66..2dc47ad8 100644--- a/src/components/layout/__tests__/AppShell-backup-triad.test.ts+++ b/src/components/layout/__tests__/AppShell-backup-triad.test.ts@@ -41,6 +41,22 @@ describe('AppShell backup triad (Bug #7)', () => {expect(src).toContain('onBeforeUnload')})+ it('beforeunload flush is synchronous — never awaits IndexedDB during teardown', () => {+ // doBackup awaits idbStorage reads; an await inside beforeunload means the+ // trailing backup_stores invoke may never fire. The handler must call the+ // sync snapshot (localStorage + idbCache mirror) instead of doBackup.+ expect(src).toContain('flushSyncBackup()')+ expect(src).toMatch(/const onBeforeUnload = \(\) => \{[^}]*flushSyncBackup\(\)/s)+ expect(src).not.toMatch(/const onBeforeUnload = \(\) => \{[^}]*void doBackup\(\)/s)+ })++ it('restore writes IDB-backed keys through idbStorage, not localStorage (quota)', () => {+ // The chat blob can exceed the ~5 MB localStorage quota — a raw+ // localStorage.setItem would throw QuotaExceededError and abort the whole+ // restore on exactly the post-NSIS boot it exists to protect.+ expect(src).toContain('idbStorage.setItem(key, value)')+ })+it('cleans up all three hooks in the useEffect return', () => {// Regression guard: the return() block must clear interval, debounce,// subscription, and event listener.diff --git a/src/components/onboarding/Onboarding.tsx b/src/components/onboarding/Onboarding.tsxindex 26643e1c..01f0b8a7 100644--- a/src/components/onboarding/Onboarding.tsx+++ b/src/components/onboarding/Onboarding.tsx@@ -15,7 +15,7 @@ import { backendCall } from '../../api/backend'import { getSystemVRAM } from '../../api/comfyui'import { pullModelTauri, checkConnection as checkOllama } from '../../api/ollama'import { hfUrlToOllamaRef, hfUrlToLmStudioSubdir } from '../../lib/hf-to-provider'-import { startBundledEngine, startBundledEmbed, isManagedBuiltinActive } from '../../api/engine'+import { startBundledEngine, startBundledEmbed } from '../../api/engine'import { BUILTIN_BACKEND_ID, classifyOnboardingBackend, resolveOnboardingBackend } from '../../lib/onboarding-backend'// Bug (h): the dedicated 'theme' onboarding step was removed because users@@ -459,10 +459,19 @@ export function Onboarding() {const [embeddingsProgress, setEmbeddingsProgress] = useState<{ completed: number; total: number }>({ completed: 0, total: 0 })const [embeddingsAlreadyHave, setEmbeddingsAlreadyHave] = useState<boolean | null>(null)+ // Embeddings route on the CHOSEN backend, not isManagedBuiltinActive():+ // rag.ts only ever queries the bundled embeddings server or Ollama — never+ // an LM-Studio-style /v1/embeddings — so openai-compat backends must take+ // the bundled path too. Branching on isManagedBuiltinActive() dead-ended+ // LM Studio users on a machine that has no Ollama by explicit choice.+ const embedsViaBundled =+ classifyOnboardingBackend(resolveOnboardingBackend(selectedBackend, ollamaReady, detectedBackends)) !== 'ollama'+// Probe whether an embedding model is already present. For the built-in- // engine (P5) we scan the app models dir via list_bundled_models; otherwise- // Ollama lists pulled models. Either way we match anything with- // `embed`/`bge`/`nomic` in the name (same heuristic used elsewhere).+ // engine (P5) and openai-compat backends we scan the app models dir via+ // list_bundled_models; only Ollama lists its pulled models. Either way we+ // match anything with `embed`/`bge`/`nomic` in the name (same heuristic+ // used elsewhere).useEffect(() => {if (step !== 'embeddings') returnlet cancelled = false@@ -470,7 +479,7 @@ export function Onboarding() {const lower = (name || '').toLowerCase()return lower.includes('embed') || lower.includes('bge-') || lower.includes('nomic')}- const probe = isManagedBuiltinActive()+ const probe = embedsViaBundled? import('../../api/engine').then(({ listBundledModels }) =>listBundledModels().then(models => models.some(m => isEmbed(m.name)))): import('../../api/ollama').then(({ listModels }) =>@@ -479,7 +488,7 @@ export function Onboarding() {.then(hasEmbedding => { if (!cancelled) setEmbeddingsAlreadyHave(hasEmbedding) }).catch(() => { if (!cancelled) setEmbeddingsAlreadyHave(false) })return () => { cancelled = true }- }, [step])+ }, [step, embedsViaBundled])const handlePullEmbeddings = async () => {if (!isTauri) {@@ -490,10 +499,12 @@ export function Onboarding() {setEmbeddingsError(null)setEmbeddingsProgress({ completed: 0, total: 0 })- // P5: built-in engine path — download the embedding GGUF flat into the app+ // P5: bundled-engine path — download the embedding GGUF flat into the app// models dir and boot the embeddings server on it. No Ollama involved, so// Document-Chat/RAG works on a fresh install with zero external provider.- if (isManagedBuiltinActive()) {+ // Taken for the built-in engine AND openai-compat backends (LM Studio+ // etc.) — see embedsViaBundled above.+ if (embedsViaBundled) {try {const destDir = await detectProviderModelPath(BUILTIN_BACKEND_ID)if (!destDir) throw new Error('Could not resolve the built-in models directory.')@@ -1698,7 +1709,7 @@ export function Onboarding() {Standard embedding model from Nomic AI. Used purely on-device to chunk and retrieve your documents — never sent anywhere.</p><p className={`text-[0.55rem] mt-0.5 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>- {isManagedBuiltinActive() ? '84 MB · bundled engine, runs on any CPU' : '274 MB · runs on any CPU'}+ {embedsViaBundled ? '84 MB · bundled engine, runs on any CPU' : '274 MB · runs on any CPU'}</p></div></div>@@ -1729,7 +1740,7 @@ export function Onboarding() {<div className="flex items-center gap-2 pt-1">{embeddingsAlreadyHave !== true && !embeddingsPulled && !embeddingsPulling && (<button onClick={handlePullEmbeddings} className={primaryBtn} style={{ flex: 1 }}>- <Download size={14} /> Install nomic-embed-text ({isManagedBuiltinActive() ? '84 MB' : '274 MB'})+ <Download size={14} /> Install nomic-embed-text ({embedsViaBundled ? '84 MB' : '274 MB'})</button>)}<buttondiff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex c29beeb0..8b4bf88f 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1049,6 +1049,8 @@ export function SettingsPage() {<ChatBackupSettings /></Section>+ {/* ComfyUI-only knobs — cloud renders use server-side limits. */}+ {settings.appMode !== 'cloud' && (<Section title="Image / Video Generation Timeouts"><div className="text-[0.6rem] text-gray-500 dark:text-gray-500 leading-relaxed pb-1.5">Maximum minutes a ComfyUI generation can run before LU aborts it. Bump these up if you run on iGPU or CPU only — a 1024px image on integrated graphics can take 30+ min.@@ -1078,24 +1080,46 @@ export function SettingsPage() {/></div></Section>+ )}<Section title="Privacy">- <div className="space-y-2 py-1 text-[0.65rem] text-gray-500 dark:text-gray-400 leading-relaxed">- <div className="flex items-start gap-2">- <Lock size={12} className="mt-0.5 shrink-0 text-emerald-500" />- <div>- <p className="text-gray-700 dark:text-gray-300 font-medium mb-0.5">100% local by default.</p>- <p>Chat, agent runs, image & video generation all execute on your machine. No telemetry, no analytics, no model pings home. The only network calls LU makes unless you explicitly opt in are: update checks against GitHub Releases, and cloud provider APIs (OpenAI, Anthropic, etc.) that you configure yourself with your own API keys.</p>+ {settings.appMode === 'cloud' ? (+ /* Cloud mode: the 100%-local pledge doesn't hold — say so+ honestly, mirroring the Speech section's cloud copy. */+ <div className="space-y-2 py-1 text-[0.65rem] text-gray-500 dark:text-gray-400 leading-relaxed">+ <div className="flex items-start gap-2">+ <Lock size={12} className="mt-0.5 shrink-0 text-sky-500" />+ <div>+ <p className="text-gray-700 dark:text-gray-300 font-medium mb-0.5">Cloud mode is active.</p>+ <p>Chat, Create renders and voice run on lu-labs.ai against your LU account and are metered against your credits; generated media and job records are stored with your account. Switch to Local in the header to run everything on your machine — the 100%-local pledge below then applies.</p>+ </div>+ </div>+ <div className="flex items-start gap-2 pt-1.5">+ <Shield size={12} className="mt-0.5 shrink-0 text-emerald-500" />+ <div>+ <p className="text-gray-700 dark:text-gray-300 font-medium mb-0.5">Local mode: 100% local.</p>+ <p>In local mode chat, agent runs, and image & video generation all execute on your machine — no telemetry, no analytics, no model pings home. Your local data lives in <code className="px-1 py-0.5 rounded bg-black/5 dark:bg-white/5 font-mono text-[0.6rem]">%APPDATA%/Locally Uncensored</code> on Windows (or the equivalent on Linux/macOS).</p>+ </div></div></div>- <div className="flex items-start gap-2 pt-1.5">- <Shield size={12} className="mt-0.5 shrink-0 text-emerald-500" />- <div>- <p className="text-gray-700 dark:text-gray-300 font-medium mb-0.5">You own your data.</p>- <p>Conversations, memories, and generated media live in <code className="px-1 py-0.5 rounded bg-black/5 dark:bg-white/5 font-mono text-[0.6rem]">%APPDATA%/Locally Uncensored</code> on Windows (or the equivalent on Linux/macOS). Back up the folder, move it between machines, or delete it — LU writes nothing else.</p>+ ) : (+ <div className="space-y-2 py-1 text-[0.65rem] text-gray-500 dark:text-gray-400 leading-relaxed">+ <div className="flex items-start gap-2">+ <Lock size={12} className="mt-0.5 shrink-0 text-emerald-500" />+ <div>+ <p className="text-gray-700 dark:text-gray-300 font-medium mb-0.5">100% local by default.</p>+ <p>Chat, agent runs, image & video generation all execute on your machine. No telemetry, no analytics, no model pings home. The only network calls LU makes unless you explicitly opt in are: update checks against GitHub Releases, and cloud provider APIs (OpenAI, Anthropic, etc.) that you configure yourself with your own API keys.</p>+ </div>+ </div>+ <div className="flex items-start gap-2 pt-1.5">+ <Shield size={12} className="mt-0.5 shrink-0 text-emerald-500" />+ <div>+ <p className="text-gray-700 dark:text-gray-300 font-medium mb-0.5">You own your data.</p>+ <p>Conversations, memories, and generated media live in <code className="px-1 py-0.5 rounded bg-black/5 dark:bg-white/5 font-mono text-[0.6rem]">%APPDATA%/Locally Uncensored</code> on Windows (or the equivalent on Linux/macOS). Back up the folder, move it between machines, or delete it — LU writes nothing else.</p>+ </div></div></div>- </div>+ )}</Section><Section title="Onboarding">@@ -1137,6 +1161,11 @@ export function SettingsPage() {</Section><Section title="ComfyUI (Image & Video)">+ {settings.appMode === 'cloud' && (+ <p className="text-[0.55rem] text-gray-500 leading-snug pb-1">+ Local mode only — cloud renders run on lu-labs.ai and never use ComfyUI.+ </p>+ )}<ComfyUISettings /></Section></>)}diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 333a1a34..d2b05c3f 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -311,7 +311,7 @@ export function useChat() {try {yield* provider.chatStream(modelId, messages, chatOpts)} catch (err: any) {- if (useThinking !== undefined && (err?.message?.includes('does not support thinking') || err?.statusCode === 400 || err?.statusCode === 422)) {+ if (useThinking !== undefined && (err?.message?.includes('does not support thinking') || err?.status === 400 || err?.status === 422)) {yield* provider.chatStream(modelId, messages, { ...chatOpts, thinking: undefined })} else {throw errdiff --git a/src/hooks/useCloudAuth.ts b/src/hooks/useCloudAuth.tsindex c8364646..6b884084 100644--- a/src/hooks/useCloudAuth.ts+++ b/src/hooks/useCloudAuth.ts@@ -15,11 +15,35 @@ import { useSettingsStore } from '../stores/settingsStore'import type { CloudQuota } from '../lib/render/cloud-jobs'const REFRESH_MS = 5 * 60_000+const PROBE_TIMEOUT_MS = 15_000++// Probe generation guard: probeAccount runs concurrently (boot, interval tick,+// login/signup/refresh) with no other coordination, and its fetches carry the+// access token captured at request time. A probe that hangs on a dead+// connection and resolves after a logout/account-switch must not write its+// stale result over the newer state — every probe start (and logout) bumps the+// generation, and a probe only touches the store while it is still the newest.+let probeGen = 0++// getMe/getQuota take no AbortSignal, so bound the wait here — the abandoned+// response, if it ever arrives, is discarded by the generation guard.+function withTimeout<T>(promise: Promise<T>): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('cloud probe timed out')), PROBE_TIMEOUT_MS)+ promise.then(+ (value) => { clearTimeout(timer); resolve(value) },+ (err) => { clearTimeout(timer); reject(err) },+ )+ })+}async function probeAccount(): Promise<void> {+ const gen = ++probeGen+ const stale = () => gen !== probeGenconst store = useCloudAuthStore.getState()try {- const me = await getMe()+ const me = await withTimeout(getMe())+ if (stale()) returnif (!me.user) {store.setSignedOut()syncChatProvider()@@ -35,17 +59,19 @@ async function probeAccount(): Promise<void> {// Gated accounts would just 403 here — skip the round-trip. A transient// quota-fetch failure keeps the last-known quota instead of collapsing// the whole cloud axis; only an auth/gate rejection clears it.- quota = await getQuota().catch((err) =>+ quota = await withTimeout(getQuota()).catch((err) =>err instanceof CloudJobError && (err.status === 401 || err.status === 403)? null: useCloudAuthStore.getState().quota,)+ if (stale()) returnvoid refreshCatalog()}store.setSignedIn({ id: me.user.id, email: me.user.email }, { licenseActive, tier, access, quota })syncChatProvider()syncAppMode()} catch (err) {+ if (stale()) return// Only a definitive auth rejection (401/403) signs out. Network errors,// 5xx and timeouts are transient: keep the session and let the next// interval tick retry. The boot probe still resolves to signed-out so the@@ -113,6 +139,9 @@ export function useCloudAuth() {}, [])const logout = useCallback(async (): Promise<void> => {+ // Invalidate any in-flight probe — its request carried the old (still+ // unexpired) access token and would resurrect the signed-in state.+ probeGen++await supabaseCloud().auth.signOut().catch(() => {})useCloudAuthStore.getState().setSignedOut()syncChatProvider()diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsindex bd693176..512d8025 100644--- a/src/hooks/useCloudCreate.ts+++ b/src/hooks/useCloudCreate.ts@@ -43,6 +43,12 @@ async function dataUrlToBlob(dataUrl: string): Promise<Blob> {let activeJobId: string | null = nulllet activeAbort: AbortController | null = null+/** True while a cloud run (generate or enhance) is in flight. CreateContext+ * routes Cancel by the backend that STARTED the run, not the current axis —+ * the header switch (or the 5-min license probe) can flip local/cloud+ * mid-render, and a mis-routed cancel strands a billing cloud job. */+export const hasActiveCloudRun = (): boolean => activeAbort !== null+export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {const { onQuotaChange } = opts@@ -111,6 +117,14 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {if (op === 'edit') {params.denoise = s.denoiseparams.grow_mask_by = s.growMaskBy+ // The mask is exported at the SOURCE image's resolution, so the output+ // must match it too — otherwise the painted region no longer aligns.+ // The generation sliders (s.width/height) are unrelated to a dropped+ // source, so drive width/height from the source when we have it.+ if (s.source?.width && s.source?.height) {+ params.width = s.source.width+ params.height = s.source.height+ }}if (op === 'upscale') {params.target_resolution = s.targetResolution@@ -139,6 +153,14 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {s.setProgress(10, 'Submitting to the render queue…')const { id } = await submitCloudJob({ kind, model, prompt: s.prompt, params })+ // A Cancel during the submit round-trip saw activeJobId still null, so+ // nothing was cancelled server-side. Now that the id exists, cancel the+ // just-queued job so its claimed credits refund instead of orphaning a+ // render we're no longer watching.+ if (ac.signal.aborted) {+ cancelJob(id).then(() => onQuotaChange?.()).catch(() => {})+ return+ }activeJobId = idonQuotaChange?.()if (s.prompt.trim()) s.addToPromptHistory(s.prompt.trim())@@ -236,7 +258,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// against the user's own storage clip, polls, and lands the enhanced clip// as a new gallery item. Runs through the same isGenerating choreography.const enhanceVideo = useCallback(- async (item: GalleryItem, targetResolution: '720p' | '1080p' | '2k' | '4k' = '1080p') => {+ async (item: GalleryItem, targetResolution: '720p' | '1080p' = '1080p') => {const s = useCreateStore.getState()if (s.isGenerating || !item.jobId) returns.setError(null)@@ -261,6 +283,12 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {prompt: '',params: { op: 'upscale', source_url: sourceJob.result_url, target_resolution: targetResolution },})+ // Same submit-window race as generate(): cancel the just-queued job+ // if the user aborted while the POST was in flight.+ if (ac.signal.aborted) {+ cancelJob(id).then(() => onQuotaChange?.()).catch(() => {})+ return+ }activeJobId = idonQuotaChange?.()diff --git a/src/hooks/useModels.ts b/src/hooks/useModels.tsindex 71821f9a..a31058f6 100644--- a/src/hooks/useModels.ts+++ b/src/hooks/useModels.ts@@ -49,6 +49,13 @@ async function resumeBuiltinEngines(bundled: BundledModel[]) {await activateBuiltinModel(activeModel)}} catch { /* engine unavailable — non-critical */ }+ await resumeEmbedServer(bundled)+}++// The bundled embeddings server serves RAG/memory for ANY local backend that+// downloaded the embed GGUF in onboarding (LM Studio/openai-compat too), so+// its resume must not depend on the chat engine being the managed builtin.+async function resumeEmbedServer(bundled: BundledModel[]) {try {const embed = bundled.find((m) => isEmbeddingModel(m.name))if (embed) {@@ -153,6 +160,13 @@ export function useModels() {void resumeBuiltinEngines(bundledRaw)}} catch { /* engine command unavailable — non-critical */ }+ } else if (!builtinResumeAttempted) {+ // Non-builtin chat backend (LM Studio etc.): still resume the bundled+ // embeddings server when its GGUF exists, so RAG survives a relaunch.+ builtinResumeAttempted = true+ try {+ void resumeEmbedServer(await listBundledModels())+ } catch { /* engine command unavailable — non-critical */ }}const ollamaEnabled = useProviderStore.getState().providers.ollama.enabledconst hasOllamaModels = allModels.some(m => m.provider === 'ollama')diff --git a/src/hooks/useVoice.ts b/src/hooks/useVoice.tsindex acb5b861..c56a4554 100644--- a/src/hooks/useVoice.ts+++ b/src/hooks/useVoice.ts@@ -22,6 +22,7 @@ import {type AudioRecorder,} from "../api/voice";import { CloudJobError } from "../api/cloud/client";+import { isTauri } from "../api/backend";import { log } from "../lib/logger";// Honest, actionable copy for dictation failures. The cloud route's own error@@ -37,6 +38,34 @@ function sttErrorMessage(err: unknown): string {return "Transcription failed — check the microphone and try again";}+// Speak-generation counter + abort plumbing, module-scoped (NOT per hook+// instance) because playback is a process-wide singleton (one HTMLAudioElement+// in api/voice): every SpeakerButton mounts its own useVoice, and a Stop click+// from ANY bubble must invalidate the running cloud chunk loop. A per-instance+// counter let another button's Stop merely settle the current clip's await,+// after which the loop kept synthesizing — and billing — the next chunks.+// Same singleton pattern as useCloudCreate's activeJobId/activeAbort.+let speakGen = 0;+let speakAbort: AbortController | null = null;++function stopSpeechPlayback(): void {+ // Invalidate the running speak generation (drops queued cloud chunks and any+ // synthesis that resolves late) and abort the in-flight cloud fetch — the+ // server cancels un-metered on a client abort.+ speakGen++;+ speakAbort?.abort();+ speakAbort = null;+ stopNeuralAudio();+ stopSpeakingApi();+ useVoiceStore.getState().setSpeaking(false);+}++// Cloud transcribe caps the request body at 12 MiB — about 6.5 minutes of the+// 16 kHz/16-bit mono WAV the recorder produces (32,000 B/s). Auto-stop just+// under the cap (~340 s ≈ 10.9 MB) so a long take is transcribed instead of+// being rejected 413 wholesale.+const CLOUD_DICTATION_LIMIT_MS = 340_000;+export function useVoice() {const store = useVoiceStore();const recorderRef = useRef<AudioRecorder | null>(null);@@ -45,11 +74,6 @@ export function useVoice() {// (CPU Whisper) transcriptions never pile up.const streamTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);const interimBusyRef = useRef(false);- // Speak-generation counter + abort plumbing: a Stop click bumps the counter- // and aborts the in-flight cloud synthesis, so audio that resolves late is- // dropped instead of playing over the idle button state.- const speakGenRef = useRef(0);- const speakAbortRef = useRef<AbortController | null>(null);// Unmount teardown (e.g. view switch mid-dictation): kill the interim// transcribe interval and stop the recorder — recorder.stop() releases the@@ -72,6 +96,40 @@ export function useVoice() {[],);+ // Close-to-tray teardown: main.rs intercepts CloseRequested with hide(), so+ // the webview stays fully alive — without this, read-aloud keeps talking and+ // a running dictation keeps the mic hot (and the PCM take growing) behind a+ // window the user believes is closed. main.rs emits `app:hidden` right+ // before hiding; stop global playback and this instance's recorder.+ useEffect(() => {+ if (!isTauri()) return;+ let disposed = false;+ let unlisten: (() => void) | undefined;+ void (async () => {+ const { listen } = await import("@tauri-apps/api/event");+ const stop = await listen("app:hidden", () => {+ stopSpeechPlayback();+ if (streamTimerRef.current) {+ clearInterval(streamTimerRef.current);+ streamTimerRef.current = null;+ }+ interimBusyRef.current = false;+ const rec = recorderRef.current;+ recorderRef.current = null;+ if (rec?.isRecording()) {+ void rec.stop().catch(() => {});+ useVoiceStore.getState().setRecording(false);+ }+ });+ if (disposed) stop();+ else unlisten = stop;+ })();+ return () => {+ disposed = true;+ unlisten?.();+ };+ }, []);+// Cloud mode routes voice through the metered lu-labs.ai endpoints — no// local Whisper/Piper install needed, both buttons just work.const appMode = useSettingsStore((s) => s.settings.appMode);@@ -216,10 +274,13 @@ export function useVoice() {const externalReady = store.ttsMode === "external" && !!store.externalTtsUrl.trim();if (!cloudVoice && !externalReady && !store.ttsAvailable && !ttsSupported) return;- const gen = ++speakGenRef.current;+ const gen = ++speakGen;+ // A new read-aloud (from any bubble) supersedes a running one — abort+ // its in-flight synthesis un-metered instead of leapfrogging playback.+ speakAbort?.abort();const controller = new AbortController();- speakAbortRef.current = controller;- const stopped = () => gen !== speakGenRef.current;+ speakAbort = controller;+ const stopped = () => gen !== speakGen;store.setSpeaking(true);try {@@ -229,17 +290,24 @@ export function useVoice() {// and the MP3s played strictly sequentially — Stop cancels the whole// queue via the generation counter + the fetch abort.if (cloudVoice) {+ const chunks = chunkForTts(text);+ let played = 0;try {- for (const chunk of chunkForTts(text)) {+ for (const chunk of chunks) {if (stopped()) return;const url = await synthesizeCloud(chunk, store.cloudTtsVoice || undefined, controller.signal);if (stopped()) return;await playNeuralAudio(url);+ played++;}return;} catch (err) {if (stopped()) return; // Stop click aborted the fetch — no fallbacklog.error("Cloud TTS failed, falling back to local engines", { err });+ // Resume from the failed chunk — the user already heard (and paid+ // for) the first `played` chunks; re-reading the whole text in a+ // different voice would double-play them.+ if (played > 0) text = chunks.slice(played).join(" ");}}// External HTTP TTS engine takes precedence when selected + configured.@@ -289,17 +357,8 @@ export function useVoice() {const speakText = useCallback((text: string) => speakInternal(text, false), [speakInternal]);const speakTextStreaming = useCallback((text: string) => speakInternal(text, true), [speakInternal]);- const stopSpeaking = useCallback(() => {- // Invalidate the running speak generation (drops queued cloud chunks and- // any synthesis that resolves late) and abort the in-flight cloud fetch —- // the server cancels un-metered on a client abort.- speakGenRef.current++;- speakAbortRef.current?.abort();- speakAbortRef.current = null;- stopNeuralAudio();- stopSpeakingApi();- store.setSpeaking(false);- }, [store]);+ // Module-scoped singleton — any instance's Stop halts the global playback.+ const stopSpeaking = useCallback(() => stopSpeechPlayback(), []);const clearSttError = useCallback(() => store.setSttError(null), [store]);@@ -315,6 +374,9 @@ export function useVoice() {ttsAvailable,ttsExternalReady,ttsEnabled: store.ttsEnabled,+ /** Client-side dictation cap (ms) — cloud transcribe 413s past ~6.5 min.+ * Null in local mode (no server limit). VoiceButton auto-stops at this. */+ maxRecordingMs: cloudVoice ? CLOUD_DICTATION_LIMIT_MS : null,startRecording,stopRecording,recheckStt,diff --git a/src/stores/__tests__/cloudCatalogStore.test.ts b/src/stores/__tests__/cloudCatalogStore.test.tsindex a4cdefe7..56b657d2 100644--- a/src/stores/__tests__/cloudCatalogStore.test.ts+++ b/src/stores/__tests__/cloudCatalogStore.test.ts@@ -88,6 +88,18 @@ describe('cloudCatalogStore', () => {expect(runCredits('image', 'upscale', 'flux-9', undefined, 300)).toBe(1000)})+ it('prices video upscale per second with the min floor and the server 8s default', () => {+ useCloudCatalogStore.getState().setCatalog(serverCatalog)+ // unknown clip length → server default 8 s → 500 × 8 = 4000 (what the submit claims)+ expect(runCredits('video', 'upscale', 'wan-9', undefined, 300)).toBe(4000)+ expect(runCredits('video', 'upscale', 'wan-9', 10, 300)).toBe(5000)+ // short clip books the floor+ expect(runCredits('video', 'upscale', 'wan-9', 3, 300)).toBe(2500)+ // no catalog → quota fallback+ useCloudCatalogStore.setState({ ops: null })+ expect(runCredits('video', 'upscale', 'wan-9', undefined, 300)).toBe(300)+ })+it('prices image upscale per target resolution, flat 4k when the res table is absent', () => {useCloudCatalogStore.getState().setCatalog(serverCatalog)expect(runCredits('image', 'upscale', 'flux-9', undefined, 300, '8k')).toBe(4000)diff --git a/src/stores/cloudCatalogStore.ts b/src/stores/cloudCatalogStore.tsindex 3c10004e..089821ec 100644--- a/src/stores/cloudCatalogStore.ts+++ b/src/stores/cloudCatalogStore.ts@@ -92,10 +92,13 @@ export function runCredits(): number {const { ops } = useCloudCatalogStore.getState()if (op === 'removebg' || op === 'eraser' || op === 'upscale') {- const upscale =- ops && kind === 'image'- ? ((resolution && ops.upscale_image_res?.[resolution]) || ops.upscale_image)- : ops?.upscale_image+ // Video upscale is per-second with a floor; the server defaults to 8 s+ // when the submit carries no clip length (mirrors mediaCredits).+ const upscale = !ops+ ? undefined+ : kind === 'video'+ ? Math.ceil(Math.max(ops.upscale_video_min, ops.upscale_video_per_s * (seconds && seconds > 0 ? seconds : 8)))+ : ((resolution && ops.upscale_image_res?.[resolution]) || ops.upscale_image)const rate = ops ? { removebg: ops.removebg, eraser: ops.eraser, upscale }[op] : undefinedreturn rate ?? fallback}diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 3f72d2cd..66d031f3 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -124,6 +124,11 @@ export interface GalleryItem {jobId?: string/** Which redesign intent produced this item (gallery tagging). */intent?: CreateIntent+ /** 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+ * is unreachable. Tiles render an honest offline state and Download+ * disables instead of silently no-oping. */+ unavailable?: boolean}interface CreateState {@@ -492,7 +497,7 @@ export const useCreateStore = create<CreateState>()(// dataUrls would blow the origin quota (~5-10 MB in WebView2/WKWebView)// and every subsequent set() would throw, killing ALL create-store// persistence. Cloud items carry remoteUrl + jobId and re-sign lazily.- gallery: state.gallery.map(({ dataUrl, ...g }) => g),+ gallery: state.gallery.map(({ dataUrl, unavailable, ...g }: GalleryItem) => g),promptHistory: state.promptHistory,// ── redesign additions (advanced params only; runtime inputs// source/mask/backend/caps stay unpersisted). No version bump: thesediff --git a/src/stores/updateStore.ts b/src/stores/updateStore.tsindex 74607fb6..42c350b8 100644--- a/src/stores/updateStore.ts+++ b/src/stores/updateStore.ts@@ -1,7 +1,7 @@import { create } from 'zustand'import { persist } from 'zustand/middleware'import { version as currentVersion } from '../../package.json'-import { isTauri, backendCall } from '../api/backend'+import { isTauri, backendCall, openExternal } from '../api/backend'import type { Update } from '@tauri-apps/plugin-updater'// ── Types ─────────────────────────────────────────────────────@@ -28,6 +28,7 @@ interface UpdateState {installAndRestart: () => Promise<void>dismissUpdate: () => voidclearDismiss: () => void+ openReleasePage: () => void}// ── Config ────────────────────────────────────────────────────@@ -186,15 +187,22 @@ export const useUpdateStore = create<UpdateState>()(clearDismiss: () => {set({ dismissed: null })},++ openReleasePage: () => {+ void openExternal(`https://github.com/${GITHUB_REPO}/releases/latest`)+ },}),{name: 'lu-update-checker-v2',+ // downloadStatus is deliberately NOT persisted: the Update handle lives+ // in module-level `_pendingUpdate`, which dies with the process — a+ // rehydrated 'downloaded'/'downloading'/'error' state would render badge+ // buttons whose actions early-return on the null handle.partialize: (state) => ({lastChecked: state.lastChecked,latestVersion: state.latestVersion,updateAvailable: state.updateAvailable,releaseNotes: state.releaseNotes,- downloadStatus: state.downloadStatus,}),// Reset stale persisted state when the binary has been updated out-of-band// (e.g. user manually installed a newer .deb / .exe than what the persisted@@ -208,6 +216,14 @@ export const useUpdateStore = create<UpdateState>()(state.updateAvailable = falsestate.releaseNotes = nullstate.lastChecked = null+ } else if (state.updateAvailable) {+ // Update still pending across a relaunch: any transient download+ // state is dead (`_pendingUpdate` is null in the new process), and a+ // persisted `lastChecked` would let the 6h cooldown block the startup+ // check that repopulates it. Reset so the badge re-offers a working+ // Download immediately.+ state.downloadStatus = 'idle'+ state.lastChecked = null}},}