Skip to content

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

feat: DRY image preview modal — hydrate Universe lightbox + extract shared hook

[._.]/ Adam Eivy97f939c9bfb3
diff --git a/client/src/hooks/useImagePreviewActions.js b/client/src/hooks/useImagePreviewActions.js
new file mode 100644
index 0000000000..b2b54b5bb3
--- /dev/null
+++ b/client/src/hooks/useImagePreviewActions.js
@@ -0,0 +1,100 @@
+import { useCallback } from 'react';
+import { useNavigate } from 'react-router-dom';
+import toast from '../components/ui/Toast';
+import { cleanGalleryImage, extractLastFrame } from '../services/apiImageVideo';
+
+/**
+ * Shared MediaPreview / MediaLightbox action handlers. The same four
+ * callbacks (`onRemix`, `onSendToVideo`, `onContinue`, `onClean`) used to
+ * live as identical copies in `pages/MediaHistory.jsx`,
+ * `pages/MediaCollectionDetail.jsx`, `pages/ImageGen.jsx`, and the new
+ * Universe Builder lightbox — drift between them produced subtle differences
+ * (one consumer set `width` as a URL param, another didn't; one passed
+ * `negativePrompt`, another aliased it from `raw.negative_prompt`). This
+ * hook is the single source of truth so consumers all open the same
+ * downstream pages with the same param set, and post-clean behavior is
+ * the only piece that differs per surface (collection-add vs. local-list
+ * prepend vs. ignore) — supplied via `onCleanComplete`.
+ *
+ * @param {object} [options]
+ * @param {(cleaned: object, level: string) => any | Promise<any>} [options.onCleanComplete]
+ * Fires AFTER `cleanGalleryImage` resolves. Use it to splice the cleaned
+ * image into the consumer's local state (collection items, gallery list,
+ * variation imageRefs, etc.). Errors thrown from the callback bubble.
+ *
+ * Returns the four handlers shaped for direct use as MediaPreview props.
+ */
+export default function useImagePreviewActions({ onCleanComplete = null } = {}) {
+ const navigate = useNavigate();
+
+ // Remix: hand the prompt + render settings to the Image Gen page so the
+ // user can iterate. `(no prompt)` is the metadata-sidecar placeholder for
+ // images that lost their prompt — skip it so the next render doesn't
+ // start with that literal as the user's prompt.
+ const handleRemix = useCallback((item) => {
+ if (!item) 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));
+ if (item.filename) params.set('remix', 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
+ // populates the field.
+ const handleSendToVideo = useCallback((item) => {
+ if (!item?.filename) return;
+ const params = new URLSearchParams({ sourceImageFile: item.filename });
+ if (item.prompt && item.prompt !== '(no prompt)') params.set('prompt', item.prompt);
+ const neg = item.negativePrompt || item.raw?.negativePrompt || item.raw?.negative_prompt;
+ if (neg) params.set('negativePrompt', neg);
+ if (item.width) params.set('w', String(item.width));
+ if (item.height) params.set('h', String(item.height));
+ navigate(`/media/video?${params}`);
+ }, [navigate]);
+
+ // Continue: extract the LAST frame of a video clip and seed Video Gen
+ // with it as the i2v source — the canonical "extend this take" path.
+ // `item.id` is the video job id; extractLastFrame returns the new image
+ // filename. Toast handles the error path; the caller doesn't need to.
+ const handleContinue = useCallback(async (item) => {
+ if (!item?.id) return;
+ const { filename } = await extractLastFrame(item.id).catch((err) => {
+ toast.error(err.message || 'Failed to extract last frame');
+ return {};
+ });
+ if (!filename) return;
+ const params = new URLSearchParams({ sourceImageFile: filename });
+ if (item.width) params.set('w', String(item.width));
+ if (item.height) params.set('h', String(item.height));
+ navigate(`/media/video?${params}`);
+ }, [navigate]);
+
+ // Clean: send to the SDAPI background-cleaner endpoint (`light` /
+ // `aggressive`). Returns the resulting gallery item so consumers can
+ // splice it into local state. `onCleanComplete` is the consumer-specific
+ // post-step (add-to-collection / prepend-to-history / etc.) — fired
+ // AFTER the success toast so a failing post-step still shows the user
+ // the clean succeeded server-side.
+ const handleClean = useCallback(async (img, level) => {
+ if (!img?.filename) throw new Error('Missing filename');
+ const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {
+ toast.error(err.message || 'Failed to clean image');
+ throw err;
+ });
+ toast.success(`Cleaned (${level}) → ${cleaned.filename}`);
+ if (onCleanComplete) await onCleanComplete(cleaned, level);
+ return cleaned;
+ }, [onCleanComplete]);
+
+ return { handleRemix, handleSendToVideo, handleContinue, handleClean };
+}
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 77384ab193..c15bdc6a9e 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -14,9 +14,9 @@ import {
listMediaCollections,
addMediaCollectionItem, removeMediaCollectionItem,
listImageGallery, listVideoHistory,
- extractLastFrame, cleanGalleryImage,
deleteImage, deleteVideoHistoryItem,
} from '../services/api';
+import useImagePreviewActions from '../hooks/useImagePreviewActions';
// Hydrate a collection's "<kind>:<ref>" pointer list into the same
// normalized records MediaCard expects. We do this on the client so the
@@ -238,52 +238,28 @@ export default function MediaCollectionDetail() {
else toast.success(`${verb} ${added} to "${targetName}"${note}`);
};
- // Image-Gen "Remix" and "Send to Video" piping — same patterns as
- // MediaHistory, kept here so the collection grid is a fully usable
- // surface for action workflows, not just a viewer.
- const handleRemix = (item) => {
- const params = new URLSearchParams({ remix: item.filename });
- if (item.prompt) params.set('prompt', item.prompt);
- navigate(`/media/image?${params.toString()}`);
- };
- const handleSendToVideo = (item) => {
- const params = new URLSearchParams({ sourceImageFile: item.filename });
- if (item.width) params.set('w', String(item.width));
- if (item.height) params.set('h', String(item.height));
- navigate(`/media/video?${params.toString()}`);
- };
- const handleClean = async (img, level) => {
- if (!img?.filename) throw new Error('Missing filename');
- const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {
- toast.error(err.message || 'Failed to clean image');
- throw err;
- });
- const updated = await addMediaCollectionItem(collection.id, {
- kind: 'image',
- ref: cleaned.filename,
- }).catch(() => null);
- if (updated) setCollection(updated);
- // Seed imagesByName so hydrate() can render the cleaned file immediately
- // — without this the next render misses it until refresh() reruns.
- setImagesByName((m) => {
- const next = new Map(m);
- next.set(cleaned.filename, cleaned);
- return next;
- });
- toast.success(`Cleaned (${level}) → ${cleaned.filename}`);
- };
-
- const handleContinue = async (item) => {
- const { filename } = await extractLastFrame(item.id).catch((err) => {
- toast.error(err.message || 'Failed to extract last frame');
- return {};
- });
- if (!filename) return;
- const params = new URLSearchParams({ sourceImageFile: filename });
- if (item.width) params.set('w', String(item.width));
- if (item.height) params.set('h', String(item.height));
- navigate(`/media/video?${params.toString()}`);
- };
+ // Remix / SendToVideo / Continue / Clean share a single implementation
+ // with MediaHistory, ImageGen, and the Universe Builder lightbox via
+ // `useImagePreviewActions`. The collection-specific post-clean step (add
+ // 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 } = useImagePreviewActions({
+ onCleanComplete: async (cleaned) => {
+ const updated = await addMediaCollectionItem(collection.id, {
+ kind: 'image',
+ ref: cleaned.filename,
+ }).catch(() => null);
+ if (updated) setCollection(updated);
+ // Without this the next render misses the cleaned file until
+ // refresh() reruns.
+ setImagesByName((m) => {
+ const next = new Map(m);
+ next.set(cleaned.filename, cleaned);
+ return next;
+ });
+ },
+ });
if (loading) return <div className="text-gray-500 text-sm">Loading…</div>;
if (!collection) return (
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 881bea397b..728a99ca1e 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -14,10 +14,11 @@ import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
+import useImagePreviewActions from '../hooks/useImagePreviewActions';
import {
- listVideoHistory, deleteVideoHistoryItem, extractLastFrame, stitchVideos,
+ listVideoHistory, deleteVideoHistoryItem, stitchVideos,
upscaleVideo,
- listImageGallery, deleteImage, cleanGalleryImage,
+ listImageGallery, deleteImage,
} from '../services/api';
const FILTERS = [
@@ -136,42 +137,18 @@ export default function MediaHistory() {
}
};
- const handleContinue = async (item) => {
- try {
- const { filename } = await extractLastFrame(item.id);
- const params = new URLSearchParams({ sourceImageFile: filename });
- if (item?.width) params.set('w', String(item.width));
- if (item?.height) params.set('h', String(item.height));
- navigate(`/media/video?${params.toString()}`);
- } catch (err) {
- toast.error(err.message || 'Failed to extract last frame');
- }
- };
-
- const handleClean = async (img, level) => {
- if (!img?.filename) throw new Error('Missing filename');
- const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {
- toast.error(err.message || 'Failed to clean image');
- throw err;
- });
- const normalized = normalizeImage(cleaned);
- setItems((prev) => [normalized, ...prev.filter((x) => x.key !== normalized.key)]);
- toast.success(`Cleaned (${level}) → ${cleaned.filename}`);
- };
-
- const handleRemix = (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));
- navigate(`/media/image?${params}`);
- };
+ // Remix / SendToVideo / Continue / Clean all share a single implementation
+ // with MediaCollectionDetail, ImageGen, and the Universe Builder lightbox
+ // via `useImagePreviewActions`. Only the post-clean side effect (splicing
+ // 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 } = useImagePreviewActions({
+ onCleanComplete: (cleaned) => {
+ const normalized = normalizeImage(cleaned);
+ setItems((prev) => [normalized, ...prev.filter((x) => x.key !== normalized.key)]);
+ },
+ });
const [upscalingId, setUpscalingId] = useState(null);
const handleUpscale = async (item) => {
@@ -189,14 +166,6 @@ export default function MediaHistory() {
}
};
- const handleSendToVideo = (item) => {
- const params = new URLSearchParams({ sourceImageFile: item.filename });
- if (item.prompt && item.prompt !== '(no prompt)') params.set('prompt', item.prompt);
- const neg = item.negativePrompt || item.raw?.negativePrompt || item.raw?.negative_prompt;
- if (neg) params.set('negativePrompt', neg);
- navigate(`/media/video?${params}`);
- };
-
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2 flex-wrap">
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index e94806e0f7..104b1eb8c5 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -38,6 +38,9 @@ import EntryCard from '../components/universe/EntryCard';
import EntryThumbSlot from '../components/universe/EntryThumbSlot';
import useMediaJobProgress from '../hooks/useMediaJobProgress';
import MediaPreview from '../components/media/MediaPreview';
+import useImagePreviewActions from '../hooks/useImagePreviewActions';
+import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
+import { listImageGallery } from '../services/apiImageVideo';
import TabPills from '../components/ui/TabPills';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
@@ -684,6 +687,29 @@ export default function UniverseBuilder() {
// one covers the category-bucket rows so clicking a variation thumb opens
// the same full-detail modal the gallery / history uses.
const [preview, setPreview] = useState(null);
+ // Filename → full image-metadata-sidecar record (prompt, negativePrompt,
+ // modelId, width, height, seed, etc.). Hydrates `previewItems` with the
+ // ACTUAL prompt that was used to render the image — without this the
+ // modal would only see the variation's label, and Refine Prompt / Remix
+ // / Send to Video would all open with empty fields. Loaded once per
+ // mount via `listImageGallery()` (the same call the History page uses)
+ // and refreshed whenever a render completes (universe `runs` advances).
+ const [galleryByFilename, setGalleryByFilename] = useState(() => new Map());
+ useEffect(() => {
+ let cancelled = false;
+ listImageGallery().then((list) => {
+ if (cancelled) return;
+ const map = new Map();
+ for (const item of Array.isArray(list) ? list : []) {
+ if (item?.filename) map.set(item.filename, item);
+ }
+ setGalleryByFilename(map);
+ }).catch(() => { /* non-fatal; modal falls back to filename-only display */ });
+ return () => { cancelled = true; };
+ // Re-fetch when a new render run lands (runs array advances) so freshly
+ // rendered images pick up their metadata sidecar.
+ }, [runs.length]);
+ const { annotations, updateAnnotation } = useMediaAnnotations();
const previewItems = useMemo(() => {
const out = [];
const seen = new Set();
@@ -691,13 +717,32 @@ export default function UniverseBuilder() {
if (typeof filename !== 'string' || !filename) return;
if (seen.has(filename)) return;
seen.add(filename);
+ // Pull the real prompt + render settings out of the gallery metadata
+ // map when available so the lightbox shows the full prompt that was
+ // sent to the renderer (with universe style influences, variation
+ // prompt fragment, etc.), not just the row's display label.
+ // Falls back to the label-only shape for filenames not in the gallery
+ // (legacy renders or pending re-fetch).
+ const meta = galleryByFilename.get(filename) || null;
out.push({
key: `universe-thumb:${filename}`,
kind: 'image',
filename,
previewUrl: `/data/images/${filename}`,
downloadUrl: `/data/images/${filename}`,
- prompt: label || filename,
+ prompt: meta?.prompt || label || filename,
+ negativePrompt: meta?.negativePrompt || null,
+ modelId: meta?.modelId || meta?.model || null,
+ width: meta?.width ?? null,
+ height: meta?.height ?? null,
+ seed: meta?.seed ?? null,
+ steps: meta?.steps ?? null,
+ guidance: meta?.guidance ?? null,
+ quantize: meta?.quantize ?? null,
+ // `raw` carries the original sidecar so MediaLightbox's "Refine
+ // Prompt" / clean / remix downstream handlers can pull any field
+ // the spec doesn't surface at the top level.
+ raw: meta,
});
};
const cats = draft?.categories && typeof draft.categories === 'object' ? draft.categories : {};
@@ -714,7 +759,22 @@ export default function UniverseBuilder() {
for (const f of refs) pushFilename(f, `Composite · ${s.label}`);
}
return out;
- }, [draft]);
+ }, [draft, galleryByFilename]);
+ // Shared preview action handlers (Remix / SendToVideo / Clean) so the
+ // universe lightbox opens the same downstream pages with the same params
+ // as the History grid + Image Gen page. `onCleanComplete` splices the
+ // cleaned image into the local gallery map so the next preview open
+ // shows it immediately — no full refetch needed.
+ const previewActions = useImagePreviewActions({
+ onCleanComplete: useCallback((cleaned) => {
+ if (!cleaned?.filename) return;
+ setGalleryByFilename((prev) => {
+ const next = new Map(prev);
+ next.set(cleaned.filename, cleaned);
+ return next;
+ });
+ }, []),
+ });
const openVariationPreview = useCallback((filename) => {
if (!filename) return;
const match = previewItems.find((i) => i.filename === filename);
@@ -2042,8 +2102,22 @@ export default function UniverseBuilder() {
`previewItems` above — they're handled there. Mounted at the page
level (not inside RenderTab) so the lightbox state is in scope; it
renders regardless of active tab because variation thumbs in the
- Cast / Places / Objects / Other tabs all open the same modal. */}
- <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />
+ Cast / Places / Objects / Other tabs all open the same modal.
+ Action handlers (Remix / SendToVideo / Clean / Continue) and the
+ annotations channel come from the shared `useImagePreviewActions`
+ + `useMediaAnnotations` hooks so the surface matches History /
+ MediaCollectionDetail / ImageGen exactly. */}
+ <MediaPreview
+ preview={preview}
+ setPreview={setPreview}
+ items={previewItems}
+ annotations={annotations}
+ updateAnnotation={updateAnnotation}
+ onRemix={previewActions.handleRemix}
+ onSendToVideo={previewActions.handleSendToVideo}
+ onClean={(item, level) => previewActions.handleClean(item?.raw || item, level)}
+ onContinue={(item) => previewActions.handleContinue(item?.raw || item)}
+ />
</div>
);
}