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: video cancel no longer reports success when the queue refused it (#12999) (#13047)
[._.]/1cc8a63fcfab
diff --git a/client/src/hooks/useMediaJobSse.js b/client/src/hooks/useMediaJobSse.jsindex 5530139972..bf6484941e 100644--- a/client/src/hooks/useMediaJobSse.js+++ b/client/src/hooks/useMediaJobSse.js@@ -138,7 +138,13 @@ export function useMediaJobSse(kind, { cancelJob } = {}) {const attach = useCallback((jobId, handlers) => subscribe(jobId, handlers, (es) => { eventSourceRef.current = es; }), [subscribe]);- const sendCancel = useCallback((jobId) => Promise.resolve().then(() => cancelJobRef.current?.(jobId)).catch(() => {}), []);+ // Rejects when the server refused the cancel (error status, or a body with+ // `ok: false`) so the caller keeps the run attached instead of reporting it+ // cancelled while the job is still live.+ const sendCancel = useCallback((jobId) => Promise.resolve().then(() => cancelJobRef.current?.(jobId)).then((res) => {+ if (res?.ok === false) throw new Error(res.reason || res.error || 'Cancel was refused');+ return res;+ }), []);const start = useCallback((kickoff, handlers = {}, { jobIdOf = defaultJobIdOf, ifIdle = false, onKickoffError } = {}) => {if (ifIdle && runRef.current) return Promise.resolve(null);@@ -155,7 +161,7 @@ export function useMediaJobSse(kind, { cancelJob } = {}) {// 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);+ if (id) sendCancel(id).catch(() => {});return;}// A throwing handler must still settle the run, never leave it dangling.@@ -184,13 +190,27 @@ export function useMediaJobSse(kind, { cancelJob } = {}) {// 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).+ // Rejects, leaving the run and its stream attached, when the server refuses+ // the cancel of an acknowledged job.const cancel = useCallback(async () => {const run = runRef.current;if (!run) return false;+ if (run.jobId) {+ // A repeated click shares the in-flight request instead of racing the+ // queue into a spurious ALREADY_TERMINAL refusal.+ run.cancelPending ||= sendCancel(run.jobId).finally(() => { run.cancelPending = null; });+ await run.cancelPending;+ // The run may have settled (terminal frame, supersede) while the request was in flight.+ if (run.canceled) return true;+ if (runRef.current !== run || run.ended) return false;+ run.canceled = true;+ runRef.current = null;+ retire(run, 'canceled');+ return true;+ }run.cancelRequested = true;runRef.current = null;retire(run, 'canceled');- if (run.jobId) await sendCancel(run.jobId);return true;}, [sendCancel]);diff --git a/client/src/hooks/useMediaJobSse.test.jsx b/client/src/hooks/useMediaJobSse.test.jsxindex 1ef0cd5d46..a82261f61e 100644--- a/client/src/hooks/useMediaJobSse.test.jsx+++ b/client/src/hooks/useMediaJobSse.test.jsx@@ -173,6 +173,42 @@ describe('useMediaJobSse run owner', () => {expect(cancelJob).toHaveBeenCalledTimes(1);});+ it.each([+ ['a rejected request', () => vi.fn(async () => { throw new Error('ALREADY_TERMINAL'); })],+ ['an ok:false body', () => vi.fn(async () => ({ ok: false, reason: 'no active render' }))],+ ])('a refused cancel (%s) rejects and keeps the run and its stream attached', async (_label, makeCancel) => {+ const cancelJob = makeCancel();+ const { result } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ const onComplete = vi.fn(() => 'done');+ const run = settle(result.current.start(async () => ({ jobId: 'job-a' }), { onComplete }));+ await act(async () => {});++ await expect(act(async () => result.current.cancel())).rejects.toThrow();+ expect(last().closed).toBe(false);++ last().emit({ type: 'complete', result: {} });+ expect(await run).toBe('resolved');+ });++ it('a double cancel shares one in-flight request', async () => {+ const pending = deferred();+ const cancelJob = vi.fn(() => pending.promise);+ const { result } = renderHook(() => useMediaJobSse('video', { cancelJob }));+ settle(result.current.start(async () => ({ jobId: 'job-a' })));+ await act(async () => {});++ let first; let second;+ await act(async () => {+ first = result.current.cancel();+ second = result.current.cancel();+ pending.resolve({ ok: true });+ await Promise.all([first, second]);+ });+ expect(cancelJob).toHaveBeenCalledTimes(1);+ expect(await first).toBe(true);+ expect(await second).toBe(true);+ });+it('a resumed (adopted) job is cancellable by its id', async () => {const cancelJob = vi.fn(async () => ({}));const { result } = renderHook(() => useMediaJobSse('video', { cancelJob }));diff --git a/client/src/pages/VideoGen.cancelOwnership.test.jsx b/client/src/pages/VideoGen.cancelOwnership.test.jsxindex 7110bacc38..ef10bd7653 100644--- a/client/src/pages/VideoGen.cancelOwnership.test.jsx+++ b/client/src/pages/VideoGen.cancelOwnership.test.jsx@@ -36,6 +36,20 @@ describe('Video Gen render ownership', () => {expect(stream.closed).toBe(true);});+ it('a refused cancel keeps the stream attached and does not report Cancelled', async () => {+ state.activeJob = { jobId: 'job-a', status: 'running', params: {} };+ cancelVideoGen.mockRejectedValueOnce(Object.assign(new Error('Job already running'), { code: 'ALREADY_TERMINAL' }));+ 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).toHaveBeenCalledWith('job-a');+ expect(stream.closed).toBe(false);+ expect(screen.queryByText('Cancelled')).toBeNull();+ });+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; }));diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex b6a6063124..4d9e1495c2 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -948,7 +948,13 @@ export default function VideoGen() {// 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();+ // A refused cancel (job already finishing, or unknown) leaves the run and+ // its stream attached, so only a server-accepted cancel reads as Cancelled.+ const refused = await cancelRun().then(() => false, (err) => {+ toast.error(err.message || 'Cancel failed');+ return true;+ });+ if (refused) return;setGenerating(false);setStatusMsg('Cancelled');};diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 31f5750fdc..7cb09e01d7 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -1170,6 +1170,16 @@ router.get('/:jobId/events', (req, res) => {if (!ok) throw new ServerError('Job not found or expired', { status: 404 });});+// The queue reports a refused cancel as { ok: false, code }; surface it as an+// error status so the caller never mistakes a refusal for a cancelled render.+const cancelOrRefuse = async (jobId) => {+ const result = await cancelJob(jobId);+ if (!result?.ok && result?.code) {+ throw new ServerError(result.error || 'Cancel failed', { status: result.code === 'ALREADY_TERMINAL' ? 409 : 404, code: result.code });+ }+ return result;+};+router.post('/cancel', asyncHandler(async (req, res) => {// Cancel selection rules, in priority order:// 1. Explicit body.jobId — cancel exactly that job (queued or running).@@ -1184,18 +1194,18 @@ router.post('/cancel', asyncHandler(async (req, res) => {// Validate that the jobId is a video job before cancelling, so a stray// image jobId from another tab doesn't accidentally cancel here.const job = listJobs({ kind: 'video' }).find((j) => j.id === requestedJobId);- if (!job) return res.json({ ok: false, reason: 'video job not found' });+ if (!job) throw new ServerError('Video job not found', { status: 404, code: 'NOT_FOUND' });if (job.status !== 'queued' && job.status !== 'running') {- return res.json({ ok: false, reason: `job already ${job.status}` });+ throw new ServerError(`Job already ${job.status}`, { status: 409, code: 'ALREADY_TERMINAL' });}- return res.json(await cancelJob(job.id));+ return res.json(await cancelOrRefuse(job.id));}const running = listJobs({ kind: 'video', status: 'running' });- if (running.length) return res.json(await cancelJob(running[0].id));+ if (running.length) return res.json(await cancelOrRefuse(running[0].id));// No running render — cancel the newest queued video instead so the user// can pull back a submission before it starts.const queued = listJobs({ kind: 'video', status: 'queued' });- if (queued.length) return res.json(await cancelJob(queued[queued.length - 1].id));+ if (queued.length) return res.json(await cancelOrRefuse(queued[queued.length - 1].id));res.json({ ok: false, reason: 'no active or queued video render' });}));diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 8b12f8c565..0aa8f88d2a 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -2983,10 +2983,30 @@ describe('videoGen routes', () => {{ id: 'running-b', kind: 'video', status: 'running' },].filter((j) => (!status || j.status === status) && (!kind || j.kind === kind)));const r = await request(app).post('/api/video-gen/cancel').send({ jobId: 'finished-a' });- expect(r.body.ok).toBe(false);+ expect(r.status).toBe(409);+ expect(r.body.code).toBe('ALREADY_TERMINAL');expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();});+ it('returns 404 NOT_FOUND for a named id the queue does not know', async () => {+ mediaJobQueue.listJobs.mockReturnValue([{ id: 'running-b', kind: 'video', status: 'running' }]);+ const r = await request(app).post('/api/video-gen/cancel').send({ jobId: 'ghost' });+ expect(r.status).toBe(404);+ expect(r.body.code).toBe('NOT_FOUND');+ expect(mediaJobQueue.cancelJob).not.toHaveBeenCalled();+ });++ it.each([+ ['ALREADY_TERMINAL', 409],+ ['NOT_FOUND', 404],+ ])('maps a queue refusal %s to %i instead of 200', async (code, status) => {+ mediaJobQueue.listJobs.mockReturnValue([{ id: 'running-b', kind: 'video', status: 'running' }]);+ mediaJobQueue.cancelJob.mockResolvedValue({ ok: false, code });+ const r = await request(app).post('/api/video-gen/cancel').send({ jobId: 'running-b' });+ expect(r.status).toBe(status);+ expect(r.body.code).toBe(code);+ });+// No running job and no jobId — fall back to newest queued so the user// can pull back a recent submission before it starts.it('falls back to newest queued video when no jobId and nothing is running', async () => {