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
show the prompt the renderer was sent in lightboxes opened from pipeline, music-video and deck pages (#7343)
[._.]/ Adam Eivy32ba6c8447c1
diff --git a/client/src/components/media/MediaPreview.jsx b/client/src/components/media/MediaPreview.jsxindex 75125923e9..516f9c67f9 100644--- a/client/src/components/media/MediaPreview.jsx+++ b/client/src/components/media/MediaPreview.jsx@@ -49,9 +49,24 @@ export default function MediaPreview({// drives prev/next nav — so if the cleaned copy was auto-filed into this// page's source collection, both variants are present and the toggle// appears. Returns null for non-image previews or single-variant items.+ //+ // `preview` is substituted for its own entry in that list first. A host that+ // hydrates the OPEN item only (`useHydratedPreviewRoute`) learns `cleanedFrom`+ // for the preview and not for the row it came from — and this scan matches+ // cleaned copies by reading `cleanedFrom` off the LIST, so without the+ // substitution the open cleaned image never finds its own original and the+ // toggle stays inert on exactly the pages that hydrate lazily.+ const variantItems = useMemo(() => {+ if (!preview || !Array.isArray(items)) return items;+ const index = items.findIndex((i) => i?.key === preview.key);+ if (index === -1 || items[index] === preview) return items;+ const next = items.slice();+ next[index] = preview;+ return next;+ }, [items, preview]);const variantGroup = useMemo(- () => computeImageVariantGroup(preview, items),- [preview, items]+ () => computeImageVariantGroup(preview, variantItems),+ [preview, variantItems]);const onSelectVariant = useCallback((nextItem) => {if (!nextItem) return;diff --git a/client/src/components/media/MediaPreview.test.jsx b/client/src/components/media/MediaPreview.test.jsxindex f9ffd63e0d..a14680dbb1 100644--- a/client/src/components/media/MediaPreview.test.jsx+++ b/client/src/components/media/MediaPreview.test.jsx@@ -15,12 +15,17 @@ vi.mock('../../services/apiImageVideo', () => ({// its own interaction coverage; this stub exposes the item it receives and// invokes the same callback the real Save prompt button uses.vi.mock('./MediaLightbox', () => ({- default: ({ item, onPromptChange }) => item ? (+ default: ({ item, onPromptChange, variantGroup }) => item ? (<div data-testid="lightbox"><span data-testid="lightbox-prompt">{item.prompt}</span><button type="button" onClick={() => onPromptChange(item, 'a saved prompt')}>Save prompt</button>+ {variantGroup && (+ <ul data-testid="variant-group">+ {variantGroup.group.map((v) => <li key={v.item.key}>{v.label}</li>)}+ </ul>+ )}</div>) : null,}));@@ -105,3 +110,30 @@ describe('MediaPreview prompt saving', () => {expect(screen.getByTestId('location')).toHaveTextContent('preview=video%3Avideo-1');});});++describe('MediaPreview variant group', () => {+ // A host that hydrates only the OPEN item (`useHydratedPreviewRoute`) hands+ // us a `preview` carrying `cleanedFrom` while the row it came from — still in+ // `items` — does not. The variant scan reads `cleanedFrom` off the list, so+ // the preview has to stand in for its own row or the toggle never appears on+ // exactly the pages that hydrate lazily.+ const ORIGINAL = { kind: 'image', key: 'image:shot.png', filename: 'shot.png', prompt: 'a shot' };+ const CLEANED_ROW = { kind: 'image', key: 'image:shot_clean.png', filename: 'shot_clean.png', prompt: 'a shot' };+ const CLEANED_HYDRATED = { ...CLEANED_ROW, cleanedFrom: 'shot.png', cleanLevel: 'light' };++ const renderWith = (preview) => render(+ <MemoryRouter>+ <MediaPreview preview={preview} setPreview={() => {}} items={[ORIGINAL, CLEANED_ROW]} />+ </MemoryRouter>,+ );++ it('pairs a lazily hydrated cleaned image with its original', () => {+ renderWith(CLEANED_HYDRATED);+ expect(screen.getByTestId('variant-group').textContent).toBe('OriginalCleaned (light)');+ });++ it('renders no toggle when nothing in the set is a cleaned copy', () => {+ renderWith(ORIGINAL);+ expect(screen.queryByTestId('variant-group')).toBeNull();+ });+});diff --git a/client/src/components/media/PinToMoodBoardMenu.jsx b/client/src/components/media/PinToMoodBoardMenu.jsxindex e420dcff26..717e25cad3 100644--- a/client/src/components/media/PinToMoodBoardMenu.jsx+++ b/client/src/components/media/PinToMoodBoardMenu.jsx@@ -18,7 +18,7 @@ import {// `item` is the normalized MediaCard shape: `item.previewUrl` is a renderable// thumbnail URL (or null), and `item.key` is usually a `<kind>:<ref>` media-key// (e.g. `image:foo.png`, `video:job-123`) — but NOT always: the lightbox is-// also used for synthetic items keyed `canon-sheet:…`, `comic-page:…`, `noun:…`+// also used for synthetic items keyed `canon-sheet:…`, `comic-page:…`// that the server's media-key validator rejects. So we pin a real mediaKey only// when the key is a valid `image:`/`video:` media-key (for source linkage +// dedup), and fall back to an imageUrl-only pin otherwise — keying membership@@ -67,7 +67,7 @@ export default function PinToMoodBoardMenu({ item, size = 'sm' }) {const triggerRef = useRef(null);// A real media-key only when it matches the server vocabulary; synthetic keys- // (canon-sheet:/comic-page:/noun:) fall through to an imageUrl-only pin.+ // (canon-sheet:/comic-page:) fall through to an imageUrl-only pin.const mediaKey = isValidMediaKey(item.key) ? item.key : null;// Only http(s) / absolute app paths are valid imageUrls (mirror the board// item schema, which rejects a protocol-relative `//host` path even though itdiff --git a/client/src/components/media/PinToMoodBoardMenu.test.jsx b/client/src/components/media/PinToMoodBoardMenu.test.jsxindex 060b7cef38..c563be02b0 100644--- a/client/src/components/media/PinToMoodBoardMenu.test.jsx+++ b/client/src/components/media/PinToMoodBoardMenu.test.jsx@@ -142,7 +142,7 @@ describe('PinToMoodBoardMenu', () => {it('renders nothing when there is no valid media-key and no renderable thumbnail', () => {const { container } = render(- <PinToMoodBoardMenu item={{ kind: 'image', key: 'noun:x.png', previewUrl: 'blob:abc' }} />,+ <PinToMoodBoardMenu item={{ kind: 'image', key: 'comic-page:x.png', previewUrl: 'blob:abc' }} />,);expect(container).toBeEmptyDOMElement();expect(screen.queryByTitle('Pin to mood board')).toBeNull();diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex b37846d1e5..b1a243dff9 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -37,9 +37,10 @@ import { buildUniverseSectionRenderTag } from '../../../lib/universeRunTag';import useMounted from '../../../hooks/useMounted';import useUniverse from '../../../hooks/useUniverse';import { useCanonPatch } from '../../../hooks/useCanonPatch';-import usePreviewRoute from '../../../hooks/usePreviewRoute';+import useHydratedPreviewRoute from '../../../hooks/useHydratedPreviewRoute';import CanonCard from '../CanonCard';import MediaPreview from '../../media/MediaPreview';+import { normalizeImage } from '../../media/normalize';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';import {@@ -104,9 +105,10 @@ export default function NounsStage({ issue, series, onStageUpdate }) {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. URL-driven via `usePreviewRoute(previewItems)`- // so the modal is deep-linkable (`?preview=<filename>`); the hook is- // declared just after the `previewItems` build below.+ // without closing/reopening. URL-driven via+ // `useHydratedPreviewRoute(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@@ -119,20 +121,20 @@ export default function NounsStage({ issue, series, onStageUpdate }) {for (const entry of list) {const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];for (const filename of refs) {- items.push({- key: `noun:${filename}`,- kind: 'image',+ // The name + description is only a LABEL — the renderer was sent it+ // under the universe style clause and any `series.stylePromptOverride`+ // (see `handleRenderRef`), so `useHydratedPreviewRoute` hydrates the+ // open item from its sidecar and this stands in until that lands.+ items.push(normalizeImage({filename,- previewUrl: `/data/images/${filename}`,- downloadUrl: `/data/images/${filename}`,prompt: `${entry.name}: ${kind.descFor(entry) || ''}`.trim().replace(/:\s*$/, ''),- });+ }));}}}return items;}, [universe]);- const [preview, setPreview] = usePreviewRoute(previewItems);+ const [preview, setPreview] = useHydratedPreviewRoute(previewItems);const openPreview = useCallback((filename) => {if (!filename) return;const match = previewItems.find((i) => i.filename === filename);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex a90ada634b..9ddd292450 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -70,6 +70,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMediaPreviewActions` | Shared MediaPreview / MediaLightbox action handlers (images + videos — dispatch by `item.kind`). | New surface that exposes the same 4 preview actions. || `useClonedGltf` | Clones a drei-cached GLTF scene with skeleton bindings intact and wires its animations; the colocated `GltfPrimitive` prevents R3F from disposing shared cache resources. Accepts an optional animation transform for derived clip sets. | Any skinned GLTF rendered from `useGLTF`; render its scene through `GltfPrimitive` so remounts cannot inherit disposed geometry or materials. || `usePreviewRoute` | URL-driven `[preview, setPreview]` via `?preview=<filename>`. | Any page hosting `<MediaPreview>` — gives the preview a deep-link. |+| `useHydratedPreviewRoute` | `usePreviewRoute` plus a lazy single-item lookup of the OPEN preview's gallery record (image sidecar or video-history entry), merged over the host's item. | Any page that owns its own media refs and composes a styled prompt on the way out (pipeline canon refs, music-video scenes, deck cards) — otherwise the lightbox shows a label the renderer never saw. Use eager `useGallerySidecars` when the page needs records for more than the lightbox. || `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. || `useLocalImageRuntime` | The local image runtime's verdict for one model — `{ runtime, loading, refresh }` — from `GET /api/image-gen/status?mode=local&modelId=…`, the same `diagnoseLocalRuntime` the renderer refuses against. `runtime` carries `readiness`, `reason` and a one-button `remedy`. Pass `null` while the host is still resolving which model it renders on. | Any surface whose renders can be blocked by an unhealthy local runtime: pair it with `LocalRuntimeStatus` to show the verdict and its fix, and read `readiness` to stand the surface's own Render button down. || `useDeckRenderTarget` | What a deck's next card render runs on — `{ backends, size, summary, localRuntime, blocked }` — resolving the `RENDER_TARGET.DECK` pin ladder, the card trim, and the local runtime's verdict in one call. | Any deck surface that queues a render or names the options it will use (the render bar, the card grid's per-card re-render) — resolve it once on the page and pass it down rather than probing per consumer. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex e2db2fe4a1..5a0db13b86 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -29,6 +29,7 @@ export { default as useFocusTrap } from './useFocusTrap.js';export { default as useGallerySidecars } from './useGallerySidecars.js';export { default as useNoteSave } from './useNoteSave.js';export { default as useHoverTooltip } from './useHoverTooltip.js';+export { default as useHydratedPreviewRoute } from './useHydratedPreviewRoute.js';export { default as useImageGenQueue } from './useImageGenQueue.js';export { default as useDeckRenderTarget } from './useDeckRenderTarget.js';export { default as useImageRenderSettings } from './useImageRenderSettings.js';diff --git a/client/src/hooks/useHydratedPreviewRoute.js b/client/src/hooks/useHydratedPreviewRoute.jsnew file mode 100644index 0000000000..1eb34a6f99--- /dev/null+++ b/client/src/hooks/useHydratedPreviewRoute.js@@ -0,0 +1,105 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import usePreviewRoute from './usePreviewRoute';+import { getGalleryImages, getVideoHistoryItem } from '../services/apiImageVideo';+import { normalizeImage, normalizeVideo } from '../components/media/normalize';++/**+ * `usePreviewRoute` plus lazy hydration of the OPEN item from its gallery+ * record — the image sidecar (`/image-gen/gallery/lookup`) or the video-history+ * entry.+ *+ * A page that owns its own media references composes a styled prompt on the way+ * out (universe/series style clause, project style suffix, deck style) and then+ * rebuilds a bare display label on the way back in. The lightbox then shows+ * wording that never reached the renderer, and Refine / Remix / Send to Video+ * open with that wrong prompt. The record written at render time is the only+ * thing that knows what was actually sent — along with the lineage fields+ * `MediaLightbox` needs for the original-vs-cleaned toggle and the+ * regen/watermark labels (`cleanedFrom`, `regenerated`, `watermarkRemoved`,+ * `renderMs`, `loraNames`, …), which a hand-rolled item shape drops.+ *+ * Hydrating lazily at this shared seam covers every `MediaPreview` host at once+ * and costs one single-item lookup when the modal opens, instead of a+ * whole-list POST on every page load. A page that needs records for more than+ * the lightbox (Universe Builder reads them for thumbs) still wants the eager+ * `useGallerySidecars` map.+ *+ * One item is the wrong unit for anything set-level, so lineage is only PARTLY+ * restored: `MediaPreview` substitutes the hydrated preview into the list it+ * scans, which is enough to pair an open CLEANED copy with its original, but+ * opening the original finds no cleaned sibling, because the siblings in the+ * list still carry no `cleanedFrom`. Hydrating the whole list is the only shape+ * that serves both directions — see #7346.+ *+ * The record wins on every field it carries; the host's item is the fallback,+ * and its `key` is kept outright — prev/next nav (`getAdjacentMedia`) and the+ * annotation lookup both match on it, so a key that drifted from the list would+ * silently disable both.+ *+ * Same `[preview, setPreview]` shape as `usePreviewRoute`; `options` passes+ * straight through (`paramName`, `resolveItem`).+ */+export default function useHydratedPreviewRoute(items, options) {+ const [preview, setPreview] = usePreviewRoute(items, options);+ // What the record is looked up BY: images by filename, videos by history id.+ // An item with neither (a synthetic entry backed by no gallery record) has+ // nothing to hydrate from and passes through untouched.+ const kind = preview?.kind;+ const ref = (kind === 'image' && preview.filename) || (kind === 'video' && preview.id) || null;+ // Cache the fetched records, not the merged items: the host's item identity+ // can change between opens (a re-render rebuilding the list) while the record+ // for a given filename/id does not.+ const [records, setRecords] = useState(() => new Map());+ // Every key already ATTEMPTED — hits and misses alike, so a legacy render+ // that has no record, or one whose lookup 404s, is asked for once rather than+ // on every reopen. Held in a ref so the effect can read it without taking the+ // map as a dependency and re-running on its own result (`useGallerySidecars`+ // does the same).+ const attemptedRef = useRef(new Set());++ useEffect(() => {+ const lookupKey = `${kind}:${ref}`;+ if (!ref || attemptedRef.current.has(lookupKey)) return undefined;+ let cancelled = false;+ const settle = (record) => {+ if (cancelled) return;+ attemptedRef.current.add(lookupKey);+ if (record) setRecords((prev) => new Map(prev).set(lookupKey, record));+ };+ // A failed lookup settles as a miss: non-fatal, and the host's own label+ // stands in for it.+ fetchRecord(kind, ref).then(settle, () => settle(null));+ return () => { cancelled = true; };+ }, [kind, ref]);++ const hydrated = useMemo(() => {+ const record = ref ? records.get(`${kind}:${ref}`) : null;+ return record ? mergeRecord(preview, record) : preview;+ }, [preview, kind, ref, records]);++ return [hydrated, setPreview];+}++function fetchRecord(kind, ref) {+ if (kind === 'video') return getVideoHistoryItem(ref, { silent: true });+ return getGalleryImages([ref], { silent: true })+ .then((list) => (Array.isArray(list) ? list : []).find((i) => i?.filename === ref) || null);+}++function mergeRecord(item, record) {+ const normalize = item.kind === 'video' ? normalizeVideo : normalizeImage;+ // `prompt` is the whole point, and it is the one fallback that has to happen+ // BEFORE normalize — which would otherwise substitute its own '(no prompt)'+ // for a record that carries none, burying the host's label under it.+ const merged = normalize({ ...record, prompt: record.prompt || item.prompt });+ return {+ ...merged,+ key: item.key,+ negativePrompt: merged.negativePrompt || item.negativePrompt || null,+ // A host may point at a file the normalizer can't address from the record+ // alone — a video-history entry with no thumbnail still has the host's+ // job-scoped poster.+ previewUrl: merged.previewUrl || item.previewUrl || null,+ downloadUrl: merged.downloadUrl || item.downloadUrl || null,+ };+}diff --git a/client/src/pages/DeckDetail.jsx b/client/src/pages/DeckDetail.jsxindex bf10242d31..08c05fb648 100644--- a/client/src/pages/DeckDetail.jsx+++ b/client/src/pages/DeckDetail.jsx@@ -34,9 +34,8 @@ import DeckRenderControls from '../components/decks/DeckRenderControls';import useDeckRenderTarget from '../hooks/useDeckRenderTarget';import useMounted from '../hooks/useMounted';import useUrlParams from '../hooks/useUrlParams';-import usePreviewRoute from '../hooks/usePreviewRoute';+import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute';import useFieldDraft from '../hooks/useFieldDraft';-import useGallerySidecars from '../hooks/useGallerySidecars';import { DECK_KIND_LABELS, cardInFlightJobId, composeCardRenderPrompt, deckCompletion } from '../lib/decks';import {deleteDeck, generateDeckPrompts, getDeck, listUniverseSummaries, removeDeckSample,@@ -112,33 +111,24 @@ function DeckEditor({ id }) {() => (deck && cardParam ? deck.cards.find((c) => c.id === cardParam) || null : null),[deck, cardParam],);- const cardImageRefs = useMemo(- () => (deck ? deck.cards.flatMap((c) => c.imageRefs) : []),- [deck],- );// The card's own `prompt` is only its subject line; the renderer was sent the// composed prompt (deck style clause, layout, titled subject, merged- // negatives). The sidecar records what was actually sent, so hydrate from it- // — and when there is no sidecar (a legacy render, a peer-synced one, or the- // first paint before the lookup lands), compose it locally rather than- // falling back to the subject line, which is the wording that was never sent.- const { byFilename: sidecars } = useGallerySidecars(cardImageRefs);+ // negatives), which `useHydratedPreviewRoute` reads back from the sidecar of+ // whichever card the user opens. Compose it locally as the stand-in — a+ // legacy or peer-synced render has no sidecar at all, and falling back to the+ // subject line would re-show the wording that was never sent.const previewItems = useMemo(() => (deck? deck.cards.flatMap((c) => {if (!c.imageRefs.length) return [];const composed = composeCardRenderPrompt(deck, c);- return c.imageRefs.map((filename) => {- const meta = sidecars.get(filename);- return normalizeImage({- ...meta,- filename,- prompt: meta?.prompt || composed.prompt,- negativePrompt: meta?.negativePrompt || composed.negativePrompt || null,- });- });+ return c.imageRefs.map((filename) => normalizeImage({+ filename,+ prompt: composed.prompt,+ negativePrompt: composed.negativePrompt || null,+ }));})- : []), [deck, sidecars]);- const [preview, setPreview] = usePreviewRoute(previewItems);+ : []), [deck]);+ const [preview, setPreview] = useHydratedPreviewRoute(previewItems);const previewFilename = (filename) => {const item = previewItems.find((i) => i.filename === filename);if (item) setPreview(item);diff --git a/client/src/pages/DeckDetail.preview.test.jsx b/client/src/pages/DeckDetail.preview.test.jsxindex e2e08f2390..733e9ded27 100644--- a/client/src/pages/DeckDetail.preview.test.jsx+++ b/client/src/pages/DeckDetail.preview.test.jsx@@ -6,9 +6,11 @@ import DeckDetail from './DeckDetail';// The deck page shows each card's SUBJECT prompt in its editor, but a render// was sent the composed prompt (deck style clause + layout + subject). The// lightbox must show what was actually sent, which only the image sidecar-// records — hence the gallery hydration this suite pins.+// records — hydrated lazily for the OPEN card, so a 78-card deck costs no+// lookup at all until the user opens one.const getDeck = vi.fn();const getGalleryImages = vi.fn();+const getVideoHistoryItem = vi.fn();let previewProps = null;vi.mock('../services/api', () => ({@@ -22,7 +24,10 @@ vi.mock('../services/api', () => ({updateDeck: vi.fn(),updateDeckCard: vi.fn(),}));-vi.mock('../services/apiImageVideo', () => ({ getGalleryImages: (...a) => getGalleryImages(...a) }));+vi.mock('../services/apiImageVideo', () => ({+ getGalleryImages: (...a) => getGalleryImages(...a),+ getVideoHistoryItem: (...a) => getVideoHistoryItem(...a),+}));vi.mock('../components/media/MediaPreview', () => ({default: (props) => { previewProps = props; return null; },}));@@ -34,6 +39,8 @@ vi.mock('../hooks/useDeckRenderTarget', () => ({default: () => ({ summary: 'Local · flux2 · 1096×1536', blocked: false, mode: 'local', options: [] }),}));+const COMPOSED = 'copperplate engraving. Full tarot card, framed border. The Fool: a youth at a cliff edge';+const deck = {id: 'd1',name: 'Test Deck',@@ -50,8 +57,8 @@ const deck = {}],};-const renderPage = () => render(- <MemoryRouter initialEntries={['/decks/d1']}>+const renderPage = (search = '') => render(+ <MemoryRouter initialEntries={[`/decks/d1${search}`]}><Routes><Route path="/decks/:id" element={<DeckDetail />} /></Routes></MemoryRouter>,);@@ -61,37 +68,53 @@ describe('DeckDetail preview items', () => {previewProps = null;getDeck.mockReset().mockResolvedValue(deck);getGalleryImages.mockReset();+ getVideoHistoryItem.mockReset();+ });++ it('reads no sidecars until a card is actually opened', async () => {+ getGalleryImages.mockResolvedValue([]);+ renderPage();+ // The list itself is enough to render the grid — hydration is the+ // lightbox's concern, so loading the deck must cost zero lookups.+ await waitFor(() => expect(previewProps?.items?.length).toBe(1));+ expect(getGalleryImages).not.toHaveBeenCalled();});it('shows the prompt the renderer was actually sent, not the card subject alone', async () => {getGalleryImages.mockResolvedValue([{filename: 'fool.png',- prompt: 'copperplate engraving. Full tarot card, framed border. The Fool: a youth at a cliff edge',- negativePrompt: 'blurry',+ prompt: `${COMPOSED}, hand-inked`,+ negativePrompt: 'blurry, extra fingers',modelId: 'flux2-klein-9b',seed: 42,}]);- renderPage();+ renderPage('?preview=fool.png');await waitFor(() => expect(getGalleryImages).toHaveBeenCalledWith(['fool.png'], { silent: true }));await waitFor(() => {- const item = previewProps?.items?.find((i) => i.filename === 'fool.png');- expect(item?.prompt).toBe('copperplate engraving. Full tarot card, framed border. The Fool: a youth at a cliff edge');- expect(item?.negativePrompt).toBe('blurry');- expect(item?.seed).toBe(42);+ expect(previewProps?.preview?.prompt).toBe(`${COMPOSED}, hand-inked`);+ expect(previewProps?.preview?.negativePrompt).toBe('blurry, extra fingers');+ expect(previewProps?.preview?.seed).toBe(42);});});+ it('keeps the open card addressable by its list key so prev/next still match', async () => {+ getGalleryImages.mockResolvedValue([{ filename: 'fool.png', prompt: 'whatever was sent' }]);+ renderPage('?preview=fool.png');+ await waitFor(() => expect(previewProps?.preview?.prompt).toBe('whatever was sent'));+ expect(previewProps.preview.key).toBe(previewProps.items[0].key);+ });+it('composes the prompt locally when the render has no sidecar', async () => {// A legacy or peer-synced render has no sidecar, and nothing does before// the lookup lands. The composed prompt is derivable right here — falling// back to the card's subject line would re-show the wording that was// never sent.getGalleryImages.mockResolvedValue([]);- renderPage();+ renderPage('?preview=fool.png');+ await waitFor(() => expect(getGalleryImages).toHaveBeenCalled());await waitFor(() => {- const item = previewProps?.items?.find((i) => i.filename === 'fool.png');- expect(item?.prompt).toBe('copperplate engraving. Full tarot card, framed border. The Fool: a youth at a cliff edge');- expect(item?.negativePrompt).toBe('blurry');+ expect(previewProps?.preview?.prompt).toBe(COMPOSED);+ expect(previewProps?.preview?.negativePrompt).toBe('blurry');});});});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 3d62794333..4781dee240 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -24,7 +24,8 @@ import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';-import usePreviewRoute from '../hooks/usePreviewRoute.js';+import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute.js';+import { normalizeImage, normalizeVideo } from '../components/media/normalize.js';import { useVideoFileSrc } from '../hooks/useVideoFileSrc.js';import MediaPreview from '../components/media/MediaPreview.jsx';import MidiInstallModal from '../components/install/MidiInstallModal.jsx';@@ -39,7 +40,7 @@ import AnalysisPanel from '../components/musicVideo/AnalysisPanel.jsx';import SceneCard from '../components/musicVideo/SceneCard.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';-import { videoSrcForJob, videoPosterForJob } from '../lib/creativeDirectorPreview.js';+import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';const STATUS_COLORS = {draft: 'bg-port-border text-port-text',@@ -366,46 +367,42 @@ export default function MusicVideo() {});// Shared lightbox: final render first (it sits above the board), then each- // scene's frame then clip in board order. Keys use the canonical- // `image:<filename>` / `video:<historyId>` shape from media/normalize so the- // lightbox's always-mounted Add-to-collection / Pin-to-moodboard menus get a- // real `id`/`filename` ref (same vocabulary as Media History's ?preview=).+ // scene's frame then clip in board order. Built through media/normalize so+ // keys use the canonical `image:<filename>` / `video:<historyId>` shape —+ // the lightbox's always-mounted Add-to-collection / Pin-to-moodboard menus+ // then get a real `id`/`filename` ref (same vocabulary as Media History's+ // ?preview=), and the lineage fields survive.+ //+ // The prompts here are the board's LABELS: `useMusicVideoSceneMedia` suffixes+ // `project.concept.style` onto both the frame and the shot prompt on the way+ // out, and the final render has no prompt of its own at all. They stand in+ // until `useHydratedPreviewRoute` reads the real one back on open.const previewItems = useMemo(() => {if (!selected) return [];const items = [];+ // `generateThumbnail` always writes `<jobId>.jpg`, which the history record+ // only names once hydrated — keep the job-scoped poster so the card has one+ // on first paint.+ const videoItem = (id, filename, prompt) => ({+ ...normalizeVideo({ id, filename, prompt }),+ previewUrl: videoPosterForJob(id),+ });if (selected.renderHistoryId && finalVideo.src) {- items.push({- key: `video:${selected.renderHistoryId}`,- kind: 'video',- id: selected.renderHistoryId,- filename: finalVideo.src.split('/').pop() || selected.renderHistoryId,- downloadUrl: finalVideo.src,- previewUrl: videoPosterForJob(selected.renderHistoryId),- prompt: `Music Video: ${selected.name}`,- });+ items.push(videoItem(+ selected.renderHistoryId,+ finalVideo.src.split('/').pop() || selected.renderHistoryId,+ `Music Video: ${selected.name}`,+ ));}for (const scene of selected.scenes || []) {if (scene.referenceImageId) {- const imgUrl = `/data/images/${scene.referenceImageId}`;- items.push({- key: `image:${scene.referenceImageId}`,- kind: 'image',+ items.push(normalizeImage({filename: scene.referenceImageId,- previewUrl: imgUrl,- downloadUrl: imgUrl,prompt: scene.framePrompt || scene.prompt || '',- });+ }));}if (scene.videoHistoryId) {- items.push({- key: `video:${scene.videoHistoryId}`,- kind: 'video',- id: scene.videoHistoryId,- filename: `${scene.videoHistoryId}.mp4`,- downloadUrl: videoSrcForJob(scene.videoHistoryId),- previewUrl: videoPosterForJob(scene.videoHistoryId),- prompt: scene.prompt || '',- });+ items.push(videoItem(scene.videoHistoryId, `${scene.videoHistoryId}.mp4`, scene.prompt || ''));}}// Scenes can reuse the same frame/clip (ProjectToolbar surfaces a@@ -414,7 +411,7 @@ export default function MusicVideo() {// several identical keys with different prompts.return [...new Map(items.map((i) => [i.key, i])).values()];}, [selected, finalVideo.src]);- const [preview, setPreview] = usePreviewRoute(previewItems);+ const [preview, setPreview] = useHydratedPreviewRoute(previewItems);const openPreview = useCallback((key) => {if (!key) return;const match = previewItems.find((i) => i.key === key);diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex c26959c756..b057729589 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -80,6 +80,12 @@ vi.mock('../services/apiImageVideo.js', () => ({],})),listVideoHistory: vi.fn(async () => [{ id: 'rh-9', filename: 'final.mp4' }]),+ // Sidecar lookup behind useHydratedPreviewRoute: the board's scene prompt is+ // only a label — `useMusicVideoSceneMedia` suffixes `concept.style` onto it+ // before rendering, so only the sidecar knows what the renderer was sent.+ getGalleryImages: vi.fn(async (filenames) => (filenames.includes('img1')+ ? [{ filename: 'img1', prompt: 'a wide desert shot, neon noir', seed: 7, cleanedFrom: 'img0' }]+ : [])),// By-id resolver behind useVideoFileSrc (#4165) — 404s (rejects) for any// other id, exactly as the real endpoint does.getVideoHistoryItem: vi.fn(async (id) => (id === 'rh-9'@@ -927,6 +933,20 @@ describe('MusicVideo media lightbox (#3718)', () => {expect(lightboxVideo?.getAttribute('src')).not.toBe('/data/videos/rh-9.mp4');});+ it('shows the styled prompt the renderer was sent, not the board label', async () => {+ // The scene's own prompt is 'a'; `useMusicVideoSceneMedia` appends the+ // project's concept style before rendering, so the board label is wording+ // the image model never saw. The sidecar is the only record of the real+ // one — and it also carries the `cleanedFrom` lineage the hand-rolled item+ // shape used to drop.+ await openProject(PROJECT_WITH_CLIP);+ fireEvent.click(await screen.findByRole('button', { name: 'View scene 1 reference frame full size' }));+ const dialog = await screen.findByRole('dialog', { name: /Media viewer/i });+ await waitFor(() => {+ expect(dialog.querySelector('img')?.getAttribute('alt')).toBe('a wide desert shot, neon noir');+ });+ });+it('opens the lightbox from a ?preview= deep link on mount', async () => {listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP]);renderMVAt('/music-video/mv-1?preview=image%3Aimg1');