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
feat(gallery): pages, hide, tags and restore from the output folder (C27, D27)
purple8e904bdc7685
diff --git a/dev-server/mlx-media-stubs.ts b/dev-server/mlx-media-stubs.tsindex b8d298e3..cc3f5abc 100644--- a/dev-server/mlx-media-stubs.ts+++ b/dev-server/mlx-media-stubs.ts@@ -50,6 +50,7 @@ export function registerMlxMediaStubs(routes: RouteMount): void {'/local-api/mlx-loras-open-folder','/local-api/mlx-lora-delete','/local-api/mlx-output-trash',+ '/local-api/scan-comfy-output','/local-api/mlx-cutout','/local-api/mlx-upscale','/local-api/mlx-image-models',diff --git a/src-tauri/src/commands/gallery_files.rs b/src-tauri/src/commands/gallery_files.rsindex fb03000c..d67f4c76 100644--- a/src-tauri/src/commands/gallery_files.rs+++ b/src-tauri/src/commands/gallery_files.rs@@ -74,10 +74,365 @@ pub async fn trash_comfy_output(filename: String, subfolder: String, state: StatOk(TrashResult { trashed: true, missing: false })}+// ── Restore from the output folder (3.1.0, C27) ──────────────────────────────+//+// Discord 01.11.2026: the gallery had lost a user's entries while the+// files were still in ComfyUI's output folder. This lists that folder so the+// gallery can take the files back, with the prompt where the file carries it:+// ComfyUI writes the graph it ran as a PNG text chunk "prompt", A1111-style+// tools write "parameters". Read only; nothing on disk is touched. The text+// chunks are read without decoding the picture, and the walk stops at fixed+// limits, so a huge or odd folder cannot hang the app.++/** Most files one scan lists. */+const SCAN_MAX_FILES: usize = 20_000;+/** How deep the scan goes below the output folder. */+const SCAN_MAX_DEPTH: usize = 4;+/** Longest text chunk kept (a graph of a big workflow is well under this). */+const PNG_TEXT_MAX: usize = 2 * 1024 * 1024;+/** Bytes of a PNG read at most while looking for its text chunks. */+const PNG_READ_MAX: u64 = 32 * 1024 * 1024;++#[derive(Debug, Serialize, PartialEq, Default)]+#[serde(rename_all = "camelCase")]+pub struct OutputFile {+ pub filename: String,+ /// Below the output folder, with "/" between the parts; "" for the folder itself.+ pub subfolder: String,+ /// "image", "video" or "audio".+ pub kind: &'static str,+ pub modified_ms: u64,+ pub bytes: u64,+ pub width: Option<u32>,+ pub height: Option<u32>,+ /// The ComfyUI graph the picture was made with (PNG text "prompt").+ pub prompt: Option<String>,+ /// A1111-style settings (PNG text "parameters").+ pub parameters: Option<String>,+}++#[derive(Debug, Serialize, PartialEq, Default)]+#[serde(rename_all = "camelCase")]+pub struct OutputScan {+ /// False when LU cannot read this ComfyUI's output folder: none set up, a+ /// ComfyUI on another machine, the Mac.+ pub reachable: bool,+ pub folder: String,+ pub files: Vec<OutputFile>,+ /// The scan stopped at SCAN_MAX_FILES.+ pub truncated: bool,+}++fn kind_of(ext: &str) -> Option<&'static str> {+ match ext {+ "png" | "jpg" | "jpeg" | "webp" | "gif" => Some("image"),+ "mp4" | "webm" | "mov" | "mkv" => Some("video"),+ "wav" | "mp3" | "flac" | "ogg" => Some("audio"),+ _ => None,+ }+}++/// What a PNG says about itself before its picture data: size and text chunks.+#[derive(Debug, Default, PartialEq)]+pub struct PngInfo {+ pub width: Option<u32>,+ pub height: Option<u32>,+ pub texts: Vec<(String, String)>,+}++fn inflate_limited(data: &[u8]) -> Option<String> {+ use std::io::Read;+ let mut out = Vec::new();+ flate2::read::ZlibDecoder::new(data).take(PNG_TEXT_MAX as u64 + 1).read_to_end(&mut out).ok()?;+ if out.len() > PNG_TEXT_MAX {+ return None;+ }+ String::from_utf8(out).ok()+}++/// The text chunks (tEXt, zTXt, iTXt) and the size of a PNG, read from+/// `reader` up to the first picture chunk. Anything malformed ends the read+/// with what was found so far.+pub fn read_png_info<R: std::io::Read>(mut reader: R) -> PngInfo {+ let mut info = PngInfo::default();+ let mut sig = [0u8; 8];+ if reader.read_exact(&mut sig).is_err() || sig != [137, 80, 78, 71, 13, 10, 26, 10] {+ return info;+ }+ let mut read: u64 = 8;+ loop {+ let mut head = [0u8; 8];+ if reader.read_exact(&mut head).is_err() {+ break;+ }+ let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as u64;+ let kind = [head[4], head[5], head[6], head[7]];+ read += 8 + len + 4;+ if &kind == b"IDAT" || &kind == b"IEND" || read > PNG_READ_MAX {+ break;+ }+ let wanted = matches!(&kind, b"IHDR" | b"tEXt" | b"zTXt" | b"iTXt") && len as usize <= PNG_TEXT_MAX * 2;+ if !wanted {+ if std::io::copy(&mut <&mut R as std::io::Read>::take(&mut reader, len + 4), &mut std::io::sink()).ok() != Some(len + 4) {+ break;+ }+ continue;+ }+ let mut data = vec![0u8; len as usize];+ let mut crc = [0u8; 4];+ if reader.read_exact(&mut data).is_err() || reader.read_exact(&mut crc).is_err() {+ break;+ }+ match &kind {+ b"IHDR" if data.len() >= 8 => {+ info.width = Some(u32::from_be_bytes([data[0], data[1], data[2], data[3]]));+ info.height = Some(u32::from_be_bytes([data[4], data[5], data[6], data[7]]));+ }+ b"tEXt" => {+ if let Some(nul) = data.iter().position(|&b| b == 0) {+ let key: String = data[..nul].iter().map(|&b| b as char).collect();+ // Latin-1 by the PNG rules; ComfyUI's JSON is ASCII-escaped anyway.+ let value: String = data[nul + 1..].iter().map(|&b| b as char).collect();+ if value.len() <= PNG_TEXT_MAX {+ info.texts.push((key, value));+ }+ }+ }+ b"zTXt" => {+ if let Some(nul) = data.iter().position(|&b| b == 0) {+ let key: String = data[..nul].iter().map(|&b| b as char).collect();+ if let Some(value) = data.get(nul + 2..).and_then(inflate_limited) {+ info.texts.push((key, value));+ }+ }+ }+ b"iTXt" => {+ // key \0 flag method lang \0 translated \0 text+ let Some(nul) = data.iter().position(|&b| b == 0) else { continue };+ let key = String::from_utf8_lossy(&data[..nul]).to_string();+ let Some(&compressed) = data.get(nul + 1) else { continue };+ let rest = data.get(nul + 3..).unwrap_or(&[]);+ let Some(lang_end) = rest.iter().position(|&b| b == 0) else { continue };+ let rest = &rest[lang_end + 1..];+ let Some(tr_end) = rest.iter().position(|&b| b == 0) else { continue };+ let text = &rest[tr_end + 1..];+ let value = if compressed == 1 {+ inflate_limited(text)+ } else {+ String::from_utf8(text.to_vec()).ok().filter(|v| v.len() <= PNG_TEXT_MAX)+ };+ if let Some(v) = value {+ info.texts.push((key, v));+ }+ }+ _ => {}+ }+ }+ info+}++/// Every media file below `dir`, newest first, at most `max_files`. Links are+/// not followed, hidden folders are skipped, names that the gallery could not+/// name safely (output_file) are left out.+pub fn scan_output_dir(dir: &Path, max_files: usize) -> (Vec<OutputFile>, bool) {+ let mut files = Vec::new();+ let mut truncated = false;+ let mut stack: Vec<(PathBuf, String, usize)> = vec![(dir.to_path_buf(), String::new(), 0)];+ 'walk: while let Some((folder, sub, depth)) = stack.pop() {+ let Ok(entries) = std::fs::read_dir(&folder) else { continue };+ let mut names: Vec<_> = entries.flatten().collect();+ names.sort_by_key(|e| e.file_name());+ for entry in names {+ let name = entry.file_name().to_string_lossy().to_string();+ if name.starts_with('.') {+ continue;+ }+ let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };+ if meta.is_dir() {+ if depth < SCAN_MAX_DEPTH {+ let next = if sub.is_empty() { name.clone() } else { format!("{sub}/{name}") };+ stack.push((entry.path(), next, depth + 1));+ }+ continue;+ }+ if !meta.is_file() {+ continue;+ }+ let ext = Path::new(&name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();+ let Some(kind) = kind_of(&ext) else { continue };+ if output_file(dir, &name, &sub).is_none() {+ continue;+ }+ if files.len() >= max_files {+ truncated = true;+ break 'walk;+ }+ let modified_ms = meta+ .modified()+ .ok()+ .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0);+ let mut file = OutputFile { filename: name, subfolder: sub.clone(), kind, modified_ms, bytes: meta.len(), ..Default::default() };+ if ext == "png" {+ if let Ok(f) = std::fs::File::open(entry.path()) {+ let info = read_png_info(std::io::BufReader::new(f));+ file.width = info.width;+ file.height = info.height;+ for (key, value) in info.texts {+ match key.as_str() {+ "prompt" if file.prompt.is_none() => file.prompt = Some(value),+ "parameters" if file.parameters.is_none() => file.parameters = Some(value),+ _ => {}+ }+ }+ }+ }+ files.push(file);+ }+ }+ files.sort_by(|a, b| b.modified_ms.cmp(&a.modified_ms).then_with(|| a.subfolder.cmp(&b.subfolder)).then_with(|| a.filename.cmp(&b.filename)));+ (files, truncated)+}++#[tauri::command]+pub async fn scan_comfy_output(state: State<'_, AppState>) -> Result<OutputScan, String> {+ if !crate::commands::process::comfy_supported_here() || crate::commands::download::remote_comfy(&state).is_some() {+ return Ok(OutputScan::default());+ }+ let comfy_path = {+ let mut p = state.comfy_path.lock().map_err(|e| e.to_string())?;+ if p.is_none() {+ if let Some(found) = crate::commands::process::find_comfyui_path() {+ *p = Some(found);+ }+ }+ p.clone()+ };+ let Some(base) = comfy_path.filter(|p| !p.trim().is_empty()) else {+ return Ok(OutputScan::default());+ };+ tauri::async_runtime::spawn_blocking(move || {+ let base = PathBuf::from(base.trim());+ let output_dir = crate::commands::comfy_user_paths::UserComfyPaths::discover(&base).output_dir_or(&base);+ if !output_dir.is_dir() {+ return OutputScan { reachable: false, folder: output_dir.to_string_lossy().to_string(), ..Default::default() };+ }+ let (files, truncated) = scan_output_dir(&output_dir, SCAN_MAX_FILES);+ OutputScan { reachable: true, folder: output_dir.to_string_lossy().to_string(), files, truncated }+ })+ .await+ .map_err(|e| e.to_string())+}+#[cfg(test)]mod tests {use super::*;+ fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {+ let mut out = (data.len() as u32).to_be_bytes().to_vec();+ out.extend_from_slice(kind);+ out.extend_from_slice(data);+ out.extend_from_slice(&[0, 0, 0, 0]);+ out+ }++ fn png(chunks: &[Vec<u8>]) -> Vec<u8> {+ let mut out = vec![137, 80, 78, 71, 13, 10, 26, 10];+ let mut ihdr = 832u32.to_be_bytes().to_vec();+ ihdr.extend_from_slice(&1216u32.to_be_bytes());+ ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);+ out.extend(chunk(b"IHDR", &ihdr));+ for c in chunks {+ out.extend_from_slice(c);+ }+ out.extend(chunk(b"IDAT", &[1, 2, 3]));+ // A text chunk after the picture data is not read.+ out.extend(chunk(b"tEXt", b"late\0x"));+ out.extend(chunk(b"IEND", &[]));+ out+ }++ #[test]+ fn png_text_chunks_and_size_are_read_up_to_the_picture() {+ use std::io::Write;+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());+ z.write_all(b"steps: 20").unwrap();+ let packed = z.finish().unwrap();+ let mut ztxt = b"ztext\0\0".to_vec();+ ztxt.extend(packed);+ let mut itxt = b"workflow\0\0\0\0\0".to_vec();+ itxt.extend("{\"a\":\"\u{e4}\"}".as_bytes());+ let bytes = png(&[+ chunk(b"tEXt", b"prompt\0{\"3\":{\"class_type\":\"KSampler\"}}"),+ chunk(b"zTXt", &ztxt),+ chunk(b"iTXt", &itxt),+ chunk(b"bKGD", &[0, 0]),+ ]);+ let info = read_png_info(&bytes[..]);+ assert_eq!(info.width, Some(832));+ assert_eq!(info.height, Some(1216));+ assert_eq!(+ info.texts,+ vec![+ ("prompt".to_string(), "{\"3\":{\"class_type\":\"KSampler\"}}".to_string()),+ ("ztext".to_string(), "steps: 20".to_string()),+ ("workflow".to_string(), "{\"a\":\"\u{e4}\"}".to_string()),+ ]+ );+ }++ #[test]+ fn broken_or_foreign_files_give_what_was_found() {+ assert_eq!(read_png_info(&b"GIF89a....."[..]), PngInfo::default());+ let mut bytes = png(&[chunk(b"tEXt", b"prompt\0ok")]);+ // Cut in the middle of the picture data.+ bytes.truncate(bytes.len() - 20);+ assert_eq!(read_png_info(&bytes[..]).texts, vec![("prompt".to_string(), "ok".to_string())]);+ // A chunk length past the end.+ let mut odd = vec![137, 80, 78, 71, 13, 10, 26, 10];+ odd.extend_from_slice(&u32::MAX.to_be_bytes());+ odd.extend_from_slice(b"tEXt");+ assert_eq!(read_png_info(&odd[..]), PngInfo::default());+ }++ #[test]+ fn the_scan_lists_media_below_the_output_folder_newest_first() {+ let dir = tempfile::tempdir().unwrap();+ let out = dir.path();+ std::fs::write(out.join("a.png"), png(&[chunk(b"tEXt", b"parameters\0a cat\nSteps: 20")])).unwrap();+ std::fs::create_dir_all(out.join("video/deep")).unwrap();+ std::fs::write(out.join("video/clip.mp4"), b"x").unwrap();+ std::fs::write(out.join("video/deep/s.wav"), b"x").unwrap();+ std::fs::write(out.join("notes.txt"), b"x").unwrap();+ std::fs::write(out.join("model.safetensors"), b"x").unwrap();+ std::fs::create_dir_all(out.join(".cache")).unwrap();+ std::fs::write(out.join(".cache/c.png"), b"x").unwrap();+ let (files, truncated) = scan_output_dir(out, 100);+ assert!(!truncated);+ let mut names: Vec<_> = files.iter().map(|f| format!("{}|{}|{}", f.subfolder, f.filename, f.kind)).collect();+ names.sort();+ assert_eq!(names, vec!["video/deep|s.wav|audio", "video|clip.mp4|video", "|a.png|image"]);+ let a = files.iter().find(|f| f.filename == "a.png").unwrap();+ assert_eq!(a.parameters.as_deref(), Some("a cat\nSteps: 20"));+ assert_eq!((a.width, a.height), (Some(832), Some(1216)));+ let (few, cut) = scan_output_dir(out, 2);+ assert_eq!(few.len(), 2);+ assert!(cut);+ }++ #[cfg(unix)]+ #[test]+ fn the_scan_does_not_follow_links_out_of_the_folder() {+ let outside = tempfile::tempdir().unwrap();+ std::fs::write(outside.path().join("secret.png"), b"x").unwrap();+ let dir = tempfile::tempdir().unwrap();+ std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();+ std::os::unix::fs::symlink(outside.path().join("secret.png"), dir.path().join("s.png")).unwrap();+ let (files, _) = scan_output_dir(dir.path(), 100);+ assert!(files.is_empty());+ }+#[test]fn only_media_files_inside_the_output_folder() {let out = PathBuf::from("/comfy/output");diff --git a/src-tauri/src/commands/mobile_guard.rs b/src-tauri/src/commands/mobile_guard.rsindex f31d69ec..a7029840 100644--- a/src-tauri/src/commands/mobile_guard.rs+++ b/src-tauri/src/commands/mobile_guard.rs@@ -48,6 +48,8 @@ pub const BLOCKED: &[&str] = &["verify_model_files_cancel","trash_model_file","comfy_torch_plan",+ // 3.1.0 (C27): reads a ComfyUI output folder on the computer; a phone has none.+ "scan_comfy_output","plugin_rea_status","mcp_child_path","plugin_rea_fetch",diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 0661a099..87dfb7f7 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -899,6 +899,7 @@ pub fn run() {commands::model_sniff::sniff_model_files,#[cfg(desktop)]commands::gallery_files::trash_comfy_output,+ commands::gallery_files::scan_comfy_output,commands::system::restore_stores,commands::system::chat_backup_conversations,commands::system::backup_rag_chunks,diff --git a/src/api/backend.ts b/src/api/backend.tsindex 5b728695..946ff6e0 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -548,6 +548,9 @@ export async function backendCall<T = unknown>(mlx_loras_open_folder: { path: "/local-api/mlx-loras-open-folder", method: "POST" },mlx_lora_delete: { path: "/local-api/mlx-lora-delete", method: "POST" },mlx_output_trash: { path: "/local-api/mlx-output-trash", method: "POST" },+ // C27 (3.1.0): "Restore from the output folder" reads a local ComfyUI's+ // output folder from the Rust process; desktop-only answer in the browser.+ scan_comfy_output: { path: "/local-api/scan-comfy-output" },mlx_cutout: { path: "/local-api/mlx-cutout", method: "POST" },mlx_image_models: { path: "/local-api/mlx-image-models" },mlx_image_install_model: { path: "/local-api/mlx-image-install-model", method: "POST" },diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsxindex 685fa2e7..08adf48b 100644--- a/src/components/create/experimental/CreateExperimental.tsx+++ b/src/components/create/experimental/CreateExperimental.tsx@@ -227,9 +227,16 @@ function CreateExperimentalInner() {// so a persisted item is never mistaken for a just-made result; only a genuinely// new top id (an in-session generation) auto-shows.const prevTop = useRef<string | undefined>(gallery[0]?.id)+ // 3.1.0 (C27): the full list from IndexedDB, or entries restored from the+ // output folder, can put an older entry on top. Only one made in this+ // session counts as a new result.+ const sessionStart = useRef(Date.now() - 60_000)useEffect(() => {- const top = gallery[0]?.id- if (top && top !== prevTop.current) { setShownId(top); prevTop.current = top }+ const top = gallery[0]+ if (top && top.id !== prevTop.current) {+ prevTop.current = top.id+ if (top.createdAt >= sessionStart.current) setShownId(top.id)+ }}, [gallery])// Switching intent/mode returns the Stage to empty — the newest gallery itemdiff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsxindex bacca178..947dd317 100644--- a/src/components/create/experimental/CreatePanel.tsx+++ b/src/components/create/experimental/CreatePanel.tsx@@ -1,7 +1,7 @@import { itemHasAlpha } from '../../../lib/transparent-image'-import { useState, type MouseEvent as ReactMouseEvent } from 'react'+import { useEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react'import { motion, AnimatePresence } from 'framer-motion'-import { Images, Play, PanelRightClose, Trash2, Download, MonitorOff, AudioLines, FolderInput, Check, X } from 'lucide-react'+import { Images, Play, PanelRightClose, Trash2, Download, MonitorOff, AudioLines, FolderInput, Check, X, Eye, EyeOff, Tag } from 'lucide-react'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'import { galleryLabel } from '../../../lib/render/gallery-label'import { GALLERY_DRAG_TYPE, playsAsVideo } from './galleryUrl'@@ -11,8 +11,11 @@ import { downloadGalleryItem } from './galleryDownload'import { useComfyMedia } from './useComfyMedia'import { cn } from '../ui/cn'import { HINWEIS_TEXT, HINWEIS_ZEILE } from '../../../lib/hinweis'-import { itemsInFolder } from '../../../lib/gallery-folders'+import { hiddenCount, itemsInView } from '../../../lib/gallery-tags'import { FolderFilter, MoveToFolderModal, OnBody } from './GalleryFolders'+import { TagFilter, TagsModal } from './GalleryTags'+import { RestoreFromOutputButton } from './GalleryRestore'+import { isTauri } from '../../../api/backend'import { ContextMenu } from '../../ui/ContextMenu'import { Modal } from '../../ui/Modal'import { ModalActions, ModalButton } from '../../ui/ModalActions'@@ -21,6 +24,10 @@ import {type GallerySelection,} from './gallerySelection'+/** Tiles drawn at first, and added each time the end of the list scrolls into+ * view (C27, 3.1.0: the gallery has no cap any more, thousands of entries). */+export const GALLERY_PAGE = 60+interface Props {open: booleanonOpenChange: (open: boolean) => void@@ -38,13 +45,42 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {const all = useCreateStore((s) => s.gallery)const folderOpen = useCreateStore((s) => s.galleryFolderOpen)const removeFromGallery = useCreateStore((s) => s.removeFromGallery)+ // C27: the output folder of a local ComfyUI. The Mac has none, the cloud neither.+ const canRestore = useCreateStore((s) => s.backend === 'local') && isTauri() && !isMlxImageHost()// D3b: the cap took older unsorted entries; said once, until closed.const notice = useCreateStore((s) => s.galleryNotice)const dismissNotice = useCreateStore((s) => s.dismissGalleryNotice)- // D3: the panel shows the open folder, "All" when none is open.- const gallery = folderOpen === null ? all : itemsInFolder(all, folderOpen)+ // D3: the panel shows the open folder, "All" when none is open. 3.1.0+ // (D27): and the picked tag, and either the hidden entries or the others.+ const tagOpen = useCreateStore((s) => s.galleryTagOpen)+ const showHidden = useCreateStore((s) => s.galleryShowHidden)+ const setHidden = useCreateStore((s) => s.setGalleryHidden)+ const gallery = itemsInView(all, { folderId: folderOpen, tag: tagOpen, hidden: showHidden })const [moving, setMoving] = useState<string[]>([])+ const [tagging, setTagging] = useState<string[]>([])const count = gallery.length+ // C27: the tiles come in pages as the list scrolls, so a gallery of+ // thousands opens as fast as one of sixty. A new view starts at the top.+ const viewKey = `${folderOpen ?? ''}\n${tagOpen ?? ''}\n${showHidden}`+ const [page, setPage] = useState({ key: viewKey, n: GALLERY_PAGE })+ const limit = page.key === viewKey ? page.n : GALLERY_PAGE+ const shown = limit >= count ? gallery : gallery.slice(0, limit)+ const scroller = useRef<HTMLDivElement | null>(null)+ const sentinel = useRef<HTMLDivElement | null>(null)+ const more = shown.length < count+ useEffect(() => {+ const end = sentinel.current+ if (!more || !end) return+ if (typeof IntersectionObserver === 'undefined') {+ setPage({ key: viewKey, n: count })+ return+ }+ const io = new IntersectionObserver((entries) => {+ if (entries.some((e) => e.isIntersecting)) setPage((p) => ({ key: viewKey, n: (p.key === viewKey ? p.n : GALLERY_PAGE) + GALLERY_PAGE }))+ }, { root: scroller.current, rootMargin: '400px 0px' })+ io.observe(end)+ return () => io.disconnect()+ }, [more, viewKey, count, limit])// Several at once (D3, 3.0.9): Cmd/Ctrl-click, Shift range, Cmd/Ctrl+A,// Escape. The menu and the bar act on `sel.ids` with the tile's own code.const [stored, setSel] = useState<GallerySelection>(EMPTY_SELECTION)@@ -95,7 +131,12 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {move: () => setMoving([...ids]),download: () => { void downloadAll(ids) },remove: () => setConfirming(ids),+ tags: () => setTagging([...ids]),+ // In the Hidden view the same action shows them again.+ hide: () => { setHidden(ids, !showHidden); setSel(EMPTY_SELECTION) },+ hidden: showHidden,})+ const visibleTotal = all.length - hiddenCount(all)const bubble ='my-2 mr-2 rounded-xl bg-gray-50 dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] flex flex-col overflow-hidden shrink-0'@@ -136,9 +177,9 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {><span className="relative"><Images size={16} />- {all.length > 0 && (+ {visibleTotal > 0 && (<span className="absolute -top-1.5 -right-2 min-w-[14px] h-[14px] px-0.5 flex items-center justify-center rounded-full text-[0.5rem] font-bold bg-gray-300 dark:bg-white/20 text-gray-700 dark:text-gray-200">- {all.length}+ {visibleTotal}</span>)}</span>@@ -168,9 +209,11 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {<Images size={13} className="text-gray-500" /><span className="t-label text-gray-400">Gallery</span>{count > 0 && <span className="t-mono text-gray-600">{count}</span>}+ {canRestore && <RestoreFromOutputButton />}</div><FolderFilter />+ <TagFilter />{notice && (<div role="status" className={cn(HINWEIS_ZEILE, 'items-center mx-3 mt-2 shrink-0')}><p className={cn('flex-1', HINWEIS_TEXT.ruhig)}>{notice}</p>@@ -178,6 +221,7 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {</div>)}<OnBody><MoveToFolderModal ids={moving} onClose={() => setMoving([])} /></OnBody>+ <OnBody><TagsModal ids={tagging} onClose={() => setTagging([])} /></OnBody><OnBody><Modal open={confirming.length > 0} onClose={() => setConfirming([])} title="Delete from the gallery" maxWidth="max-w-md"><div data-testid="gallery-delete-confirm">@@ -208,18 +252,22 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {><span className="t-label text-gray-500 dark:text-gray-400 mr-auto" aria-live="polite">{sel.ids.length} selected</span><BarBtn title="Move to folder" onClick={actionsFor(sel.ids).move}><FolderInput size={13} /></BarBtn>+ <BarBtn title="Tags" onClick={actionsFor(sel.ids).tags}><Tag size={13} /></BarBtn>+ <BarBtn title={showHidden ? 'Show again' : 'Hide from gallery'} onClick={actionsFor(sel.ids).hide}>+ {showHidden ? <Eye size={13} /> : <EyeOff size={13} />}+ </BarBtn><BarBtn title="Download" onClick={actionsFor(sel.ids).download}><Download size={13} /></BarBtn><BarBtn title="Delete" danger onClick={actionsFor(sel.ids).remove}><Trash2 size={13} /></BarBtn><BarBtn title="Clear selection" onClick={() => setSel(EMPTY_SELECTION)}><X size={13} /></BarBtn></div>)}- <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin p-3">+ <div ref={scroller} className="flex-1 min-h-0 overflow-y-auto scrollbar-thin p-3">{count === 0 ? (- <p className="t-body text-gray-500 py-2">{all.length > 0 ? 'Nothing in this folder yet.' : 'Nothing generated yet.'}</p>+ <p className="t-body text-gray-500 py-2">{emptyLine(all.length, { folder: folderOpen !== null, tag: tagOpen !== null, hidden: showHidden })}</p>) : (<div className="grid grid-cols-2 gap-2" role="group" aria-label="Gallery items" onKeyDown={onGridKey}>- {gallery.map((g) => (+ {shown.map((g) => (<div key={g.id} className="relative group"><buttononClick={(e) => onTileClick(e, g.id)}@@ -262,6 +310,16 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {><Trash2 size={12} /></button>+ {!picked.has(g.id) && (+ <button+ onClick={() => setHidden([g.id], !showHidden)}+ className="lu-on-dark absolute top-1 left-1 w-6 h-6 rounded-md bg-black/55 hover:bg-black/70 text-gray-100 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center shadow-sm"+ title={showHidden ? 'Show again' : 'Hide from gallery. The file stays.'}+ aria-label={showHidden ? 'Show again' : 'Hide from gallery'}+ >+ {showHidden ? <Eye size={12} /> : <EyeOff size={12} />}+ </button>+ )}<buttononClick={() => setMoving([g.id])}className="lu-on-dark absolute bottom-1 left-1 w-6 h-6 rounded-md bg-black/55 hover:bg-black/70 text-gray-100 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center shadow-sm"@@ -280,6 +338,11 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {))}</div>)}+ {more && (+ <div ref={sentinel} className="py-3 text-center t-label text-gray-500" data-testid="gallery-more">+ {shown.length} of {count}+ </div>+ )}</div></motion.aside>)}@@ -287,6 +350,14 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {)}+/** What an empty view says. */+export function emptyLine(total: number, filter: { folder: boolean; tag: boolean; hidden: boolean }): string {+ if (total === 0) return 'Nothing generated yet.'+ if (filter.hidden) return 'Nothing hidden here.'+ if (filter.tag) return 'No items with this tag here.'+ return filter.folder ? 'Nothing in this folder yet.' : 'Everything here is hidden.'+}+function BarBtn({ children, title, onClick, danger }: { children: React.ReactNode; title: string; onClick: () => void; danger?: boolean }) {return (<button@@ -320,10 +391,10 @@ function GalleryThumb({ g }: { g: GalleryItem }) {}return playsAsVideo(g) ? (<>- <video src={src} muted playsInline onError={onError} onLoadedData={onLoad} className="w-full h-full object-cover" />+ <video src={src} muted playsInline preload="metadata" 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" />+ <img src={src} alt="" loading="lazy" decoding="async" onError={onError} onLoad={onLoad} className="w-full h-full object-cover" />)}diff --git a/src/components/create/experimental/GalleryFolders.tsx b/src/components/create/experimental/GalleryFolders.tsxindex 45e6c6b3..b78046f4 100644--- a/src/components/create/experimental/GalleryFolders.tsx+++ b/src/components/create/experimental/GalleryFolders.tsx@@ -28,7 +28,11 @@ const ROW_FIELD = `flex-1 min-w-0 ${FIELD}`/** The filter at the top of the gallery: "All" and every folder, with counts,* and the button that manages the folders. */export function FolderFilter() {- const gallery = useCreateStore((s) => s.gallery)+ const all = useCreateStore((s) => s.gallery)+ // 3.1.0 (D27): the counts are of the entries the view can show, the hidden+ // ones in the Hidden view and the others everywhere else.+ const showHidden = useCreateStore((s) => s.galleryShowHidden)+ const gallery = all.filter((g) => !!g.hidden === showHidden)const folders = useCreateStore((s) => s.galleryFolders)const open = useCreateStore((s) => s.galleryFolderOpen)const setOpen = useCreateStore((s) => s.setGalleryFolderOpen)diff --git a/src/components/create/experimental/GalleryRestore.tsx b/src/components/create/experimental/GalleryRestore.tsxnew file mode 100644index 00000000..4ef149c0--- /dev/null+++ b/src/components/create/experimental/GalleryRestore.tsx@@ -0,0 +1,69 @@+import { useState } from 'react'+import { ArchiveRestore } from 'lucide-react'+import { Modal } from '../../ui/Modal'+import { ModalActions, ModalButton } from '../../ui/ModalActions'+import { restoreFromOutputFolder, type RestoreResult } from '../../../lib/gallery-restore'+import { OnBody } from './GalleryFolders'++// "Restore from the output folder" (C27, 3.1.0): the gallery takes back the+// pictures and videos ComfyUI's output folder still has (lib/gallery-restore.ts).++/** What the dialog says after a run. */+export function restoreLine(r: RestoreResult): string {+ if (!r.reachable) return 'LU cannot read the output folder of this ComfyUI. It is on another computer, or not set up yet.'+ if (r.found === 0) return 'The output folder has no pictures or videos.'+ const found = `Found ${r.found} file${r.found === 1 ? '' : 's'}`+ const added = r.added === 0+ ? 'the gallery lists all of them already.'+ : `${r.added} ${r.added === 1 ? 'is' : 'are'} back in the gallery${r.withPrompt > 0 ? `, ${r.withPrompt} with their prompt` : ''}.`+ const cut = r.truncated ? ' The folder holds more than one look can take; run it again after sorting some out.' : ''+ return `${found}, ${added}${cut}`+}++/** The button in the gallery header and its dialog. */+export function RestoreFromOutputButton() {+ const [open, setOpen] = useState(false)+ const [busy, setBusy] = useState(false)+ const [line, setLine] = useState<string | null>(null)+ const run = async () => {+ setBusy(true)+ setLine(null)+ try {+ setLine(restoreLine(await restoreFromOutputFolder()))+ } catch (err) {+ setLine(`Could not look through the output folder: ${err instanceof Error ? err.message : String(err)}`)+ } finally {+ setBusy(false)+ }+ }+ const close = () => { if (!busy) { setOpen(false); setLine(null) } }+ return (+ <>+ <button+ type="button"+ onClick={() => setOpen(true)}+ title="Restore from the output folder" aria-label="Restore from the output folder"+ className="ml-auto flex items-center justify-center w-6 h-6 rounded text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"+ >+ <ArchiveRestore size={13} />+ </button>+ <OnBody>+ <Modal open={open} onClose={close} title="Restore from the output folder" maxWidth="max-w-md">+ <div className="flex flex-col gap-3" data-testid="gallery-restore">+ <p className="t-body text-gray-500">+ LU looks through ComfyUI's output folder and adds every picture, video and sound the gallery does not list yet.+ Prompts and settings come back where the file carries them. Nothing on disk changes.+ </p>+ {line && <p role="status" className="t-body text-gray-200">{line}</p>}+ <ModalActions>+ <ModalButton variant="quiet" onClick={close} disabled={busy}>{line ? 'Done' : 'Cancel'}</ModalButton>+ <ModalButton variant="primary" onClick={() => { void run() }} disabled={busy}>+ {busy ? 'Looking…' : line ? 'Look again' : 'Look now'}+ </ModalButton>+ </ModalActions>+ </div>+ </Modal>+ </OnBody>+ </>+ )+}diff --git a/src/components/create/experimental/GalleryTags.tsx b/src/components/create/experimental/GalleryTags.tsxnew file mode 100644index 00000000..26bee3f3--- /dev/null+++ b/src/components/create/experimental/GalleryTags.tsx@@ -0,0 +1,141 @@+import { useState } from 'react'+import { Eye, EyeOff, X } from 'lucide-react'+import { Modal } from '../../ui/Modal'+import { ModalActions, ModalButton } from '../../ui/ModalActions'+import { useCreateStore } from '../../../stores/createStore'+import { TAG_MAX, cleanTag, hiddenCount, tagCounts } from '../../../lib/gallery-tags'+import { Select, type SelectOption } from '../ui/Select'+import { cn } from '../ui/cn'++// Hide and tags in the gallery (D27, 3.1.0). Labels inside the app, like+// folders: hiding keeps the file, the prompt and the folder (lib/gallery-tags.ts).++const ALL_TAGS = '__all_tags'++const FIELD =+ 'h-[var(--control-h-md)] px-2.5 rounded-[var(--radius-control)] bg-white/[0.04] border border-white/[0.08] focus:border-white/20 outline-none t-control text-gray-100'++/** Under the folder filter: the tag filter (once a tag exists) and the way into+ * the hidden entries (once one is hidden). Nothing shows while neither exists. */+export function TagFilter() {+ const gallery = useCreateStore((s) => s.gallery)+ const tagOpen = useCreateStore((s) => s.galleryTagOpen)+ const setTagOpen = useCreateStore((s) => s.setGalleryTagOpen)+ const showHidden = useCreateStore((s) => s.galleryShowHidden)+ const setShowHidden = useCreateStore((s) => s.setGalleryShowHidden)+ const tags = tagCounts(gallery)+ const hidden = hiddenCount(gallery)+ if (tags.length === 0 && hidden === 0 && !showHidden && tagOpen === null) return null+ const options: SelectOption[] = [+ { value: ALL_TAGS, label: 'All tags' },+ ...tags.map((t) => ({ value: t.tag, label: `#${t.tag} (${t.count})` })),+ ]+ return (+ <div className="flex items-center gap-1.5 px-3 pt-2 shrink-0" data-testid="gallery-tag-filter">+ {tags.length > 0 && (+ <Select+ size="sm"+ className="flex-1 min-w-0"+ ariaLabel="Show tag"+ options={options}+ value={tagOpen ?? ALL_TAGS}+ onChange={(v) => setTagOpen(v === ALL_TAGS ? null : v)}+ />+ )}+ {(hidden > 0 || showHidden) && (+ <button+ type="button"+ onClick={() => setShowHidden(!showHidden)}+ aria-pressed={showHidden}+ title={showHidden ? 'Back to the gallery' : 'Show the hidden items'}+ className={cn(+ 'flex items-center justify-center gap-1 h-[var(--control-h-sm)] px-1.5 rounded t-label transition-colors',+ showHidden ? 'bg-white/10 text-gray-200' : 'text-gray-500 hover:text-gray-200 hover:bg-white/5',+ tags.length === 0 && 'ml-auto',+ )}+ >+ {showHidden ? <Eye size={13} /> : <EyeOff size={13} />}+ <span>{showHidden ? 'Hidden' : `Hidden (${hidden})`}</span>+ </button>+ )}+ </div>+ )+}++/** The tags of one or more entries: add one to all of them, take one off all of them. */+export function TagsModal({ ids, onClose }: { ids: readonly string[]; onClose: () => void }) {+ return (+ <Modal open={ids.length > 0} onClose={onClose} title={ids.length > 1 ? `Tags for ${ids.length} items` : 'Tags'} maxWidth="max-w-md">+ <TagsEditor ids={ids} />+ <ModalActions>+ <ModalButton variant="primary" onClick={onClose}>Done</ModalButton>+ </ModalActions>+ </Modal>+ )+}++function TagsEditor({ ids }: { ids: readonly string[] }) {+ const gallery = useCreateStore((s) => s.gallery)+ const tag = useCreateStore((s) => s.tagGalleryItems)+ const untag = useCreateStore((s) => s.untagGalleryItems)+ const [text, setText] = useState('')+ const pick = new Set(ids)+ const picked = gallery.filter((g) => pick.has(g.id))+ const onThese = tagCounts(picked)+ const known = new Set(onThese.map((t) => t.tag.toLocaleLowerCase()))+ const others = tagCounts(gallery).filter((t) => !known.has(t.tag.toLocaleLowerCase())).slice(0, 12)+ const add = (raw: string) => {+ if (!cleanTag(raw)) return+ tag(ids, raw)+ setText('')+ }+ return (+ <div className="flex flex-col gap-3" data-testid="gallery-tags">+ <p className="t-body text-gray-500">Tags only sort the gallery. Pick one above the gallery to see just those items.</p>+ {onThese.length > 0 && (+ <ul className="flex flex-wrap gap-1.5" aria-label="Tags on these items">+ {onThese.map((t) => (+ <li key={t.tag} className="flex items-center gap-1 pl-2 pr-1 h-6 rounded-full bg-white/[0.07] t-label text-gray-200">+ #{t.tag}+ {picked.length > 1 && t.count < picked.length && <span className="text-gray-500">{t.count}/{picked.length}</span>}+ <button+ type="button"+ onClick={() => untag(ids, t.tag)}+ title={`Remove #${t.tag}`} aria-label={`Remove tag ${t.tag}`}+ className="w-4 h-4 flex items-center justify-center rounded-full text-gray-400 hover:text-gray-100 hover:bg-white/10"+ >+ <X size={10} />+ </button>+ </li>+ ))}+ </ul>+ )}+ <div className="flex items-center gap-2">+ <input+ value={text}+ maxLength={TAG_MAX + 1}+ placeholder="New tag"+ aria-label="New tag"+ onChange={(e) => setText(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') add(text) }}+ className={`flex-1 min-w-0 ${FIELD}`}+ />+ <ModalButton onClick={() => add(text)} disabled={!cleanTag(text)}>Add</ModalButton>+ </div>+ {others.length > 0 && (+ <div className="flex flex-wrap gap-1.5" aria-label="Tags in use">+ {others.map((t) => (+ <button+ key={t.tag}+ type="button"+ onClick={() => add(t.tag)}+ className="px-2 h-6 rounded-full border border-white/[0.08] t-label text-gray-400 hover:text-gray-100 hover:bg-white/5"+ >+ #{t.tag}+ </button>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/src/components/create/experimental/Lightbox.tsx b/src/components/create/experimental/Lightbox.tsxindex 1035669c..124ba598 100644--- a/src/components/create/experimental/Lightbox.tsx+++ b/src/components/create/experimental/Lightbox.tsx@@ -10,7 +10,7 @@ import { PromptDetails } from './PromptDetails'import { cn } from '../ui/cn'import { MoveToFolderModal, OnBody } from './GalleryFolders'import { playsAsVideo } from './galleryUrl'-import { itemsInFolder } from '../../../lib/gallery-folders'+import { itemsInView } from '../../../lib/gallery-tags'/** How far the mouse wheel zooms a picture in the large view, and the step per notch. */const MAX_ZOOM = 5@@ -21,13 +21,14 @@ const ZOOM_STEP = 1.2* them (the open folder, else all). Null at either end, and for an entry the* panel does not show.*/-export function galleryNeighbor<T extends { id: string; folderId?: string }>(+export function galleryNeighbor<T extends { id: string; folderId?: string; hidden?: boolean; tags?: string[] }>(all: readonly T[],folderOpen: string | null,id: string,step: -1 | 1,+ filter: { tag?: string | null; hidden?: boolean } = {},): T | null {- const shown = itemsInFolder(all, folderOpen)+ const shown = itemsInView(all, { folderId: folderOpen, tag: filter.tag ?? null, hidden: filter.hidden ?? false })const at = shown.findIndex((g) => g.id === id)if (at < 0) return nullreturn shown[at + step] ?? null@@ -68,13 +69,17 @@ export function Lightbox({ item, onClose, onSaveCharacter, onNavigate, promptOpe// and zoom a picture with the mouse wheel, as a photo viewer does.const all = useCreateStore((s) => s.gallery)const folderOpen = useCreateStore((s) => s.galleryFolderOpen)- const prev = item && onNavigate ? galleryNeighbor(all, folderOpen, item.id, -1) : null- const next = item && onNavigate ? galleryNeighbor(all, folderOpen, item.id, 1) : null+ // 3.1.0 (D27): the tag filter and the Hidden view are part of the view too.+ const tagOpen = useCreateStore((s) => s.galleryTagOpen)+ const showHidden = useCreateStore((s) => s.galleryShowHidden)+ const filter = { tag: tagOpen, hidden: showHidden }+ const prev = item && onNavigate ? galleryNeighbor(all, folderOpen, item.id, -1, filter) : null+ const next = item && onNavigate ? galleryNeighbor(all, folderOpen, item.id, 1, filter) : null// D3 (Discord 01.11.2026): an entry moved out of the open folder is no// longer in the view the arrows step through, and they were gone. The view// goes on with the next entry of the folder, or closes when none is left.// An entry opened while not in the view (from the stage) is left alone.- const viewKey = itemsInFolder(all, folderOpen).map((g) => g.id).join('\n')+ const viewKey = itemsInView(all, { folderId: folderOpen, ...filter }).map((g) => g.id).join('\n')const lastView = useRef<{ id: string; ids: string[] } | null>(null)useEffect(() => {if (!item) { lastView.current = null; return }diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxindex 63008b13..8926d719 100644--- a/src/components/create/experimental/Stage.tsx+++ b/src/components/create/experimental/Stage.tsx@@ -328,7 +328,7 @@ function InputSlot() {// 2026-07-10: ops never auto-adopt a gallery image — instead the slot// offers the recent gallery images as an EXPLICIT pick, next to drag&drop// and the file picker ("aus Galerie ODER vom Desktop").- const galleryImages = gallery.filter((g) => g.type === 'image' && !g.unavailable).slice(0, 8)+ const galleryImages = gallery.filter((g) => g.type === 'image' && !g.unavailable && !g.hidden).slice(0, 8)// The image a list was made from is not in the gallery, and a batch can push// every older result out of the strip. It stays pinned at the front.const original = useBatchOriginalOffer()diff --git a/src/components/create/experimental/__tests__/galerie-ausblenden-tags-seiten.test.tsx b/src/components/create/experimental/__tests__/galerie-ausblenden-tags-seiten.test.tsxnew file mode 100644index 00000000..3203a480--- /dev/null+++ b/src/components/create/experimental/__tests__/galerie-ausblenden-tags-seiten.test.tsx@@ -0,0 +1,128 @@+// @vitest-environment jsdom+/**+ * The gallery panel in 3.1.0: no cap any more, so the tiles come in pages+ * (C27); entries can be hidden and shown again, and tagged and filtered by+ * tag (D27, promised on Discord 05.11.2026).+ *+ * Run: npx vitest run src/components/create/experimental/__tests__/galerie-ausblenden-tags-seiten.test.tsx+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'++vi.mock('../CreateContext', () => ({+ useCreateExp: () => ({ quota: null, enhanceVideo: vi.fn() }),+}))+vi.mock('../useComfyMedia', () => ({+ useComfyMedia: () => ({ src: 'blob:media', onError: vi.fn(), onLoad: vi.fn() }),+}))+vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => false, MLX_MODEL_PREFIX: 'MLX ' }))++import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'+import { CreatePanel, GALLERY_PAGE, emptyLine } from '../CreatePanel'++const ITEM = (n: number, extra: Partial<GalleryItem> = {}): GalleryItem => ({+ id: `g${n}`, type: 'image', filename: `${n}.png`, subfolder: '', prompt: `prompt ${n}`, negativePrompt: '',+ model: 'm.safetensors', modelType: 'sdxl', seed: 1, steps: 20, cfgScale: 5, sampler: 'euler',+ scheduler: 'normal', width: 512, height: 512, batchSize: 1, createdAt: n, ...extra,+})++/** IntersectionObserver that the test fires by hand. */+const observers: { cb: IntersectionObserverCallback; el: Element | null }[] = []+class FakeIO {+ cb: IntersectionObserverCallback+ constructor(cb: IntersectionObserverCallback) { this.cb = cb }+ observe(el: Element) { observers.push({ cb: this.cb, el }) }+ disconnect() { for (let i = observers.length - 1; i >= 0; i--) if (observers[i].cb === this.cb) observers.splice(i, 1) }+ unobserve() {}+ takeRecords() { return [] }+}+const scrollToEnd = () => act(() => {+ for (const o of [...observers]) o.cb([{ isIntersecting: true, target: o.el } as IntersectionObserverEntry], {} as IntersectionObserver)+})++beforeEach(() => {+ vi.stubGlobal('IntersectionObserver', FakeIO)+ observers.length = 0+ useCreateStore.setState({+ backend: 'local', gallery: [], galleryFolders: [], galleryFolderOpen: null, galleryTagOpen: null,+ galleryShowHidden: false, galleryNotice: null,+ })+})+afterEach(() => { cleanup(); vi.unstubAllGlobals() })++const panel = () => render(<CreatePanel open onOpenChange={() => {}} activeId={null} onSelect={() => {}} />)+const tiles = () => document.querySelectorAll('[data-gallery-id]')++describe('pages instead of a cap', () => {+ it('1000 entries: the first page, then the next as the end scrolls into view', () => {+ useCreateStore.setState({ gallery: Array.from({ length: 1000 }, (_, i) => ITEM(1000 - i)) })+ panel()+ expect(tiles()).toHaveLength(GALLERY_PAGE)+ expect(screen.getByTestId('gallery-more').textContent).toBe(`${GALLERY_PAGE} of 1000`)+ scrollToEnd()+ expect(tiles()).toHaveLength(GALLERY_PAGE * 2)+ // The count in the header is the whole view, not the page.+ expect(screen.getByText('1000')).toBeTruthy()+ })++ it('a short list has no page line', () => {+ useCreateStore.setState({ gallery: [ITEM(2), ITEM(1)] })+ panel()+ expect(tiles()).toHaveLength(2)+ expect(screen.queryByTestId('gallery-more')).toBeNull()+ })+})++describe('hide and show again', () => {+ beforeEach(() => { useCreateStore.setState({ gallery: [ITEM(3), ITEM(2), ITEM(1)] }) })++ it('the tile button hides an entry; Hidden shows it and brings it back', () => {+ panel()+ const tile = document.querySelector('[data-gallery-id="g2"]')!.parentElement!+ fireEvent.click(within(tile).getByRole('button', { name: 'Hide from gallery' }))+ expect([...tiles()].map((t) => t.getAttribute('data-gallery-id'))).toEqual(['g3', 'g1'])+ // The entry is still in the store, with its file and prompt.+ expect(useCreateStore.getState().gallery.find((g) => g.id === 'g2')).toMatchObject({ hidden: true, filename: '2.png', prompt: 'prompt 2' })+ fireEvent.click(screen.getByRole('button', { name: 'Hidden (1)' }))+ expect([...tiles()].map((t) => t.getAttribute('data-gallery-id'))).toEqual(['g2'])+ const hiddenTile = document.querySelector('[data-gallery-id="g2"]')!.parentElement!+ fireEvent.click(within(hiddenTile).getByRole('button', { name: 'Show again' }))+ expect(useCreateStore.getState().gallery.find((g) => g.id === 'g2')!.hidden).toBeUndefined()+ expect(screen.getByText('Nothing hidden here.')).toBeTruthy()+ })++ it('the right-click menu hides several at once', () => {+ panel()+ fireEvent.click(document.querySelector('[data-gallery-id="g3"]')!, { ctrlKey: true })+ fireEvent.click(document.querySelector('[data-gallery-id="g1"]')!, { ctrlKey: true })+ fireEvent.contextMenu(document.querySelector('[data-gallery-id="g1"]')!)+ fireEvent.click(screen.getByRole('menuitem', { name: 'Hide 2 from gallery' }))+ expect([...tiles()].map((t) => t.getAttribute('data-gallery-id'))).toEqual(['g2'])+ })+})++describe('tags', () => {+ it('the tag dialog adds a tag, the filter shows only those entries', () => {+ useCreateStore.setState({ gallery: [ITEM(3), ITEM(2), ITEM(1)] })+ panel()+ fireEvent.contextMenu(document.querySelector('[data-gallery-id="g2"]')!)+ fireEvent.click(screen.getByRole('menuitem', { name: 'Tags…' }))+ const field = screen.getByRole('textbox', { name: 'New tag' })+ fireEvent.change(field, { target: { value: 'Keeper' } })+ fireEvent.keyDown(field, { key: 'Enter' })+ expect(useCreateStore.getState().gallery.find((g) => g.id === 'g2')!.tags).toEqual(['Keeper'])+ fireEvent.click(screen.getByRole('button', { name: 'Done' }))+ act(() => { useCreateStore.getState().setGalleryTagOpen('keeper') })+ expect([...tiles()].map((t) => t.getAttribute('data-gallery-id'))).toEqual(['g2'])+ })+})++describe('empty views', () => {+ it('say why they are empty', () => {+ expect(emptyLine(0, { folder: false, tag: false, hidden: false })).toBe('Nothing generated yet.')+ expect(emptyLine(5, { folder: true, tag: false, hidden: false })).toBe('Nothing in this folder yet.')+ expect(emptyLine(5, { folder: false, tag: true, hidden: false })).toBe('No items with this tag here.')+ expect(emptyLine(5, { folder: false, tag: false, hidden: true })).toBe('Nothing hidden here.')+ expect(emptyLine(5, { folder: false, tag: false, hidden: false })).toBe('Everything here is hidden.')+ })+})diff --git a/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx b/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsxindex 78109202..2b9b843c 100644--- a/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx+++ b/src/components/create/experimental/__tests__/galerie-mehrfachauswahl.test.tsx@@ -114,7 +114,7 @@ describe('the right-click menu', () => {fireEvent.click(tile('b'), { metaKey: true })fireEvent.contextMenu(tile('b'), { clientX: 40, clientY: 40 })const menu = screen.getByRole('menu')- expect(within(menu).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move 2 to folder…', 'Download 2', 'Delete 2…'])+ expect(within(menu).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move 2 to folder…', 'Tag 2…', 'Hide 2 from gallery', 'Download 2', 'Delete 2…'])})it('a right-click right after Cmd-clicks, before the next render, keeps them (Mac run)', () => {@@ -126,7 +126,7 @@ describe('the right-click menu', () => {fire('b', 'click', { metaKey: true })fire('b', 'contextmenu', { clientX: 40, clientY: 40 })})- expect(within(screen.getByRole('menu')).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move 2 to folder…', 'Download 2', 'Delete 2…'])+ expect(within(screen.getByRole('menu')).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move 2 to folder…', 'Tag 2…', 'Hide 2 from gallery', 'Download 2', 'Delete 2…'])})it('on an unselected tile acts on that tile alone', () => {@@ -134,7 +134,7 @@ describe('the right-click menu', () => {fireEvent.click(tile('a'), { metaKey: true })fireEvent.contextMenu(tile('d'), { clientX: 40, clientY: 40 })expect(selected()).toEqual(['d'])- expect(within(screen.getByRole('menu')).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move to folder…', 'Download', 'Delete…'])+ expect(within(screen.getByRole('menu')).getAllByRole('menuitem').map((m) => m.textContent)).toEqual(['Move to folder…', 'Tags…', 'Hide from gallery', 'Download', 'Delete…'])})it('Delete asks with the count first; Cancel keeps everything', () => {diff --git a/src/components/create/experimental/gallerySelection.ts b/src/components/create/experimental/gallerySelection.tsindex badb3763..0dcb9e3e 100644--- a/src/components/create/experimental/gallerySelection.ts+++ b/src/components/create/experimental/gallerySelection.ts@@ -71,12 +71,20 @@ export interface GalleryMenuHandlers {readonly download: () => void/** Opens the question; nothing is deleted before it is answered. */readonly remove: () => void+ /** Opens the tag dialog (D27, 3.1.0). */+ readonly tags?: () => void+ /** Hides the entries, or shows them again in the Hidden view (D27). */+ readonly hide?: () => void+ /** True in the Hidden view: the entry is shown again instead. */+ readonly hidden?: boolean}export function buildGalleryMenu(h: GalleryMenuHandlers, count: number): MenuAction[] {const n = count > 1 ? ` ${count}` : ''return [{ id: 'move', label: count > 1 ? `Move${n} to folder…` : 'Move to folder…', run: h.move },+ ...(h.tags ? [{ id: 'tags', label: count > 1 ? `Tag${n}…` : 'Tags…', run: h.tags }] : []),+ ...(h.hide ? [{ id: 'hide', label: h.hidden ? `Show${n} again` : `Hide${n} from gallery`, run: h.hide }] : []),{ id: 'download', label: `Download${n}`, run: h.download },{ id: 'delete', label: `Delete${n}…`, run: h.remove, destructive: true },]diff --git a/src/lib/__tests__/gallery-restore.test.ts b/src/lib/__tests__/gallery-restore.test.tsnew file mode 100644index 00000000..6b68bb91--- /dev/null+++ b/src/lib/__tests__/gallery-restore.test.ts@@ -0,0 +1,117 @@+// @vitest-environment jsdom+/**+ * "Restore from the output folder" (C27, 3.1.0): the prompt and settings come+ * back out of the text ComfyUI and A1111-style tools store in a PNG, and a+ * second run adds nothing.+ *+ * Run: npx vitest run src/lib/__tests__/gallery-restore.test.ts+ */+import { beforeEach, describe, expect, it } from 'vitest'+import { entryFromScan, madeWithFromComfyGraph, madeWithFromParameters, restoreFromOutputFolder, restoredId, type ScannedFile } from '../gallery-restore'+import { useCreateStore, type GalleryItem } from '../../stores/createStore'++/** The graph shape of LU's own SDXL run (dynamic workflow, KSampler). */+const KSAMPLER_GRAPH = JSON.stringify({+ '4': { class_type: 'CheckpointLoaderSimple', inputs: { ckpt_name: 'juggernautXL_v9.safetensors' } },+ '10': { class_type: 'LoraLoader', inputs: { lora_name: 'style.safetensors', strength_model: 0.8, strength_clip: 0.8, model: ['4', 0], clip: ['4', 1] } },+ '5': { class_type: 'EmptyLatentImage', inputs: { width: 832, height: 1216, batch_size: 1 } },+ '6': { class_type: 'CLIPTextEncode', inputs: { text: 'a red fox in snow', clip: ['10', 1] } },+ '7': { class_type: 'CLIPTextEncode', inputs: { text: 'blurry', clip: ['10', 1] } },+ '3': { class_type: 'KSampler', inputs: { seed: 42, steps: 30, cfg: 6.5, sampler_name: 'dpmpp_2m', scheduler: 'karras', denoise: 1, model: ['10', 0], positive: ['6', 0], negative: ['7', 0], latent_image: ['5', 0] } },+ '9': { class_type: 'SaveImage', inputs: { filename_prefix: 'LU', images: ['8', 0] } },+})++/** The Flux shape: custom sampler, guidance node, prompt from a text primitive. */+const CUSTOM_GRAPH = JSON.stringify({+ '12': { class_type: 'UNETLoader', inputs: { unet_name: 'flux1-dev-fp8.safetensors', weight_dtype: 'default' } },+ '40': { class_type: 'PrimitiveStringMultiline', inputs: { value: 'portrait, soft light' } },+ '6': { class_type: 'CLIPTextEncode', inputs: { text: ['40', 0], clip: ['11', 0] } },+ '26': { class_type: 'FluxGuidance', inputs: { guidance: 3.5, conditioning: ['6', 0] } },+ '22': { class_type: 'BasicGuider', inputs: { model: ['12', 0], conditioning: ['26', 0] } },+ '25': { class_type: 'RandomNoise', inputs: { noise_seed: 7 } },+ '16': { class_type: 'KSamplerSelect', inputs: { sampler_name: 'euler' } },+ '17': { class_type: 'BasicScheduler', inputs: { scheduler: 'simple', steps: 20, denoise: 1, model: ['12', 0] } },+ '27': { class_type: 'EmptySD3LatentImage', inputs: { width: 1024, height: 1024, batch_size: 1 } },+ '13': { class_type: 'SamplerCustomAdvanced', inputs: { noise: ['25', 0], guider: ['22', 0], sampler: ['16', 0], sigmas: ['17', 0], latent_image: ['27', 0] } },+})++const file = (extra: Partial<ScannedFile> = {}): ScannedFile => ({+ filename: 'LU_00001_.png', subfolder: '', kind: 'image', modifiedMs: 1_700_000_000_000, bytes: 1000, width: 512, height: 768, ...extra,+})++describe('the graph ComfyUI stored', () => {+ it('KSampler: prompt, negative, settings, model, size and LoRA', () => {+ expect(madeWithFromComfyGraph(KSAMPLER_GRAPH)).toEqual({+ prompt: 'a red fox in snow', negativePrompt: 'blurry', seed: 42, steps: 30, cfgScale: 6.5,+ sampler: 'dpmpp_2m', scheduler: 'karras', model: 'juggernautXL_v9.safetensors', width: 832, height: 1216,+ loras: [{ name: 'style.safetensors', strength: 0.8 }],+ })+ })++ it('custom sampler: through the guider and the guidance node to the text primitive', () => {+ expect(madeWithFromComfyGraph(CUSTOM_GRAPH)).toEqual({+ prompt: 'portrait, soft light', seed: 7, steps: 20, sampler: 'euler', scheduler: 'simple',+ model: 'flux1-dev-fp8.safetensors', width: 1024, height: 1024,+ })+ })++ it('anything else is no graph', () => {+ expect(madeWithFromComfyGraph('not json')).toBeNull()+ expect(madeWithFromComfyGraph('[1,2]')).toBeNull()+ expect(madeWithFromComfyGraph('{}')).toBeNull()+ })+})++describe('A1111 parameters', () => {+ it('prompt over several lines, negative, settings', () => {+ const text = 'a cat\non a roof\nNegative prompt: ugly, blurry\nSteps: 25, Sampler: DPM++ 2M, Schedule type: Karras, CFG scale: 7, Seed: 123, Size: 512x768, Model: dreamshaper_8'+ expect(madeWithFromParameters(text)).toEqual({+ prompt: 'a cat\non a roof', negativePrompt: 'ugly, blurry', steps: 25, sampler: 'DPM++ 2M', scheduler: 'Karras',+ cfgScale: 7, seed: 123, width: 512, height: 768, model: 'dreamshaper_8',+ })+ })++ it('only a prompt', () => {+ expect(madeWithFromParameters('just words')).toEqual({ prompt: 'just words' })+ })+})++describe('entries', () => {+ it('a picture with its graph, and one that says nothing', () => {+ const made = entryFromScan(file({ prompt: KSAMPLER_GRAPH }))+ expect(made).toMatchObject({ prompt: 'a red fox in snow', model: 'juggernautXL_v9.safetensors', modelType: 'sdxl', width: 832, comfyType: 'output', createdAt: 1_700_000_000_000 })+ expect(made.label).toBeUndefined()+ const bare = entryFromScan(file({ filename: 'clip.mp4', subfolder: 'video', kind: 'video', width: null, height: null }))+ expect(bare).toMatchObject({ type: 'video', prompt: '', label: 'clip.mp4', subfolder: 'video', modelType: 'unknown' })+ })++ it('the same file is the same id, another file another', () => {+ expect(restoredId('', 'a.png')).toBe(restoredId('', 'a.png'))+ expect(restoredId('', 'a.png')).not.toBe(restoredId('x', 'a.png'))+ })+})++describe('restoreFromOutputFolder', () => {+ const listed = (n: number): GalleryItem => ({+ id: `g${n}`, type: 'image', filename: `LU_${n}.png`, subfolder: '', prompt: 'kept', negativePrompt: '', model: 'm',+ modelType: 'sdxl', seed: 1, steps: 1, cfgScale: 1, sampler: 's', scheduler: 's', width: 1, height: 1, batchSize: 1, createdAt: n,+ })+ beforeEach(() => { useCreateStore.setState({ gallery: [listed(2), listed(1)] }) })++ it('adds the files the gallery does not list, keeps the entries it has, and a second run adds nothing', async () => {+ const files = [file({ filename: 'LU_1.png' }), file({ filename: 'LU_9.png', prompt: KSAMPLER_GRAPH }), file({ filename: 'v.mp4', kind: 'video' })]+ const scan = async () => ({ reachable: true, folder: '/c/output', files, truncated: false })+ const first = await restoreFromOutputFolder(scan)+ expect(first).toMatchObject({ reachable: true, found: 3, added: 2, withPrompt: 1 })+ const g1 = useCreateStore.getState().gallery.find((g) => g.filename === 'LU_1.png')!+ expect(g1).toMatchObject({ id: 'g1', prompt: 'kept' })+ expect(useCreateStore.getState().gallery).toHaveLength(4)+ expect((await restoreFromOutputFolder(scan)).added).toBe(0)+ })++ it('says so when the folder cannot be read', async () => {+ const r = await restoreFromOutputFolder(async () => ({ reachable: false, folder: '', files: [], truncated: false }))+ expect(r).toMatchObject({ reachable: false, added: 0 })+ expect(useCreateStore.getState().gallery).toHaveLength(2)+ })+})diff --git a/src/lib/gallery-persist.ts b/src/lib/gallery-persist.tsindex 67509737..d22ee7bd 100644--- a/src/lib/gallery-persist.ts+++ b/src/lib/gallery-persist.ts@@ -1,6 +1,6 @@// The gallery list on IndexedDB, without the cap (3.1.0, C27).//-// boromirofgeo, Discord 05.11. and 06.11.2026: "200 not enough", after the+// Discord 05.11. and 06.11.2026: "200 not enough", after the// gallery had dropped his sorted folders (D3b). Until 3.1.0 the list sat in the// create-store blob in localStorage, about 5 MB for the whole origin, so it was// cut at 200 unsorted entries.@@ -317,7 +317,7 @@ export async function startGalleryPersistence<T extends StoredEntry>(deps: Galle}} catch (err) {// No copy, no move: the old way holds until a copy can be made.- log.error('[gallery] could not keep a copy of the old gallery list, not moving it yet', { err: String(err) })+ log.error('[gallery] could not keep a copy of the old gallery list, the move waits for the next start', { err: String(err) })state = 'unreadable'return handle}diff --git a/src/lib/gallery-restore.ts b/src/lib/gallery-restore.tsnew file mode 100644index 00000000..286d4fca--- /dev/null+++ b/src/lib/gallery-restore.ts@@ -0,0 +1,277 @@+// "Restore from the output folder" (3.1.0, C27, Discord D2: a user lost+// the gallery while the files were still in ComfyUI's output folder).+//+// The scan (Rust, commands/gallery_files.rs scan_comfy_output) lists the+// media files and hands over the PNG text chunks. This turns them into gallery+// entries: the prompt and the settings out of the graph ComfyUI stored in the+// picture ("prompt", the API graph it ran) or out of A1111-style "parameters".+// Where a file says nothing, the entry carries its file name and an empty+// prompt; the picture itself is what matters.+//+// The store adds only files it does not list yet (restoreGalleryItems), so+// running this twice adds nothing the second time.++import { backendCall } from '../api/backend'+import { classifyModel } from '../api/comfyui'+import { useCreateStore, type GalleryItem } from '../stores/createStore'++/** One file of the scan, as the Rust command sends it. */+export interface ScannedFile {+ filename: string+ subfolder: string+ kind: 'image' | 'video' | 'audio'+ modifiedMs: number+ bytes: number+ width?: number | null+ height?: number | null+ prompt?: string | null+ parameters?: string | null+}++export interface OutputScan {+ reachable: boolean+ folder: string+ files: ScannedFile[]+ truncated: boolean+}++/** What a picture's own text says about how it was made. */+export interface MadeWith {+ prompt: string+ negativePrompt: string+ model: string+ seed: number+ steps: number+ cfgScale: number+ sampler: string+ scheduler: string+ width: number+ height: number+ loras?: { name: string; strength: number }[]+}++type Graph = Record<string, { class_type?: unknown; inputs?: Record<string, unknown> }>++const isLink = (v: unknown): v is [string | number, number] =>+ Array.isArray(v) && v.length === 2 && (typeof v[0] === 'string' || typeof v[0] === 'number') && typeof v[1] === 'number'++const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)+const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)++function node(graph: Graph, link: unknown) {+ return isLink(link) ? graph[String(link[0])] : undefined+}++/** The inputs that carry conditioning on, in the order they are followed. */+const CONDITIONING_INPUTS = ['conditioning', 'conditioning_1', 'conditioning_to', 'positive', 'clip_conditioning']+/** The inputs a text encoder takes its words from. */+const TEXT_INPUTS = ['text', 'prompt', 'text_g', 'clip_l', 't5xxl', 'value', 'string', 'text_a']++/** The text at the end of a link: a string widget, or a node that holds one. */+function textOf(graph: Graph, v: unknown, depth = 0): string | null {+ if (typeof v === 'string') return v+ if (depth > 6) return null+ const n = node(graph, v)+ if (!n?.inputs) return null+ for (const k of TEXT_INPUTS) {+ const t = textOf(graph, n.inputs[k], depth + 1)+ if (t !== null) return t+ }+ return null+}++/** The prompt of a conditioning link: through guidance and combine nodes to the encoder. */+function promptOf(graph: Graph, link: unknown, depth = 0): string | null {+ const n = node(graph, link)+ if (!n?.inputs || depth > 8) return null+ const type = String(n.class_type ?? '')+ if (/TextEncode|CLIPText|PromptEncode/i.test(type)) {+ for (const k of TEXT_INPUTS) {+ const t = textOf(graph, n.inputs[k])+ if (t !== null && t.trim() !== '') return t+ }+ return null+ }+ for (const k of CONDITIONING_INPUTS) {+ if (isLink(n.inputs[k])) {+ const t = promptOf(graph, n.inputs[k], depth + 1)+ if (t !== null) return t+ }+ }+ return null+}++const SAMPLER_TYPES = /^(KSampler|KSamplerAdvanced|SamplerCustom|SamplerCustomAdvanced|KSampler \(Efficient\))$/++/** The settings a ComfyUI API graph ran with. Null when it is not one. */+export function madeWithFromComfyGraph(json: string): Partial<MadeWith> | null {+ let graph: Graph+ try {+ const parsed: unknown = JSON.parse(json)+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null+ graph = parsed as Graph+ } catch {+ return null+ }+ const nodes = Object.values(graph).filter((n) => n && typeof n === 'object' && n.inputs && typeof n.inputs === 'object')+ if (nodes.length === 0) return null+ const out: Partial<MadeWith> = {}+ const sampler = nodes.find((n) => SAMPLER_TYPES.test(String(n.class_type ?? '')))+ if (sampler?.inputs) {+ const i = sampler.inputs+ out.seed = num(i.seed) ?? num(i.noise_seed) ?? undefined+ out.steps = num(i.steps) ?? undefined+ out.cfgScale = num(i.cfg) ?? undefined+ out.sampler = str(i.sampler_name) ?? undefined+ out.scheduler = str(i.scheduler) ?? undefined+ let positive: unknown = i.positive+ let negative: unknown = i.negative+ // The custom sampler: noise, guider, sampler and sigmas are nodes of their own.+ const noise = node(graph, i.noise)?.inputs+ if (noise) out.seed ??= num(noise.noise_seed) ?? num(noise.seed) ?? undefined+ const guider = node(graph, i.guider)?.inputs+ if (guider) {+ out.cfgScale ??= num(guider.cfg) ?? undefined+ positive ??= guider.positive ?? guider.conditioning+ negative ??= guider.negative+ }+ const pick = node(graph, i.sampler)?.inputs+ if (pick) out.sampler ??= str(pick.sampler_name) ?? undefined+ const sigmas = node(graph, i.sigmas)?.inputs+ if (sigmas) {+ out.steps ??= num(sigmas.steps) ?? undefined+ out.scheduler ??= str(sigmas.scheduler) ?? undefined+ }+ const p = promptOf(graph, positive)+ if (p !== null) out.prompt = p+ const n = promptOf(graph, negative)+ if (n !== null) out.negativePrompt = n+ }+ if (out.prompt === undefined) {+ // No sampler found, or no link to follow: the first text encoder with words.+ for (const n of nodes) {+ if (!/TextEncode|CLIPText/i.test(String(n.class_type ?? ''))) continue+ const t = TEXT_INPUTS.map((k) => textOf(graph, n.inputs?.[k])).find((x) => x !== null && x.trim() !== '')+ if (t) { out.prompt = t; break }+ }+ }+ for (const n of nodes) {+ const i = n.inputs!+ const model = str(i.ckpt_name) ?? str(i.unet_name)+ if (model && out.model === undefined) out.model = model+ const lat = /Empty.*Latent/i.test(String(n.class_type ?? ''))+ if (lat && out.width === undefined && num(i.width) && num(i.height)) {+ out.width = num(i.width)!+ out.height = num(i.height)!+ }+ const lora = str(i.lora_name)+ if (lora && /Lora/i.test(String(n.class_type ?? ''))) {+ ;(out.loras ??= []).push({ name: lora, strength: num(i.strength_model) ?? num(i.strength) ?? 1 })+ }+ }+ for (const k of Object.keys(out) as (keyof MadeWith)[]) if (out[k] === undefined) delete out[k]+ return out+}++/** The settings of A1111-style "parameters": prompt, "Negative prompt:", then "Key: value, ...". */+export function madeWithFromParameters(text: string): Partial<MadeWith> | null {+ if (!text.trim()) return null+ const lines = text.replace(/\r\n/g, '\n').split('\n')+ let last = lines.length - 1+ while (last > 0 && !lines[last].trim()) last--+ const settingsLine = /(^|,\s*)Steps:\s*\d+/.test(lines[last]) ? lines[last] : ''+ const body = settingsLine ? lines.slice(0, last) : lines+ const negAt = body.findIndex((l) => l.startsWith('Negative prompt:'))+ const out: Partial<MadeWith> = {+ prompt: (negAt >= 0 ? body.slice(0, negAt) : body).join('\n').trim(),+ }+ if (negAt >= 0) out.negativePrompt = body.slice(negAt).join('\n').replace(/^Negative prompt:\s*/, '').trim()+ const fields = new Map<string, string>()+ for (const m of settingsLine.matchAll(/([A-Za-z][\w ]*?):\s*("(?:[^"\\]|\\.)*"|[^,]*)/g)) fields.set(m[1].trim().toLowerCase(), m[2].trim())+ const n = (k: string) => { const v = Number(fields.get(k)); return Number.isFinite(v) && fields.has(k) ? v : undefined }+ out.steps = n('steps')+ out.cfgScale = n('cfg scale')+ out.seed = n('seed')+ out.sampler = fields.get('sampler')+ out.scheduler = fields.get('schedule type')+ out.model = fields.get('model')+ const size = /^(\d+)x(\d+)$/.exec(fields.get('size') ?? '')+ if (size) { out.width = Number(size[1]); out.height = Number(size[2]) }+ for (const k of Object.keys(out) as (keyof MadeWith)[]) if (out[k] === undefined) delete out[k]+ return out+}++/** A short stable id for a file, so the same file is the same entry every time. */+export function restoredId(subfolder: string, filename: string): string {+ let h1 = 0x811c9dc5+ let h2 = 0x01000193+ const s = `${subfolder}/${filename}`+ for (let i = 0; i < s.length; i++) {+ const c = s.charCodeAt(i)+ h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0+ h2 = Math.imul(h2 ^ c, 0x5bd1e995) >>> 0+ }+ return `out-${h1.toString(36)}${h2.toString(36)}`+}++/** The gallery entry for one scanned file. */+export function entryFromScan(f: ScannedFile): GalleryItem {+ const made = (f.prompt ? madeWithFromComfyGraph(f.prompt) : null) ?? (f.parameters ? madeWithFromParameters(f.parameters) : null) ?? {}+ const model = made.model ?? ''+ const item: GalleryItem = {+ id: restoredId(f.subfolder, f.filename),+ type: f.kind,+ filename: f.filename,+ subfolder: f.subfolder,+ comfyType: 'output',+ prompt: made.prompt ?? '',+ negativePrompt: made.negativePrompt ?? '',+ model,+ modelType: model ? classifyModel(model) : 'unknown',+ seed: made.seed ?? 0,+ steps: made.steps ?? 0,+ cfgScale: made.cfgScale ?? 0,+ sampler: made.sampler ?? '',+ scheduler: made.scheduler ?? '',+ width: made.width ?? f.width ?? 0,+ height: made.height ?? f.height ?? 0,+ batchSize: 1,+ createdAt: f.modifiedMs || Date.now(),+ }+ if (made.loras?.length) item.loras = made.loras+ // Without a prompt the tile and the details name the file.+ if (!item.prompt) item.label = f.filename+ return item+}++export interface RestoreResult {+ /** False: LU cannot read this ComfyUI's output folder. */+ reachable: boolean+ folder: string+ /** Media files found. */+ found: number+ /** Entries the gallery did not have and has now. */+ added: number+ /** Found entries that brought their prompt along. */+ withPrompt: number+ /** The scan stopped at its limit. */+ truncated: boolean+}++/** Scan the output folder and add what the gallery does not list yet. */+export async function restoreFromOutputFolder(+ scan: () => Promise<OutputScan> = () => backendCall<OutputScan>('scan_comfy_output'),+): Promise<RestoreResult> {+ const result = await scan()+ if (!result?.reachable) return { reachable: false, folder: result?.folder ?? '', found: 0, added: 0, withPrompt: 0, truncated: false }+ const items = result.files.map(entryFromScan)+ const added = useCreateStore.getState().restoreGalleryItems(items)+ return {+ reachable: true,+ folder: result.folder,+ found: items.length,+ added,+ withPrompt: items.filter((g) => g.prompt).length,+ truncated: result.truncated,+ }+}diff --git a/src/lib/gallery-tags.ts b/src/lib/gallery-tags.tsindex c25a1cb2..7e3c7aad 100644--- a/src/lib/gallery-tags.ts+++ b/src/lib/gallery-tags.ts@@ -1,5 +1,5 @@-// Hide and tag gallery entries (3.1.0, Discord D27, promised 05.11.2026 to-// boromirofgeo: "hide from gallery" and tags).+// Hide and tag gallery entries (3.1.0, Discord D27, promised 05.11.2026:+// "hide from gallery" and tags).//// Both are labels inside the app, like folders (lib/gallery-folders.ts):// hiding an entry takes it out of the list and keeps its file, its prompt anddiff --git a/src/lib/remote-create-lanes.ts b/src/lib/remote-create-lanes.tsindex 4d09d834..34b2b96f 100644--- a/src/lib/remote-create-lanes.ts+++ b/src/lib/remote-create-lanes.ts@@ -421,9 +421,12 @@ export const FROM_YOUR_PHONE = 'From your phone'export function galleryForRemote(items: readonly {id: string; type: 'image' | 'video' | 'audio'; filename: string; subfolder: string; comfyType?: stringlocalPath?: string; remoteUrl?: string; prompt: string; model: string; createdAt: number; label?: string+ hidden?: boolean}[]): GalleryOut[] {const out: GalleryOut[] = []for (const it of items) {+ // Hidden on the computer (D27, 3.1.0): not shown on the phone either.+ if (it.hidden) continueconst base = { key: it.id, media: it.type, prompt: it.prompt ?? '', model: it.model ?? '', created_at: it.createdAt ?? 0, from_phone: it.label === FROM_YOUR_PHONE }if (it.localPath) out.push({ ...base, path: it.localPath })else if (!it.remoteUrl && it.filename && (it.comfyType ?? 'output') === 'output') out.push({ ...base, comfy_filename: it.filename, comfy_subfolder: it.subfolder ?? '' })diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex b31bd0af..859bc0b3 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -112,15 +112,15 @@ export const STORE_KEYS = [// (at most SWITCHED_MAX ids)// Guard: src/mobile/boot/__tests__/local-keys-backup.test.ts'lu-mobile-thinking-default-v1', 'lu-mobile-report-queue', 'lu-mobile-switched-under-answer',+ // 3.1.0 (C27): the gallery list without the cap, on IndexedDB+ // (lib/gallery-persist.ts). The create-store blob keeps only a short copy.+ 'lu-gallery',// L5, check of package 17 (mobile-docs/r41/funde.md). When the settings were// last written (boot/settings-durable.ts). The start compares it with the// stamp in localStorage when the copy in IndexedDB is gone, and takes the// settings of this backup when they are newer. Listed last, so a snapshot// reads it after the settings it stamps.'lu-mobile-settings-stamp',- // 3.1.0 (C27): the gallery list without the cap, on IndexedDB- // (lib/gallery-persist.ts). The create-store blob keeps only a short copy.- 'lu-gallery',]/** The phone keys of STORE_KEYS, for the tests that hold the two lists together. */