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
report what a video render is actually doing instead of a motionless 0%
[._.]/ Adam Eivyb05201d7fbb2
diff --git a/client/src/components/videoGen/LiveVideoStage.jsx b/client/src/components/videoGen/LiveVideoStage.jsxdeleted file mode 100644index 5231cb8b51..0000000000--- a/client/src/components/videoGen/LiveVideoStage.jsx+++ /dev/null@@ -1,145 +0,0 @@-/**- * 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: the clip an extend is continuing (animated, muted, looping)- * or the still it is growing out of, and the finished clip once it lands.- * Transient runner frames stay off this surface because a single decoded frame- * does not usefully represent the motion or quality of the finished video.- *- * 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.jsxdeleted file mode 100644index ff5e43b5f8..0000000000--- a/client/src/components/videoGen/LiveVideoStage.test.jsx+++ /dev/null@@ -1,121 +0,0 @@-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('keeps conditioning media on stage instead of showing a live runner frame', () => {- const descriptor = resolveVideoStagePreview({- generating: true,- currentImage: 'iVBORw0KG',- sourceImageFile: 'start.png',- width: 480,- height: 832,- });- render(<LiveVideoStage descriptor={descriptor} generating progressPct={40} statusMsg="Rendering step 4/10" />);-- expect(screen.queryByAltText('Live frame')).not.toBeInTheDocument();- expect(screen.getByAltText('Start frame').getAttribute('src')).toBe('/data/images/start.png');- // 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 });- 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 still = resolveVideoStagePreview({ generating: true, sourceImageFile: 'start.png' });- rerender(<LiveVideoStage descriptor={still} generating />);- expect(stageFrame().dataset.stageKind).toBe(VIDEO_STAGE_KIND.STILL);- });-- 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/components/videoGen/RenderStatusCard.jsx b/client/src/components/videoGen/RenderStatusCard.jsxnew file mode 100644index 0000000000..9d24a4d82e--- /dev/null+++ b/client/src/components/videoGen/RenderStatusCard.jsx@@ -0,0 +1,118 @@+/**+ * Video Gen render status (#5872) — what the render is doing, where the user+ * is looking.+ *+ * This replaces the full-size preview stage that used to carry the render's+ * status text. That stage sat above the form, so once the user scrolled down to+ * press Generate the only live feedback left on screen was a bare percentage —+ * and for a runner that reports no numeric progress until denoising begins+ * (FastH3 streams an ~89 GB INT4 DiT first) that percentage sat at 0 for many+ * minutes with no text at all. A video render also can't be usefully previewed+ * mid-flight, so the stage was spending a screen's worth of space on a+ * conditioning still to say something a status line says better.+ *+ * Three things a stalled-looking render needs and a percentage can't give:+ * - the named step it is on, drawn from the runner's own STAGE: markers;+ * - elapsed wall clock, so "silent" is visibly distinct from "stuck";+ * - the display-sleep warning, BEFORE the screen goes dark. An MLX render+ * sleeps the display on purpose (the Apple GPU watchdog panics when+ * WindowServer contends with Metal). A user who isn't told reads the dark+ * screen as a crash and wakes it, re-creating the exact contention.+ *+ * Presentational — every input is owned by the VideoGen page.+ */+import { AlertTriangle, Check, Film, MonitorOff } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';+import Banner from '../ui/Banner';+import ProgressBar from '../ui/ProgressBar';+import { useTimeTick } from '../../hooks/useTimeTick';+import { formatDurationMs } from '../../utils/formatters';+import { resolveVideoRenderSteps } from '../../lib/videoRenderPhase';++const STEP_STATE_STYLE = {+ done: { text: 'text-port-success', dot: 'bg-port-success' },+ active: { text: 'text-port-accent', dot: 'bg-port-accent' },+ pending: { text: 'text-gray-600', dot: 'bg-gray-700' },+};++/**+ * The elapsed clock, isolated in its own component so its one-second tick+ * re-renders a single span rather than the whole card (the step list, the+ * progress bar and the sleep warning all change far more rarely).+ */+function RenderElapsed({ startedAt }) {+ const now = useTimeTick(1000);+ if (!startedAt || now < startedAt) return null;+ return <span className="font-mono text-gray-500">{formatDurationMs(now - startedAt)}</span>;+}++export default function RenderStatusCard({+ generating = false,+ phase = null,+ progressPct = null,+ statusMsg = '',+ error = null,+ startedAt = null,+ sleepsDisplay = false,+}) {+ const { steps, activeId } = resolveVideoRenderSteps({ generating, phase, progressPct });++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">+ <div className="flex items-center justify-between gap-2">+ <h2 className="text-xs font-medium text-gray-400 uppercase tracking-wide">Render status</h2>+ <div className="flex items-center gap-2 text-xs">+ {generating && <RenderElapsed startedAt={startedAt} />}+ {progressPct != null && <span className="font-mono text-port-accent">{progressPct}%</span>}+ </div>+ </div>++ {error ? (+ <Banner tone="error" icon={AlertTriangle}>{error}</Banner>+ ) : generating ? (+ <>+ <div className="flex items-center gap-2 text-sm text-gray-200">+ <BrailleSpinner />+ <span className="truncate" title={statusMsg || undefined}>+ {statusMsg || 'Starting render…'}+ </span>+ </div>++ <ol className="flex flex-wrap gap-x-3 gap-y-1 text-xs">+ {steps.map((step) => (+ <li+ key={step.id}+ data-testid={`render-step-${step.id}`}+ data-state={step.state}+ className={`flex items-center gap-1 ${STEP_STATE_STYLE[step.state].text}`}+ >+ {step.state === 'done'+ ? <Check className="w-3 h-3" />+ : <span className={`w-1.5 h-1.5 rounded-full ${STEP_STATE_STYLE[step.state].dot}`} />}+ <span>{step.label}</span>+ </li>+ ))}+ </ol>++ {progressPct != null && <ProgressBar percent={progressPct} label="Render progress" track="border" />}++ {/* Only shown once the job is past the queue: a render still waiting+ in line has not slept anything yet, and saying so would train the+ user to ignore the warning that matters. */}+ {sleepsDisplay && activeId && activeId !== 'queued' && (+ <Banner tone="warning" icon={MonitorOff}>+ Your display has been put to sleep on purpose for this render — it stops the window+ server from competing with the GPU and crashing it. Leave the screen off; the render+ keeps going and the display wakes when it finishes.+ </Banner>+ )}+ </>+ ) : (+ <div className="flex items-center gap-2 text-xs text-gray-500">+ <Film className="w-4 h-4" />+ <span>{statusMsg || 'No render in progress.'}</span>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/videoGen/RenderStatusCard.test.jsx b/client/src/components/videoGen/RenderStatusCard.test.jsxnew file mode 100644index 0000000000..d9cec00f89--- /dev/null+++ b/client/src/components/videoGen/RenderStatusCard.test.jsx@@ -0,0 +1,51 @@+import { render, screen } from '@testing-library/react';+import { describe, it, expect } from 'vitest';+import RenderStatusCard from './RenderStatusCard';++describe('RenderStatusCard', () => {+ it('names the step a silent render is on instead of showing a bare percentage', () => {+ render(<RenderStatusCard generating progressPct={0} statusMsg="Loading the FastVideo pipeline · 2m45s elapsed" />);++ expect(screen.getByText('Loading the FastVideo pipeline · 2m45s elapsed')).toBeInTheDocument();+ expect(screen.getByTestId('render-step-load')).toHaveAttribute('data-state', 'active');+ expect(screen.getByTestId('render-step-render')).toHaveAttribute('data-state', 'pending');+ });++ it('advances the step list from the runner phase', () => {+ render(<RenderStatusCard generating phase="sampling" progressPct={40} />);++ expect(screen.getByTestId('render-step-load')).toHaveAttribute('data-state', 'done');+ expect(screen.getByTestId('render-step-render')).toHaveAttribute('data-state', 'active');+ expect(screen.getByRole('progressbar', { name: 'Render progress' }))+ .toHaveAttribute('aria-valuenow', '40');+ });++ it('shows elapsed wall clock so a silent phase reads as work, not a hang', () => {+ render(<RenderStatusCard generating startedAt={Date.now() - 165_000} />);+ expect(screen.getByText('2m 45s')).toBeInTheDocument();+ });++ // The display going dark unannounced is what made users wake it — and waking+ // it is what risks the GPU-watchdog panic the sleep is there to prevent.+ it('explains the dark screen while an MLX render is running', () => {+ render(<RenderStatusCard generating phase="sampling" sleepsDisplay />);+ expect(screen.getByText(/put to sleep on purpose/i)).toBeInTheDocument();+ });++ it('does not claim the display is asleep while the job is still queued', () => {+ render(<RenderStatusCard generating phase="queued" sleepsDisplay />);+ expect(screen.queryByText(/put to sleep on purpose/i)).not.toBeInTheDocument();+ expect(screen.getByTestId('render-step-queued')).toHaveAttribute('data-state', 'active');+ });++ it('shows the error instead of the step list when a render fails', () => {+ render(<RenderStatusCard generating={false} error="Runner exited with code 1" />);+ expect(screen.getByText('Runner exited with code 1')).toBeInTheDocument();+ expect(screen.queryByTestId('render-step-render')).not.toBeInTheDocument();+ });++ it('rests quietly when nothing is rendering', () => {+ render(<RenderStatusCard />);+ expect(screen.getByText('No render in progress.')).toBeInTheDocument();+ });+});diff --git a/client/src/hooks/useMediaJobSse.js b/client/src/hooks/useMediaJobSse.jsindex f32b400a14..198190a9b4 100644--- a/client/src/hooks/useMediaJobSse.js+++ b/client/src/hooks/useMediaJobSse.js@@ -22,15 +22,12 @@ 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`, `onPreview`, `onRenderMeta`, `onComplete`,- * `onError`, `onCanceled`, `onConnectionError`.+ * `onStatus`, `onProgress`, `onPreview`, `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.+ * type so a consumer's progress bar isn't disturbed by it.** `eventSourceRef` is exposed so callers can `close()` on cancel/unmount.*/@@ -45,7 +42,7 @@ export function useMediaJobSse(kind) {const attach = useCallback((jobId, handlers = {}) => {const {isCurrent = () => true,- onQueued, onStarted, onStage, onStatus, onProgress, onPreview, onRenderMeta,+ onQueued, onStarted, onStage, onStatus, onProgress, onPreview,onComplete, onError, onCanceled, onConnectionError,} = handlers;return new Promise((resolve, reject) => {@@ -64,7 +61,6 @@ export function useMediaJobSse(kind) {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 85791e1259..f63635af8f 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -83,7 +83,7 @@ grep -i "what you want to do" client/src/lib/README.md| `videoGenStatusCache.js` | Session-scoped cache of the model-shaping half of `GET /api/video-gen/status` (`readCachedVideoGenStatus` / `writeCachedVideoGenStatus` / `VIDEO_GEN_STATUS_CACHE_KEY`), so the Video Gen Model picker paints from the previous answer instead of waiting on the python probe behind that route. Stores only the model list plus `defaultModel` / `systemMemoryGb` and hands them back marked `stale: true`; every python-health field is dropped rather than guarded, so a stored answer can never report connectivity. || `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. || `videoReferenceModes.js` | Mirror of `server/lib/videoReferenceModes.js` (parity enforced by `server/lib/videoReferenceModes.mirror.test.js`) — the i2v reference-mode contract: `I2V_REFERENCE_MODES`, `I2V_REFERENCE_MODE_OPTIONS` (label + the promise sentence `AdvancedParamsPanel` and the source-frame note print), `runtimeSupportsI2vReferenceMode` (gates which options the picker offers), `resolveI2vReferenceStrength` (the effective strength the panel displays), and `i2vReferenceModeViolation` for pre-submit feedback. |-| `videoStagePreview.js` | VideoGen main-stage preview resolver (#4588). `resolveVideoStagePreview({ generating, width, height, result, extendSource, sourceImageFile/Url, lastImageFile/Url, keyframes })` → `{ kind: 'loop'|'still'|'result'|'empty', src, poster, label, aspectRatio }` — conditioning media while a render runs and the finished clip once it lands; transient runner frames are intentionally excluded. 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) and `videoStageSignature()` for the hold/return guard in `components/videoGen/LiveVideoStage.jsx`. |+| `videoRenderPhase.js` | Video render phase → named progress step (#5872). `resolveVideoRenderSteps({ generating, phase, progressPct })` → `{ activeId, steps: [{ id, label, state: 'done'|'active'|'pending' }] }`, collapsing the runners' fine-grained `STAGE:` vocabulary (`load-transformer`, `encode-prompt`, `sampling`, `mux`, …) onto six steps a person can read — the queue's own `queued` is one of them, so a caller needs no separate flag. Family prefixes (`download-*`, `load-*`, `wan-*`, …) absorb markers a future runner adds; `videoRenderStepFor(phase)` returns `null` for a genuinely unknown one, never step 0. Consumed by `components/videoGen/RenderStatusCard.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 a0a62b903e..513e9edbd6 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -63,7 +63,7 @@ export * from './videoGenResolutions.js';export * from './videoGenStatusCache.js';export * from './videoGenSubmission.js';export * from './videoReferenceModes.js';-export * from './videoStagePreview.js';+export * from './videoRenderPhase.js';export * from './videoTilingOptions.js';export * from './wrImageDefaults.js';diff --git a/client/src/lib/videoRenderPhase.js b/client/src/lib/videoRenderPhase.jsnew file mode 100644index 0000000000..89a818eb38--- /dev/null+++ b/client/src/lib/videoRenderPhase.js@@ -0,0 +1,140 @@+/**+ * Video render phase → named progress step (#5872).+ *+ * A local video render spends most of its wall clock somewhere other than the+ * sampler: resolving a cache, streaming tens of gigabytes of weights onto the+ * GPU, encoding the prompt, decoding latents, muxing audio. The runners already+ * announce which of those they are in — every helper under `scripts/` emits+ * `STAGE:<phase>` markers, and the server now forwards that id on its status and+ * progress frames — but the page had nowhere to put it, so a FastH3 render (an+ * ~89 GB INT4 DiT, no per-step progress until denoising starts) showed a+ * motionless "0%" and the word "Starting render…" for many minutes.+ *+ * This maps the runner's fine-grained phase vocabulary onto a short, ordered+ * list of steps a person can actually read, so the UI can say "Loading model —+ * step 2 of 5" instead of nothing. Pure: the caller owns every input.+ *+ * The step list is deliberately coarse. Runners disagree on how finely they+ * subdivide their work (`load-transformer` / `load-text-encoder` /+ * `from-pretrained` / `move-to-device` are all one wait as far as the user is+ * concerned), and a list that grew a row per marker would be a changelog of the+ * Python scripts rather than a description of the render.+ */++/** Ordered coarse steps. `id` is stable; `label` is what the user reads. */+export const VIDEO_RENDER_STEPS = Object.freeze([+ { id: 'queued', label: 'Queued' },+ { id: 'download', label: 'Downloading weights' },+ { id: 'load', label: 'Loading model' },+ { id: 'encode', label: 'Encoding prompt' },+ { id: 'render', label: 'Rendering' },+ { id: 'finalize', label: 'Decoding and saving' },+].map(Object.freeze));++const STEP_INDEX = Object.fromEntries(VIDEO_RENDER_STEPS.map((step, index) => [step.id, index]));++// Exact runner `STAGE:` id → coarse step, for the markers that carry no useful+// family prefix. Keys are what the helpers under `scripts/` actually emit (grep+// `STAGE:` there); anything unmatched falls through to `null`, which the caller+// must treat as "unknown phase", never as step 0 — reporting "Queued" for an+// unrecognized marker would read as the render having gone backwards.+const PHASE_STEP = Object.freeze({+ // The download helper's own preamble, not separate user-visible work.+ 'resolve-cache': 'download',+ verify: 'download',+ list: 'download',+ bytes: 'download',++ // Getting the pipeline resident. The single longest phase on a large+ // quantized checkpoint, and the one that used to show nothing at all.+ 'from-pretrained': 'load',+ 'move-to-device': 'load',+ 'apply-loras': 'load',+ starting: 'load',++ // Conditioning.+ 'encode-prompt': 'encode',+ 'precompute-latents': 'encode',++ // The sampler itself.+ inference: 'render',+ sampling: 'render',+ generate: 'render',+ render: 'render',+ fastvideo: 'render',+ 'minimax-h3': 'render',+ 'ref2va-window': 'render',++ // Everything after the last denoise step.+ mux: 'finalize',+ complete: 'finalize',++ // The queue's own state, so a caller has one vocabulary rather than a+ // separate "is it queued" flag alongside the phase.+ queued: 'queued',+});++// Prefix families, longest-prefix-first. The runners name their markers by+// family (`download-text-encoder`, `load-transformer`, `swap-video-decoder`,+// `wan-i2v`, `ref2va-mux`), and each family already ends up in one step — so+// matching the prefix absorbs the markers a future runner adds instead of+// silently degrading them to "unknown phase".+const PHASE_PREFIX_STEP = Object.freeze([+ ['download-', 'download'],+ ['load-', 'load'],+ ['swap-', 'load'],+ ['encode-prompt', 'encode'],+ ['ref2va-', 'render'],+ ['wan-', 'render'],+]);++/**+ * The coarse step a runner phase belongs to, or `null` when the phase is+ * unrecognized. Case-insensitive because BYOV helpers are not required to agree+ * on capitalization (the server normalizes STAGE tags the same way).+ */+export function videoRenderStepFor(phase) {+ if (typeof phase !== 'string' || !phase) return null;+ const id = phase.toLowerCase();+ if (PHASE_STEP[id]) return PHASE_STEP[id];+ return PHASE_PREFIX_STEP.find(([prefix]) => id.startsWith(prefix))?.[1] || null;+}++// One frozen step list per possible active step, plus the all-pending list.+// `resolveVideoRenderSteps` is called on every render of a page that re-renders+// on each keystroke and each SSE frame, and there are only seven answers — so+// they are built once at import and shared, which also gives callers a stable+// identity to memo on.+const STEPS_BY_ACTIVE_ID = Object.freeze(Object.fromEntries(+ [null, ...VIDEO_RENDER_STEPS.map((step) => step.id)].map((activeId) => [+ String(activeId),+ Object.freeze(VIDEO_RENDER_STEPS.map((step, index) => Object.freeze({+ ...step,+ state: index === STEP_INDEX[activeId] ? 'active'+ : index < STEP_INDEX[activeId] ? 'done' : 'pending',+ }))),+ ]),+));++/**+ * Project a render's live state onto the step list.+ *+ * `phase` is the runner's marker (absent until the first status frame, and set+ * to `'queued'` by the page while the job is still in line), and `progressPct`+ * is only used to decide whether the sampler has demonstrably started — a+ * runner that reports numeric progress is rendering even if its phase marker+ * never arrived.+ *+ * Returns `{ steps, activeId }` where each step carries `state`:+ * `'done' | 'active' | 'pending'`. `activeId` is `null` only when there is+ * nothing to show (not generating).+ */+export function resolveVideoRenderSteps({ generating = false, phase = null, progressPct = null } = {}) {+ // Order of preference: an explicit phase, then "the sampler is visibly+ // running", then the honest default for a render that has started but told us+ // nothing yet — which is loading, not rendering.+ const activeId = !generating ? null+ : videoRenderStepFor(phase)+ || (Number.isFinite(progressPct) && progressPct > 0 ? 'render' : 'load');+ return { activeId, steps: STEPS_BY_ACTIVE_ID[String(activeId)] };+}diff --git a/client/src/lib/videoRenderPhase.test.js b/client/src/lib/videoRenderPhase.test.jsnew file mode 100644index 0000000000..0d7a256f4a--- /dev/null+++ b/client/src/lib/videoRenderPhase.test.js@@ -0,0 +1,70 @@+import { describe, it, expect } from 'vitest';+import { resolveVideoRenderSteps, videoRenderStepFor } from './videoRenderPhase';++const activeLabel = (result) => result.steps.find((step) => step.state === 'active')?.label ?? null;++describe('videoRenderStepFor', () => {+ it('collapses each runner phase family onto its coarse step', () => {+ expect(videoRenderStepFor('download-text-encoder')).toBe('download');+ expect(videoRenderStepFor('load-transformer')).toBe('load');+ expect(videoRenderStepFor('encode-prompt')).toBe('encode');+ expect(videoRenderStepFor('sampling')).toBe('render');+ expect(videoRenderStepFor('mux')).toBe('finalize');+ });++ // Matching the family prefix is what keeps the table from silently rotting:+ // runners keep adding markers within families they already emit.+ it('absorbs unseen markers within a known family via its prefix', () => {+ expect(videoRenderStepFor('download-some-new-shard')).toBe('download');+ expect(videoRenderStepFor('load-audio-vae')).toBe('load');+ expect(videoRenderStepFor('swap-video-decoder')).toBe('load');+ expect(videoRenderStepFor('encode-prompt-done')).toBe('encode');+ // generate_wan22.py emits STAGE:wan-i2v / STAGE:wan-t2v, never bare "wan".+ expect(videoRenderStepFor('wan-i2v')).toBe('render');+ expect(videoRenderStepFor('ref2va-mux')).toBe('render');+ });++ it('normalizes case, because BYOV helpers are not required to agree on it', () => {+ expect(videoRenderStepFor('Load-Pipeline')).toBe('load');+ });++ // An unknown marker must not resolve to the FIRST step: a render that jumped+ // back to "Queued" mid-flight reads as having lost its work.+ it('returns null for an unrecognized phase rather than the first step', () => {+ expect(videoRenderStepFor('some-future-marker')).toBeNull();+ expect(videoRenderStepFor('')).toBeNull();+ expect(videoRenderStepFor(undefined)).toBeNull();+ });+});++describe('resolveVideoRenderSteps', () => {+ it('marks earlier steps done and later ones pending', () => {+ const { activeId, steps } = resolveVideoRenderSteps({ generating: true, phase: 'sampling' });+ expect(activeId).toBe('render');+ expect(steps.map((s) => s.state)).toEqual(['done', 'done', 'done', 'done', 'active', 'pending']);+ });++ it('shows nothing active when no render is running', () => {+ const { activeId, steps } = resolveVideoRenderSteps({ generating: false, phase: 'sampling' });+ expect(activeId).toBeNull();+ expect(steps.every((s) => s.state === 'pending')).toBe(true);+ });++ it('treats the queue as one more phase rather than a separate flag', () => {+ expect(activeLabel(resolveVideoRenderSteps({ generating: true, phase: 'queued' }))).toBe('Queued');+ });++ // The regression this whole card exists for: FastH3 streams an ~89 GB+ // checkpoint before its first denoise step and reports no phase and no+ // progress while it does. "Loading model" is the truthful default there —+ // "Rendering" would be a lie and a blank would be the old bug.+ it('defaults a started-but-silent render to loading, not rendering', () => {+ expect(activeLabel(resolveVideoRenderSteps({ generating: true }))).toBe('Loading model');+ });++ it('treats visible numeric progress as rendering when no phase arrived', () => {+ expect(activeLabel(resolveVideoRenderSteps({ generating: true, progressPct: 12 }))).toBe('Rendering');+ // 0% is what the page seeds before the first frame — not evidence of work.+ expect(activeLabel(resolveVideoRenderSteps({ generating: true, progressPct: 0 }))).toBe('Loading model');+ });+});diff --git a/client/src/lib/videoStagePreview.js b/client/src/lib/videoStagePreview.jsdeleted file mode 100644index 9383cfe3a6..0000000000--- a/client/src/lib/videoStagePreview.js+++ /dev/null@@ -1,125 +0,0 @@-/**- * 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 — 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. Transient runner- * frames are deliberately omitted because they are not useful video previews.- *- * 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({- 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;-}--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 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 conditioning is the- * subject and the finished clip from the PREVIOUS render is only a last resort;- * idle, the finished clip is the subject and the conditioning is the fallback.- */-export function resolveVideoStagePreview({- generating = false,- width = null,- height = null,- result = null,- extendSource = null,- sourceImageFile = null,- sourceUploadUrl = null,- lastImageFile = null,- lastUploadUrl = null,- keyframes = null,-} = {}) {- const aspectRatio = videoStageAspectRatio(width, height);- const finished = resultCandidate(result);- const loop = loopCandidate(extendSource);- const still = stillCandidate({ sourceImageFile, sourceUploadUrl, lastImageFile, lastUploadUrl, keyframes });- const ordered = generating ? [loop, still, finished] : [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.jsdeleted file mode 100644index a3fa8b02e3..0000000000--- a/client/src/lib/videoStagePreview.test.js+++ /dev/null@@ -1,109 +0,0 @@-import { describe, it, expect } from 'vitest';-import {- VIDEO_STAGE_KIND,- resolveVideoStagePreview,- 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('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('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 2de0774e4e..da24b1f570 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -52,8 +52,7 @@ 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 RenderStatusCard from '../components/videoGen/RenderStatusCard';import VideoGenGallery from '../components/videoGen/VideoGenGallery';import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';import MediaPreview from '../components/media/MediaPreview';@@ -64,7 +63,7 @@ import PromptFromMedia from '../components/media/PromptFromMedia';import { normalizeVideo } from '../components/media/normalize';import {Film, Sparkles, Settings as SettingsIcon, RefreshCw, AlertTriangle,- X, Type, Image as ImageIcon, GitBranch, ListPlus, Music, SlidersHorizontal,+ X, Type, Image as ImageIcon, GitBranch, ListPlus, Music, SlidersHorizontal, MonitorOff,} from 'lucide-react';import toast from '../components/ui/Toast';import MediaJobsQueue from '../components/media/MediaJobsQueue';@@ -382,14 +381,15 @@ export default function VideoGen() {const [progress, setProgress] = useState(null);const [statusMsg, setStatusMsg] = useState('');const [error, setError] = useState(null);- // Main-stage preview state (#4588). `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. Transient runner frames- // are intentionally ignored: they are not useful for judging a video render.- // `lastRender` is this session's finished clip, so the stage hands off to it- // instead of going blank when the render lands.- const [renderGeometry, setRenderGeometry] = useState(null);- const [lastRender, setLastRender] = useState(null);+ // Live render status (#5872). `phase` is the runner's own STAGE: id, mapped+ // to a named step by the status card — with the queue's own 'queued' as one+ // more phase id, so waiting in line and running share one piece of state+ // instead of a boolean every SSE handler has to remember to clear.+ // `renderStartedAt` drives the elapsed clock, which is what makes a silent+ // phase (an ~89 GB checkpoint streaming onto the GPU) legible as work rather+ // than as a hang.+ const [phase, setPhase] = useState(null);+ const [renderStartedAt, setRenderStartedAt] = 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@@ -424,25 +424,38 @@ export default function VideoGen() {const attachJobEvents = (jobId, { isCurrent = () => true, settleResolve = () => {}, settleReject = () => {}, withToast = true } = {}) => {return attach(jobId, {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 }),- onStatus: (msg) => setStatusMsg(msg.message),+ onQueued: (msg) => {+ setPhase('queued');+ setStatusMsg(typeof msg.position === 'number' ? `Queued (position ${msg.position})` : 'Queued');+ },+ onStarted: () => {+ // Out of the queue, but the runner hasn't named a phase yet — clear it+ // rather than guessing, and let the card default to "Loading model".+ setPhase(null);+ setRenderStartedAt((at) => at ?? Date.now());+ setStatusMsg('Starting render…');+ },+ // `phase` is presence-guarded on the wire: a frame that carries none must+ // leave the last known phase alone rather than reset the step list to+ // "unknown" on every bare status line.+ onStatus: (msg) => {+ if (msg.phase) setPhase(msg.phase);+ setStatusMsg(msg.message);+ },onProgress: (msg) => {setProgress({ progress: msg.progress });+ if (msg.phase) setPhase(msg.phase);// 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);},- onComplete: (msg) => {+ onComplete: () => {setGenerating(false);setProgress({ progress: 1 });+ setPhase(null);setStatusMsg('Complete');- // Hand the stage off from the conditioning media to the finished clip.- if (msg.result) setLastRender(msg.result);if (withToast) toast.success('Video generated');refreshHistory();- return msg.result;},onError: (msg) => {setError(msg.error);@@ -452,6 +465,7 @@ export default function VideoGen() {},onCanceled: (msg) => {setGenerating(false);+ setPhase(null);setStatusMsg(msg.reason || 'Canceled');if (withToast) toast(msg.reason || 'Render canceled');return new Error(msg.reason || 'Canceled');@@ -479,10 +493,11 @@ 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);+ setPhase(job.status === 'queued' ? 'queued' : null);+ // The worker's own start time, so a reload keeps a truthful elapsed clock+ // instead of restarting it and reading as a fresh render.+ setRenderStartedAt(job.startedAt ? new Date(job.startedAt).getTime() : Date.now());// Skip a forced setProgress(0) here — attachJobEvents will replay the// server's last SSE payload synchronously after EventSource open, and// a job mid-render would otherwise visibly flash 0% before jumping@@ -648,29 +663,13 @@ 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,- width: renderGeometry?.width ?? width,- height: renderGeometry?.height ?? height,- result: lastRender,- extendSource,- sourceImageFile, sourceUploadUrl,- lastImageFile, lastUploadUrl,- keyframes: keyframesActive ? keyframes : null,- }), [- generating, renderGeometry, width, height, lastRender, extendSource,- sourceImageFile, sourceUploadUrl, lastImageFile, lastUploadUrl, keyframesActive, keyframes,- ]);- const showStage = generating || stage.kind !== VIDEO_STAGE_KIND.EMPTY;+ // Will this render put the display to sleep? Both halves are server-owned so+ // the warning can't drift from the behaviour: the model says whether its+ // runtime needs the mitigation, and /status says whether this install will+ // actually apply it (macOS, and the user hasn't opted out).+ const rendersSleepDisplay = !!status?.displaySleepOnRender+ && !!currentModel?.sleepsDisplayDuringRender+ && !remoteTarget.isRemote && !isGrok;// Run a single payload through the SSE pipeline. Returns a promise that// resolves when the job completes (or rejects on error / cancel). The@@ -692,10 +691,10 @@ export default function VideoGen() {setProgress({ progress: 0 });setStatusMsg('Starting...');setError(null);- // Stale-job isolation: the previous run's geometry must not be shown as if- // it belonged to this one. `lastRender` deliberately survives so the stage- // keeps the finished clip until this run produces something of its own.- setRenderGeometry(null);+ // Stale-job isolation: the previous run's phase and clock must not be shown+ // as if they belonged to this one.+ setPhase(null);+ setRenderStartedAt(Date.now());const myToken = ++runTokenRef.current;const isCurrent = () => myToken === runTokenRef.current;@@ -870,19 +869,6 @@ 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} />{statusFresh && status.connected === false && (() => {@@ -1482,6 +1468,22 @@ export default function VideoGen() {</span>)}</div>++ {/* Said BEFORE the button is pressed, not after the screen is already+ dark. A user who first learns about the sleep by watching their+ display go black reads it as a crash and wakes it — which puts+ WindowServer back in contention with Metal and risks the GPU+ watchdog panic the sleep exists to avoid. */}+ {rendersSleepDisplay && !generating && (+ <p className="flex items-start gap-1.5 text-[11px] text-port-warning">+ <MonitorOff className="w-3.5 h-3.5 mt-px shrink-0" />+ <span>+ This model renders with your display asleep. The screen will go dark shortly+ after you start — that is expected, and waking it can crash the render. Disable it+ under Settings → Media Generation if you would rather keep the screen on.+ </span>+ </p>+ )}</div><div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">@@ -1496,6 +1498,16 @@ export default function VideoGen() {</div></form>+ <RenderStatusCard+ generating={generating}+ phase={phase}+ progressPct={progressPct}+ statusMsg={statusMsg}+ error={error}+ startedAt={renderStartedAt}+ sleepsDisplay={rendersSleepDisplay}+ />+<MediaJobsQueue kind="video" /><VideoGenGallerydiff --git a/scripts/_runner_common.py b/scripts/_runner_common.pyindex 92e25c6ff3..0e669c1f1e 100644--- a/scripts/_runner_common.py+++ b/scripts/_runner_common.py@@ -59,7 +59,7 @@ def register_source_namespace(package_name: str, package_dir: "str | Path"):@contextmanager-def heartbeat(stage: str, interval: float = 20.0):+def heartbeat(stage: "str | Callable[[], str]", interval: float = 20.0):"""Emit a periodic STAGE:<stage>:heartbeat:Ns marker so the JS idlewatchdog (default 5min) doesn't kill silent long pipeline loads.@@ -69,14 +69,22 @@ def heartbeat(stage: str, interval: float = 20.0):the heartbeat line and resets lastActivityAt. True hangs (GIL-pinnedC extension, no I/O) still trip the watchdog because the heartbeatthread can't print either.++ `stage` may be a callable resolved per beat, for a runner that wraps a+ whole child process rather than one load step: generate_fastvideo.py scrapes+ the phase out of the child's own log lines, so the phase the heartbeat is+ reporting changes underneath it. The server stamps that phase onto the+ status frame, which is what lets the UI name the step during the many+ minutes a large checkpoint spends streaming in silence."""stop = threading.Event()+ resolve_stage = stage if callable(stage) else (lambda: stage)def beat():elapsed = 0while not stop.wait(interval):elapsed += int(interval)- print(f"STAGE:{stage}:heartbeat:{elapsed}s", file=sys.stderr, flush=True)+ print(f"STAGE:{resolve_stage()}:heartbeat:{elapsed}s", file=sys.stderr, flush=True)t = threading.Thread(target=beat, daemon=True)t.start()diff --git a/scripts/generate_fastvideo.py b/scripts/generate_fastvideo.pyindex 20a696203a..2140013298 100755--- a/scripts/generate_fastvideo.py+++ b/scripts/generate_fastvideo.py@@ -27,7 +27,7 @@ from pathlib import Path# Same-dir sibling import. _runner_common is stdlib-only at import time.sys.path.insert(0, str(Path(__file__).resolve().parent))-from _runner_common import emit_runtime_fingerprint, establish_process_group # noqa: E402+from _runner_common import emit_runtime_fingerprint, establish_process_group, heartbeat # noqa: E402_DENOISE_STEP_PATTERN = re.compile(@@ -35,6 +35,79 @@ _DENOISE_STEP_PATTERN = re.compile()_PERCENT_PATTERN = re.compile(r'\d+%')+# ---------------------------------------------------------------------------+# Phase reporting (#5872)+#+# FastH3 is silent for MINUTES at a time. Its MLX pipeline+# (fastvideo/mlx_runtime/minimax_h3_pipeline.py) logs one milestone line per+# phase and emits no per-step denoise progress at all, so a render that is+# streaming an ~89 GB INT4 DiT off disk looks identical to a hung one: 0%, no+# text. PortOS therefore derives the phase itself, by scraping the milestone+# lines upstream DOES log into a small monotonic state machine.+#+# Liveness is the shared `_runner_common.heartbeat`, handed a callable so each+# beat reports whichever phase the scraper is currently in. The server stamps+# that phase onto the status frame it broadcasts, so the UI can name the step+# even while nothing else is being said.+# ---------------------------------------------------------------------------++# The phase progression, earliest first. Ordering is load-bearing — it is what+# keeps `advance_phase` monotonic — so it is declared here rather than inferred+# from the key order of the label table below.+_PHASE_ORDER = ("load-pipeline", "encode-prompt", "sampling", "mux")++# Phase id -> the sentence the user reads, emitted once per transition. Ids are+# drawn from the STAGE: vocabulary the server already parses+# (generateVideoHelpers.js), so the client's phase→step mapping needs no+# FastVideo-specific entries.+PHASE_LABELS = {+ "load-pipeline": "Loading the FastVideo pipeline",+ "encode-prompt": "Encoding the prompt and streaming model weights",+ "sampling": "Rendering (denoising)",+ "mux": "Decoding and muxing video + audio",+}++# The phase a render is in from spawn until upstream says otherwise.+INITIAL_PHASE = _PHASE_ORDER[0]++# (lowercase substring, phase it moves us to). First match wins. Each marker is+# a line upstream logs at the END of the work it names, so it opens the NEXT+# phase rather than the one it describes.+_PHASE_MARKERS = (+ # `Geometry: output=...` is the first line generate() logs, i.e. the+ # pipeline object is constructed and the long conditioning leg starts here.+ ("geometry:", "encode-prompt"),+ # Text conditioning is done — either freshly encoded or read from cache.+ ("loaded prompt embeddings", "sampling"),+ # The DiT finished streaming in; denoising is the only thing left before+ # decode. Both orderings are covered because a prompt-cache hit skips the+ # encode entirely.+ ("loaded mlx h3 dit", "sampling"),+ ("recomputing adaln cache", "sampling"),+ # Denoising is over; everything after it is VAE decode + ffmpeg mux.+ ("generation complete", "mux"),+)+++def advance_phase(line: str, current: str) -> str:+ """The phase `line` moves us into, or `current` when it names none.++ Never moves backwards: upstream repeats some milestone lines (a chained or+ retried leg re-logs `Geometry:`), and a phase that regressed to+ "Encoding the prompt" halfway through denoising would read as a stall.+ """+ # A denoising-step line is proof of the sampler running whatever the+ # milestone wording said. It is the only marker the fastmetal family emits,+ # so without this its heartbeat would keep claiming "Loading the FastVideo+ # pipeline" while the step counter climbed.+ phase = "sampling" if _DENOISE_STEP_PATTERN.search(line) else None+ if phase is None:+ lowered = line.lower()+ phase = next((p for marker, p in _PHASE_MARKERS if marker in lowered), None)+ if phase is None or _PHASE_ORDER.index(phase) <= _PHASE_ORDER.index(current):+ return current+ return phase+def translate_line(line: str) -> str:"""Translate one upstream output line into PortOS's progress protocol."""@@ -197,7 +270,6 @@ def main() -> int:cmd = build_command(args, entry_script, model_root, mlx_checkpoint)- print("STAGE:inference", file=sys.stderr, flush=True)print(f"🎬 fastvideo {args.family} generate {args.width}x{args.height} frames={args.num_frames} steps={args.steps} seed={args.seed}", file=sys.stderr, flush=True)env = os.environ.copy()@@ -221,17 +293,29 @@ def main() -> int:cwd=str(repo_dir),)+ def emit(text: str) -> None:+ print(text, file=sys.stderr, flush=True)++ phase = INITIAL_PHASE+ emit(f"STAGE:{phase}")+assert proc.stdout is not None# Parse output lines and map to STAGE: / STATUS: protocols. Only the# upstream denoising-step message represents render progress. Startup# model-loading bars also contain percentages (often ending at 100%) and# must remain status output or the generic server parser will report them# as completed rendering.- for raw in proc.stdout:- line = raw.rstrip()- if not line:- continue- print(translate_line(line), file=sys.stderr, flush=True)+ with heartbeat(lambda: phase):+ for raw in proc.stdout:+ line = raw.rstrip()+ if not line:+ continue+ next_phase = advance_phase(line, phase)+ if next_phase != phase:+ phase = next_phase+ emit(f"STAGE:{phase}")+ emit(f"STATUS:{PHASE_LABELS[phase]}")+ emit(translate_line(line))return_code = proc.wait()if return_code != 0:diff --git a/scripts/generate_fastvideo.test.js b/scripts/generate_fastvideo.test.jsindex d7e9a80eea..8dcd731dca 100644--- a/scripts/generate_fastvideo.test.js+++ b/scripts/generate_fastvideo.test.js@@ -45,3 +45,52 @@ describe.skipIf(!pyBin)('generate_fastvideo.py', () => {]);});});++// Phase reporting (#5872). FastH3's MLX pipeline logs one milestone line per+// phase and NO per-step denoise progress, so these markers plus the heartbeat+// are the only thing standing between the user and a 20-minute blank 0%.+describe.skipIf(!pyBin)('generate_fastvideo.py phase reporting', () => {+ it('advances the phase on each upstream milestone line', () => {+ const output = runPython(`${importRunner}\n${[+ 'phase = runner.INITIAL_PHASE',+ 'for line in [',+ ' "INFO Geometry: output=832x480x124 model=832x480x124 audio_frames=124 fast=None",',+ ' "INFO Loaded prompt embeddings from cache abc123",',+ ' "INFO Loaded MLX H3 DiT from /models/int4 in 412.7s",',+ ' "INFO Generation complete: /out/render.mp4 | timings={} peaks={}",',+ ']:',+ ' phase = runner.advance_phase(line, phase)',+ ' print(phase)',+ ].join('\n')}`);++ expect(lines(output)).toEqual(['encode-prompt', 'sampling', 'sampling', 'mux']);+ });++ it('never moves the phase backwards when a milestone line repeats', () => {+ const output = runPython(`${importRunner}\n${[+ 'print(runner.advance_phase("INFO Geometry: output=832x480x124", "sampling"))',+ 'print(runner.advance_phase("nothing to see here", "sampling"))',+ ].join('\n')}`);++ expect(lines(output)).toEqual(['sampling', 'sampling']);+ });++ // fastmetal reports denoise steps but none of FastH3's milestone wording, so+ // without this its heartbeat would keep claiming "Loading the FastVideo+ // pipeline" while the step counter climbed.+ it('treats a denoising step as proof the sampler is running', () => {+ const output = runPython(`${importRunner}\n${[+ 'print(runner.advance_phase("denoising step 2/4", runner.INITIAL_PHASE))',+ ].join('\n')}`);++ expect(lines(output)).toEqual(['sampling']);+ });++ it('labels every phase it can advance into', () => {+ const output = runPython(`${importRunner}\n${[+ 'print(sorted(runner._PHASE_ORDER) == sorted(runner.PHASE_LABELS))',+ ].join('\n')}`);++ expect(lines(output)).toEqual(['True']);+ });+});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 6bfa1e2ad5..eea7898f0c 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -72,6 +72,7 @@ import {streamVideoRuntimeInstall,} from '../services/videoGen/runtimeInstaller.js';import { detectSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js';+import { isDisplaySleepEnabled } from '../services/displayPower.js';const router = Router();@@ -437,6 +438,13 @@ router.get('/status', asyncHandler(async (_req, res) => {// with a catch as defense-in-depth so a runtime-block failure can never// reject the whole /status response.runtime: await resolveRuntimeFingerprint().catch(() => null),+ // Will a render on this install actually sleep the display? macOS-only, and+ // the user can opt out (settings.videoGen.displaySleep). Paired with each+ // model's `sleepsDisplayDuringRender`, this is what lets the UI warn BEFORE+ // the screen goes dark — a user who is not warned reads it as a crash and+ // wakes the display, re-introducing the exact GPU-watchdog contention the+ // sleep is there to avoid.+ displaySleepOnRender: isDisplaySleepEnabled(s.videoGen),});}));@@ -1048,13 +1056,10 @@ 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,+ // When the worker dequeued this job. A page that reloads mid-render needs+ // it to keep showing a truthful elapsed clock; without it the render+ // status card would restart from zero and read as a fresh start (#5872).+ startedAt: job.startedAt || null,params: pickJobParams(job),},});diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 59638b7925..bc26da4a6a 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -406,6 +406,23 @@ describe('videoGen routes', () => {}});+ // #5872 — the page warns the user BEFORE the screen goes dark, which it can+ // only do if the server says whether THIS install will actually sleep it+ // (macOS, and the user hasn't opted out). Warning a user who opted out+ // would teach them to ignore the warning that matters.+ it('reports whether a render will sleep the display, honoring the opt-out', async () => {+ const { getSettings } = await import('../services/settings.js');+ const dflt = await request(app).get('/api/video-gen/status');+ expect(typeof dflt.body.displaySleepOnRender).toBe('boolean');++ getSettings.mockResolvedValueOnce({+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ videoGen: { displaySleep: false },+ });+ const optedOut = await request(app).get('/api/video-gen/status');+ expect(optedOut.body.displaySleepOnRender).toBe(false);+ });+it('passes each model entry through with its registry disclosure block', async () => {videoGenService.listVideoModels.mockReturnValueOnce([{diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 271721c366..e954fef0ab 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -791,22 +791,9 @@ function synthesizeMessage(e, kind) {// Two finite positive edges, or nothing. A runner that reports no geometry —// or a heartbeat-shaped frame with a zero/NaN edge — must produce NO geometry// rather than a ratio the client would have to defend against.-const renderGeometryOf = (e) => {- const width = Number(e.width);- const height = Number(e.height);- if (!Number.isFinite(width) || width <= 0) return null;- if (!Number.isFinite(height) || height <= 0) return null;- return { width, height };-};-function makeGenDispatcher(emitter, job, handlers) {const onProgress = (e) => {if (e.generationId !== job.id) return;- // A CHAINED video render never emits `started` under the queue's job id —- // `started` is per-chunk, under ids only the orchestrator knows — so its- // resolved geometry rides the outer progress frames instead (#4588).- const chainedGeometry = renderGeometryOf(e);- if (chainedGeometry) handlers.renderMeta?.(chainedGeometry);const hasProgress = typeof e.progress === 'number' && Number.isFinite(e.progress);const hasCurrentImage = typeof e.currentImage === 'string' && e.currentImage.length > 0;const message = e.message !== undefined ? e.message : synthesizeMessage(e, job.kind);@@ -818,17 +805,23 @@ function makeGenDispatcher(emitter, job, handlers) {// wall-clock estimate for the whole render. Presence-guarded on purpose —// an install with no matching measurement emits no key at all, which the// UI must show as "unknown" rather than as a zero countdown.- const addStepFields = (payload) => {+ // `phase` (video gen, #5872) is the runner's own STAGE: id — 'load-model',+ // 'encode-prompt', 'sampling', 'mux', … The client turns it into a named+ // render step so a runner that reports no numeric progress for minutes+ // (FastH3 streams an ~89 GB DiT before its first denoise step) still says+ // WHAT it is doing rather than showing a motionless 0%.+ const addFrameFields = (payload) => {if (typeof e.step === 'number') payload.step = e.step;if (typeof e.totalSteps === 'number') payload.totalSteps = e.totalSteps;if (typeof e.loss === 'number') payload.loss = e.loss;if (typeof e.etaMs === 'number') payload.etaMs = e.etaMs;+ if (typeof e.phase === 'string' && e.phase) payload.phase = e.phase;};if (hasProgress) {const payload = { type: 'progress', progress: e.progress };if (hasCurrentImage) payload.currentImage = e.currentImage;if (message !== undefined) payload.message = message;- addStepFields(payload);+ addFrameFields(payload);handlers.progress(payload);return;}@@ -837,43 +830,31 @@ function makeGenDispatcher(emitter, job, handlers) {// existing consumers can keep their progress-bar value untouched.const payload = { type: 'preview', currentImage: e.currentImage };if (message !== undefined) payload.message = message;- addStepFields(payload);+ addFrameFields(payload);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).- const onStarted = (e) => {- if (e.generationId !== job.id) return;- const geometry = renderGeometryOf(e);- if (geometry) handlers.renderMeta?.(geometry);- };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// can call `videoGenEvents.emit('status', { generationId, message })`.if (e.generationId !== job.id) return;if (typeof e.message === 'string' && e.message.length > 0) {- handlers.progress({ type: 'status', message: e.message });+ const payload = { type: 'status', message: e.message };+ if (typeof e.phase === 'string' && e.phase) payload.phase = e.phase;+ handlers.progress(payload);}};const onCompleted = (e) => { if (e.generationId === job.id) handlers.completed(e); };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);@@ -988,18 +969,6 @@ 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; })@@ -1341,25 +1310,10 @@ function ensureSseEntry(jobId) {// 3. Terminal job after the grace window — entry is gone; we synthesize a// one-shot terminal frame from the archived job and end the stream so// a late client doesn't hang on an empty SSE stream forever.-// A client attaching to a live job also needs the render's resolved geometry-// (#4588), and it cannot come from the replay slot: that slot holds exactly one-// frame and must hold the one that says what the run is DOING. The geometry is-// announced once, very early — routinely before the submitting page's-// EventSource has even opened — so replay it from the job to each client as it-// attaches instead of retaining it on the wire.-const replayRenderMeta = (job, res) => {- if (!job.render) return;- res.write(`data: ${JSON.stringify({ type: 'render-meta', ...job.render })}\n\n`);-};-export function attachSseClient(jobId, res) {const job = findJob(jobId);if (!job) return false;- if (sseJobs.has(jobId)) {- const attached = attachSse(sseJobs, jobId, res);- if (attached) replayRenderMeta(job, res);- return attached;- }+ if (sseJobs.has(jobId)) return attachSse(sseJobs, jobId, res);// No SSE entry but the job is still live (queued/running) — the entry was// dropped or never created (e.g. crash recovery). Create one on the fly// and attach so the client receives subsequent progress/terminal events@@ -1372,9 +1326,7 @@ export function attachSseClient(jobId, res) {? { type: 'queued', position: job.position }: { type: 'started', kind: job.kind };broadcastSse(entry, heartbeat);- const attached = attachSse(sseJobs, jobId, res);- if (attached) replayRenderMeta(job, res);- return attached;+ return attachSse(sseJobs, jobId, res);}// Terminal job whose SSE entry was already cleaned up. Synthesize the// expected terminal payload from the archived state and end immediately.diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex b1afe03f97..21cad4178c 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -507,78 +507,39 @@ 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 } });+ it('forwards the runner phase on status and progress frames (#5872)', async () => {+ // A local video render is silent for minutes at a time — FastH3 streams an+ // ~89 GB INT4 DiT before its first denoise step and reports no numeric+ // progress while it does. The phase id is the ONLY thing that lets the page+ // say what it is doing, so it has to survive the dispatcher on both frame+ // types. Presence-guarded: a frame that carries no phase must not stamp one.+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'what are you doing' } });await waitFor(() => stubs.generateVideo.mock.calls.length === 1);await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'running');const frames = [];- const makeRes = (sink) => ({+ expect(mediaJobQueue.attachSseClient(job.jobId, {writeHead: () => {},write: (msg) => {for (const line of msg.split('\n')) {- if (line.startsWith('data: ')) sink.push(JSON.parse(line.slice(6)));+ if (line.startsWith('data: ')) frames.push(JSON.parse(line.slice(6)));}},end: () => {},req: { on: () => {} },+ })).toBe(true);++ videoGenEvents.emit('status', {+ generationId: job.jobId, message: 'Loading the FastVideo pipeline · 2m45s elapsed', phase: 'load-pipeline',});- 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'));-- // A client that attaches AFTER the geometry was announced (the normal case- // — the geometry lands before the submitting page's EventSource is even- // open) still gets it, replayed from the job rather than from the single- // retained slot, which keeps holding the frame that says what the run is- // doing.- const replayed = [];- expect(mediaJobQueue.attachSseClient(job.jobId, makeRes(replayed))).toBe(true);- expect(replayed).toHaveLength(2);- expect(replayed[0]).toMatchObject({ type: 'progress', progress: 0.25 });- expect(replayed[1]).toEqual({ type: 'render-meta', width: 704, height: 480 });-- // A chained render emits `started` per CHUNK, under ids the queue ignores,- // so its geometry rides the outer progress frames instead — same handler,- // same dedupe, no second frame for an unchanged geometry.- videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.3, width: 704, height: 480 });- videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.4, width: 1280, height: 704 });- await waitFor(() => frames.filter((f) => f.type === 'render-meta').length === 2);- expect(frames.filter((f) => f.type === 'render-meta').at(-1))- .toEqual({ type: 'render-meta', width: 1280, height: 704 });- expect(mediaJobQueue.getJob(job.jobId).render).toEqual({ width: 1280, height: 704 });-- // Restore the original geometry for the persistence assertion below.- videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.5, width: 704, height: 480 });- await waitFor(() => mediaJobQueue.getJob(job.jobId).render?.width === 704);-- // Survives a server restart too — the geometry is part of the persisted- // projection, not just in-memory state.- await waitFor(() => {- const data = JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf-8'));- return data.jobs.find((j) => j.id === job.jobId)?.render?.width === 704;- });+ await waitFor(() => frames.some((f) => f.type === 'status' && f.phase === 'load-pipeline'));++ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.25, phase: 'sampling' });+ await waitFor(() => frames.some((f) => f.type === 'progress' && f.phase === 'sampling'));++ videoGenEvents.emit('status', { generationId: job.jobId, message: 'no phase here' });+ await waitFor(() => frames.some((f) => f.message === 'no phase here'));+ expect('phase' in frames.find((f) => f.message === 'no phase here')).toBe(false);videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.jsindex 53ca0848c3..e6e525507a 100644--- a/server/services/mediaJobQueue/sanitizeJob.js+++ b/server/services/mediaJobQueue/sanitizeJob.js@@ -98,12 +98,6 @@ 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: safeResult,diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.jsindex df601de3ee..2d37e79979 100644--- a/server/services/mediaJobQueue/sanitizeJob.test.js+++ b/server/services/mediaJobQueue/sanitizeJob.test.js@@ -72,24 +72,6 @@ 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',diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex e0d307f7e4..f58386beae 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -51,6 +51,7 @@ import {routesToWindowsHelper,byovRuntimeExpectedRevision,isByovRuntimeCurrent,+ runtimeUsesMlx,} from './runtimes.js';import { getSettings } from '../settings.js';import { loadHistory, saveHistory, mutateVideoHistory, getHistoryItem } from './history.js';@@ -132,6 +133,16 @@ const decorateVideoModel = (m) => (m ? {// (lib/videoDraftDecoders.js). Empty for every model that declares no draft// decoder, so the client renders no control instead of a one-entry select.draftDecodeOptions: publicVideoDraftDecodeOptions(m),+ // Does a render on this model put the display to sleep? An MLX render must+ // (spawnWatch.js sleeps it so WindowServer stops contending with Metal and+ // tripping the Apple GPU watchdog), and a user who is not told that reads the+ // dark screen as a crash and wakes it — which is the failure the sleep exists+ // to prevent. Decorated here rather than derived client-side so the warning+ // and the behaviour can never disagree about which runtimes do it. Whether it+ // will ACTUALLY happen also depends on the platform and the user's opt-out,+ // which are per-install facts reported once on /status as+ // `displaySleepOnRender`.+ sleepsDisplayDuringRender: runtimeUsesMlx(m.runtime),} : m);export const resolveVideoModel = (modelId) =>diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsindex e3a04d5eee..5052631e73 100644--- a/server/services/videoGen/generateVideoHelpers.js+++ b/server/services/videoGen/generateVideoHelpers.js@@ -113,6 +113,16 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {// a missed `started` event. Omitted entirely when there is no estimate — an// absent key, never `etaMs: 0`, which a UI would render as "done".const etaField = () => (Number.isFinite(job?.etaMs) ? { etaMs: job.etaMs } : {});+ // Every status line goes out twice: on the videoGen job's own SSE stream, and+ // on videoGenEvents for the mediaJobQueue dispatcher to forward to the page's+ // stream. Both carry the phase the last STAGE: marker put us in — the client+ // maps it to a named render step ("Loading model" / "Rendering" / …), and a+ // bare STATUS line is often the ONLY thing a runner emits for minutes at a+ // time, so without the phase it can only be shown as undifferentiated text.+ const emitStatus = (message, extra = {}) => {+ broadcastSse(job, { type: 'status', message, phase: currentPhase, ...extra });+ videoGenEvents.emit('status', { generationId: jobId, message, phase: currentPhase, ...extra });+ };return (raw) => {const line = raw.trim();@@ -177,13 +187,11 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {// Heartbeat for the queue's idle watchdog (see imageGen/local.js).videoGenEvents.emit('activity', { generationId: jobId });if (line.startsWith('STATUS:')) {- const message = line.slice(7);- broadcastSse(job, { type: 'status', message });- // Mirror status to videoGenEvents so the mediaJobQueue SSE dispatcher- // forwards it to the client. Without this, only STAGE: progress- // reaches the UI and long pre-render phases ("Loading pipeline…",- // "Generating I2V…") display nothing.- videoGenEvents.emit('status', { generationId: jobId, message });+ // Mirrored to videoGenEvents by emitStatus so the mediaJobQueue SSE+ // dispatcher forwards it to the client. Without that, only STAGE:+ // progress reaches the UI and long pre-render phases ("Loading+ // pipeline…", "Generating I2V…") display nothing.+ emitStatus(line.slice(7));return true;}if (line.startsWith('STAGE:')) {@@ -213,11 +221,8 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {const tag = (parts[2] || '').toLowerCase();if (tag === 'heartbeat') {// Surface as a status message; the activity emit above already- // resets the queue watchdog. Mirror to videoGenEvents so the- // mediaJobQueue SSE dispatcher forwards it to the client.- const message = `${parts[1]}: heartbeat ${parts[3] || ''}`;- broadcastSse(job, { type: 'status', message });- videoGenEvents.emit('status', { generationId: jobId, message });+ // resets the queue watchdog.+ emitStatus(`${parts[1]}: heartbeat ${parts[3] || ''}`);return true;}if (tag === 'step') {@@ -229,15 +234,12 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {// it to the client instead of falling back to the synthesized// "Rendering step X/Y" (which hides useful labels like "Loading// model" emitted at stage boundaries).- videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total, message: label || undefined, ...etaField() });+ videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total, message: label || undefined, phase: currentPhase, ...etaField() });return true;}// Bare phase marker (e.g. STAGE:load-pipeline, STAGE:from-pretrained) —// surface as a status line. No progress %, no division-by-undefined.- // Mirror to videoGenEvents for client forwarding.- const message = parts.slice(1).join(':');- broadcastSse(job, { type: 'status', message });- videoGenEvents.emit('status', { generationId: jobId, message });+ emitStatus(parts.slice(1).join(':'));return true;}if (line.startsWith('DOWNLOAD:')) {@@ -245,13 +247,11 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {currentPhase = 'download';const rawText = line.slice(9);const byteInfo = parseByteProgress(rawText);- const message = formatDownloadMessage(rawText, byteInfo);- // Include downloadedBytes/totalBytes fields for clients that want numeric progress- const frame = { type: 'status', message, phase: currentPhase };- if (byteInfo.downloaded != null) frame.downloadedBytes = byteInfo.downloaded;- if (byteInfo.total != null) frame.totalBytes = byteInfo.total;- broadcastSse(job, frame);- videoGenEvents.emit('status', { generationId: jobId, message, ...byteInfo });+ // Include downloadedBytes/totalBytes for clients that want numeric progress.+ const bytes = {};+ if (byteInfo.downloaded != null) bytes.downloadedBytes = byteInfo.downloaded;+ if (byteInfo.total != null) bytes.totalBytes = byteInfo.total;+ emitStatus(formatDownloadMessage(rawText, byteInfo), bytes);return true;}const m = line.match(/(\d+)%\|/);@@ -273,7 +273,7 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {// (`60%|██████ | 6/10 [00:30<00:20, ...]`) is terminal noise that// would clobber the last meaningful STATUS/STAGE line on every// percent update. Client renders the percentage separately.- videoGenEvents.emit('progress', { generationId: jobId, progress: pct, ...etaField() });+ videoGenEvents.emit('progress', { generationId: jobId, progress: pct, phase: currentPhase, ...etaField() });return true;}return false;diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.jsindex 25ec1b817e..aca564588d 100644--- a/server/services/videoGen/generateVideoHelpers.test.js+++ b/server/services/videoGen/generateVideoHelpers.test.js@@ -142,7 +142,7 @@ describe('makeVideoGenLineHandler', () => {it('still surfaces the prompt-encode markers to the client as status frames', () => {handle('STAGE:encode-prompt');- expect(eventsOfType('status')).toContainEqual({ generationId: 'job-12345678', message: 'encode-prompt' });+ expect(eventsOfType('status')).toContainEqual({ generationId: 'job-12345678', message: 'encode-prompt', phase: 'encode-prompt' });});it('repeats the job ETA on every progress frame, and omits it when absent (#3801)', () => {@@ -170,8 +170,8 @@ describe('makeVideoGenLineHandler', () => {it('STATUS: → status SSE frame + status event, and an activity heartbeat', () => {expect(handle('STATUS:Generating I2V…')).toBe(true);- expect(sseFrames()).toContainEqual({ type: 'status', message: 'Generating I2V…' });- expect(eventsOfType('status')).toContainEqual({ generationId: 'job-12345678', message: 'Generating I2V…' });+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'Generating I2V…', phase: 'starting' });+ expect(eventsOfType('status')).toContainEqual({ generationId: 'job-12345678', message: 'Generating I2V…', phase: 'starting' });expect(eventsOfType('activity')).toContainEqual({ generationId: 'job-12345678' });});@@ -179,14 +179,14 @@ describe('makeVideoGenLineHandler', () => {expect(handle('STAGE:render:step:6:10:Sampling latents')).toBe(true);expect(sseFrames()).toContainEqual({ type: 'progress', progress: 0.6, message: 'Sampling latents', phase: 'render' });expect(eventsOfType('progress')).toContainEqual({- generationId: 'job-12345678', progress: 0.6, step: 6, totalSteps: 10, message: 'Sampling latents',+ generationId: 'job-12345678', progress: 0.6, step: 6, totalSteps: 10, message: 'Sampling latents', phase: 'render',});});it('STAGE: heartbeat does NOT become bogus progress (regression: 20s → 2000%)', () => {expect(handle('STAGE:download-clip:heartbeat:20s')).toBe(true);// Heartbeat is a status line, never a progress frame.- expect(sseFrames()).toContainEqual({ type: 'status', message: 'download-clip: heartbeat 20s' });+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'download-clip: heartbeat 20s', phase: 'download-clip' });expect(sseFrames().some((f) => f.type === 'progress')).toBe(false);});@@ -197,7 +197,7 @@ describe('makeVideoGenLineHandler', () => {it('bare STAGE: phase marker → status (no division-by-undefined progress)', () => {expect(handle('STAGE:load-pipeline')).toBe(true);- expect(sseFrames()).toContainEqual({ type: 'status', message: 'load-pipeline' });+ expect(sseFrames()).toContainEqual({ type: 'status', message: 'load-pipeline', phase: 'load-pipeline' });expect(sseFrames().some((f) => f.type === 'progress')).toBe(false);});@@ -218,7 +218,7 @@ describe('makeVideoGenLineHandler', () => {expect(handle('60%|██████ | 6/10 [00:30<00:20, 1.2s/it]')).toBe(true);expect(sseFrames()).toContainEqual({ type: 'progress', progress: 0.6, message: '60%|██████ | 6/10 [00:30<00:20, 1.2s/it]', phase: 'starting' });// The mediaJobQueue dispatcher emit must NOT carry the raw bar as message.- expect(eventsOfType('progress')).toContainEqual({ generationId: 'job-12345678', progress: 0.6 });+ expect(eventsOfType('progress')).toContainEqual({ generationId: 'job-12345678', progress: 0.6, phase: 'starting' });});it('tqdm bar with byte sizes during download → formatted GB message', () => {