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
feat: deep-link image preview modal + unify Universe cast preview with Media History
[._.]/ Adam Eivy1ad265f408b2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 30d810f8a5..702c7a34e8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,10 +2,14 @@## Added+- **Deep-linkable image preview modals via `?preview=<filename>`.** Every page hosting `<MediaPreview>` (Media History, Media Collections, Image Gen, Video Gen, Universe Builder variations + cast, Comic Script Stage, Nouns Stage) now drives the lightbox through a `?preview=<filename>` query param, so `/media/history?preview=foo.png` or `/universe-builder/:id?tab=cast&preview=foo.png` re-opens the same image on reload and is shareable. New `usePreviewRoute(items)` hook (`client/src/hooks/usePreviewRoute.js`) owns the URL round-trip — first open pushes a history entry so the browser back button closes the modal; prev/next nav and close replace so the history stack stays clean.+- **Per-bucket exporter hash cache.** Subscription re-exports of large series no longer re-hash every referenced asset to confirm "blob already there." A new `<bucket>/assets/blobs/.index.json` sidecar maps `<sourcePath>:<mtimeMs>:<size> → <hash>` so `server/services/sharing/exporter.js#copyAssetIfPresent` skips both `sha256File` (multi-GB stream read) and the redundant `copyFile` when the cache hit's blob is still on disk. mtime change invalidates automatically because it's part of the key. A 200MB re-export drops from ~200MB of disk reads to a single JSON load + stat per asset.## Changed+- **Universe Builder cast preview now matches Media History exactly.** Clicking a cast/canon image used to open a stripped-down modal: only Refine Prompt / Add to Collection / Download, no negative prompt, no notes, and the "prompt" field showed the character description rather than the actual prompt that produced the image. The canon section's local `<MediaPreview>` is gone — canon clicks now bubble up to the page-level lightbox, which hydrates from the gallery sidecar (real prompt, negative prompt, model, seed, resolution, …) and exposes the full action set (Refine Prompt, Remix, Send to Video, Clean, Add to Collection, Download, notes, favorite). The descriptor string is kept as a fallback label only when no sidecar exists (legacy canon renders). Character reference sheets still route through `/data/image-refs/` via a `canon-sheet:<filename>` key so a basename collision with a gallery image can't misroute the preview.+- **First-run no longer silently flips :5555 from HTTP to self-signed HTTPS.** `scripts/setup-cert.js` ran on every `npm start` and, when Tailscale was unavailable, auto-generated a self-signed cert — breaking the documented `http://localhost:5555` URL and forcing a browser click-through. It now only auto-generates a self-signed cert when (a) the user explicitly passes `--self-signed`, or (b) a self-signed cert is already present (renewal path). Fresh installs without Tailscale stay HTTP-only on :5555 so the URL in the README and in `setup.sh`'s final banner just works. `setup.sh`'s "Access at:" banner is now cert-aware — when HTTPS got provisioned it prints the loopback HTTP mirror (`http://localhost:5553`) and the Tailscale hostname instead of the broken `http://localhost:5555`.- **PLAN.md — CODEX 5.5 review residue folded in.** Triaged the 2026-04-25 CODEX 5.5 product/engineering review: confirmed the six concrete bugs (Brain Feeds + Time Capsule nav coverage, `/cos/scripts` dead target, `/ask` full-height workaround, client lint, route/nav contract tests) are all shipped, and added 15 unaddressed strategic items to PLAN.md under a new `### CODEX 5.5 review residue` Backlog section (perf/bundle, polling consolidation, client error reporter, network exposure UI, unified Review Queue, health provenance chips, dashboard intent layouts, autonomy guardrails, onboarding capability map, mobile task flows, operating-loop dashboard, sidebar IA collapse, visual modes, decision/provenance pattern, teaching empty states). Enriched the existing Knowledge Legacy Future Idea with the bundle scope from the review.diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 9a0cf2d3f0..9ce0076ebd 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -28,6 +28,7 @@ import { getSettings, updateSettings } from '../../../services/apiSystem';import { listImageModels } from '../../../services/apiImageVideo';import MediaJobThumb from '../MediaJobThumb';import MediaPreview from '../../media/MediaPreview';+import usePreviewRoute from '../../../hooks/usePreviewRoute';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';import ExtractCanonButton from './ExtractCanonButton';@@ -179,8 +180,8 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actionsconst [sysSettings, setSysSettings] = useState(null);// Shared lightbox state. PageRow reports its rendered filename up via// `onFilenameKnown` so the parent can build a navigable items list keyed by- // page order — preview prev/next walks rendered pages in page order.- const [preview, setPreview] = useState(null);+ // page order — preview prev/next walks rendered pages in page order. URL-+ // driven via `usePreviewRoute(previewItems)` below so the modal deep-links.const [filenameByJobId, setFilenameByJobId] = useState({});const onFilenameKnown = useCallback((jobId, filename) => {if (!jobId || !filename) return;@@ -200,34 +201,31 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions}), []);const previewItems = useMemo(() => {const pageList = Array.isArray(comicPages.pages) ? comicPages.pages : [];- return pageList- .map((p, idx) => {- // Prefer the hi-res final when present; fall back to proof (or legacy)- // so users still see something while the final renders or before they- // upgrade a page to a final render.- const slot = getPreferredSlot(p);- if (!slot?.jobId) return null;+ const out = [];+ // Include BOTH proof + final slots when both exist so URL-driven+ // resolution by filename picks the slot whose prompt produced *this*+ // image. Filenames are unique per render so the two entries never+ // collide. Final is listed first so a deep-link to a page that has+ // both shows the hi-res variant.+ pageList.forEach((p, idx) => {+ for (const slot of [getFinalSlot(p), getProofSlot(p)]) {+ if (!slot?.jobId) continue;const filename = slot.filename || filenameByJobId[slot.jobId];- if (!filename) return null;- return buildPageItem(idx, slot, filename);- })- .filter(Boolean);+ if (!filename) continue;+ // De-dupe in case a legacy record stores the same filename in both+ // slots (older pre-proof renders).+ if (out.some((i) => i.filename === filename)) continue;+ out.push(buildPageItem(idx, slot, filename));+ }+ });+ return out;}, [comicPages.pages, filenameByJobId, buildPageItem]);- const openPreview = useCallback((pageIndex, filename, page) => {+ const [preview, setPreview] = usePreviewRoute(previewItems);+ const openPreview = useCallback((pageIndex, filename) => {if (!filename) return;- // Proof and final renders carry their own prompts (the user can re-render- // one without the other), so match the clicked filename against each slot- // to surface the prompt that produced *this* image. A slot's filename can- // still be null while the job is in-flight, so also consult the- // jobId→filename map the thumbs report up via onFilenameKnown.- const finalSlot = getFinalSlot(page);- const proofSlot = getProofSlot(page);- const matches = (slot) => !!slot && (- slot.filename === filename || (slot.jobId && filenameByJobId[slot.jobId] === filename)- );- const slot = [finalSlot, proofSlot].find(matches) || getPreferredSlot(page);- setPreview(buildPageItem(pageIndex, slot, filename));- }, [buildPageItem, filenameByJobId]);+ const match = previewItems.find((i) => i.filename === filename);+ if (match) setPreview(match);+ }, [previewItems, setPreview]);const availableBackends = useMemo(() => deriveAvailableBackends(sysSettings, { excludeExternal: true }),[sysSettings],diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex dd81acb245..8e2382f4c2 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -33,6 +33,7 @@ import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';import { universeStylePreset } from '../../../lib/universeStylePreset';import useMounted from '../../../hooks/useMounted';+import usePreviewRoute from '../../../hooks/usePreviewRoute';import CanonCard from '../CanonCard';import MediaPreview from '../../media/MediaPreview';import Drawer from '../../Drawer';@@ -85,8 +86,9 @@ export default function NounsStage({ issue, series }) {const [renderingJobs, setRenderingJobs] = useState({});// Shared lightbox state — a flat items list across every kind's imageRefs// powers prev/next nav so the user can page through every reference image- // without closing/reopening.- const [preview, setPreview] = useState(null);+ // without closing/reopening. URL-driven via `usePreviewRoute(previewItems)`+ // so the modal is deep-linkable (`?preview=<filename>`); the hook is+ // declared just after the `previewItems` build below.// Canon lives on the linked universe. An orphan series (no universeId)// renders the link-required gate instead of this body, so by the time@@ -112,11 +114,12 @@ export default function NounsStage({ issue, series }) {}return items;}, [universe]);+ const [preview, setPreview] = usePreviewRoute(previewItems);const openPreview = useCallback((filename) => {if (!filename) return;const match = previewItems.find((i) => i.filename === filename);if (match) setPreview(match);- }, [previewItems]);+ }, [previewItems, setPreview]);const availableBackends = useMemo(() => deriveAvailableBackends(sysSettings, { excludeExternal: true }),diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex 8fd78539e3..e6ef9ec26c 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -33,7 +33,6 @@ import { composeCleanPlatePrompt } from '../../lib/cleanPlatePrompt';import { useAsyncAction } from '../../hooks/useAsyncAction';import useMounted from '../../hooks/useMounted';import CanonCard from '../pipeline/CanonCard';-import MediaPreview from '../media/MediaPreview';import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';import { universeStylePreset } from '../../lib/universeStylePreset';import { descriptorForCanonEntry } from '../../lib/canonPrompt';@@ -72,6 +71,11 @@ export default function UniverseCanonSection({// queue accumulates completed jobIds forever and a follow-up batch render// would show the previous run's image instead of the new spinner.onExternalCanonJobSettled = null,+ // Thumbnail click handler: `(filename, { isSheet? }) => void`. The parent+ // (UniverseBuilder) owns the lightbox so every page surface shares one+ // MediaPreview instance with the full action set + sidecar-hydrated prompt.+ // When null (defensive — should always be supplied) clicks no-op.+ onPreview = null,}) {const mountedRef = useMounted();const [searchParams, setSearchParams] = useSearchParams();@@ -87,7 +91,6 @@ export default function UniverseCanonSection({const togglingLockRef = useRef(null);const [extractText, setExtractText] = useState('');const [extractOpen, setExtractOpen] = useState(false);- const [preview, setPreview] = useState(null);// Per-canon-entry usage map: `{ characters: { [entryId]: [{seriesId, seriesName, issueCount, ...}] }, ... }`.// Loaded lazily — usage is a derived view and shouldn't block the initial// paint. Refetched after mutations that change the canon shape (extract /@@ -180,53 +183,15 @@ export default function UniverseCanonSection({return out;}, [universe, usage, seriesFilter]);- const previewItems = useMemo(() => {- if (!universe) return [];- const out = [];- for (const kind of KINDS) {- const list = Array.isArray(universe[kind.key]) ? universe[kind.key] : [];- for (const entry of list) {- const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];- for (const filename of refs) {- out.push({- key: `canon:${filename}`,- kind: 'image',- filename,- previewUrl: `/data/images/${filename}`,- downloadUrl: `/data/images/${filename}`,- prompt: `${entry.name}: ${kind.descFor(entry) || ''}`.trim().replace(/:\s*$/, ''),- });- }- // Reference sheets live in data/image-refs/ — different static prefix- // than the gallery. Built into the same list so the existing- // MediaPreview lightbox + arrow navigation work uniformly.- if (kind.key === 'characters' && typeof entry.referenceSheetImageRef === 'string' && entry.referenceSheetImageRef) {- const filename = entry.referenceSheetImageRef;- out.push({- key: `canon-sheet:${filename}`,- kind: 'image',- filename,- previewUrl: `/data/image-refs/${filename}`,- downloadUrl: `/data/image-refs/${filename}`,- prompt: `${entry.name} — character reference sheet`,- });- }- }- }- return out;- }, [universe]);-+ // Thumbnail click → bubbles to the parent's `onPreview(filename, opts)` so+ // the page-level MediaPreview opens the unified lightbox (full action set,+ // sidecar-hydrated prompt). `isSheet` is forwarded so the parent can route+ // reference-sheet clicks through the `/data/image-refs/` static prefix+ // instead of `/data/images/`.const openPreview = useCallback((filename, opts) => {- if (!filename) return;- // Match on the kind-tagged key when the caller indicates a sheet —- // gallery `imageRefs[]` and `referenceSheetImageRef` can theoretically- // collide on basename, in which case a filename-only find would route- // the lightbox to the wrong static prefix (/data/images vs /data/image-refs).- const targetKey = opts?.isSheet ? `canon-sheet:${filename}` : `canon:${filename}`;- const match = previewItems.find((i) => i.key === targetKey)- || previewItems.find((i) => i.filename === filename);- if (match) setPreview(match);- }, [previewItems]);+ if (!filename || typeof onPreview !== 'function') return;+ onPreview(filename, opts);+ }, [onPreview]);const [runExtract, extracting] = useAsyncAction(() => extractUniverseCanon(universeId, { corpus: extractText.trim() }),@@ -674,7 +639,6 @@ export default function UniverseCanonSection({/>))}- <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} /></section>);}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 12d7aa91ca..ecf26502db 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -44,6 +44,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMediaCompletionRefresh` | Refetch on image/video completion socket events. | A list view that needs to refresh when new media lands. || `useOpenClawAttachments` | File attachment handling (base64, size-capped). | OpenClaw attachment UI. || `useImagePreviewActions` | Shared MediaPreview / MediaLightbox action handlers. | New surface that exposes the same 4 preview actions. |+| `usePreviewRoute` | URL-driven `[preview, setPreview]` via `?preview=<filename>`. | Any page hosting `<MediaPreview>` — gives the preview a deep-link. || `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |## Sockets & lifecyclediff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 904bd6eb6e..afb3482ae2 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -18,6 +18,7 @@ export { default as useKeyboardControls } from './useKeyboardControls.js';export { default as useMediaJobProgress } from './useMediaJobProgress.js';export { default as useMoltworldWs } from './useMoltworldWs.js';export { default as useMounted } from './useMounted.js';+export { default as usePreviewRoute } from './usePreviewRoute.js';export { default as useProviderModels } from './useProviderModels.js';export { default as useRowDraft } from './useRowDraft.js';export { default as useTheme } from './useTheme.js';diff --git a/client/src/hooks/usePreviewRoute.js b/client/src/hooks/usePreviewRoute.jsnew file mode 100644index 0000000000..d449a30450--- /dev/null+++ b/client/src/hooks/usePreviewRoute.js@@ -0,0 +1,46 @@+import { useCallback, useMemo } from 'react';+import { useSearchParams } from 'react-router-dom';++// URL-driven MediaPreview state. Returns `[preview, setPreview]` with the same+// shape every MediaPreview host already expects, but the source of truth is a+// `?preview=<filename>` query param so previews are deep-linkable, reload-safe,+// and shareable. setPreview(null) drops the param; setPreview(item) writes the+// item's filename (falling back to its key).+//+// Match strategy against the host's items list (in order):+// 1. exact filename match+// 2. exact key match (so callers can deep-link by `key` when filenames collide+// across different static prefixes — e.g. `canon-sheet:foo.png`)+// 3. key suffix `:<filename>` (so the bare-filename URL still resolves to+// keys like `image:foo.png` / `canon:foo.png`)+//+// Push vs replace: the first transition closed→open pushes a history entry so+// the browser back button closes the modal. Subsequent prev/next navigation+// and the open→closed transition use replace so the gallery doesn't pollute+// the history stack.+export default function usePreviewRoute(items, { paramName = 'preview' } = {}) {+ const [searchParams, setSearchParams] = useSearchParams();+ const previewParam = searchParams.get(paramName);++ const preview = useMemo(() => {+ if (!previewParam) return null;+ const list = Array.isArray(items) ? items : [];+ return (+ list.find((i) => i?.filename === previewParam)+ || list.find((i) => i?.key === previewParam)+ || list.find((i) => typeof i?.key === 'string' && i.key.endsWith(`:${previewParam}`))+ || null+ );+ }, [items, previewParam]);++ const setPreview = useCallback((item) => {+ const wasOpen = !!searchParams.get(paramName);+ const isOpen = !!item;+ const next = new URLSearchParams(searchParams);+ if (!item) next.delete(paramName);+ else next.set(paramName, item.filename || item.key || '');+ setSearchParams(next, { replace: wasOpen || !isOpen });+ }, [searchParams, setSearchParams, paramName]);++ return [preview, setPreview];+}diff --git a/client/src/hooks/usePreviewRoute.test.jsx b/client/src/hooks/usePreviewRoute.test.jsxnew file mode 100644index 0000000000..8b1a7cea7d--- /dev/null+++ b/client/src/hooks/usePreviewRoute.test.jsx@@ -0,0 +1,69 @@+import { describe, it, expect } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router-dom';+import usePreviewRoute from './usePreviewRoute';++// Wraps the hook with a MemoryRouter so `useSearchParams` resolves. The+// second hook (`useLocation`) gives the assertions a peek at the resulting+// URL — that's the contract this hook is defining (deep-link friendliness),+// so it's what the tests assert on.+const renderWithRouter = (items, initial = '/x') => {+ const wrapper = ({ children }) => (+ <MemoryRouter initialEntries={[initial]}>{children}</MemoryRouter>+ );+ return renderHook(() => ({+ pair: usePreviewRoute(items),+ location: useLocation(),+ }), { wrapper });+};++const FOO = { key: 'image:foo.png', filename: 'foo.png', prompt: 'foo' };+const BAR = { key: 'image:bar.png', filename: 'bar.png', prompt: 'bar' };+const SHEET = { key: 'canon-sheet:foo.png', filename: 'foo.png', prompt: 'sheet' };++describe('usePreviewRoute', () => {+ it('returns null when no `preview` query param is present', () => {+ const { result } = renderWithRouter([FOO, BAR]);+ expect(result.current.pair[0]).toBeNull();+ });++ it('resolves the param to the matching item by filename', () => {+ const { result } = renderWithRouter([FOO, BAR], '/x?preview=bar.png');+ expect(result.current.pair[0]).toBe(BAR);+ });++ it('falls back to exact key match when filenames collide', () => {+ // SHEET listed first so a filename-only resolver would return it; the+ // key path is what lets a caller deep-link the gallery copy by key.+ const { result } = renderWithRouter([SHEET, FOO], '/x?preview=image:foo.png');+ expect(result.current.pair[0]).toBe(FOO);+ });++ it('returns null for a stale param that has no matching item', () => {+ const { result } = renderWithRouter([FOO], '/x?preview=does-not-exist.png');+ expect(result.current.pair[0]).toBeNull();+ });++ it('setPreview(item) writes the filename to the URL', () => {+ const { result } = renderWithRouter([FOO, BAR]);+ act(() => result.current.pair[1](BAR));+ expect(result.current.location.search).toContain('preview=bar.png');+ expect(result.current.pair[0]).toBe(BAR);+ });++ it('setPreview(null) drops the preview param but preserves siblings', () => {+ const { result } = renderWithRouter([FOO, BAR], '/x?preview=foo.png&tab=cast');+ act(() => result.current.pair[1](null));+ expect(result.current.location.search).not.toContain('preview=');+ expect(result.current.location.search).toContain('tab=cast');+ expect(result.current.pair[0]).toBeNull();+ });++ it('prev/next round-trip swaps the param on the URL', () => {+ const { result } = renderWithRouter([FOO, BAR], '/x?preview=foo.png');+ expect(result.current.pair[0]).toBe(FOO);+ act(() => result.current.pair[1](BAR));+ expect(result.current.location.search).toContain('preview=bar.png');+ expect(result.current.pair[0]).toBe(BAR);+ });+});diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 6b0e729208..670d547c54 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -26,6 +26,7 @@ import LoraPicker from '../components/imageGen/LoraPicker';import MediaJobsQueue from '../components/media/MediaJobsQueue';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';+import usePreviewRoute from '../hooks/usePreviewRoute';import {Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,AlertTriangle, X, Film,@@ -107,7 +108,8 @@ export default function ImageGen() {const [models, setModels] = useState([]);const [availableLoras, setAvailableLoras] = useState([]);const [gallery, setGallery] = useState([]);- const [preview, setPreview] = useState(null);+ // `preview` is URL-driven via `usePreviewRoute(previewItems)` — declared+ // after `previewItems` below so the resolver can match against it.const [showHidden, setShowHidden] = useState(false);const [favoritesOnly, setFavoritesOnly] = useState(false);const { annotations, updateAnnotation, getCardProps } = useMediaAnnotations();@@ -537,6 +539,7 @@ export default function ImageGen() {...visibleGallery.map(normalizeImage),...(showHidden ? hiddenGallery.map(normalizeImage) : []),], [visibleGallery, hiddenGallery, showHidden]);+ const [preview, setPreview] = usePreviewRoute(previewItems);// Snapshots current form state into a server payload + POSTs it to the// mediaJobQueue. Returns the queue's response ({ jobId, position, ... }).diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex c15bdc6a9e..345f42b283 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -17,6 +17,7 @@ import {deleteImage, deleteVideoHistoryItem,} from '../services/api';import useImagePreviewActions from '../hooks/useImagePreviewActions';+import usePreviewRoute from '../hooks/usePreviewRoute';// Hydrate a collection's "<kind>:<ref>" pointer list into the same// normalized records MediaCard expects. We do this on the client so the@@ -53,7 +54,8 @@ export default function MediaCollectionDetail() {const [loading, setLoading] = useState(true);const [editingName, setEditingName] = useState(false);const [nameDraft, setNameDraft] = useState('');- const [preview, setPreview] = useState(null);+ // Preview state is URL-driven (`?preview=<filename>`) — see `usePreviewRoute`+ // call below, declared after `items` so the resolver can match against it.const [selectMode, setSelectMode] = useState(false);const [selected, setSelected] = useState(new Set());const [bulkBusy, setBulkBusy] = useState(false);@@ -100,6 +102,7 @@ export default function MediaCollectionDetail() {() => collection ? hydrate(collection, imagesByName, videosById) : [],[collection, imagesByName, videosById]);+ const [preview, setPreview] = usePreviewRoute(items);const handleRename = async () => {const trimmed = nameDraft.trim();diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex 728a99ca1e..94ce8f56fb 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -15,6 +15,7 @@ import { normalizeImage, normalizeVideo } from '../components/media/normalize';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';import useImagePreviewActions from '../hooks/useImagePreviewActions';+import usePreviewRoute from '../hooks/usePreviewRoute';import {listVideoHistory, deleteVideoHistoryItem, stitchVideos,upscaleVideo,@@ -36,9 +37,12 @@ export default function MediaHistory() {const [stitchMode, setStitchMode] = useState(false);const [selected, setSelected] = useState([]); // video idsconst [stitching, setStitching] = useState(false);- const [preview, setPreview] = useState(null);const [favoritesOnly, setFavoritesOnly] = useState(false);const { annotations, toggleStar, updateAnnotation, getCardProps } = useMediaAnnotations();+ // URL-driven preview (`?preview=<filename>`) so the lightbox is deep-linkable.+ // Match against the full `items` list (not the filtered view) so a shared link+ // still opens even when the recipient's filter doesn't include that image.+ const [preview, setPreview] = usePreviewRoute(items);const refresh = useCallback(async ({ silent = false } = {}) => {if (!silent) setLoading(true);diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 5795ee71ff..a1f2f06545 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -39,13 +39,14 @@ import EntryThumbSlot from '../components/universe/EntryThumbSlot';import useMediaJobProgress from '../hooks/useMediaJobProgress';import MediaPreview from '../components/media/MediaPreview';import useImagePreviewActions from '../hooks/useImagePreviewActions';+import usePreviewRoute from '../hooks/usePreviewRoute';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';import { normalizeSlugline } from '../lib/scenePrompt';-import { hasCanonDescriptorContent } from '../lib/canonPrompt';+import { hasCanonDescriptorContent, descriptorForCanonEntry } from '../lib/canonPrompt';import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';import { BIBLE_LIMITS } from '../lib/bibleLimits';@@ -693,11 +694,15 @@ export default function UniverseBuilder() {);const [runs, setRuns] = useState([]);- // Page-level lightbox state for variation + composite-sheet thumbs. Canon- // entries route through `UniverseCanonSection`'s own MediaPreview; this- // 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);+ // Page-level lightbox state. Single MediaPreview at this level covers+ // EVERY thumb on the page: variations, composite sheets, canon imageRefs,+ // and character reference sheets — so clicking any image opens the same+ // full-detail modal History / Collections / ImageGen use, with the same+ // actions (Refine / Remix / SendToVideo / Clean / AddToCollection /+ // Download / notes). Canon previews used to live inside UniverseCanonSection+ // and showed only a refine/add/download subset against the character+ // description; lifting state up here is what unifies them. URL-driven+ // (`?preview=<filename>`) via `usePreviewRoute(previewItems)` below.// 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@@ -782,8 +787,44 @@ export default function UniverseBuilder() {const refs = Array.isArray(s?.imageRefs) ? s.imageRefs : [];for (const f of refs) pushFilename(f, `Composite · ${s.label}`);}+ // Canon refs — characters / places / objects. Hydrate from the gallery+ // sidecar so the modal shows the ACTUAL render prompt (the same one the+ // History page sees), not just the character description. The descriptor+ // string is only used as a fallback label when no sidecar exists (legacy+ // canon renders without metadata). Character reference sheets live in a+ // different static prefix (`/data/image-refs/`) so they get a dedicated+ // `canon-sheet:<filename>` key + don't collide with gallery entries.+ const canonKinds = [+ { key: 'characters', singular: 'character' },+ { key: 'places', singular: 'place' },+ { key: 'objects', singular: 'object' },+ ];+ for (const kind of canonKinds) {+ const list = Array.isArray(draft?.[kind.key]) ? draft[kind.key] : [];+ for (const entry of list) {+ const descriptor = descriptorForCanonEntry(kind.key, entry) || '';+ const fallbackLabel = `${entry.name}${descriptor ? `: ${descriptor}` : ''}`;+ const refs = Array.isArray(entry?.imageRefs) ? entry.imageRefs : [];+ for (const f of refs) pushFilename(f, fallbackLabel);+ if (kind.key === 'characters' && typeof entry.referenceSheetImageRef === 'string' && entry.referenceSheetImageRef) {+ const filename = entry.referenceSheetImageRef;+ if (!seen.has(filename)) {+ seen.add(filename);+ out.push({+ key: `canon-sheet:${filename}`,+ kind: 'image',+ filename,+ previewUrl: `/data/image-refs/${filename}`,+ downloadUrl: `/data/image-refs/${filename}`,+ prompt: `${entry.name} — character reference sheet`,+ });+ }+ }+ }+ }return out;}, [draft, galleryByFilename]);+ const [preview, setPreview] = usePreviewRoute(previewItems);// 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@@ -799,11 +840,22 @@ export default function UniverseBuilder() {});}, []),});- const openVariationPreview = useCallback((filename) => {+ // Generic filename → preview opener used by every clickable thumb on the+ // page (variation grids, composite sheets, canon entries, character+ // reference sheets). `opts.isSheet` forces a key match against the+ // `canon-sheet:` prefix so a basename collision with a gallery image+ // can't route the lightbox to `/data/images/` instead of+ // `/data/image-refs/`.+ const openPreviewByFilename = useCallback((filename, opts) => {if (!filename) return;- const match = previewItems.find((i) => i.filename === filename);+ const targetKey = opts?.isSheet ? `canon-sheet:${filename}` : null;+ const match = (targetKey && previewItems.find((i) => i.key === targetKey))+ || previewItems.find((i) => i.filename === filename);if (match) setPreview(match);- }, [previewItems]);+ }, [previewItems, setPreview]);+ // Legacy name retained for the variation/composite call sites that pass a+ // single filename — same implementation, different label.+ const openVariationPreview = openPreviewByFilename;// Two-click delete: first click flips this to the world id; a second// click within the live render confirms. Avoids window.confirm per@@ -1980,6 +2032,7 @@ export default function UniverseBuilder() {onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}onPreviewVariation={openVariationPreview}+ onCanonPreview={openPreviewByFilename}pendingByEntryId={pendingHeadByEntryId}externalPendingByEntryId={pendingHeadByEntryId}onPendingCleared={clearPendingForEntry}@@ -2127,18 +2180,17 @@ export default function UniverseBuilder() {)}</section>- {/* Page-level lightbox for variation + composite-sheet thumb clicks.- UniverseCanonSection owns its own MediaPreview for canon entries- (which routes character reference sheets through a different- static prefix), so we deliberately don't include canon refs in- `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.- 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. */}+ {/* Single page-level lightbox for every thumb on the page: variation+ grids, composite sheets, canon imageRefs (characters / places /+ objects), and character reference sheets. UniverseCanonSection used+ to host its own MediaPreview with a reduced action set + character+ description in place of the prompt; that fork is gone — canon+ clicks now bubble up through `openPreviewByFilename` and hit this+ modal, so the canon surface matches History / Collections / ImageGen+ exactly (Refine / Remix / SendToVideo / Clean / AddToCollection /+ Download / notes, all hydrated from the gallery sidecar). URL-driven+ via `usePreviewRoute` so `?preview=<filename>` deep-links open the+ same modal on reload. */}<MediaPreviewpreview={preview}setPreview={setPreview}@@ -3307,6 +3359,7 @@ export function TrunkView({onBulkRenderBucket, onRenderVariation, onBulkRenderTrunk,onAddBucket,onPreviewVariation = null,+ onCanonPreview = null,pendingByEntryId = {},// Same pending head-map, passed through to UniverseCanonSection so canon// rows show a spinner when a batch `/render` queues canon prompts.@@ -3413,6 +3466,7 @@ export function TrunkView({kindFilter={trunk.kind}externalPendingByEntryId={externalPendingByEntryId}onExternalCanonJobSettled={onPendingCleared}+ onPreview={onCanonPreview}/>) : null}diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex aabd52bcab..c30f4a8cf0 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -45,6 +45,7 @@ import FavoritesFilterChip from '../components/media/FavoritesFilterChip';import ModelSelect from '../components/ModelSelect';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';+import usePreviewRoute from '../hooks/usePreviewRoute';import {getVideoGenStatus, generateVideo, cancelVideoGen,listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,@@ -183,7 +184,8 @@ export default function VideoGen() {}, [incomingWidth, incomingHeight]);const [history, setHistory] = useState([]);- const [preview, setPreview] = useState(null);+ // `preview` is URL-driven via `usePreviewRoute(previewItems)` — declared+ // after `previewItems` below so the resolver can match against it.const [showHidden, setShowHidden] = useState(false);const navigate = useNavigate();@@ -233,6 +235,7 @@ export default function VideoGen() {...galleryVisible.map(normalizeVideo),...(showHidden ? galleryHidden.map(normalizeVideo) : []),], [galleryVisible, galleryHidden, showHidden]);+ const [preview, setPreview] = usePreviewRoute(previewItems);const handleDeleteHistory = async (item) => {await deleteVideoHistoryItem(item.id).catch((err) => toast.error(err.message || 'Delete failed'));