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: isolate local-video preparation failures from other media jobs (#9729)
Adam Eivyb80f627c4f10
diff --git a/server/services/README.md b/server/services/README.mdindex ff60b04ea9..59cdf009fe 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -11,6 +11,7 @@ image-generation paths below are useful entry points when tracing render jobs.| `databaseMaintenanceProducers.js` | Internal one-use coordinator stage: retain producer identity, stop this install's PM2 CoS/server, and verify fresh readback while admission remains fenced. || `databaseMaintenanceQuiescence.js` | Internal coordinator stage after producer shutdown: terminate verified running detached-writer groups, prove every registry record quiescent from process-table evidence, archive it with the operation, and refuse pending, legacy, orphaned, ambiguous or unregistered writers. || `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. |+| `mediaJobQueue/index.js` | Owns admission, lanes, durability and terminal effects; `videoHolds.js` returns local-video cohort preparation results and owns circuit breakers, while `videoGen/modelSelection.js` owns model-selection policy. || `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. || `superColliderRuntime.js` | Managed SuperCollider runtime I/O (#9412): Docker probe, recipe-hash-stamped image build, `runSuperColliderContainer` (contained `sclang` run with forced container removal), the synthetic render probe and its cached evidence, `getSuperColliderStatus` and idempotent `setupSuperColliderRuntime`. Never runs at boot. || `superColliderRender.js` | Contained SuperCollider renders (#9413): media-queue `supercollider` jobs that snapshot source into a job-private dir, run the trusted NRT wrapper via `runSuperColliderContainer` (output quota, timeout, cancel → container force-removed), validate the decoded WAV and publish a 24 h preview + provenance sidecar (`readSuperColliderPreview`). Sweeps orphaned containers/scratch before each render. |diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex add5fbca8f..4a4c6b9a69 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -657,7 +657,7 @@ export async function initMediaJobQueue() {if (persistedJobs.length) {console.log(`📦 mediaJobQueue restored: ${queue.length} queued, ${archive.length} archived`);}- await videoHolds.resolveCohorts(queue);+ await prepareQueuedVideos();videoHolds.updateQueued(queue);// Pre-seed terminal SSE payloads for each restart-failed job so that any// client that reconnects to /:jobId/events after a restart (the route@@ -779,10 +779,51 @@ function startLaneJob(job, { lane }) {return true;}+// Withdraw synchronously before cleanup yields: cancellation and preparation+// can race, but only the caller that removes this exact waiting job owns it.+// Shared by pre-dispatch failures and queued cancellation; no lane is claimed.+async function settleQueuedJob(job, { status, error }) {+ const idx = queue.indexOf(job);+ if (idx < 0 || job.status !== 'queued') return false;+ queue.splice(idx, 1);+ job.status = status;+ job.error = error;+ job.completedAt = new Date().toISOString();+ archive.push(job);+ recomputeQueuePositions();+ await trackTerminalOperation((async () => {+ await safeUnlinkUpload(job.params?.uploadedTempPath);+ await safeUnlinkUpload(job.params?.audioFilePath);+ for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {+ await safeUnlinkUpload(p);+ }+ await persist().catch((e) => console.error(`❌ mediaJobQueue persist on queued ${status} failed: ${e.message}`));+ broadcastSse(ensureSseEntry(job.id), status === 'canceled'+ ? { type: 'canceled', reason: error } : { type: 'error', error });+ closeJobAfterDelay(sseJobs, job.id);+ mediaJobEvents.emit(status, job);+ if (status === 'failed') console.error(`❌ media-job [${job.id.slice(0, 8)}] preparation failed: ${error}`);+ else console.log(`🛑 media-job [${job.id.slice(0, 8)}] canceled (was queued)`);+ })());+ return true;+}++async function prepareQueuedVideos(jobs = queue.filter((job) => !job.admitting)) {+ // An admission still waiting for its durable snapshot is not eligible for+ // preparation or failure. Re-check after every await before withdrawing it.+ const results = await videoHolds.resolveCohorts(jobs);+ for (const { job, error } of results) {+ if (dispatchQuiesced) break;+ if (!error || job.admitting) continue;+ await settleQueuedJob(job, { status: 'failed',+ error: `Could not prepare local video model: ${error.message || String(error)}` });+ }+}+async function drainLoop() {while (!dispatchQuiesced) {- const candidates = queue.slice();- await videoHolds.resolveCohorts(candidates);+ const candidates = queue.filter((job) => !job.admitting);+ await prepareQueuedVideos(candidates);// Shutdown may have begun while cohorts resolved; exit without promoting.if (dispatchQuiesced) break;videoHolds.updateQueued(queue);@@ -1484,39 +1525,8 @@ export async function cancelQueuedJobs({ kind } = {}) {export async function cancelJob(jobId) {const queueIdx = queue.findIndex((j) => j.id === jobId);if (queueIdx >= 0) {- const [job] = queue.splice(queueIdx, 1);- // Multipart uploads (e.g. /api/video-gen with an image) hand us a path- // staged under PATHS.uploads. If we drop the job before it starts,- // runJob never gets a chance to delete it — clean up here so the- // uploads dir doesn't accumulate. safeUnlinkUpload constrains the- // delete to PATHS.uploads. audioFilePath is the same kind of staged- // upload (a2v/voice/video jobs) and would otherwise leak when the user- // cancels before the job starts.- await safeUnlinkUpload(job.params?.uploadedTempPath);- await safeUnlinkUpload(job.params?.audioFilePath);- for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {- await safeUnlinkUpload(p);- }- job.status = 'canceled';- job.error = 'Canceled before start';- job.completedAt = new Date().toISOString();- // Archive so /api/media-jobs?status=canceled and the recent-reel UI- // can still find it within the 24h TTL. Mirrors the running-cancel path- // in startLaneJob's terminal handler.- archive.push(job);- // Removing a queued job shifts everyone behind it up one slot. Recompute- // + broadcast so clients still attached to those SSE streams see the new- // position immediately, instead of waiting for the next dequeue.- recomputeQueuePositions();- const sseEntry = ensureSseEntry(jobId);- // Emit `canceled` (not `error`) so clients can distinguish a user-- // initiated cancellation from a real failure. Mirror the event type- // emitted for running-job cancellation in runJob's failed handler.- broadcastSse(sseEntry, { type: 'canceled', reason: job.error });- closeJobAfterDelay(sseJobs, jobId);- mediaJobEvents.emit('canceled', job);- persist().catch(() => {});- console.log(`🛑 media-job [${jobId.slice(0, 8)}] canceled (was queued)`);+ const job = queue[queueIdx];+ await settleQueuedJob(job, { status: 'canceled', error: 'Canceled before start' });return { ok: true, status: 'canceled' };}// Cancel-while-running — check every lane.diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 9b58a2296f..ed6b2bd476 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -38,12 +38,12 @@ vi.mock('../../lib/fileUtils.js', async () => {});vi.mock('../../lib/mediaModels.js', () => ({- getVideoModels: () => [+ getVideoModels: vi.fn(() => [{ id: 'example-mlx', runtime: 'mlx_video' },{ id: 'example-cuda', runtime: 'cuda_video' },{ id: 'example-large-cuda', runtime: 'cuda_video', hardwareRequirements: { requiresNvidiaGpu: true, minVramGb: 48 } },{ id: 'example-other', runtime: 'mlx_video' },- ],+ ]),getDefaultVideoModelId: vi.fn(() => 'example-mlx'),}));@@ -2415,6 +2415,165 @@ describe('local video failure holds', () => {});});+// A rejected cohort lookup must settle only its local-video jobs, without+// turning model preparation into an admission gate for other lanes.+describe('local video preparation failures', () => {+ let resolveModel;+ beforeEach(async () => {+ vi.useFakeTimers();+ resolveModel = vi.fn(async () => ({ model: { id: 'example-mlx', runtime: 'mlx_video' } }));+ vi.doMock('../videoGen/modelSelection.js', () => ({ resolveVideoModelSelection: resolveModel }));+ await importFresh();+ });+ afterEach(() => {+ vi.doUnmock('../videoGen/modelSelection.js');+ vi.clearAllTimers();+ vi.useRealTimers();+ });+ const tick = async () => {+ await vi.dynamicImportSettled();+ await vi.advanceTimersByTimeAsync(150);+ await flush();+ };+ const stage = () => {+ const uploads = join(tempDataDir, 'uploads');+ mkdirSync(uploads, { recursive: true });+ const paths = ['frame.png', 'audio.wav', 'extra.png'].map((name) => join(uploads, name));+ paths.forEach((path) => writeFileSync(path, 'synthetic upload'));+ return paths;+ };+ const waitForFailure = async (id) => {+ await vi.waitFor(() => expect(mediaJobQueue.getJob(id).status).toBe('failed'));+ await flush();+ };+ const readJobs = () => JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf8')).jobs;++ it('fails an omitted-model job once, cleans its inputs, and drains independent lanes without another enqueue', async () => {+ await mediaJobQueue.initMediaJobQueue();+ const paths = stage();+ const failed = vi.fn();+ mediaJobQueue.mediaJobEvents.on('failed', failed);+ resolveModel.mockRejectedValue(new Error('Example settings could not be loaded'));+ const omitted = await mediaJobQueue.enqueueJob({ kind: 'video', params: {+ prompt: 'omitted model', uploadedTempPath: paths[0], audioFilePath: paths[1], uploadedTempPaths: [paths[2]],+ } });+ const explicit = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-mlx' } });+ const waiting = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-other' } });+ const cloud = await mediaJobQueue.enqueueJob({ kind: 'image', params: { mode: 'codex' } });+ const remote = await mediaJobQueue.enqueueJob({ kind: 'video', params: { remoteMedia: remoteVideoMediaParams() } });+ await tick();+ await waitForFailure(omitted.jobId);+ await vi.waitFor(() => expect(stubs.generateVideoRemote).toHaveBeenCalled());+ expect(stubs.generateVideo.mock.calls.map(([params]) => params.jobId)).toEqual([explicit.jobId]);+ expect(stubs.generateImageCodex).toHaveBeenCalledWith(expect.objectContaining({ jobId: cloud.jobId }));+ expect(stubs.generateVideoRemote).toHaveBeenCalledWith(expect.objectContaining({ jobId: remote.jobId }));+ expect(mediaJobQueue.getJob(waiting.jobId)).toMatchObject({ status: 'queued', position: 2 });+ expect(mediaJobQueue.getJob(omitted.jobId).error).toContain('Example settings could not be loaded');+ expect(failed).toHaveBeenCalledTimes(1);+ expect(readJobs().filter((job) => job.id === omitted.jobId)).toMatchObject([{ status: 'failed' }]);+ for (const path of paths) expect(existsSync(path)).toBe(false);+ const res = { write: vi.fn(), req: { on: vi.fn() }, writeHead: vi.fn(), flushHeaders: vi.fn(), end: vi.fn() };+ mediaJobQueue.attachSseClient(omitted.jobId, res);+ expect(res.write.mock.calls.flat().join('')).toContain('Could not prepare local video model');+ videoGenEvents.emit('completed', { generationId: explicit.jobId });+ await tick();+ expect(mediaJobQueue.getJob(waiting.jobId).status).toBe('running');+ videoGenEvents.emit('completed', { generationId: waiting.jobId });+ await flush();+ resolveModel.mockResolvedValue({ model: { id: 'example-mlx', runtime: 'mlx_video' } });+ const repaired = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after repair' } });+ await tick();+ expect(mediaJobQueue.getJob(repaired.jobId).status).toBe('running');+ expect(failed).toHaveBeenCalledTimes(1);+ expect(mediaJobQueue.listJobs().filter((job) => job.id === omitted.jobId)).toHaveLength(1);+ mediaJobQueue.mediaJobEvents.off('failed', failed);+ });++ it('restores a mixed snapshot without rejecting boot and resolves the failed default once for the batch', async () => {+ const paths = stage();+ resolveModel.mockRejectedValue(new Error('Example default unavailable'));+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: [+ { id: 'saved-omitted', kind: 'video', status: 'queued', params: { uploadedTempPath: paths[0], audioFilePath: paths[1], uploadedTempPaths: [paths[2]] } },+ { id: 'saved-empty', kind: 'video', status: 'queued', params: { modelId: '' } },+ { id: 'saved-explicit', kind: 'video', status: 'queued', params: { modelId: 'example-mlx' } },+ { id: 'saved-null', kind: 'video', status: 'queued', params: { modelId: null } },+ { id: 'saved-cloud', kind: 'image', status: 'queued', params: { mode: 'codex' } },+ { id: 'saved-remote', kind: 'video', status: 'queued', params: { remoteMedia: remoteVideoMediaParams() } },+ ] }));+ await expect(mediaJobQueue.initMediaJobQueue()).resolves.toBeUndefined();+ await tick();+ expect(resolveModel).toHaveBeenCalledTimes(1);+ for (const id of ['saved-omitted', 'saved-empty']) {+ expect(readJobs().filter((job) => job.id === id)).toMatchObject([{ status: 'failed', error: expect.stringContaining('Example default unavailable') }]);+ }+ expect(mediaJobQueue.getJob('saved-explicit').status).toBe('running');+ expect(mediaJobQueue.getJob('saved-cloud').status).toBe('running');+ expect(mediaJobQueue.getJob('saved-remote').status).toBe('running');+ expect(mediaJobQueue.getJob('saved-null')).toMatchObject({ status: 'queued', params: { modelId: null }, position: 2 });+ for (const path of paths) expect(existsSync(path)).toBe(false);+ });++ it('limits catalog failures to local videos while restored cloud and remote work dispatch', async () => {+ const { getVideoModels } = await import('../../lib/mediaModels.js');+ getVideoModels.mockImplementationOnce(() => { throw new Error('Example catalog unavailable'); });+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: [+ { id: 'catalog-local', kind: 'video', status: 'queued', params: { modelId: 'example-mlx' } },+ { id: 'catalog-default', kind: 'video', status: 'queued', params: {} },+ { id: 'catalog-cloud', kind: 'image', status: 'queued', params: { mode: 'codex' } },+ { id: 'catalog-remote', kind: 'video', status: 'queued', params: { remoteMedia: remoteVideoMediaParams() } },+ ] }));+ await expect(mediaJobQueue.initMediaJobQueue()).resolves.toBeUndefined();+ await tick();+ for (const id of ['catalog-local', 'catalog-default']) {+ expect(readJobs().filter((job) => job.id === id)).toMatchObject([{ status: 'failed', error: expect.stringContaining('Example catalog unavailable') }]);+ }+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ expect(resolveModel).not.toHaveBeenCalled();+ expect(mediaJobQueue.getJob('catalog-cloud').status).toBe('running');+ expect(mediaJobQueue.getJob('catalog-remote').status).toBe('running');+ });++ it.each(['cancel', 'shutdown'])('preserves %s ownership while default preparation is awaiting', async (action) => {+ await mediaJobQueue.initMediaJobQueue();+ let rejectModel;+ const pending = new Promise((_, reject) => { rejectModel = reject; });+ resolveModel.mockReturnValue(pending);+ const paths = stage();+ const failed = vi.fn();+ mediaJobQueue.mediaJobEvents.on('failed', failed);+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { uploadedTempPath: paths[0] } });+ await tick();+ expect(resolveModel).toHaveBeenCalledTimes(1);+ if (action === 'cancel') await mediaJobQueue.cancelJob(jobId);+ else mediaJobQueue.quiesceMediaJobQueue();+ rejectModel(new Error('Example default unavailable'));+ await tick();+ expect(failed).not.toHaveBeenCalled();+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ expect(mediaJobQueue.getJob(jobId).status).toBe(action === 'cancel' ? 'canceled' : 'queued');+ expect(existsSync(paths[0])).toBe(action === 'shutdown');+ expect(readJobs().filter((job) => job.id === jobId)).toHaveLength(1);+ mediaJobQueue.mediaJobEvents.off('failed', failed);+ });++ it('does not prepare or fail an admission before its snapshot settles', async () => {+ await mediaJobQueue.initMediaJobQueue();+ resolveModel.mockRejectedValue(new Error('Example default unavailable'));+ const release = holdNextWrite();+ const admission = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });+ await vi.advanceTimersByTimeAsync(150);+ await vi.dynamicImportSettled();+ expect(resolveModel).not.toHaveBeenCalled();+ expect(mediaJobQueue.listJobs()[0].status).toBe('queued');+ release();+ const { jobId, status } = await admission;+ expect(status).toBe('queued');+ await tick();+ await waitForFailure(jobId);+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ });+});+// #8325: a job id handed to a caller must survive a crash, so admission waits// for the snapshot that contains the job — and a failed snapshot refuses it.const persistedJobs = () => JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf-8')).jobs;diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.jsindex b10d5a810b..cd2153d2b3 100644--- a/server/services/mediaJobQueue/videoHolds.js+++ b/server/services/mediaJobQueue/videoHolds.js@@ -49,20 +49,34 @@ export function createVideoHolds() {clear,async resolveCohorts(jobs) {const local = jobs.filter(isLocalVideo);- if (!local.length) return;+ if (!local.length) return [];// Catalog loading stays off the queue's widely imported static graph.- const { getVideoModels } = await import('../../lib/mediaModels.js');+ // Preparation owns only local videos; an error is a per-job result,+ // never a rejection of the scheduler's mixed-lane pass.+ let models;+ try {+ const { getVideoModels } = await import('../../lib/mediaModels.js');+ models = getVideoModels();+ } catch (error) {+ return local.map((job) => ({ job, error }));+ }const omitted = (job) => job.params?.modelId === undefined || job.params?.modelId === '';let defaultModel = null;+ let defaultError;if (local.some(omitted)) {- const { resolveVideoModelSelection } = await import('../videoGen/modelSelection.js');- ({ model: defaultModel } = await resolveVideoModelSelection());+ try {+ const { resolveVideoModelSelection } = await import('../videoGen/modelSelection.js');+ ({ model: defaultModel } = await resolveVideoModelSelection());+ } catch (error) {+ defaultError = error;+ }}- const models = getVideoModels();- for (const job of local) {+ return local.map((job) => {+ if (omitted(job) && defaultError) return { job, error: defaultError };const model = omitted(job) ? defaultModel : models.find((m) => m.id === job.params.modelId);job.videoCohort = model ? { modelId: model.id, runtime: model.runtime || 'mlx_video' } : null;- }+ return { job };+ });},updateQueued(jobs) {const counts = new Map();