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([unify-media-job-sse-hook-imagegen-videogen]): share media-job SSE attach across ImageGen + VideoGen

[._.]/ Adam Eivy0e5ab232ee34
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index b07ed30272..c7af952c35 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -33,6 +33,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. |
| `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
+| `useMediaJobSse` | Imperative per-job `/{kind}-gen/:id/events` SSE; `attach()` returns a Promise that settles on the terminal frame. | POST-then-attach media render flows that await completion (ImageGen/VideoGen). |
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
| `usePipelineAutoRunProgress` | Auto-run-text SSE for a pipeline issue. | Pipeline auto-run UI surfaces only. |
| `usePipelineEditorialProgress` | Series editorial reader-emotion batch SSE. | Editorial Roadmap analysis UI only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index a3bfb18216..336e3e0b01 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -16,6 +16,7 @@ export { default as useImageGenQueue } from './useImageGenQueue.js';
export { default as useMediaPreviewActions } from './useMediaPreviewActions.js';
export { default as useKeyboardControls } from './useKeyboardControls.js';
export { default as useMediaJobProgress } from './useMediaJobProgress.js';
+export * from './useMediaJobSse.js';
export { default as useMoltworldWs } from './useMoltworldWs.js';
export { default as useMounted } from './useMounted.js';
export { default as useNextEvalCountdown } from './useNextEvalCountdown.js';
diff --git a/client/src/hooks/useMediaJobSse.js b/client/src/hooks/useMediaJobSse.js
new file mode 100644
index 0000000000..d775b0cc2b
--- /dev/null
+++ b/client/src/hooks/useMediaJobSse.js
@@ -0,0 +1,89 @@
+import { useCallback, useRef } from 'react';
+import { safeParseJSON } from '../lib/genUtils';
+
+/**
+ * Imperative EventSource subscriber for a single media-generation job's
+ * `/api/{kind}-gen/:id/events` stream. Used by ImageGen + VideoGen, which
+ * both POST a render, learn the jobId from the response, then open the SSE
+ * and settle a Promise on the terminal frame (the queue worker awaits it).
+ *
+ * This is a sibling to the declarative `useSseProgress` — not a wrapper of
+ * it — because those pages can't know the stream URL until the POST returns,
+ * and the batch/queue paths need an awaitable Promise rather than reactive
+ * `frames`/`latest` state. The shared machinery here is the parse → dispatch
+ * → terminal-close → settle lifecycle; each page maps the per-type fields to
+ * its own state via the handler callbacks.
+ *
+ * `attach(jobId, handlers)` returns a Promise that:
+ * - resolves on `complete` (with `onComplete`'s return value, or `msg.result`)
+ * - rejects on `error` / `canceled` (with the handler's returned Error, or a
+ * default built from `msg.error` / `msg.reason`)
+ * - rejects on connection loss ("Lost connection to server")
+ *
+ * Handlers (all optional): `isCurrent` (staleness guard — a stale frame
+ * closes the stream and is ignored), `onQueued`, `onStarted`, `onStage`,
+ * `onStatus`, `onProgress`, `onComplete`, `onError`, `onCanceled`,
+ * `onConnectionError`.
+ *
+ * `eventSourceRef` is exposed so callers can `close()` on cancel/unmount.
+ */
+export function useMediaJobSse(kind) {
+ const eventSourceRef = useRef(null);
+
+ const close = useCallback(() => {
+ eventSourceRef.current?.close();
+ eventSourceRef.current = null;
+ }, []);
+
+ const attach = useCallback((jobId, handlers = {}) => {
+ const {
+ isCurrent = () => true,
+ onQueued, onStarted, onStage, onStatus, onProgress,
+ onComplete, onError, onCanceled, onConnectionError,
+ } = handlers;
+ return new Promise((resolve, reject) => {
+ const es = new EventSource(`/api/${kind}-gen/${jobId}/events`);
+ eventSourceRef.current = es;
+ es.onmessage = (ev) => {
+ // A stale frame (the run this stream belonged to was cancelled /
+ // superseded) tears down the stream and is otherwise ignored.
+ if (!isCurrent()) { es.close(); return; }
+ const msg = safeParseJSON(ev.data);
+ if (!msg) return;
+ switch (msg.type) {
+ case 'queued': onQueued?.(msg); break;
+ case 'started': onStarted?.(msg); break;
+ case 'stage': onStage?.(msg); break;
+ case 'status': onStatus?.(msg); break;
+ case 'progress': onProgress?.(msg); break;
+ case 'complete': {
+ es.close();
+ const value = onComplete?.(msg);
+ resolve(value === undefined ? msg.result : value);
+ break;
+ }
+ case 'error': {
+ es.close();
+ reject(onError?.(msg) || new Error(msg.error));
+ break;
+ }
+ case 'canceled': {
+ es.close();
+ reject(onCanceled?.(msg) || new Error(msg.reason || 'Canceled'));
+ break;
+ }
+ default: break;
+ }
+ };
+ es.onerror = () => {
+ if (!isCurrent()) { es.close(); return; }
+ es.close();
+ const err = new Error('Lost connection to server');
+ onConnectionError?.(err);
+ reject(err);
+ };
+ });
+ }, [kind]);
+
+ return { attach, close, eventSourceRef };
+}
diff --git a/client/src/hooks/useMediaJobSse.test.jsx b/client/src/hooks/useMediaJobSse.test.jsx
new file mode 100644
index 0000000000..bdf426c83f
--- /dev/null
+++ b/client/src/hooks/useMediaJobSse.test.jsx
@@ -0,0 +1,148 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook } from '@testing-library/react';
+import { useMediaJobSse } from './useMediaJobSse';
+
+// jsdom has no EventSource — stand up a minimal mock that records instances
+// and lets a test drive onmessage / onerror by hand.
+class MockEventSource {
+ constructor(url) {
+ this.url = url;
+ this.onmessage = null;
+ this.onerror = null;
+ this.closed = false;
+ MockEventSource.instances.push(this);
+ }
+
+ close() { this.closed = true; }
+
+ emit(payload) { this.onmessage?.({ data: JSON.stringify(payload) }); }
+
+ emitRaw(data) { this.onmessage?.({ data }); }
+
+ fail() { this.onerror?.(); }
+}
+
+const last = () => MockEventSource.instances[MockEventSource.instances.length - 1];
+
+beforeEach(() => {
+ MockEventSource.instances = [];
+ global.EventSource = MockEventSource;
+});
+
+afterEach(() => {
+ delete global.EventSource;
+});
+
+describe('useMediaJobSse', () => {
+ it('opens the per-job events URL for the given kind', () => {
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ result.current.attach('job1', {});
+ expect(last().url).toBe('/api/image-gen/job1/events');
+
+ const { result: video } = renderHook(() => useMediaJobSse('video'));
+ video.current.attach('job2', {});
+ expect(last().url).toBe('/api/video-gen/job2/events');
+ });
+
+ it('dispatches non-terminal frames to their handlers', () => {
+ const handlers = {
+ onQueued: vi.fn(), onStarted: vi.fn(), onStage: vi.fn(),
+ onStatus: vi.fn(), onProgress: vi.fn(),
+ };
+ const { result } = renderHook(() => useMediaJobSse('video'));
+ result.current.attach('j', handlers);
+
+ last().emit({ type: 'queued', position: 3 });
+ last().emit({ type: 'started' });
+ last().emit({ type: 'stage', stage: 'inference' });
+ last().emit({ type: 'status', message: 'hi' });
+ last().emit({ type: 'progress', progress: 0.5 });
+
+ expect(handlers.onQueued).toHaveBeenCalledWith(expect.objectContaining({ position: 3 }));
+ expect(handlers.onStarted).toHaveBeenCalledTimes(1);
+ expect(handlers.onStage).toHaveBeenCalledWith(expect.objectContaining({ stage: 'inference' }));
+ expect(handlers.onStatus).toHaveBeenCalledWith(expect.objectContaining({ message: 'hi' }));
+ expect(handlers.onProgress).toHaveBeenCalledWith(expect.objectContaining({ progress: 0.5 }));
+ expect(last().closed).toBe(false);
+ });
+
+ it('resolves with msg.result by default on complete and closes the stream', async () => {
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ const p = result.current.attach('j', {});
+ last().emit({ type: 'complete', result: { filename: 'a.png' } });
+ await expect(p).resolves.toEqual({ filename: 'a.png' });
+ expect(last().closed).toBe(true);
+ });
+
+ it('resolves with onComplete return value when provided', async () => {
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ const onComplete = vi.fn(() => 'custom');
+ const p = result.current.attach('j', { onComplete });
+ last().emit({ type: 'complete', result: { filename: 'a.png' } });
+ await expect(p).resolves.toBe('custom');
+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ result: { filename: 'a.png' } }));
+ });
+
+ it('rejects with a default Error(msg.error) on error', async () => {
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ const p = result.current.attach('j', {});
+ last().emit({ type: 'error', error: 'boom' });
+ await expect(p).rejects.toThrow('boom');
+ expect(last().closed).toBe(true);
+ });
+
+ it('rejects with the custom Error returned from onError', async () => {
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ const onError = vi.fn((msg) => {
+ const err = new Error(msg.error);
+ err.kind = msg.kind;
+ return err;
+ });
+ const p = result.current.attach('j', { onError });
+ last().emit({ type: 'error', error: 'gated', kind: 'gated_repo' });
+ await expect(p).rejects.toMatchObject({ message: 'gated', kind: 'gated_repo' });
+ });
+
+ it('rejects with the cancel reason on canceled', async () => {
+ const { result } = renderHook(() => useMediaJobSse('video'));
+ const p = result.current.attach('j', {});
+ last().emit({ type: 'canceled', reason: 'user stopped' });
+ await expect(p).rejects.toThrow('user stopped');
+ });
+
+ it('rejects and notifies onConnectionError on a connection failure', async () => {
+ const { result } = renderHook(() => useMediaJobSse('video'));
+ const onConnectionError = vi.fn();
+ const p = result.current.attach('j', { onConnectionError });
+ last().fail();
+ await expect(p).rejects.toThrow('Lost connection to server');
+ expect(onConnectionError).toHaveBeenCalledTimes(1);
+ expect(last().closed).toBe(true);
+ });
+
+ it('ignores frames and tears down the stream when isCurrent() is false', () => {
+ const onProgress = vi.fn();
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ result.current.attach('j', { isCurrent: () => false, onProgress });
+ last().emit({ type: 'progress', progress: 0.9 });
+ expect(onProgress).not.toHaveBeenCalled();
+ expect(last().closed).toBe(true);
+ });
+
+ it('silently ignores unparseable frames', () => {
+ const onProgress = vi.fn();
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ result.current.attach('j', { onProgress });
+ expect(() => last().emitRaw('not json')).not.toThrow();
+ expect(onProgress).not.toHaveBeenCalled();
+ expect(last().closed).toBe(false);
+ });
+
+ it('close() tears down the active stream', () => {
+ const { result } = renderHook(() => useMediaJobSse('image'));
+ result.current.attach('j', {});
+ expect(last().closed).toBe(false);
+ result.current.close();
+ expect(last().closed).toBe(true);
+ });
+});
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 0dd73cc7c0..7156af227d 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -39,13 +39,13 @@ import { resolveCleanersFromConfig } from '../lib/imageCleaners';
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import { useImageGenProgress } from '../hooks/useImageGenProgress';
+import { useMediaJobSse } from '../hooks/useMediaJobSse';
import { useModelDownloadStatus } from '../hooks/useModelDownloadStatus';
import {
getImageGenStatus, generateImage, listImageModels, listLorasFull, listImageGallery,
cancelImageGen, deleteImage, setImageHidden, cleanGalleryImage, getActiveImageJob, getSettings,
buildFormData, listMediaJobs,
} from '../services/api';
-import { safeParseJSON } from '../lib/genUtils';
// Multi-reference editing (FLUX.2 only) — 4 fixed slots, each carrying an
// uploaded File + a 0..1 strength weight. Slots are positional so the
@@ -187,7 +187,7 @@ export default function ImageGen() {
const [stage, setStage] = useState(null);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
- const eventSourceRef = useRef(null);
+ const { attach: attachJobEvents, eventSourceRef } = useMediaJobSse('image');
// External-mode socket-driven progress (kept for backward compat with
// existing AUTOMATIC1111 wiring; the local mode also feeds the same hook
@@ -313,19 +313,16 @@ export default function ImageGen() {
setGenerating(true);
setStatusMsg('Resuming…');
resumeGenerate(activeJob);
- // Re-attach the per-job SSE so raw status text resumes too.
- const es = new EventSource(`/api/image-gen/${activeJob.generationId}/events`);
- eventSourceRef.current = es;
- es.onmessage = (e) => {
- const msg = safeParseJSON(e.data);
- if (!msg) return;
- if (msg.type === 'status') setStatusMsg(msg.message);
- if (msg.type === 'progress') setLocalProgress({ progress: msg.progress });
- if (msg.type === 'complete' || msg.type === 'error' || msg.type === 'canceled') {
- setGenerating(false);
- es.close();
- }
- };
+ // Re-attach the per-job SSE so raw status text resumes too. The reject
+ // on a terminal error/canceled frame is expected here (we only want the
+ // generating flag flipped off), so swallow it.
+ attachJobEvents(activeJob.generationId, {
+ onStatus: (msg) => setStatusMsg(msg.message),
+ onProgress: (msg) => setLocalProgress({ progress: msg.progress }),
+ onComplete: () => setGenerating(false),
+ onError: () => setGenerating(false),
+ onCanceled: () => setGenerating(false),
+ }).catch(() => {});
}).catch(() => {});
return () => eventSourceRef.current?.close();
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -650,61 +647,44 @@ export default function ImageGen() {
const startLocalGeneration = async () => {
setLocalProgress({ progress: 0 });
const { payload, data } = await submitGenerationPayload();
- return new Promise((resolve, reject) => {
- const jobId = data.jobId || data.generationId;
- const es = new EventSource(`/api/image-gen/${jobId}/events`);
- eventSourceRef.current = es;
-
- es.onmessage = (ev) => {
- const msg = safeParseJSON(ev.data);
- if (!msg) return;
- if (msg.type === 'stage') setStage({ name: msg.stage, detail: msg.detail });
- if (msg.type === 'status') setStatusMsg(msg.message);
- if (msg.type === 'progress') {
- setLocalProgress({ progress: msg.progress, phase: msg.phase });
- setStatusMsg(msg.message);
- }
- if (msg.type === 'complete') {
- // Codex's built-in image_gen tool decides steps/guidance/seed
- // internally and ignores whatever we pass — so don't backfill
- // local-mode model defaults onto a codex render's metadata.
- // The gallery / sidecar would otherwise show steps=20,
- // guidance=3.5 (Flux 1 Dev defaults) on every codex image,
- // misleading the user about what actually produced it.
- const localOnlyMeta = isCodexMode ? {} : {
- steps: payload.steps ?? currentModel?.steps,
- guidance: payload.guidance ?? currentModel?.guidance,
- };
- setResult({
- ...data,
- ...msg.result,
- prompt: payload.prompt,
- negativePrompt: payload.negativePrompt,
- width, height,
- ...localOnlyMeta,
- });
- es.close();
- resolve(msg.result);
- }
- if (msg.type === 'error') {
- es.close();
- // The server may attach `kind` (e.g. 'gated_repo', 'hf_unauthorized')
- // and `repo` for the UI to deep-link to the HF access page. Carry
- // them on the Error so handleGenerate's catch can render guidance.
- const err = new Error(msg.error);
- if (msg.kind) err.kind = msg.kind;
- if (msg.repo) err.repo = msg.repo;
- reject(err);
- }
- if (msg.type === 'canceled') {
- es.close();
- reject(new Error(msg.reason || 'Canceled'));
- }
- };
- es.onerror = () => {
- es.close();
- reject(new Error('Lost connection to server'));
- };
+ const jobId = data.jobId || data.generationId;
+ return attachJobEvents(jobId, {
+ onStage: (msg) => setStage({ name: msg.stage, detail: msg.detail }),
+ onStatus: (msg) => setStatusMsg(msg.message),
+ onProgress: (msg) => {
+ setLocalProgress({ progress: msg.progress, phase: msg.phase });
+ setStatusMsg(msg.message);
+ },
+ onComplete: (msg) => {
+ // Codex's built-in image_gen tool decides steps/guidance/seed
+ // internally and ignores whatever we pass — so don't backfill
+ // local-mode model defaults onto a codex render's metadata.
+ // The gallery / sidecar would otherwise show steps=20,
+ // guidance=3.5 (Flux 1 Dev defaults) on every codex image,
+ // misleading the user about what actually produced it.
+ const localOnlyMeta = isCodexMode ? {} : {
+ steps: payload.steps ?? currentModel?.steps,
+ guidance: payload.guidance ?? currentModel?.guidance,
+ };
+ setResult({
+ ...data,
+ ...msg.result,
+ prompt: payload.prompt,
+ negativePrompt: payload.negativePrompt,
+ width, height,
+ ...localOnlyMeta,
+ });
+ return msg.result;
+ },
+ onError: (msg) => {
+ // The server may attach `kind` (e.g. 'gated_repo', 'hf_unauthorized')
+ // and `repo` for the UI to deep-link to the HF access page. Carry
+ // them on the Error so handleGenerate's catch can render guidance.
+ const err = new Error(msg.error);
+ if (msg.kind) err.kind = msg.kind;
+ if (msg.repo) err.repo = msg.repo;
+ return err;
+ },
});
};
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 8d03a4fc25..c0f912ec07 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -47,6 +47,7 @@ import FavoritesFilterChip from '../components/media/FavoritesFilterChip';
import ModelSelect from '../components/ModelSelect';
import ModelDownloadBadge, { deriveSizeEstimate } from '../components/media/ModelDownloadBadge';
import { useModelDownloadStatus, TEXT_ENCODER_DOWNLOAD_ID } from '../hooks/useModelDownloadStatus';
+import { useMediaJobSse } from '../hooks/useMediaJobSse';
import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import usePreviewRoute from '../hooks/usePreviewRoute';
@@ -58,7 +59,7 @@ import {
getSettings, patchSettingsSlice,
getActiveVideoJob,
} from '../services/api';
-import { randomSeed, safeParseJSON } from '../lib/genUtils';
+import { randomSeed } from '../lib/genUtils';
import { VIDEO_RESOLUTIONS } from '../lib/videoGenResolutions';
import { VIDEO_TILING_OPTIONS, VIDEO_TILING_ENUM_SET } from '../lib/videoTilingOptions';
import { resolveResolutionLabel } from '../lib/imageGenResolutions';
@@ -421,7 +422,7 @@ export default function VideoGen() {
const [statusMsg, setStatusMsg] = useState('');
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
- const eventSourceRef = useRef(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
// outstanding Promise dangles forever — and the queue worker's .finally()
@@ -458,63 +459,50 @@ export default function VideoGen() {
useEffect(() => {
refreshStatus();
return () => eventSourceRef.current?.close();
- }, [refreshStatus]);
+ }, [refreshStatus, eventSourceRef]);
// 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') {
+ return attach(jobId, {
+ isCurrent,
+ onQueued: (msg) => setStatusMsg(typeof msg.position === 'number' ? `Queued (position ${msg.position})` : 'Queued'),
+ onStarted: () => setStatusMsg('Starting render…'),
+ onStatus: (msg) => setStatusMsg(msg.message),
+ onProgress: (msg) => {
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') {
+ },
+ onComplete: (msg) => {
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') {
+ return msg.result;
+ },
+ onError: (msg) => {
setError(msg.error);
setGenerating(false);
- es.close();
if (withToast) toast.error(msg.error);
- settleReject(new Error(msg.error));
- }
- if (msg.type === 'canceled') {
+ return new Error(msg.error);
+ },
+ onCanceled: (msg) => {
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;
+ return new Error(msg.reason || 'Canceled');
+ },
+ onConnectionError: () => {
+ setError('Lost connection to server');
+ setGenerating(false);
+ },
+ }).then(settleResolve, settleReject);
};
// Resume an in-flight (or queued) render so a page reload doesn't lose