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: recover media lanes when saved video holds are damaged (#6282)
[._.]/ Adam Eivy94dbb86398ea
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex 465e9201a1..bed30814b6 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -297,12 +297,12 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''{holds.map((hold) => (<div key={hold.id} role="status" className="rounded border border-port-warning/30 bg-port-warning/10 p-3 text-sm"><div className="font-medium text-port-warning">{hold.heldJobCount} video job{hold.heldJobCount === 1 ? '' : 's'} held</div>- <div className="text-xs text-port-text-muted break-words">{hold.modelId} · {hold.runtime}</div>+ <div className="text-xs text-port-text-muted break-words">{hold.scope === 'local-video' ? 'All local video' : `${hold.modelId} · ${hold.runtime}`}</div><p className="mt-1 break-words">{hold.cause}</p>- <p className="mt-1 text-xs text-port-text-muted">Three matching failures. Repair the runtime, then resume the retained jobs.</p>+ {hold.scope !== 'local-video' && <p className="mt-1 text-xs text-port-text-muted">Three matching failures. Repair the runtime, then resume the retained jobs.</p>}<button type="button" disabled={resumingHold !== null} onClick={() => handleResume(hold.id)}className="mt-2 min-h-[44px] rounded border border-port-border px-3 py-2 text-sm hover:bg-port-border disabled:opacity-50">- {resumingHold === hold.id ? 'Resuming…' : 'Resume'}+ {resumingHold === hold.id ? 'Resuming…' : hold.scope === 'local-video' ? 'Resume all local video' : 'Resume'}</button></div>))}diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsxindex 3db724b072..3d5e386bc7 100644--- a/client/src/components/media/MediaJobsQueue.test.jsx+++ b/client/src/components/media/MediaJobsQueue.test.jsx@@ -713,6 +713,21 @@ 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([]);+ listMediaVideoHolds.mockResolvedValue([{ id: 'recovery-hold', scope: 'local-video', modelId: '*', runtime: '*',+ cause: 'Saved video holds are damaged.', heldJobCount: 0 }]);+ const user = userEvent.setup();+ render(<MediaJobsQueue kind="video" />);+ expect(await screen.findByText('All local video')).toBeInTheDocument();+ expect(screen.queryByText(/Three matching failures/)).not.toBeInTheDocument();+ resumeMediaVideoHold.mockResolvedValue({ resumed: true });+ listMediaVideoHolds.mockResolvedValue([]);+ await user.click(screen.getByRole('button', { name: 'Resume all local video' }));+ await waitFor(() => expect(screen.queryByText('All local video')).not.toBeInTheDocument());+ expect(resumeMediaVideoHold).toHaveBeenCalledWith('recovery-hold', { silent: true });+ });+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: {} }));diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 852286d294..cc46b283ac 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -107,7 +107,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](**Examples.**- Upload staging — `data/uploads/*`. Ephemeral; do not put in DB except as job references.-- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB. Local video failure holds live in the existing `data/media-jobs.json` envelope as `videoHolds`, beside unchanged `jobs`. They are machine-local dispatch state, never federated and never sent in capability/status payloads to peers; the local queue API exposes them on retained jobs and through `GET /api/media-jobs/holds`, so status and resume remain available when no retained jobs remain. Three matching terminal causes hold one catalog model/runtime until explicit resume. Migration 344 adds an empty hold list to legacy envelopes without changing jobs; fresh installs use the empty seed. The envelope retains its existing filesystem backup coverage, with no new store, search index, sync cursor, or tombstone.+- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB. Local video failure holds live in the existing `data/media-jobs.json` envelope as `videoHolds`, beside unchanged `jobs`. They are machine-local dispatch state, never federated and never sent in capability/status payloads to peers; the local queue API exposes them on retained jobs and through `GET /api/media-jobs/holds`, so status and resume remain available when no retained jobs remain. Three matching terminal causes hold one catalog model/runtime until explicit resume. If hold metadata is damaged, boot restores unrelated work but holds all local video, including new submissions, behind an explicit session-only recovery action; the original snapshot stays preserved until repaired and restarted. Migration 344 adds an empty hold list to legacy envelopes without changing jobs; fresh installs use the empty seed. The envelope retains its existing filesystem backup coverage, with no new store, search index, sync cursor, or tombstone.- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.- CoS event ledgers — ordinary diagnostics use `data/cos/run-events.jsonl` + `run-events.1.jsonl`; persistent-mind trajectory uses the separate `mind-events.jsonl` + `mind-events.1.jsonl` pair (`server/services/agentRunEventLog.js`, #4540, #5082). Both are append-only, machine-local `ephemeral-file` replay aids with no federation cursor, tombstone, or `PORTOS_SCHEMA_VERSIONS` entry. The durable ordinary run record remains `data/runs/{id}/metadata.json`; mind rollups remain in their own bounded cache. Ordinary generations rotate at 5000 events and additionally expire after 30 days. Mind generations rotate at 10000 events without an age cutoff so a stopped mind keeps its unsummarized window, while high-volume mind chatter cannot evict ordinary run diagnostics. Migration 301 moves existing `mind.*` lines out of the shared files and stamps predecessor sequence provenance used to distinguish a legitimate timestamp jump from lost retained events. Payloads are redacted at append time, and both bounded pairs are backed up with the rest of `data/cos/`.diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex c573fb957b..ebfb297958 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -466,7 +466,7 @@ export async function initMediaJobQueue() {// A malformed hold must neither kill server boot nor silently release a// batch. Preserve the snapshot under the existing unreadable-file latch.persistBlocked = true;- console.error('❌ media-job queue: invalid video holds — snapshot preserved and retained jobs not dispatched; repair the holds and restart');+ console.error('❌ media-job queue: invalid video holds — snapshot preserved and local video held; repair the holds and restart');}const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];const restartedFailedIds = [];@@ -486,8 +486,6 @@ export async function initMediaJobQueue() {// present is an orphan from the prior process.const videoReap = await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));if (videoReap.reaped) console.log(`🧹 reaped ${videoReap.reaped} surviving render(s) on boot`);- if (!holdsReadable) return;-for (const j of persistedJobs) {if (j.status === 'running') {// A remote provider job survives this process: its local queue id isdiff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 000a671d94..95a9ae670f 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -1863,8 +1863,8 @@ describe('local video failure holds', () => {expect(mediaJobQueue.getJob(ids[5]).status).toBe('running');});- it('loads legacy jobs without treating startup reconciliation as an engine failure', async () => {- writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: [+ it.each([undefined, null])('loads legacy jobs with holds=%s without counting restart failures', async (videoHolds) => {+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ videoHolds, jobs: [...[1, 2, 3].map((n) => ({ id: `interrupted-${n}`, kind: 'video', status: 'running', params: { modelId: 'example-mlx' } })),{ id: 'retained-legacy', kind: 'video', status: 'queued', params: { modelId: 'example-mlx' } },] }));@@ -1875,18 +1875,53 @@ describe('local video failure holds', () => {expect(mediaJobQueue.getJob(next).status).toBe('running');});- it('preserves malformed holds without crashing boot or dispatching the retained batch', async () => {+ it('recovers independent work while damaged holds protect saved and new local video until explicit resume', async () => {const file = join(tempDataDir, 'media-jobs.json');- const snapshot = JSON.stringify({ jobs: [{ id: 'retained-corrupt', kind: 'video', status: 'queued',- params: { modelId: 'example-mlx' } }], videoHolds: [{ id: 'malformed-hold' }] });+ const savedVideos = ['retained-mlx', 'retained-cuda'];+ const snapshot = JSON.stringify({ jobs: [+ ...savedVideos.map((id, index) => ({ id, kind: 'video', status: 'queued',+ params: { modelId: index ? 'example-cuda' : 'example-mlx' } })),+ { id: 'saved-image', kind: 'image', status: 'queued', params: {} },+ { id: 'saved-cloud', kind: 'video', status: 'queued', params: { mode: 'grok' } },+ { id: 'saved-remote', kind: 'video', status: 'running', params: { remoteMedia: remoteVideoMediaParams() } },+ { id: 'saved-training', kind: 'training', status: 'running', params: { runId: 'example-training' } },+ { id: 'interrupted-video', kind: 'video', status: 'running', params: { modelId: 'example-mlx' } },+ ], videoHolds: [+ { id: 'aaaaaaaa-0000-4000-8000-000000000001', modelId: 'example-cuda', runtime: 'cuda_video',+ classification: 'runtimeerror', cause: 'shader failed', heldAt: new Date().toISOString() },+ { id: 'malformed-hold' },+ ] });writeFileSync(file, snapshot);+ stubs.hasSurvivingTrainer.mockResolvedValue(true);+ stubs.runTraining.mockResolvedValue({});await expect(mediaJobQueue.initMediaJobQueue()).resolves.toBeUndefined();await tick();expect(stubs.generateVideo).not.toHaveBeenCalled();- expect(readFileSync(file, 'utf8')).toBe(snapshot);- submit('example-other');+ expect(mediaJobQueue.getJob('interrupted-video').status).toBe('failed');+ expect(mediaJobQueue.getJob('saved-remote')).toMatchObject({ status: 'running', params: { remoteMedia: { reconcile: true } } });+ expect(mediaJobQueue.getJob('saved-cloud').status).toBe('running');+ expect(mediaJobQueue.getJob('saved-training')).toMatchObject({ status: 'running', params: { reattach: true } });+ (await import('../loraTraining/events.js')).trainingEvents.emit('completed', { generationId: 'saved-training' });+ await tick();+ expect(mediaJobQueue.getJob('saved-image').status).toBe('running');+ imageGenEvents.emit('completed', { generationId: 'saved-image' });+ await flush();+ const newlyQueued = submit('example-other');await tick();+ const retainedIds = [...savedVideos, newlyQueued];+ for (const id of retainedIds) expect(mediaJobQueue.getJob(id)).toMatchObject({ status: 'queued', hold: { scope: 'local-video', heldJobCount: 3 } });+ expect(mediaJobQueue.isVideoModelHeld('example-cuda', 'cuda_video')).toBe(true);+ expect(mediaJobQueue.isVideoModelHeld('example-other', 'mlx_video')).toBe(true);+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ expect(readFileSync(file, 'utf8')).toBe(snapshot);+ const [recoveryHold] = mediaJobQueue.listVideoHolds();+ expect(recoveryHold).toMatchObject({ scope: 'local-video', heldJobCount: 3 });+ const { sanitizeJob } = await import('./sanitizeJob.js');+ expect(sanitizeJob(mediaJobQueue.getJob(savedVideos[0])).hold).toEqual(recoveryHold);+ expect(await mediaJobQueue.resumeVideoHold(recoveryHold.id)).toBe(true);+ expect(mediaJobQueue.listVideoHolds()).toEqual([]);+ for (const id of retainedIds) { await tick(); await finish(id, null); }+ expect(stubs.generateVideo.mock.calls.map(([params]) => params.jobId)).toEqual(retainedIds);expect(readFileSync(file, 'utf8')).toBe(snapshot);- expect(stubs.generateVideo.mock.calls.every(([params]) => params.jobId !== 'retained-corrupt')).toBe(true);});});diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.jsindex ba334a8ddb..1ba3476587 100644--- a/server/services/mediaJobQueue/sanitizeJob.js+++ b/server/services/mediaJobQueue/sanitizeJob.js@@ -101,7 +101,8 @@ export function sanitizeJob(job) {executionLane: mediaJobExecutionLane({ kind: job.kind, mode: job.params?.mode, remote: routed }),owner: job.owner,status: job.status,- ...(hold?.success ? { hold: { ...hold.data, heldJobCount: job.hold.heldJobCount } } : {}),+ ...(hold?.success ? { hold: { ...hold.data, heldJobCount: job.hold.heldJobCount,+ ...(job.hold.scope === 'local-video' ? { scope: 'local-video' } : {}) } } : {}),queuedAt: job.queuedAt,startedAt: job.startedAt,completedAt: job.completedAt,diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.jsindex 64da557a32..b10d5a810b 100644--- a/server/services/mediaJobQueue/videoHolds.js+++ b/server/services/mediaJobQueue/videoHolds.js@@ -21,16 +21,32 @@ export const videoHoldSchema = z.object({export function createVideoHolds() {const holds = new Map();const streaks = new Map();+ let recoveryHold = null;+ const holdFor = (cohort) => recoveryHold || (cohort && holds.get(cohortKey(cohort)));+ const clear = () => { holds.clear(); streaks.clear(); recoveryHold = null; };return {- restore(value = []) {- const result = z.array(videoHoldSchema).safeParse(value);- if (!result.success) return false;- for (const hold of result.data) holds.set(cohortKey(hold), hold);- return true;+ restore(value) {+ const entries = value ?? [];+ let readable = Array.isArray(entries);+ for (const entry of readable ? entries : []) {+ const result = videoHoldSchema.safeParse(entry);+ if (result.success) holds.set(cohortKey(result.data), result.data);+ else readable = false;+ }+ if (!readable) {+ // Unknown hold metadata cannot identify a safe local video cohort.+ // Cover all local video, including new submissions, while other kinds+ // recover normally. The queue latches persistence off to preserve the+ // original file; this recovery hold exists only in this process.+ recoveryHold = { id: randomUUID(), scope: 'local-video', modelId: '*', runtime: '*',+ classification: 'invalid-hold-metadata', heldAt: new Date().toISOString(),+ cause: 'Saved video holds are damaged. Repair the queue snapshot and restart to restore persistence. Resume releases all local video holds for this session.' };+ }+ return readable;},- snapshot: () => [...holds.values()],- has: (cohort) => holds.has(cohortKey(cohort)),- clear() { holds.clear(); streaks.clear(); },+ snapshot: () => recoveryHold ? [recoveryHold] : [...holds.values()],+ has: (cohort) => Boolean(holdFor(cohort)),+ clear,async resolveCohorts(jobs) {const local = jobs.filter(isLocalVideo);if (!local.length) return;@@ -51,13 +67,12 @@ export function createVideoHolds() {updateQueued(jobs) {const counts = new Map();for (const job of jobs) {- const key = job.videoCohort && cohortKey(job.videoCohort);- if (isLocalVideo(job) && holds.has(key)) counts.set(key, (counts.get(key) || 0) + 1);+ const hold = isLocalVideo(job) && holdFor(job.videoCohort);+ if (hold) counts.set(hold.id, (counts.get(hold.id) || 0) + 1);}for (const job of jobs) {- const key = job.videoCohort && cohortKey(job.videoCohort);- job.hold = isLocalVideo(job) && holds.has(key)- ? { ...holds.get(key), heldJobCount: counts.get(key) } : undefined;+ const hold = isLocalVideo(job) && holdFor(job.videoCohort);+ job.hold = hold ? { ...hold, heldJobCount: counts.get(hold.id) } : undefined;}},captureFailure(job, error, { code, failure } = {}) {@@ -82,6 +97,7 @@ export function createVideoHolds() {}},resume(id) {+ if (recoveryHold?.id === id) { clear(); return true; }const entry = [...holds].find(([, hold]) => hold.id === id);if (!entry) return false;holds.delete(entry[0]);