Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: split video renders into independent lanes

[._.]/ Adam Eivyf1f7d18115e4
diff --git a/client/src/components/media/BatchQueuePanel.jsx b/client/src/components/media/BatchQueuePanel.jsx
deleted file mode 100644
index 6bc3685ccd..0000000000
--- a/client/src/components/media/BatchQueuePanel.jsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { Trash2, CheckCircle2, AlertCircle, Loader2, Clock } from 'lucide-react';
-
-// Shared batch-queue panel used by both Video Gen and Image Gen. The owner
-// page tracks queue state and the worker effect; this component is
-// presentation-only — it renders the list, status icons, and the
-// remove/clear-finished affordances.
-//
-// Each item is { id, status: 'pending'|'running'|'complete'|'error',
-// params: { prompt, mode, ... }, error?, ... }. `summarize` lets the host
-// page format the per-item subtitle line however it wants (e.g. video
-// shows resolution+frames, image shows resolution+steps).
-
-const STATUS_ICON = {
- pending: { Icon: Clock, color: 'text-gray-400' },
- running: { Icon: Loader2, color: 'text-port-accent animate-spin' },
- complete: { Icon: CheckCircle2, color: 'text-port-success' },
- error: { Icon: AlertCircle, color: 'text-port-error' },
-};
-
-export default function BatchQueuePanel({ queue, onRemove, onClear, summarize }) {
- if (!queue.length) return null;
- // Compute status text from the queue itself so callers don't have to
- // pass in pre-aggregated counts. Distinguishing "running" (1, the actively
- // processing job) from "queued" (pending count) is more accurate than the
- // earlier "X in flight" copy, which lumped both together.
- // "finished" covers both successful and errored items because the clear
- // action removes both — counting only `complete` would understate what the
- // button is about to clear.
- const finishedCount = queue.filter((q) => q.status === 'complete' || q.status === 'error').length;
- const runningCount = queue.filter((q) => q.status === 'running').length;
- const pendingCount = queue.filter((q) => q.status === 'pending').length;
- const queueStatusText =
- runningCount > 0 && pendingCount > 0
- ? `${runningCount} running, ${pendingCount} queued`
- : runningCount > 0
- ? `${runningCount} running`
- : pendingCount > 0
- ? `${pendingCount} queued`
- : 'idle';
- return (
- <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">
- <div className="flex items-center justify-between">
- <h2 className="text-sm font-medium text-gray-300">
- Batch queue
- <span className="ml-2 text-xs text-gray-500">{queueStatusText}</span>
- </h2>
- {finishedCount > 0 && (
- <button
- type="button"
- onClick={onClear}
- className="text-xs text-gray-400 hover:text-white"
- >
- Clear finished ({finishedCount})
- </button>
- )}
- </div>
- <ul className="space-y-2 max-h-72 overflow-y-auto">
- {queue.map((item) => {
- const { Icon, color } = STATUS_ICON[item.status] || STATUS_ICON.pending;
- return (
- <li
- key={item.id}
- className="flex items-center gap-3 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-xs"
- >
- <Icon className={`w-4 h-4 flex-shrink-0 ${color}`} />
- <div className="flex-1 min-w-0">
- <div className="text-gray-200 truncate">{item.params.prompt}</div>
- <div className="text-gray-500 text-[11px] truncate">
- {summarize(item)}
- {item.error && <span className="text-port-error ml-2">— {item.error}</span>}
- </div>
- </div>
- <button
- type="button"
- onClick={() => onRemove(item.id)}
- disabled={item.status === 'running'}
- className="p-1 text-gray-500 hover:text-port-error disabled:opacity-30 disabled:cursor-not-allowed"
- aria-label={item.status === 'running' ? 'Cancel via the form button' : 'Remove from queue'}
- title={item.status === 'running' ? 'Cancel via the form button' : 'Remove from queue'}
- >
- <Trash2 aria-hidden="true" className="w-3.5 h-3.5" />
- </button>
- </li>
- );
- })}
- </ul>
- </div>
- );
-}
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 0d8122fb41..c8e81a5ac0 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -43,6 +43,23 @@ const STATUS_BADGE = {
const KIND_ICON = { video: Film, image: ImageIcon, training: Cpu };
+// Video jobs are scheduled by the server into independent execution lanes.
+// Keep the UI labels aligned with the user-facing targets rather than exposing
+// implementation names such as "gpu" and "cloud". Remote jobs are already
+// projected with renderer="remote"; Grok video jobs carry the Grok mode while
+// local video jobs carry their pipeline mode (text/image/etc.).
+const VIDEO_QUEUE_LANES = Object.freeze([
+ { id: 'local', label: 'Local machine', description: 'Local GPU renders run one at a time.' },
+ { id: 'grok', label: 'Grok', description: 'Grok renders use a cloud lane in parallel with local work.' },
+ { id: 'remote', label: 'Remote machines', description: 'Each selected peer owns the queue for work it receives.' },
+]);
+
+const videoQueueLane = (job) => {
+ if (job?.renderer === 'remote') return 'remote';
+ if (job?.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return 'grok';
+ return 'local';
+};
+
// Creative Director scene renders use the same durable media queue as manual
// Video Gen renders, but carry an owner tag so the orchestrator can reconcile
// completion. Keep that ownership visible in the shared queue: otherwise an
@@ -165,6 +182,13 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
return { live: liveJobs, recent: recentJobs, queuedCount: queued, failedCount: failed };
}, [jobs, recentLimit]);
+ const videoLanes = useMemo(() => {
+ if (kind !== 'video') return [];
+ return VIDEO_QUEUE_LANES
+ .map((lane) => ({ ...lane, jobs: live.filter((job) => videoQueueLane(job) === lane.id) }))
+ .filter((lane) => lane.jobs.length > 0);
+ }, [kind, live]);
+
// Accepts optional `overrides` so the inline Edit form can patch prompt /
// negativePrompt / model / dimensions before the re-enqueue. No overrides =
// same behavior as the plain Retry button.
@@ -192,7 +216,9 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
})
.catch((err) => toast.error(err?.message || 'Delete failed'));
const KIND_LABEL = { image: 'Image', video: 'Video', training: 'Training' };
- const headerLabel = kind ? `${KIND_LABEL[kind] || ''} ${kind === 'training' ? 'Queue' : 'Render Queue'}`.trim() : 'Render Queue';
+ const headerLabel = kind
+ ? `${KIND_LABEL[kind] || ''} ${kind === 'training' ? 'Queue' : kind === 'video' ? 'Render Queues' : 'Render Queue'}`.trim()
+ : 'Render Queue';
const handleClearQueued = () => {
if (!queuedCount) return;
@@ -253,7 +279,28 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
</div>
) : (
<div className="space-y-2">
- {live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} onRetry={handleRetry} onRunNow={handleRunNow} />)}
+ {kind === 'video' ? (
+ <div className="space-y-3">
+ {videoLanes.map((lane) => (
+ <section
+ key={lane.id}
+ aria-label={`${lane.label} video queue`}
+ className="space-y-1.5"
+ title={lane.description}
+ >
+ <div className="flex items-center justify-between gap-2 px-1">
+ <h3 className="text-[11px] font-medium text-gray-300 uppercase tracking-wide">{lane.label}</h3>
+ <span className="text-[11px] text-port-text-muted">{formatLaneCounts(lane.jobs)}</span>
+ </div>
+ {lane.jobs.map((j) => (
+ <JobRow key={j.id} job={j} onCancel={handleCancel} onRetry={handleRetry} onRunNow={handleRunNow} />
+ ))}
+ </section>
+ ))}
+ </div>
+ ) : (
+ live.map((j) => <JobRow key={j.id} job={j} onCancel={handleCancel} onRetry={handleRetry} onRunNow={handleRunNow} />)
+ )}
{recent.length > 0 && (
<button
@@ -280,6 +327,15 @@ function formatCounts(live, recent, failedCount) {
return parts.join(' • ');
}
+function formatLaneCounts(jobs) {
+ const running = jobs.filter((job) => job.status === 'running').length;
+ const queued = jobs.filter((job) => job.status === 'queued').length;
+ return [
+ running > 0 ? `${running} running` : null,
+ queued > 0 ? `${queued} queued` : null,
+ ].filter(Boolean).join(' · ');
+}
+
// One-line training summary in place of the (absent) prompt: who's training,
// the LoRA rank, and the step budget.
function trainingSummary(params) {
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
index 0de4dd17f0..cc6afbddbd 100644
--- a/client/src/components/media/MediaJobsQueue.test.jsx
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -126,6 +126,44 @@ describe('MediaJobsQueue — Creative Director renders', () => {
});
});
+describe('MediaJobsQueue — video render lanes', () => {
+ it('shows local, Grok, and remote work in separate queues', async () => {
+ listMediaJobs.mockResolvedValue([
+ {
+ id: 'localvideo0001',
+ kind: 'video',
+ status: 'running',
+ queuedAt: '2026-06-19T10:00:00Z',
+ params: { prompt: 'an invented local shot', mode: 'text', modelId: 'local-video' },
+ },
+ {
+ id: 'grokvideo0001',
+ kind: 'video',
+ status: 'running',
+ queuedAt: '2026-06-19T10:01:00Z',
+ params: { prompt: 'an invented cloud shot', mode: 'grok' },
+ },
+ {
+ id: 'remotevideo001',
+ kind: 'video',
+ status: 'queued',
+ queuedAt: '2026-06-19T10:02:00Z',
+ renderer: 'remote',
+ params: { prompt: 'an invented peer shot', mode: 'text', modelId: 'peer-video' },
+ },
+ ]);
+
+ render(<MediaJobsQueue kind="video" />);
+
+ expect(await screen.findByRole('region', { name: 'Local machine video queue' })).toHaveTextContent('an invented local shot');
+ expect(screen.getByRole('region', { name: 'Grok video queue' })).toHaveTextContent('an invented cloud shot');
+ expect(screen.getByRole('region', { name: 'Remote machines video queue' })).toHaveTextContent('an invented peer shot');
+ expect(screen.getByRole('heading', { name: 'Local machine' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Grok' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Remote machines' })).toBeInTheDocument();
+ });
+});
+
describe('MediaJobsQueue — federated render badge', () => {
it('badges a peer-rendered job remote instead of claiming a local render', async () => {
// The server projects `renderer` and rebuilds `modelId` off the wire
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 7d6beb9a4d..196bf9ac11 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -209,7 +209,6 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). |
| `useVideoGenFieldState` | Mutable VideoGen field values, setters, and lifecycle refs initialized from URL handoff values. | Internal state slice composed by `useVideoGenForm`; keep model reconciliation and submission behavior in their focused units. |
| `useVideoGenForm` | `useVideoGenForm({ models, status, availableLoras, grokEnabled })` → every VideoGen form field + setter, the URL-param prefill paths (ImageGen handoff, Continue, Remix, `?lora=`), the mode/backend transitions that clear stale inputs, the derived model/keyframe/IC gates (`extendModeBlocked`, `a2vModeBlocked`, `icLoraModeBlocked`, `keyframesError`), `applyRemix` / `applyResumedParams`, and `buildGeneratePayload()`. | The /media/video form — the single client-side source of truth for the payload `server/routes/videoGen.js` validates. Reuse it for any second entry point that generates video. |
-| `useVideoGenQueue` | `useVideoGenQueue({ generating, runGeneration })` → `{ queue, runningQueueId, enqueue, removeFromQueue, clearFinishedQueue, cancelRunning }`. Client-side serial batch queue for VideoGen: owns the queue array + running marker + the worker effect that pumps the head whenever nothing is generating (with BUSY-backoff retry + unmount/staleness guards). | The VideoGen "Add to queue" batch flow. |
| `useVideoGenSubmitFlow` | Builds the current VideoGen wire payload and enveloped prompt from a form-state snapshot. | Internal submission slice composed by `useVideoGenForm`; all local, Grok, and federated request shaping remains in `videoGenSubmission`. |
| `useVideoGenValidation` | Derives keyframe errors and all VideoGen submit-blocking predicates from the current fields and model capabilities. | Internal validation slice composed by `useVideoGenForm`; also exports `validateVideoKeyframes` for focused tests. |
| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, context, start(url, context), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 03e99cc8c4..aa9c977e7e 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -208,7 +208,6 @@ export * from './useUniverseNav.js';
export * from './useVideoFileSrc.js';
export * from './useVideoGenFieldState.js';
export * from './useVideoGenForm.js';
-export * from './useVideoGenQueue.js';
export * from './useVideoGenSubmitFlow.js';
export * from './useVideoGenValidation.js';
export * from './useVoiceUiSync.js';
diff --git a/client/src/hooks/useVideoGenQueue.js b/client/src/hooks/useVideoGenQueue.js
deleted file mode 100644
index 58f6cd7f9d..0000000000
--- a/client/src/hooks/useVideoGenQueue.js
+++ /dev/null
@@ -1,172 +0,0 @@
-import { useState, useEffect, useRef, useCallback } from 'react';
-import { uuidv4 } from '../lib/uuid.js';
-import useMounted from './useMounted.js';
-import toast from '../components/ui/Toast';
-
-const newQueueId = () => uuidv4();
-
-/**
- * Client-side serial batch queue for VideoGen (#2834). Owns the queue array,
- * the running-item marker, and the worker effect that pumps the head of the
- * queue whenever nothing is generating.
- *
- * The caller supplies:
- * - `generating` — the page's in-flight flag; the worker parks while true.
- * - `runGeneration(payload)` — runs one payload through the SSE pipeline and
- * resolves/rejects when the job settles. Held on a ref so the worker always
- * calls the latest closure without re-subscribing the effect on every
- * render (the page recreates runGeneration each render).
- *
- * Returns the queue state plus `enqueue` / `removeFromQueue` /
- * `clearFinishedQueue` / `cancelRunning` mutators.
- */
-export function useVideoGenQueue({ generating, runGeneration }) {
- // Each item snapshots the params at enqueue time so the user can keep editing
- // the form while jobs are in flight without affecting the queued ones. The
- // active generation is held in the page's `generating`/`progress`;
- // `runningQueueId` (if set) marks which queued item it represents.
- const [queue, setQueue] = useState([]);
- const [runningQueueId, setRunningQueueId] = useState(null);
-
- // Always call the freshest runGeneration without listing it in the worker
- // effect's deps — the page recreates it every render, and re-running the
- // worker on identity churn would re-dispatch.
- const runGenerationRef = useRef(runGeneration);
- runGenerationRef.current = runGeneration;
-
- // BUSY-backoff retry timer for the queue worker, held on a ref so it can be
- // cleared from a stable unmount cleanup regardless of how often the worker
- // effect re-runs (setQueue/setRunningQueueId churn consumes the effect's own
- // cleanup before the async .catch ever assigns the timer, so the effect
- // cleanup alone can't be trusted to clear it).
- const busyRetryTimerRef = useRef(null);
- // Generation token for the queue-worker dispatch. Bumped only when a new item
- // is actually dispatched; a stale async then/catch/finally (from a superseded
- // dispatch or after unmount) sees a moved-on token and bails without touching
- // state or re-releasing the running slot.
- const queueWorkerGenRef = useRef(0);
- // Unmount guard for the queue worker's deferred callbacks (StrictMode-safe:
- // resets to true on mount, so the mount→cleanup→remount cycle can't strand it
- // false and freeze the queue worker). A dedicated unmount cleanup clears any
- // pending BUSY-retry timer — this is the authoritative clear (the worker
- // effect's own cleanup is unreliable, see the queue-worker effect below).
- const mountedRef = useMounted();
- useEffect(() => () => {
- if (busyRetryTimerRef.current) {
- clearTimeout(busyRetryTimerRef.current);
- busyRetryTimerRef.current = null;
- }
- }, []);
-
- const enqueue = useCallback((payload) => {
- // Preserve string properties in params so filenames/URLs/strings aren't stripped,
- // and hold File/Blob objects in _blobs.
- const _blobs = {};
- const params = {};
- for (const [k, v] of Object.entries(payload)) {
- if (v instanceof File || v instanceof Blob) {
- _blobs[k] = v;
- } else if (Array.isArray(v) && v.some((item) => item instanceof File || item instanceof Blob)) {
- _blobs[k] = v;
- } else {
- params[k] = v;
- }
- }
- setQueue((q) => [...q, {
- id: newQueueId(),
- status: 'pending',
- params,
- _blobs,
- enqueuedAt: Date.now(),
- }]);
- toast.success('Added to queue');
- }, []);
-
- const removeFromQueue = useCallback((id) => {
- setQueue((q) => q.filter((item) => item.id !== id || item.status === 'running'));
- }, []);
-
- // Drops both successful and errored items — the panel surfaces this as
- // "Clear finished" so the label matches the behavior.
- const clearFinishedQueue = useCallback(() => {
- setQueue((q) => q.filter((item) => item.status !== 'complete' && item.status !== 'error'));
- }, []);
-
- // Mark the running item errored + release the slot (called from the page's
- // Cancel handler). No-op when nothing is running.
- const cancelRunning = useCallback(() => {
- if (!runningQueueId) return;
- setQueue((q) => q.map((item) => item.id === runningQueueId ? { ...item, status: 'error', error: 'Cancelled' } : item));
- setRunningQueueId(null);
- }, [runningQueueId]);
-
- // Queue worker — pumps the head of the queue when nothing's running.
- // Runs as an effect so it picks up any newly-enqueued item even while
- // the user is interacting with the form.
- //
- // BUSY backoff: the server's `cancel()` keeps `activeProcess` set until
- // the SIGKILL'd child actually exits (up to ~8s), so a freshly-cancelled
- // item leaving the running slot here will often hit a 409 VIDEO_GEN_BUSY
- // when the worker tries to dispatch the next pending item. Treat that as
- // "not yet" (return the item to pending) instead of marking it errored.
- useEffect(() => {
- if (generating || runningQueueId) return;
- const next = queue.find((item) => item.status === 'pending');
- if (!next) return;
- // Capture a generation token for this dispatch. Every deferred callback
- // below re-checks it (via isCurrent) so a superseded dispatch or an
- // unmount can't set state / re-release the running slot after teardown.
- const myGen = ++queueWorkerGenRef.current;
- const isCurrent = () => mountedRef.current && myGen === queueWorkerGenRef.current;
- setRunningQueueId(next.id);
- setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'running', startedAt: Date.now() } : item));
- const payload = { ...next.params };
- if (next._blobs) {
- for (const [k, v] of Object.entries(next._blobs)) {
- if (v != null) payload[k] = v;
- }
- }
- let busyRetry = false;
- runGenerationRef.current(payload).then((res) => {
- if (!isCurrent()) return;
- setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'complete', result: res } : item));
- }).catch((err) => {
- if (!isCurrent()) return;
- const isBusy = /already in progress|VIDEO_GEN_BUSY|409/i.test(err?.message || '');
- if (isBusy) {
- // Bounce the item back to pending after a short delay so the worker
- // re-tries once the server's previous child has finished cleaning up.
- busyRetry = true;
- setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'pending', startedAt: undefined } : item));
- busyRetryTimerRef.current = setTimeout(() => {
- busyRetryTimerRef.current = null;
- // Stale/unmounted: a fresh dispatch (or teardown) already owns the
- // slot, so don't release it out from under whatever runs now.
- if (!isCurrent()) return;
- setRunningQueueId((curr) => (curr === next.id ? null : curr));
- }, 1500);
- return;
- }
- setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'error', error: err.message } : item));
- }).finally(() => {
- // For the BUSY branch the timeout above releases the slot — releasing
- // it here too would let the worker immediately re-fire and hit the
- // same 409 before the server's old child has exited.
- if (isCurrent() && !busyRetry) setRunningQueueId(null);
- });
- // Effect cleanup: cancel a pending BUSY-retry setTimeout. This is a
- // best-effort clear; because the worker effect re-runs on every
- // setQueue/setRunningQueueId, this cleanup is usually consumed before the
- // async .catch assigns the timer — the authoritative clear lives in the
- // dedicated unmount effect above, and the isCurrent()/mountedRef guards in
- // the timer callback prevent any stale setState.
- return () => {
- if (busyRetryTimerRef.current) {
- clearTimeout(busyRetryTimerRef.current);
- busyRetryTimerRef.current = null;
- }
- };
- }, [queue, generating, runningQueueId, mountedRef]);
-
- return { queue, runningQueueId, enqueue, removeFromQueue, clearFinishedQueue, cancelRunning };
-}
diff --git a/client/src/hooks/useVideoGenQueue.test.jsx b/client/src/hooks/useVideoGenQueue.test.jsx
deleted file mode 100644
index 58e5bad315..0000000000
--- a/client/src/hooks/useVideoGenQueue.test.jsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { renderHook, act, waitFor } from '@testing-library/react';
-
-vi.mock('../components/ui/Toast', () => ({
- default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
-}));
-
-import { useVideoGenQueue } from './useVideoGenQueue.js';
-import toast from '../components/ui/Toast';
-
-const flush = () => act(async () => {});
-
-describe('useVideoGenQueue', () => {
- beforeEach(() => {
- toast.success.mockClear();
- });
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('preserves string filenames and File/Blob objects when a queued item is dispatched', async () => {
- const sourceImageFile = new File(['x'], 'source.png', { type: 'image/png' });
- const seen = [];
- const runGeneration = vi.fn(async (payload) => {
- seen.push(payload);
- return { ok: true };
- });
-
- const { result } = renderHook(() => useVideoGenQueue({
- generating: false,
- runGeneration,
- }));
-
- act(() => {
- result.current.enqueue({
- prompt: 'a cinematic scene',
- sourceImage: 'gallery_source.png',
- lastImage: 'gallery_last.png',
- icReferenceImageFiles: ['ref1.png', 'ref2.png'],
- keyframes: [{ frame: 0, image: 'f1.png' }],
- sourceImageFile,
- });
- });
-
- await waitFor(() => expect(runGeneration).toHaveBeenCalledTimes(1));
- expect(seen[0].sourceImage).toBe('gallery_source.png');
- expect(seen[0].lastImage).toBe('gallery_last.png');
- expect(seen[0].icReferenceImageFiles).toEqual(['ref1.png', 'ref2.png']);
- expect(seen[0].keyframes).toEqual([{ frame: 0, image: 'f1.png' }]);
- expect(seen[0].sourceImageFile).toBe(sourceImageFile);
- });
-
- it('retries a BUSY item after the backoff instead of marking it errored', async () => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- let calls = 0;
- const runGeneration = vi.fn(() => {
- calls += 1;
- if (calls === 1) return Promise.reject(new Error('VIDEO_GEN_BUSY'));
- return Promise.resolve({ ok: true });
- });
- const { result } = renderHook(() => useVideoGenQueue({
- generating: false,
- runGeneration,
- }));
-
- act(() => {
- result.current.enqueue({ prompt: 'one' });
- });
- await waitFor(() => expect(result.current.queue[0]?.status).toBe('pending'));
- expect(result.current.runningQueueId).not.toBeNull();
-
- await act(async () => {
- vi.advanceTimersByTime(1500);
- });
- await waitFor(() => expect(result.current.queue[0]?.status).toBe('complete'));
- expect(runGeneration).toHaveBeenCalledTimes(2);
- expect(result.current.runningQueueId).toBeNull();
- });
-
- it('does not release the slot from a stale BUSY timer after unmount', async () => {
- vi.useFakeTimers({ shouldAdvanceTime: true });
- const runGeneration = vi.fn(() => Promise.reject(new Error('409 already in progress')));
- const { result, unmount } = renderHook(() => useVideoGenQueue({
- generating: false,
- runGeneration,
- }));
-
- act(() => {
- result.current.enqueue({ prompt: 'one' });
- });
- await waitFor(() => expect(result.current.runningQueueId).not.toBeNull());
- await flush();
- const idAtUnmount = result.current.runningQueueId;
- unmount();
-
- await act(async () => {
- vi.advanceTimersByTime(5000);
- });
- // Hook is unmounted — the timer must not throw, and the last observed
- // slot is whatever was running at teardown (not cleared by a leaked fire).
- expect(idAtUnmount).not.toBeNull();
- vi.useRealTimers();
- });
-
- it('marks a non-BUSY failure as error and releases the slot immediately', async () => {
- const runGeneration = vi.fn(() => Promise.reject(new Error('boom')));
- const { result } = renderHook(() => useVideoGenQueue({
- generating: false,
- runGeneration,
- }));
-
- act(() => {
- result.current.enqueue({ prompt: 'one' });
- });
- await waitFor(() => expect(result.current.queue[0]?.status).toBe('error'));
- expect(result.current.queue[0].error).toBe('boom');
- expect(result.current.runningQueueId).toBeNull();
- });
-});
diff --git a/client/src/pages/VideoGen.composeWhileBusy.test.jsx b/client/src/pages/VideoGen.composeWhileBusy.test.jsx
index 7e1b554ee0..e7f6f4ef17 100644
--- a/client/src/pages/VideoGen.composeWhileBusy.test.jsx
+++ b/client/src/pages/VideoGen.composeWhileBusy.test.jsx
@@ -31,7 +31,6 @@ const MODEL = {
const state = vi.hoisted(() => ({
generateVideo: vi.fn(),
attach: vi.fn(),
- enqueue: vi.fn(),
eventSourceRef: { current: null },
}));
@@ -98,15 +97,6 @@ vi.mock('../hooks/useMediaAnnotations', () => ({
useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
}));
vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
-vi.mock('../hooks/useVideoGenQueue.js', () => ({
- useVideoGenQueue: () => ({
- queue: [],
- enqueue: state.enqueue,
- removeFromQueue: vi.fn(),
- clearFinishedQueue: vi.fn(),
- cancelRunning: vi.fn(),
- }),
-}));
vi.mock('../components/ui/Toast', () => ({
default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
}));
@@ -138,7 +128,6 @@ vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => nul
vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));
vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
-vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));
vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
@@ -149,7 +138,6 @@ describe('VideoGen compose-while-busy', () => {
beforeEach(() => {
state.generateVideo.mockReset().mockReturnValue(new Promise(() => {}));
state.attach.mockReset().mockReturnValue(new Promise(() => {}));
- state.enqueue.mockReset();
state.eventSourceRef.current = null;
vi.stubGlobal('open', vi.fn());
Object.defineProperty(globalThis.navigator, 'clipboard', {
@@ -192,4 +180,49 @@ describe('VideoGen compose-while-busy', () => {
expect(screen.getByTestId('prompt-from-media')).toHaveAttribute('data-disabled', '0');
expect(screen.getByRole('button', { name: /Add to queue/ })).toBeEnabled();
});
+ it('submits an additional render to the server queue while another render is active', async () => {
+ await act(async () => {
+ render(
+ <MemoryRouter initialEntries={['/media/video']}>
+ <VideoGen />
+ </MemoryRouter>,
+ );
+ });
+
+ const prompt = await screen.findByLabelText('Prompt');
+ fireEvent.change(prompt, { target: { value: 'a fox watches the rain' } });
+ await waitFor(() => expect(screen.getByRole('button', { name: /^Generate$/ })).toBeEnabled());
+
+ fireEvent.click(screen.getByRole('button', { name: /^Generate$/ }));
+ await waitFor(() => expect(screen.getByRole('button', { name: /Cancel/i })).toBeInTheDocument());
+
+ fireEvent.click(screen.getByRole('button', { name: /Add to queue/ }));
+ await waitFor(() => expect(state.generateVideo).toHaveBeenCalledTimes(2));
+ expect(state.generateVideo.mock.calls[1][0]).toMatchObject({
+ mode: 'text',
+ prompt: 'a fox watches the rain',
+ });
+ });
+
+ it('copies the composed prompt and opens fal H3 Max without queueing a paid API job', async () => {
+ await act(async () => {
+ render(
+ <MemoryRouter initialEntries={['/media/video']}>
+ <VideoGen />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(screen.getByText(/fal\.ai currently advertises up to 5 free videos per day with an account/))
+ .toBeInTheDocument();
+ fireEvent.change(await screen.findByLabelText('Prompt'), { target: { value: 'A clockwork bird takes flight.' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Copy prompt & open fal.ai' }));
+
+ expect(globalThis.open).toHaveBeenCalledWith(
+ 'https://fal.ai/tools/minimax-h3-max', '_blank', 'noopener,noreferrer',
+ );
+ await waitFor(() => expect(globalThis.navigator.clipboard.writeText)
+ .toHaveBeenCalledWith('A clockwork bird takes flight.'));
+ expect(state.generateVideo).not.toHaveBeenCalled();
+ });
});
diff --git a/client/src/pages/VideoGen.federatedTarget.test.jsx b/client/src/pages/VideoGen.federatedTarget.test.jsx
index f14cf5fb8b..774c11fa26 100644
--- a/client/src/pages/VideoGen.federatedTarget.test.jsx
+++ b/client/src/pages/VideoGen.federatedTarget.test.jsx
@@ -54,7 +54,6 @@ const PEER = {
const state = vi.hoisted(() => ({
generateVideo: vi.fn(),
attach: vi.fn(),
- enqueue: vi.fn(),
eventSourceRef: { current: null },
}));
@@ -118,15 +117,6 @@ vi.mock('../hooks/useMediaAnnotations', () => ({
useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
}));
vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
-vi.mock('../hooks/useVideoGenQueue.js', () => ({
- useVideoGenQueue: () => ({
- queue: [],
- enqueue: state.enqueue,
- removeFromQueue: vi.fn(),
- clearFinishedQueue: vi.fn(),
- cancelRunning: vi.fn(),
- }),
-}));
vi.mock('../components/ui/Toast', () => ({
default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
}));
@@ -156,7 +146,6 @@ vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => nul
vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));
vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
-vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));
vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
@@ -179,7 +168,6 @@ describe('VideoGen federated render target', () => {
beforeEach(() => {
state.generateVideo.mockReset().mockReturnValue(new Promise(() => {}));
state.attach.mockReset().mockReturnValue(new Promise(() => {}));
- state.enqueue.mockReset();
state.eventSourceRef.current = null;
});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 0651900a07..17eb2426dc 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -1,6 +1,6 @@
/**
* Video Generation page (LTX models via mlx_video on macOS, diffusers on
- * Windows). Local-only — there is no external A1111 equivalent for video.
+ * Windows), with local, Grok, and federated render targets.
*
* Accepts a source image either via direct upload or via the
* `?sourceImageFile=` query param so the Image Gen page can pipe a generation
@@ -26,13 +26,13 @@
* Form state, the URL-param prefill paths, the mode/backend transitions, and
* `buildGeneratePayload()` live in `useVideoGenForm` (issue #3291) — this page
* owns the fetching (status/models/history/gallery), the SSE run pipeline, the
- * batch queue, and the rendering.
+ * the rendering. The durable server queue owns queued work; each render target
+ * drains through its own lane.
*
- * Batch queue: client-side serial executor. The form's "Add to queue" button
- * appends a job to the queue (preserving the current params). When no job is
- * actively generating, the head of the queue is dequeued and submitted via
- * the same generate path as the inline button — so SSE progress, history
- * refresh, and error handling are all reused.
+ * "Add to queue" submits immediately to the durable server queue. That is
+ * important for mixed-target work: a Grok submission can start in its cloud
+ * lane while a local render occupies the GPU lane, and a federated peer owns
+ * the queue for the work it receives.
*/
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
@@ -66,7 +66,6 @@ import {
X, Type, Image as ImageIcon, GitBranch, ListPlus, Music, SlidersHorizontal,
} from 'lucide-react';
import toast from '../components/ui/Toast';
-import BatchQueuePanel from '../components/media/BatchQueuePanel';
import MediaJobsQueue from '../components/media/MediaJobsQueue';
import ModelSelect from '../components/ModelSelect';
import { FormField } from '../components/ui/FormField';
@@ -78,7 +77,6 @@ import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
import usePreviewRoute from '../hooks/usePreviewRoute';
import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
-import { useVideoGenQueue } from '../hooks/useVideoGenQueue.js';
import { useVideoGenForm } from '../hooks/useVideoGenForm.js';
import { useFederatedMediaTarget } from '../hooks/useFederatedMediaTarget';
import RemoteMediaTargetPicker from '../components/federatedMedia/RemoteMediaTargetPicker';
@@ -94,7 +92,7 @@ import {
} from '../services/api';
import LoraPicker from '../components/imageGen/LoraPicker';
import { VIDEO_RESOLUTIONS, resolutionOptionsForModel } from '../lib/videoGenResolutions';
-import { GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';
+import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';
import ResolutionField from '../components/media/ResolutionField';
import { VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, IC_LORA_MODES } from '../lib/videoGenParams.js';
import { finishTargetForRecord, isDeliveryVideoModel } from '../lib/videoFinish.js';
@@ -387,8 +385,7 @@ export default function VideoGen() {
const { attach, eventSourceRef } = useMediaJobSse('video');
// Hold the reject() of the in-flight runGeneration Promise so cancel can
// settle it. Without this, handleCancel() closes the EventSource but the
- // outstanding Promise dangles forever — and the queue worker's .finally()
- // never runs, leaving runningQueueId stuck and freezing further dequeue.
+ // 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
@@ -667,8 +664,9 @@ export default function VideoGen() {
const showStage = generating || stage.kind !== VIDEO_STAGE_KIND.EMPTY;
// Run a single payload through the SSE pipeline. Returns a promise that
- // resolves when the job completes (or rejects on error / cancel). Shared
- // by the inline submit and the queue worker.
+ // resolves when the job completes (or rejects on error / cancel). The
+ // 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.
@@ -694,8 +692,8 @@ export default function VideoGen() {
const isCurrent = () => myToken === runTokenRef.current;
// Wrap settle so the cancel ref is cleared exactly once when the Promise
- // transitions to a final state — guarantees the queue worker's .finally()
- // always runs and stale rejects can't fire after a successful complete.
+ // 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;
@@ -728,39 +726,44 @@ export default function VideoGen() {
});
});
- // Client-side serial batch queue. Owns the queue state + worker effect;
- // the page supplies `generating` (parks the worker) and `runGeneration`
- // (runs one payload through the SSE pipeline).
- const {
- queue, enqueue, removeFromQueue, clearFinishedQueue, cancelRunning,
- } = useVideoGenQueue({ generating, runGeneration });
-
const handleGenerate = async (e) => {
e?.preventDefault?.();
if (generating) {
- if (canEnqueue) handleEnqueue();
+ if (canEnqueue) await handleEnqueue();
return;
}
if (!canEnqueue) return;
// A capacity window expires on the clock, so an enabled button can already
// be pointing at a lapsed peer — re-derive at the moment of commit and say
// so, rather than letting the peer reject a render already paid for.
- if (remoteTarget.isRemote) {
- const fresh = remoteTarget.verify();
- if (!fresh.ok) { toast.error(fresh.message); return; }
- }
+ if (!verifyRemoteTarget()) return;
await runGeneration(buildGeneratePayload()).catch(() => {});
};
- const handleEnqueue = () => {
+ const verifyRemoteTarget = () => {
+ if (!remoteTarget.isRemote) return true;
+ const fresh = remoteTarget.verify();
+ if (!fresh.ok) { toast.error(fresh.message); return false; }
+ return true;
+ };
+
+ const handleEnqueue = async () => {
// Mirror the Generate guard — a BYOV runtime that isn't installed yet
// would silently queue a doomed job that fails late in the worker with
// VENV_MISSING, hiding the installer banner from the user. Block at
// enqueue time so the only path forward is the install banner above.
if (!canEnqueue) return;
- // useVideoGenQueue strips the File blobs into `_blobs` and snapshots the
- // rest as a stable summary for the queue UI.
- enqueue(buildGeneratePayload());
+ // A capacity window expires on the clock, so re-check the selected peer at
+ // the moment this queued job is committed. The server then owns the job,
+ // including any multipart uploads, and the appropriate lane can start it
+ // without waiting for this tab's active SSE render.
+ if (!verifyRemoteTarget()) return;
+ await generateVideo(buildGeneratePayload())
+ .then((data) => {
+ const position = Number.isInteger(data?.position) ? ` (position ${data.position})` : '';
+ toast.success(`Queued${position}`);
+ })
+ .catch((err) => toast.error(err.message || 'Failed to queue video'));
};
const handleCancel = async () => {
@@ -779,17 +782,13 @@ export default function VideoGen() {
}
setGenerating(false);
setStatusMsg('Cancelled');
- // Settle the in-flight runGeneration Promise so the queue worker's
- // .finally() releases runningQueueId and the next pending item can run.
- // Without this the Promise would dangle and the worker would stay parked.
+ // 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'));
}
- // Mark the running queue item errored + release the slot so the next
- // pending item can dispatch (no-op when nothing's queued).
- cancelRunning();
};
// `status.connected` reflects the LEGACY mlx_video pythonPath health. BYOV
@@ -1053,7 +1052,8 @@ export default function VideoGen() {
</div>
{/* Keep Enhance live while a render is in flight so the next clip
- can be composed and queued. Generate itself becomes Cancel. */}
+ can be composed and submitted to its server queue. Generate
+ itself becomes Cancel. */}
<PromptEnhancer
kind="video"
prompt={prompt}
@@ -1444,7 +1444,7 @@ export default function VideoGen() {
onClick={handleEnqueue}
disabled={!canEnqueue}
className="flex items-center gap-2 px-4 py-2 border border-port-border text-gray-200 hover:text-white hover:bg-port-border/40 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium rounded-lg min-h-[40px]"
- title={canEnqueue ? 'Add this configuration to the batch queue'
+ title={canEnqueue ? 'Submit this configuration to its server queue; local, Grok, and remote lanes run independently'
: icWeightsBlocked ? `Download the ${icSpec?.label || 'IC-LoRA'} weight before queueing`
: weightsGateBlocked ? 'Finish required model downloads before queueing'
: 'Complete the required inputs before queueing'}
@@ -1472,18 +1472,6 @@ export default function VideoGen() {
</div>
</form>
- <BatchQueuePanel
- queue={queue}
- onRemove={removeFromQueue}
- onClear={clearFinishedQueue}
- summarize={(item) => (
- <>
- <span className="uppercase mr-2">{item.params.backend === 'grok' ? `grok ${item.params.mode}` : item.params.mode}</span>
- {item.params.width}×{item.params.height} · {item.params.backend === 'grok' ? `${item.params.grokDuration || GROK_VIDEO_DEFAULT_DURATION}s` : `${item.params.numFrames}f`}
- </>
- )}
- />
-
<MediaJobsQueue kind="video" />
<VideoGenGallery
diff --git a/client/src/pages/VideoGen.terms.test.jsx b/client/src/pages/VideoGen.terms.test.jsx
index 6c9a1c035d..a5d976b3de 100644
--- a/client/src/pages/VideoGen.terms.test.jsx
+++ b/client/src/pages/VideoGen.terms.test.jsx
@@ -36,7 +36,6 @@ const state = vi.hoisted(() => ({
generateVideo: vi.fn(),
startDownload: vi.fn(),
repairModel: vi.fn(),
- enqueue: vi.fn(),
attach: vi.fn(),
eventSourceRef: { current: null },
// Stands in for the persisted install-wide acceptance list
@@ -110,15 +109,6 @@ vi.mock('../hooks/useMediaAnnotations', () => ({
useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
}));
vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
-vi.mock('../hooks/useVideoGenQueue.js', () => ({
- useVideoGenQueue: () => ({
- queue: [],
- enqueue: state.enqueue,
- removeFromQueue: vi.fn(),
- clearFinishedQueue: vi.fn(),
- cancelRunning: vi.fn(),
- }),
-}));
vi.mock('../components/ui/Toast', () => ({
default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
}));
@@ -145,7 +135,6 @@ vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => nul
vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));
vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
-vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));
vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
@@ -178,7 +167,6 @@ describe('VideoGen MiniMax H3 orchestration', () => {
state.generateVideo.mockReset().mockResolvedValue({ jobId: 'job-1' });
state.startDownload.mockReset();
state.repairModel.mockReset().mockResolvedValue({ ok: true });
- state.enqueue.mockReset();
state.acceptedTerms = [];
state.setVideoModelTerms.mockReset().mockImplementation(async (termsId, accepted) => {
state.acceptedTerms = accepted
@@ -213,8 +201,10 @@ describe('VideoGen MiniMax H3 orchestration', () => {
await waitFor(() => expect(enqueue()).toBeEnabled());
fireEvent.click(enqueue());
- expect(state.enqueue).toHaveBeenCalledWith(expect.objectContaining({ modelId: H3_ONE.id }));
- expect(state.enqueue.mock.calls[0][0]).not.toHaveProperty('termsAcceptance');
+ await waitFor(() => expect(state.generateVideo).toHaveBeenCalledWith(expect.objectContaining({
+ modelId: H3_ONE.id,
+ })));
+ expect(state.generateVideo.mock.calls[0][0]).not.toHaveProperty('termsAcceptance');
await act(async () => {
fireEvent.submit(prompt().closest('form'));
diff --git a/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx b/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx
index 01215dfaa0..16d82ee8b7 100644
--- a/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx
+++ b/client/src/pages/VideoGen.textEncoderAutoDownload.test.jsx
@@ -51,7 +51,6 @@ const state = vi.hoisted(() => ({
activeJob: null,
generateVideo: vi.fn(),
attach: vi.fn(),
- enqueue: vi.fn(),
eventSourceRef: { current: null },
}));
@@ -123,15 +122,6 @@ vi.mock('../hooks/useMediaAnnotations', () => ({
useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
}));
vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
-vi.mock('../hooks/useVideoGenQueue.js', () => ({
- useVideoGenQueue: () => ({
- queue: [],
- enqueue: state.enqueue,
- removeFromQueue: vi.fn(),
- clearFinishedQueue: vi.fn(),
- cancelRunning: vi.fn(),
- }),
-}));
vi.mock('../components/ui/Toast', () => ({
default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
}));
@@ -161,7 +151,6 @@ vi.mock('../components/videoGen/RuntimeFingerprint', () => ({ default: () => nul
vi.mock('../components/videoGen/VideoGenGallery', () => ({ default: () => null }));
vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
-vi.mock('../components/media/BatchQueuePanel', () => ({ default: () => null }));
vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index e3f4837773..271721c366 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -627,7 +627,7 @@ function startLaneJob(job, { lane }) {
recomputeQueuePositions();
const label = lane === 'cloud'
? (job.params?.mode || 'cloud')
- : lane === 'remote' ? 'remote audio' : job.kind;
+ : lane === 'remote' ? `remote ${job.kind}` : job.kind;
persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} start failed: ${e.message}`));
broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });
mediaJobEvents.emit('started', job);
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 142f008a9a..b1afe03f97 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -40,6 +40,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
const stubs = {
generateVideo: vi.fn(async () => ({
tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
+ generateVideoGrok: vi.fn(async () => ({ jobId: 'whatever' })),
generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),
generateImage: vi.fn(async () => ({ jobId: 'whatever' })),
generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),
@@ -67,6 +68,11 @@ vi.mock('../videoGen/local.js', () => ({
cancel: (...args) => stubs.cancelVideo(...args),
}));
+vi.mock('../videoGen/grok.js', () => ({
+ generateVideo: (...args) => stubs.generateVideoGrok(...args),
+ cancel: (...args) => stubs.cancelVideo(...args),
+}));
+
vi.mock('../imageGen/local.js', () => ({
generateImage: (...args) => stubs.generateImage(...args),
cancel: (...args) => stubs.cancelImage(...args),
@@ -214,6 +220,31 @@ describe('mediaJobQueue', () => {
expect(capacity.totals).toEqual({ running: 2, queued: 1 });
});
+ it('runs local and Grok video renders in parallel lanes', async () => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ stubs.generateVideoGrok.mockImplementation(() => new Promise(() => {}));
+ const local = mediaJobQueue.enqueueJob({ kind: 'video', params: { mode: 'text', prompt: 'local' } });
+ const grok = mediaJobQueue.enqueueJob({
+ kind: 'video',
+ params: { mode: IMAGE_GEN_MODE.GROK, prompt: 'grok' },
+ });
+
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1
+ && stubs.generateVideoGrok.mock.calls.length === 1);
+
+ expect(mediaJobQueue.getJob(local.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(grok.jobId).status).toBe('running');
+ expect(mediaJobQueue.getQueueCapacity().lanes).toMatchObject({
+ gpu: { running: 1, queued: 0 },
+ cloud: { running: 1, queued: 0 },
+ });
+
+ videoGenEvents.emit('failed', { generationId: local.jobId, error: 'cleanup' });
+ videoGenEvents.emit('failed', { generationId: grok.jobId, error: 'cleanup' });
+ await waitFor(() => mediaJobQueue.getJob(local.jobId)?.status === 'failed'
+ && mediaJobQueue.getJob(grok.jobId)?.status === 'failed');
+ });
+
it('counts queue depth per kind', async () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
@@ -1235,6 +1266,35 @@ describe('Audio kind (#1928)', () => {
await waitFor(() => mediaJobQueue.getJob(remote.jobId)?.status === 'completed');
});
+ it('runs local and federated video renders in parallel lanes', async () => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ stubs.generateVideoRemote.mockImplementation(() => new Promise(() => {}));
+
+ const local = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local render' } });
+ const remote = mediaJobQueue.enqueueJob({
+ kind: 'video',
+ params: { prompt: '', modelId: null, remoteMedia: remoteVideoMediaParams() },
+ });
+
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1
+ && stubs.generateVideoRemote.mock.calls.length === 1);
+
+ expect(mediaJobQueue.getJob(local.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(remote.jobId).status).toBe('running');
+ expect(stubs.generateVideo).not.toHaveBeenCalledWith(
+ expect.objectContaining({ jobId: remote.jobId }),
+ );
+ expect(mediaJobQueue.getQueueCapacity().lanes).toMatchObject({
+ gpu: { running: 1, queued: 0 },
+ remote: { running: 1, queued: 0 },
+ });
+
+ videoGenEvents.emit('failed', { generationId: local.jobId, error: 'cleanup' });
+ videoGenEvents.emit('failed', { generationId: remote.jobId, error: 'cleanup' });
+ await waitFor(() => mediaJobQueue.getJob(local.jobId)?.status === 'failed'
+ && mediaJobQueue.getJob(remote.jobId)?.status === 'failed');
+ });
+
it('re-enqueues a persisted running remote VIDEO job with reconciliation enabled', async () => {
const id = '00000000-0000-4000-8000-000000000003';
writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({