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
fix: keep the render ETA across reloads and guard the fit's numerics (#3801)
[._.]/ Adam Eivy93dfb09a4bf1
diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsxindex 451fd7ff24..a5539e7017 100644--- a/client/src/components/pipeline/MediaJobThumb.jsx+++ b/client/src/components/pipeline/MediaJobThumb.jsx@@ -196,7 +196,10 @@ export default function MediaJobThumb({<Loader2 size={14} className="animate-spin text-port-accent" /></div>)}- {pct > 0 && (+ {/* Also shown at 0% when an estimate exists: the pre-step phase (weight+ load, text encode) is minutes long and is exactly when the bar was+ previously blank. */}+ {(pct > 0 || remainingMs != null) && (<div className="absolute bottom-0 left-0 right-0 bg-black/60 text-[9px] text-white text-center py-0.5 font-mono">{pct}%{remainingMs != null ? ` · ~${formatDurationMs(remainingMs)} left` : ''}</div>diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.jsindex c0bc23551c..aef68f6b92 100644--- a/client/src/hooks/useMediaJobProgress.js+++ b/client/src/hooks/useMediaJobProgress.js@@ -69,6 +69,9 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {status: job.status || 'unknown',progress: typeof job.progress === 'number' ? job.progress : prev.progress,statusMsg: job.statusMsg || prev.statusMsg,+ // Reload mid-render: the queue retained the estimate, so the ETA comes+ // back immediately instead of after the next (minutes-away) step.+ etaMs: typeof job.etaMs === 'number' ? job.etaMs : prev.etaMs,filename: job.result?.filename || prev.filename,path: job.result?.path || prev.path,error: job.error || prev.error,diff --git a/client/src/hooks/useMediaJobProgress.test.js b/client/src/hooks/useMediaJobProgress.test.jsindex 81d0236420..1a5a7aab53 100644--- a/client/src/hooks/useMediaJobProgress.test.js+++ b/client/src/hooks/useMediaJobProgress.test.js@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { renderHook, act, waitFor } from '@testing-library/react';const handlers = new Map();+const mediaJob = { current: { status: 'running' } };vi.mock('../services/socket', () => ({default: {on: (event, fn) => { handlers.set(event, fn); },@@ -9,7 +10,7 @@ vi.mock('../services/socket', () => ({},}));vi.mock('../services/apiMediaJobs', () => ({- getMediaJob: vi.fn(async () => ({ status: 'running' })),+ getMediaJob: vi.fn(async () => mediaJob.current),}));import useMediaJobProgress from './useMediaJobProgress';@@ -17,7 +18,7 @@ import useMediaJobProgress from './useMediaJobProgress';const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });describe('useMediaJobProgress — render ETA (#3801)', () => {- beforeEach(() => { handlers.clear(); });+ beforeEach(() => { handlers.clear(); mediaJob.current = { status: 'running' }; });it('starts with no estimate', async () => {const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));@@ -51,6 +52,12 @@ describe('useMediaJobProgress — render ETA (#3801)', () => {expect(result.current.etaMs).toBeNull();});+ it('hydrates the estimate from the queue snapshot on reload', async () => {+ mediaJob.current = { status: 'running', progress: 0.3, etaMs: 900_000 };+ const { result } = renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));+ await waitFor(() => expect(result.current.etaMs).toBe(900_000));+ });+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));diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex e143ae2c40..fff968f33c 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -111,6 +111,9 @@ function sanitizeJob(job) {position: job.position,progress: job.progress,statusMsg: job.statusMsg,+ // History-calibrated render ETA (#3801); undefined when the gen produced+ // no estimate, which the client renders as "unknown".+ etaMs: job.etaMs,error: job.error,result: job.result,params: safeParams,diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex fbfdeb0267..352123005c 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -282,8 +282,8 @@ async function persistImpl() {...archive,];// Strip non-serializable bits.- const serializable = live.map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg }) =>- ({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg }),+ const serializable = live.map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }) =>+ ({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }),);await atomicWrite(JOBS_FILE, { jobs: serializable });}@@ -743,6 +743,13 @@ async function runJob(job) {job.statusMsg = payload.message;didUpdatePersistedProgress = true;}+ // Retain the render ETA (#3801) on the job so a browser that reloads+ // mid-render gets it back from GET /api/media-jobs/:id instead of+ // waiting minutes for the next progress frame to re-deliver it.+ if (typeof payload.etaMs === 'number' && payload.etaMs !== job.etaMs) {+ job.etaMs = payload.etaMs;+ didUpdatePersistedProgress = true;+ }if (didUpdatePersistedProgress) scheduleProgressPersist();broadcastSse(sseEntry, payload);},diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex edb0e7f4b4..ea6c5884a1 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -288,6 +288,23 @@ describe('mediaJobQueue', () => {expect(persisted.statusMsg).toBe('Completed');});+ it('retains the render ETA on the job record so a reload gets it back (#3801)', async () => {+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'how long' } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'running');++ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.1, etaMs: 1_800_000 });+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.etaMs === 1_800_000);+ // A later frame without the field must not wipe the retained estimate —+ // the client hydrates from this record on reload.+ videoGenEvents.emit('progress', { generationId: job.jobId, progress: 0.2 });+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.progress === 0.2);+ expect(mediaJobQueue.getJob(job.jobId).etaMs).toBe(1_800_000);++ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });+ await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');+ });+it('forwards structured step/totalSteps/loss onto the SSE wire', async () => {// The LoRA training live gallery reads loss + step off the progress/preview// SSE frames to plot a curve and key sample thumbnails by step. Thediff --git a/server/services/videoGen/eta.js b/server/services/videoGen/eta.jsindex 7ad639a070..3977135b9c 100644--- a/server/services/videoGen/eta.js+++ b/server/services/videoGen/eta.js@@ -46,6 +46,10 @@ 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;+// Divisor applied to work units before the least-squares sums, so `x²` stays+// far inside the exactly-representable integer range. Purely numerical — it+// cancels out of the returned slope.+const WORK_FIT_SCALE = 1e6;/*** Sampler work for one render, in arbitrary but consistent units.@@ -103,18 +107,27 @@ export const timedRenderSamples = (history, modelId) => {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);+ // Work units are ~1e9 for a real render, so `x²` would land near 1e18 —+ // past the 2^53 integer-exact range of a double. `n·Σx² − (Σx)²` then+ // subtracts two ~1e20 values whose low bits are already gone, which is+ // catastrophic cancellation exactly when the samples are close together+ // (the common case: a few renders at neighboring frame counts). Fitting in+ // scaled units keeps every intermediate comfortably exact; the slope is+ // rescaled back on the way out so the returned units are unchanged.+ const xs = samples.map((s) => s.workUnits / WORK_FIT_SCALE);+ const sumX = xs.reduce((a, x) => a + x, 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 sumXY = samples.reduce((a, s, i) => a + xs[i] * s.durationMs, 0);+ const sumXX = xs.reduce((a, x) => a + x * x, 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;+ const perUnitMs = ((n * sumXY - sumX * sumY) / denom) / WORK_FIT_SCALE;if (!Number.isFinite(perUnitMs) || perUnitMs <= 0) return null;- const fixedMs = Math.max(0, (sumY - perUnitMs * sumX) / n);- return { perUnitMs, fixedMs };+ const fixedMs = (sumY - perUnitMs * WORK_FIT_SCALE * sumX) / n;+ if (!Number.isFinite(fixedMs)) return null;+ return { perUnitMs, fixedMs: Math.max(0, fixedMs) };};/**@@ -141,13 +154,23 @@ export const estimateRenderMs = ({ history, modelId, width, height, numFrames, sconst 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,- });+ // Final backstop: an estimate that isn't a positive finite number is not an+ // estimate. Returning 0 (or NaN, or a negative) here would be worse than+ // returning nothing, because every consumer reads a number as truth.+ const finish = (perChunkMs, basis, sampleCount) => {+ if (!Number.isFinite(perChunkMs) || perChunkMs <= 0) return null;+ const etaMs = Math.round(perChunkMs * chunkCount);+ // Checked AFTER rounding: a sub-millisecond estimate is positive but+ // rounds to 0, and 0 is the one number this must never report.+ if (etaMs <= 0) return null;+ return {+ etaMs,+ perChunkMs: Math.round(perChunkMs),+ chunks: chunkCount,+ basis,+ sampleCount,+ };+ };// 1. A real measurement of this exact shape overrides the model.const exact = samples@@ -160,10 +183,10 @@ export const estimateRenderMs = ({ history, modelId, width, height, numFrames, s// 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);+ const fitted = fit ? finish(fit.perUnitMs * workUnits + fit.fixedMs, 'linear', recent.length) : null;+ if (fitted) return fitted;// 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.jsindex df98701c7b..e5032c7d38 100644--- a/server/services/videoGen/eta.test.js+++ b/server/services/videoGen/eta.test.js@@ -66,6 +66,20 @@ describe('fitRenderCost', () => {expect(fitRenderCost(samples)).toBeNull();});+ it('stays numerically stable on real-scale, closely-spaced work units', () => {+ // ~1e9 work units per render: squaring these overflows the exactly-+ // representable integer range, so an unscaled normal-equation fit+ // catastrophically cancels and returns a garbage slope.+ const samples = [97, 105, 113].map((frames) => {+ const w = 768 * 512 * frames * 30;+ return { workUnits: w, durationMs: 2e-6 * w + 90_000 };+ });+ const fit = fitRenderCost(samples);+ expect(fit.perUnitMs).toBeCloseTo(2e-6, 12);+ expect(fit.fixedMs).toBeGreaterThan(89_000);+ expect(fit.fixedMs).toBeLessThan(91_000);+ });+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 }));@@ -146,6 +160,12 @@ describe('estimateRenderMs', () => {}});+ it('returns null rather than a zero estimate when the samples round to nothing', () => {+ // A sub-millisecond measurement rounds to 0, and 0 is the one number this+ // must never report — the contract is "no estimate" instead.+ expect(estimateRenderMs({ history: [rec({ renderMs: 0.4 })], ...target })).toBeNull();+ });+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.