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: resume video-gen progress on page reload + propagate STATUS lines
[._.]/ Adam Eivybcc86d1dd907
diff --git a/PLAN.md b/PLAN.mdindex 2b37a7745c..5d8bd3cc89 100644--- a/PLAN.md+++ b/PLAN.md@@ -64,6 +64,7 @@ Items here need a research / design pass, an explicit decision, or a preconditio- [ ] [episode-video-provider-picker-runwayml-third-party] **Episode-video provider picker (RunwayML / third-party).** Once the abstraction lands, expose picker on EpisodeVideoStage.- [ ] [comic-book-pdf-export-once-stages-comicpages] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.- [ ] [ai-assisted-panel-scene-prompt-generation-reserve] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` for a future "turn script fragment into N image-gen prompts" button.+- [ ] [unify-media-job-sse-hook-imagegen-videogen] **Unify ImageGen + VideoGen SSE attach into `useMediaJobSse` hook.** Both pages now have near-duplicate EventSource handlers (ImageGen `startLocalGeneration` lines 653-708 + resume block lines 317-328; VideoGen `attachJobEvents`). Build a hook on top of `useSseProgress` (`client/src/hooks/useSseProgress.js`) that handles the queued / started / status / progress / complete / error / canceled SSE types and consolidate both sites. Deferred from the video-reload PR — scope was just the bug fix.- [ ] [whole-episode-audio-generation-strategy-stop] **Whole-episode audio generation strategy.** Stop relying on per-clip audio; drive audio gen from episode-level prose/script arc. Generator candidates: Suno (commercial, duration control), MusicGen-MLX (local, bounded ~30s), AudioLDM2. New `audioMode: 'per-clip' | 'silent' | 'generated' | 'uploaded-track'`. Treat as a new sub-brainstorm when picked up — investigation first.### Large product / UX redesignsdiff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 983c9e4d7c..f7f8bbc56d 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -56,6 +56,7 @@ import {upscaleVideo,listImageGallery,getSettings, updateSettings,+ getActiveVideoJob,} from '../services/api';import { randomSeed, safeParseJSON } from '../lib/genUtils';import { VIDEO_RESOLUTIONS } from '../lib/videoGenResolutions';@@ -431,6 +432,99 @@ export default function VideoGen() {return () => eventSourceRef.current?.close();}, [refreshStatus]);+ // SSE subscriber shared by the in-flight POST path and the mount-time+ // resume path. `withToast: false` on resume suppresses the success/error+ // toast — the user already saw it the first time and a page reload+ // shouldn't replay it.+ const attachJobEvents = (jobId, { isCurrent = () => true, settleResolve = () => {}, settleReject = () => {}, withToast = true } = {}) => {+ const es = new EventSource(`/api/video-gen/${jobId}/events`);+ eventSourceRef.current = es;+ es.onmessage = (ev) => {+ if (!isCurrent()) { es.close(); return; }+ const msg = safeParseJSON(ev.data);+ if (!msg) return;+ if (msg.type === 'queued') {+ setStatusMsg(typeof msg.position === 'number' ? `Queued (position ${msg.position})` : 'Queued');+ }+ if (msg.type === 'started') setStatusMsg('Starting render…');+ if (msg.type === 'status') setStatusMsg(msg.message);+ if (msg.type === 'progress') {+ setProgress({ progress: msg.progress });+ // 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);+ }+ if (msg.type === 'complete') {+ setResult(msg.result);+ setGenerating(false);+ setProgress({ progress: 1 });+ setStatusMsg('Complete');+ es.close();+ if (withToast) toast.success('Video generated');+ refreshHistory();+ settleResolve(msg.result);+ }+ if (msg.type === 'error') {+ setError(msg.error);+ setGenerating(false);+ es.close();+ if (withToast) toast.error(msg.error);+ settleReject(new Error(msg.error));+ }+ if (msg.type === 'canceled') {+ setGenerating(false);+ setStatusMsg(msg.reason || 'Canceled');+ es.close();+ if (withToast) toast(msg.reason || 'Render canceled');+ settleReject(new Error(msg.reason || 'Canceled'));+ }+ };+ es.onerror = () => {+ if (!isCurrent()) { es.close(); return; }+ setError('Lost connection to server');+ setGenerating(false);+ es.close();+ settleReject(new Error('Lost connection to server'));+ };+ return es;+ };++ // Resume an in-flight (or queued) render so a page reload doesn't lose+ // the preview/progress display. Server holds the job's last SSE payload,+ // so re-attaching replays the most recent status/progress immediately.+ // Mirrors the ImageGen `getActiveImageJob` mount path.+ useEffect(() => {+ getActiveVideoJob().then((data) => {+ const job = data?.activeJob;+ if (!job?.jobId) return;+ if (generating || eventSourceRef.current) return;+ const p = job.params || {};+ if (p.prompt) setPrompt(p.prompt);+ if (p.negativePrompt) setNegativePrompt(p.negativePrompt);+ if (p.modelId) setModelId(p.modelId);+ if (p.width) setWidth(p.width);+ if (p.height) setHeight(p.height);+ if (p.numFrames) setNumFrames(p.numFrames);+ if (p.fps) setFps(p.fps);+ if (p.steps != null) setSteps(String(p.steps));+ if (p.guidanceScale != null) setGuidanceScale(String(p.guidanceScale));+ if (p.seed != null) setSeed(String(p.seed));+ if (p.tiling) setTiling(p.tiling);+ if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);+ if (p.mode) setMode(p.mode);+ if (p.chunks && p.chunks > 1) setChunks(p.chunks);+ setGenerating(true);+ setProgress({ progress: 0 });+ setStatusMsg(job.status === 'queued'+ ? (typeof job.position === 'number' ? `Queued (position ${job.position})` : 'Queued')+ : 'Resuming…');+ const myToken = ++runTokenRef.current;+ const isCurrent = () => myToken === runTokenRef.current;+ attachJobEvents(job.jobId, { isCurrent, withToast: false });+ }).catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+// Settings PUT shallow-merges top-level keys, so the full imageGen slice// must round-trip — otherwise mode/external/codex/expose get clobbered.const handleSavePythonPath = useCallback(async (path) => {@@ -724,55 +818,7 @@ export default function VideoGen() {// earlier handleCancel() already settled the Promise via runRejectRef.if (!isCurrent()) return;const jobId = data.jobId || data.generationId;- const es = new EventSource(`/api/video-gen/${jobId}/events`);- eventSourceRef.current = es;-- es.onmessage = (ev) => {- // A cancel that landed after the EventSource opened would have closed- // it, but a stray buffered message could still fire — bail before- // touching component state for a run we no longer own.- if (!isCurrent()) { es.close(); return; }- const msg = safeParseJSON(ev.data);- if (!msg) return;- if (msg.type === 'status') setStatusMsg(msg.message);- if (msg.type === 'progress') {- setProgress({ progress: msg.progress });- setStatusMsg(msg.message);- }- if (msg.type === 'complete') {- setResult(msg.result);- setGenerating(false);- setProgress({ progress: 1 });- setStatusMsg('Complete');- es.close();- toast.success('Video generated');- refreshHistory();- settleResolve(msg.result);- }- if (msg.type === 'error') {- setError(msg.error);- setGenerating(false);- es.close();- toast.error(msg.error);- settleReject(new Error(msg.error));- }- if (msg.type === 'canceled') {- // Queue-driven cancellation (different from gen-side error). Mark- // the UI terminal so the spinner clears and the user can resubmit.- setGenerating(false);- setStatusMsg(msg.reason || 'Canceled');- es.close();- toast(msg.reason || 'Render canceled');- settleReject(new Error(msg.reason || 'Canceled'));- }- };- es.onerror = () => {- if (!isCurrent()) { es.close(); return; }- setError('Lost connection to server');- setGenerating(false);- es.close();- settleReject(new Error('Lost connection to server'));- };+ attachJobEvents(jobId, { isCurrent, settleResolve, settleReject, withToast: true });}).catch((err) => {if (!isCurrent()) return;setError(err.message || 'Video generation failed');diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 806597e783..c8b96ff466 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -44,6 +44,10 @@ export const listVideoModels = () => request('/video-gen/models');// encoder is a separate multi-GB pull.export const getVideoModelStatuses = () => request('/video-gen/models/status', { silent: true });export const cancelVideoGen = () => request('/video-gen/cancel', { method: 'POST' });+// Currently-running (or next-queued) video job — used on VideoGen mount to+// resume progress display after a page reload. Silent so a 5xx during status+// poll doesn't double-toast on every navigation.+export const getActiveVideoJob = () => request('/video-gen/active', { silent: true });export const listVideoHistory = () => request('/video-gen/history');export const deleteVideoHistoryItem = (id) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE' });export const setVideoHidden = (id, hidden) => request(`/video-gen/history/${encodeURIComponent(id)}/visibility`, {diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 81ab0933a3..1472387723 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -706,6 +706,28 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {res.json({ jobId, generationId: jobId, filename: `${jobId}.mp4`, model: effectiveModelId, mode: 'local', status, position });}));+// Currently-running video job (if any) so the page can re-attach after a+// reload — the SSE replay of `lastPayload` then resumes progress display.+// Mirrors GET /api/image-gen/active. Returns `{ activeJob: null }` when no+// video render is in flight. Queued-but-not-yet-running jobs are returned+// too so the user lands on a "Queued (position N)" state instead of an+// empty form.+router.get('/active', (_req, res) => {+ const running = listJobs({ kind: 'video', status: 'running' })[0];+ const queued = !running ? listJobs({ kind: 'video', status: 'queued' })[0] : null;+ const job = running || queued;+ if (!job) return res.json({ activeJob: null });+ res.json({+ activeJob: {+ jobId: job.id,+ generationId: job.id,+ status: job.status,+ position: job.position,+ params: job.params || {},+ },+ });+});+router.get('/:jobId/events', (req, res) => {const ok = attachSseClient(req.params.jobId, res);if (!ok) res.status(404).json({ error: 'Job not found or expired' });diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 4d97dd7703..a37de62298 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -755,7 +755,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// Heartbeat for the queue's idle watchdog (see imageGen/local.js).videoGenEvents.emit('activity', { generationId: jobId });if (line.startsWith('STATUS:')) {- broadcastSse(job, { type: 'status', message: line.slice(7) });+ 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 });return true;}if (line.startsWith('STAGE:')) {@@ -772,31 +778,44 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst tag = (parts[2] || '').toLowerCase();if (tag === 'heartbeat') {// Surface as a status message; the activity emit above already- // resets the queue watchdog.- broadcastSse(job, { type: 'status', message: `${parts[1]}: heartbeat ${parts[3] || ''}` });+ // 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 });return true;}if (tag === 'step') {const step = parseInt(parts[3], 10) || 0;const total = parseInt(parts[4], 10) || 1;- broadcastSse(job, { type: 'progress', progress: step / total, message: parts.slice(5).join(':') });- videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total });+ const label = parts.slice(5).join(':');+ broadcastSse(job, { type: 'progress', progress: step / total, message: label });+ // Pass the python-side label as `message` so the dispatcher surfaces+ // 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 });return true;}// Bare phase marker (e.g. STAGE:load-pipeline, STAGE:from-pretrained) —// surface as a status line. No progress %, no division-by-undefined.- broadcastSse(job, { type: 'status', message: parts.slice(1).join(':') });+ // Mirror to videoGenEvents for client forwarding.+ const message = parts.slice(1).join(':');+ broadcastSse(job, { type: 'status', message });+ videoGenEvents.emit('status', { generationId: jobId, message });return true;}if (line.startsWith('DOWNLOAD:')) {- broadcastSse(job, { type: 'status', message: `Downloading model... ${line.slice(9)}` });+ const message = `Downloading model... ${line.slice(9)}`;+ broadcastSse(job, { type: 'status', message });+ videoGenEvents.emit('status', { generationId: jobId, message });return true;}const m = line.match(/(\d+)%\|/);if (m) {const pct = parseInt(m[1], 10) / 100;broadcastSse(job, { type: 'progress', progress: pct, message: line });- videoGenEvents.emit('progress', { generationId: jobId, progress: pct });+ videoGenEvents.emit('progress', { generationId: jobId, progress: pct, message: line });return true;}return false;