Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Add send-to-image-to-image action and a searchable gallery picker
[._.]/ Adam Eivy8e028ce51a18
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0b1899481a..f88a4d952c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -17,6 +17,7 @@- **[issue-912] Regenerate gallery images to defeat SynthID watermarks** — Generated images gain a "Regenerate" action in the lightbox, next to "Clean", whenever a local FLUX image generator is installed. The existing Clean only strips embedded provenance metadata and can't touch SynthID — Google's invisible per-pixel watermark — which survives by design. Regenerate is the honest defeat path: it round-trips the picture through a local FLUX model so the watermark signal is overwritten by fresh sampling, while keeping the change to the image as small as possible — it uses no prompt and a low denoise, so the result is a near-faithful copy of the original rather than a reinterpretation. It runs entirely on-device, is never applied automatically, and saves the result as a new variant beside the original (which is kept); the lightbox's variant switch lets you toggle between them. Very large source images (e.g. 4K) are handled by regenerating at a model-friendly resolution and scaling the clean result back up to the original size, so a big image no longer stalls the pass. The Regenerate button opens an inline panel with a strength slider (lower = more faithful) and an optional prompt field, so you can dial in how much the pass changes the image — or paste a prompt for a creative re-roll — right from the lightbox.- **[issue-877] City records its history for a future timeline scrubber** — The City now quietly snapshots its own state on a schedule (every 5 minutes by default), capturing which apps are online, how many agents are working, system health, and the other landmark readouts. These frames accumulate locally — never synced to peers — so an upcoming timeline view can let you scrub back and watch the city change over time. There's nothing to interact with yet; this is the recording groundwork. You can tune the capture interval, set how many frames to keep, or turn it off in settings.- **[issue-967] Scrub back through City history** — A new "History" button on the City opens a playback timeline: drag the slider to any past moment, or hit play to watch your city evolve at 1×/2×/4× (←/→ step a frame, Esc exits). As you move through time, buildings rise in (construction) when an app first appeared, scale away (teardown) when one was gone, and recolor as their status changed; agent activity, automation state, and backup status follow each recorded moment, and a readout shows that moment's captured CPU/memory/disk, task, agent, peer, and review numbers. Districts whose detail the snapshots don't capture (the task, federation, health, memory, goals, Jira, and activity landmarks) keep showing live data and are flagged as such in the timeline bar, so a historical view never quietly passes off "now" as "then."+- **Send any image straight into image-to-image, and pick a source from your gallery visually** — Image cards and the image lightbox gain a "Send to i2i" action next to "Remix": click it and the Image Gen page opens with that picture already loaded as the image-to-image source and its prompt + render settings filled in, ready to iterate (it switches you to an image-to-image-capable backend if needed). Image-to-image now works on the Codex backend too, not just local FLUX — the init-image picker appears for both. And the picker is no longer upload-only: a new "Browse gallery" button opens a searchable visual picker of everything you've generated, with the same prompt/model/seed/LoRA search as Media History, so you can reuse an existing image without downloading and re-uploading it. The FLUX.2 multi-reference slots get the same "Gallery" pick option alongside upload.## Changeddiff --git a/client/src/components/imageGen/GalleryImagePicker.jsx b/client/src/components/imageGen/GalleryImagePicker.jsxnew file mode 100644index 0000000000..e9cad2698b--- /dev/null+++ b/client/src/components/imageGen/GalleryImagePicker.jsx@@ -0,0 +1,118 @@+// Visual picker over the local image gallery — the "search + grid" alternative+// to the plain file `<input>` in InitImagePicker. Opens as a modal, fetches the+// gallery on open (GET /api/image-gen/gallery via listImageGallery), and lets+// the user search by prompt/model/seed/LoRA/etc. (shared lib/mediaSearch logic,+// same as MediaHistory) and click a thumbnail to pick it. Calls `onSelect(item)`+// with the normalized media item (item.filename + item.previewUrl) then closes.+//+// Local gallery only — no external/web search (deliberate, see plan).++import { useEffect, useMemo, useState } from 'react';+import { Search, X, RefreshCw } from 'lucide-react';+import Modal from '../ui/Modal';+import MediaCard from '../media/MediaCard';+import { normalizeImage } from '../media/normalize';+import { listImageGallery } from '../../services/apiImageVideo';+import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';++export default function GalleryImagePicker({ open, onClose, onSelect }) {+ const [items, setItems] = useState([]);+ const [loading, setLoading] = useState(false);+ const [query, setQuery] = useState('');++ // Fetch the gallery each time the picker opens so newly generated images show+ // up without a page reload. Reset the search on close so a re-open starts clean.+ useEffect(() => {+ if (!open) { setQuery(''); return; }+ let cancelled = false;+ setLoading(true);+ listImageGallery()+ .then((images) => {+ if (cancelled) return;+ const normalized = (Array.isArray(images) ? images : [])+ .map(normalizeImage)+ // Skip hidden images — the picker is for reuse, not gallery management.+ .filter((it) => !it.hidden);+ setItems(normalized);+ })+ .catch(() => { if (!cancelled) setItems([]); })+ .finally(() => { if (!cancelled) setLoading(false); });+ return () => { cancelled = true; };+ }, [open]);++ // Cache each item's haystack per fetched list; keystrokes then only re-run the+ // cheap token match instead of rebuilding every haystack (mirrors MediaHistory).+ const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);+ const tokens = useMemo(() => tokenizeQuery(query), [query]);+ const filtered = useMemo(+ () => tokens.length === 0 ? items : items.filter((_, idx) => matchHaystack(haystacks[idx], tokens)),+ [items, haystacks, tokens],+ );++ return (+ <Modal+ open={open}+ onClose={onClose}+ size="3xl"+ panelClassName="bg-port-card border border-port-border rounded-xl max-h-[85vh] flex flex-col"+ ariaLabel="Pick an image from your gallery"+ >+ <div className="flex items-center justify-between gap-3 p-3 border-b border-port-border">+ <h2 className="text-sm font-medium text-white shrink-0">Pick from gallery</h2>+ <div className="relative flex-1 max-w-md">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />+ <input+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search prompt, model, seed, LoRA…"+ className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ autoFocus+ />+ {query && (+ <button+ type="button"+ onClick={() => setQuery('')}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"+ aria-label="Clear search"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ <button+ type="button"+ onClick={onClose}+ className="shrink-0 p-1.5 text-gray-400 hover:text-white rounded"+ aria-label="Close"+ >+ <X className="w-4 h-4" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto p-3">+ {loading ? (+ <div className="flex items-center justify-center gap-2 text-xs text-gray-400 py-10">+ <RefreshCw className="w-4 h-4 animate-spin" /> Loading gallery…+ </div>+ ) : filtered.length === 0 ? (+ <div className="text-xs text-gray-500 py-10 text-center">+ {items.length === 0 ? 'No images in your gallery yet.' : 'No images match your search.'}+ </div>+ ) : (+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">+ {filtered.map((item) => (+ <MediaCard+ key={item.key}+ item={item}+ hideActions+ showCollectionMenu={false}+ onClick={() => { onSelect?.(item); onClose?.(); }}+ />+ ))}+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/client/src/components/imageGen/GalleryImagePicker.test.jsx b/client/src/components/imageGen/GalleryImagePicker.test.jsxnew file mode 100644index 0000000000..d941127893--- /dev/null+++ b/client/src/components/imageGen/GalleryImagePicker.test.jsx@@ -0,0 +1,58 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import GalleryImagePicker from './GalleryImagePicker';++const listImageGallery = vi.fn();+vi.mock('../../services/apiImageVideo', () => ({+ listImageGallery: (...args) => listImageGallery(...args),+}));++const GALLERY = [+ { filename: 'neon.png', path: '/data/images/neon.png', prompt: 'a neon sunset', modelId: 'flux2', seed: 1 },+ { filename: 'forest.png', path: '/data/images/forest.png', prompt: 'a quiet forest', modelId: 'sdxl', seed: 2 },+];++describe('GalleryImagePicker', () => {+ beforeEach(() => {+ listImageGallery.mockReset();+ listImageGallery.mockResolvedValue(GALLERY);+ });++ it('does not fetch or render while closed', () => {+ render(<GalleryImagePicker open={false} onClose={vi.fn()} onSelect={vi.fn()} />);+ expect(listImageGallery).not.toHaveBeenCalled();+ expect(screen.queryByText(/Pick from gallery/i)).toBeNull();+ });++ it('fetches and renders gallery images on open', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ expect(listImageGallery).toHaveBeenCalledTimes(1);+ expect(await screen.findByAltText('a neon sunset')).toBeTruthy();+ expect(screen.getByAltText('a quiet forest')).toBeTruthy();+ });++ it('filters by query across prompt + model (AND tokens)', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ fireEvent.change(screen.getByPlaceholderText(/Search prompt/i), { target: { value: 'forest sdxl' } });+ await waitFor(() => expect(screen.queryByAltText('a neon sunset')).toBeNull());+ expect(screen.getByAltText('a quiet forest')).toBeTruthy();+ });++ it('calls onSelect with the normalized item and closes on tile click', async () => {+ const onSelect = vi.fn();+ const onClose = vi.fn();+ render(<GalleryImagePicker open onSelect={onSelect} onClose={onClose} />);+ const tile = await screen.findByAltText('a neon sunset');+ fireEvent.click(tile);+ expect(onSelect).toHaveBeenCalledTimes(1);+ expect(onSelect.mock.calls[0][0]).toMatchObject({ filename: 'neon.png', previewUrl: '/data/images/neon.png' });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('shows an empty state when the gallery is empty', async () => {+ listImageGallery.mockResolvedValue([]);+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ expect(await screen.findByText(/No images in your gallery yet/i)).toBeTruthy();+ });+});diff --git a/client/src/components/imageGen/InitImagePicker.jsx b/client/src/components/imageGen/InitImagePicker.jsxindex 542ad8cd34..93fd90fcbf 100644--- a/client/src/components/imageGen/InitImagePicker.jsx+++ b/client/src/components/imageGen/InitImagePicker.jsx@@ -9,7 +9,7 @@// `editOnly` flips the label copy/styling: edit-only models need a source// image (shown as a required warning), regular i2i is optional.-import { Image as ImageIcon, X } from 'lucide-react';+import { Image as ImageIcon, Images, X } from 'lucide-react';export default function InitImagePicker({initImage,@@ -17,15 +17,22 @@ export default function InitImagePicker({onStrengthChange,onPick,onClear,+ onBrowse,editOnly = false,+ backend = 'local',disabled = false,}) {+ // i2i runs on both local (FLUX) and codex; the "Flux only" caveat applies only+ // to the local backend (non-FLUX local models ignore the init image).+ const subtitle = editOnly+ ? '(required — this model edits an existing image)'+ : backend === 'codex' ? '(image-to-image)' : '(image-to-image — Flux only)';return (<div><label className="block text-xs font-medium text-gray-400 mb-1">{editOnly ? 'Source image' : 'Init image'}{' '}<span className={`font-normal ${editOnly ? 'text-port-warning' : 'text-gray-500'}`}>- {editOnly ? '(required — this model edits an existing image)' : '(image-to-image — Flux only)'}+ {subtitle}</span></label>{initImage.previewUrl ? (@@ -48,7 +55,20 @@ export default function InitImagePicker({</button></div><div className="flex-1 min-w-0 space-y-1">- <div className="text-xs text-gray-400 truncate" title={initImage.name}>{initImage.name}</div>+ <div className="flex items-center gap-2 min-w-0">+ <span className="text-xs text-gray-400 truncate" title={initImage.name}>{initImage.name}</span>+ {onBrowse && (+ <button+ type="button"+ onClick={onBrowse}+ disabled={disabled}+ className="shrink-0 inline-flex items-center gap-1 text-[10px] text-port-accent hover:text-white disabled:opacity-50"+ title="Pick a different image from your gallery"+ >+ <Images className="w-3 h-3" /> Gallery+ </button>+ )}+ </div><label className="block text-[11px] text-gray-500">Strength {initImageStrength.toFixed(2)}<input@@ -62,11 +82,24 @@ export default function InitImagePicker({</div></div>) : (- <label className="flex items-center justify-center gap-2 w-full px-3 py-2 border border-dashed border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent cursor-pointer transition-colors">- <ImageIcon className="w-4 h-4" />- Upload image to remix (PNG/JPG/WebP)- <input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={onPick} disabled={disabled} />- </label>+ <div className="flex flex-col sm:flex-row gap-2">+ <label className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-dashed border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent cursor-pointer transition-colors">+ <ImageIcon className="w-4 h-4" />+ Upload (PNG/JPG/WebP)+ <input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={onPick} disabled={disabled} />+ </label>+ {onBrowse && (+ <button+ type="button"+ onClick={onBrowse}+ disabled={disabled}+ className="flex-1 flex items-center justify-center gap-2 px-3 py-2 border border-port-border rounded-lg text-xs text-gray-400 hover:text-white hover:border-port-accent transition-colors disabled:opacity-50"+ >+ <Images className="w-4 h-4" />+ Browse gallery+ </button>+ )}+ </div>)}</div>);diff --git a/client/src/components/imageGen/InitImagePicker.test.jsx b/client/src/components/imageGen/InitImagePicker.test.jsxindex b388b59960..5e33d03403 100644--- a/client/src/components/imageGen/InitImagePicker.test.jsx+++ b/client/src/components/imageGen/InitImagePicker.test.jsx@@ -16,10 +16,54 @@ describe('InitImagePicker', () => {onClear={vi.fn()}/>,);- expect(screen.getByText(/Upload image to remix/i)).toBeTruthy();+ expect(screen.getByText(/Upload \(PNG\/JPG\/WebP\)/i)).toBeTruthy();expect(screen.getByText(/image-to-image — Flux only/i)).toBeTruthy();});+ it('drops the "Flux only" caveat on the codex backend', () => {+ render(+ <InitImagePicker+ initImage={EMPTY}+ initImageStrength={0.4}+ onStrengthChange={vi.fn()}+ onPick={vi.fn()}+ onClear={vi.fn()}+ backend="codex"+ />,+ );+ expect(screen.getByText('(image-to-image)')).toBeTruthy();+ expect(screen.queryByText(/Flux only/i)).toBeNull();+ });++ it('renders a Browse gallery button when onBrowse is provided and fires it', () => {+ const onBrowse = vi.fn();+ render(+ <InitImagePicker+ initImage={EMPTY}+ initImageStrength={0.4}+ onStrengthChange={vi.fn()}+ onPick={vi.fn()}+ onClear={vi.fn()}+ onBrowse={onBrowse}+ />,+ );+ fireEvent.click(screen.getByText(/Browse gallery/i));+ expect(onBrowse).toHaveBeenCalledTimes(1);+ });++ it('omits the Browse gallery button when onBrowse is absent', () => {+ render(+ <InitImagePicker+ initImage={EMPTY}+ initImageStrength={0.4}+ onStrengthChange={vi.fn()}+ onPick={vi.fn()}+ onClear={vi.fn()}+ />,+ );+ expect(screen.queryByText(/Browse gallery/i)).toBeNull();+ });+it('shows the required-source label and warning copy when editOnly', () => {render(<InitImagePickerdiff --git a/client/src/components/imageGen/ReferenceImagePicker.jsx b/client/src/components/imageGen/ReferenceImagePicker.jsxindex e3c64327c8..51b8b3944c 100644--- a/client/src/components/imageGen/ReferenceImagePicker.jsx+++ b/client/src/components/imageGen/ReferenceImagePicker.jsx@@ -14,13 +14,14 @@// `onPick(slotIndex, event)` receives the raw file-input change event so the// caller can run EXIF orientation normalization before storing the File.-import { Image as ImageIcon, X } from 'lucide-react';+import { Image as ImageIcon, Images, X } from 'lucide-react';export default function ReferenceImagePicker({referenceImages = [],onPick,onClear,onStrengthChange,+ onBrowse,disabled = false,}) {return (@@ -67,21 +68,34 @@ export default function ReferenceImagePicker({/></>) : (- <label- htmlFor={slotId}- className="flex flex-col items-center justify-center gap-1 h-[88px] border border-dashed border-port-border rounded text-[10px] text-gray-500 hover:text-white hover:border-port-accent cursor-pointer transition-colors"- >- <ImageIcon className="w-4 h-4" />- Add- <input- id={slotId}- type="file"- accept="image/png,image/jpeg,image/webp"- className="hidden"- onChange={(e) => onPick(i, e)}- disabled={disabled}- />- </label>+ <div className="flex flex-col gap-1">+ <label+ htmlFor={slotId}+ className="flex flex-col items-center justify-center gap-1 h-[64px] border border-dashed border-port-border rounded text-[10px] text-gray-500 hover:text-white hover:border-port-accent cursor-pointer transition-colors"+ >+ <ImageIcon className="w-4 h-4" />+ Upload+ <input+ id={slotId}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ className="hidden"+ onChange={(e) => onPick(i, e)}+ disabled={disabled}+ />+ </label>+ {onBrowse && (+ <button+ type="button"+ onClick={() => onBrowse(i)}+ disabled={disabled}+ className="flex items-center justify-center gap-1 h-[20px] border border-port-border rounded text-[10px] text-gray-500 hover:text-white hover:border-port-accent transition-colors disabled:opacity-50"+ title="Pick a reference image from your gallery"+ >+ <Images className="w-3 h-3" /> Gallery+ </button>+ )}+ </div>)}</div>);diff --git a/client/src/components/imageGen/ReferenceImagePicker.test.jsx b/client/src/components/imageGen/ReferenceImagePicker.test.jsxindex df462103cd..63744345b5 100644--- a/client/src/components/imageGen/ReferenceImagePicker.test.jsx+++ b/client/src/components/imageGen/ReferenceImagePicker.test.jsx@@ -6,20 +6,34 @@ const emptySlot = () => ({ file: null, previewUrl: null, strength: 1.0 });const fourEmpty = () => Array.from({ length: 4 }, emptySlot);describe('ReferenceImagePicker', () => {- it('renders an Add tile per empty slot', () => {+ it('renders an Upload tile per empty slot', () => {render(<ReferenceImagePicker referenceImages={fourEmpty()} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} />);- expect(screen.getAllByText('Add')).toHaveLength(4);+ expect(screen.getAllByText('Upload')).toHaveLength(4);expect(screen.getByText('Ref 1')).toBeTruthy();expect(screen.getByText('Ref 4')).toBeTruthy();});+ it('renders a per-slot Gallery button when onBrowse is set and fires it with the slot index', () => {+ const onBrowse = vi.fn();+ render(<ReferenceImagePicker referenceImages={fourEmpty()} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} onBrowse={onBrowse} />);+ const galleryButtons = screen.getAllByText('Gallery');+ expect(galleryButtons).toHaveLength(4);+ fireEvent.click(galleryButtons[2]);+ expect(onBrowse).toHaveBeenCalledWith(2);+ });++ it('omits the Gallery button when onBrowse is absent', () => {+ render(<ReferenceImagePicker referenceImages={fourEmpty()} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} />);+ expect(screen.queryByText('Gallery')).toBeNull();+ });+it('renders a thumbnail + strength slider for a populated slot', () => {const slots = fourEmpty();slots[1] = { file: null, previewUrl: 'blob:two', strength: 0.6 };render(<ReferenceImagePicker referenceImages={slots} onPick={vi.fn()} onClear={vi.fn()} onStrengthChange={vi.fn()} />);expect(screen.getByAltText('Reference 2')).toBeTruthy();expect(screen.getByText(/Strength 0.60/)).toBeTruthy();- expect(screen.getAllByText('Add')).toHaveLength(3);+ expect(screen.getAllByText('Upload')).toHaveLength(3);});it('fires onClear with the slot index', () => {diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsxindex 10598fe440..24245a3c95 100644--- a/client/src/components/media/MediaCard.jsx+++ b/client/src/components/media/MediaCard.jsx@@ -13,6 +13,7 @@ export default function MediaCard({onPreview,onClick, // overrides preview when set (e.g. stitch mode toggling selection)onRemix,+ onSendToImage,onSendToVideo,onContinue,onUpscale,@@ -120,6 +121,17 @@ export default function MediaCard({<Sparkles className="w-3 h-3 shrink-0" /> <span className="truncate">Remix</span></button>)}+ {!isVideo && onSendToImage && (+ <button+ type="button"+ onClick={() => onSendToImage(item)}+ className="shrink-0 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded flex items-center justify-center"+ title="Send to image-to-image"+ aria-label="Send to image-to-image"+ >+ <Wand2 className="w-3 h-3" />+ </button>+ )}{!isVideo && onSendToVideo && (<buttontype="button"diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 72e9ec9a6e..5bf3f22fb3 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -79,6 +79,7 @@ export default function MediaLightbox({item,onClose,onRemix,+ onSendToImage,onSendToVideo,onContinue,onClean,@@ -323,6 +324,7 @@ export default function MediaLightbox({isVideo={isVideo}onClose={onClose}onRemix={onRemix}+ onSendToImage={onSendToImage}onSendToVideo={onSendToVideo}onContinue={onContinue}onClean={onClean}@@ -370,7 +372,7 @@ function PeerNotes({ others }) {function SettingsPane({item, meta, isVideo,- onClose, onRemix, onSendToVideo, onContinue, onClean, onRegenerate, regenAvailable, regenBounds,+ onClose, onRemix, onSendToImage, onSendToVideo, onContinue, onClean, onRegenerate, regenAvailable, regenBounds,copy, onRefine,annotation, onAnnotationChange,variantGroup, onSelectVariant,@@ -625,6 +627,16 @@ function SettingsPane({<Sparkles className="w-3.5 h-3.5" /> Remix</button>)}+ {!isVideo && onSendToImage && (+ <button+ type="button"+ onClick={() => closeThenRun(onSendToImage)}+ title="Open this image in Image Gen as the image-to-image source"+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent/80 text-white hover:opacity-90 rounded"+ >+ <Wand2 className="w-3.5 h-3.5" /> Send to i2i+ </button>+ )}{!isVideo && onSendToVideo && (<buttontype="button"diff --git a/client/src/hooks/useMediaPreviewActions.js b/client/src/hooks/useMediaPreviewActions.jsindex 03318b5179..e39bab6a71 100644--- a/client/src/hooks/useMediaPreviewActions.js+++ b/client/src/hooks/useMediaPreviewActions.js@@ -4,6 +4,25 @@ import toast from '../components/ui/Toast';import { cleanGalleryImage, extractLastFrame } from '../services/apiImageVideo';import { VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';+// Common image render-setting params shared by the image branch of Remix and by+// Send-to-image-to-image — both open /media/image with the same fields prefilled+// and differ only in their discriminator param (`remix` vs `initImageFile`).+// `(no prompt)` is the metadata-sidecar placeholder for items that lost their+// prompt — skip it so the next render doesn't start with that literal.+function buildImageGenParams(item) {+ const params = new URLSearchParams();+ if (item.prompt && item.prompt !== '(no prompt)') params.set('prompt', item.prompt);+ if (item.negativePrompt) params.set('negativePrompt', item.negativePrompt);+ if (item.modelId) params.set('modelId', item.modelId);+ if (item.width) params.set('width', String(item.width));+ if (item.height) params.set('height', String(item.height));+ if (item.seed != null) params.set('seed', String(item.seed));+ if (item.steps) params.set('steps', String(item.steps));+ if (item.guidance != null) params.set('guidance', String(item.guidance));+ if (item.quantize) params.set('quantize', String(item.quantize));+ return params;+}+/*** Shared MediaPreview / MediaLightbox action handlers. The same four* callbacks (`onRemix`, `onSendToVideo`, `onContinue`, `onClean`) used to@@ -65,20 +84,24 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})navigate(`/media/video?${params}`);return;}- const params = new URLSearchParams();- if (item.prompt && item.prompt !== '(no prompt)') params.set('prompt', item.prompt);- if (item.negativePrompt) params.set('negativePrompt', item.negativePrompt);- if (item.modelId) params.set('modelId', item.modelId);- if (item.width) params.set('width', String(item.width));- if (item.height) params.set('height', String(item.height));- if (item.seed != null) params.set('seed', String(item.seed));- if (item.steps) params.set('steps', String(item.steps));- if (item.guidance != null) params.set('guidance', String(item.guidance));- if (item.quantize) params.set('quantize', String(item.quantize));+ const params = buildImageGenParams(item);if (item.filename) params.set('remix', item.filename);navigate(`/media/image?${params}`);}, [navigate]);+ // Send to image-to-image: open the Image Gen page with this image queued as+ // the i2i init image AND the prompt + render settings pre-filled (like Remix),+ // so the user lands in a full "iterate on this image" state. Images only — the+ // ImageGen page resolves `?initImageFile=<basename>` against the gallery and+ // nudges to an i2i-capable backend. Deliberately omits the `remix` param so it+ // reads as a distinct intent from plain Remix.+ const handleSendToImage = useCallback((item) => {+ if (!item?.filename || item.kind === 'video') return;+ const params = buildImageGenParams(item);+ params.set('initImageFile', item.filename);+ navigate(`/media/image?${params}`);+ }, [navigate]);+// Send to Video: open the Video Gen page with the image queued as the// i2v source. `negativePrompt` is resolved from any of the legacy aliases// (`raw.negativePrompt` / `raw.negative_prompt`) so older metadata still@@ -128,5 +151,5 @@ export default function useMediaPreviewActions({ onCleanComplete = null } = {})return cleaned;}, [onCleanComplete]);- return { handleRemix, handleSendToVideo, handleContinue, handleClean };+ return { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean };}diff --git a/client/src/hooks/useMediaPreviewActions.test.jsx b/client/src/hooks/useMediaPreviewActions.test.jsxnew file mode 100644index 0000000000..f2457d18f2--- /dev/null+++ b/client/src/hooks/useMediaPreviewActions.test.jsx@@ -0,0 +1,51 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook } from '@testing-library/react';+import useMediaPreviewActions from './useMediaPreviewActions';++const navigate = vi.fn();+vi.mock('react-router-dom', () => ({ useNavigate: () => navigate }));+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));+vi.mock('../services/apiImageVideo', () => ({ cleanGalleryImage: vi.fn(), extractLastFrame: vi.fn() }));++const parseNav = () => {+ const url = navigate.mock.calls.at(-1)?.[0] || '';+ const [path, qs] = url.split('?');+ return { path, params: new URLSearchParams(qs) };+};++describe('useMediaPreviewActions.handleSendToImage', () => {+ beforeEach(() => navigate.mockReset());++ it('navigates to /media/image with the image queued as init + settings carried', () => {+ const { result } = renderHook(() => useMediaPreviewActions());+ result.current.handleSendToImage({+ kind: 'image', filename: 'cat.png', prompt: 'a cat', negativePrompt: 'blurry',+ modelId: 'flux2', width: 1024, height: 768, seed: 7, steps: 8, guidance: 3.5, quantize: '8',+ });+ const { path, params } = parseNav();+ expect(path).toBe('/media/image');+ expect(params.get('initImageFile')).toBe('cat.png');+ expect(params.get('prompt')).toBe('a cat');+ expect(params.get('negativePrompt')).toBe('blurry');+ expect(params.get('modelId')).toBe('flux2');+ expect(params.get('width')).toBe('1024');+ expect(params.get('seed')).toBe('7');+ // Distinct from Remix — no `remix` param.+ expect(params.get('remix')).toBeNull();+ });++ it('skips the (no prompt) placeholder so it does not seed the next render', () => {+ const { result } = renderHook(() => useMediaPreviewActions());+ result.current.handleSendToImage({ kind: 'image', filename: 'x.png', prompt: '(no prompt)' });+ const { params } = parseNav();+ expect(params.get('initImageFile')).toBe('x.png');+ expect(params.get('prompt')).toBeNull();+ });++ it('is a no-op for videos and for items without a filename', () => {+ const { result } = renderHook(() => useMediaPreviewActions());+ result.current.handleSendToImage({ kind: 'video', filename: 'clip.mp4' });+ result.current.handleSendToImage({ kind: 'image' });+ expect(navigate).not.toHaveBeenCalled();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex d6d10c501c..4db7079a90 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -45,7 +45,7 @@ grep -i "what you want to do" client/src/lib/README.md|---|---|| `pipelineImageDefaults.js` | Pipeline comic-page image-gen defaults + settings reader. || `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. |-| `imageGenBackends.js` | `IMAGE_GEN_MODE` enum (local / codex / external) + metadata. |+| `imageGenBackends.js` | `IMAGE_GEN_MODE` enum (local / codex / external) + metadata; `deriveAvailableBackends`; `I2I_CAPABLE_MODES` / `isI2iCapableMode(mode)` / `pickI2iMode(backends)` — image-to-image capability gating + best-backend selection. || `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. || `imageGenResolutions.js` | Shared resolution presets for image generation. || `videoGenResolutions.js` | Shared resolution presets for video generation (companion to image side; LTX-2 latent-friendly sizes). |@@ -73,6 +73,7 @@ grep -i "what you want to do" client/src/lib/README.md| `localLlmTargetKey.js` | `localLlmTargetKey({ backend, modelId })` — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip. || `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. || `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |+| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. || `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. || `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. || `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.jsindex c92ba9bba0..a2f655fe64 100644--- a/client/src/lib/imageGenBackends.js+++ b/client/src/lib/imageGenBackends.js@@ -8,6 +8,23 @@ const META = {[IMAGE_GEN_MODE.EXTERNAL]: { label: 'External', icon: Cloud },};+// Backends that support image-to-image (init image / reference editing). The+// external SD-API path does not. Single source of truth for i2i gating in the UI.+export const I2I_CAPABLE_MODES = Object.freeze([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX]);++// True when a mode can run image-to-image.+export const isI2iCapableMode = (mode) => I2I_CAPABLE_MODES.includes(mode);++// Pick the best available i2i backend from a list of `{ id }` backends,+// preferring local (its form exposes strength + LoRAs), else codex. Returns+// null when neither is installed.+export function pickI2iMode(backends) {+ for (const mode of I2I_CAPABLE_MODES) {+ if (backends.some((b) => b.id === mode)) return mode;+ }+ return null;+}+export function deriveAvailableBackends(settings, { excludeExternal = false } = {}) {const ig = settings?.imageGen || {};const out = [];diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex eeb365614f..495c648696 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -44,6 +44,7 @@ export * from './joinInfluenceList.js';export * from './localLlmTargetKey.js';export * from './loopbackHost.js';export * from './mediaNavigation.js';+export * from './mediaSearch.js';export * from './sameJsonShape.js';export * from './unsorted.js';export * from './upsertByIdPrepend.js';diff --git a/client/src/lib/mediaSearch.js b/client/src/lib/mediaSearch.jsnew file mode 100644index 0000000000..149f86a085--- /dev/null+++ b/client/src/lib/mediaSearch.js@@ -0,0 +1,55 @@+// Shared client-side search over normalized media items (images + videos).+// Extracted from MediaHistory's inline haystack/token logic so the Image Gen+// gallery picker (GalleryImagePicker) and any future media browser share one+// definition of "what's searchable" and the AND-token matching semantics.+//+// Items are the normalized shape from `components/media/normalize.js`+// (normalizeImage / normalizeVideo) — prompt, modelId, seed, loraNames,+// universe/entry tags, etc.++// Build the lowercased searchable string for one normalized item. Keep this in+// sync with the fields users expect to match on (prompt text, model id, seed,+// resolution, LoRA names, Universe Builder entity/universe tags, lineage tags).+export function buildMediaHaystack(item) {+ if (!item) return '';+ return [+ item.prompt,+ item.negativePrompt,+ item.modelId,+ item.filename,+ item.kind,+ item.seed != null ? `seed ${item.seed}` : '',+ item.width && item.height ? `${item.width}x${item.height}` : '',+ ...(Array.isArray(item.loraNames) ? item.loraNames : []),+ // Universe Builder tags — searchable by entity name (e.g. "Ash"), universe+ // name, kind, or category even when those tokens aren't in the prompt.+ item.universeName,+ item.entryName,+ item.entryLabel,+ item.entryCategory,+ item.entryKind,+ item.extractedFromVideoId ? 'extracted frame' : '',+ item.stitchedFrom ? 'stitched' : '',+ item.upscaledFrom ? 'upscaled 2x' : '',+ ].filter(Boolean).join(' ').toLowerCase();+}++// Split a query into lowercased whitespace tokens (AND semantics across them).+export function tokenizeQuery(query) {+ return String(query || '').trim().toLowerCase().split(/\s+/).filter(Boolean);+}++// True when the haystack contains every token (substring, any order).+export function matchHaystack(haystack, tokens) {+ return tokens.every((t) => haystack.includes(t));+}++// Convenience: filter a list of normalized items by a raw query string. Builds+// haystacks inline — fine for one-shot filtering (the picker). For hot keystroke+// paths over a large list, cache `buildMediaHaystack` per item and reuse+// `tokenizeQuery` + `matchHaystack` (see MediaHistory).+export function filterByQuery(items, query) {+ const tokens = tokenizeQuery(query);+ if (tokens.length === 0) return items;+ return items.filter((item) => matchHaystack(buildMediaHaystack(item), tokens));+}diff --git a/client/src/lib/mediaSearch.test.js b/client/src/lib/mediaSearch.test.jsnew file mode 100644index 0000000000..848839c967--- /dev/null+++ b/client/src/lib/mediaSearch.test.js@@ -0,0 +1,79 @@+import { describe, it, expect } from 'vitest';+import { buildMediaHaystack, tokenizeQuery, matchHaystack, filterByQuery } from './mediaSearch';++const img = (over = {}) => ({+ kind: 'image',+ prompt: 'a neon sunset over the bay',+ negativePrompt: 'blurry',+ modelId: 'flux2',+ filename: 'abc123.png',+ seed: 42,+ width: 1024,+ height: 768,+ loraNames: ['lora-realstagram-v7.safetensors'],+ universeName: 'Ashworld',+ entryName: 'Ash',+ ...over,+});++describe('buildMediaHaystack', () => {+ it('includes prompt, model, seed, resolution, LoRA, and universe tags (lowercased)', () => {+ const h = buildMediaHaystack(img());+ expect(h).toContain('neon sunset');+ expect(h).toContain('flux2');+ expect(h).toContain('seed 42');+ expect(h).toContain('1024x768');+ expect(h).toContain('lora-realstagram-v7.safetensors');+ expect(h).toContain('ashworld');+ expect(h).toContain('ash');+ expect(h).toBe(h.toLowerCase());+ });++ it('returns an empty string for nullish input', () => {+ expect(buildMediaHaystack(null)).toBe('');+ });++ it('omits seed/resolution fragments when absent', () => {+ const h = buildMediaHaystack(img({ seed: null, width: 0, height: 0 }));+ expect(h).not.toContain('seed');+ expect(h).not.toContain('x768');+ });+});++describe('tokenizeQuery', () => {+ it('lowercases and splits on whitespace, dropping empties', () => {+ expect(tokenizeQuery(' Neon Sunset ')).toEqual(['neon', 'sunset']);+ expect(tokenizeQuery('')).toEqual([]);+ expect(tokenizeQuery(null)).toEqual([]);+ });+});++describe('matchHaystack', () => {+ it('requires every token (AND semantics)', () => {+ const h = buildMediaHaystack(img());+ expect(matchHaystack(h, ['neon', 'flux2'])).toBe(true);+ expect(matchHaystack(h, ['neon', 'missing'])).toBe(false);+ expect(matchHaystack(h, [])).toBe(true);+ });+});++describe('filterByQuery', () => {+ const items = [+ img({ filename: 'a.png', prompt: 'neon sunset', modelId: 'flux2' }),+ img({ filename: 'b.png', prompt: 'forest morning', modelId: 'sdxl', universeName: null, entryName: null, loraNames: [] }),+ ];++ it('returns all items for an empty query', () => {+ expect(filterByQuery(items, '')).toHaveLength(2);+ });++ it('AND-matches across tokens in any order', () => {+ const res = filterByQuery(items, 'flux2 neon');+ expect(res).toHaveLength(1);+ expect(res[0].filename).toBe('a.png');+ });++ it('returns empty when no item matches all tokens', () => {+ expect(filterByQuery(items, 'neon sdxl')).toHaveLength(0);+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 240b4276cf..a2f34c9758 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -23,6 +23,7 @@ import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';import HfTokenBanner from '../components/imageGen/HfTokenBanner';import ImageGenControls from '../components/imageGen/ImageGenControls';import InitImagePicker from '../components/imageGen/InitImagePicker';+import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';import LoraPicker from '../components/imageGen/LoraPicker';import ReferenceImagePicker from '../components/imageGen/ReferenceImagePicker';import MediaJobsQueue from '../components/media/MediaJobsQueue';@@ -35,7 +36,7 @@ import {AlertTriangle, X, Film,} from 'lucide-react';import { composeStyledPrompt } from '../lib/composeStyledPrompt';-import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';+import { deriveAvailableBackends, IMAGE_GEN_MODE, isI2iCapableMode, pickI2iMode } from '../lib/imageGenBackends';import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';import { resolveCleanersFromConfig } from '../lib/imageCleaners';import toast from '../components/ui/Toast';@@ -55,6 +56,12 @@ import {const REFERENCE_SLOT_COUNT = 4;const EMPTY_REF_SLOT = { file: null, previewUrl: null, strength: 1.0 };+// Revoke an object URL only when it's a blob: URL we created — gallery `/data/...`+// previews must never be revoked.+const revokeIfBlob = (url) => {+ if (url?.startsWith('blob:')) URL.revokeObjectURL(url);+};+// Append LoRA trigger words to a prompt comma-separated, skipping any// already present. Compares against comma-separated prompt segments rather// than raw substrings so a short trigger like "cat" doesn't false-match@@ -132,6 +139,9 @@ export default function ImageGen() {const selectedModeRef = useRef(null);selectedModeRef.current = selectedMode;const [availableBackends, setAvailableBackends] = useState([]);+ // Set when we arrive with an i2i init image but no i2i-capable backend has+ // loaded yet — a deferred effect flips to one once backends resolve.+ const wantI2iModeRef = useRef(false);const [prompt, setPrompt] = useState('');const [negativePrompt, setNegativePrompt] = useState(DEFAULT_NEGATIVE_PROMPT);@@ -151,6 +161,10 @@ export default function ImageGen() {// the whole object so previewUrl can never out-live its file/name.const [initImage, setInitImage] = useState({ source: null, file: null, name: null, previewUrl: null });const [initImageStrength, setInitImageStrength] = useState(0.4);+ // Visual gallery picker target: null (closed), { kind: 'init' }, or+ // { kind: 'reference', slot: i }. The search/browse alternative to the plain+ // file inputs in InitImagePicker / ReferenceImagePicker.+ const [galleryPicker, setGalleryPicker] = useState(null);// Form posts populated slots as `referenceImage1` … `referenceImage4`// multipart fields with a parallel `referenceStrengths` array.const [referenceImages, setReferenceImages] = useState(() => Array.from({ length: REFERENCE_SLOT_COUNT }, () => ({ ...EMPTY_REF_SLOT })));@@ -208,6 +222,9 @@ export default function ImageGen() {const isLocalMode = effectiveMode === IMAGE_GEN_MODE.LOCAL;const isCodexMode = effectiveMode === IMAGE_GEN_MODE.CODEX;const isAsyncMode = isLocalMode || isCodexMode;+ // Whether the active backend supports image-to-image (init image). Distinct+ // concept from isAsyncMode (queued vs sync) even though they coincide today.+ const i2iCapable = isI2iCapableMode(effectiveMode);// Prefer the socket-driven hook (carries currentImage for both modes since// local mflux now writes stepwise frames). Fall back to the local SSE's// simpler progress shape if the hook hasn't received its first event yet.@@ -357,16 +374,35 @@ export default function ImageGen() {refreshStatus(effectiveMode);}, [effectiveMode, refreshStatus]);- // ?initImageFile=foo.png pre-fills from a gallery basename — supports a- // future "Send to Image (i2i)" gallery action.+ // ?initImageFile=foo.png pre-fills from a gallery basename — the "Send to+ // image-to-image" card/lightbox action navigates here with it. Strip the param+ // after applying (mirror the remix-keys effect below) so a refresh/back-nav+ // doesn't re-clobber a cleared init image. The init image only applies on an+ // i2i-capable backend (hasInitImage gate), so request a switch — deferred via+ // a ref since availableBackends may not have loaded yet on this navigation.useEffect(() => {const fromUrl = searchParams.get('initImageFile');- if (fromUrl && initImage.source == null) {+ if (!fromUrl) return;+ if (initImage.source == null) {setInitImage({ source: 'gallery', file: null, name: fromUrl, previewUrl: `/data/images/${fromUrl}` });}+ wantI2iModeRef.current = true;+ setSearchParams((prev) => { const n = new URLSearchParams(prev); n.delete('initImageFile'); return n; }, { replace: true });// eslint-disable-next-line react-hooks/exhaustive-deps}, [searchParams]);+ // Deferred i2i mode nudge: once backends resolve, flip to an i2i-capable+ // backend so the URL-supplied init image actually takes effect (the picker ++ // generate payload are local/codex only). Give up quietly if neither exists.+ useEffect(() => {+ if (!wantI2iModeRef.current) return;+ if (i2iCapable) { wantI2iModeRef.current = false; return; }+ if (!availableBackends.length) return; // wait for load+ const mode = pickI2iMode(availableBackends);+ if (mode) setSelectedMode(mode);+ wantI2iModeRef.current = false;+ }, [availableBackends, i2iCapable]);+// ?lora=<filename> preselects a LoRA when the user clicks "Test" on the// /media/loras manager page. Defers until availableLoras has loaded so the// metadata (recommendedScale, name, triggerWords) is available; once applied,@@ -441,13 +477,20 @@ export default function ImageGen() {const raw = e.target.files?.[0];if (!raw) return;const file = await normalizeImageOrientation(raw);- if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);+ revokeIfBlob(initImage.previewUrl);setInitImage({ source: 'upload', file, name: file.name, previewUrl: URL.createObjectURL(file) });};const handleClearInitImage = () => {- if (initImage.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(initImage.previewUrl);+ revokeIfBlob(initImage.previewUrl);setInitImage({ source: null, file: null, name: null, previewUrl: null });};+ // Pick an existing gallery image as the i2i source (from GalleryImagePicker).+ // No EXIF normalization needed — gallery PNGs are already baked correct.+ const handlePickGalleryInitImage = (item) => {+ if (!item?.filename) return;+ revokeIfBlob(initImage.previewUrl);+ setInitImage({ source: 'gallery', file: null, name: item.filename, previewUrl: item.previewUrl || `/data/images/${item.filename}` });+ };const handlePickReferenceImage = async (slotIndex, e) => {const raw = e.target.files?.[0];@@ -455,17 +498,15 @@ export default function ImageGen() {const file = await normalizeImageOrientation(raw);setReferenceImages((prev) => {const next = [...prev];- const prior = next[slotIndex];- if (prior?.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(prior.previewUrl);- next[slotIndex] = { file, previewUrl: URL.createObjectURL(file), strength: prior?.strength ?? 1.0 };+ revokeIfBlob(next[slotIndex]?.previewUrl);+ next[slotIndex] = { file, previewUrl: URL.createObjectURL(file), strength: next[slotIndex]?.strength ?? 1.0 };return next;});};const handleClearReferenceImage = (slotIndex) => {setReferenceImages((prev) => {const next = [...prev];- const prior = next[slotIndex];- if (prior?.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(prior.previewUrl);+ revokeIfBlob(next[slotIndex]?.previewUrl);next[slotIndex] = { ...EMPTY_REF_SLOT };return next;});@@ -478,6 +519,37 @@ export default function ImageGen() {});};+ // Fetch a gallery image into a File so it can ride the multipart reference+ // upload path — the server has no gallery-basename field for references (unlike+ // the init image). Gallery PNGs are already EXIF-correct, so no re-encode.+ const galleryImageToFile = async (filename) => {+ const res = await fetch(`/data/images/${filename}`);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const blob = await res.blob();+ return new File([blob], filename, { type: blob.type || 'image/png' });+ };+ const handlePickGalleryReferenceImage = async (slotIndex, item) => {+ if (!item?.filename) return;+ const file = await galleryImageToFile(item.filename).catch((err) => {+ toast.error(`Failed to load reference image: ${err.message}`);+ return null;+ });+ if (!file) return;+ setReferenceImages((prev) => {+ const next = [...prev];+ revokeIfBlob(next[slotIndex]?.previewUrl);+ next[slotIndex] = { file, previewUrl: item.previewUrl || `/data/images/${item.filename}`, strength: next[slotIndex]?.strength ?? 1.0 };+ return next;+ });+ };++ // Route a gallery pick to whichever picker opened it (init image or a+ // specific reference slot).+ const handleGallerySelect = (item) => {+ if (galleryPicker?.kind === 'reference') handlePickGalleryReferenceImage(galleryPicker.slot, item);+ else handlePickGalleryInitImage(item);+ };+// Object URL cleanup on unmount — both the single init image and any// populated reference slots. Mirror the live URLs into a ref so the// empty-deps unmount cleanup walks the LATEST set, not the initial empty@@ -492,10 +564,8 @@ export default function ImageGen() {});useEffect(() => () => {const { init, refs } = previewUrlsRef.current;- if (init?.startsWith('blob:')) URL.revokeObjectURL(init);- for (const url of refs) {- if (url?.startsWith('blob:')) URL.revokeObjectURL(url);- }+ revokeIfBlob(init);+ for (const url of refs) revokeIfBlob(url);}, []);// When the user closes the Settings drawer, settings may have changed@@ -644,7 +714,8 @@ export default function ImageGen() {mode: IMAGE_GEN_MODE.LOCAL,cleanC2PA, denoise,};- const hasInitImage = isLocalMode && initImage.source != null;+ // i2i works on local (mflux/FLUX) and codex (gpt-image edit) — not external.+ const hasInitImage = i2iCapable && initImage.source != null;// Multi-reference editing is FLUX.2-only; gate the slot read so it can't// accidentally fire on mflux or codex, and pack the populated slots so a// gap (e.g. slots 1,3 filled, 2 empty) collapses to a packed two-image@@ -899,6 +970,29 @@ export default function ImageGen() {window.scrollTo({ top: 0, behavior: 'smooth' });};+ // The i2i init image only applies on an i2i-capable backend (local or codex).+ // Switch to one now if installed; otherwise flag the deferred effect to retry+ // once availableBackends resolves. Shared by the in-page send-to-i2i handler+ // and the ?initImageFile URL effect. No-op when already on local/codex, so an+ // explicit codex user stays on codex.+ const ensureI2iCapableMode = useCallback(() => {+ if (i2iCapable) return;+ const mode = pickI2iMode(availableBackends);+ if (mode) setSelectedMode(mode);+ else wantI2iModeRef.current = true;+ }, [i2iCapable, availableBackends]);++ // Send to image-to-image (in-page): reuse the remix settings AND queue this+ // image as the i2i source on an i2i-capable backend.+ const handleSendToImage = (img) => {+ if (!img?.filename) return;+ handleRemix(img);+ ensureI2iCapableMode();+ revokeIfBlob(initImage.previewUrl);+ setInitImage({ source: 'gallery', file: null, name: img.filename, previewUrl: `/data/images/${img.filename}` });+ setInitImageStrength(0.4);+ };+const notConnected = status && status.connected === false;return (@@ -1057,14 +1151,16 @@ export default function ImageGen() {/>)}- {isLocalMode && (+ {i2iCapable && (<InitImagePickerinitImage={initImage}initImageStrength={initImageStrength}onStrengthChange={setInitImageStrength}onPick={handlePickInitImage}onClear={handleClearInitImage}+ onBrowse={() => setGalleryPicker({ kind: 'init' })}editOnly={isEditOnlyModel}+ backend={effectiveMode}disabled={statusLoading}/>)}@@ -1075,6 +1171,7 @@ export default function ImageGen() {onPick={handlePickReferenceImage}onClear={handleClearReferenceImage}onStrengthChange={handleReferenceStrengthChange}+ onBrowse={(slot) => setGalleryPicker({ kind: 'reference', slot })}disabled={statusLoading}/>)}@@ -1280,6 +1377,7 @@ export default function ImageGen() {item={item}onPreview={() => setPreview(item)}onRemix={() => handleRemix(img)}+ onSendToImage={() => handleSendToImage(img)}onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}onToggleHidden={() => handleToggleHidden(item)}@@ -1312,6 +1410,7 @@ export default function ImageGen() {item={item}onPreview={() => setPreview(item)}onRemix={() => handleRemix(img)}+ onSendToImage={() => handleSendToImage(img)}onSendToVideo={() => sendToVideo(img)}onDelete={() => handleDelete(img.filename)}onToggleHidden={() => handleToggleHidden(item)}@@ -1331,6 +1430,7 @@ export default function ImageGen() {annotations={annotations}updateAnnotation={updateAnnotation}onRemix={(item) => item?.raw && handleRemix(item.raw)}+ onSendToImage={(item) => item?.raw?.filename && handleSendToImage(item.raw)}onSendToVideo={(item) => item?.raw?.filename && sendToVideo(item.raw)}onClean={(item) => handleClean(item?.raw)}onRegenerate={(item, opts) => handleRegenerate(item?.raw, opts)}@@ -1338,6 +1438,11 @@ export default function ImageGen() {regenBounds={regenInfo}/>+ <GalleryImagePicker+ open={!!galleryPicker}+ onClose={() => setGalleryPicker(null)}+ onSelect={handleGallerySelect}+ /><Drawer open={settingsOpen} onClose={closeSettings} title="Media Generation Settings"><ImageGenTab />diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex d560f45758..298f305730 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -269,7 +269,7 @@ export default function MediaCollectionDetail() {// the cleaned image to THIS collection + seed imagesByName so hydrate()// renders it immediately, no refresh round-trip) is wired through// `onCleanComplete`.- const { handleRemix, handleSendToVideo, handleContinue, handleClean } = useMediaPreviewActions({+ const { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean } = useMediaPreviewActions({onCleanComplete: async (cleaned) => {// The server's clean route auto-files the cleaned filename into every// collection that contained the source — including this one — so this@@ -514,6 +514,7 @@ export default function MediaCollectionDetail() {onPreview={selectMode ? undefined : setPreview}onClick={selectMode ? () => toggleSelect(key) : undefined}onRemix={!selectMode && item.kind === 'image' ? handleRemix : undefined}+ onSendToImage={!selectMode && item.kind === 'image' ? handleSendToImage : undefined}onSendToVideo={!selectMode && item.kind === 'image' ? handleSendToVideo : undefined}onContinue={!selectMode && item.kind === 'video' ? handleContinue : undefined}onDelete={!selectMode ? handleDelete : undefined}@@ -554,6 +555,7 @@ export default function MediaCollectionDetail() {annotations={annotations}updateAnnotation={updateAnnotation}onRemix={handleRemix}+ onSendToImage={handleSendToImage}onSendToVideo={handleSendToVideo}onContinue={(i) => handleContinue(i.raw || i)}onClean={(i) => handleClean(i?.raw || i)}diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex ef585b4fc5..bf05ed748a 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -16,6 +16,7 @@ import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';import useMediaPreviewActions from '../hooks/useMediaPreviewActions';import usePreviewRoute from '../hooks/usePreviewRoute';+import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../lib/mediaSearch';import {listVideoHistory, deleteVideoHistoryItem, stitchVideos,upscaleVideo,@@ -66,37 +67,14 @@ export default function MediaHistory() {// Precompute the searchable haystack per item once per items list — keystrokes// then only re-run token .includes() against a cached string instead of- // rebuilding the array + join + lowercase per item per keystroke.- const haystacks = useMemo(() => items.map((item) => [- item.prompt,- item.negativePrompt,- item.modelId,- item.filename,- item.kind,- item.seed != null ? `seed ${item.seed}` : '',- item.width && item.height ? `${item.width}x${item.height}` : '',- ...(Array.isArray(item.loraNames) ? item.loraNames : []),- // Universe Builder tags — searchable by entity name (e.g. "Ash"), universe- // name, kind, or category even when those tokens aren't in the prompt.- item.universeName,- item.entryName,- item.entryLabel,- item.entryCategory,- item.entryKind,- item.extractedFromVideoId ? 'extracted frame' : '',- item.stitchedFrom ? 'stitched' : '',- item.upscaledFrom ? 'upscaled 2x' : '',- ].filter(Boolean).join(' ').toLowerCase()), [items]);-- // AND semantics across whitespace tokens — "sunset flux2 1024" matches items- // whose haystack contains all three substrings, in any order.- const tokens = useMemo(- () => query.trim().toLowerCase().split(/\s+/).filter(Boolean),- [query]- );+ // rebuilding the array + join + lowercase per item per keystroke. The haystack+ // shape + AND-token semantics live in lib/mediaSearch so the Image Gen gallery+ // picker searches identically.+ const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);+ const tokens = useMemo(() => tokenizeQuery(query), [query]);const searched = useMemo(- () => tokens.length === 0 ? items : items.filter((_, idx) => tokens.every((t) => haystacks[idx].includes(t))),+ () => tokens.length === 0 ? items : items.filter((_, idx) => matchHaystack(haystacks[idx], tokens)),[items, haystacks, tokens]);const kindFiltered = useMemo(@@ -154,7 +132,7 @@ export default function MediaHistory() {// the cleaned image to the top of the local list) is page-specific —// wired through `onCleanComplete` so the cleaned record lands in `items`// without a full gallery refetch.- const { handleRemix, handleSendToVideo, handleContinue, handleClean } = useMediaPreviewActions({+ const { handleRemix, handleSendToImage, handleSendToVideo, handleContinue, handleClean } = useMediaPreviewActions({onCleanComplete: (cleaned) => {const normalized = normalizeImage(cleaned);setItems((prev) => [normalized, ...prev.filter((x) => x.key !== normalized.key)]);@@ -274,6 +252,7 @@ export default function MediaHistory() {onPreview={(media) => setPreview(media)}onClick={inStitch ? () => toggleSelect(it.id) : undefined}onRemix={!stitchMode ? handleRemix : undefined}+ onSendToImage={!stitchMode ? handleSendToImage : undefined}onSendToVideo={!stitchMode ? handleSendToVideo : undefined}onContinue={!stitchMode ? handleContinue : undefined}onUpscale={!stitchMode && it.kind === 'video' ? handleUpscale : undefined}@@ -297,6 +276,7 @@ export default function MediaHistory() {annotations={annotations}updateAnnotation={updateAnnotation}onRemix={handleRemix}+ onSendToImage={handleSendToImage}onSendToVideo={handleSendToVideo}onContinue={handleContinue}onClean={(item) => handleClean(item?.raw)}diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex fc3fcfc136..acaa097704 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -2073,6 +2073,7 @@ export default function UniverseBuilder() {annotations={annotations}updateAnnotation={updateAnnotation}onRemix={preview?.key?.startsWith('canon-sheet:') ? undefined : previewActions.handleRemix}+ onSendToImage={preview?.key?.startsWith('canon-sheet:') ? undefined : previewActions.handleSendToImage}onSendToVideo={preview?.key?.startsWith('canon-sheet:') ? undefined : previewActions.handleSendToVideo}onClean={preview?.key?.startsWith('canon-sheet:') ? undefined : (item) => previewActions.handleClean(item?.raw || item)}onContinue={preview?.key?.startsWith('canon-sheet:') ? undefined : (item) => previewActions.handleContinue(item?.raw || item)}diff --git a/docs/plans/2026-06-05-send-to-i2i-and-gallery-picker.md b/docs/plans/2026-06-05-send-to-i2i-and-gallery-picker.mdnew file mode 100644index 0000000000..6ada967956--- /dev/null+++ b/docs/plans/2026-06-05-send-to-i2i-and-gallery-picker.md@@ -0,0 +1,165 @@+# Plan: "Send to image-to-image" action + visual gallery picker on Image Gen++## Context++The Image Gen page (`client/src/pages/ImageGen.jsx`) supports image-to-image (i2i) on+the local FLUX/mflux and Codex backends — it sends either an uploaded `initImage` file+or a gallery basename `initImageFile` + `initImageStrength` to `POST /api/image-gen/generate`.+Two gaps in the UX today:++1. **Image cards/modals only offer "Remix."** Remix carries prompt + render settings to+ the gen page but does NOT seed the source image. There is no one-click "take *this*+ image and run img2img on it." The backend + the `?initImageFile=` URL param already+ exist (`ImageGen.jsx:360-368`) — the action was scaffolded for but never wired.++2. **The init-image picker is upload-only.** `InitImagePicker.jsx` exposes a single+ `<input type="file">`. To reuse an image you already generated you must download it+ and re-upload. There's a rich local gallery (`GET /api/image-gen/gallery`, listed via+ `listImageGallery()`) with prompt/model/seed/LoRA metadata and a proven client-side+ search in `MediaHistory.jsx` — but no way to browse/search it from the gen form.++**Decisions (confirmed with user):** the visual picker searches the **local gallery only**;+"Send to image-to-image" carries the **image + prompt + settings** (like Remix, plus the+init image and a default strength).++---++## Part 1 — "Send to image-to-image" action++### 1a. Shared handler (for MediaHistory / MediaCollectionDetail / UniverseBuilder)++`client/src/hooks/useMediaPreviewActions.js` — add a `handleSendToImage(item)` alongside+`handleRemix`. Images only (`if (!item?.filename || item.kind === 'video') return;`).+Build the same param set `handleRemix` uses for images (prompt, negativePrompt, modelId,+width, height, seed, steps, guidance, quantize) **plus** `initImageFile: item.filename`,+then `navigate(\`/media/image?${params}\`)`. Do **not** set the `remix` param. Return it+from the hook with the other handlers.++### 1b. Buttons on the card + lightbox++- `client/src/components/media/MediaCard.jsx` — add `onSendToImage` prop. Render a button+ in the action row (`MediaCard.jsx:111-122`) right after Remix, gated on+ `!isVideo && onSendToImage`. Use a distinct icon (e.g. `Wand2` / `Images`) and+ `title="Send to image-to-image"`; match the compact icon-button styling of the+ Send-to-Video button.+- `client/src/components/media/MediaLightbox.jsx` — add `onSendToImage` prop. Render a+ footer button after Remix (`MediaLightbox.jsx:619-627`), gated on+ `!isVideo && onSendToImage`, using `closeThenRun(onSendToImage)` like its siblings.+- `MediaPreview.jsx` already forwards arbitrary `...handlers` to the lightbox — no change+ needed there; passing `onSendToImage` to `<MediaPreview>` is enough.++### 1c. Wire the prop in the shared consumers++In `MediaHistory.jsx` and `MediaCollectionDetail.jsx`: destructure `handleSendToImage`+from `useMediaPreviewActions()` and pass `onSendToImage={...}` to both the `MediaCard`+grid and the `MediaPreview` (mirroring how `handleRemix` is wired today at+`MediaHistory.jsx:276,299` and `MediaCollectionDetail.jsx:516,556`). In+`UniverseBuilder.jsx:2075`, pass `previewActions.handleSendToImage` to the lightbox with+the same canon-sheet gate Remix uses.++### 1d. ImageGen's own cards/lightbox (in-page, no navigation)++`ImageGen.jsx` has its own in-page `handleRemix` (`ImageGen.jsx:872-900`) and wires it on+its recent-gallery cards (`:1282`, `:1314`) and its `MediaPreview` (`:1333`). Add an+in-page `handleSendToImage(img)` that:+- calls the existing remix body (prompt/negativePrompt/seed/steps/guidance/quantize/+ width/height/modelId/LoRAs) — factor the shared body out of `handleRemix` so both reuse it;+- sets the init image to the gallery source:+ `setInitImage({ source: 'gallery', file: null, name: img.filename, previewUrl: \`/data/images/${img.filename}\` })`+ and `setInitImageStrength(0.4)` (current default);+- ensures an i2i-capable backend is active — if the current mode is external (no i2i),+ switch to the local mode so the picker is actually usable;+- `window.scrollTo({ top: 0, behavior: 'smooth' })`.+Wire `onSendToImage` on the two `MediaCard`s and the `MediaPreview`.++### 1e. Tighten the inbound URL effect++In `ImageGen.jsx:360-368`, after applying `?initImageFile`, strip the param (mirror the+remix-keys effect at `:411-415`) so a refresh/back-nav doesn't re-clobber a cleared init+image, and nudge mode to a local/i2i-capable backend when arriving with an init image.++---++## Part 2 — Visual gallery picker on the Image Gen page++### 2a. Extract reusable search helper (backbone)++`MediaHistory.jsx:70-101` builds a per-item search "haystack" and does AND-token matching.+Extract that into `client/src/lib/mediaSearch.js`:+- `buildMediaHaystack(item)` → lowercased searchable string (prompt, negativePrompt,+ modelId, filename, kind, seed, `WxH`, loraNames, universe/entry tags…);+- `filterByQuery(items, query)` → tokenized AND filter using cached haystacks.+Refactor `MediaHistory.jsx` to consume it (keeps behavior identical, removes duplication).+**Maintenance rule:** add `mediaSearch` to `client/src/lib/index.js` barrel and a row in+`client/src/lib/README.md` (enforced by the barrel test).++### 2b. New `GalleryImagePicker` modal component++`client/src/components/imageGen/GalleryImagePicker.jsx` — a modal that:+- on open, fetches `listImageGallery()` (from `services/apiImageVideo.js`) and maps with+ `normalizeImage` (`components/media/normalize.js`); shows a loading + empty state;+- renders a search `<input>` (Search icon, like MediaHistory) filtered via+ `filterByQuery` from 2a;+- renders the results as a responsive grid of `MediaCard` with+ `onClick={() => onSelect(item)} hideActions showCollectionMenu={false}` — `MediaCard`+ already supports `onClick` overriding preview (`MediaCard.jsx:14,32`);+- calls `onSelect(item)` then `onClose()` when a tile is picked.+Use the existing UI modal/overlay component (e.g. `components/ui/Modal`) for the shell —+no `window.*` dialogs (per conventions). Mobile-responsive grid.++### 2c. Hook the picker into the init-image flow++- `InitImagePicker.jsx` — add an `onBrowse` prop. In the empty state+ (`InitImagePicker.jsx:64-70`) render a "Browse gallery" button next to the upload label;+ keep the file `<input>` for upload. (Both affordances coexist.)+- `ImageGen.jsx` — hold `galleryPickerOpen` state; pass `onBrowse={() => setGalleryPickerOpen(true)}`+ to `InitImagePicker`; render `<GalleryImagePicker>` whose `onSelect(item)` sets+ `setInitImage({ source: 'gallery', file: null, name: item.filename, previewUrl: item.previewUrl })`.+ No EXIF normalization needed for gallery picks (server-side PNGs already correct).++### 2d. (Roll-in) Reference-image slots++`ReferenceImagePicker.jsx` (FLUX.2 multi-ref) is also upload-only. Reuse the same+`GalleryImagePicker` to add a "Browse" affordance per slot, setting the slot from a gallery+basename. The generate route already accepts gallery-derived references via the existing+multipart path; if a slot needs a `File` rather than a basename, fetch the gallery image to+a Blob on select. Keep this secondary to the init-image path; include only if it stays+low-risk.++---++## Files to modify / add++- `client/src/hooks/useMediaPreviewActions.js` — add `handleSendToImage`+- `client/src/components/media/MediaCard.jsx` — `onSendToImage` button+- `client/src/components/media/MediaLightbox.jsx` — `onSendToImage` footer button+- `client/src/pages/MediaHistory.jsx` — wire `onSendToImage`; consume `mediaSearch`+- `client/src/pages/MediaCollectionDetail.jsx` — wire `onSendToImage`+- `client/src/pages/UniverseBuilder.jsx` — wire `onSendToImage` on lightbox+- `client/src/pages/ImageGen.jsx` — in-page `handleSendToImage`, gallery-picker state,+ strip `initImageFile` param, factor shared remix body+- `client/src/components/imageGen/InitImagePicker.jsx` — `onBrowse` button+- `client/src/components/imageGen/GalleryImagePicker.jsx` — **new** modal+- `client/src/lib/mediaSearch.js` — **new** helper (+ `index.js` barrel + `README.md` row)+- Tests (next to source): `mediaSearch.test.js`, `GalleryImagePicker.test.jsx`, and extend+ `useMediaPreviewActions` coverage for the new navigation URL.++No server changes — the generate route, `initImageFile`/`initImageStrength` validation, and+`GET /api/image-gen/gallery` already support everything needed.++---++## Verification++1. `cd client && npm test` — new + existing vitest suites pass (mediaSearch helper,+ GalleryImagePicker render/search/select, MediaHistory unchanged behavior).+2. `npm run dev`, open `/media/image`:+ - Init image → **Browse gallery** opens the modal; type a prompt keyword → grid filters;+ click a tile → it becomes the init image with the strength slider; Generate runs i2i.+3. Open `/media/history` (and a collection): an image card/lightbox shows **Send to+ image-to-image**; click → lands on `/media/image` with that image pre-set as init image+ and prompt/model/dimensions pre-filled; mode is an i2i-capable backend.+4. On the Image Gen page's own recent gallery, **Send to image-to-image** sets the init+ image in place (no navigation) and scrolls to the form.+5. Confirm videos never show the action (image-only gating) and a cleared init image stays+ cleared after refresh (param stripped).