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

refactor([issue-1144]): consolidate SSE stream wiring and tab validation onto shared hooks

[._.]/ Adam Eivy86e3b0c4de2e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b0f8fc3eda..ebbefefc50 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,6 +35,8 @@
## Changed
+- **[issue-1144] Internal cleanup of live-progress streams and tab handling** — consolidated duplicated client plumbing for streamed progress (installs, renders, pipeline runs) and tabbed-page URL validation onto shared building blocks; no change to how any page behaves.
+
- **[issue-1136] Debug and status responses no longer echo raw upstream payloads** — the OpenClaw status check and the message-account token test now return only the summary fields they're meant to (connection state, counts, errors) instead of passing through whatever the upstream service responded with.
- **[issue-1094] Federation "Make mutual" sync behavior clarified** — documented and locked in how toggling a sync category toward a peer stays mirrored on both machines. No change to how syncing behaves.
diff --git a/client/src/components/feature-agents/constants.js b/client/src/components/feature-agents/constants.js
index dda459abf6..f80eee5798 100644
--- a/client/src/components/feature-agents/constants.js
+++ b/client/src/components/feature-agents/constants.js
@@ -9,8 +9,6 @@ export const TABS = [
{ id: 'git', label: 'Git', icon: GitBranch }
];
-export const VALID_TAB_IDS = new Set(TABS.map(t => t.id));
-
export const STATUS_COLORS = {
draft: 'text-gray-400',
active: 'text-port-success',
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 8c79361ec3..7c19a685d7 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -47,10 +47,10 @@ import {
startPipelineVolumeBeats, cancelPipelineVolumeBeats,
generatePipelineVolumeCover, generatePipelineVolumeBackCover,
generatePipelineVolumeCoverConcepts,
- pipelineVolumePdfUrl,
+ pipelineVolumePdfUrl, pipelineVolumeBeatsSseUrl,
} from '../../services/api';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
-import { usePipelineVolumeBeatsProgress } from '../../hooks/usePipelineVolumeBeatsProgress';
+import { usePipelineProgress } from '../../hooks/usePipelineProgress';
import { useSeriesEditorial } from '../../hooks/useSeriesEditorial';
import { dominant } from '../../lib/editorialRoadmap';
import SeriesLlmPicker from './SeriesLlmPicker';
@@ -1516,7 +1516,7 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp
// frame drives the per-issue label on the button.
const [beatsActive, setBeatsActive] = useState(false);
const [beatsStarting, setBeatsStarting] = useState(false);
- const { latest: beatsLatest } = usePipelineVolumeBeatsProgress(series.id, season.id, { enabled: beatsActive });
+ const { latest: beatsLatest } = usePipelineProgress(pipelineVolumeBeatsSseUrl, [series.id, season.id], { enabled: beatsActive });
// Stable ref over the parent's setter — `handleIssuesUpdate` in
// PipelineSeries is re-allocated every render, so depending on it would
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 8bf4d4cc0e..48b35cb1b5 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -6,7 +6,7 @@
* lives in the always-visible Codex CLI Imagegen section.
*/
-import { useState, useEffect, useCallback, useRef, useId } from 'react';
+import { useState, useEffect, useCallback, useId } from 'react';
import {
Save, Image as ImageIcon, Zap, Wrench, Cloud, Cpu, Globe, AlertTriangle,
Sparkles, Terminal, Key, Check, Trash2
@@ -22,7 +22,7 @@ import {
} from '../../services/api';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
import { resolveCleanersFromConfig } from '../../lib/imageCleaners';
-import { safeParseJSON } from '../../lib/genUtils';
+import { useMediaJobSse } from '../../hooks/useMediaJobSse';
const SDAPI_TOOL_ID = 'sdapi';
const CODEX_TOOL_ID = 'codex-imagegen';
@@ -93,7 +93,9 @@ export function ImageGenTab() {
const [testPrompt, setTestPrompt] = useState(DEFAULT_TEST_PROMPT);
const [rendering, setRendering] = useState(false);
const [renderResult, setRenderResult] = useState(null);
- const renderEsRef = useRef(null);
+ // Shared per-job SSE subscriber — same hook ImageGen/VideoGen use to await
+ // an async render's terminal frame after the kickoff POST returns a jobId.
+ const { attach: attachRenderSse, close: closeRenderSse } = useMediaJobSse('image');
// HuggingFace token state — separate from the main settings save flow because
// it has its own validated endpoints (POST /setup/hf-token + DELETE) and
@@ -136,7 +138,7 @@ export function ImageGenTab() {
// Close any in-flight test-render SSE on unmount so we don't fire setState
// on a torn-down component if the user navigates away mid-render.
- useEffect(() => () => renderEsRef.current?.close(), []);
+ useEffect(() => () => closeRenderSse(), [closeRenderSse]);
useEffect(() => {
Promise.all([getSettings(), getToolsList()])
@@ -326,27 +328,10 @@ export function ImageGenTab() {
// by the time generateImage resolves, so we can short-circuit.
const isAsync = (result?.mode === IMAGE_GEN_MODE.LOCAL || result?.mode === IMAGE_GEN_MODE.CODEX);
if (isAsync && result?.generationId) {
- await new Promise((resolve, reject) => {
- const es = new EventSource(`/api/image-gen/${result.generationId}/events`);
- renderEsRef.current = es;
- const closeEs = () => { es.close(); renderEsRef.current = null; };
- es.onmessage = (e) => {
- const msg = safeParseJSON(e.data);
- if (!msg) return;
- if (msg.type === 'complete') {
- closeEs();
- setRenderResult({ ...result, ...msg.result });
- resolve();
- } else if (msg.type === 'error') {
- closeEs();
- reject(new Error(msg.error || 'Generation failed'));
- } else if (msg.type === 'canceled') {
- closeEs();
- reject(new Error(msg.reason || 'Canceled'));
- }
- };
- es.onerror = () => { closeEs(); reject(new Error('Lost connection during test render')); };
+ const jobResult = await attachRenderSse(result.generationId, {
+ onError: (msg) => new Error(msg.error || 'Generation failed'),
});
+ setRenderResult({ ...result, ...jobResult });
} else {
setRenderResult(result);
}
diff --git a/client/src/components/settings/LocalSetupPanel.jsx b/client/src/components/settings/LocalSetupPanel.jsx
index a609958eff..7958f7cb1c 100644
--- a/client/src/components/settings/LocalSetupPanel.jsx
+++ b/client/src/components/settings/LocalSetupPanel.jsx
@@ -4,17 +4,18 @@ import toast from '../ui/Toast';
import Banner from '../ui/Banner';
import BrailleSpinner from '../BrailleSpinner';
import { usePrevious } from '../../hooks/usePrevious.js';
-import { safeParseJSON } from '../../lib/genUtils.js';
+import { useInstallStream } from '../../hooks/useInstallStream.js';
export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPackagesChanged }) {
const [detecting, setDetecting] = useState(false);
const [check, setCheck] = useState(null); // { required, installed, missing, missingPip }
const [checking, setChecking] = useState(false);
- const [installing, setInstalling] = useState(false);
- const [installLog, setInstallLog] = useState([]);
+ // Pip-install SSE URL — null until the user clicks Install. The `attempt`
+ // counter makes a retry after a failed install produce a fresh URL, so the
+ // stream hook re-subscribes even when the package list is unchanged.
+ const [installUrl, setInstallUrl] = useState(null);
+ const installAttemptRef = useRef(0);
const [creatingVenv, setCreatingVenv] = useState(false);
- const logRef = useRef(null);
- const installEsRef = useRef(null);
// Decouple the input from the parent's persisted path. The VideoGen
// consumer saves on every onPythonPathChange, so wiring the input to the
// prop directly fires a settings PATCH + ~1-2s status re-probe per
@@ -35,11 +36,6 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
commitTimerRef.current = setTimeout(() => commitDraft(value), 800);
};
- // Closing the install EventSource on unmount stops setInstalling /
- // setInstallLog calls firing on a torn-down component if the user
- // navigates away mid pip-install.
- useEffect(() => () => installEsRef.current?.close(), []);
-
const refreshCheck = useCallback(async (path) => {
if (!path) { setCheck(null); return; }
setChecking(true);
@@ -63,10 +59,33 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
return () => clearTimeout(t);
}, [pythonPath, refreshCheck]);
- // Auto-scroll install log to bottom
+ // The shared install-stream hook owns the EventSource lifecycle, log
+ // accumulation (capped at the same 200 lines as before), connection-lost
+ // handling, unmount teardown, and auto-scroll.
+ const {
+ logs: installLog,
+ done: installDone,
+ error: installError,
+ streamStarted: installStarted,
+ logsEndRef,
+ } = useInstallStream(installUrl, {
+ maxLogLines: 200,
+ onComplete: () => {
+ toast.success('Packages installed');
+ refreshCheck(pythonPath);
+ },
+ });
+ const installing = installStarted && !installDone && !installError;
+
+ // Surface an install failure (error frame or dropped connection) once, then
+ // re-check so the package list reflects whatever did get installed.
+ const prevInstallError = usePrevious(installError, null);
useEffect(() => {
- if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
- }, [installLog]);
+ if (installError && !prevInstallError) {
+ toast.error(installError);
+ refreshCheck(pythonPath);
+ }
+ }, [installError, prevInstallError, refreshCheck, pythonPath]);
// Notify the parent whenever local check transitions from "had missing
// packages" to "all installed" — covers manual refresh, terminal installs,
@@ -102,37 +121,8 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
const handleInstall = () => {
if (!check?.missingPip?.length) return;
- setInstalling(true);
- setInstallLog([]);
-
- const url = `/api/image-gen/setup/install?pythonPath=${encodeURIComponent(pythonPath)}&packages=${encodeURIComponent(check.missingPip.join(','))}`;
- const es = new EventSource(url);
- installEsRef.current = es;
-
- es.onmessage = (e) => {
- const event = safeParseJSON(e.data);
- if (!event) return;
- setInstallLog(prev => [...prev.slice(-200), event]);
- if (event.type === 'complete') {
- es.close();
- installEsRef.current = null;
- setInstalling(false);
- toast.success('Packages installed');
- refreshCheck(pythonPath);
- } else if (event.type === 'error') {
- es.close();
- installEsRef.current = null;
- setInstalling(false);
- toast.error(event.message);
- refreshCheck(pythonPath);
- }
- };
-
- es.onerror = () => {
- es.close();
- installEsRef.current = null;
- setInstalling(false);
- };
+ installAttemptRef.current += 1;
+ setInstallUrl(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(pythonPath)}&packages=${encodeURIComponent(check.missingPip.join(','))}&attempt=${installAttemptRef.current}`);
};
const handleCreateVenv = async () => {
@@ -266,14 +256,14 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
)}
{(installing || installLog.length > 0) && (
<pre
- ref={logRef}
className="mt-3 max-h-48 overflow-y-auto text-[11px] font-mono text-gray-400 bg-black/40 border border-port-border rounded p-2 whitespace-pre-wrap"
>
{installLog.map((e, i) => (
- <div key={i} className={e.type === 'error' ? 'text-port-error' : e.type === 'complete' ? 'text-port-success' : ''}>
- {e.message}
+ <div key={i} className={e.kind === 'error' ? 'text-port-error' : e.kind === 'success' ? 'text-port-success' : ''}>
+ {e.text}
</div>
))}
+ <div ref={logsEndRef} />
</pre>
)}
</>
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f1af615a5e..2ed3a87360 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -43,12 +43,8 @@ grep -i "what you want to do" client/src/hooks/README.md
| `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. |
-| `usePipelineManuscriptCompletenessProgress` | Streamed manuscript-completeness review (generate-edits pass) per-chunk SSE. | Manuscript editor review trigger only. |
-| `usePipelineVolumeBeatsProgress` | Volume beat-sheet SSE. | Volume beat-sheet UI only. |
+| `usePipelineProgress` | Id-derived runner SSE stream: builds the URL from `(urlBuilder, ids)`, connects only when every id is truthy. | Any runner SSE keyed by record ids (pipeline auto-run, editorial, manuscript completeness, volume beats, story steps). |
| `useSeriesEditorial` | Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |
-| `useStoryStepProgress` | Generate/refine SSE for one Story Builder step. | Story Builder step generate/refine progress only. |
## Media (annotations, completion, attachments)
@@ -95,6 +91,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `usePopoverPosition` | Viewport-clamped `{ left, top, width }` for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns `{ triggerRef, popoverRef, style, reposition }`; pass `anchorRef` to follow a parent-owned trigger. | Any portal-into-`<body>` menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. |
| `useScrollLock` | Body-scroll lock with ref-count. | Modals, drawers, lightboxes. |
| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |
+| `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. |
| `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |
## Storage & persistence
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 46ac81f99f..0913f8b351 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -58,13 +58,9 @@ export * from './useImageGenProgress.js';
export * from './useImporterProgress.js';
export * from './useInstallStream.js';
export * from './useOpenClawStream.js';
-export * from './usePipelineAutoRunProgress.js';
-export * from './usePipelineEditorialProgress.js';
-export * from './usePipelineManuscriptCompletenessProgress.js';
-export * from './usePipelineVolumeBeatsProgress.js';
+export * from './usePipelineProgress.js';
export * from './useSeriesEditorial.js';
export * from './useSseProgress.js';
-export * from './useStoryStepProgress.js';
export * from './useModelDownloadStatus.js';
// === Media (annotations, completion, attachments) ===
@@ -93,6 +89,7 @@ export * from './useKeyboardHelp.js';
export * from './useLockToggle.js';
export * from './useScrollLock.js';
export * from './useSwipeNav.js';
+export * from './useValidTab.js';
// === Storage & persistence ===
export * from './useLocalStorageBool.js';
diff --git a/client/src/hooks/usePipelineAutoRunProgress.js b/client/src/hooks/usePipelineAutoRunProgress.js
deleted file mode 100644
index fe688f864e..0000000000
--- a/client/src/hooks/usePipelineAutoRunProgress.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { pipelineAutoRunSseUrl } from '../services/api';
-import { useSseProgress } from './useSseProgress';
-
-/**
- * Subscribe to the auto-run-text SSE stream for a pipeline issue. Frame
- * shapes are documented in server/services/pipeline/autoRunner.js#broadcast.
- */
-export function usePipelineAutoRunProgress(issueId, { enabled = true } = {}) {
- const url = issueId ? pipelineAutoRunSseUrl(issueId) : null;
- return useSseProgress(url, { enabled });
-}
diff --git a/client/src/hooks/usePipelineEditorialProgress.js b/client/src/hooks/usePipelineEditorialProgress.js
deleted file mode 100644
index 040f272099..0000000000
--- a/client/src/hooks/usePipelineEditorialProgress.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { pipelineEditorialSseUrl } from '../services/api';
-import { useSseProgress } from './useSseProgress';
-
-/**
- * Subscribe to the series editorial-analysis batch SSE stream. Frame shapes are
- * documented in server/services/pipeline/editorialAnalysisRunner.js
- * (start / issue:start / issue:complete / issue:error / complete / canceled / error).
- */
-export function usePipelineEditorialProgress(seriesId, { enabled = true } = {}) {
- const url = seriesId ? pipelineEditorialSseUrl(seriesId) : null;
- return useSseProgress(url, { enabled });
-}
diff --git a/client/src/hooks/usePipelineManuscriptCompletenessProgress.js b/client/src/hooks/usePipelineManuscriptCompletenessProgress.js
deleted file mode 100644
index 199d08f056..0000000000
--- a/client/src/hooks/usePipelineManuscriptCompletenessProgress.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import { pipelineManuscriptCompletenessSseUrl } from '../services/api';
-import { useSseProgress } from './useSseProgress';
-
-/**
- * Subscribe to the streamed manuscript-completeness review SSE stream (the
- * "generate edits for every finding" pass). Frame shapes are documented in
- * server/services/pipeline/manuscriptCompletenessRunner.js
- * (start / plan / chunk:start / chunk:complete / complete / canceled / error).
- */
-export function usePipelineManuscriptCompletenessProgress(seriesId, { enabled = true } = {}) {
- const url = seriesId ? pipelineManuscriptCompletenessSseUrl(seriesId) : null;
- return useSseProgress(url, { enabled });
-}
diff --git a/client/src/hooks/usePipelineProgress.js b/client/src/hooks/usePipelineProgress.js
new file mode 100644
index 0000000000..8c7062d552
--- /dev/null
+++ b/client/src/hooks/usePipelineProgress.js
@@ -0,0 +1,19 @@
+import { useSseProgress } from './useSseProgress';
+
+/**
+ * Subscribe to a runner SSE progress stream whose URL derives from one or
+ * more record ids. Generalizes the former per-runner wrapper hooks
+ * (auto-run, editorial, manuscript-completeness, volume-beats, story-step):
+ * the stream connects only when every id is truthy, and tears down when one
+ * clears or `enabled` flips false. Frame shapes are documented in the server
+ * runner that backs each `urlBuilder` (e.g.
+ * server/services/pipeline/autoRunner.js#broadcast).
+ *
+ * @param {(...ids: string[]) => string} urlBuilder - SSE-URL builder from services/api
+ * @param {Array} ids - builder arguments; any falsy id keeps the stream closed
+ * @param {{ enabled?: boolean }} [opts]
+ */
+export function usePipelineProgress(urlBuilder, ids, { enabled = true } = {}) {
+ const url = ids.every(Boolean) ? urlBuilder(...ids) : null;
+ return useSseProgress(url, { enabled });
+}
diff --git a/client/src/hooks/usePipelineProgress.test.jsx b/client/src/hooks/usePipelineProgress.test.jsx
new file mode 100644
index 0000000000..29c9bd05e8
--- /dev/null
+++ b/client/src/hooks/usePipelineProgress.test.jsx
@@ -0,0 +1,48 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { renderHook } from '@testing-library/react';
+import { usePipelineProgress } from './usePipelineProgress';
+
+class MockEventSource {
+ constructor(url) {
+ this.url = url;
+ this.onmessage = null;
+ this.onerror = null;
+ this.onopen = null;
+ this.readyState = MockEventSource.OPEN;
+ MockEventSource.instances.push(this);
+ }
+
+ close() { this.readyState = MockEventSource.CLOSED; }
+}
+MockEventSource.CONNECTING = 0;
+MockEventSource.OPEN = 1;
+MockEventSource.CLOSED = 2;
+
+beforeEach(() => {
+ MockEventSource.instances = [];
+ global.EventSource = MockEventSource;
+});
+
+afterEach(() => {
+ delete global.EventSource;
+});
+
+const sseUrl = (a, b) => `/api/thing/${a}/${b}/events`;
+
+describe('usePipelineProgress', () => {
+ it('builds the stream URL from the ids', () => {
+ renderHook(() => usePipelineProgress(sseUrl, ['s1', 'v2']));
+ expect(MockEventSource.instances).toHaveLength(1);
+ expect(MockEventSource.instances[0].url).toBe('/api/thing/s1/v2/events');
+ });
+
+ it('stays closed while any id is falsy', () => {
+ renderHook(() => usePipelineProgress(sseUrl, ['s1', null]));
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+
+ it('stays closed when disabled', () => {
+ renderHook(() => usePipelineProgress(sseUrl, ['s1', 'v2'], { enabled: false }));
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+});
diff --git a/client/src/hooks/usePipelineVolumeBeatsProgress.js b/client/src/hooks/usePipelineVolumeBeatsProgress.js
deleted file mode 100644
index 7885d14867..0000000000
--- a/client/src/hooks/usePipelineVolumeBeatsProgress.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { pipelineVolumeBeatsSseUrl } from '../services/api';
-import { useSseProgress } from './useSseProgress';
-
-/**
- * Subscribe to the volume beat-sheet SSE stream. Frame shapes are documented
- * in server/services/pipeline/volumeBeatsRunner.js.
- */
-export function usePipelineVolumeBeatsProgress(seriesId, seasonId, { enabled = true } = {}) {
- const url = seriesId && seasonId ? pipelineVolumeBeatsSseUrl(seriesId, seasonId) : null;
- return useSseProgress(url, { enabled });
-}
diff --git a/client/src/hooks/useSeriesEditorial.js b/client/src/hooks/useSeriesEditorial.js
index ad3b99a154..ac3696d47d 100644
--- a/client/src/hooks/useSeriesEditorial.js
+++ b/client/src/hooks/useSeriesEditorial.js
@@ -1,11 +1,11 @@
import { useCallback, useEffect, useState } from 'react';
import {
getSeriesEditorial, getSeriesEditorialStatus,
- analyzeSeriesEditorial, cancelSeriesEditorial,
+ analyzeSeriesEditorial, cancelSeriesEditorial, pipelineEditorialSseUrl,
} from '../services/api';
import toast from '../components/ui/Toast';
import { projectAnalyzedPoints } from '../lib/editorialRoadmap';
-import { usePipelineEditorialProgress } from './usePipelineEditorialProgress';
+import { usePipelineProgress } from './usePipelineProgress';
const EMPTY_COVERAGE = { analyzed: 0, total: 0, withContent: 0, stale: 0, noContent: 0 };
@@ -54,7 +54,7 @@ export function useSeriesEditorial(seriesId) {
// Reload when the batch ends. `closed` covers a terminal frame OR a
// dropped/404 stream (fast batch pruned before we attached), so the UI never
// hangs in "Analyzing…" waiting for a frame that will never arrive.
- const { latest, closed } = usePipelineEditorialProgress(seriesId, { enabled: analysisEnabled });
+ const { latest, closed } = usePipelineProgress(pipelineEditorialSseUrl, [seriesId], { enabled: analysisEnabled });
useEffect(() => {
if (closed && analysisEnabled) {
setAnalysisEnabled(false);
diff --git a/client/src/hooks/useSseProgress.js b/client/src/hooks/useSseProgress.js
index 316b5b5ecc..d0e8ad4e15 100644
--- a/client/src/hooks/useSseProgress.js
+++ b/client/src/hooks/useSseProgress.js
@@ -1,6 +1,8 @@
import { useEffect, useRef, useState } from 'react';
-const TERMINAL_TYPES = new Set(['complete', 'canceled', 'error']);
+// Both cancel spellings are terminal: pipeline runners emit `canceled`,
+// the video-timeline renderer emits `cancelled`.
+const TERMINAL_TYPES = new Set(['complete', 'canceled', 'cancelled', 'error']);
/**
* Subscribe to a server-side EventSource stream of JSON-payload progress
diff --git a/client/src/hooks/useSseProgress.test.jsx b/client/src/hooks/useSseProgress.test.jsx
new file mode 100644
index 0000000000..bf5c2780ff
--- /dev/null
+++ b/client/src/hooks/useSseProgress.test.jsx
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { useSseProgress } from './useSseProgress';
+
+// jsdom has no EventSource — minimal mock that records instances and lets a
+// test drive onmessage / onerror by hand (same shape as useInstallStream's).
+class MockEventSource {
+ constructor(url) {
+ this.url = url;
+ this.onmessage = null;
+ this.onerror = null;
+ this.onopen = null;
+ this.closed = false;
+ this.readyState = MockEventSource.OPEN;
+ MockEventSource.instances.push(this);
+ }
+
+ close() { this.closed = true; this.readyState = MockEventSource.CLOSED; }
+
+ emit(payload) { this.onmessage?.({ data: JSON.stringify(payload) }); }
+
+ fail() { this.readyState = MockEventSource.CLOSED; this.onerror?.(); }
+}
+MockEventSource.CONNECTING = 0;
+MockEventSource.OPEN = 1;
+MockEventSource.CLOSED = 2;
+
+const last = () => MockEventSource.instances[MockEventSource.instances.length - 1];
+
+beforeEach(() => {
+ MockEventSource.instances = [];
+ global.EventSource = MockEventSource;
+});
+
+afterEach(() => {
+ delete global.EventSource;
+});
+
+describe('useSseProgress', () => {
+ it('does not open a stream when url is null or enabled is false', () => {
+ renderHook(() => useSseProgress(null));
+ renderHook(() => useSseProgress('/x', { enabled: false }));
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+
+ it('accumulates frames and tracks the latest', () => {
+ const { result } = renderHook(() => useSseProgress('/x'));
+ act(() => {
+ last().emit({ type: 'progress', progress: 0.25 });
+ last().emit({ type: 'progress', progress: 0.5 });
+ });
+ expect(result.current.frames).toHaveLength(2);
+ expect(result.current.latest).toEqual({ type: 'progress', progress: 0.5 });
+ expect(result.current.closed).toBe(false);
+ });
+
+ it.each(['complete', 'canceled', 'cancelled', 'error'])(
+ 'closes the stream on a terminal %s frame',
+ (type) => {
+ const { result } = renderHook(() => useSseProgress('/x'));
+ act(() => { last().emit({ type }); });
+ expect(result.current.closed).toBe(true);
+ expect(result.current.isOpen).toBe(false);
+ expect(last().closed).toBe(true);
+ },
+ );
+
+ it('marks the stream closed on a terminal connection failure', () => {
+ const { result } = renderHook(() => useSseProgress('/x'));
+ act(() => { last().fail(); });
+ expect(result.current.closed).toBe(true);
+ expect(result.current.latest).toBeNull();
+ });
+
+ it('resets state when the url changes', () => {
+ const { result, rerender } = renderHook(({ url }) => useSseProgress(url), {
+ initialProps: { url: '/a' },
+ });
+ act(() => { last().emit({ type: 'complete' }); });
+ expect(result.current.closed).toBe(true);
+ rerender({ url: '/b' });
+ expect(result.current.closed).toBe(false);
+ expect(result.current.frames).toHaveLength(0);
+ expect(last().url).toBe('/b');
+ });
+});
diff --git a/client/src/hooks/useStoryStepProgress.js b/client/src/hooks/useStoryStepProgress.js
deleted file mode 100644
index 648d9e9efd..0000000000
--- a/client/src/hooks/useStoryStepProgress.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import { storyStepProgressSseUrl } from '../services/api';
-import { useSseProgress } from './useSseProgress';
-
-/**
- * Subscribe to the generate/refine SSE stream for one Story Builder step. Frame
- * shapes are documented in server/services/storyBuilderRunner.js. Enable only
- * after the kickoff POST resolves (so the run is registered server-side before
- * the EventSource connects) — see StoryBuilder.jsx's step runner.
- */
-export function useStoryStepProgress(sessionId, stepId, { enabled = true } = {}) {
- const url = sessionId && stepId ? storyStepProgressSseUrl(sessionId, stepId) : null;
- return useSseProgress(url, { enabled });
-}
diff --git a/client/src/hooks/useValidTab.js b/client/src/hooks/useValidTab.js
new file mode 100644
index 0000000000..26fe448093
--- /dev/null
+++ b/client/src/hooks/useValidTab.js
@@ -0,0 +1,18 @@
+import { useMemo } from 'react';
+import { useParams } from 'react-router-dom';
+
+/**
+ * Resolve the active tab for a tabbed page from the `:tab` URL param.
+ * Returns the param when it names a real tab, otherwise `fallback` — so a
+ * hand-edited or stale deep link degrades to the default tab instead of a
+ * blank view. Accepts the page's TABS array (`{ id }` objects) or plain id
+ * strings.
+ */
+export function useValidTab(tabs, fallback) {
+ const { tab } = useParams();
+ const validIds = useMemo(
+ () => new Set(tabs.map((t) => (typeof t === 'string' ? t : t.id))),
+ [tabs],
+ );
+ return validIds.has(tab) ? tab : fallback;
+}
diff --git a/client/src/hooks/useValidTab.test.jsx b/client/src/hooks/useValidTab.test.jsx
new file mode 100644
index 0000000000..6d62aa74cd
--- /dev/null
+++ b/client/src/hooks/useValidTab.test.jsx
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest';
+import { renderHook } from '@testing-library/react';
+import { MemoryRouter, Routes, Route } from 'react-router-dom';
+import { useValidTab } from './useValidTab';
+
+const TABS = [
+ { id: 'overview', label: 'Overview' },
+ { id: 'runs', label: 'Runs' },
+];
+
+const wrapperAt = (path) => ({ children }) => (
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route path="/page/:tab?" element={children} />
+ </Routes>
+ </MemoryRouter>
+);
+
+describe('useValidTab', () => {
+ it('returns the tab param when it names a real tab', () => {
+ const { result } = renderHook(() => useValidTab(TABS, 'overview'), {
+ wrapper: wrapperAt('/page/runs'),
+ });
+ expect(result.current).toBe('runs');
+ });
+
+ it('falls back when the tab param is not a valid id', () => {
+ const { result } = renderHook(() => useValidTab(TABS, 'overview'), {
+ wrapper: wrapperAt('/page/bogus'),
+ });
+ expect(result.current).toBe('overview');
+ });
+
+ it('falls back when no tab param is present', () => {
+ const { result } = renderHook(() => useValidTab(TABS, 'overview'), {
+ wrapper: wrapperAt('/page'),
+ });
+ expect(result.current).toBe('overview');
+ });
+
+ it('accepts plain id strings as the tabs list', () => {
+ const { result } = renderHook(() => useValidTab(['a', 'b'], 'a'), {
+ wrapper: wrapperAt('/page/b'),
+ });
+ expect(result.current).toBe('b');
+ });
+});
diff --git a/client/src/pages/Calendar.jsx b/client/src/pages/Calendar.jsx
index b4d07852b0..0db286ab13 100644
--- a/client/src/pages/Calendar.jsx
+++ b/client/src/pages/Calendar.jsx
@@ -1,9 +1,10 @@
-import { useParams, useNavigate } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
import { CalendarDays, Calendar as CalendarIcon, ClipboardList, Clock, Columns, LayoutGrid, RefreshCw, Settings } from 'lucide-react';
import { useState, useEffect, useCallback } from 'react';
import * as api from '../services/api';
import BrailleSpinner from '../components/BrailleSpinner';
import TabPills from '../components/ui/TabPills';
+import { useValidTab } from '../hooks/useValidTab';
import AgendaTab from '../components/calendar/AgendaTab';
import DayView from '../components/calendar/DayView';
@@ -28,10 +29,8 @@ export const TABS = [
];
export default function Calendar() {
- const { tab } = useParams();
const navigate = useNavigate();
- const VALID_TABS = TABS.map(t => t.id);
- const activeTab = VALID_TABS.includes(tab) ? tab : 'agenda';
+ const activeTab = useValidTab(TABS, 'agenda');
const [accounts, setAccounts] = useState([]);
const [loading, setLoading] = useState(true);
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index cdcf8beefb..cb918e3373 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -4,6 +4,7 @@ import { useSocket } from '../hooks/useSocket';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import useNextEvalCountdown from '../hooks/useNextEvalCountdown';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useValidTab } from '../hooks/useValidTab';
import * as api from '../services/api';
import { Play, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp, ChevronLeft, ChevronRight, Brain, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -60,8 +61,7 @@ const CANVAS_AVATAR_STYLES = new Set([
export default function ChiefOfStaff() {
const { tab } = useParams();
const navigate = useNavigate();
- const validTabIds = useMemo(() => new Set(TABS.map(t => t.id)), []);
- const activeTab = (tab && validTabIds.has(tab)) ? tab : 'tasks';
+ const activeTab = useValidTab(TABS, 'tasks');
const [status, setStatus] = useState(null);
const [tasks, setTasks] = useState({ user: null, cos: null });
@@ -154,12 +154,13 @@ export default function ChiefOfStaff() {
setActiveAgentMeta(runningAgent?.metadata || null);
}, [deriveAgentState]);
- // Redirect unknown tab IDs to the default tab
+ // Redirect unknown tab IDs to the default tab — `activeTab !== tab` only
+ // when the param failed validation and fell back.
useEffect(() => {
- if (tab && !validTabIds.has(tab)) {
+ if (tab && tab !== activeTab) {
navigate('/cos/tasks', { replace: true });
}
- }, [tab, validTabIds, navigate]);
+ }, [tab, activeTab, navigate]);
// Reduced polling since most updates come via socket events
useAutoRefetch(fetchData, 30_000, { pollOnly: true });
diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsx
index 4a1571eb3e..8c6598cf69 100644
--- a/client/src/pages/CreativeDirectorDetail.jsx
+++ b/client/src/pages/CreativeDirectorDetail.jsx
@@ -15,6 +15,7 @@ import RunsTab from '../components/creative-director/RunsTab.jsx';
import ActiveAgentsBanner from '../components/creative-director/ActiveAgentsBanner.jsx';
import { getCosAgents } from '../services/apiAgents.js';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useValidTab } from '../hooks/useValidTab';
const TERMINAL_PROJECT_STATUSES = new Set(['complete', 'failed', 'paused', 'draft']);
@@ -25,12 +26,10 @@ const TABS = [
{ id: 'runs', label: 'Runs' },
];
-const VALID_TAB_IDS = new Set(TABS.map((t) => t.id));
-
export default function CreativeDirectorDetail() {
- const { id, tab } = useParams();
+ const { id } = useParams();
const navigate = useNavigate();
- const activeTab = VALID_TAB_IDS.has(tab) ? tab : 'overview';
+ const activeTab = useValidTab(TABS, 'overview');
const [project, setProject] = useState(null);
const [loading, setLoading] = useState(true);
const [activeAgents, setActiveAgents] = useState([]);
diff --git a/client/src/pages/FeatureAgentDetail.jsx b/client/src/pages/FeatureAgentDetail.jsx
index 68a42561b3..2133535686 100644
--- a/client/src/pages/FeatureAgentDetail.jsx
+++ b/client/src/pages/FeatureAgentDetail.jsx
@@ -4,7 +4,8 @@ import { Wand2, ArrowLeft } from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { TABS, VALID_TAB_IDS } from '../components/feature-agents/constants';
+import { TABS } from '../components/feature-agents/constants';
+import { useValidTab } from '../hooks/useValidTab';
import OverviewTab from '../components/feature-agents/OverviewTab';
import ConfigTab from '../components/feature-agents/ConfigTab';
import RunsTab from '../components/feature-agents/RunsTab';
@@ -13,10 +14,10 @@ import GitTab from '../components/feature-agents/GitTab';
import BrailleSpinner from '../components/BrailleSpinner';
export default function FeatureAgentDetail() {
- const { id, tab } = useParams();
+ const { id } = useParams();
const navigate = useNavigate();
const isCreate = !id;
- const activeTab = VALID_TAB_IDS.has(tab) ? tab : 'overview';
+ const activeTab = useValidTab(TABS, 'overview');
const [agent, setAgent] = useState(null);
const [loading, setLoading] = useState(!isCreate);
diff --git a/client/src/pages/Goals.jsx b/client/src/pages/Goals.jsx
index 93214ca711..540bc613e2 100644
--- a/client/src/pages/Goals.jsx
+++ b/client/src/pages/Goals.jsx
@@ -5,6 +5,7 @@ import * as api from '../services/api';
import GoalsListView from '../components/goals/GoalsListView';
import MortalLoomBanner from '../components/MortalLoomBanner';
import BrailleSpinner from '../components/BrailleSpinner';
+import { useValidTab } from '../hooks/useValidTab';
const GoalsTreeView = lazy(() => import('../components/goals/GoalsTreeView'));
@@ -14,11 +15,9 @@ export const TABS = [
{ id: 'tree', label: 'Tree', icon: TreePine }
];
-const VALID_TABS = new Set(TABS.map(t => t.id));
-
export default function Goals() {
const { tab: rawTab } = useParams();
- const tab = VALID_TABS.has(rawTab) ? rawTab : 'list';
+ const tab = useValidTab(TABS, 'list');
const navigate = useNavigate();
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
@@ -32,10 +31,11 @@ export default function Goals() {
useEffect(() => { loadData(); }, [loadData]);
useEffect(() => {
- if (rawTab && !VALID_TABS.has(rawTab)) {
+ // `tab !== rawTab` only when the param failed validation and fell back.
+ if (rawTab && rawTab !== tab) {
navigate('/goals/list', { replace: true });
}
- }, [rawTab, navigate]);
+ }, [rawTab, tab, navigate]);
const handleTabChange = (tabId) => {
navigate(`/goals/${tabId}`, { replace: true });
diff --git a/client/src/pages/Insights.jsx b/client/src/pages/Insights.jsx
index 4d20511660..088476e494 100644
--- a/client/src/pages/Insights.jsx
+++ b/client/src/pages/Insights.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
-import { useParams, useNavigate } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
+import { useValidTab } from '../hooks/useValidTab';
import { Dna, Palette, Link2, Lightbulb, ArrowRight } from 'lucide-react';
import {
getGenomeHealthCorrelations,
@@ -20,8 +21,6 @@ export const TABS = [
{ id: 'cross-domain', label: 'Cross-Domain Patterns', icon: Link2 }
];
-const VALID_TAB_IDS = new Set(TABS.map(t => t.id));
-
function SummaryCardSkeleton() {
return (
<div className="bg-port-card border border-port-border rounded-lg p-6 animate-pulse">
@@ -177,9 +176,8 @@ function OverviewTab() {
}
export default function Insights() {
- const { tab } = useParams();
const navigate = useNavigate();
- const activeTab = VALID_TAB_IDS.has(tab) ? tab : 'overview';
+ const activeTab = useValidTab(TABS, 'overview');
const renderTabContent = () => {
switch (activeTab) {
diff --git a/client/src/pages/Messages.jsx b/client/src/pages/Messages.jsx
index 76a715bf1b..9a972e9225 100644
--- a/client/src/pages/Messages.jsx
+++ b/client/src/pages/Messages.jsx
@@ -1,9 +1,10 @@
-import { useParams, useNavigate } from 'react-router-dom';
+import { useNavigate } from 'react-router-dom';
import { Mail, RefreshCw, Settings } from 'lucide-react';
import { useState, useEffect, useCallback } from 'react';
import * as api from '../services/api';
import BrailleSpinner from '../components/BrailleSpinner';
import TabPills from '../components/ui/TabPills';
+import { useValidTab } from '../hooks/useValidTab';
import InboxTab from '../components/messages/InboxTab';
import ConfigTab from '../components/messages/ConfigTab';
@@ -19,10 +20,8 @@ export const TABS = [
];
export default function Messages() {
- const { tab } = useParams();
const navigate = useNavigate();
- const VALID_TABS = TABS.map(t => t.id);
- const activeTab = VALID_TABS.includes(tab) ? tab : 'inbox';
+ const activeTab = useValidTab(TABS, 'inbox');
const [accounts, setAccounts] = useState([]);
const [loading, setLoading] = useState(true);
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index 4debeab204..b77f758acd 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -17,10 +17,10 @@ import Modal from '../components/ui/Modal';
import TabPills from '../components/ui/TabPills';
import {
getPipelineIssue, getPipelineSeries, updatePipelineIssue,
- startPipelineAutoRunText, cancelPipelineAutoRunText,
+ startPipelineAutoRunText, cancelPipelineAutoRunText, pipelineAutoRunSseUrl,
PIPELINE_STAGES, PIPELINE_TAB_STAGES, PIPELINE_STAGE_LABELS,
} from '../services/api';
-import { usePipelineAutoRunProgress } from '../hooks/usePipelineAutoRunProgress';
+import { usePipelineProgress } from '../hooks/usePipelineProgress';
import { useLockToggle } from '../hooks/useLockToggle';
import IdeaStage from '../components/pipeline/stages/IdeaStage';
import ProseStage from '../components/pipeline/stages/ProseStage';
@@ -101,7 +101,7 @@ export default function PipelineIssue() {
// Close the settings modal whenever the active stage changes so it doesn't
// reopen unexpectedly when the user returns to a previously-visited stage.
useEffect(() => { setSettingsOpen(false); }, [stageId]);
- const { latest, frames } = usePipelineAutoRunProgress(issueId, { enabled: autoRunActive });
+ const { latest, frames } = usePipelineProgress(pipelineAutoRunSseUrl, [issueId], { enabled: autoRunActive });
useEffect(() => {
let canceled = false;
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index b5a266d110..eb1c1fc49d 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -34,7 +34,7 @@ import {
} from 'lucide-react';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
-import { usePipelineManuscriptCompletenessProgress } from '../hooks/usePipelineManuscriptCompletenessProgress';
+import { usePipelineProgress } from '../hooks/usePipelineProgress';
import { filterGenerationModels, mergeModelLists, localBackendForProvider, modelOptionLabel } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import { locateAnchors } from '../lib/manuscriptAnchors';
@@ -49,6 +49,7 @@ import {
savePipelineManuscriptSection, restorePipelineStageVersion,
analyzePipelineManuscriptCompleteness, startPipelineManuscriptCompleteness,
cancelPipelineManuscriptCompleteness, getPipelineManuscriptCompletenessStatus, getProviders,
+ pipelineManuscriptCompletenessSseUrl,
} from '../services/api';
// Stable empty array so sections that gain no comments/spans don't get a fresh
@@ -213,7 +214,7 @@ export default function PipelineManuscriptEditor() {
// re-fetches the review (comments now carry pre-built fixes). `closed` flips
// true when the stream ends for ANY reason, including a non-terminal death
// (attach 404, dropped connection) where no terminal frame ever arrives.
- const { latest: reviewLatest, closed: reviewClosed } = usePipelineManuscriptCompletenessProgress(seriesId, { enabled: reviewActive });
+ const { latest: reviewLatest, closed: reviewClosed } = usePipelineProgress(pipelineManuscriptCompletenessSseUrl, [seriesId], { enabled: reviewActive });
// On mount, re-attach to an in-flight streamed run (e.g. after a reload mid-run).
useEffect(() => {
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 1be4775a90..596fc9e1bc 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -16,12 +16,12 @@ import {
import toast from '../components/ui/Toast';
import Banner from '../components/ui/Banner';
import { useLockToggle } from '../hooks/useLockToggle';
-import { useStoryStepProgress } from '../hooks/useStoryStepProgress';
+import { usePipelineProgress } from '../hooks/usePipelineProgress';
import {
getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,
updateStorySession, setStoryCurrentStep, lockStoryStep, unlockStoryStep,
generateStoryStep, refineStoryStep, setStoryIssueLock, generateStoryIssues,
- setStorySessionSync, reconcileStorySession,
+ setStorySessionSync, reconcileStorySession, storyStepProgressSseUrl,
getUniverse, getPipelineSeries, listPipelineIssues,
analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,
getProviders, updateUniverse,
@@ -502,7 +502,9 @@ function useStepStream(sessionId, stepId) {
// the PREVIOUS run's terminal frame. Gating the terminal branches on a frame's
// runId stops that stale frame from firing the new run's onComplete instantly.
const runIdRef = useRef(null);
- const { latest, closed } = useStoryStepProgress(sessionId, stepId, { enabled: active });
+ // Enable only after the kickoff POST resolves (so the run is registered
+ // server-side before the EventSource connects) — see the step runner below.
+ const { latest, closed } = usePipelineProgress(storyStepProgressSseUrl, [sessionId, stepId], { enabled: active });
const settle = useCallback(() => {
setActive(false); setPhase(''); setOp(null);
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index 29843ce141..2cb90c5fbb 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -20,6 +20,7 @@ import {
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import { formatTimecode } from '../utils/formatters';
+import { useSseProgress } from '../hooks/useSseProgress';
// Map project-time t (every clip contributes its trimmed duration) to the
// (clipIndex, withinClipSec) pair the preview <video> element needs. The
@@ -405,39 +406,40 @@ export default function VideoTimelineEditor() {
}
};
- // SSE progress wiring — opens an EventSource on the render jobId, updates
- // the progress bar, and on 'complete' navigates to Media History focused
- // on the new clip.
+ // SSE progress wiring — subscribes to the render jobId's event stream (via
+ // the shared useSseProgress lifecycle), updates the progress bar, and on
+ // 'complete' navigates to Media History focused on the new clip. Frame
+ // shapes come from server/services/videoTimeline/local.js
+ // (progress / complete / error / cancelled).
+ const { latest: renderFrame, closed: renderStreamClosed } = useSseProgress(
+ renderJobId ? `/api/video-timeline/${renderJobId}/events` : null,
+ { enabled: !!renderJobId },
+ );
useEffect(() => {
- if (!renderJobId) return;
- const es = new EventSource(`/api/video-timeline/${renderJobId}/events`);
- es.onmessage = (ev) => {
- const data = JSON.parse(ev.data);
- if (data.type === 'progress') setRenderProgress(data.progress);
- else if (data.type === 'complete') {
- toast.success('Timeline rendered');
- es.close();
- setRenderJobId(null);
- navigate(`/media/history?focus=${data.result.id}`);
- } else if (data.type === 'error') {
- toast.error(data.error || 'Render failed');
- es.close();
- setRenderJobId(null);
- } else if (data.type === 'cancelled') {
- toast('Render cancelled');
- es.close();
- setRenderJobId(null);
- setRenderProgress(0);
- }
- };
- es.onerror = () => {
- es.close();
- toast.error('Lost connection to render — check Media History');
+ if (!renderJobId || !renderFrame) return;
+ if (renderFrame.type === 'progress') setRenderProgress(renderFrame.progress);
+ else if (renderFrame.type === 'complete') {
+ toast.success('Timeline rendered');
+ setRenderJobId(null);
+ navigate(`/media/history?focus=${renderFrame.result.id}`);
+ } else if (renderFrame.type === 'error') {
+ toast.error(renderFrame.error || 'Render failed');
+ setRenderJobId(null);
+ } else if (renderFrame.type === 'cancelled') {
+ toast('Render cancelled');
setRenderJobId(null);
setRenderProgress(0);
- };
- return () => es.close();
- }, [renderJobId, navigate]);
+ }
+ }, [renderJobId, renderFrame, navigate]);
+ useEffect(() => {
+ // Stream ended without a terminal frame — connection lost. Terminal frames
+ // are handled (and clear renderJobId) in the frame effect above.
+ if (!renderJobId || !renderStreamClosed) return;
+ if (['complete', 'error', 'cancelled'].includes(renderFrame?.type)) return;
+ toast.error('Lost connection to render — check Media History');
+ setRenderJobId(null);
+ setRenderProgress(0);
+ }, [renderJobId, renderStreamClosed, renderFrame]);
if (loading) return <div className="text-gray-500 text-sm">Loading project…</div>;
if (error || !project) {
diff --git a/client/src/services/apiStoryBuilder.js b/client/src/services/apiStoryBuilder.js
index b2eb4a96c0..c2f6a5d708 100644
--- a/client/src/services/apiStoryBuilder.js
+++ b/client/src/services/apiStoryBuilder.js
@@ -52,7 +52,7 @@ export const unlockStoryStep = (id, stepId, options = {}) =>
// generate / refine kick off a background run and return { runId, alreadyRunning,
// sseUrl }. Subscribe to progress via storyStepProgressSseUrl (see
-// hooks/useStoryStepProgress.js); the result lands on the stream's `complete`
+// hooks/usePipelineProgress.js); the result lands on the stream's `complete`
// frame and the persisted content is read back by refetching the session view.
export const generateStoryStep = (id, stepId, payload = {}, options = {}) =>
request(`/story-builder/${id}/steps/${stepId}/generate`, {