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: give media render start, resume and cancel one job owner (#9929)
Adam Eivy4fe5dfa6cbb0
diff --git a/client/src/asyncEffectDisposalConventions.test.js b/client/src/asyncEffectDisposalConventions.test.jsindex dfd4f16d86..646e2c0cfb 100644--- a/client/src/asyncEffectDisposalConventions.test.js+++ b/client/src/asyncEffectDisposalConventions.test.js@@ -101,6 +101,8 @@ const ALLOWED = {'deps are [open] only — a drawer preload with no record identity to switch','src/components/voice/VoiceWidget.jsx':'deps are [enabled, navigate] — a session toggle, not a record identity',+ 'src/hooks/useImageGenPageRuntime.js':+ 'the active-job read is adopted through useMediaJobSse.start, whose run owner drops it when superseded or unmounted (ifIdle makes a re-run a no-op)','src/pages/AIProviders.jsx':'deps are [fleetSetupOpen] only — a modal preload with no record identity to switch','src/pages/Browser.jsx':diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex d2c540c2bd..375dbe7235 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -32,7 +32,7 @@ import FalModelSelect from '../imageGen/FalModelSelect';import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, FAL_IMAGE_DEFAULT_MODEL, falImageFamily, LOCAL_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, localModelSelectOptions, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';import { resolveCleanersFromConfig } from '../../lib/imageCleaners';import { withUnlistedOption } from '../../lib/withUnlistedOption';-import { useMediaJobSse } from '../../hooks/useMediaJobSse';+import { useMediaJobSse, isMediaRunEnded } from '../../hooks/useMediaJobSse';import { useAgyModels } from '../../hooks/useAgyModels';import { useHfTokenStatus } from '../../hooks/useHfTokenStatus';import useLocalImageModels from '../../hooks/useLocalImageModels';@@ -243,9 +243,10 @@ export function ImageGenTab() {const testModeId = useId();const [rendering, setRendering] = useState(false);const [renderResult, setRenderResult] = useState(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');+ // Shared media-run owner — same hook ImageGen/VideoGen use to await an async+ // render's terminal frame after the kickoff POST returns a jobId. It also+ // detaches the stream and drops the pending kickoff when the tab unmounts.+ const { start: startRenderRun } = 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@@ -329,10 +330,6 @@ export function ImageGenTab() {toast.success('Saved key cleared. External credentials may still apply.');};- // 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(() => () => closeRenderSse(), [closeRenderSse]);-useEffect(() => {Promise.all([getSettings({ silent: true }), getToolsList({ silent: true })]).then(([s, tools]) => {@@ -747,24 +744,27 @@ export function ImageGenTab() {// prevents this branch from running with unsaved changes, but resolving// through `saved` makes the contract explicit. Codex is async like local// (returns a job descriptor immediately) so the SSE branch handles it.- const result = await generateImage({ prompt: testPrompt.trim(), mode: effectiveTestMode }, { silent: true });// Local + Codex modes return immediately after spawning the child —// the PNG isn't on disk yet. Subscribe to the per-job SSE and only// mark the render complete on the `complete` event (or fail on// `error`). External mode awaits internally and the file is on disk- // by the time generateImage resolves, so we can short-circuit.- const isAsync = (result?.mode === IMAGE_GEN_MODE.LOCAL || isCloudCliMode(result?.mode));- if (isAsync && result?.generationId) {- const jobResult = await attachRenderSse(result.generationId, {+ // by the time generateImage resolves, so it completes synchronously+ // (no job id to follow).+ const result = await startRenderRun(+ () => generateImage({ prompt: testPrompt.trim(), mode: effectiveTestMode }, { silent: true }),+ (ack) => ({onError: (msg) => new Error(msg.error || 'Generation failed'),- });- setRenderResult({ ...result, ...jobResult });- } else {- setRenderResult(result);- }+ onComplete: (msg) => ({ ...ack, ...msg.result }),+ }),+ {+ jobIdOf: (ack) => ((ack?.mode === IMAGE_GEN_MODE.LOCAL || isCloudCliMode(ack?.mode)) ? ack.generationId : null),+ },+ );+ setRenderResult(result);toast.success('Test render complete');} catch (err) {- toast.error(err.message || 'Test render failed');+ // A detached run (tab unmounted mid-render) has nothing left to report to.+ if (!isMediaRunEnded(err)) toast.error(err.message || 'Test render failed');} finally {setRendering(false);}diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsxindex 690af81b06..d58c009019 100644--- a/client/src/components/settings/ImageGenTab.test.jsx+++ b/client/src/components/settings/ImageGenTab.test.jsx@@ -33,9 +33,6 @@ vi.mock('./LocalSetupPanel', () => ({}));// The runtime card's install modal opens its own SSE stream.vi.mock('../imageGen/Flux2InstallModal', () => ({ default: () => null }));-vi.mock('../../hooks/useMediaJobSse', () => ({- useMediaJobSse: () => ({ attach: vi.fn(), close: vi.fn() }),-}));import {getSettings, getToolsList, updateSettings, listAgyImageModels, listImageModels, getImageGenStatus,@@ -46,13 +43,14 @@ import { ImageGenTab, MEDIA_TABS } from './ImageGenTab';import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';const renderTab = async (initialEntries = ['/media/image']) => {- render(+ const view = render(<MemoryRouter initialEntries={initialEntries}><ImageGenTab /></MemoryRouter>,);// Cards render only after the settings fetch resolves.await waitFor(() => expect(screen.getByRole('tablist')).toBeTruthy());+ return view;};beforeEach(() => {@@ -432,6 +430,25 @@ describe('ImageGenTab — Test Render backend picker (#4128)', () => {expect(generateImage.mock.calls[0][0].mode).toBe('grok');});+ it('opens no render stream when the tab unmounts before the test render is acknowledged', async () => {+ getSettings.mockResolvedValue(multiBackendSettings);+ let acknowledge;+ generateImage.mockReturnValue(new Promise((resolve) => { acknowledge = resolve; }));+ const OriginalEventSource = globalThis.EventSource;+ const streams = [];+ globalThis.EventSource = function EventSourceStub(url) { streams.push(url); this.close = vi.fn(); };+ try {+ const view = await renderTab(['/media/image?mediaTab=test']);+ fireEvent.click(screen.getByRole('button', { name: /Render Test Image/i }));+ await waitFor(() => expect(generateImage).toHaveBeenCalled());+ view.unmount();+ await act(async () => { acknowledge({ mode: 'local', generationId: 'job-durable' }); });+ expect(streams).toEqual([]);+ } finally {+ globalThis.EventSource = OriginalEventSource;+ }+ });+it('keeps the saved default selectable even when it is not otherwise renderable', async () => {// External is the saved default with a blank URL: the server still routes// the render there, so the select must not silently show a differentdiff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 769ef47bec..8d66c81612 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -54,7 +54,7 @@ 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. || `useSceneRenderLifecycle` | One Music Video board lane's async-render lifecycle: owns the per-scene spinner state (`genScenes`), job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + `*-gen:completed/failed/canceled` socket subscription (with running-cancel toast disambiguation). Returns `{ genScenes, startScene, clearScene, trackJob }`. | A board lane that kicks media-job renders per scene and clears spinners from terminal events (reference frame, i2v clip). One call per lane. || `useSlotInFlight` | Whether a render slot (`{ jobId, filename }`) has an in-flight render; returns `{ inFlight, setStatus }`. A present `filename` (or 5s grace on a stale/expired job) clears `inFlight` so the render button never sticks "loading". | A render button that should disable + spin only while its own slot is actually rendering (comic pages, covers). Wire `setStatus` to the slot's `MediaJobThumb` `onStatus`. |-| `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). |+| `useMediaJobSse` | The one owner of a displayed media render's lifecycle: `start(kickoff, handlers, { jobIdOf, ifIdle, onKickoffError })` runs the POST (or an active-job read), adopts the acknowledged job and awaits its `/{kind}-gen/:id/events` terminal frame; `cancel()` cancels only that job (before the acknowledgement it cancels the eventual job once, opening no stream); `dispose()` (also on unmount) detaches without cancelling durable work. A cancelled/detached/superseded run settles once with an error `isMediaRunEnded()` recognises. `attach()` stays the bare transport. | POST-then-attach (or resume-then-attach) media render flows — Video Gen, Image Gen, Settings Test Render. Don't keep a page-local job id / run token / reject ref / raw `EventSource` close. || `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface 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). || `useStoryStepRuns` | Story Builder step generate/refine runs hoisted above the step rail: `<StoryStepRunProvider sessionId>` owns one run slot per step id (SSE subscription, phase, `onComplete`/`onError` handlers, arbitrary `meta`), `useStoryStepRun(stepId)` reads/drives it. | Any Story Builder surface that starts a step run — the panel unmounts on rail navigation, so run state must not live in it (#3905). |diff --git a/client/src/hooks/useImageGenPageRuntime.js b/client/src/hooks/useImageGenPageRuntime.jsindex f67522068f..46915b2643 100644--- a/client/src/hooks/useImageGenPageRuntime.js+++ b/client/src/hooks/useImageGenPageRuntime.js@@ -14,7 +14,7 @@ import { useSocketResource } from './useSocketResource';import { useFederatedMediaTarget } from './useFederatedMediaTarget';import { useImageGenProgress } from './useImageGenProgress';import { useMediaCompletionRefresh } from './useMediaCompletionRefresh';-import { useMediaJobSse } from './useMediaJobSse';+import { useMediaJobSse, isMediaRunEnded } from './useMediaJobSse';import { useModelDownloadStatus } from './useModelDownloadStatus';import { useHfTokenStatus } from './useHfTokenStatus';import { useAgyModels } from './useAgyModels';@@ -140,7 +140,11 @@ export function useImageGenPageRuntime() {const [result, setResult] = useState(null);const [error, setError] = useState(null);const [regenInfo, setRegenInfo] = useState(null);- const { attach: attachJobEvents, eventSourceRef } = useMediaJobSse('image');+ // One run owner for the displayed render: Cancel targets exactly its job, and+ // unmount detaches the stream without cancelling accepted durable work.+ const { start: startRun, cancel: cancelRun } = useMediaJobSse('image', {+ cancelJob: (jobId) => cancelImageGen({ jobId }),+ });const { progress: externalProgress, begin: beginGenerate, end: endGenerate, resume: resumeGenerate } = useImageGenProgress();useMediaCompletionRefresh({ onImageCompleted: gallery.refreshRecent });const modelDownload = useModelDownloadStatus({ kind: 'image' });@@ -181,27 +185,28 @@ export function useImageGenPageRuntime() {}, [derived.sharesFlux2Venv, fields.modelId, refreshFlux2Status]);useEffect(() => {- let active = true;- getActiveImageJob().then(({ activeJob }) => {- if (!active || !activeJob) return;- actions.restoreActiveJob(activeJob);- setGenerating(true);- setStatusMsg('Resuming…');- resumeGenerate(activeJob);- attachJobEvents(activeJob.generationId, {+ // Adopt the job still running server-side after a reload. `ifIdle` yields to+ // a render this tab already owns; the owner creates no stream (or+ // presentation) when the page unmounts before the read resolves.+ startRun(+ () => getActiveImageJob().then(({ activeJob }) => activeJob),+ {+ onAcknowledged: (activeJob) => {+ actions.restoreActiveJob(activeJob);+ setGenerating(true);+ setStatusMsg('Resuming…');+ resumeGenerate(activeJob);+ },onStatus: (message) => setStatusMsg(message.message),onProgress: (message) => setLocalProgress({ progress: message.progress }),onComplete: () => setGenerating(false),onError: () => setGenerating(false),onCanceled: () => setGenerating(false),onConnectionError: () => setGenerating(false),- }).catch(() => {});- }).catch(() => {});- return () => {- active = false;- eventSourceRef.current?.close();- };- }, [actions.restoreActiveJob, attachJobEvents, eventSourceRef, resumeGenerate]);+ },+ { ifIdle: true, jobIdOf: (activeJob) => activeJob?.generationId },+ ).catch(() => {});+ }, [actions.restoreActiveJob, startRun, resumeGenerate]);const regenAvailable = !!regenInfo?.available;const refreshRegenAvailability = useCallback(() => {@@ -309,11 +314,13 @@ export function useImageGenPageRuntime() {return { payload, data };};- const startLocalGeneration = async () => {+ const startLocalGeneration = () => {setLocalProgress({ progress: 0 });- const { payload, data } = await submitGenerationPayload();- const jobId = data.jobId || data.generationId;- return attachJobEvents(jobId, {+ let submitted;+ return startRun(async () => {+ submitted = await submitGenerationPayload();+ return submitted.data;+ }, (data) => ({onStage: (message) => setStage({ name: message.stage, detail: message.detail }),onStatus: (message) => setStatusMsg(message.message),onProgress: (message) => {@@ -321,6 +328,7 @@ export function useImageGenPageRuntime() {setStatusMsg(message.message);},onComplete: (message) => {+ const { payload } = submitted;const localOnlyMeta = isCloudMode ? {} : {steps: payload.steps ?? derived.currentModel?.steps,guidance: payload.guidance ?? derived.currentModel?.guidance,@@ -342,7 +350,7 @@ export function useImageGenPageRuntime() {if (message.repo) generationError.repo = message.repo;return generationError;},- });+ }));};const queueAdditional = async (count = 1) => {@@ -420,6 +428,9 @@ export function useImageGenPageRuntime() {toast.success('Image generated');gallery.refreshRecent();} catch (generationError) {+ // Cancelled / detached runs are not failures: Cancel already did the+ // presentation, and an unmounted page has nothing to present.+ if (isMediaRunEnded(generationError)) return;setError(generationError.message || 'Image generation failed');if (generationError.kind) setErrorMeta({ kind: generationError.kind, repo: generationError.repo });const firstLine = String(generationError.message || 'Image generation failed').split('\n')[0];@@ -433,8 +444,11 @@ export function useImageGenPageRuntime() {};const handleCancel = async () => {- eventSourceRef.current?.close();- await cancelImageGen().catch(() => {});+ // Cancel exactly the render this page owns. Only a render with no owned job+ // (a synchronous external-service call) falls back to the legacy+ // "most recent job" cancel.+ const owned = await cancelRun();+ if (!owned) await cancelImageGen().catch(() => {});setGenerating(false);setStatusMsg('Cancelled');};diff --git a/client/src/hooks/useMediaJobSse.js b/client/src/hooks/useMediaJobSse.jsindex 198190a9b4..5530139972 100644--- a/client/src/hooks/useMediaJobSse.js+++ b/client/src/hooks/useMediaJobSse.js@@ -1,4 +1,4 @@-import { useCallback, useRef } from 'react';+import { useCallback, useEffect, useRef } from 'react';import { safeParseJSON } from '../lib/genUtils';/**@@ -29,17 +29,56 @@ import { safeParseJSON } from '../lib/genUtils';* frame (`currentImage`) that arrived without a progress value, kept a distinct* type so a consumer's progress bar isn't disturbed by it.*- * `eventSourceRef` is exposed so callers can `close()` on cancel/unmount.+ * On top of that transport sits the single-run owner the pages share. One+ * active run record holds the request generation, the job identity the run+ * acquired or adopted, its stream and its completion settlement:+ *+ * - `start(kickoff, handlers, opts)` runs `kickoff()` (the POST, or a read of+ * the already-active job), adopts the acknowledged job and attaches its+ * stream. `handlers` is the `attach` handler object, or `(ack) => handlers`+ * when a handler needs the acknowledgement. Extra handlers: `onAcknowledged(ack)`+ * (run is still current, before the stream opens) and `onSync(ack)` (the ack+ * carries no job id — the work already finished). `opts`: `jobIdOf(ack)`+ * (default `ack.jobId || ack.generationId`), `ifIdle` (skip when a run is+ * already active — the resume path) and `onKickoffError(err)` (the request+ * itself failed while the run was still current).+ * - `cancel()` targets ONLY this run's job via the `cancelJob(jobId)` option.+ * Cancelled before the kickoff is acknowledged, it records the intent and+ * cancels exactly the eventual acknowledged job — no stream is opened.+ * - `dispose()` (also run on unmount) detaches: it closes the stream and+ * invalidates every pending callback but does NOT cancel the accepted+ * durable job, so a reload can resume it.+ *+ * A run that is cancelled, detached or superseded settles its promise ONCE+ * with an error `isMediaRunEnded()` recognises, so callers can skip the error+ * presentation that belongs to a genuine failure.*/-export function useMediaJobSse(kind) {+const ENDED = 'MediaRunEndedError';+const endedError = (reason) => Object.assign(new Error(reason === 'canceled' ? 'Cancelled' : 'Detached'), { name: ENDED, reason });+export const isMediaRunEnded = (err) => err?.name === ENDED;++const defaultJobIdOf = (ack) => ack?.jobId || ack?.generationId;++// Take a run out of play and settle it with the reason; the caller owns+// clearing `runRef` (it knows whether this run is the current one).+const retire = (run, reason) => {+ run.ended = true;+ run.es?.close();+ run.reject(endedError(reason));+};++export function useMediaJobSse(kind, { cancelJob } = {}) {const eventSourceRef = useRef(null);+ const runRef = useRef(null);+ const cancelJobRef = useRef(cancelJob);+ useEffect(() => { cancelJobRef.current = cancelJob; });const close = useCallback(() => {eventSourceRef.current?.close();eventSourceRef.current = null;}, []);- const attach = useCallback((jobId, handlers = {}) => {+ const subscribe = useCallback((jobId, handlers = {}, register) => {const {isCurrent = () => true,onQueued, onStarted, onStage, onStatus, onProgress, onPreview,@@ -47,7 +86,7 @@ export function useMediaJobSse(kind) {} = handlers;return new Promise((resolve, reject) => {const es = new EventSource(`/api/${kind}-gen/${jobId}/events`);- eventSourceRef.current = es;+ register(es);es.onmessage = (ev) => {// A stale frame (the run this stream belonged to was cancelled /// superseded) tears down the stream and is otherwise ignored.@@ -97,5 +136,71 @@ export function useMediaJobSse(kind) {});}, [kind]);- return { attach, close, eventSourceRef };+ const attach = useCallback((jobId, handlers) => subscribe(jobId, handlers, (es) => { eventSourceRef.current = es; }), [subscribe]);++ const sendCancel = useCallback((jobId) => Promise.resolve().then(() => cancelJobRef.current?.(jobId)).catch(() => {}), []);++ const start = useCallback((kickoff, handlers = {}, { jobIdOf = defaultJobIdOf, ifIdle = false, onKickoffError } = {}) => {+ if (ifIdle && runRef.current) return Promise.resolve(null);+ const previous = runRef.current;+ return new Promise((resolve, reject) => {+ const run = { ended: false, cancelRequested: false, jobId: null, es: null, reject };+ if (previous) retire(previous, 'superseded');+ runRef.current = run;+ const isCurrent = () => !run.ended && runRef.current === run;+ const finish = () => { run.ended = true; if (runRef.current === run) runRef.current = null; };+ const fail = (err) => { finish(); reject(err); };+ (async () => kickoff())().then((ack) => {+ if (!isCurrent()) {+ // Cancelled before the acknowledgement: the job exists server-side now,+ // so cancel exactly that job. A detached/superseded run leaves it be.+ const id = run.cancelRequested ? jobIdOf(ack) : null;+ if (id) sendCancel(id);+ return;+ }+ // A throwing handler must still settle the run, never leave it dangling.+ try {+ const h = typeof handlers === 'function' ? handlers(ack) : handlers;+ const jobId = jobIdOf(ack);+ if (!jobId) {+ finish();+ resolve(h.onSync ? h.onSync(ack) : ack);+ return;+ }+ run.jobId = jobId;+ h.onAcknowledged?.(ack);+ subscribe(jobId, { ...h, isCurrent: () => isCurrent() && (h.isCurrent?.() ?? true) }, (es) => { run.es = es; })+ .then((value) => { finish(); resolve(value); }, fail);+ } catch (err) {+ fail(err);+ }+ }, (err) => {+ if (!isCurrent()) return;+ onKickoffError?.(err);+ fail(err);+ });+ });+ }, [subscribe, sendCancel]);++ // Resolves true when a run was cancelled (false: nothing owned, so nothing to+ // cancel by id — the caller decides whether a legacy cancel still applies).+ const cancel = useCallback(async () => {+ const run = runRef.current;+ if (!run) return false;+ run.cancelRequested = true;+ runRef.current = null;+ retire(run, 'canceled');+ if (run.jobId) await sendCancel(run.jobId);+ return true;+ }, [sendCancel]);++ const dispose = useCallback(() => {+ const run = runRef.current;+ runRef.current = null;+ if (run) retire(run, 'detached');+ close();+ }, [close]);+ useEffect(() => dispose, [dispose]);++ return { attach, start, cancel, close, dispose };}diff --git a/client/src/hooks/useMediaJobSse.test.jsx b/client/src/hooks/useMediaJobSse.test.jsxindex 0ad50a2cee..1ef0cd5d46 100644--- a/client/src/hooks/useMediaJobSse.test.jsx+++ b/client/src/hooks/useMediaJobSse.test.jsx@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { renderHook } from '@testing-library/react';-import { useMediaJobSse } from './useMediaJobSse';+import { renderHook, act } from '@testing-library/react';+import { useMediaJobSse, isMediaRunEnded } from './useMediaJobSse';import { MockEventSource, lastEventSource as last } from '../test/mockEventSource';beforeEach(() => {@@ -141,3 +141,126 @@ describe('useMediaJobSse', () => {expect(last().closed).toBe(true);});});++// The single run owner: identity, stream, cancellation and unmount detach.+describe('useMediaJobSse run owner', () => {+ const deferred = () => {+ let resolve; let reject;+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+ };+ const settle = (p) => p.then(() => 'resolved', (err) => err);++ it('cancel() targets only the owned job and settles the wait once', async () => {+ const cancelJob = vi.fn(async () => ({}));+ const { result } = renderHook(() => useMediaJobSse('image', { cancelJob }));+ const run = settle(result.current.start(async () => ({ jobId: 'job-a' })));+ await act(async () => {});+ expect(last().url).toBe('/api/image-gen/job-a/events');++ const cancelled = await act(async () => result.current.cancel());+ expect(cancelled).toBe(true);+ expect(cancelJob).toHaveBeenCalledTimes(1);+ expect(cancelJob).toHaveBeenCalledWith('job-a');+ expect(last().closed).toBe(true);+ const err = await run;+ expect(isMediaRunEnded(err)).toBe(true);+ expect(err.reason).toBe('canceled');++ // Nothing left to cancel; a stale terminal frame is ignored.+ expect(await result.current.cancel()).toBe(false);+ last().emit({ type: 'complete', result: {} });+ expect(cancelJob).toHaveBeenCalledTimes(1);+ });++ it('a resumed (adopted) job is cancellable by its id', async () => {+ const cancelJob = vi.fn(async () => ({}));+ const { result } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ settle(result.current.start(async () => ({ jobId: 'resumed', status: 'running' }), {}, { ifIdle: true }));+ await act(async () => {});+ await act(async () => { await result.current.cancel(); });+ expect(cancelJob).toHaveBeenCalledWith('resumed');+ });++ it('cancel before the acknowledgement cancels the eventual job exactly once and opens no stream', async () => {+ const cancelJob = vi.fn(async () => ({}));+ const ack = deferred();+ const { result } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ const run = settle(result.current.start(() => ack.promise));+ await act(async () => { await result.current.cancel(); });+ expect(cancelJob).not.toHaveBeenCalled();+ expect(isMediaRunEnded(await run)).toBe(true);++ await act(async () => { ack.resolve({ generationId: 'late-job' }); });+ expect(cancelJob).toHaveBeenCalledTimes(1);+ expect(cancelJob).toHaveBeenCalledWith('late-job');+ expect(MockEventSource.instances).toHaveLength(0);+ });++ it('unmount before the acknowledgement creates no stream, calls no handler and cancels nothing', async () => {+ const cancelJob = vi.fn(async () => ({}));+ const onAcknowledged = vi.fn();+ const onStatus = vi.fn();+ const ack = deferred();+ const { result, unmount } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ const run = settle(result.current.start(() => ack.promise, { onAcknowledged, onStatus }));+ unmount();+ expect(isMediaRunEnded(await run)).toBe(true);+ await act(async () => { ack.resolve({ jobId: 'durable' }); });+ expect(MockEventSource.instances).toHaveLength(0);+ expect(onAcknowledged).not.toHaveBeenCalled();+ expect(cancelJob).not.toHaveBeenCalled();+ });++ it('unmount mid-stream closes the stream but leaves the accepted job running', async () => {+ const cancelJob = vi.fn(async () => ({}));+ const { result, unmount } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ const run = settle(result.current.start(async () => ({ jobId: 'durable' })));+ await act(async () => {});+ const stream = last();+ unmount();+ expect(stream.closed).toBe(true);+ expect(isMediaRunEnded(await run)).toBe(true);+ expect(cancelJob).not.toHaveBeenCalled();+ });++ it('ifIdle yields to an active run, and a new start supersedes the old run without cancelling it', async () => {+ const cancelJob = vi.fn(async () => ({}));+ const { result } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ const first = settle(result.current.start(async () => ({ jobId: 'first' })));+ await act(async () => {});+ expect(await result.current.start(async () => ({ jobId: 'resume' }), {}, { ifIdle: true })).toBeNull();++ const second = result.current.start(async () => ({ jobId: 'second' }));+ expect((await first).reason).toBe('superseded');+ await act(async () => {});+ expect(MockEventSource.instances[0].closed).toBe(true);+ expect(last().url).toBe('/api/video-gen/second/events');+ expect(cancelJob).not.toHaveBeenCalled();+ last().emit({ type: 'complete', result: { filename: 'b.mp4' } });+ await expect(second).resolves.toEqual({ filename: 'b.mp4' });+ });++ it('completes without a stream when the acknowledgement names no job (synchronous work)', async () => {+ const { result } = renderHook(() => useMediaJobSse('image'));+ const handlers = vi.fn((ack) => ({ onSync: (value) => ({ ...value, done: ack.filename }) }));+ await expect(result.current.start(async () => ({ mode: 'external', filename: 'a.png' }), handlers))+ .resolves.toEqual({ mode: 'external', filename: 'a.png', done: 'a.png' });+ expect(MockEventSource.instances).toHaveLength(0);+ });++ it('reports a failed kickoff to onKickoffError only while the run is current', async () => {+ const onKickoffError = vi.fn();+ const { result } = renderHook(() => useMediaJobSse('image'));+ await expect(result.current.start(async () => { throw new Error('POST failed'); }, {}, { onKickoffError }))+ .rejects.toThrow('POST failed');+ expect(onKickoffError).toHaveBeenCalledTimes(1);++ const failing = deferred();+ const run = settle(result.current.start(() => failing.promise, {}, { onKickoffError }));+ await act(async () => { await result.current.cancel(); });+ failing.reject(new Error('late failure'));+ expect(isMediaRunEnded(await run)).toBe(true);+ expect(onKickoffError).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/pages/ImageGen.cancelOwnership.test.jsx b/client/src/pages/ImageGen.cancelOwnership.test.jsxnew file mode 100644index 0000000000..b979b9fb2e--- /dev/null+++ b/client/src/pages/ImageGen.cancelOwnership.test.jsx@@ -0,0 +1,69 @@+import { beforeEach, describe, expect, it } from 'vitest';+import { act, fireEvent, screen, waitFor } from '@testing-library/react';+import { loadImageGenPage, renderImageGenPage, resetImageGenMockState, state } from '../test/imageGenPageMocks.jsx';+import { cancelImageGen } from '../services/api';+import { lastEventSource, MockEventSource } from '../test/mockEventSource';++await loadImageGenPage();++describe('Image Gen render ownership', () => {+ beforeEach(() => {+ resetImageGenMockState();+ cancelImageGen.mockClear();+ });++ // The legacy server selection cancels the MOST RECENT queued job, so the+ // displayed render A kept running while B was cancelled and the page said+ // "Cancelled".+ it('cancels the displayed render, not the job queued after it', async () => {+ state.generateImage.mockResolvedValueOnce({ jobId: 'job-a' }).mockResolvedValueOnce({ jobId: 'job-b', status: 'queued' });+ await renderImageGenPage();+ fireEvent.click(screen.getByRole('button', { name: /^generate$/i }));+ await waitFor(() => expect(lastEventSource()?.url).toBe('/api/image-gen/job-a/events'));+ const streamA = lastEventSource();++ fireEvent.click(await screen.findByRole('button', { name: /^queue$/i }));+ await waitFor(() => expect(state.generateImage).toHaveBeenCalledTimes(2));++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /cancel/i })); });++ expect(cancelImageGen).toHaveBeenCalledTimes(1);+ expect(cancelImageGen).toHaveBeenCalledWith({ jobId: 'job-a' });+ expect(streamA.closed).toBe(true);+ // B was queued independently and stays untouched: no stream, no cancel.+ expect(MockEventSource.instances).toHaveLength(1);+ expect(screen.getByRole('button', { name: /^generate$/i })).toBeInTheDocument();+ });++ it('cancel before the POST is acknowledged cancels the eventual job once and opens no stream', async () => {+ let acknowledge;+ state.generateImage.mockReturnValueOnce(new Promise((resolve) => { acknowledge = resolve; }));+ await renderImageGenPage();+ fireEvent.click(screen.getByRole('button', { name: /^generate$/i }));+ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: /cancel/i })); });+ expect(cancelImageGen).not.toHaveBeenCalled();++ await act(async () => { acknowledge({ jobId: 'job-late' }); });+ expect(cancelImageGen).toHaveBeenCalledTimes(1);+ expect(cancelImageGen).toHaveBeenCalledWith({ jobId: 'job-late' });+ expect(MockEventSource.instances).toHaveLength(0);+ });++ it('a resumed render is cancelled by its own id, and an unmount mid-read opens no stream', async () => {+ state.activeJob = { generationId: 'job-resumed', status: 'running', params: {} };+ const view = await renderImageGenPage();+ await waitFor(() => expect(lastEventSource()?.url).toBe('/api/image-gen/job-resumed/events'));+ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: /cancel/i })); });+ expect(cancelImageGen).toHaveBeenCalledWith({ jobId: 'job-resumed' });+ view.unmount();++ MockEventSource.reset();+ let resolveActive;+ const { getActiveImageJob } = await import('../services/api');+ getActiveImageJob.mockReturnValueOnce(new Promise((resolve) => { resolveActive = resolve; }));+ const second = await renderImageGenPage();+ second.unmount();+ await act(async () => { resolveActive({ activeJob: { generationId: 'job-durable', status: 'running', params: {} } }); });+ expect(MockEventSource.instances).toHaveLength(0);+ });+});diff --git a/client/src/pages/VideoGen.cancelOwnership.test.jsx b/client/src/pages/VideoGen.cancelOwnership.test.jsxnew file mode 100644index 0000000000..7110bacc38--- /dev/null+++ b/client/src/pages/VideoGen.cancelOwnership.test.jsx@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it } from 'vitest';+import { act, fireEvent, screen, waitFor } from '@testing-library/react';+import {+ loadVideoGenPage, renderVideoGenPage, resetVideoGenMockState, state,+ videoGenModel, videoGenModelContext, videoGenStatus,+} from '../test/videoGenPageMocks.jsx';+import { findEnabledByRole } from '../test/enabledBarrier.js';+import { cancelVideoGen, getActiveVideoJob } from '../services/api';+import { lastEventSource, MockEventSource } from '../test/mockEventSource';++const MODEL = videoGenModel('h3-one');++await loadVideoGenPage();++describe('Video Gen render ownership', () => {+ beforeEach(() => {+ resetVideoGenMockState();+ cancelVideoGen.mockClear();+ state.getVideoGenStatus.mockResolvedValue(videoGenStatus([MODEL]));+ state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));+ state.modelStatuses = { [MODEL.id]: { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 } };+ });++ // Reload mid-render used to leave the resumed job without an owned identity, so+ // Cancel closed the stream and said "Cancelled" while the render kept running.+ it('cancelling a resumed render cancels exactly that job', async () => {+ state.activeJob = { jobId: 'job-a', status: 'running', params: {} };+ await renderVideoGenPage();+ await waitFor(() => expect(lastEventSource()?.url).toBe('/api/video-gen/job-a/events'));+ const stream = lastEventSource();++ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: /^cancel$/i })); });++ expect(cancelVideoGen).toHaveBeenCalledTimes(1);+ expect(cancelVideoGen).toHaveBeenCalledWith('job-a');+ expect(stream.closed).toBe(true);+ });++ it('a POST acknowledged after unmount opens no stream, and an unmounted active-job read is ignored', async () => {+ let acknowledge;+ state.generateVideo.mockReturnValue(new Promise((resolve) => { acknowledge = resolve; }));+ const view = await renderVideoGenPage();+ fireEvent.change(await screen.findByLabelText('Prompt'), { target: { value: 'a fox watches the rain' } });+ await findEnabledByRole('button', { name: /^Generate$/ });+ fireEvent.click(screen.getByRole('button', { name: /^Generate$/ }));+ await waitFor(() => expect(state.generateVideo).toHaveBeenCalled());+ view.unmount();+ await act(async () => { acknowledge({ jobId: 'job-durable' }); });+ expect(MockEventSource.instances).toHaveLength(0);+ expect(cancelVideoGen).not.toHaveBeenCalled();++ let resolveActive;+ getActiveVideoJob.mockReturnValueOnce(new Promise((resolve) => { resolveActive = resolve; }));+ const second = await renderVideoGenPage();+ second.unmount();+ await act(async () => { resolveActive({ activeJob: { jobId: 'job-running', status: 'running', params: {} } }); });+ expect(MockEventSource.instances).toHaveLength(0);+ });+});diff --git a/client/src/pages/VideoGen.composeWhileBusy.test.jsx b/client/src/pages/VideoGen.composeWhileBusy.test.jsxindex 6b96e05c3c..bb8fef752d 100644--- a/client/src/pages/VideoGen.composeWhileBusy.test.jsx+++ b/client/src/pages/VideoGen.composeWhileBusy.test.jsx@@ -25,7 +25,6 @@ describe('VideoGen compose-while-busy', () => {state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));state.modelStatuses = { [MODEL.id]: { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 } };state.generateVideo.mockReturnValue(new Promise(() => {}));- state.attach.mockReturnValue(new Promise(() => {}));vi.stubGlobal('open', vi.fn());Object.defineProperty(globalThis.navigator, 'clipboard', {configurable: true,diff --git a/client/src/pages/VideoGen.displaySleep.test.jsx b/client/src/pages/VideoGen.displaySleep.test.jsxindex 1efa235d87..2f9e2d3920 100644--- a/client/src/pages/VideoGen.displaySleep.test.jsx+++ b/client/src/pages/VideoGen.displaySleep.test.jsx@@ -36,7 +36,6 @@ describe('VideoGen per-render display-sleep control', () => {state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MLX_MODEL]));state.modelStatuses = { [MLX_MODEL.id]: { id: MLX_MODEL.id, repo: MLX_MODEL.repo, cached: true, sizeBytes: 100 } };state.generateVideo.mockResolvedValue({ jobId: 'job-1' });- state.attach.mockReturnValue(new Promise(() => {}));});it('defaults the checkbox to the install setting and sends the choice with the render', async () => {diff --git a/client/src/pages/VideoGen.fal.test.jsx b/client/src/pages/VideoGen.fal.test.jsxindex 299666b148..97ea0c1098 100644--- a/client/src/pages/VideoGen.fal.test.jsx+++ b/client/src/pages/VideoGen.fal.test.jsx@@ -17,7 +17,6 @@ describe('VideoGen curated fal controls (#9232)', () => {state.getVideoGenStatus.mockResolvedValue(videoGenStatus([MODEL], { falEnabled: true }));state.modelStatuses = { [MODEL.id]: { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 } };state.generateVideo.mockResolvedValue({ jobId: 'job-1' });- state.attach.mockReturnValue(new Promise(() => {}));});// Pins field-state → form → submission and pricing before enqueue, includingdiff --git a/client/src/pages/VideoGen.federatedTarget.test.jsx b/client/src/pages/VideoGen.federatedTarget.test.jsxindex ba11ad5783..7a11da3658 100644--- a/client/src/pages/VideoGen.federatedTarget.test.jsx+++ b/client/src/pages/VideoGen.federatedTarget.test.jsx@@ -54,7 +54,6 @@ describe('VideoGen federated render target', () => {state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));state.modelStatuses = { [MODEL.id]: { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 } };state.generateVideo.mockReturnValue(new Promise(() => {}));- state.attach.mockReturnValue(new Promise(() => {}));});// The whole point of the picker: a peer's model reaches the generate route asdiff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 49e6a1df46..ff1565a0c0 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -188,9 +188,6 @@ export default function VideoGen() {// entry) still surfaces the backend switcher below.const falEnabled = status?.falEnabled === true;const reactorEnabled = status?.reactorEnabled === true;- // The jobId of the render this tab's Generate button currently owns —- // threaded into cancelVideoGen so cancellation is job-scoped.- const activeJobIdRef = useRef(null);const models = useMemo(() => modelContext?.models || [], [modelContext]);const refreshGrokEnabled = useCallback(() => {getSettings({ silent: true })@@ -602,15 +599,10 @@ export default function VideoGen() {// than as a hang.const [phase, setPhase] = useState(null);const [renderStartedAt, setRenderStartedAt] = useState(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.- const runRejectRef = useRef(null);- // Per-run abort token. Bumped at the start of each runGeneration() and- // again on cancel; runGeneration captures the value at start and bails- // when the token has moved on (e.g. POST resolves after cancel).- const runTokenRef = useRef(0);+ // One run owner for the displayed render: its identity (the acquired OR+ // resumed job), stream, cancellation and unmount detach all live in the hook,+ // so Cancel is job-scoped on both the start and the reload-resume path.+ const { start: startRun, cancel: cancelRun } = useMediaJobSse('video', { cancelJob: cancelVideoGen });const refreshStatus = useCallback(() => {setStatusLoading(true);@@ -635,16 +627,14 @@ export default function VideoGen() {useEffect(() => {refreshStatus();refreshModelContext();- return () => eventSourceRef.current?.close();- }, [refreshStatus, refreshModelContext, eventSourceRef]);+ }, [refreshStatus, refreshModelContext]);- // SSE subscriber shared by the in-flight POST path and the mount-time+ // Presentation handlers 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 } = {}) => {- return attach(jobId, {- isCurrent,+ const videoRunHandlers = (withToast) => {+ return {onQueued: (msg) => {setPhase('queued');setStatusMsg(typeof msg.position === 'number' ? `Queued (position ${msg.position})` : 'Queued');@@ -698,7 +688,7 @@ export default function VideoGen() {setError('Lost connection to server');setGenerating(false);},- }).then(settleResolve, settleReject);+ };};// Resume an in-flight (or queued) render so a page reload doesn't lose@@ -706,38 +696,36 @@ export default function VideoGen() {// 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;- // Bail if the user already started a render in this tab. `generating`- // would be stale here (effect deps are []), so gate on the live ref:- // runTokenRef is bumped at the top of every runGeneration() and stays- // > 0 for the session afterward. eventSourceRef is also checked as a- // belt-and-suspenders signal for the in-flight POST window before- // attachJobEvents runs.- if (runTokenRef.current > 0 || eventSourceRef.current) return;- applyResumedParams(job.params || {});- // The form hook doesn't own this page-level toggle — restore it directly- // so a reload mid-render shows the choice that render is actually keeping.- if (job.params?.displaySleep !== undefined) setDisplaySleepOverride(!!job.params.displaySleep);- setGenerating(true);- setPhase(job.status === 'queued' ? 'queued' : null);- // The worker's own start time, so a reload keeps a truthful elapsed clock- // instead of restarting it and reading as a fresh render. A job still in- // the queue has no start time yet and gets no clock — the same rule the- // live path follows.- setRenderStartedAt(job.startedAt ? new Date(job.startedAt).getTime() : null);- // Skip a forced setProgress(0) here — attachJobEvents will replay the- // server's last SSE payload synchronously after EventSource open, and- // a job mid-render would otherwise visibly flash 0% before jumping- // back to its real progress.- 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(() => {});+ // `ifIdle`: bail when the user already started a render in this tab. The+ // owner also drops this run if one starts while the read is in flight, and+ // creates no stream (or presentation) if the page unmounts first — the+ // accepted job stays durable for the next resume.+ startRun(+ () => getActiveVideoJob().then((data) => data?.activeJob),+ {+ ...videoRunHandlers(false),+ onAcknowledged: (job) => {+ applyResumedParams(job.params || {});+ // The form hook doesn't own this page-level toggle — restore it directly+ // so a reload mid-render shows the choice that render is actually keeping.+ if (job.params?.displaySleep !== undefined) setDisplaySleepOverride(!!job.params.displaySleep);+ setGenerating(true);+ setPhase(job.status === 'queued' ? 'queued' : null);+ // The worker's own start time, so a reload keeps a truthful elapsed clock+ // instead of restarting it and reading as a fresh render. A job still in+ // the queue has no start time yet and gets no clock — the same rule the+ // live path follows.+ setRenderStartedAt(job.startedAt ? new Date(job.startedAt).getTime() : null);+ // Skip a forced setProgress(0) here — the stream replays the server's+ // last SSE payload right after open, and a job mid-render would+ // otherwise visibly flash 0% before jumping back to its real progress.+ setStatusMsg(job.status === 'queued'+ ? (typeof job.position === 'number' ? `Queued (position ${job.position})` : 'Queued')+ : 'Resuming…');+ },+ },+ { ifIdle: true, jobIdOf: (job) => job?.jobId },+ ).catch(() => {});}, []);const handleSavePythonPath = useCallback(async (path) => {@@ -857,17 +845,10 @@ export default function VideoGen() {// separate queue-submit path below deliberately does not attach SSE: the// shared MediaJobsQueue is the live view for work submitted in parallel.//- // Per-run abort token: the user can press Cancel during the brief window- // between generateVideo() POST and its `.then()` resolving with a jobId.- // Without a guard, the late `.then()` would still open an EventSource and- // start applying SSE updates for a job the UI considers cancelled, AND- // could clobber a queue item that's already advanced. handleCancel bumps- // runTokenRef; runGeneration captures the token at start and ignores the- // POST response (and any SSE messages) when the token no longer matches.- const runGeneration = (payload) => new Promise((resolve, reject) => {- // A new run owns no job yet — clear the previous run's id so a Cancel- // racing the POST can't target a stale (completed) job.- activeJobIdRef.current = null;+ // The run owner (useMediaJobSse) holds the abort/identity bookkeeping: Cancel+ // pressed between the POST and its acknowledgement cancels the eventual job+ // by id without opening a stream, and an unmount detaches without one.+ const runGeneration = (payload) => {setGenerating(true);setProgress({ progress: 0 });setStatusMsg('Starting...');@@ -877,44 +858,14 @@ export default function VideoGen() {// lands, so it measures the render rather than the queue wait.setPhase(null);setRenderStartedAt(null);-- const myToken = ++runTokenRef.current;- const isCurrent = () => myToken === runTokenRef.current;-- // Wrap settle so the cancel ref is cleared exactly once when the Promise- // transitions to a final state and stale rejects can't fire after a- // successful complete.- const settleResolve = (value) => { runRejectRef.current = null; activeJobIdRef.current = null; resolve(value); };- const settleReject = (err) => { runRejectRef.current = null; activeJobIdRef.current = null; reject(err); };- runRejectRef.current = settleReject;-- generateVideo(payload).then((data) => {- // The user cancelled while we were waiting for the POST to return —- // don't open an EventSource at all, and don't touch any state. The- // earlier handleCancel() already settled the Promise via runRejectRef.- const jobId = data.jobId || data.generationId;- if (!isCurrent()) {- // The user cancelled while this POST was in flight — the job was- // still created server-side, so cancel it by id now (handleCancel- // couldn't: it had no id yet, and an unscoped cancel could have- // killed an unrelated parallel render instead).- if (jobId) cancelVideoGen(jobId).catch(() => {});- return;- }- // Remember which job this run owns — with the cloud lane, video- // renders are no longer single-flight, so Cancel must target exactly- // this job instead of "the first running video" (which could be an- // unrelated local or grok render).- activeJobIdRef.current = jobId;- attachJobEvents(jobId, { isCurrent, settleResolve, settleReject, withToast: true });- }).catch((err) => {- if (!isCurrent()) return;- setError(err.message || 'Video generation failed');- setGenerating(false);- toast.error(err.message || 'Video generation failed');- settleReject(err);+ return startRun(() => generateVideo(payload), videoRunHandlers(true), {+ onKickoffError: (err) => {+ setError(err.message || 'Video generation failed');+ setGenerating(false);+ toast.error(err.message || 'Video generation failed');+ },});- });+ };const handleGenerate = async (e) => {e?.preventDefault?.();@@ -957,28 +908,12 @@ export default function VideoGen() {};const handleCancel = async () => {- // Bump the run token FIRST so any late `.then()` from the in-flight- // generateVideo() POST sees a stale token and bails before opening an- // EventSource for a job we've already declared cancelled.- runTokenRef.current += 1;- eventSourceRef.current?.close();- // Only cancel by id. When the id isn't known yet (Cancel raced the- // generation POST), skip the server call entirely — the POST's stale-- // token branch cancels the freshly-created job by id when it lands.- // An unscoped cancel here could kill an unrelated parallel render.- if (activeJobIdRef.current) {- await cancelVideoGen(activeJobIdRef.current).catch(() => {});- activeJobIdRef.current = null;- }+ // Cancel targets only the run this page owns — started here or resumed+ // after a reload. With nothing owned there is no job id to name, and an+ // unscoped cancel could kill an unrelated parallel render.+ await cancelRun();setGenerating(false);setStatusMsg('Cancelled');- // Settle the in-flight runGeneration Promise so callers waiting on the- // active render do not retain a dangling promise after cancellation.- if (runRejectRef.current) {- const reject = runRejectRef.current;- runRejectRef.current = null;- reject(new Error('Cancelled'));- }};// `status.connected` reflects the LEGACY mlx_video pythonPath health. BYOVdiff --git a/client/src/pages/VideoGen.modelLoading.test.jsx b/client/src/pages/VideoGen.modelLoading.test.jsxindex a6636bbc46..9c5244afa4 100644--- a/client/src/pages/VideoGen.modelLoading.test.jsx+++ b/client/src/pages/VideoGen.modelLoading.test.jsx@@ -43,7 +43,6 @@ describe('VideoGen model picker vs the /status python probe', () => {resetVideoGenMockState();state.getVideoGenStatus.mockResolvedValue(statusPayload());state.getVideoGenModelContext.mockResolvedValue(modelContextPayload());- state.attach.mockResolvedValue({ filename: 'example.mp4' });});it('keeps the Model field with a loading placeholder until the model list lands', async () => {diff --git a/client/src/pages/VideoGen.reactor.test.jsx b/client/src/pages/VideoGen.reactor.test.jsxindex 7e5cdab03e..f2f26c3e1f 100644--- a/client/src/pages/VideoGen.reactor.test.jsx+++ b/client/src/pages/VideoGen.reactor.test.jsx@@ -60,7 +60,6 @@ describe('VideoGen reactor.inc lane', () => {state.modelStatuses = { [MODEL.id]: { id: MODEL.id, repo: MODEL.repo, cached: true, sizeBytes: 100 } };state.listVideoHistory.mockResolvedValue([REACTOR_RENDER, LOCAL_RENDER]);state.generateVideo.mockResolvedValue({ jobId: 'job-1' });- state.attach.mockReturnValue(new Promise(() => {}));});// The 800-character cap used to surface only as a 400 after Generate, namingdiff --git a/client/src/pages/VideoGen.remix.test.jsx b/client/src/pages/VideoGen.remix.test.jsxindex 3378e7ecac..7e33a7b709 100644--- a/client/src/pages/VideoGen.remix.test.jsx+++ b/client/src/pages/VideoGen.remix.test.jsx@@ -119,7 +119,6 @@ describe('VideoGen cross-page Remix handoff', () => {resetVideoGenMockState();state.getVideoGenStatus.mockResolvedValue(videoGenStatus([MODEL]));state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));- state.attach.mockResolvedValue({ filename: 'example.mp4' });state.availableLoras = [LORA];state.listVideoHistory.mockResolvedValue([RECORD, LEGACY_RECORD]);// Every weight cached — a ready install. Without this the Generate buttondiff --git a/client/src/pages/VideoGen.terms.test.jsx b/client/src/pages/VideoGen.terms.test.jsxindex c37a5cbb8f..b2b24ab6f0 100644--- a/client/src/pages/VideoGen.terms.test.jsx+++ b/client/src/pages/VideoGen.terms.test.jsx@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it } from 'vitest';import { act, fireEvent, screen, waitFor } from '@testing-library/react';import { awaitEnabled } from '../test/enabledBarrier.js';+import { lastEventSource } from '../test/mockEventSource';import {loadVideoGenPage,@@ -36,10 +37,6 @@ describe('VideoGen MiniMax H3 orchestration', () => {state.repair.mockResolvedValue({ ok: true });state.getVideoGenStatus.mockResolvedValue(videoGenStatus([H3_ONE, H3_TWO]));state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([H3_ONE, H3_TWO]));- state.attach.mockImplementation(async (_jobId, handlers) => {- handlers.onComplete({ result: { filename: 'example.mp4' } });- return { filename: 'example.mp4' };- });});it('lets H3 generate and queue with no eligibility checkbox', async () => {@@ -65,6 +62,10 @@ describe('VideoGen MiniMax H3 orchestration', () => {})));expect(state.generateVideo.mock.calls[0][0]).not.toHaveProperty('termsAcceptance');+ // Finish the render so the page returns to idle and Generate is offered again.+ await waitFor(() => expect(lastEventSource()).toBeTruthy());+ await act(async () => { lastEventSource().emit({ type: 'complete', result: { filename: 'example.mp4' } }); });+fireEvent.change(screen.getByLabelText('Model'), { target: { value: H3_TWO.id } });await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue(H3_TWO.id));expect(generate()).toBeEnabled();diff --git a/client/src/test/imageGenPageMocks.jsx b/client/src/test/imageGenPageMocks.jsxindex 351d0d47a4..d9e5f36f2c 100644--- a/client/src/test/imageGenPageMocks.jsx+++ b/client/src/test/imageGenPageMocks.jsx@@ -30,6 +30,7 @@ import { StrictMode } from 'react';import { act, render } from '@testing-library/react';import { MemoryRouter, useLocation } from 'react-router';import { vi } from 'vitest';+import { MockEventSource } from './mockEventSource';/** Local model as the catalog reports it; `.defaultLocalModel` pins its regressions against this shape. */export const imageGenModel = (id, overrides = {}) => ({@@ -108,11 +109,6 @@ export const state = {getImageGenStatus: vi.fn(defaultStatus),/** `generateImage`; a spy so a suite can assert payloads or reject. */generateImage: vi.fn(async () => ({ jobId: 'job-1' })),- /**- * `useMediaJobSse('image')`'s `attach`; a spy so federatedTarget can hold the- * job stream open while it asserts over the submitted payload.- */- attachJobEvents: vi.fn(),/** `getActiveImageJob`'s payload. */activeJob: null,/** Settings `getSettings` resolves to; reset restores DEFAULT_SETTINGS. */@@ -159,9 +155,11 @@ export function resetImageGenMockState() {state.peers = [];state.getImageGenStatus.mockReset().mockImplementation(defaultStatus);state.generateImage.mockReset().mockResolvedValue({ jobId: 'job-1' });- // A never-resolving attach keeps a local job stream open, the way the real- // SSE hook behaves mid-render, without leaking timers into the test.- state.attachJobEvents.mockReset().mockReturnValue(new Promise(() => {}));+ // The real media-run hook opens this for a started/resumed render; a silent+ // stream keeps the job open mid-render without leaking timers, and a test+ // drives its frames through `lastEventSource()`.+ MockEventSource.reset();+ globalThis.EventSource = MockEventSource;state.activeJob = null;state.settings = DEFAULT_SETTINGS;state.getSettings.mockReset().mockImplementation(async () => state.settings);@@ -208,9 +206,6 @@ vi.mock('../services/apiImageVideo', () => ({vi.mock('../hooks/useImageGenProgress', () => ({useImageGenProgress: () => ({ progress: null, begin: vi.fn(), end: vi.fn(), resume: vi.fn() }),}));-vi.mock('../hooks/useMediaJobSse', () => ({- useMediaJobSse: () => ({ attach: state.attachJobEvents, eventSourceRef: { current: null } }),-}));vi.mock('../hooks/useModelDownloadStatus', () => ({useModelDownloadStatus: () => ({getStatus: () => ({ cached: true }), start: vi.fn(), cancel: vi.fn(), repair: vi.fn(), refresh: vi.fn(),diff --git a/client/src/test/videoGenPageMocks.jsx b/client/src/test/videoGenPageMocks.jsxindex 0c7797eaf8..3d63cf1695 100644--- a/client/src/test/videoGenPageMocks.jsx+++ b/client/src/test/videoGenPageMocks.jsx@@ -25,6 +25,7 @@import { act, render } from '@testing-library/react';import { MemoryRouter, useNavigate } from 'react-router';import { vi } from 'vitest';+import { MockEventSource } from './mockEventSource';/** Universe style the stub picker hands to the page when its button is clicked. */const DEFAULT_UNIVERSE_STYLE = {@@ -48,8 +49,6 @@ export const state = {*/getVideoGenModelContext: vi.fn(),generateVideo: vi.fn(),- attach: vi.fn(),- eventSourceRef: { current: null },activeJob: null,/** Cache-status entries keyed by download id, read by the default `getModelStatus`. */modelStatuses: {},@@ -93,7 +92,7 @@ export const state = {navigate: null,};-const SPIES = ['getVideoGenStatus', 'getVideoGenModelContext', 'generateVideo', 'attach', 'start', 'startWhenIdle', 'repair', 'cancel', 'refresh', 'listVideoHistory', 'listLorasFull'];+const SPIES = ['getVideoGenStatus', 'getVideoGenModelContext', 'generateVideo', 'start', 'startWhenIdle', 'repair', 'cancel', 'refresh', 'listVideoHistory', 'listLorasFull'];/** Restore every documented default, including fresh spies. Call it first in `beforeEach`. */export function resetVideoGenMockState() {@@ -107,7 +106,10 @@ export function resetVideoGenMockState() {state.queuedModelId = null;state.runtimeInstallComplete = null;state.universeStyle = DEFAULT_UNIVERSE_STYLE;- state.eventSourceRef.current = null;+ // The real media-run hook opens this for a resumed/started render; a test+ // drives its frames through `lastEventSource()`.+ MockEventSource.reset();+ globalThis.EventSource = MockEventSource;state.advancedParams = null;state.loraPicker = null;state.galleryProps = null;@@ -222,9 +224,6 @@ vi.mock('../hooks/useModelDownloadStatus', async (importOriginal) => ({}),}));-vi.mock('../hooks/useMediaJobSse', () => ({- useMediaJobSse: () => ({ attach: state.attach, eventSourceRef: state.eventSourceRef }),-}));vi.mock('../hooks/useMediaCompletionRefresh', () => ({useMediaCompletionRefresh: (options) => { state.completionRefresh = options; },}));