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: put a forming video render on a main stage instead of a bare percentage (#4588)
[._.]/ Adam Eivybc2678ca2828
diff --git a/client/src/components/videoGen/LiveVideoStage.jsx b/client/src/components/videoGen/LiveVideoStage.jsxnew file mode 100644index 0000000000..bd83a74c6e--- /dev/null+++ b/client/src/components/videoGen/LiveVideoStage.jsx@@ -0,0 +1,144 @@+/**+ * VideoGen main stage (#4588) — the full-size preview a render forms on.+ *+ * Before this, the only sign a video render was happening was a percentage next+ * to the Generate button; the clip appeared in the gallery minutes later. The+ * stage shows, at the render's RESOLVED geometry (so a portrait render is a+ * portrait box, not a letterboxed 16:9 one), whatever best represents the+ * in-flight render: a live runner frame if one exists, otherwise the clip an+ * extend is continuing (animated, muted, looping) or the still it is growing+ * out of, and the finished clip once it lands.+ *+ * Hold and return. The stage never yanks a clip out from under the user: while+ * `held` is set by the page (the lightbox is open) or while the user is playing+ * the finished clip on the stage itself, an incoming descriptor is deferred and+ * adopted when playback settles. An ambient LOOP preview is muted/auto-playing+ * chrome, not something the user chose to watch, so it never holds.+ *+ * Presentational — every input is owned by the VideoGen page.+ */+import { useEffect, useState } from 'react';+import { Film } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';+import { VIDEO_STAGE_KIND, videoStageSignature } from '../../lib/videoStagePreview';++export default function LiveVideoStage({+ descriptor,+ generating = false,+ progressPct = null,+ statusMsg = '',+ error = null,+ held = false,+}) {+ const [shown, setShown] = useState(descriptor);+ const [playing, setPlaying] = useState(false);++ const shownSignature = videoStageSignature(shown);+ const nextSignature = videoStageSignature(descriptor);+ // A user-driven playback of the finished clip holds; the ambient loop does not.+ const holding = held || (shown?.kind === VIDEO_STAGE_KIND.RESULT && playing);+ const pendingSwap = shownSignature !== nextSignature;++ useEffect(() => {+ // Signature-gated so a parent re-render that produced an equivalent+ // descriptor doesn't loop setState on a fresh object identity.+ if (holding || !pendingSwap) return;+ setShown(descriptor);+ setPlaying(false);+ }, [holding, pendingSwap, descriptor]);++ const stage = shown || { kind: VIDEO_STAGE_KIND.EMPTY, src: null, poster: null, label: '', aspectRatio: null };+ const isLoop = stage.kind === VIDEO_STAGE_KIND.LOOP;+ const isResult = stage.kind === VIDEO_STAGE_KIND.RESULT;+ const isClip = isLoop || isResult;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-3 space-y-2">+ <div className="flex items-center justify-between gap-2">+ <h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Stage</h2>+ {holding && pendingSwap && (+ <span className="text-[11px] text-port-accent">Newer preview ready — showing after playback</span>+ )}+ </div>++ <div+ data-testid="video-stage-frame"+ data-stage-kind={stage.kind}+ className="relative mx-auto flex w-full max-w-3xl items-center justify-center overflow-hidden rounded-lg border border-port-border bg-port-bg"+ // Inline, not a Tailwind `aspect-[w/h]` class — a computed class name+ // never reaches the JIT build. `null` geometry lets the media size itself+ // rather than being letterboxed into a guessed ratio.+ //+ // The height cap has to be paired with a ratio-derived width cap: with+ // `aspect-ratio` + `width: 100%`, a `max-height` alone just overrides the+ // ratio, and a portrait render ends up in a wide box with the clip+ // letterboxed in the middle — the exact geometry bug this stage exists to+ // avoid. Capping the width at `60vh × ratio` keeps the box portrait.+ style={stage.aspectRatio+ ? {+ aspectRatio: String(stage.aspectRatio),+ maxHeight: '60vh',+ maxWidth: `min(100%, calc(60vh * ${stage.aspectRatio}))`,+ }+ : { maxHeight: '60vh' }}+ >+ {isClip ? (+ <video+ key={stage.src}+ src={stage.src}+ poster={stage.poster || undefined}+ aria-label={stage.label}+ className="h-full w-full object-contain"+ playsInline+ controls={isResult}+ muted={isLoop}+ loop={isLoop}+ autoPlay={isLoop}+ onPlay={() => setPlaying(true)}+ onPause={() => setPlaying(false)}+ onEnded={() => setPlaying(false)}+ />+ ) : stage.src ? (+ <img+ src={stage.src}+ alt={stage.label}+ decoding="async"+ className="h-full w-full object-contain"+ />+ ) : generating ? (+ <div className="flex flex-col items-center gap-2 px-4 py-10 text-center text-sm text-gray-500">+ <BrailleSpinner />+ <span className="font-medium text-gray-300">{statusMsg || 'Starting render…'}</span>+ </div>+ ) : (+ <div className="flex flex-col items-center gap-1.5 px-4 py-10 text-xs text-gray-600">+ <Film className="w-8 h-8" />+ <span>{stage.label}</span>+ </div>+ )}++ {(generating || error) && (+ <div className="port-media-overlay absolute left-2 top-2 max-w-[calc(100%-1rem)] rounded-lg px-2 py-1 text-[11px]">+ <span className="truncate">{error || statusMsg || 'Working…'}</span>+ </div>+ )}++ {stage.src && !error && (+ <div className="port-media-overlay absolute bottom-2 left-2 rounded-lg px-2 py-1 text-[10px]">+ {stage.label}+ </div>+ )}++ {generating && progressPct != null && (+ <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/50">+ <div+ data-testid="video-stage-progress"+ className="h-full bg-port-accent transition-all"+ style={{ width: `${progressPct}%` }}+ />+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/videoGen/LiveVideoStage.test.jsx b/client/src/components/videoGen/LiveVideoStage.test.jsxnew file mode 100644index 0000000000..75469c5196--- /dev/null+++ b/client/src/components/videoGen/LiveVideoStage.test.jsx@@ -0,0 +1,117 @@+import { describe, it, expect } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import LiveVideoStage from './LiveVideoStage';+import { resolveVideoStagePreview, VIDEO_STAGE_KIND } from '../../lib/videoStagePreview';++const stageFrame = () => screen.getByTestId('video-stage-frame');++describe('LiveVideoStage', () => {+ it('renders a live runner frame as an image at the render aspect ratio', () => {+ const descriptor = resolveVideoStagePreview({+ generating: true, currentImage: 'iVBORw0KG', width: 480, height: 832,+ });+ render(<LiveVideoStage descriptor={descriptor} generating progressPct={40} statusMsg="Rendering step 4/10" />);++ const img = screen.getByAltText('Live frame');+ expect(img.getAttribute('src')).toBe('data:image/png;base64,iVBORw0KG');+ // Portrait geometry: an inline style, never a computed Tailwind class+ // (a `aspect-[480/832]` class name would not survive the JIT build).+ // (CSS normalizes a bare number to `<n> / 1`, hence the split.)+ const ratio = Number(stageFrame().style.aspectRatio.split('/')[0]);+ expect(ratio).toBeCloseTo(480 / 832);+ expect(ratio).toBeLessThan(1);+ // The height cap alone would override the ratio and hand a portrait render+ // a wide box; the width has to be capped by the ratio as well.+ expect(stageFrame().style.maxHeight).toBe('60vh');+ // (CSS folds the `calc(60vh * ratio)` to a single vh length.)+ const capped = stageFrame().style.maxWidth.match(/min\(100%,\s*([\d.]+)vh\)/);+ expect(capped).toBeTruthy();+ expect(Number(capped[1])).toBeCloseTo(60 * (480 / 832));+ expect(screen.getByTestId('video-stage-progress').style.width).toBe('40%');+ });++ it('leaves the aspect ratio unset when the render geometry is unknown', () => {+ const descriptor = resolveVideoStagePreview({ generating: true, currentImage: 'AAA' });+ render(<LiveVideoStage descriptor={descriptor} generating />);+ expect(stageFrame().style.aspectRatio).toBe('');+ });++ it('plays the extend source as a muted ambient loop with no controls', () => {+ const descriptor = resolveVideoStagePreview({+ generating: true, extendSource: { filename: 'clip-a.mp4', thumbnail: 'clip-a.jpg' },+ });+ render(<LiveVideoStage descriptor={descriptor} generating />);++ const video = screen.getByLabelText('Continuing from this clip');+ expect(video.tagName).toBe('VIDEO');+ expect(video.getAttribute('src')).toBe('/data/videos/clip-a.mp4');+ expect(video.getAttribute('poster')).toBe('/data/video-thumbnails/clip-a.jpg');+ expect(video.muted).toBe(true);+ expect(video.loop).toBe(true);+ expect(video.controls).toBe(false);+ });++ it('shows the spinner and status while a render has nothing to preview yet', () => {+ const descriptor = resolveVideoStagePreview({ generating: true });+ render(<LiveVideoStage descriptor={descriptor} generating statusMsg="Loading pipeline…" />);+ expect(screen.getAllByText('Loading pipeline…').length).toBeGreaterThan(0);+ expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.EMPTY);+ });++ it('hands off to the finished clip when the render completes', () => {+ const forming = resolveVideoStagePreview({ generating: true, sourceImageFile: 'start.png' });+ const { rerender } = render(<LiveVideoStage descriptor={forming} generating />);+ expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.STILL);++ const done = resolveVideoStagePreview({ result: { path: '/data/videos/done.mp4' } });+ rerender(<LiveVideoStage descriptor={done} />);+ expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.RESULT);+ expect(screen.getByLabelText('Latest render').getAttribute('src')).toBe('/data/videos/done.mp4');+ });++ it('holds the stage while the page reports the user is watching, then returns', () => {+ const first = resolveVideoStagePreview({ result: { path: '/data/videos/one.mp4' } });+ const { rerender } = render(<LiveVideoStage descriptor={first} held />);+ expect(screen.getByLabelText('Latest render').getAttribute('src')).toBe('/data/videos/one.mp4');++ const second = resolveVideoStagePreview({ result: { path: '/data/videos/two.mp4' } });+ rerender(<LiveVideoStage descriptor={second} held />);+ expect(screen.getByLabelText('Latest render').getAttribute('src')).toBe('/data/videos/one.mp4');+ expect(screen.getByText(/Newer preview ready/)).toBeTruthy();++ rerender(<LiveVideoStage descriptor={second} />);+ expect(screen.getByLabelText('Latest render').getAttribute('src')).toBe('/data/videos/two.mp4');+ });++ it('does not swap out a finished clip the user is playing, and swaps once it pauses', () => {+ const first = resolveVideoStagePreview({ result: { path: '/data/videos/one.mp4' } });+ const { rerender } = render(<LiveVideoStage descriptor={first} />);+ fireEvent.play(screen.getByLabelText('Latest render'));++ const forming = resolveVideoStagePreview({ generating: true, sourceImageFile: 'start.png' });+ rerender(<LiveVideoStage descriptor={forming} generating />);+ expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.RESULT);++ fireEvent.pause(screen.getByLabelText('Latest render'));+ rerender(<LiveVideoStage descriptor={forming} generating />);+ expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.STILL);+ });++ it('never holds on the ambient loop — it is chrome, not something the user chose to watch', () => {+ const loop = resolveVideoStagePreview({+ generating: true, extendSource: { filename: 'clip-a.mp4' },+ });+ const { rerender } = render(<LiveVideoStage descriptor={loop} generating />);+ fireEvent.play(screen.getByLabelText('Continuing from this clip'));++ const live = resolveVideoStagePreview({ generating: true, currentImage: 'AAA' });+ rerender(<LiveVideoStage descriptor={live} generating />);+ expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.LIVE);+ });++ it('surfaces a render failure over the stage', () => {+ const descriptor = resolveVideoStagePreview({ sourceImageFile: 'start.png' });+ render(<LiveVideoStage descriptor={descriptor} error="Runtime not installed" />);+ expect(screen.getByText('Runtime not installed')).toBeTruthy();+ });+});diff --git a/client/src/hooks/useMediaJobSse.js b/client/src/hooks/useMediaJobSse.jsindex 0a7d935524..f32b400a14 100644--- a/client/src/hooks/useMediaJobSse.js+++ b/client/src/hooks/useMediaJobSse.js@@ -22,8 +22,15 @@ import { safeParseJSON } from '../lib/genUtils';** Handlers (all optional): `isCurrent` (staleness guard — a stale frame* closes the stream and is ignored), `onQueued`, `onStarted`, `onStage`,- * `onStatus`, `onProgress`, `onComplete`, `onError`, `onCanceled`,- * `onConnectionError`.+ * `onStatus`, `onProgress`, `onPreview`, `onRenderMeta`, `onComplete`,+ * `onError`, `onCanceled`, `onConnectionError`.+ *+ * `preview` is the mediaJobQueue dispatcher's preview-ONLY frame — a runner+ * frame (`currentImage`) that arrived without a progress value, kept a distinct+ * type so a consumer's progress bar isn't disturbed by it. `render-meta`+ * carries the geometry the render actually resolved to (the requested edges+ * snapped to the model's resolution grid), which is what a preview stage must+ * size itself by. Both were dropped on the floor here before #4588.** `eventSourceRef` is exposed so callers can `close()` on cancel/unmount.*/@@ -38,7 +45,7 @@ export function useMediaJobSse(kind) {const attach = useCallback((jobId, handlers = {}) => {const {isCurrent = () => true,- onQueued, onStarted, onStage, onStatus, onProgress,+ onQueued, onStarted, onStage, onStatus, onProgress, onPreview, onRenderMeta,onComplete, onError, onCanceled, onConnectionError,} = handlers;return new Promise((resolve, reject) => {@@ -56,6 +63,8 @@ export function useMediaJobSse(kind) {case 'stage': onStage?.(msg); break;case 'status': onStatus?.(msg); break;case 'progress': onProgress?.(msg); break;+ case 'preview': onPreview?.(msg); break;+ case 'render-meta': onRenderMeta?.(msg); break;case 'complete': {es.close();const value = onComplete?.(msg);diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex a05a49a217..21284c5c5a 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -72,6 +72,7 @@ grep -i "what you want to do" client/src/lib/README.md| `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. || `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS`/`DEFAULT_CONTEXT_FRAMES`/`CONTEXT_FRAME_OPTIONS` constants, model-aware frame/fps/resolution-grid normalization, separate mute vs prompt-audio capability checks, `supportsContextWindow(model)` (does this runtime have an extend pipeline to feed a continuation window to — display mirror of `server/lib/videoContinuity.js`, pinned by `server/lib/videoContinuity.parity.test.js`), `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. || `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |+| `videoStagePreview.js` | VideoGen main-stage preview resolver (#4588). `resolveVideoStagePreview({ generating, currentImage, width, height, result, extendSource, sourceImageFile/Url, lastImageFile/Url, keyframes })` → `{ kind: 'live'|'loop'|'still'|'result'|'empty', src, poster, label, aspectRatio }` — what the stage should show at each moment of a render, with mid-render vs idle precedence. Plus `videoStageAspectRatio()` (a NUMBER for an inline `aspect-ratio` style — a computed Tailwind `aspect-[w/h]` class never reaches the JIT build; `null` means unknown geometry, not 16:9), `videoPreviewFrameSrc()` (the runners' `currentImage` is polymorphic — raw base64 from imageGen, a served URL from loraTraining — so classify before prefixing), and `videoStageSignature()` for the hold/return guard in `components/videoGen/LiveVideoStage.jsx`. || `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |## Graph & simdiff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 8c4989fe24..776f3645d1 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -51,6 +51,7 @@ export * from './slashdoCatalog.js';export * from './videoFinish.js';export * from './videoGenParams.js';export * from './videoGenResolutions.js';+export * from './videoStagePreview.js';export * from './videoTilingOptions.js';export * from './wrImageDefaults.js';diff --git a/client/src/lib/videoStagePreview.js b/client/src/lib/videoStagePreview.jsnew file mode 100644index 0000000000..f9556f6765--- /dev/null+++ b/client/src/lib/videoStagePreview.js@@ -0,0 +1,149 @@+/**+ * VideoGen main-stage preview resolver (#4588).+ *+ * VideoGen used to show nothing but a percentage next to the Generate button+ * until the MP4 landed. This picks what the page's main stage should display at+ * any moment of a render — a live runner frame when one exists, otherwise the+ * conditioning the render is forming FROM (the clip an extend continues, the+ * start/keyframe/end still an i2v or FFLF render is growing out of), and the+ * finished clip once it arrives.+ *+ * Pure: every input is already in the page's hands, nothing fetches. The+ * component owns the hold/return behaviour; this module owns "what would be+ * correct to show right now".+ */++export const VIDEO_STAGE_KIND = Object.freeze({+ LIVE: 'live', // a decoded frame from the in-flight render+ LOOP: 'loop', // an animated clip (the source an extend continues)+ STILL: 'still', // a conditioning image (start frame / keyframe / end frame)+ RESULT: 'result', // a finished render+ EMPTY: 'empty', // nothing to show yet+});++const isPositive = (value) => Number.isFinite(value) && value > 0;+const nonEmpty = (value) => (typeof value === 'string' && value !== '' ? value : null);++/**+ * The render's aspect ratio as a plain number for an inline `aspect-ratio`+ * style. Deliberately NOT a Tailwind `aspect-[w/h]` class — a computed class+ * name never reaches the JIT build (see `previewAspectClass` in+ * creativeDirectorPreview.js for the same trap).+ *+ * Returns `null` — not a 16:9 guess — when either edge is missing or bogus, so+ * a caller can tell "unknown geometry" from "known and square" and let the+ * media size itself instead of being letterboxed into a wrong box.+ */+export function videoStageAspectRatio(width, height) {+ const w = Number(width);+ const h = Number(height);+ return isPositive(w) && isPositive(h) ? w / h : null;+}++/**+ * Build an <img> src from a runner's `currentImage` frame.+ *+ * That key is polymorphic across runners: imageGen/local.js emits a raw base64+ * PNG body, loraTraining emits an already-served URL. Both ride the same field,+ * so classify before prefixing — assuming base64 would corrupt the URL form.+ * Returns `null` for absent/empty, which callers must treat as "no live frame"+ * rather than as an empty image.+ */+export function videoPreviewFrameSrc(currentImage) {+ const raw = nonEmpty(currentImage);+ if (!raw) return null;+ return /^(data:|https?:|\/)/.test(raw) ? raw : `data:image/png;base64,${raw}`;+}++const videoSrc = (filename) => {+ const name = nonEmpty(filename);+ return name ? `/data/videos/${name}` : null;+};+const thumbnailSrc = (thumbnail) => {+ const name = nonEmpty(thumbnail);+ return name ? `/data/video-thumbnails/${name}` : null;+};+const imageSrc = (uploadUrl, galleryFile) =>+ nonEmpty(uploadUrl) || (nonEmpty(galleryFile) ? `/data/images/${galleryFile}` : null);++const liveCandidate = (currentImage) => {+ const src = videoPreviewFrameSrc(currentImage);+ return src ? { kind: VIDEO_STAGE_KIND.LIVE, src, poster: null, label: 'Live frame' } : null;+};++const resultCandidate = (result) => {+ // `path` is what the completion payload carries; `filename` is the shape the+ // history records use. Accept either so the stage works whether the page+ // hands it the SSE result or a gallery record.+ const src = nonEmpty(result?.path) || videoSrc(result?.filename);+ return src+ ? { kind: VIDEO_STAGE_KIND.RESULT, src, poster: thumbnailSrc(result?.thumbnail), label: 'Latest render' }+ : null;+};++const loopCandidate = (extendSource) => {+ const src = videoSrc(extendSource?.filename);+ return src+ ? {+ kind: VIDEO_STAGE_KIND.LOOP,+ src,+ poster: thumbnailSrc(extendSource?.thumbnail),+ label: 'Continuing from this clip',+ }+ : null;+};++const stillCandidate = ({ sourceImageFile, sourceUploadUrl, lastImageFile, lastUploadUrl, keyframes }) => {+ const firstKeyframe = Array.isArray(keyframes)+ ? keyframes.filter((kf) => nonEmpty(kf?.file)).sort((a, b) => (a.index ?? 0) - (b.index ?? 0))[0]+ : null;+ const options = [+ [imageSrc(sourceUploadUrl, sourceImageFile), 'Start frame'],+ [imageSrc(null, firstKeyframe?.file), 'First keyframe'],+ [imageSrc(lastUploadUrl, lastImageFile), 'End frame'],+ ];+ const hit = options.find(([src]) => !!src);+ return hit ? { kind: VIDEO_STAGE_KIND.STILL, src: hit[0], poster: null, label: hit[1] } : null;+};++/**+ * Resolve the stage descriptor: `{ kind, src, poster, label, aspectRatio }`.+ *+ * Precedence differs by phase on purpose. Mid-render the forming clip is the+ * subject, so a live frame wins and the finished clip from the PREVIOUS render+ * is only a last resort; idle, the finished clip is the subject and the+ * conditioning stills are the fallback.+ */+export function resolveVideoStagePreview({+ generating = false,+ currentImage = null,+ width = null,+ height = null,+ result = null,+ extendSource = null,+ sourceImageFile = null,+ sourceUploadUrl = null,+ lastImageFile = null,+ lastUploadUrl = null,+ keyframes = null,+} = {}) {+ const aspectRatio = videoStageAspectRatio(width, height);+ const live = liveCandidate(currentImage);+ const finished = resultCandidate(result);+ const loop = loopCandidate(extendSource);+ const still = stillCandidate({ sourceImageFile, sourceUploadUrl, lastImageFile, lastUploadUrl, keyframes });+ const ordered = generating ? [live, loop, still, finished] : [live, finished, loop, still];+ const picked = ordered.find(Boolean)+ || { kind: VIDEO_STAGE_KIND.EMPTY, src: null, poster: null, label: 'Your render will appear here' };+ return { ...picked, aspectRatio };+}++/**+ * Stable identity for a descriptor, so the stage can tell "the same thing, new+ * object" from "a genuinely different thing" without deep-comparing. Used by+ * the hold/return guard — a re-render that produced an identical descriptor+ * must not count as a pending swap.+ */+export function videoStageSignature(descriptor) {+ return `${descriptor?.kind || VIDEO_STAGE_KIND.EMPTY}|${descriptor?.src || ''}|${descriptor?.aspectRatio ?? ''}`;+}diff --git a/client/src/lib/videoStagePreview.test.js b/client/src/lib/videoStagePreview.test.jsnew file mode 100644index 0000000000..4a7b6c5129--- /dev/null+++ b/client/src/lib/videoStagePreview.test.js@@ -0,0 +1,142 @@+import { describe, it, expect } from 'vitest';+import {+ VIDEO_STAGE_KIND,+ resolveVideoStagePreview,+ videoPreviewFrameSrc,+ videoStageAspectRatio,+ videoStageSignature,+} from './videoStagePreview';++describe('videoStageAspectRatio', () => {+ it('returns the ratio for two positive edges', () => {+ expect(videoStageAspectRatio(704, 480)).toBeCloseTo(704 / 480);+ expect(videoStageAspectRatio(480, 704)).toBeCloseTo(480 / 704);+ });++ it('returns null — not a 16:9 guess — for unknown or bogus geometry', () => {+ expect(videoStageAspectRatio(null, 480)).toBeNull();+ expect(videoStageAspectRatio(704, undefined)).toBeNull();+ expect(videoStageAspectRatio(0, 480)).toBeNull();+ expect(videoStageAspectRatio(704, -1)).toBeNull();+ expect(videoStageAspectRatio('wide', 480)).toBeNull();+ });+});++describe('videoPreviewFrameSrc', () => {+ it('prefixes a raw base64 body', () => {+ expect(videoPreviewFrameSrc('iVBORw0KG')).toBe('data:image/png;base64,iVBORw0KG');+ });++ it('passes an already-usable src through unchanged', () => {+ expect(videoPreviewFrameSrc('data:image/png;base64,AAA')).toBe('data:image/png;base64,AAA');+ expect(videoPreviewFrameSrc('/api/lora-training/runs/r1/samples/step_4.png'))+ .toBe('/api/lora-training/runs/r1/samples/step_4.png');+ expect(videoPreviewFrameSrc('https://example.com/frame.png')).toBe('https://example.com/frame.png');+ });++ it('treats absent and empty alike as "no frame" rather than an empty image', () => {+ expect(videoPreviewFrameSrc(null)).toBeNull();+ expect(videoPreviewFrameSrc(undefined)).toBeNull();+ expect(videoPreviewFrameSrc('')).toBeNull();+ expect(videoPreviewFrameSrc(42)).toBeNull();+ });+});++describe('resolveVideoStagePreview', () => {+ const extendSource = { filename: 'clip-a.mp4', thumbnail: 'clip-a.jpg' };++ it('is empty with nothing to show', () => {+ const stage = resolveVideoStagePreview();+ expect(stage.kind).toBe(VIDEO_STAGE_KIND.EMPTY);+ expect(stage.src).toBeNull();+ expect(stage.aspectRatio).toBeNull();+ });++ it('carries the resolved aspect ratio so a portrait render gets a portrait box', () => {+ const stage = resolveVideoStagePreview({ width: 480, height: 832, sourceImageFile: 'a.png' });+ expect(stage.aspectRatio).toBeCloseTo(480 / 832);+ expect(stage.aspectRatio).toBeLessThan(1);+ });++ it('prefers a live runner frame over every fallback while rendering', () => {+ const stage = resolveVideoStagePreview({+ generating: true,+ currentImage: 'iVBORw0KG',+ extendSource,+ sourceImageFile: 'start.png',+ result: { filename: 'done.mp4' },+ });+ expect(stage.kind).toBe(VIDEO_STAGE_KIND.LIVE);+ expect(stage.src).toBe('data:image/png;base64,iVBORw0KG');+ });++ it('falls back to the animated source clip an extend is continuing', () => {+ const stage = resolveVideoStagePreview({ generating: true, extendSource, sourceImageFile: 'start.png' });+ expect(stage.kind).toBe(VIDEO_STAGE_KIND.LOOP);+ expect(stage.src).toBe('/data/videos/clip-a.mp4');+ expect(stage.poster).toBe('/data/video-thumbnails/clip-a.jpg');+ });++ it('falls back to a still when no clip is available', () => {+ const stage = resolveVideoStagePreview({ generating: true, sourceImageFile: 'start.png' });+ expect(stage.kind).toBe(VIDEO_STAGE_KIND.STILL);+ expect(stage.src).toBe('/data/images/start.png');+ expect(stage.label).toBe('Start frame');+ });++ it('prefers a freshly uploaded still over a gallery pick, and orders start → keyframe → end', () => {+ expect(resolveVideoStagePreview({ sourceImageFile: 'gallery.png', sourceUploadUrl: 'blob:local' }).src)+ .toBe('blob:local');+ expect(resolveVideoStagePreview({ keyframes: [{ file: 'k2.png', index: 40 }, { file: 'k1.png', index: 0 }] }))+ .toMatchObject({ kind: VIDEO_STAGE_KIND.STILL, src: '/data/images/k1.png', label: 'First keyframe' });+ expect(resolveVideoStagePreview({ lastImageFile: 'end.png' }))+ .toMatchObject({ src: '/data/images/end.png', label: 'End frame' });+ });++ it('ignores keyframe rows that have no file yet', () => {+ const stage = resolveVideoStagePreview({ keyframes: [{ file: '', index: 0 }, { index: 40 }] });+ expect(stage.kind).toBe(VIDEO_STAGE_KIND.EMPTY);+ });++ it('keeps a previous render on stage mid-run only when nothing else applies', () => {+ const result = { filename: 'done.mp4' };+ expect(resolveVideoStagePreview({ generating: true, result, sourceImageFile: 'start.png' }).kind)+ .toBe(VIDEO_STAGE_KIND.STILL);+ expect(resolveVideoStagePreview({ generating: true, result }))+ .toMatchObject({ kind: VIDEO_STAGE_KIND.RESULT, src: '/data/videos/done.mp4' });+ });++ it('promotes the finished render above the conditioning once the run settles', () => {+ const stage = resolveVideoStagePreview({+ generating: false,+ result: { path: '/data/videos/done.mp4', thumbnail: 'done.jpg' },+ sourceImageFile: 'start.png',+ extendSource,+ });+ expect(stage.kind).toBe(VIDEO_STAGE_KIND.RESULT);+ expect(stage.src).toBe('/data/videos/done.mp4');+ expect(stage.poster).toBe('/data/video-thumbnails/done.jpg');+ });++ it('accepts either the completion payload shape or a history record shape', () => {+ expect(resolveVideoStagePreview({ result: { path: '/data/videos/a.mp4' } }).src).toBe('/data/videos/a.mp4');+ expect(resolveVideoStagePreview({ result: { filename: 'b.mp4' } }).src).toBe('/data/videos/b.mp4');+ expect(resolveVideoStagePreview({ result: { filename: '' } }).kind).toBe(VIDEO_STAGE_KIND.EMPTY);+ });+});++describe('videoStageSignature', () => {+ it('is stable across equivalent descriptors and changes with the source', () => {+ const a = resolveVideoStagePreview({ sourceImageFile: 'start.png', width: 704, height: 480 });+ const b = resolveVideoStagePreview({ sourceImageFile: 'start.png', width: 704, height: 480 });+ const c = resolveVideoStagePreview({ sourceImageFile: 'other.png', width: 704, height: 480 });+ expect(videoStageSignature(a)).toBe(videoStageSignature(b));+ expect(videoStageSignature(a)).not.toBe(videoStageSignature(c));+ });++ it('changes when only the geometry changed, so a resized stage still swaps', () => {+ const wide = resolveVideoStagePreview({ sourceImageFile: 'a.png', width: 704, height: 480 });+ const tall = resolveVideoStagePreview({ sourceImageFile: 'a.png', width: 480, height: 704 });+ expect(videoStageSignature(wide)).not.toBe(videoStageSignature(tall));+ });+});diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 82cba2172d..16eec0451d 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -51,6 +51,8 @@ import AdvancedParamsPanel from '../components/videoGen/AdvancedParamsPanel';import RuntimeFingerprint from '../components/videoGen/RuntimeFingerprint';import ModelDisclosure from '../components/videoGen/ModelDisclosure';import ModelRepairBanner from '../components/videoGen/ModelRepairBanner';+import LiveVideoStage from '../components/videoGen/LiveVideoStage';+import { resolveVideoStagePreview, VIDEO_STAGE_KIND } from '../lib/videoStagePreview';import VideoGenGallery from '../components/videoGen/VideoGenGallery';import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';import MediaPreview from '../components/media/MediaPreview';@@ -284,6 +286,16 @@ export default function VideoGen() {const [progress, setProgress] = useState(null);const [statusMsg, setStatusMsg] = useState('');const [error, setError] = useState(null);+ // Main-stage preview state (#4588). `currentImage` is the runner's latest+ // decoded frame (absent for every runner that doesn't publish one yet, which+ // is why the stage falls back to the render's conditioning). `renderGeometry`+ // is the server's RESOLVED width/height — the form's values are what we+ // asked for, and videoGen snaps both edges down to the model's grid.+ // `lastRender` is this session's finished clip, so the stage hands off to it+ // instead of going blank when the render lands.+ const [currentImage, setCurrentImage] = useState(null);+ const [renderGeometry, setRenderGeometry] = useState(null);+ const [lastRender, setLastRender] = useState(null);const { attach, eventSourceRef } = useMediaJobSse('video');// Hold the reject() of the in-flight runGeneration Promise so cancel can// settle it. Without this, handleCancel() closes the EventSource but the@@ -320,9 +332,16 @@ export default function VideoGen() {isCurrent,onQueued: (msg) => setStatusMsg(typeof msg.position === 'number' ? `Queued (position ${msg.position})` : 'Queued'),onStarted: () => setStatusMsg('Starting render…'),+ onRenderMeta: (msg) => setRenderGeometry({ width: msg.width, height: msg.height }),+ // Preview-only frame: a runner frame with no progress value. It must not+ // disturb the progress bar, hence its own frame type on the wire.+ onPreview: (msg) => { if (msg.currentImage) setCurrentImage(msg.currentImage); },onStatus: (msg) => setStatusMsg(msg.message),onProgress: (msg) => {setProgress({ progress: msg.progress });+ // Runners throttle frames, so an absent key must leave the last frame+ // on the stage rather than blanking it.+ if (msg.currentImage) setCurrentImage(msg.currentImage);// A bare tqdm percentage shouldn't blank the STATUS line that just// preceded it; only overwrite when the progress event carries text.if (msg.message) setStatusMsg(msg.message);@@ -331,6 +350,9 @@ export default function VideoGen() {setGenerating(false);setProgress({ progress: 1 });setStatusMsg('Complete');+ // Hand the stage off from the forming preview to the finished clip.+ setCurrentImage(null);+ if (msg.result) setLastRender(msg.result);if (withToast) toast.success('Video generated');refreshHistory();return msg.result;@@ -370,6 +392,9 @@ export default function VideoGen() {// attachJobEvents runs.if (runTokenRef.current > 0 || eventSourceRef.current) return;applyResumedParams(job.params || {});+ // The in-flight render's own geometry, not the form's — a reload has to+ // size the stage by what the server resolved.+ if (job.render) setRenderGeometry({ width: job.render.width, height: job.render.height });setGenerating(true);// Skip a forced setProgress(0) here — attachJobEvents will replay the// server's last SSE payload synchronously after EventSource open, and@@ -536,6 +561,31 @@ export default function VideoGen() {const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;+ // What the main stage shows right now (#4588). Memoized because the stage+ // holds a pending descriptor by signature — a fresh object identity on every+ // keystroke in the prompt box would otherwise churn its hold/return guard.+ // Geometry prefers the server's resolved edges and falls back to the form's+ // (a queued job, or a runtime that never reports them).+ const extendSource = useMemo(+ () => (extendFromVideoId ? history.find((v) => v.id === extendFromVideoId) || null : null),+ [extendFromVideoId, history],+ );+ const stage = useMemo(() => resolveVideoStagePreview({+ generating,+ currentImage,+ width: renderGeometry?.width ?? width,+ height: renderGeometry?.height ?? height,+ result: lastRender,+ extendSource,+ sourceImageFile, sourceUploadUrl,+ lastImageFile, lastUploadUrl,+ keyframes: keyframesActive ? keyframes : null,+ }), [+ generating, currentImage, renderGeometry, width, height, lastRender, extendSource,+ sourceImageFile, sourceUploadUrl, lastImageFile, lastUploadUrl, keyframesActive, keyframes,+ ]);+ const showStage = generating || stage.kind !== VIDEO_STAGE_KIND.EMPTY;+// Run a single payload through the SSE pipeline. Returns a promise that// resolves when the job completes (or rejects on error / cancel). Shared// by the inline submit and the queue worker.@@ -555,6 +605,12 @@ export default function VideoGen() {setProgress({ progress: 0 });setStatusMsg('Starting...');setError(null);+ // Stale-job isolation: the previous run's frame and geometry must not be+ // shown as if they belonged to this one. `lastRender` deliberately+ // survives so the stage keeps the finished clip until this run produces+ // something of its own.+ setCurrentImage(null);+ setRenderGeometry(null);const myToken = ++runTokenRef.current;const isCurrent = () => myToken === runTokenRef.current;@@ -707,6 +763,19 @@ export default function VideoGen() {</div></div>+ {showStage && (+ <LiveVideoStage+ descriptor={stage}+ generating={generating}+ progressPct={progressPct}+ statusMsg={statusMsg}+ error={error}+ // Hold while the lightbox is open — the user is watching a clip there,+ // and swapping the stage under it is exactly the theft this guards.+ held={!!preview}+ />+ )}+<RuntimeFingerprint runtime={status?.runtime} />{status && status.connected === false && (() => {diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 8d5d54ba41..87688650b3 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -1285,6 +1285,13 @@ router.get('/active', (_req, res) => {generationId: job.id,status: job.status,position: job.position,+ // Geometry the running render actually resolved to (#4588). `params`+ // carries what the form ASKED for; videoGen/local.js snaps both edges+ // down to the model's resolution grid, so a page that reloads mid-render+ // has to size its preview stage by this, not by the request. `null` when+ // the run hasn't reported it yet (still queued, or a runner that never+ // does) — an explicit "unknown", never a guessed default.+ render: job.render || null,params: pickJobParams(job),},});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex ac7e88c16d..c87c814086 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -750,6 +750,23 @@ function makeGenDispatcher(emitter, job, handlers) {handlers.progress(payload);}};+ // The gen module's `started` event carries the geometry the render actually+ // resolved to — for video, the requested edges snapped DOWN to the model's+ // resolution grid (videoGen/local.js), so it is routinely not what the client+ // submitted. A live preview stage has to size itself by the resolved edges or+ // a portrait render renders into a landscape box. The queue's own `started`+ // SSE frame is broadcast before the gen run begins and cannot carry this, so+ // it rides its own frame type (#4588). Guarded on two finite positive edges:+ // a runner that reports no geometry emits no frame at all, rather than a+ // zero/NaN ratio the client would have to defend against.+ const onStarted = (e) => {+ if (e.generationId !== job.id) return;+ const width = Number(e.width);+ const height = Number(e.height);+ if (!Number.isFinite(width) || width <= 0) return;+ if (!Number.isFinite(height) || height <= 0) return;+ handlers.renderMeta?.({ width, height });+ };const onStatus = (e) => {// Optional explicit `status` event for gens that want to push a status// line independent of progress. Unused today; here so a future emitter@@ -763,12 +780,14 @@ function makeGenDispatcher(emitter, job, handlers) {const onFailed = (e) => { if (e.generationId === job.id) handlers.failed({ error: e.error }); };return {attach() {+ emitter.on('started', onStarted);emitter.on('progress', onProgress);emitter.on('status', onStatus);emitter.on('completed', onCompleted);emitter.on('failed', onFailed);},detach() {+ emitter.off('started', onStarted);emitter.off('progress', onProgress);emitter.off('status', onStatus);emitter.off('completed', onCompleted);@@ -883,6 +902,18 @@ async function runJob(job) {if (didUpdatePersistedProgress) scheduleProgressPersist();broadcastSse(sseEntry, payload);},+ // Geometry the render resolved to (#4588) — see makeGenDispatcher's+ // onStarted. `retain: false` because there is exactly ONE replay slot on+ // the SSE entry and it must hold the frame that says what the run is doing;+ // a reconnecting or reloading client recovers the geometry from the job+ // projection instead, which is why it is persisted here as well.+ renderMeta: ({ width, height }) => {+ if (job.terminating || job.status !== 'running') return;+ if (job.render?.width === width && job.render?.height === height) return;+ job.render = { width, height };+ scheduleProgressPersist();+ broadcastSse(sseEntry, { type: 'render-meta', width, height }, { retain: false });+ },completed: (payload) => {trackTerminalOperation(terminate('completed', (j) => { j.result = payload; })diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex f4c02ae236..cdc404315a 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -393,6 +393,56 @@ describe('mediaJobQueue', () => {await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');});+ it('forwards the resolved render geometry, isolated per job and out of the replay slot', async () => {+ // #4588: a live preview stage must size itself by the geometry the render+ // RESOLVED to (videoGen snaps both edges down to the model's grid), not by+ // what the form submitted. The queue's own `started` SSE frame is broadcast+ // before the gen run begins, so the geometry rides its own frame type.+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'geometry', width: 720, height: 484 } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'running');++ const frames = [];+ const makeRes = (sink) => ({+ writeHead: () => {},+ write: (msg) => {+ for (const line of msg.split('\n')) {+ if (line.startsWith('data: ')) sink.push(JSON.parse(line.slice(6)));+ }+ },+ end: () => {},+ req: { on: () => {} },+ });+ expect(mediaJobQueue.attachSseClient(job.jobId, makeRes(frames))).toBe(true);++ // A `started` event for an unrelated render must not stamp this job.+ videoGenEvents.emit('started', { generationId: 'some-other-job', width: 1920, height: 1080 });+ // Neither must a runner that reports no usable geometry — absent/zero edges+ // emit no frame at all rather than a ratio the client has to defend against.+ videoGenEvents.emit('started', { generationId: job.jobId, totalSteps: 30 });+ videoGenEvents.emit('started', { generationId: job.jobId, width: 0, height: 480 });+ expect(frames.some((f) => f.type === 'render-meta')).toBe(false);+ expect(mediaJobQueue.getJob(job.jobId)?.render).toBeUndefined();++ videoGenEvents.emit('started', { generationId: job.jobId, totalSteps: 30, width: 704, height: 480 });+ await waitFor(() => frames.some((f) => f.type === 'render-meta'));+ expect(frames.find((f) => f.type === 'render-meta')).toEqual({ type: 'render-meta', width: 704, height: 480 });+ // Persisted on the job so a reload recovers it — the SSE entry keeps only+ // ONE replay frame and it must hold what the run is doing.+ expect(mediaJobQueue.getJob(job.jobId).render).toEqual({ width: 704, height: 480 });++ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.25 });+ await waitFor(() => frames.some((f) => f.type === 'progress'));++ const replayed = [];+ expect(mediaJobQueue.attachSseClient(job.jobId, makeRes(replayed))).toBe(true);+ expect(replayed).toHaveLength(1);+ expect(replayed[0]).toMatchObject({ type: 'progress', progress: 0.25 });++ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');+ });+it('debounce-persists live progress before a terminal transition', async () => {const file = join(tempDataDir, 'media-jobs.json');const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'restart snapshot' } });diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.jsindex f5924836f8..191a05eade 100644--- a/server/services/mediaJobQueue/sanitizeJob.js+++ b/server/services/mediaJobQueue/sanitizeJob.js@@ -62,6 +62,12 @@ export function sanitizeJob(job) {position: job.position,progress: job.progress,statusMsg: job.statusMsg,+ // Geometry the gen module resolved to (#4588) — the render's own edges after+ // any model-grid snapping, NOT the requested `params.width/height`. Lives on+ // the envelope rather than in `params` because it is an OUTPUT of the run.+ // Absent until the gen run reports it; `undefined` means "not reported",+ // which a preview stage must not read as a geometry.+ render: job.render,etaMs: job.etaMs,error: job.error,result: job.result,diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.jsindex 1e34339e7c..b2df8753bf 100644--- a/server/services/mediaJobQueue/sanitizeJob.test.js+++ b/server/services/mediaJobQueue/sanitizeJob.test.js@@ -28,6 +28,24 @@ describe('sanitizeJob', () => {});});+ it('projects the resolved render geometry on the envelope, distinct from the requested params', () => {+ // #4588: `params.width/height` is what was ASKED for; `render` is what the+ // gen module resolved to after snapping to the model grid. A preview stage+ // has to size itself by the latter.+ const sanitized = sanitizeJob({+ id: 'video-job',+ kind: 'video',+ status: 'running',+ render: { width: 704, height: 480 },+ params: { width: 720, height: 484 },+ });+ expect(sanitized.render).toEqual({ width: 704, height: 480 });+ expect(sanitized.params).toEqual({ width: 720, height: 484 });+ });++ it('leaves render absent — not zeroed — when the run never reported a geometry', () => {+ expect(sanitizeJob({ id: 'j', kind: 'video', status: 'queued' }).render).toBeUndefined();+ });it('exposes instrumental mode without leaking authored Music Studio text', () => {const job = sanitizeJob({id: 'job-1',