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

address review (self): guard watchdog against the async-terminate cancel race; tighten progress test; move done PLAN item to changelog

[._.]/ Adam Eivy6d815954a517
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 60962d0f45..de168fb63f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,7 @@
## Changed
- **[chrome-canary-followups] Custom Chrome setup writes browser config through the shared atomic writer.** The Canary setup script now uses `server/lib/fileUtils.js#atomicWrite` for browser-config updates, so it gets the same temp-file/rename behavior and Windows fallback as the rest of PortOS config persistence.
+- **[media-job-throttled-progress-persist] Live media-job progress is now debounce-persisted to disk so a mid-render restart recovers the last snapshot.** `runJob` schedules a ~250ms-debounced `persist()` after each `progress`/`statusMsg` mutation — coalescing the dozens-per-second diffusion progress events instead of writing per event — and drains it in `terminate()` before the terminal transition, mirroring the `appendAgentOutputLines` batching pattern. The terminal sink (`terminate`) is now async and made idempotent via a `terminalStarted` guard, which also closes the watchdog `mod.cancel` race the async drain would otherwise widen.
- **[media-job-store-progress-on-job-record] Render queue rows now hydrate live progress from the job record.** The media job queue now stores `progress` and `statusMsg` on the running job whenever image/video runners emit progress or status events, exposes those fields through `GET /api/media-jobs/:id` and list responses, and preserves them in persisted queue snapshots. The Image / Video render queue uses that snapshot to show a compact progress bar during polling, so non-SSE consumers no longer reset in-flight jobs to 0% until the next live event arrives.
- **[shared-bounded-concurrency-mapper] Bounded-concurrency worker pool extracted to a shared helper.** The cursor-based worker-pool idiom that was hand-rolled in `embeddings.js`, `catalogExtraction.js`, and `routes/imageVideoModels.js` is now a single tested `server/lib/mapWithConcurrency.js` (order-preserving, concurrency-bounded), with all three call sites migrated and behavior unchanged.
- Bumped the bundled slashdo submodule (`lib/slashdo`) to latest `main` (`11cb89c`).
diff --git a/PLAN.md b/PLAN.md
index b2b9485206..db61c9e313 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.
-- [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.
+- [ ] [media-job-progress-persist-debounce-count-test] **Add a write-count regression test that pins the progress-persist *debounce* (not just the snapshot).** `server/services/mediaJobQueue/index.test.js`'s `debounce-persists live progress before a terminal transition` asserts the running snapshot reaches disk, but it would also pass if `scheduleProgressPersist` regressed to a naive per-event `persist()` — the high-frequency-write antipattern CLAUDE.md forbids. Pin the coalescing by counting `atomicWrite` calls under a burst of N progress events (expect ≪ N within one debounce window). Requires reworking the shared `vi.mock('../../lib/fileUtils.js')` to expose a counting spy on `atomicWrite` (it currently only overrides `PATHS`) — deferred from the `/do:review` self pass because the mock-harness change is larger/riskier than a contained edit and the underlying feature is cosmetic (single-user). 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 e1d8f1a603..88f5e3b7e1 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -714,7 +714,10 @@ async function runJob(job) {
let watchdogInFlight = false;
watchdogTimer = setInterval(async () => {
if (watchdogInFlight) return;
- if (job.status !== 'running') return;
+ // terminalStarted closes the window terminate() opens: it now awaits a
+ // disk drain before flipping job.status, so a tick that only checked
+ // status could fire mod.cancel on a job that is already terminating.
+ if (terminalStarted || job.status !== 'running') return;
const idleFor = Date.now() - lastActivityAt;
if (idleFor < idleTimeoutMs) return;
watchdogInFlight = true;
@@ -727,7 +730,9 @@ async function runJob(job) {
// queue still settles, and reset inFlight in finally.
try {
const mod = await getGenModuleForJob(job);
- if (job.status !== 'running') return;
+ // Re-check after the await — terminate() may have started (and is
+ // draining to disk with job.status still 'running') during the import.
+ if (terminalStarted || job.status !== 'running') return;
console.log(`⏱️ media-job [${job.id.slice(0, 8)}] watchdog fired after ${idleFor}ms idle (limit ${idleTimeoutMs}ms) — marking failed`);
if (mod?.cancel) mod.cancel(job.id);
handlers.failed({ error: `watchdog timeout: no runner output for ${Math.round(idleFor / 1000)}s (limit ${Math.round(idleTimeoutMs / 1000)}s)` });
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 68362da9ed..582f00ed21 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -255,12 +255,15 @@ describe('mediaJobQueue', () => {
const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'restart snapshot' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+ // Use a message synthesizeMessage() could NOT produce (it would emit
+ // "Rendering step 37/100" from step/totalSteps) so this pins the
+ // explicit-message passthrough, not the synthesized fallback.
videoGenEvents.emit('progress', {
generationId: job.jobId,
progress: 0.37,
step: 37,
totalSteps: 100,
- message: 'Rendering step 37/100',
+ message: 'Rendering step 37/100 (upscaling)',
});
await waitFor(() => {
@@ -268,7 +271,7 @@ describe('mediaJobQueue', () => {
const persisted = data.jobs.find((j) => j.id === job.jobId);
return persisted?.status === 'running'
&& persisted.progress === 0.37
- && persisted.statusMsg === 'Rendering step 37/100';
+ && persisted.statusMsg === 'Rendering step 37/100 (upscaling)';
}, { timeoutMs: 2000 });
videoGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.mp4` });