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

Persist media job progress snapshots

[._.]/ Adam Eivy47d88a0b6edc
diff --git a/PLAN.md b/PLAN.md
index fc103bf57c..b2b9485206 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -11,7 +11,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
-- [ ] [media-job-throttled-progress-persist] **Throttle-persist live media-job progress so a mid-render restart recovers the last snapshot, not 0%/Starting.** `runJob`'s `handlers.progress` in `server/services/mediaJobQueue/index.js` (~lines 582-586) now mutates `job.progress`/`job.statusMsg` in memory (visible to `getJob`/`listJobs` and `GET /api/media-jobs/:id`) but only writes to disk on enqueue/start/terminal — so a restart before the terminal transition recovers (and then reclassifies as failed) the stale start snapshot. Cosmetic only (the recovered row is already `failed`), deferred from the PR #581 self-review codex pass because a naive per-event `persist()` is the high-frequency-write antipattern CLAUDE.md forbids — diffusion runners emit progress dozens/sec. If picked up: add a ~250ms-debounced persist after the progress mutation and drain it in `terminate()` before the terminal `persist()`, mirroring the `appendAgentOutputLines` batching pattern. Low priority.
+- [x] [media-job-throttled-progress-persist] **Throttle-persist live media-job progress so a mid-render restart recovers the last snapshot, not 0%/Starting.** `runJob`'s `handlers.progress` in `server/services/mediaJobQueue/index.js` (~lines 582-586) now mutates `job.progress`/`job.statusMsg` in memory (visible to `getJob`/`listJobs` and `GET /api/media-jobs/:id`) but only writes to disk on enqueue/start/terminal — so a restart before the terminal transition recovers (and then reclassifies as failed) the stale start snapshot. Cosmetic only (the recovered row is already `failed`), deferred from the PR #581 self-review codex pass because a naive per-event `persist()` is the high-frequency-write antipattern CLAUDE.md forbids — diffusion runners emit progress dozens/sec. If picked up: add a ~250ms-debounced persist after the progress mutation and drain it in `terminate()` before the terminal `persist()`, mirroring the `appendAgentOutputLines` batching pattern. Low priority.
- [ ] [unify-media-job-sse-hook-imagegen-videogen] **Unify ImageGen + VideoGen SSE attach into `useMediaJobSse` hook.** Both pages now have near-duplicate EventSource handlers (ImageGen `startLocalGeneration` ~lines 655 + resume block ~317; VideoGen `attachJobEvents` ~line 450). Build a hook on top of `useSseProgress` (`client/src/hooks/useSseProgress.js`) that handles the queued / started / status / progress / complete / error / canceled SSE types and consolidate both sites.
- [ ] [capabilities-cheap-memory-count] **Capabilities route should count active memories without sorting/paginating.** `GET /api/capabilities` calls `getMemories({ status: 'active' })` (`server/routes/capabilities.js` ~line 69) only to read `.total`, but `getMemories` loads the full index, filters, sorts, and paginates before returning `{ total, memories }` — the sort + slice is wasted work on a page polled every ~20s. Add a lightweight `countMemories({ status })` (or a `countOnly` option) to `server/services/memory.js` that returns the filtered count without the sort/paginate, and switch the route to it. Micro-opt; the index is cached via `loadIndex`, so low urgency.
- [ ] [banner-icon-aria-hidden] **Apply `aria-hidden="true"` to `<Banner>`'s rendered icon.** `client/src/components/ui/Banner.jsx` (~line 62) renders the `icon` prop as a bare `<Icon …>` — when the icon is decorative (the body text already conveys the meaning), screen readers should skip it. Either wrap the icon render in `<span aria-hidden="true">` inside Banner, or thread an `iconAriaHidden` prop. Once landed, re-migrate the `ImportTab.jsx` error row to `<Banner tone="error" size="md" icon={AlertCircle} actions={…}>` (it was reverted from `<Banner>` because the icon prop doesn't pass through a11y attributes).
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index cceedb0c77..e1d8f1a603 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -64,6 +64,7 @@ const WATCHDOG_IMAGE_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_IMAGE_MS, 5
// default trips false positives. 20 minutes covers a slow generation +
// queueing delay, and is env-overridable when batch limits change.
const WATCHDOG_CODEX_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_CODEX_MS, 20 * 60 * 1000);
+const PROGRESS_PERSIST_DEBOUNCE_MS = 250;
// Returns true if `p` resolves strictly under PATHS.uploads. Shared by
// safeUnlinkUpload (cleanup) and the pre-gen sanitizer (Thread #1 guard).
@@ -544,20 +545,54 @@ function makeGenDispatcher(emitter, job, handlers) {
async function runJob(job) {
const sseEntry = ensureSseEntry(job.id);
+ let progressPersistDirty = false;
+ let progressPersistTimer = null;
+ let progressPersisting = null;
+ let terminalStarted = false;
+
+ const flushProgressPersist = async () => {
+ if (progressPersistTimer) {
+ clearTimeout(progressPersistTimer);
+ progressPersistTimer = null;
+ }
+ if (!progressPersistDirty) return;
+ progressPersistDirty = false;
+ await persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on progress failed: ${e.message}`));
+ };
+
+ const drainProgressPersist = async () => {
+ if (progressPersisting) await progressPersisting.catch(() => {});
+ await flushProgressPersist();
+ };
+
+ const scheduleProgressPersist = () => {
+ progressPersistDirty = true;
+ if (progressPersistTimer || progressPersisting) return;
+ progressPersistTimer = setTimeout(() => {
+ progressPersistTimer = null;
+ progressPersisting = flushProgressPersist().finally(() => {
+ progressPersisting = null;
+ if (progressPersistDirty) scheduleProgressPersist();
+ });
+ }, PROGRESS_PERSIST_DEBOUNCE_MS);
+ progressPersistTimer.unref?.();
+ };
// Single idempotent terminal sink. All terminal paths (completed, failed,
// canceled, watchdog) funnel through here. The status check at the top
// ensures only the first caller wins; any subsequent call (e.g. watchdog
// fired and then the gen emits 'completed') is a no-op.
let watchdogTimer;
- function terminate(state, apply) {
- if (job.status !== 'running') return;
+ async function terminate(state, apply) {
+ if (terminalStarted || job.status !== 'running') return;
+ terminalStarted = true;
// setInterval now (was setTimeout) — using clearInterval to match the new
// API. (Node accepts either clearTimeout or clearInterval on the same
// Timeout handle, so this is purely stylistic.)
clearInterval(watchdogTimer);
emitter.off?.('activity', onActivity);
emitter.off?.('progress', onActivity);
+ await drainProgressPersist();
apply(job);
job.status = state;
if (state === 'completed') {
@@ -582,16 +617,22 @@ async function runJob(job) {
const handlers = {
progress: (payload) => {
+ if (terminalStarted || job.status !== 'running') return;
+ let didUpdatePersistedProgress = false;
if (payload.type === 'progress' && typeof payload.progress === 'number' && Number.isFinite(payload.progress)) {
job.progress = Math.max(0, Math.min(1, payload.progress));
+ didUpdatePersistedProgress = true;
}
if (typeof payload.message === 'string' && payload.message.length > 0) {
job.statusMsg = payload.message;
+ didUpdatePersistedProgress = true;
}
+ if (didUpdatePersistedProgress) scheduleProgressPersist();
broadcastSse(sseEntry, payload);
},
completed: (payload) => {
- terminate('completed', (j) => { j.result = payload; });
+ terminate('completed', (j) => { j.result = payload; })
+ .catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`));
},
failed: (payload) => {
// If cancelJob() flagged this job before the underlying gen reported
@@ -603,10 +644,11 @@ async function runJob(job) {
// is cleaned up still gets a meaningful terminal frame from the
// archived state, rather than the generic "Canceled" fallback.
j.error = 'Canceled while running';
- });
+ }).catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`));
return;
}
- terminate('failed', (j) => { j.error = payload.error || 'unknown error'; });
+ terminate('failed', (j) => { j.error = payload.error || 'unknown error'; })
+ .catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`));
},
};
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index ed318c0f7f..68362da9ed 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -250,6 +250,31 @@ describe('mediaJobQueue', () => {
expect(persisted.statusMsg).toBe('Completed');
});
+ it('debounce-persists live progress before a terminal transition', async () => {
+ const file = join(tempDataDir, 'media-jobs.json');
+ const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'restart snapshot' } });
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+
+ videoGenEvents.emit('progress', {
+ generationId: job.jobId,
+ progress: 0.37,
+ step: 37,
+ totalSteps: 100,
+ message: 'Rendering step 37/100',
+ });
+
+ await waitFor(() => {
+ const data = JSON.parse(readFileSync(file, 'utf-8'));
+ const persisted = data.jobs.find((j) => j.id === job.jobId);
+ return persisted?.status === 'running'
+ && persisted.progress === 0.37
+ && persisted.statusMsg === 'Rendering step 37/100';
+ }, { timeoutMs: 2000 });
+
+ videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');
+ });
+
it('boot recovery: persisted "running" jobs are reclassified as failed', async () => {
const interruptedId = '00000000-0000-4000-8000-000000000001';
const persisted = {