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: queue video stitching as cancellable deduplicated jobs (#13383)
[._.]/90e510a0cbbd
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsxindex e8991bc852..a6de7b744b 100644--- a/client/src/pages/MediaHistory.jsx+++ b/client/src/pages/MediaHistory.jsx@@ -7,7 +7,7 @@ import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';* into Video Gen.*/-import { useState, useCallback, useMemo } from 'react';+import { useState, useCallback, useEffect, useMemo, useRef } from 'react';import { Link, useNavigate } from 'react-router';import { Combine, Image as ImageIcon, Film, Search, X } from 'lucide-react';import PageSkeleton from '../components/ui/PageSkeleton';@@ -23,6 +23,9 @@ import { useMediaAnnotations } from '../hooks/useMediaAnnotations';import useMediaPreviewActions from '../hooks/useMediaPreviewActions';import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute';import { useGalleryPage } from '../hooks/useGalleryPage';+import socket from '../services/socket';+import useMounted from '../hooks/useMounted';+import { getMediaJob } from '../services/apiMediaJobs';import {deleteVideoHistoryItem, stitchVideos, deleteImage,} from '../services/api';@@ -41,6 +44,11 @@ export default function MediaHistory() {const [stitchMode, setStitchMode] = useState(false);const [selected, setSelected] = useState([]); // video idsconst [stitching, setStitching] = useState(false);+ // Stitch job ids still running server-side; the toast waits for the job's own+ // terminal event rather than the enqueue response (#13000). The button frees+ // at enqueue: a repeat POST of the same ids returns the live job server-side.+ const stitchJobsRef = useRef(new Set());+ const mounted = useMounted();const [favoritesOnly, setFavoritesOnly] = useState(false);const { annotations, updateAnnotation: saveAnnotation, getCardProps } = useMediaAnnotations();const [annotationSaves, setAnnotationSaves] = useState(0);@@ -71,19 +79,56 @@ export default function MediaHistory() {}, []);const handleSelectCard = useCallback((item) => toggleSelect(item.id), [toggleSelect]);+ const settleStitch = useCallback((id, error = null) => {+ if (!stitchJobsRef.current.delete(id)) return false;+ if (error) toast.error(error);+ else toast.success('Stitched videos');+ return true;+ }, []);++ const recheckStitch = useCallback(async (jobId) => {+ const current = await getMediaJob(jobId).catch(() => null);+ if (!mounted.current) return;+ if (!current?.status && stitchJobsRef.current.delete(jobId)) {+ toast('Stitch status unknown — check media history');+ } else if (current?.status === 'completed' && settleStitch(jobId)) refresh();+ else if (current?.status === 'failed' || current?.status === 'canceled') {+ settleStitch(jobId, current.error || (current.status === 'canceled' ? 'Stitch canceled' : 'Stitch failed'));+ }+ }, [mounted, refresh, settleStitch]);++ useEffect(() => {+ const onCompleted = (event) => settleStitch(event?.generationId);+ const onFailed = (event) => settleStitch(event?.generationId, event?.error || 'Stitch failed');+ const onReconnect = () => { for (const id of stitchJobsRef.current) void recheckStitch(id); };+ socket.on('video-gen:completed', onCompleted);+ socket.on('video-gen:failed', onFailed);+ socket.on('connect', onReconnect);+ return () => {+ socket.off('video-gen:completed', onCompleted);+ socket.off('video-gen:failed', onFailed);+ socket.off('connect', onReconnect);+ };+ }, [recheckStitch, settleStitch]);+const handleStitch = async () => {if (selected.length < 2) return;setStitching(true);try {- await stitchVideos(selected, { silent: true });- toast.success(`Stitched ${selected.length} videos`);+ const { job } = await stitchVideos(selected, { silent: true });+ if (!mounted.current) return;+ stitchJobsRef.current.add(job.jobId);+ setStitching(false);+ toast('Stitch queued — it lands in history when it finishes');setStitchMode(false);setSelected([]);- refresh();+ // Subscribe before this one-shot read: a terminal event can beat the POST+ // acknowledgement, or arrive during the read. The id set settles once.+ await recheckStitch(job.jobId);} catch (err) {- toast.error(err.message || 'Stitch failed');- } finally {+ if (!mounted.current) return;setStitching(false);+ toast.error(err.message || 'Stitch failed');}};diff --git a/client/src/pages/MediaHistory.test.jsx b/client/src/pages/MediaHistory.test.jsxindex e60c21c273..744374f6f4 100644--- a/client/src/pages/MediaHistory.test.jsx+++ b/client/src/pages/MediaHistory.test.jsx@@ -1,24 +1,29 @@+const jobsApi = vi.hoisted(() => ({ getMediaJob: vi.fn() }));+vi.mock('../services/apiMediaJobs', () => jobsApi);const batchApi = vi.hoisted(() => ({ importGalleryFile: vi.fn(), assignImportedMedia: vi.fn() }));vi.mock('../services/apiMedia', () => batchApi);import { beforeEach, describe, expect, it, vi } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';import { MemoryRouter } from 'react-router';-const { fetchPage, deleteImage, saveAnnotation, getGalleryImages, getVideoHistoryItem, listImageVariants } = vi.hoisted(() => ({ fetchPage: vi.fn(), deleteImage: vi.fn(), saveAnnotation: vi.fn(), getGalleryImages: vi.fn(), getVideoHistoryItem: vi.fn(), listImageVariants: vi.fn() }));+const { fetchPage, deleteImage, saveAnnotation, getGalleryImages, getVideoHistoryItem, listImageVariants, stitchVideos, toast, socketHandlers } = vi.hoisted(() => ({ stitchVideos: vi.fn(), toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }), socketHandlers: new Map(), fetchPage: vi.fn(), deleteImage: vi.fn(), saveAnnotation: vi.fn(), getGalleryImages: vi.fn(), getVideoHistoryItem: vi.fn(), listImageVariants: vi.fn() }));vi.mock('../services/apiImageVideo', () => ({ listMediaGalleryPage: fetchPage, getGalleryImages, getVideoHistoryItem, listImageVariants }));-vi.mock('../services/api', () => ({ listMediaGalleryPage: fetchPage, deleteImage, deleteVideoHistoryItem: vi.fn(), stitchVideos: vi.fn() }));+vi.mock('../services/api', () => ({ listMediaGalleryPage: fetchPage, deleteImage, deleteVideoHistoryItem: vi.fn(), stitchVideos }));+vi.mock('../services/socket', () => ({ default: { on: (event, fn) => socketHandlers.set(event, fn), off: (event) => socketHandlers.delete(event) } }));+vi.mock('../components/ui/Toast', () => ({ default: toast }));vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: () => {} }));vi.mock('../hooks/useMediaAnnotations', () => ({ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: saveAnnotation, getCardProps: () => ({}) }) }));vi.mock('../hooks/useMediaPreviewActions', () => ({ default: () => ({}) }));vi.mock('../components/media/VideoUpscaleDrawer', () => ({ default: () => null }));vi.mock('../components/media/MediaPreview', () => ({ default: ({ preview }) => preview ? <div role="dialog">{preview.prompt}{preview.detailError && ' [details unavailable]'}</div> : null }));-vi.mock('../components/media/MediaCard', () => ({ default: ({ item, onDelete, onToggleStar, onPreview }) => <div><button type="button" onClick={() => onPreview(item)}>{item.prompt}</button><button type="button" onClick={() => onToggleStar(item)}>Favorite {item.filename}</button><button type="button" onClick={() => onDelete(item)}>Delete {item.filename}</button></div> }));+vi.mock('../components/media/MediaCard', () => ({ default: ({ item, onDelete, onToggleStar, onPreview, onClick }) => <div>{onClick && <button type="button" onClick={() => onClick(item)}>Pick {item.filename}</button>}<button type="button" onClick={() => onPreview(item)}>{item.prompt}</button><button type="button" onClick={() => onToggleStar(item)}>Favorite {item.filename}</button><button type="button" onClick={() => onDelete(item)}>Delete {item.filename}</button></div> }));vi.mock('../components/media/MediaHistoryGrid', () => ({ default: ({ items, children }) => <div>{items.map(children)}</div> }));import MediaHistory from './MediaHistory';let rows;beforeEach(() => {vi.resetAllMocks();+ jobsApi.getMediaJob.mockResolvedValue({ status: 'queued' });saveAnnotation.mockResolvedValue({ ok: true });rows = Array.from({ length: 61 }, (_, n) => ({ kind: 'image', data: { filename: `${n}.png`, prompt: `Picture ${n}`, createdAt: '2026-01-01' } }));fetchPage.mockImplementation(async ({ limit = 60, offset = 0, q = '', filename }) => {@@ -143,3 +148,65 @@ it('imports a mixed batch from History and inserts both returned records', asyncexpect(await screen.findByText('Imported video prompt')).toBeInTheDocument();expect(batchApi.assignImportedMedia).not.toHaveBeenCalled();});++describe('stitch job', () => {+ it('recovers a terminal result that arrived before enqueue acknowledgement and settles only once', async () => {+ rows = ['a', 'b'].map(id => ({ kind: 'video', data: { id, filename: `${id}.mp4`, prompt: `Clip ${id}`, createdAt: '2026-01-01' } }));+ let acknowledge;+ stitchVideos.mockImplementationOnce(() => new Promise(resolve => { acknowledge = resolve; }));+ jobsApi.getMediaJob.mockResolvedValueOnce({ status: 'completed' });+ open();+ await screen.findByText('Clip a');+ fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));+ await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'fast-job' }));+ expect(toast.success).not.toHaveBeenCalled();+ await act(async () => { acknowledge({ job: { jobId: 'fast-job', status: 'queued' } }); });+ await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));+ await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'fast-job' }));+ expect(toast.success).toHaveBeenCalledTimes(1);++ stitchVideos.mockResolvedValueOnce({ job: { jobId: 'unknown-job', status: 'queued' } });+ jobsApi.getMediaJob.mockRejectedValueOnce(new Error('Status unavailable'));+ fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));+ await waitFor(() => expect(toast).toHaveBeenCalledWith('Stitch status unknown — check media history'));+ await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'unknown-job' }));+ expect(toast.success).toHaveBeenCalledTimes(1);+ });++ it('toasts success only when the job settles, and surfaces an enqueue failure', async () => {+ rows = ['a', 'b'].map(id => ({ kind: 'video', data: { id, filename: `${id}.mp4`, prompt: `Clip ${id}`, createdAt: '2026-01-01' } }));+ stitchVideos.mockResolvedValueOnce({ ok: true, job: { jobId: 'job-1', status: 'queued' } });+ open();+ await screen.findByText('Clip a');+ fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));+ await waitFor(() => expect(stitchVideos).toHaveBeenCalledWith(['a', 'b'], { silent: true }));+ await waitFor(() => expect(toast).toHaveBeenCalled());+ expect(toast.success).not.toHaveBeenCalled();+ await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'unrelated-job' }));+ expect(toast.success).not.toHaveBeenCalled();+ await act(async () => socketHandlers.get('video-gen:failed')(undefined));+ expect(toast.error).not.toHaveBeenCalled();+ jobsApi.getMediaJob.mockResolvedValueOnce({ status: 'completed' });+ await act(async () => socketHandlers.get('connect')());+ await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));+ await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'job-1' }));+ await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));++ stitchVideos.mockRejectedValueOnce(new Error('Queue full'));+ fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));+ fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));+ fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Queue full'));+ expect(toast.success).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 2361b7ff0a..5460f56838 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -47,7 +47,6 @@ import {setHistoryItemHidden,updateHistoryItemPrompt,extractLastFrame,- stitchVideos,upscaleHistoryItem,planUpscaleHistoryItem,resolveFflfLtx2PixelBudget,@@ -58,6 +57,7 @@ import {// re-declaring it just so this file's route schemas can be built.import { UPSCALE_METHODS, DEFAULT_UPSCALE_METHOD } from '../services/videoGen/upscalePlan.js';import { enqueueLtxUpscale } from '../services/videoGen/upscaleJob.js';+import { enqueueStitch } from '../services/videoGen/stitchJob.js';import { trimHistoryItemStart } from '../services/videoGen/trimStart.js';import { cleanupMultipartTemp } from '../services/videoGen/prepareParams.js';import { submitVideoGenJob } from '../services/videoGen/submitJob.js';@@ -1375,8 +1375,9 @@ const stitchBodySchema = z.object({router.post('/stitch', asyncHandler(async (req, res) => {const parsed = stitchBodySchema.safeParse(req.body || {});if (!parsed.success) failValidation(parsed);- const stitched = await stitchVideos(parsed.data.videoIds);- res.json({ ok: true, video: stitched });+ // The concat runs as a media job (#13000); the row lands in history when it+ // finishes. A repeat POST of the same ordered ids returns the live job.+ res.json({ ok: true, job: await enqueueStitch(parsed.data.videoIds) });}));export default router;diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 018bd72122..91540061d3 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -114,6 +114,11 @@ vi.mock('../services/videoGen/upscaleJob.js', () => ({enqueueLtxUpscale: vi.fn(),}));+// Stitch is queued as a media job (#13000); the route reaches it directly.+vi.mock('../services/videoGen/stitchJob.js', () => ({+ enqueueStitch: vi.fn(),+}));+vi.mock('../services/videoGen/trimStart.js', () => ({trimHistoryItemStart: vi.fn(),}));@@ -308,6 +313,7 @@ vi.mock('fs/promises', () => ({import { copyFile, unlink } from 'fs/promises';import * as videoGenService from '../services/videoGen/local.js';import * as upscaleJobService from '../services/videoGen/upscaleJob.js';+import * as stitchJobService from '../services/videoGen/stitchJob.js';import { trimHistoryItemStart } from '../services/videoGen/trimStart.js';import * as mediaJobQueue from '../services/mediaJobQueue/index.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';@@ -3293,21 +3299,21 @@ describe('videoGen routes', () => {expect(r.status).toBe(400);});- it('proxies array of ids to stitchVideos and wraps result', async () => {- videoGenService.stitchVideos.mockResolvedValue({ id: 's1', filename: 's1.mp4' });+ it('queues the stitch and answers with the job before ffmpeg runs', async () => {+ stitchJobService.enqueueStitch.mockResolvedValue({ jobId: 'job-s1', position: 1, status: 'queued' });const r = await request(app).post('/api/video-gen/stitch').send({ videoIds: [validId(1), validId(2)] });expect(r.status).toBe(200);- expect(r.body.ok).toBe(true);- expect(r.body.video.id).toBe('s1');- expect(videoGenService.stitchVideos).toHaveBeenCalledWith([validId(1), validId(2)]);+ expect(r.body).toEqual({ ok: true, job: { jobId: 'job-s1', position: 1, status: 'queued' } });+ expect(stitchJobService.enqueueStitch).toHaveBeenCalledWith([validId(1), validId(2)]);+ expect(videoGenService.stitchVideos).not.toHaveBeenCalled();});it('accepts a shared-gallery upload history id', async () => {- videoGenService.stitchVideos.mockResolvedValue({ id: 's1', filename: 's1.mp4' });+ stitchJobService.enqueueStitch.mockResolvedValue({ jobId: 'job-s2', position: 1, status: 'queued' });const uploadId = 'upload-ab12cd34';const r = await request(app).post('/api/video-gen/stitch').send({ videoIds: [uploadId, validId(2)] });expect(r.status).toBe(200);- expect(videoGenService.stitchVideos).toHaveBeenCalledWith([uploadId, validId(2)]);+ expect(stitchJobService.enqueueStitch).toHaveBeenCalledWith([uploadId, validId(2)]);});});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 8bb18b0a57..1641a688fd 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -218,6 +218,15 @@ const MEDIA_JOB_RUNTIME = Object.freeze({modules: { default: () => import('../videoGen/upscaleJob.js') },invoke: (mod, request) => mod.runVideoUpscale(request),},+ // Hand stitching (#13000): ffmpeg only, so it never touches the GPU lane's+ // render state, and local-only like the upscale (no peer map names it).+ 'video-stitch': {+ events: videoGenEvents,+ verb: 'Stitching',+ watchdogMs: flatWatchdog(WATCHDOG_VIDEO_MS),+ modules: { default: () => import('../videoGen/stitchJob.js') },+ invoke: (mod, request) => mod.runVideoStitch(request),+ },'video-sharing': {events: videoGenEvents,verb: 'Generating',diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex f57a2ee82b..8b2f5a8801 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -83,6 +83,8 @@ const stubs = {hasSurvivingTrainer: vi.fn(async () => false),runVideoUpscale: vi.fn(() => new Promise(() => {})),cancelVideoUpscale: vi.fn(),+ runVideoStitch: vi.fn(() => new Promise(() => {})),+ cancelVideoStitch: vi.fn(),runSharingCopy: vi.fn(async () => ({})),cancelSharingCopy: vi.fn(() => true),renderComposition: vi.fn(async () => ({})),@@ -125,6 +127,11 @@ vi.mock('../videoGen/upscaleJob.js', () => ({cancel: (...args) => stubs.cancelVideoUpscale(...args),}));+vi.mock('../videoGen/stitchJob.js', () => ({+ runVideoStitch: (...args) => stubs.runVideoStitch(...args),+ cancel: (...args) => stubs.cancelVideoStitch(...args),+}));+vi.mock('../videoGen/grok.js', () => ({generateVideo: (...args) => stubs.generateVideoGrok(...args),cancel: (...args) => stubs.cancelVideo(...args),@@ -246,6 +253,7 @@ beforeEach(async () => {stubs.runTraining.mockImplementation(() => new Promise(() => {}));stubs.hasSurvivingTrainer.mockResolvedValue(false);stubs.runVideoUpscale.mockImplementation(() => new Promise(() => {}));+ stubs.runVideoStitch.mockImplementation(() => new Promise(() => {}));await importFresh();});@@ -4223,6 +4231,7 @@ describe('mediaJobQueue per-kind runtime wiring', () => {const KIND_CASES = [{ kind: 'video', params: {}, entry: 'generateVideo', bus: 'video', verb: 'Rendering', window: WINDOWS.VIDEO },{ kind: 'video-upscale', params: {}, entry: 'runVideoUpscale', bus: 'video', verb: 'Upscaling', window: WINDOWS.VIDEO },+ { kind: 'video-stitch', params: {}, entry: 'runVideoStitch', bus: 'video', verb: 'Stitching', window: WINDOWS.VIDEO },{ kind: 'video-sharing', params: { sharingProjectId: 'mv-example', renderHistoryId: 'final-example', sourceHash: 'a'.repeat(64) },entry: 'runSharingCopy', bus: 'video', verb: 'Generating', window: WINDOWS.VIDEO },{ kind: 'html-composition', params: { directory: 'compositions/example' }, entry: 'renderComposition', bus: 'video', verb: 'Generating', window: WINDOWS.IMAGE },diff --git a/server/services/videoGen/stitchJob.js b/server/services/videoGen/stitchJob.jsnew file mode 100644index 0000000000..826f5a57ec--- /dev/null+++ b/server/services/videoGen/stitchJob.js@@ -0,0 +1,73 @@+/**+ * Hand stitching as a media job (#13000). The concat runs ffmpeg for as long as+ * the clips are long, so `POST /api/video-gen/stitch` queues it and returns the+ * job; the new gallery row lands when the worker finishes.+ *+ * Cancel handles live in this module rather than the shared `videoJobState`:+ * a stitch child is not a GPU render, so `videoGen.cancel()` must never kill+ * it (same split as upscaleJob.js). Chained and continuous renders keep calling+ * `stitchVideos` in-process with their own id and never come through here.+ */++import { enqueueJob, listJobs } from '../mediaJobQueue/index.js';+import { videoGenEvents } from './events.js';+import { stitchVideos } from './stitchVideos.js';++export const STITCH_JOB_KIND = 'video-stitch';++// jobId → { abort } for the in-flight worker run.+const activeStitches = new Map();+const pendingAdmissions = new Map();++const stitchKey = (videoIds) => videoIds.join(',');++/**+ * Queue a stitch of `videoIds` (in order). A queued or running job for the same+ * ordered ids is returned instead of starting a second encode and a second row.+ */+export async function enqueueStitch(videoIds) {+ const key = stitchKey(videoIds);+ const pending = pendingAdmissions.get(key);+ if (pending) return { ...await pending, deduplicated: true };+ const live = listJobs({ kind: STITCH_JOB_KIND })+ .find((j) => (j.status === 'queued' || j.status === 'running') && j.params?.stitchKey === key);+ if (live) return { jobId: live.id, position: live.position, status: live.status, deduplicated: true };+ const admission = enqueueJob({+ kind: STITCH_JOB_KIND,+ params: {+ videoIds,+ stitchKey: key,+ prompt: `Stitch ${videoIds.length} videos`,+ },+ });+ pendingAdmissions.set(key, admission);+ return admission.finally(() => pendingAdmissions.delete(key));+}++// Called by mediaJobQueue's cancelJob and its idle watchdog.+export function cancel(jobId) {+ const entry = activeStitches.get(jobId);+ if (!entry) return false;+ entry.abort.abort();+ return true;+}++/** What the queue worker invokes; settles on the videoGen event bus like upscale. */+export async function runVideoStitch({ jobId, videoIds }) {+ const entry = { abort: new AbortController() };+ activeStitches.set(jobId, entry);+ let result = null;+ let failureReason;+ try {+ videoGenEvents.emit('started', { generationId: jobId, id: jobId, stitchedFrom: videoIds, etaMs: null });+ result = await stitchVideos(videoIds, { id: jobId, signal: entry.abort.signal });+ } catch (err) {+ failureReason = entry.abort.signal.aborted ? 'Canceled while running' : (err.message || 'Stitch failed');+ console.error(`❌ Video stitch ${entry.abort.signal.aborted ? 'canceled' : 'failed'} [${jobId.slice(0, 8)}]: ${failureReason}`);+ } finally {+ activeStitches.delete(jobId);+ }+ if (failureReason) videoGenEvents.emit('failed', { generationId: jobId, error: failureReason });+ else videoGenEvents.emit('completed', { generationId: jobId, ...result });+ return result;+}diff --git a/server/services/videoGen/stitchJob.test.js b/server/services/videoGen/stitchJob.test.jsnew file mode 100644index 0000000000..b8e1647cae--- /dev/null+++ b/server/services/videoGen/stitchJob.test.js@@ -0,0 +1,85 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { EventEmitter } from 'events';++const state = vi.hoisted(() => ({ jobs: [], enqueued: [], stitch: null, admission: null }));++vi.mock('../mediaJobQueue/index.js', () => ({+ listJobs: vi.fn(({ kind }) => state.jobs.filter((j) => j.kind === kind)),+ enqueueJob: vi.fn(async (job) => {+ state.enqueued.push(job);+ await state.admission?.();+ return { jobId: `job-${state.enqueued.length}`, position: 1, status: 'queued' };+ }),+}));+vi.mock('./events.js', () => ({ videoGenEvents: new EventEmitter() }));+vi.mock('./stitchVideos.js', () => ({ stitchVideos: vi.fn((...args) => state.stitch(...args)) }));++const { enqueueStitch, runVideoStitch, cancel, STITCH_JOB_KIND } = await import('./stitchJob.js');+const { videoGenEvents } = await import('./events.js');++beforeEach(() => {+ state.jobs = [];+ state.enqueued = [];+ state.admission = null;+ state.stitch = async (ids, { id }) => ({ id, stitchedFrom: ids });+ videoGenEvents.removeAllListeners();+});++describe('enqueueStitch', () => {+ it('coalesces overlapping admissions before queue persistence completes', async () => {+ let release;+ state.admission = () => new Promise(resolve => { release = resolve; });+ const first = enqueueStitch(['a', 'b']);+ const duplicate = enqueueStitch(['a', 'b']);+ expect(state.enqueued).toHaveLength(1);+ release();+ await expect(first).resolves.toMatchObject({ jobId: 'job-1' });+ await expect(duplicate).resolves.toMatchObject({ jobId: 'job-1', deduplicated: true });+ });++ it('does not retain a rejected admission as a live job', async () => {+ state.admission = async () => { throw new Error('Could not save queue'); };+ await expect(enqueueStitch(['a', 'b'])).rejects.toThrow('Could not save queue');+ state.admission = null;+ await expect(enqueueStitch(['a', 'b'])).resolves.toMatchObject({ jobId: 'job-2' });+ });++ it('returns the live job for the same ordered ids instead of queueing a second encode', async () => {+ state.jobs = [{ id: 'live', kind: STITCH_JOB_KIND, status: 'running', position: 1, params: { stitchKey: 'a,b' } }];+ await expect(enqueueStitch(['a', 'b'])).resolves.toMatchObject({ jobId: 'live', deduplicated: true });+ expect(state.enqueued).toHaveLength(0);+ });++ it('queues a different selection, a reordered one, and a repeat after the job settled', async () => {+ state.jobs = [+ { id: 'live', kind: STITCH_JOB_KIND, status: 'queued', params: { stitchKey: 'a,b' } },+ { id: 'done', kind: STITCH_JOB_KIND, status: 'completed', params: { stitchKey: 'c,d' } },+ ];+ await enqueueStitch(['a', 'c']);+ await enqueueStitch(['b', 'a']);+ await enqueueStitch(['c', 'd']);+ expect(state.enqueued.map((j) => j.params.stitchKey)).toEqual(['a,c', 'b,a', 'c,d']);+ });+});++describe('runVideoStitch', () => {+ it('stitches under the job id and emits completed with the new row', async () => {+ const done = vi.fn();+ videoGenEvents.on('completed', done);+ await runVideoStitch({ jobId: 'j1', videoIds: ['a', 'b'] });+ expect(done).toHaveBeenCalledWith(expect.objectContaining({ generationId: 'j1', id: 'j1' }));+ });++ it('cancel aborts the signal handed to stitchVideos and settles as failed', async () => {+ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ state.stitch = (ids, { signal }) => new Promise((_, reject) => {+ signal.addEventListener('abort', () => reject(new Error('Stitch canceled')));+ });+ const run = runVideoStitch({ jobId: 'j2', videoIds: ['a', 'b'] });+ expect(cancel('j2')).toBe(true);+ await run;+ expect(failed).toHaveBeenCalledWith({ generationId: 'j2', error: 'Canceled while running' });+ expect(cancel('j2')).toBe(false);+ });+});diff --git a/server/services/videoGen/stitchVideos.cancel.test.js b/server/services/videoGen/stitchVideos.cancel.test.jsnew file mode 100644index 0000000000..23e42855a1--- /dev/null+++ b/server/services/videoGen/stitchVideos.cancel.test.js@@ -0,0 +1,57 @@+import { describe, it, expect, vi, afterAll } from 'vitest';+import { EventEmitter } from 'events';+import { join } from 'path';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('portos-stitch-cancel-') }) };+});+afterAll(cleanupTempDataRoots);++const state = vi.hoisted(() => ({ proc: null, kills: [], published: false }));++vi.mock('../../lib/childProcess.js', async (importOriginal) => ({+ ...(await importOriginal()),+ spawn: vi.fn(() => {+ const proc = new EventEmitter();+ proc.exitCode = null;+ proc.signalCode = null;+ proc.kill = (sig) => {+ state.kills.push(sig);+ proc.signalCode = sig;+ queueMicrotask(() => proc.emit('close', null));+ };+ state.proc = proc;+ return proc;+ }),+}));+vi.mock('../../lib/ffmpeg.js', () => ({+ findFfmpeg: vi.fn(async () => 'ffmpeg'),+ safeUnder: vi.fn((base, name) => join(base, name)),+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),+ optimizeForStreaming: vi.fn(async () => {}),+ hasAudioStream: vi.fn(async () => true),+ buildTrimConcatArgs: vi.fn(),+ bt709TagFilter: vi.fn(async () => null),+}));+vi.mock('./generateVideoHelpers.js', () => ({ discardUnpublishedVideo: vi.fn() }));+vi.mock('fs', async (importOriginal) => ({ ...(await importOriginal()), existsSync: () => true }));+vi.mock('./history.js', () => ({+ loadHistory: vi.fn(async () => ['a', 'b'].map((id) => ({ id, filename: `${id}.mp4`, prompt: id, modelId: 'm', width: 1, height: 1, fps: 24 }))),+ mutateVideoHistory: vi.fn(async () => { state.published = true; }),+}));++const { stitchVideos } = await import('./stitchVideos.js');++describe('stitchVideos cancellation', () => {+ it('kills the ffmpeg child and publishes no history row', async () => {+ const abort = new AbortController();+ const run = stitchVideos(['a', 'b'], { id: 'job-x', signal: abort.signal });+ await vi.waitFor(() => expect(state.proc).not.toBeNull());+ abort.abort();+ await expect(run).rejects.toMatchObject({ code: 'STITCH_CANCELED' });+ expect(state.kills).toContain('SIGTERM');+ expect(state.published).toBe(false);+ });+});diff --git a/server/services/videoGen/stitchVideos.js b/server/services/videoGen/stitchVideos.jsindex b1fe0f3cc9..9575d003a4 100644--- a/server/services/videoGen/stitchVideos.js+++ b/server/services/videoGen/stitchVideos.js@@ -14,6 +14,7 @@ import {hasAudioStream, buildTrimConcatArgs, bt709TagFilter,} from '../../lib/ffmpeg.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';+import { killWithEscalation } from '../../lib/killWithEscalation.js';import { renderTimingFields } from '../../lib/renderTiming.js';import { loadHistory, mutateVideoHistory } from './history.js';@@ -98,6 +99,9 @@ export async function stitchVideos(videoIds, opts = {}) {// "no cut, but here is the real length." Only a non-zero offset routes the// concat through the filter graph.trims = null,+ // Optional AbortSignal (the stitch media job's cancel): kills the ffmpeg+ // child and removes the partial output so a cancelled encode publishes no row.+ signal = null,} = opts;if (!Array.isArray(videoIds) || videoIds.length < 2) {throw new ServerError('Need at least 2 videos to stitch', { status: 400, code: 'VALIDATION_ERROR' });@@ -160,12 +164,22 @@ export async function stitchVideos(videoIds, opts = {}) {// return, so a failure mid-encode would otherwise trail a run of them behind// the line that matters.const runFfmpeg = (args, { captureStderr = false } = {}) => new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(new ServerError('Stitch canceled', { status: 499, code: 'STITCH_CANCELED' }));+ return;+ }const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: captureStderr ? ['ignore', 'ignore', 'pipe'] : 'ignore' }));+ const onAbort = () => killWithEscalation(proc, { label: 'stitch ffmpeg child', stillRunning: () => true });+ signal?.addEventListener('abort', onAbort, { once: true });+ proc.on('close', () => signal?.removeEventListener('abort', onAbort));let tail = '';proc.stderr?.on('data', (d) => { tail = `${tail}${d}`.slice(-400); });- proc.on('close', (code) => code === 0- ? resolve()- : reject(new ServerError(`Stitch failed${tail ? `: ${tail.split(/[\r\n]+/).filter(Boolean).pop()?.trim() || ''}` : ''}`, { status: 500, code: 'FFMPEG_FAILED' })));+ proc.on('close', (code) => {+ if (signal?.aborted) return reject(new ServerError('Stitch canceled', { status: 499, code: 'STITCH_CANCELED' }));+ if (code === 0) return resolve();+ const detail = tail ? `: ${tail.split(/[\r\n]+/).filter(Boolean).pop()?.trim() || ''}` : '';+ reject(new ServerError(`Stitch failed${detail}`, { status: 500, code: 'FFMPEG_FAILED' }));+ });proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));});@@ -216,6 +230,11 @@ export async function stitchVideos(videoIds, opts = {}) {await runFfmpeg(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath], { captureStderr: true });}await optimizeForStreaming(outPath);+ if (signal?.aborted) throw new ServerError('Stitch canceled', { status: 499, code: 'STITCH_CANCELED' });+ } catch (err) {+ // A canceled encode leaves a partial file that no history row will ever own.+ if (signal?.aborted) await unlinkGuarded(outPath).catch(() => {});+ throw err;} finally {if (listFileWritten) await unlinkGuarded(listFile).catch(() => {});}