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

fix: resolve CD final-video id to its real file and stop cropping inline previews (#2702)

[._.]/ Adam Eivy8a46a7bcb761
diff --git a/client/src/components/creative-director/OverviewTab.jsx b/client/src/components/creative-director/OverviewTab.jsx
index 41f784792c..ddebd0da4f 100644
--- a/client/src/components/creative-director/OverviewTab.jsx
+++ b/client/src/components/creative-director/OverviewTab.jsx
@@ -2,7 +2,8 @@ import { Link } from 'react-router-dom';
import { useState, useEffect, useRef } from 'react';
import { Sparkles, Loader2 } from 'lucide-react';
import { updateCreativeDirectorProject, applyCreativeDirectorAutoCast } from '../../services/apiCreativeDirector.js';
-import { selectProjectPreview, previewAspectClass } from '../../lib/creativeDirectorPreview.js';
+import { selectProjectPreview, previewAspectClass, previewMaxWidthClass } from '../../lib/creativeDirectorPreview.js';
+import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
import MediaImage from '../MediaImage.jsx';
import ScenePreview from './ScenePreview.jsx';
import toast from '../ui/Toast';
@@ -169,7 +170,18 @@ export default function OverviewTab({ project, onProjectUpdate, onAsyncWorkQueue
// Final video field remains the single honest signal.
const preview = selectProjectPreview(project);
const aspectClass = previewAspectClass(project.aspectRatio);
- const inlineImage = !project.finalVideoId && preview.kind === 'image' ? preview : null;
+ const maxWidthClass = previewMaxWidthClass(project.aspectRatio);
+ // Only a PRODUCED image earns the hero slot. `kind: 'image'` also covers the
+ // `startingImageFile` fallback — an input the user supplied, already shown as
+ // a field below — and promoting that would push Configuration below the fold
+ // to echo a value the page states anyway. The produced-image branch is the one
+ // that carries a `jobId`, so that's the discriminator (pinned by a test).
+ const inlineImage = !project.finalVideoId && preview.kind === 'image' && preview.jobId ? preview : null;
+ // The id→file mismatch: a stitched final is `timeline-*.mp4` behind a UUID.
+ // The idle player is `preload="none"`, so a late resolve can't be raced here.
+ const { src: finalVideoSrc } = useVideoFileSrc(project.finalVideoId, {
+ enabled: Boolean(project.finalVideoId),
+ });
return (
<div className="space-y-4 max-w-3xl">
@@ -178,9 +190,9 @@ export default function OverviewTab({ project, onProjectUpdate, onAsyncWorkQueue
<h2 className="text-sm font-semibold text-port-text-muted uppercase tracking-wide">
{project.finalVideoId ? 'Final video' : inlineImage.label}
</h2>
- <div className={`${aspectClass} rounded overflow-hidden bg-port-bg max-h-[60vh] mx-auto`}>
+ <div className={`${aspectClass} ${maxWidthClass} w-full mx-auto rounded overflow-hidden bg-port-bg`}>
{project.finalVideoId
- ? <ScenePreview jobId={project.finalVideoId} label="Final video" aspectClass={aspectClass} />
+ ? <ScenePreview jobId={project.finalVideoId} src={finalVideoSrc} label="Final video" aspectClass={aspectClass} />
: (
<MediaImage
src={inlineImage.src}
diff --git a/client/src/components/creative-director/ProjectPreview.jsx b/client/src/components/creative-director/ProjectPreview.jsx
index bb08ae29b0..b3d29d0278 100644
--- a/client/src/components/creative-director/ProjectPreview.jsx
+++ b/client/src/components/creative-director/ProjectPreview.jsx
@@ -4,6 +4,7 @@ import { Play, Film } from 'lucide-react';
import MediaImage from '../MediaImage.jsx';
import ScenePreview from './ScenePreview.jsx';
import { selectProjectPreview, previewAspectClass } from '../../lib/creativeDirectorPreview.js';
+import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';
/**
* Compact media preview for a Creative Director list card (#2702) — shows what
@@ -40,10 +41,28 @@ export default function ProjectPreview({ project, to }) {
setPlaying(false);
}, [preview.jobId, preview.src]);
+ // A video id is not necessarily its filename stem (a stitched final cut is
+ // `timeline-*.mp4` behind a UUID), so resolve the real file before playing.
+ // `enabled` keeps the grid light: this fires only once the user presses play,
+ // never for the N cards sitting idle on the page.
+ const { src: resolvedSrc, resolving } = useVideoFileSrc(preview.jobId, {
+ enabled: playing && preview.kind === 'video',
+ });
+
if (playing) {
+ // Autoplay races the lookup, so hold the frame until it settles — mounting
+ // early would autoplay the unresolved guess and flash "media missing".
+ if (resolving) {
+ return (
+ <div className={`${aspectClass} rounded overflow-hidden bg-port-bg border border-port-border flex items-center justify-center text-port-text-muted text-xs`}>
+ loading…
+ </div>
+ );
+ }
return (
<ScenePreview
jobId={preview.jobId}
+ src={resolvedSrc}
label={`${project?.name || 'Project'} — ${preview.label}`}
aspectClass={aspectClass}
autoPlay
diff --git a/client/src/components/creative-director/ScenePreview.jsx b/client/src/components/creative-director/ScenePreview.jsx
index 38c33e367b..27211ea540 100644
--- a/client/src/components/creative-director/ScenePreview.jsx
+++ b/client/src/components/creative-director/ScenePreview.jsx
@@ -31,20 +31,32 @@ import { videoSrcForJob, videoPosterForJob } from '../../lib/creativeDirectorPre
* would be redundant. Off by default — the grid must never
* fetch mp4s on its own (`preload="none"` only holds while
* this is false).
+ * src? — explicit video URL, overriding the `<jobId>.mp4` guess below.
+ * Required whenever the id is NOT the filename stem: the
+ * timeline renderer (a CD project's stitched final cut) mints
+ * `timeline-<project>-<ts>.mp4` beside a `randomUUID()` id, so
+ * reconstructing the path 404s. Resolve one with
+ * `useVideoFileSrc(jobId)`. The POSTER is deliberately still
+ * derived from `jobId` — `generateThumbnail` always writes
+ * `<jobId>.jpg`, on both the clip and timeline paths.
*/
-export default function ScenePreview({ jobId, label, aspectClass = 'aspect-video', autoPlay = false }) {
+export default function ScenePreview({ jobId, label, aspectClass = 'aspect-video', autoPlay = false, src = null }) {
const [missing, setMissing] = useState(false);
const [attempt, setAttempt] = useState(0);
+ // Reset on `src` too, not just `jobId`: a caller resolving the real filename
+ // asynchronously renders once with src=null (the reconstructed guess) and
+ // again once it lands. Without this, an error recorded against the guess
+ // would pin "media missing" over the correct URL that arrived a tick later.
useEffect(() => {
setMissing(false);
setAttempt(0);
- }, [jobId]);
+ }, [jobId, src]);
if (!jobId) {
return <div className={`bg-port-bg ${aspectClass} flex items-center justify-center text-port-text-muted text-xs`}>no render yet</div>;
}
const cacheBust = attempt > 0 ? `?retry=${attempt}` : '';
- const videoSrc = `${videoSrcForJob(jobId)}${cacheBust}`;
+ const videoSrc = `${src || videoSrcForJob(jobId)}${cacheBust}`;
const posterSrc = `${videoPosterForJob(jobId)}${cacheBust}`;
if (missing) {
return (
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index de223bd1ce..6e28a84417 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -162,6 +162,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useUniverseGallery` | Page-level lightbox + gallery-metadata concern for the Universe Builder. Takes `{ draft, runsLength }`; hydrates a filename→sidecar map (prompt/seed/model), derives `previewItems` across variations, composite sheets, style probes, and canon/character-sheet refs (namespaced-key dedupe), and wires `usePreviewRoute` + `useMediaPreviewActions` + `useMediaAnnotations`. Returns `{ previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }`. | Universe Builder image lightbox — don't re-roll the gallery-sidecar/previewItems derivation. |
| `useUniverseRender` | Universe Builder batch-render settings, scoped render payload compilation, canon-selection defaults, per-entry job queue, and run-list refresh. Returns the shared `runRender`/`handleRender` action used by the Render tab and inline bucket/canon controls. | Universe Builder composition shell and presentational panels; don't fork render payload semantics per tab. |
| `useUniverseNav` | `goToWorld(id)` → navigate to `/universes/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. |
+| `useVideoFileSrc` | `useVideoFileSrc(jobId, { enabled })` → `{ src, resolving }`. Resolves a video-history **id** to the file it really points at (`/data/videos/<filename>`) via the history lookup. | Any surface rendering a video by history id where the id is NOT the filename stem — notably a CD `finalVideoId` (the timeline renderer mints `timeline-*.mp4` beside a `randomUUID()` id, so `/data/videos/<id>.mp4` 404s while `<id>.jpg` poster loads). Pass the result to `<ScenePreview src=…>`. Gate autoplay on `resolving`. |
| `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. |
| `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. |
| `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 67d9489641..faaa07b4c2 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -149,4 +149,5 @@ export * from './useRenderJobQueue.js';
export * from './useSyncIntegrity.js';
export * from './useTwinEvaluationSuite.js';
export * from './useUniverseNav.js';
+export * from './useVideoFileSrc.js';
export * from './useVoiceUiSync.js';
diff --git a/client/src/hooks/useVideoFileSrc.js b/client/src/hooks/useVideoFileSrc.js
new file mode 100644
index 0000000000..a905dcaae7
--- /dev/null
+++ b/client/src/hooks/useVideoFileSrc.js
@@ -0,0 +1,62 @@
+import { useEffect, useState } from 'react';
+import { listVideoHistory } from '../services/apiImageVideo.js';
+
+/**
+ * Resolve a video-history id to the URL of the file it actually points at.
+ *
+ * WHY THIS EXISTS: a history entry's id and its filename are NOT the same value,
+ * and only some writers make them look like they are. `videoGen/local.js` names
+ * a clip `<jobId>.mp4`, so reconstructing `/data/videos/<id>.mp4` happens to work
+ * for per-scene renders. The video-TIMELINE renderer — which produces a Creative
+ * Director project's stitched final cut — mints an independent
+ * `timeline-<project>-<ts>.mp4` alongside a `randomUUID()` id
+ * (`videoTimeline/local.js`), so a CD `finalVideoId` is a *history id*, not a
+ * filename stem, and the reconstructed path 404s. The thumbnail is keyed the
+ * other way (`generateThumbnail` always writes `<jobId>.jpg`), which is what
+ * makes the mismatch so easy to miss: the poster renders perfectly while the mp4
+ * behind it does not exist.
+ *
+ * So: resolve through the stored `filename` — the same thing the server does
+ * (`stitchRunner.js` joins `PATHS.videos` with `finalEntry.filename`) and the
+ * media UI does (`components/media/normalize.js` → `/data/videos/${v.filename}`).
+ *
+ * Usage: pass the resolved `src` to `<ScenePreview src=…>`, which falls back to
+ * its `<jobId>.mp4` reconstruction when this returns null. Callers should gate
+ * on `resolving` before AUTOPLAYING, or the player would race the lookup and
+ * autoplay the wrong (nonexistent) path. A caller that only renders an idle
+ * `preload="none"` player can ignore `resolving` — nothing is fetched until the
+ * user hits Play, by which time the lookup has long settled.
+ *
+ * `enabled` keeps this lazy: the list grid must not fetch history for N cards,
+ * so a card resolves only once the user actually presses play.
+ */
+export function useVideoFileSrc(jobId, { enabled = true } = {}) {
+ const [src, setSrc] = useState(null);
+ const [resolving, setResolving] = useState(false);
+
+ useEffect(() => {
+ setSrc(null);
+ if (!enabled || !jobId) {
+ setResolving(false);
+ return undefined;
+ }
+ setResolving(true);
+ let cancelled = false;
+ // Silent: a failed lookup is not a user-facing error — ScenePreview's
+ // reconstruction fallback (and its own missing-media UI) covers it, so a
+ // toast here would be noise on a page that already degrades gracefully.
+ listVideoHistory({ silent: true })
+ .then((entries) => {
+ if (cancelled) return;
+ const list = Array.isArray(entries) ? entries : [];
+ const entry = list.find((e) => e?.id === jobId);
+ const filename = typeof entry?.filename === 'string' ? entry.filename.trim() : '';
+ if (filename) setSrc(`/data/videos/${filename}`);
+ })
+ .catch(() => {})
+ .finally(() => { if (!cancelled) setResolving(false); });
+ return () => { cancelled = true; };
+ }, [jobId, enabled]);
+
+ return { src, resolving };
+}
diff --git a/client/src/lib/creativeDirectorPreview.js b/client/src/lib/creativeDirectorPreview.js
index 0877227dae..7f8ccbf9a3 100644
--- a/client/src/lib/creativeDirectorPreview.js
+++ b/client/src/lib/creativeDirectorPreview.js
@@ -52,6 +52,19 @@ const ASPECT_CLASSES = Object.freeze({
'1:1': 'aspect-square',
});
+// Height cap for an inline hero preview, expressed as a MAX-WIDTH per ratio.
+// Capping height directly does not work: a block box is fill-available wide, so
+// `max-h` clamps the box while the aspect-ratio'd player inside still derives
+// its height from the UNCLAMPED width and overflows (a 9:16 preview in a 736px
+// column wants 1308px tall — `overflow-hidden` then crops half the video away).
+// Constraining width instead lets aspect-ratio derive a height that already
+// fits, and makes `mx-auto` actually center. Literals, per the note above.
+const MAX_WIDTH_CLASSES = Object.freeze({
+ '16:9': 'max-w-[calc(60vh*16/9)]',
+ '9:16': 'max-w-[calc(60vh*9/16)]',
+ '1:1': 'max-w-[60vh]',
+});
+
/**
* Tailwind aspect class for a project's locked aspect ratio, falling back to
* `aspect-video` for an unset/legacy/hand-edited value.
@@ -60,6 +73,15 @@ export function previewAspectClass(aspectRatio) {
return ASPECT_CLASSES[aspectRatio] || 'aspect-video';
}
+/**
+ * Max-width class that keeps an inline preview of `aspectRatio` within ~60vh
+ * tall without distorting or cropping it. Pair with `previewAspectClass` +
+ * `w-full mx-auto`; do NOT also apply a `max-h` (see the note above).
+ */
+export function previewMaxWidthClass(aspectRatio) {
+ return MAX_WIDTH_CLASSES[aspectRatio] || MAX_WIDTH_CLASSES['16:9'];
+}
+
const nonEmptyString = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
/**
diff --git a/client/src/lib/creativeDirectorPreview.test.js b/client/src/lib/creativeDirectorPreview.test.js
index f04f6465a8..936ebec4fb 100644
--- a/client/src/lib/creativeDirectorPreview.test.js
+++ b/client/src/lib/creativeDirectorPreview.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
selectProjectPreview,
previewAspectClass,
+ previewMaxWidthClass,
startingImageSrc,
videoSrcForJob,
videoPosterForJob,
@@ -26,6 +27,19 @@ describe('previewAspectClass', () => {
});
});
+describe('previewMaxWidthClass', () => {
+ it('caps an inline preview by WIDTH per ratio (a max-h would crop it)', () => {
+ expect(previewMaxWidthClass('16:9')).toBe('max-w-[calc(60vh*16/9)]');
+ expect(previewMaxWidthClass('9:16')).toBe('max-w-[calc(60vh*9/16)]');
+ expect(previewMaxWidthClass('1:1')).toBe('max-w-[60vh]');
+ });
+
+ it('falls back to the 16:9 cap for unset/unknown values', () => {
+ expect(previewMaxWidthClass(undefined)).toBe('max-w-[calc(60vh*16/9)]');
+ expect(previewMaxWidthClass('21:9')).toBe('max-w-[calc(60vh*16/9)]');
+ });
+});
+
describe('asset path builders', () => {
it('mirror the worker naming conventions', () => {
expect(videoSrcForJob('job-1')).toBe('/data/videos/job-1.mp4');
@@ -189,6 +203,21 @@ describe('selectProjectPreview', () => {
expect(preview).toEqual({ kind: 'image', src: '/data/images/start.png', label: 'Starting image' });
});
+ it('marks a PRODUCED image with a jobId and a starting image WITHOUT one', () => {
+ // `jobId` is the discriminator between the two `kind: 'image'` cases —
+ // OverviewTab gates its hero section on it so a user-supplied input image
+ // never gets promoted as if the director produced it. Don't "helpfully"
+ // start setting jobId on the starting-image branch.
+ const produced = selectProjectPreview({
+ plan: { steps: [step('media_enqueueImageJob', 'done', { jobId: 'img-1' })] },
+ });
+ const starting = selectProjectPreview({ startingImageFile: 'start.png' });
+ expect(produced.kind).toBe('image');
+ expect(produced.jobId).toBe('img-1');
+ expect(starting.kind).toBe('image');
+ expect(starting.jobId).toBeUndefined();
+ });
+
it('does not use an unservable starting image', () => {
expect(selectProjectPreview({ startingImageFile: 'https://example.com/x.png' }).kind).toBe('none');
});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index fcb81f8e7f..0022057f67 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -139,7 +139,7 @@ export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST
// resume progress display after a page reload. Silent so a 5xx during status
// poll doesn't double-toast on every navigation.
export const getActiveVideoJob = () => request('/video-gen/active', { silent: true });
-export const listVideoHistory = () => request('/video-gen/history');
+export const listVideoHistory = (options = {}) => request('/video-gen/history', options);
export const deleteVideoHistoryItem = (id, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
export const setVideoHidden = (id, hidden, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}/visibility`, {
method: 'POST',