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

perf: bound media queue responses to visible jobs (#8230)

[._.]/ Adam Eivy840d1ec6cce4
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index b3284ddd0a..55cbca7247 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -5,7 +5,7 @@ import toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import { FormField } from '../ui/FormField';
import AutoSizeTextarea from '../ui/AutoSizeTextarea';
-import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow, listMediaVideoHolds, resumeMediaVideoHold } from '../../services/apiMediaJobs.js';
+import { listQueueMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow, listMediaVideoHolds, resumeMediaVideoHold } from '../../services/apiMediaJobs.js';
import { listLoraTrainingCheckpoints } from '../../services/apiLoraTraining.js';
import { isCloudCliMode, IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT, supportsCloudModelOverride, modeLabel, mediaJobLane, isCloudVideoMode } from '../../lib/imageGenBackends';
import { ANTIGRAVITY_CONFIGURED_DEFAULT, effortLevelsForProvider, isConfiguredDefaultModel } from '../../utils/providers';
@@ -142,7 +142,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
const fetchJobs = useCallback(async () => {
const outcome = await Promise.all([
- listMediaJobs(kind ? { kind } : {}),
+ listQueueMediaJobs({ ...(kind ? { kind } : {}), limit: recentLimit }),
!kind || kind === 'video' ? listMediaVideoHolds() : [],
]).then(
(value) => ({ value }),
@@ -158,7 +158,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
setHasSnapshot(true);
setLoadError(false);
setLoading(false);
- }, [kind]);
+ }, [kind, recentLimit]);
useAutoRefetch(fetchJobs, 3000, { pollOnly: true });
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
index 36124b29d4..b83795b175 100644
--- a/client/src/components/media/MediaJobsQueue.test.jsx
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -6,12 +6,12 @@ import { findEnabledByRole } from '../../test/enabledBarrier.js';
// Mock the media-jobs API so the queue renders a controlled job list without
// the network. useAutoRefetch calls the fetcher on mount.
-const listMediaJobs = vi.fn();
+const listQueueMediaJobs = vi.fn();
const retryMediaJob = vi.fn();
const resumeMediaVideoHold = vi.fn();
const listMediaVideoHolds = vi.fn();
vi.mock('../../services/apiMediaJobs.js', () => ({
- listMediaJobs: (...a) => listMediaJobs(...a),
+ listQueueMediaJobs: (...a) => listQueueMediaJobs(...a),
cancelMediaJob: vi.fn(),
cancelQueuedMediaJobs: vi.fn(),
deleteMediaJob: vi.fn(),
@@ -55,7 +55,7 @@ const trainingJob = {
};
beforeEach(() => {
- listMediaJobs.mockReset();
+ listQueueMediaJobs.mockReset();
listMediaVideoHolds.mockReset().mockResolvedValue([]);
resumeMediaVideoHold.mockReset();
listLoraTrainingCheckpoints.mockReset();
@@ -104,7 +104,7 @@ const failedCodexDefaultEffortJob = {
describe('MediaJobsQueue — unavailable state', () => {
it('does not report a failed queue probe as an empty queue', async () => {
- listMediaJobs.mockRejectedValue(new Error('offline'));
+ listQueueMediaJobs.mockRejectedValue(new Error('offline'));
render(<MediaJobsQueue kind="image" />);
@@ -115,7 +115,7 @@ describe('MediaJobsQueue — unavailable state', () => {
describe('MediaJobsQueue — Creative Director renders', () => {
it('surfaces a Creative Director-owned video job in the live queue', async () => {
- listMediaJobs.mockResolvedValue([{
+ listQueueMediaJobs.mockResolvedValue([{
id: 'cdvideo0000live',
kind: 'video',
owner: 'cd:example-project',
@@ -128,6 +128,7 @@ describe('MediaJobsQueue — Creative Director renders', () => {
render(<MediaJobsQueue kind="video" />);
await waitFor(() => expect(screen.getByText(/Creative Director/)).toBeInTheDocument());
+ expect(listQueueMediaJobs).toHaveBeenCalledWith({ kind: 'video', limit: 10 });
expect(screen.getByText(/#2 in queue/)).toBeInTheDocument();
expect(screen.getByText(/an invented establishing shot/)).toBeInTheDocument();
});
@@ -137,7 +138,7 @@ describe('MediaJobsQueue — video render lanes', () => {
it('files each job under the lane the server scheduled it into', async () => {
// The lane comes from the server's own classifier (`executionLane`), so a
// cloud backend the client has never heard of still lands in Cloud renders.
- listMediaJobs.mockResolvedValue([
+ listQueueMediaJobs.mockResolvedValue([
{
id: 'localvideo0001',
kind: 'video',
@@ -196,7 +197,7 @@ describe('MediaJobsQueue — video render lanes', () => {
});
it('badges a cloud provider render with its provider, not the local engine', async () => {
- listMediaJobs.mockResolvedValue([{
+ listQueueMediaJobs.mockResolvedValue([{
id: 'falvideo00001',
kind: 'video',
status: 'running',
@@ -215,7 +216,7 @@ describe('MediaJobsQueue — video render lanes', () => {
// A rebuilt bundle can be served briefly by a server process that has not
// restarted onto the new projection yet; the queue must not fall back to
// filing every cloud render under Local machine while that window is open.
- listMediaJobs.mockResolvedValue([
+ listQueueMediaJobs.mockResolvedValue([
{
id: 'legacylocal01',
kind: 'video',
@@ -252,7 +253,7 @@ 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
// request — the raw job nulls both so a rolled-back build fails closed.
- listMediaJobs.mockResolvedValue([{
+ listQueueMediaJobs.mockResolvedValue([{
id: 'remotejob0000beef',
kind: 'image',
status: 'running',
@@ -268,7 +269,7 @@ describe('MediaJobsQueue — federated render badge', () => {
});
it('keeps the local badge on a job with no renderer projection', async () => {
- listMediaJobs.mockResolvedValue([{ ...failedLocalJob, status: 'running', error: undefined }]);
+ listQueueMediaJobs.mockResolvedValue([{ ...failedLocalJob, status: 'running', error: undefined }]);
render(<MediaJobsQueue kind="image" />);
@@ -280,7 +281,7 @@ describe('MediaJobsQueue — federated render badge', () => {
// renders from the wire request inside the marker — so showing the form
// would silently discard what the user typed.
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([{ ...failedLocalJob, id: 'remotefail0000beef', renderer: 'remote' }]);
+ listQueueMediaJobs.mockResolvedValue([{ ...failedLocalJob, id: 'remotefail0000beef', renderer: 'remote' }]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
@@ -293,7 +294,7 @@ describe('MediaJobsQueue — federated render badge', () => {
describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
it('surfaces the job effort in the row label', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedCodexJob]);
+ listQueueMediaJobs.mockResolvedValue([failedCodexJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
await waitFor(() => expect(screen.getByText(/codex \/ gpt-5.6-luna · high/)).toBeInTheDocument());
@@ -301,7 +302,7 @@ describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
it('shows the effective default effort in the row label when the job stored none', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedCodexDefaultEffortJob]);
+ listQueueMediaJobs.mockResolvedValue([failedCodexDefaultEffortJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
// Default-effort jobs store no `effort`, but codex still rendered at `low`.
@@ -312,7 +313,7 @@ describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
const user = userEvent.setup();
// A hand-edited media-jobs.json could carry a numeric effort; the row label
// must coerce safely (mirror of codex.js) instead of throwing on .trim().
- listMediaJobs.mockResolvedValue([{
+ listQueueMediaJobs.mockResolvedValue([{
...failedCodexDefaultEffortJob, id: 'codexbadeff00dead', params: { ...failedCodexDefaultEffortJob.params, effort: 5 },
}]);
render(<MediaJobsQueue kind="image" />);
@@ -323,7 +324,7 @@ describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
it('pre-fills the retry editor to Default for a job that stored no effort', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedCodexDefaultEffortJob]);
+ listQueueMediaJobs.mockResolvedValue([failedCodexDefaultEffortJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -336,7 +337,7 @@ describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
it('renders the effort select (Codex only) and pins a new level on retry', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedCodexJob]);
+ listQueueMediaJobs.mockResolvedValue([failedCodexJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -352,7 +353,7 @@ describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
it('sends the clear sentinel when the effort is reset to Default', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedCodexJob]);
+ listQueueMediaJobs.mockResolvedValue([failedCodexJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -366,7 +367,7 @@ describe('MediaJobsQueue — Codex reasoning-effort retry control', () => {
it('does not render the effort control for non-Codex jobs', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedLocalJob]);
+ listQueueMediaJobs.mockResolvedValue([failedLocalJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -393,7 +394,7 @@ describe('MediaJobsQueue — Agy retry model field', () => {
it('pre-fills the Agy model from params.model and retries with the edited value', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([failedAgyJob]);
+ listQueueMediaJobs.mockResolvedValue([failedAgyJob]);
render(<MediaJobsQueue kind="image" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -410,7 +411,7 @@ describe('MediaJobsQueue — Agy retry model field', () => {
it('shows the configured-default sentinel as an empty field and sends no override', async () => {
const user = userEvent.setup();
- listMediaJobs.mockResolvedValue([{
+ listQueueMediaJobs.mockResolvedValue([{
...failedAgyJob,
id: 'agysentinel00dead',
params: { ...failedAgyJob.params, model: 'antigravity-configured-default' },
@@ -430,7 +431,7 @@ describe('MediaJobsQueue — Agy retry model field', () => {
describe('MediaJobsQueue — training rows', () => {
it('renders a training summary + engine/character label instead of a prompt', async () => {
- listMediaJobs.mockResolvedValue([trainingJob]);
+ listQueueMediaJobs.mockResolvedValue([trainingJob]);
listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
render(<MediaJobsQueue kind="training" />);
@@ -442,7 +443,7 @@ describe('MediaJobsQueue — training rows', () => {
});
it('draws a loss sparkline and sample thumbnails from the run checkpoints', async () => {
- listMediaJobs.mockResolvedValue([trainingJob]);
+ listQueueMediaJobs.mockResolvedValue([trainingJob]);
listLoraTrainingCheckpoints.mockResolvedValue({
checkpoints: [
{ step: 100, loss: 0.8, previewUrl: '/api/lora-training/runs/run-abc/samples/a.png', deployed: false },
@@ -461,7 +462,7 @@ describe('MediaJobsQueue — training rows', () => {
});
it('shows a friendly placeholder when no checkpoints exist yet', async () => {
- listMediaJobs.mockResolvedValue([trainingJob]);
+ listQueueMediaJobs.mockResolvedValue([trainingJob]);
listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
render(<MediaJobsQueue kind="training" />);
@@ -470,7 +471,7 @@ describe('MediaJobsQueue — training rows', () => {
});
it('does not fetch checkpoints for non-training jobs', async () => {
- listMediaJobs.mockResolvedValue([{
+ listQueueMediaJobs.mockResolvedValue([{
id: 'img1', kind: 'image', status: 'running', progress: 0.2,
params: { prompt: 'a castle', modelId: 'z-image-turbo' },
}]);
@@ -491,7 +492,7 @@ describe('MediaJobsQueue — hidden-tab polling (#5697)', () => {
afterEach(() => { vi.useRealTimers(); });
it('pauses the checkpoint poll while the tab is hidden and re-fires on return', async () => {
- listMediaJobs.mockResolvedValue([trainingJob]);
+ listQueueMediaJobs.mockResolvedValue([trainingJob]);
listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
render(<MediaJobsQueue kind="training" />);
@@ -504,7 +505,7 @@ describe('MediaJobsQueue — hidden-tab polling (#5697)', () => {
* "the mount fetches finished". A mount chain needing one more turn on a
* loaded machine is measured mid-flight, and the counts race BOTH ways
* (#7592/#7448): the checkpoint assertion goes red, and
- * `listMediaJobs.mock.calls.length` is a baseline taken before the list had
+ * `listQueueMediaJobs.mock.calls.length` is a baseline taken before the list had
* loaded — so "the count did not move" then passes for the wrong reason,
* because nothing had loaded to move it.
*
@@ -531,13 +532,13 @@ describe('MediaJobsQueue — hidden-tab polling (#5697)', () => {
*/
await screen.findByText(/No checkpoints yet/);
expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
- const jobListCalls = listMediaJobs.mock.calls.length;
+ const jobListCalls = listQueueMediaJobs.mock.calls.length;
const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
// The queue's own job poll is paused by the same hook.
- expect(listMediaJobs.mock.calls.length).toBe(jobListCalls);
+ expect(listQueueMediaJobs.mock.calls.length).toBe(jobListCalls);
visibility.mockReturnValue('visible');
await act(async () => {
@@ -568,7 +569,7 @@ describe('MediaJobsQueue — video retry reference mode (#4874)', () => {
};
const openRetryEditor = async (user) => {
- listMediaJobs.mockResolvedValue([failedInspireJob]);
+ listQueueMediaJobs.mockResolvedValue([failedInspireJob]);
render(<MediaJobsQueue kind="video" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -649,7 +650,7 @@ describe('MediaJobsQueue — video retry decode override (#5449)', () => {
});
const openRetryEditor = async (user, job) => {
- listMediaJobs.mockResolvedValue([job]);
+ listQueueMediaJobs.mockResolvedValue([job]);
render(<MediaJobsQueue kind="video" />);
await expandReel(user);
await user.click(await screen.findByLabelText('Edit and retry'));
@@ -752,7 +753,7 @@ describe('MediaJobsQueue — video retry decode override (#5449)', () => {
describe('MediaJobsQueue — local video holds', () => {
it('makes the scope of damaged-hold recovery explicit before resuming', async () => {
- listMediaJobs.mockResolvedValue([]);
+ listQueueMediaJobs.mockResolvedValue([]);
listMediaVideoHolds.mockResolvedValue([{ id: 'recovery-hold', scope: 'local-video', modelId: '*', runtime: '*',
cause: 'Saved video holds are damaged.', heldJobCount: 0 }]);
const user = userEvent.setup();
@@ -769,7 +770,7 @@ describe('MediaJobsQueue — local video holds', () => {
it('retains held state on a failed resume and clears it only after a successful response', async () => {
const hold = { id: 'example-hold', modelId: 'example-mlx', runtime: 'mlx_video', cause: 'Shader compilation failed', heldJobCount: 2 };
const jobs = ['held-1', 'held-2'].map((id) => ({ id, kind: 'video', status: 'queued', hold, params: {} }));
- listMediaJobs.mockResolvedValue(jobs);
+ listQueueMediaJobs.mockResolvedValue(jobs);
listMediaVideoHolds.mockResolvedValue([hold]);
resumeMediaVideoHold.mockRejectedValueOnce(new Error('Resume unavailable'));
const user = userEvent.setup();
@@ -784,7 +785,7 @@ describe('MediaJobsQueue — local video holds', () => {
await user.click(screen.getByRole('button', { name: 'Resume' }));
expect(screen.getByRole('button', { name: 'Resuming…' })).toBeDisabled();
expect(screen.getByText('2 video jobs held')).toBeInTheDocument();
- listMediaJobs.mockResolvedValue(jobs.map((job) => ({ ...job, hold: undefined })));
+ listQueueMediaJobs.mockResolvedValue(jobs.map((job) => ({ ...job, hold: undefined })));
listMediaVideoHolds.mockResolvedValue([]);
await act(async () => { finishResume({ resumed: true }); });
await waitFor(() => expect(screen.queryByText('2 video jobs held')).not.toBeInTheDocument());
@@ -793,7 +794,7 @@ describe('MediaJobsQueue — local video holds', () => {
});
it('offers resume for an active hold after all retained jobs were canceled', async () => {
- listMediaJobs.mockResolvedValue([]);
+ listQueueMediaJobs.mockResolvedValue([]);
listMediaVideoHolds.mockResolvedValue([{ id: 'empty-hold', modelId: 'example-mlx', runtime: 'mlx_video',
cause: 'Shader compilation failed', heldJobCount: 0 }]);
const user = userEvent.setup();
diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.js
index 97c18e4e72..b77d1285a2 100644
--- a/client/src/services/apiMediaJobs.js
+++ b/client/src/services/apiMediaJobs.js
@@ -7,6 +7,13 @@ export const listMediaJobs = (filters = {}, options = {}) => {
return request(`/media-jobs${qs ? `?${qs}` : ''}`, options);
};
+export const listQueueMediaJobs = (filters = {}, options = {}) => {
+ const qs = new URLSearchParams(
+ Object.entries(filters).filter(([, v]) => v != null && v !== ''),
+ ).toString();
+ return request(`/media-jobs/queue${qs ? `?${qs}` : ''}`, options);
+};
+
// `silent` so speculative lookups (e.g. MediaJobThumb hydration for old
// panel/scene jobIds past the queue's 24h archive TTL) don't surface a
// global toast on the routine 404 — the caller's own .catch handles the
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index 0b05ba1c6d..7fa1a2983f 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -9,7 +9,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, listVideoHolds, resumeVideoHold, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { listJobs, listQueueJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, listVideoHolds, resumeVideoHold, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
import { refineMediaPrompt } from '../services/mediaPromptRefiner.js';
import { promptFromMedia } from '../services/mediaPromptFromMedia.js';
import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';
@@ -131,6 +131,17 @@ router.get('/', asyncHandler(async (req, res) => {
res.json([...live, ...terminal].map(sanitizeJob));
}));
+const queueQuerySchema = z.object({
+ kind: z.enum(JOB_KINDS).optional(),
+ owner: z.string().max(256).optional(),
+ limit: z.coerce.number().int().min(0).max(100).optional(),
+});
+
+router.get('/queue', asyncHandler(async (req, res) => {
+ const filters = validateRequest(queueQuerySchema, req.query);
+ res.json(listQueueJobs(filters).map(sanitizeJob));
+}));
+
router.post('/refine-prompt', asyncHandler(async (req, res) => {
const data = validateRequest(refinePromptSchema, req.body);
res.json(await refineMediaPrompt(data));
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
index 304957f8ab..fa08e10a44 100644
--- a/server/routes/mediaJobs.test.js
+++ b/server/routes/mediaJobs.test.js
@@ -15,11 +15,14 @@ const stubs = {
removeArchivedJob: vi.fn((id) => jobStore.delete(id)),
resumeVideoHold: vi.fn(),
listVideoHolds: vi.fn(() => []),
+ listQueueJobs: vi.fn(() => []),
+ sanitizeJob: vi.fn(),
};
vi.mock('../services/mediaJobQueue/index.js', () => ({
JOB_KINDS: ['video', 'image'],
JOB_STATUSES: ['queued', 'running', 'completed', 'failed', 'canceled'],
listJobs: () => Array.from(jobStore.values()),
+ listQueueJobs: (...args) => stubs.listQueueJobs(...args),
getJob: (id) => jobStore.get(id) || null,
enqueueJob: (...args) => stubs.enqueueJob(...args),
cancelJob: (...args) => stubs.cancelJob(...args),
@@ -29,6 +32,13 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
resumeVideoHold: (...args) => stubs.resumeVideoHold(...args),
listVideoHolds: (...args) => stubs.listVideoHolds(...args),
}));
+vi.mock('../services/mediaJobQueue/sanitizeJob.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { sanitizeJob: (job) => {
+ stubs.sanitizeJob(job);
+ return actual.sanitizeJob(job);
+ } };
+});
vi.mock('../services/videoGen/prepareParams.js', () => ({
validateVideoRetryParams: vi.fn(),
}));
@@ -49,6 +59,27 @@ describe('mediaJobs routes', () => {
vi.clearAllMocks();
});
+ it('GET /queue sanitizes only the selected rows and preserves the full-list API', async () => {
+ const jobs = Array.from({ length: 500 }, (_, i) => ({
+ id: `job-${i}`, kind: 'image', status: 'failed',
+ queuedAt: new Date(Date.now() - i * 1000).toISOString(), params: {},
+ }));
+ jobs.forEach((job) => jobStore.set(job.id, job));
+ stubs.listQueueJobs.mockReturnValue(jobs.slice(0, 10));
+ const app = makeApp();
+
+ const queue = await request(app).get('/api/media-jobs/queue?kind=image&limit=10');
+ expect(queue.status).toBe(200);
+ expect(queue.body).toHaveLength(10);
+ expect(stubs.listQueueJobs).toHaveBeenCalledWith({ kind: 'image', limit: 10 });
+ expect(stubs.sanitizeJob).toHaveBeenCalledTimes(10);
+
+ const full = await request(app).get('/api/media-jobs');
+ expect(full.status).toBe(200);
+ expect(full.body).toHaveLength(500);
+ expect(stubs.sanitizeJob).toHaveBeenCalledTimes(510);
+ });
+
it('GET /:id exposes progress and statusMsg while sanitizing params', async () => {
jobStore.set('j-progress', {
id: 'j-progress',
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 9a9ed9f7ab..dd47b654bd 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -403,6 +403,30 @@ export function listJobs({ status, kind, owner } = {}) {
});
}
+// The render queue displays every live job and only a short recent failure
+// reel. Select that reel before sanitization; the archive can hold 500 rows.
+export function listQueueJobs({ kind, owner, limit = 10 } = {}) {
+ const matches = (job) => (!kind || job.kind === kind) && (!owner || job.owner === owner);
+ const live = [
+ ...(running ? [running] : []),
+ ...cloudRunning,
+ ...remoteRunning,
+ ...queue,
+ ].filter(matches);
+ const recent = [];
+ const finishedAt = (job) => new Date(job.completedAt || job.startedAt || job.queuedAt || 0).getTime();
+ for (const job of archive) {
+ if (!matches(job) || (job.status !== 'failed' && job.status !== 'canceled')) continue;
+ const time = finishedAt(job);
+ let index = 0;
+ while (index < recent.length && !(time > recent[index].time)) index += 1;
+ if (index >= limit) continue;
+ recent.splice(index, 0, { job, time });
+ if (recent.length > limit) recent.pop();
+ }
+ return [...live, ...recent.map(({ job }) => job)];
+}
+
// Serialize persist() calls through a single chain. atomicWrite rename can
// finish out-of-order under concurrent calls, so a slow "start" persist
// landing after a fast "done" persist would regress the on-disk snapshot
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 9e62b40c0f..f0e465e4ce 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -391,6 +391,40 @@ describe('mediaJobQueue', () => {
expect(mediaJobQueue.listJobs({ status: 'running' })).toHaveLength(1);
});
+ it('limits a 500-row terminal archive while preserving live FIFO and filtered recents', async () => {
+ const now = Date.now();
+ const archived = Array.from({ length: 500 }, (_, i) => ({
+ id: `archived-${i}`,
+ kind: i % 2 ? 'video' : 'image',
+ owner: i % 4 ? 'other' : 'example',
+ status: i % 5 === 0 ? 'completed' : i % 3 === 0 ? 'canceled' : 'failed',
+ queuedAt: new Date(now - 600_000).toISOString(),
+ completedAt: new Date(now - i * 1000).toISOString(),
+ params: {},
+ }));
+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: archived }));
+ await mediaJobQueue.initMediaJobQueue();
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ const first = mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'example' });
+ const second = mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'example' });
+ await flush();
+
+ const all = mediaJobQueue.listQueueJobs();
+ expect(all.slice(0, 2).map((j) => j.id)).toEqual([first.jobId, second.jobId]);
+ expect(all).toHaveLength(12);
+ expect(all.slice(2).map((j) => j.id)).toEqual(
+ archived.filter((j) => j.status !== 'completed').slice(0, 10).map((j) => j.id),
+ );
+ expect(mediaJobQueue.listJobs()).toHaveLength(502);
+
+ const scoped = mediaJobQueue.listQueueJobs({ kind: 'video', owner: 'example', limit: 3 });
+ expect(scoped.slice(0, 2).map((j) => j.id)).toEqual([first.jobId, second.jobId]);
+ expect(scoped.slice(2).map((j) => j.id)).toEqual(
+ archived.filter((j) => j.kind === 'video' && j.owner === 'example' && j.status !== 'completed')
+ .slice(0, 3).map((j) => j.id),
+ );
+ });
+
it('cancelQueuedJobs cancels every queued job, leaves running ones alone', async () => {
// Block the worker so subsequent enqueues stay queued.
let resolveBlocker;