Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: estimate local video render time from measured render history (#3801)

[._.]/ Adam Eivy9c8d611d2b2b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index acad842c5a..3e2d8200b6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -90,3 +90,4 @@
- **Arc verification no longer reports a phantom "no pilot or finale" on a volume that has both.** The check that flags arc-role imbalance reads each episode's `arcRole`, but the plan snapshot handed to the verifier never included that field — so it saw twelve episodes with no roles at all and reported the imbalance on every single pass, on every series, no matter how the volume was actually laid out. On its own that was a stray low-severity finding. What made it expensive is that the foundation gate's structure repair reverts its whole rewrite whenever verification comes back with *any* blocker left: the phantom finding could never be closed, so a run whose real contradictions had all been fixed still rolled the repair back and paused for human review, reporting the correct fixes as a failed attempt. (Observed on a series that paused with "structure repair left 5 arc-verification blocker(s)", one of which was this.) The snapshot now carries `arcRole` — as an explicit `null` when unset, so "no role" stays distinguishable from a dropped field — which also means the auto-resolver can finally see the roles it is being asked to fix instead of assigning them blind.
- **A URL that doesn't match a page now says so instead of quietly depositing you on the Dashboard.** Every unmatched route — a stale bookmark, a typo, or a half-remembered path like `/annotate` (the annotator actually lives at `/media/annotate`) — hit a blanket redirect to `/`, so the user saw the page-loading spinner, then the Dashboard's skeleton widgets, then the Dashboard: indistinguishable from the app losing their navigation, with no account of what happened. Unknown routes now render a 404 page that names the path that didn't match and offers Go back, Dashboard, and a reminder that ⌘K searches every page by name. `/annotate` and `/annotate/:mediaKey` are redirected to their real `/media/annotate` home rather than being swallowed, and the annotator's own keyless state stopped reading like a loading screen: it now distinguishes "nothing selected" from "that media is no longer available" and offers **Choose media** and **Blank canvas** — the latter being the first way to start a free-standing sketch from the UI at all.
- **A character repair that objectively filled the blank cast fields is no longer thrown away because the judge scored it a tie.** The foundation gate holds each repair provisional until an independent re-judge proves it helped the dimension it was asked to fix, and reverts it otherwise — the right rule for editorial work that can only be assessed by reading it. But the character dimension's core complaint is frequently a countable one ("every core character has blank physicalDescription, visualNotes, silhouetteNotes, visualIdentity and colorPalette"), and answering it is a countable act. On the observed run the repair authored all five visual fields for all five leads — roughly five minutes of a max-effort ensemble pass — the judge came back holding character at the same 5 while unrelated worldbuilding drifted 8 → 7, and the gate reverted every sheet and paused the run for review with the cast blank again. The gate now takes a second, LLM-free opinion before it reverts a *tied* character repair: it counts the blank framework and visual fields across the exact cast the repair is allowed to write (the series roster, minus locked members) before and after, and keeps the work when that count went down. A repair whose target regressed is still reverted, every other dimension is unaffected, and a repair that changed nothing measurable is still rejected — what changed is that a fact on disk now outranks a tied score.
+- **A local video render now tells you how long it has left, once your machine has rendered something comparable.** Local renders run 15–40+ minutes and the only progress the UI could show was a step counter — "20%" on a job that might finish in four minutes or forty, with no way to tell which. Each completed render now records its wall-clock time alongside the shape it rendered (model, resolution, frames, steps), and a new job estimates itself from that history: a run of the same shape uses the median of your own measured runs outright, a different shape is placed on a least-squares fit of cost against pixels × frames × steps, and the fit's intercept — the fixed per-render cost of loading weights and decoding — is what lets a chained multi-chunk render be estimated as N renders rather than one long one. The estimate rides the render's started/progress events through to the client, where the progress bar reads "20% · ~18m 30s left". An install that has never measured a comparable render reports no estimate at all rather than a fabricated one, and the progress bar simply shows the percentage as before.
diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsx
index aafd2d19c5..451fd7ff24 100644
--- a/client/src/components/pipeline/MediaJobThumb.jsx
+++ b/client/src/components/pipeline/MediaJobThumb.jsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { AlertCircle, Ban, Loader2 } from 'lucide-react';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import { formatDurationMs } from '../../utils/formatters';
/**
* Small thumbnail strip for a single mediaJobQueue job. Used by the
@@ -33,7 +34,7 @@ export default function MediaJobThumb({
// a poster, so keep the live subscription path for video.
const hasStaticFallback = !!fallbackFilename && kind === 'image';
const liveJobId = hasStaticFallback ? null : jobId;
- const { status, progress, step, totalSteps, currentImage, filename, error } =
+ const { status, progress, step, totalSteps, currentImage, filename, error, etaMs } =
useMediaJobProgress(liveJobId, { kind });
const [missing, setMissing] = useState(false);
const [attempt, setAttempt] = useState(0);
@@ -175,6 +176,13 @@ export default function MediaJobThumb({
// otherwise a spinner with step counter. The base64 currentImage is the
// freshly-decoded latent frame from the diffusion loop.
const pct = totalSteps ? Math.round((step / totalSteps) * 100) : Math.round((progress || 0) * 100);
+ // Remaining wall-clock, from the server's history-calibrated estimate for the
+ // whole render (#3801) scaled by how much is left. Absent whenever the server
+ // sent no estimate — a 15–40 minute render showing only "20%" is exactly the
+ // case this exists for, but a fabricated countdown would be worse than none.
+ const remainingMs = Number.isFinite(etaMs) && etaMs > 0
+ ? Math.max(0, Math.round(etaMs * (1 - Math.min(1, Math.max(0, pct / 100)))))
+ : null;
return (
<div className={`relative ${isFill ? 'w-full min-h-[200px]' : dims} bg-port-bg rounded overflow-hidden border border-port-border`}>
{currentImage ? (
@@ -190,7 +198,7 @@ export default function MediaJobThumb({
)}
{pct > 0 && (
<div className="absolute bottom-0 left-0 right-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">
- {pct}%
+ {pct}%{remainingMs != null ? ` · ~${formatDurationMs(remainingMs)} left` : ''}
</div>
)}
</div>
diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.js
index 650789b7f8..c0bc23551c 100644
--- a/client/src/hooks/useMediaJobProgress.js
+++ b/client/src/hooks/useMediaJobProgress.js
@@ -15,9 +15,14 @@ import useMounted from './useMounted';
* {
* status: 'unknown' | 'queued' | 'running' | 'completed' | 'failed' | 'canceled',
* progress, statusMsg, step, totalSteps, currentImage,
- * filename, path, error,
+ * filename, path, error, etaMs,
* }
*
+ * `etaMs` is the server's history-calibrated wall-clock estimate for the whole
+ * render (#3801) — video gen only, and only once that install has measured a
+ * comparable render. It stays `null` when the server sent no estimate, which
+ * consumers must render as "unknown" rather than as a finished countdown.
+ *
* Initial state is hydrated from GET /api/media-jobs/:id so navigating
* back to a page mid-render picks up the in-flight job's snapshot
* instead of showing an empty preview until the next event lands.
@@ -29,6 +34,7 @@ const INITIAL_STATE = Object.freeze({
step: 0,
totalSteps: null,
currentImage: null,
+ etaMs: null,
filename: null,
path: null,
error: null,
@@ -78,8 +84,12 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
if (data.generationId !== jobId) return;
setState((prev) => {
const totalSteps = data.totalSteps ?? prev.totalSteps;
- if (prev.status === 'running' && totalSteps === prev.totalSteps) return prev;
- return { ...prev, status: 'running', totalSteps };
+ // `etaMs: null` on the wire is the server saying "no estimate for this
+ // shape" — an intentional value, not an absent key, so it must clear a
+ // stale estimate rather than fall through to `prev`.
+ const etaMs = data.etaMs !== undefined ? data.etaMs : prev.etaMs;
+ if (prev.status === 'running' && totalSteps === prev.totalSteps && etaMs === prev.etaMs) return prev;
+ return { ...prev, status: 'running', totalSteps, etaMs };
});
};
// Diffusion runners throttle `currentImage` but still emit identical
@@ -97,6 +107,7 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
step: data.step ?? prev.step,
totalSteps: data.totalSteps ?? prev.totalSteps,
currentImage: data.currentImage ?? prev.currentImage,
+ etaMs: data.etaMs !== undefined ? data.etaMs : prev.etaMs,
};
if (
next.status === prev.status
@@ -105,6 +116,7 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
&& next.step === prev.step
&& next.totalSteps === prev.totalSteps
&& next.currentImage === prev.currentImage
+ && next.etaMs === prev.etaMs
) return prev;
return next;
});
diff --git a/client/src/hooks/useMediaJobProgress.test.js b/client/src/hooks/useMediaJobProgress.test.js
new file mode 100644
index 0000000000..81d0236420
--- /dev/null
+++ b/client/src/hooks/useMediaJobProgress.test.js
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+
+const handlers = new Map();
+vi.mock('../services/socket', () => ({
+ default: {
+ on: (event, fn) => { handlers.set(event, fn); },
+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },
+ },
+}));
+vi.mock('../services/apiMediaJobs', () => ({
+ getMediaJob: vi.fn(async () => ({ status: 'running' })),
+}));
+
+import useMediaJobProgress from './useMediaJobProgress';
+
+const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });
+
+describe('useMediaJobProgress — render ETA (#3801)', () => {
+ beforeEach(() => { handlers.clear(); });
+
+ it('starts with no estimate', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));
+ // Settle the mount-time GET /api/media-jobs/:id hydration.
+ await act(async () => {});
+ expect(result.current.etaMs).toBeNull();
+ });
+
+ it('picks up the estimate from the started event and repeats it on progress', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));
+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));
+ fire('video-gen:started', { generationId: 'job-1', totalSteps: 30, etaMs: 1_800_000 });
+ expect(result.current.etaMs).toBe(1_800_000);
+ fire('video-gen:progress', { generationId: 'job-1', progress: 0.5, etaMs: 1_800_000 });
+ expect(result.current.etaMs).toBe(1_800_000);
+ });
+
+ it('keeps the last estimate when a progress frame omits the key', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));
+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));
+ fire('video-gen:started', { generationId: 'job-1', etaMs: 600_000 });
+ fire('video-gen:progress', { generationId: 'job-1', progress: 0.2 });
+ expect(result.current.etaMs).toBe(600_000);
+ });
+
+ it('treats an explicit null estimate as "unknown", not as a stale value to keep', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));
+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));
+ fire('video-gen:started', { generationId: 'job-1', etaMs: 600_000 });
+ fire('video-gen:started', { generationId: 'job-1', etaMs: null });
+ expect(result.current.etaMs).toBeNull();
+ });
+
+ it('ignores events for a different job', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));
+ await waitFor(() => expect(handlers.has('video-gen:started')).toBe(true));
+ fire('video-gen:started', { generationId: 'job-2', etaMs: 600_000 });
+ expect(result.current.etaMs).toBeNull();
+ });
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index d20a638204..fbfdeb0267 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -593,10 +593,15 @@ function makeGenDispatcher(emitter, job, handlers) {
// them (LoRA training does) so the client plots a loss curve and keys
// sample thumbnails by step instead of re-parsing the message string.
// Additive + presence-guarded — image/video gen omit them, unaffected.
+ // `etaMs` (video gen, #3801) rides along the same way: a history-calibrated
+ // 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) => {
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 (hasProgress) {
const payload = { type: 'progress', progress: e.progress };
diff --git a/server/services/videoGen/eta.js b/server/services/videoGen/eta.js
new file mode 100644
index 0000000000..6720f73bd9
--- /dev/null
+++ b/server/services/videoGen/eta.js
@@ -0,0 +1,163 @@
+/**
+ * Video Gen — history-calibrated render ETA.
+ *
+ * Local video renders run 15–40+ minutes. The child emits step progress but no
+ * wall-clock estimate, so the UI can only say "step 7/30" for half an hour.
+ * This module turns the render history into an estimate using nothing but the
+ * install's own measured runs — no hand-tuned constants, no per-chip table.
+ *
+ * The model, in order of preference:
+ *
+ * 1. **Measured** — records of the *same shape* (same model + width × height ×
+ * numFrames × steps) already exist. A real measurement always beats a
+ * model, so the median of those durations is the answer outright.
+ * 2. **Linear fit** — same model, differing shapes. Render cost is very close
+ * to `a · (pixels × frames × steps) + b`: the sampler work scales with the
+ * product, while `b` is the fixed cost paid once per render (weight load,
+ * text encode, VAE decode, mux). Least-squares over the recent same-model
+ * records recovers both. `b` is what makes chained renders estimable —
+ * an N-chunk chain pays it N times, not once.
+ * 3. **Proportional** — too few / too degenerate a sample set to separate the
+ * fixed cost, so fall back to the median ms-per-work-unit with no
+ * intercept.
+ * 4. **No estimate** — nothing usable in history. Returns `null`, an explicit
+ * absent sentinel. Never a fabricated number and never `0`: a caller that
+ * showed "0s remaining" for an unmeasured model would be lying, and a
+ * fresh install has no measurements by definition.
+ *
+ * Everything here is pure — `history` is passed in, never read from disk.
+ */
+
+// Only the most recent N same-model records feed a fit. Older runs drift away
+// from present reality (different runtime build, different thermal envelope,
+// different competing load), and an unbounded window would let a year-old
+// sample outvote last week's.
+const RECENT_SAMPLE_LIMIT = 20;
+// Exact-shape matches are the strongest signal, so a much shorter window is
+// enough — and staying short keeps the median responsive to a runtime upgrade
+// that halved render time.
+const EXACT_SAMPLE_LIMIT = 5;
+// A linear fit needs enough spread to separate slope from intercept. Below
+// this it overfits noise and can produce an absurd (even negative) intercept.
+const MIN_FIT_SAMPLES = 3;
+
+/**
+ * Sampler work for one render, in arbitrary but consistent units.
+ * Returns null when any dimension is missing or non-positive — an entry we
+ * can't place on the cost curve must be dropped, not defaulted to zero.
+ */
+export const renderWorkUnits = ({ width, height, numFrames, steps }) => {
+ const dims = [width, height, numFrames, steps].map(Number);
+ if (dims.some((n) => !Number.isFinite(n) || n <= 0)) return null;
+ return dims.reduce((a, b) => a * b, 1);
+};
+
+const median = (values) => {
+ const sorted = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
+};
+
+const entryTime = (entry) => {
+ const t = Date.parse(entry?.createdAt ?? '');
+ return Number.isFinite(t) ? t : 0;
+};
+
+/**
+ * Timed, shape-complete history records for one model, newest first.
+ * `renderMs` is stamped by finalizeGeneratedVideo; entries that predate it
+ * (and non-render entries like downloaded videos) simply have no measurement
+ * and are excluded rather than guessed at.
+ */
+export const timedRenderSamples = (history, modelId) => {
+ if (!Array.isArray(history)) return [];
+ return history
+ .filter((e) => e && e.modelId === modelId && Number.isFinite(Number(e.renderMs)) && Number(e.renderMs) > 0)
+ .map((e) => ({
+ workUnits: renderWorkUnits(e),
+ durationMs: Number(e.renderMs),
+ width: Number(e.width),
+ height: Number(e.height),
+ numFrames: Number(e.numFrames),
+ steps: Number(e.steps),
+ at: entryTime(e),
+ }))
+ .filter((s) => s.workUnits != null)
+ .sort((a, b) => b.at - a.at);
+};
+
+/**
+ * Least-squares `ms = perUnitMs · work + fixedMs` over the samples.
+ * Returns null when the samples can't support a fit (too few, all one shape,
+ * or a fit whose slope came out non-positive — which means the sample set is
+ * noise, not a cost curve). A negative intercept is clamped to 0 rather than
+ * discarded: the slope is still informative, and a negative fixed cost would
+ * make short renders estimate below zero.
+ */
+export const fitRenderCost = (samples) => {
+ if (!Array.isArray(samples) || samples.length < MIN_FIT_SAMPLES) return null;
+ const n = samples.length;
+ const sumX = samples.reduce((a, s) => a + s.workUnits, 0);
+ const sumY = samples.reduce((a, s) => a + s.durationMs, 0);
+ const sumXY = samples.reduce((a, s) => a + s.workUnits * s.durationMs, 0);
+ const sumXX = samples.reduce((a, s) => a + s.workUnits * s.workUnits, 0);
+ const denom = n * sumXX - sumX * sumX;
+ // Zero denominator = every sample has the same work units, so the fit is a
+ // vertical line with no recoverable slope.
+ if (denom === 0) return null;
+ const perUnitMs = (n * sumXY - sumX * sumY) / denom;
+ if (!Number.isFinite(perUnitMs) || perUnitMs <= 0) return null;
+ const fixedMs = Math.max(0, (sumY - perUnitMs * sumX) / n);
+ return { perUnitMs, fixedMs };
+};
+
+/**
+ * Estimate wall-clock render time for a job about to start.
+ *
+ * @param {object} ctx
+ * @param {Array} ctx.history - the video render history (newest-first list)
+ * @param {string} ctx.modelId
+ * @param {number} ctx.width
+ * @param {number} ctx.height
+ * @param {number} ctx.numFrames - frames rendered PER CHUNK
+ * @param {number} ctx.steps
+ * @param {number} [ctx.chunks=1] - chained-render chunk count. Each chunk is a
+ * full render of its own and pays the fixed per-render cost again, so the
+ * chain estimate is `chunks × per-chunk estimate` — not a single render
+ * scaled by total frames.
+ * @returns {{ etaMs: number, perChunkMs: number, chunks: number, basis: 'measured'|'linear'|'proportional', sampleCount: number } | null}
+ * null when history holds no usable measurement for this model.
+ */
+export const estimateRenderMs = ({ history, modelId, width, height, numFrames, steps, chunks = 1 }) => {
+ const workUnits = renderWorkUnits({ width, height, numFrames, steps });
+ if (workUnits == null) return null;
+ const chunkCount = Number.isFinite(Number(chunks)) && Number(chunks) > 0 ? Math.floor(Number(chunks)) : 1;
+ const samples = timedRenderSamples(history, modelId);
+ if (!samples.length) return null;
+
+ const finish = (perChunkMs, basis, sampleCount) => ({
+ etaMs: Math.round(perChunkMs * chunkCount),
+ perChunkMs: Math.round(perChunkMs),
+ chunks: chunkCount,
+ basis,
+ sampleCount,
+ });
+
+ // 1. A real measurement of this exact shape overrides the model.
+ const exact = samples
+ .filter((s) => s.width === Number(width) && s.height === Number(height)
+ && s.numFrames === Number(numFrames) && s.steps === Number(steps))
+ .slice(0, EXACT_SAMPLE_LIMIT);
+ if (exact.length) return finish(median(exact.map((s) => s.durationMs)), 'measured', exact.length);
+
+ const recent = samples.slice(0, RECENT_SAMPLE_LIMIT);
+
+ // 2. Linear fit — recovers the per-chunk fixed cost along with the slope.
+ const fit = fitRenderCost(recent);
+ if (fit) return finish(fit.perUnitMs * workUnits + fit.fixedMs, 'linear', recent.length);
+
+ // 3. Proportional — median rate, no separable fixed cost.
+ const rate = median(recent.map((s) => s.durationMs / s.workUnits));
+ if (!Number.isFinite(rate) || rate <= 0) return null;
+ return finish(rate * workUnits, 'proportional', recent.length);
+};
diff --git a/server/services/videoGen/eta.test.js b/server/services/videoGen/eta.test.js
new file mode 100644
index 0000000000..df98701c7b
--- /dev/null
+++ b/server/services/videoGen/eta.test.js
@@ -0,0 +1,158 @@
+import { describe, it, expect } from 'vitest';
+import { renderWorkUnits, timedRenderSamples, fitRenderCost, estimateRenderMs } from './eta.js';
+
+const MODEL = 'example_video_model';
+
+// A history record as finalizeGeneratedVideo writes it. `at` orders records.
+const rec = ({ modelId = MODEL, width = 768, height = 512, numFrames = 121, steps = 30, renderMs, createdAt = '2026-08-01T00:00:00.000Z' }) =>
+ ({ modelId, width, height, numFrames, steps, renderMs, createdAt });
+
+describe('renderWorkUnits', () => {
+ it('multiplies pixels × frames × steps', () => {
+ expect(renderWorkUnits({ width: 2, height: 3, numFrames: 5, steps: 7 })).toBe(210);
+ });
+
+ it('returns null (absent sentinel) when a dimension is missing or non-positive', () => {
+ expect(renderWorkUnits({ width: 768, height: 512, numFrames: 121 })).toBeNull();
+ expect(renderWorkUnits({ width: 768, height: 512, numFrames: 0, steps: 30 })).toBeNull();
+ expect(renderWorkUnits({ width: 768, height: 512, numFrames: 121, steps: 'many' })).toBeNull();
+ });
+});
+
+describe('timedRenderSamples', () => {
+ it('keeps only timed, shape-complete records for the requested model, newest first', () => {
+ const history = [
+ rec({ renderMs: 1000, createdAt: '2026-08-01T00:00:00.000Z' }),
+ rec({ renderMs: 2000, createdAt: '2026-08-03T00:00:00.000Z' }),
+ rec({ modelId: 'other_model', renderMs: 9999 }),
+ // Legacy record from before render timing was stamped.
+ rec({ renderMs: undefined }),
+ // A downloaded video: no shape at all.
+ { modelId: MODEL, renderMs: 500 },
+ ];
+ const samples = timedRenderSamples(history, MODEL);
+ expect(samples.map((s) => s.durationMs)).toEqual([2000, 1000]);
+ });
+
+ it('drops zero/negative durations rather than treating them as instant renders', () => {
+ expect(timedRenderSamples([rec({ renderMs: 0 }), rec({ renderMs: -5 })], MODEL)).toEqual([]);
+ });
+
+ it('tolerates a missing history file (non-array)', () => {
+ expect(timedRenderSamples(null, MODEL)).toEqual([]);
+ });
+});
+
+describe('fitRenderCost', () => {
+ it('recovers slope and fixed cost from a perfectly linear sample set', () => {
+ // ms = 3·work + 60000
+ const samples = [10, 20, 30].map((w) => ({ workUnits: w, durationMs: 3 * w + 60000 }));
+ const fit = fitRenderCost(samples);
+ expect(fit.perUnitMs).toBeCloseTo(3, 6);
+ expect(fit.fixedMs).toBeCloseTo(60000, 3);
+ });
+
+ it('refuses to fit fewer than three samples', () => {
+ expect(fitRenderCost([{ workUnits: 10, durationMs: 100 }, { workUnits: 20, durationMs: 200 }])).toBeNull();
+ });
+
+ it('refuses to fit when every sample has the same work units', () => {
+ const samples = [1000, 1200, 1400].map((ms) => ({ workUnits: 50, durationMs: ms }));
+ expect(fitRenderCost(samples)).toBeNull();
+ });
+
+ it('rejects a non-positive slope (noise, not a cost curve)', () => {
+ const samples = [{ workUnits: 10, durationMs: 900 }, { workUnits: 20, durationMs: 600 }, { workUnits: 30, durationMs: 300 }];
+ expect(fitRenderCost(samples)).toBeNull();
+ });
+
+ it('clamps a negative intercept to zero instead of estimating below zero', () => {
+ // ms = 5·work − 100 → intercept would be negative.
+ const samples = [40, 60, 80].map((w) => ({ workUnits: w, durationMs: 5 * w - 100 }));
+ const fit = fitRenderCost(samples);
+ expect(fit.perUnitMs).toBeGreaterThan(0);
+ expect(fit.fixedMs).toBe(0);
+ });
+});
+
+describe('estimateRenderMs', () => {
+ const target = { modelId: MODEL, width: 768, height: 512, numFrames: 121, steps: 30 };
+
+ it('returns null when history holds no measurement for this model', () => {
+ expect(estimateRenderMs({ history: [], ...target })).toBeNull();
+ expect(estimateRenderMs({ history: [rec({ modelId: 'other_model', renderMs: 1000 })], ...target })).toBeNull();
+ });
+
+ it('returns null when the requested shape is incomplete', () => {
+ expect(estimateRenderMs({ history: [rec({ renderMs: 1000 })], modelId: MODEL, width: 768, height: 512, steps: 30 })).toBeNull();
+ });
+
+ it('uses the median of exact-shape measurements, overriding the model', () => {
+ const history = [
+ rec({ renderMs: 900_000, createdAt: '2026-08-03T00:00:00.000Z' }),
+ rec({ renderMs: 1_100_000, createdAt: '2026-08-02T00:00:00.000Z' }),
+ rec({ renderMs: 1_000_000, createdAt: '2026-08-01T00:00:00.000Z' }),
+ // Different shape, wildly different cost — must not perturb the exact match.
+ rec({ width: 1024, renderMs: 60_000, createdAt: '2026-08-04T00:00:00.000Z' }),
+ ];
+ const est = estimateRenderMs({ history, ...target });
+ expect(est.basis).toBe('measured');
+ expect(est.etaMs).toBe(1_000_000);
+ expect(est.sampleCount).toBe(3);
+ });
+
+ it('falls back to a linear fit across differing shapes', () => {
+ // ms = 2e-6·work + 120000, over three distinct frame counts.
+ const mk = (numFrames) => {
+ const work = 768 * 512 * numFrames * 30;
+ return rec({ numFrames, renderMs: Math.round(2e-6 * work + 120_000) });
+ };
+ const est = estimateRenderMs({ history: [mk(97), mk(145), mk(193)], ...target });
+ expect(est.basis).toBe('linear');
+ const expected = 2e-6 * (768 * 512 * 121 * 30) + 120_000;
+ expect(est.etaMs).toBeGreaterThan(expected * 0.99);
+ expect(est.etaMs).toBeLessThan(expected * 1.01);
+ });
+
+ it('falls back to a proportional rate when there are too few samples to fit', () => {
+ const halfWork = rec({ numFrames: 61, renderMs: 500_000 });
+ const est = estimateRenderMs({ history: [halfWork], ...target });
+ expect(est.basis).toBe('proportional');
+ // 121/61 of the measured run.
+ expect(est.etaMs).toBe(Math.round(500_000 * (121 / 61)));
+ expect(est.sampleCount).toBe(1);
+ });
+
+ it('multiplies by the chunk count for chained renders, paying the fixed cost per chunk', () => {
+ const mk = (numFrames) => {
+ const work = 768 * 512 * numFrames * 30;
+ return rec({ numFrames, renderMs: Math.round(2e-6 * work + 120_000) });
+ };
+ const history = [mk(97), mk(145), mk(193)];
+ const single = estimateRenderMs({ history, ...target });
+ const chained = estimateRenderMs({ history, ...target, chunks: 4 });
+ expect(chained.chunks).toBe(4);
+ expect(chained.etaMs).toBe(single.perChunkMs * 4);
+ // The fixed per-render cost is paid four times, so a 4-chunk chain costs
+ // strictly more than one render of four times the sampler work would.
+ const quadWork = estimateRenderMs({ history, ...target, numFrames: 121 * 4 });
+ expect(chained.etaMs).toBeGreaterThan(quadWork.etaMs);
+ });
+
+ it('treats a bogus chunk count as a single chunk', () => {
+ const history = [rec({ renderMs: 600_000 })];
+ for (const chunks of [0, -3, NaN, undefined, 'two']) {
+ expect(estimateRenderMs({ history, ...target, chunks }).chunks).toBe(1);
+ }
+ });
+
+ it('prefers recent measurements when the shape repeats many times', () => {
+ // Six exact-shape records; only the newest five feed the median, so the
+ // stale slow outlier at the bottom cannot drag the estimate up.
+ const history = [
+ ...[1, 2, 3, 4, 5].map((d) => rec({ renderMs: 600_000, createdAt: `2026-08-0${d + 1}T00:00:00.000Z` })),
+ rec({ renderMs: 5_000_000, createdAt: '2026-07-01T00:00:00.000Z' }),
+ ];
+ expect(estimateRenderMs({ history, ...target }).etaMs).toBe(600_000);
+ });
+});
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index 58c6113487..bc5553d832 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -98,6 +98,12 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {
// be formatted as "Downloading model · first run · X.X GB" during downloads.
let currentPhase = 'starting';
let isDownloading = false;
+ // History-calibrated wall-clock estimate for this render (#3801), stamped on
+ // the job by generateVideo. Repeated on every progress frame so a client that
+ // subscribed mid-render still learns it, and so the estimate can't be lost to
+ // 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 } : {});
return (raw) => {
const line = raw.trim();
@@ -167,7 +173,7 @@ 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 });
+ videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total, message: label || undefined, ...etaField() });
return true;
}
// Bare phase marker (e.g. STAGE:load-pipeline, STAGE:from-pretrained) —
@@ -211,7 +217,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 });
+ videoGenEvents.emit('progress', { generationId: jobId, progress: pct, ...etaField() });
return true;
}
return false;
@@ -366,8 +372,10 @@ export function isWatchdogSuccess({ completionWatchdogFired, idleStallFired = fa
* @param {object} ctx.meta - the history-entry metadata built up-front
* @param {number} ctx.actualSeed
* @param {(mutator: (h: Array) => Array) => Promise<Array>} ctx.mutateHistory - serialized read-modify-write on the shared history file (mutateVideoHistory)
+ * @param {number} [ctx.startedAtMs] - Date.now() captured just before the child
+ * spawned. Defaults to `job.renderStartedAtMs`, which generateVideo stamps.
*/
-export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory }) {
+export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory, startedAtMs = job?.renderStartedAtMs }) {
job.status = 'complete';
await optimizeForStreaming(outputPath);
const thumbnail = await generateThumbnail(outputPath, jobId);
@@ -380,8 +388,25 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,
// self-documents the exact ltx/mlx/torch + chip + OS stack it rendered on.
// Absent (sentinel) when the runtime didn't emit one — e.g. the bare
// `mlx_video.generate_av` path we don't control.
+ //
+ // Wall-clock render timing (#3801) is what makes a future render estimable:
+ // videoGen/eta.js calibrates its cost model purely from these measurements.
+ // Stamped ONLY when we actually observed the spawn instant — an entry with
+ // no `renderMs` is an explicit absent sentinel that the estimator skips,
+ // which is why the timing spread is conditional rather than defaulted to 0
+ // (a zero-duration sample would drag every estimate toward "instant").
+ // The window measured is spawn → output finalized, i.e. what the user waits
+ // through, including the thumbnail/faststart tail above.
+ const startMs = Number(startedAtMs);
+ const timing = Number.isFinite(startMs) && startMs > 0
+ ? {
+ renderMs: Date.now() - startMs,
+ renderStartedAt: new Date(startMs).toISOString(),
+ renderCompletedAt: new Date().toISOString(),
+ }
+ : {};
await mutateHistory((history) => {
- history.unshift({ ...meta, thumbnail, ...(job.runtime ? { runtime: job.runtime } : {}) });
+ history.unshift({ ...meta, thumbnail, ...timing, ...(job.runtime ? { runtime: job.runtime } : {}) });
return history;
});
console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);
diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.js
index 5cd8ffda36..7d1f1f6506 100644
--- a/server/services/videoGen/generateVideoHelpers.test.js
+++ b/server/services/videoGen/generateVideoHelpers.test.js
@@ -120,6 +120,21 @@ describe('makeVideoGenLineHandler', () => {
const sseFrames = () => sse.mock.calls.map((c) => c[1]);
const eventsOfType = (t) => emitted.filter((e) => e.type === t).map((e) => e.payload);
+ it('repeats the job ETA on every progress frame, and omits it when absent (#3801)', () => {
+ // No estimate on the job → the key must be absent, never etaMs: 0.
+ handle('STAGE:inference:step:5:30:Rendering');
+ handle('60%|██████ | 6/10');
+ expect(eventsOfType('progress').every((p) => !('etaMs' in p))).toBe(true);
+
+ emitted.length = 0;
+ job.etaMs = 1_800_000;
+ handle('STAGE:inference:step:6:30:Rendering');
+ handle('70%|███████ | 7/10');
+ const progress = eventsOfType('progress');
+ expect(progress).toHaveLength(2);
+ expect(progress.every((p) => p.etaMs === 1_800_000)).toBe(true);
+ });
+
it('suppresses blank + python-noise lines without emitting', () => {
expect(handle('')).toBe(true);
expect(handle(' ')).toBe(true);
@@ -266,6 +281,31 @@ describe('finalizeGeneratedVideo runtime persistence', () => {
// No staging/temp path may ride along on a user-facing history record.
expect(JSON.stringify(saved[0])).not.toMatch(/\/tmp\/|uploads/);
});
+
+ it('stamps wall-clock render timing so future renders are estimable (#3801)', async () => {
+ const job = { id: 'job-abcdef12', clients: [], renderStartedAtMs: Date.now() - 5000 };
+ let saved = null;
+ await finalizeGeneratedVideo({
+ ...baseCtx(job),
+ mutateHistory: async (fn) => { saved = await fn([]); return saved; },
+ });
+ expect(saved[0].renderMs).toBeGreaterThanOrEqual(5000);
+ expect(Date.parse(saved[0].renderStartedAt)).toBe(job.renderStartedAtMs);
+ expect(Date.parse(saved[0].renderCompletedAt)).toBeGreaterThanOrEqual(job.renderStartedAtMs);
+ });
+
+ it('omits render timing entirely when the spawn instant was never observed (#3801)', async () => {
+ const job = { id: 'job-abcdef12', clients: [] };
+ let saved = null;
+ await finalizeGeneratedVideo({
+ ...baseCtx(job),
+ mutateHistory: async (fn) => { saved = await fn([]); return saved; },
+ });
+ // Absent, NOT renderMs: 0 — a zero-duration sample would poison the
+ // estimator's cost model.
+ expect('renderMs' in saved[0]).toBe(false);
+ expect('renderStartedAt' in saved[0]).toBe(false);
+ });
});
describe('describeRenderConditioning (#3696)', () => {
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 41c7a3a5aa..33e4854ad8 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -69,10 +69,12 @@ import {
} from './runtimes.js';
import { loadHistory, saveHistory, mutateVideoHistory } from './history.js';
import { videoModeContractError, videoChainUnsupportedError, VIDEO_MODE_GATED_RUNTIMES } from './modeContract.js';
+import { estimateRenderMs } from './eta.js';
// Re-export the extracted runtime + history surface so existing deep imports
// (`from '../videoGen/local.js'`) keep resolving every symbol they used to.
export * from './runtimes.js';
export * from './modeContract.js';
+export * from './eta.js';
export { loadHistory, saveHistory, mutateVideoHistory };
// LoRA wrapper for the notapalindrome `mlx_video` runtime. The stock
@@ -1290,8 +1292,26 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
throw err;
}
- console.log(`🎬 Generating video [${jobId.slice(0, 8)}]: ${modelId} ${w}x${h} frames=${parsedNumFrames} steps=${actualSteps}`);
- videoGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps, ...meta });
+ // History-calibrated wall-clock estimate (#3801). `null` when this install
+ // has never measured a render on this model — an explicit "no estimate"
+ // sentinel the UI must render as "unknown", never as 0 or a guess. Stamped
+ // on the job so every progress frame can carry it alongside step progress.
+ const etaEstimate = estimateRenderMs({
+ history: await loadHistory(),
+ modelId,
+ width: w,
+ height: h,
+ numFrames: parsedNumFrames,
+ steps: actualSteps,
+ });
+ job.etaMs = etaEstimate ? etaEstimate.etaMs : null;
+ const etaFields = etaEstimate
+ ? { etaMs: etaEstimate.etaMs, etaBasis: etaEstimate.basis, etaSampleCount: etaEstimate.sampleCount }
+ : { etaMs: null };
+ job.renderStartedAtMs = Date.now();
+
+ console.log(`🎬 Generating video [${jobId.slice(0, 8)}]: ${modelId} ${w}x${h} frames=${parsedNumFrames} steps=${actualSteps} eta=${etaEstimate ? `${Math.round(etaEstimate.etaMs / 1000)}s (${etaEstimate.basis}, n=${etaEstimate.sampleCount})` : 'unknown'}`);
+ videoGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps, ...meta, ...etaFields });
// Clear PYTHONPATH so the child uses the venv's own site-packages instead
// of the parent shell's PYTHONPATH. Setting to `undefined` in a spread does
@@ -1694,6 +1714,29 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
rest.numFrames ?? chainModel?.defaultFrames ?? DEFAULT_NUM_FRAMES,
);
+ // Chain-level wall-clock estimate (#3801). Every chunk is a full render that
+ // pays the fixed per-render cost again, so the chain estimate is the
+ // per-chunk estimate times the chunk count — `chunks` is handed to the
+ // estimator rather than folding the chain into one oversized render.
+ // The dimension/step defaults mirror generateVideo's own resolution (its
+ // `width = 768, height = 512` parameter defaults and the samplerLocked step
+ // rule); the estimator returns null on anything it can't resolve, so a drift
+ // here degrades to "no estimate" rather than to a wrong number.
+ const chainSteps = chainModel?.samplerLocked
+ ? chainModel.steps
+ : (rest.steps ? Number(rest.steps) : chainModel?.steps);
+ const chainEta = estimateRenderMs({
+ history: await loadHistory(),
+ modelId: rest.modelId || defaultVideoModelId(),
+ width: rest.width ?? 768,
+ height: rest.height ?? 512,
+ numFrames: rest.numFrames ?? chainModel?.defaultFrames ?? DEFAULT_NUM_FRAMES,
+ steps: chainSteps,
+ chunks: totalChunks,
+ });
+ const chainEtaField = chainEta ? { etaMs: chainEta.etaMs } : {};
+ console.log(`🎬 Chained video [${outerJobId.slice(0, 8)}]: ${totalChunks} chunks, eta=${chainEta ? `${Math.round(chainEta.etaMs / 1000)}s (${chainEta.basis}, n=${chainEta.sampleCount})` : 'unknown'}`);
+
const chainState = { stopped: false };
activeChain = chainState;
@@ -1738,6 +1781,9 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
step: typeof e.step === 'number' ? e.step : undefined,
totalSteps: typeof e.totalSteps === 'number' ? e.totalSteps : undefined,
message: `Chunk ${i + 1}/${totalChunks}${e.message ? ` — ${e.message}` : ''}`,
+ // Chain-level estimate, NOT the inner chunk's — the outer id's
+ // consumers are watching the whole chain's clock.
+ ...chainEtaField,
});
broadcastSse(outerJob, {
type: 'progress',
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index f452e431d5..179f3590eb 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -3014,3 +3014,65 @@ describe('generateVideo — durable re-render inputs (#3696)', () => {
expect(started.conditioning).toEqual(['audio']);
});
});
+
+describe('generateVideo — history-calibrated ETA (#3801)', () => {
+ const startedFor = async (history, params = {}) => {
+ const { readJSONFile } = await import('../../lib/fileUtils.js');
+ vi.mocked(readJSONFile).mockImplementation(async () => history);
+ let started = null;
+ const onStarted = (e) => { started = e; };
+ videoGenEvents.on('started', onStarted);
+ await generateVideo({
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a quiet street at dusk',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ ...params,
+ });
+ videoGenEvents.off('started', onStarted);
+ return started;
+ };
+
+ const timedRecord = (renderMs, over = {}) => ({
+ modelId: 'ltx2_unified',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ steps: 30,
+ renderMs,
+ createdAt: '2026-08-01T00:00:00.000Z',
+ ...over,
+ });
+
+ it('reports an explicit null ETA on a fresh install with no measured renders', async () => {
+ const started = await startedFor([], { jobId: 'eta-no-history' });
+ // null, not 0 and not omitted — the client must be able to tell "unknown"
+ // apart from "about to finish".
+ expect(started.etaMs).toBeNull();
+ expect('etaBasis' in started).toBe(false);
+ });
+
+ it('estimates from a same-shape measured render and labels the basis', async () => {
+ const history = [timedRecord(1_200_000), timedRecord(1_200_000, { createdAt: '2026-07-30T00:00:00.000Z' })];
+ const started = await startedFor(history, { jobId: 'eta-measured' });
+ expect(started.etaMs).toBe(1_200_000);
+ expect(started.etaBasis).toBe('measured');
+ expect(started.etaSampleCount).toBe(2);
+ });
+
+ it('ignores measurements from a different model', async () => {
+ const history = [timedRecord(1_200_000, { modelId: 'some_other_model' })];
+ expect((await startedFor(history, { jobId: 'eta-other-model' })).etaMs).toBeNull();
+ });
+
+ it('scales a differently-shaped measurement by pixels × frames × steps', async () => {
+ const history = [timedRecord(600_000, { numFrames: 50 })];
+ const started = await startedFor(history, { jobId: 'eta-scaled' });
+ // Half the frames → half the work → half the time.
+ expect(started.etaMs).toBe(300_000);
+ expect(started.etaBasis).toBe('proportional');
+ });
+});