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

fix: refresh media queue and checkpoints from socket events (#8533)

[._.]/ Adam Eivyb9d8cfaa2505
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 75676a743e..a13c0c341b 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -1,4 +1,4 @@
-import { useMemo, useState, useCallback, useEffect } from 'react';
+import { useMemo, useState, useEffect } from 'react';
import { ListOrdered, Image as ImageIcon, Film, Cpu, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import toast from '../ui/Toast';
@@ -14,9 +14,8 @@ import {
DEFAULT_I2V_REFERENCE_MODE, isDefaultI2vReferenceMode, normalizeI2vReferenceMode,
resolveI2vReferenceStrength, runtimeSupportsI2vReferenceMode,
} from '../../lib/videoReferenceModes';
-import { useAutoRefetch } from '../../hooks/useAutoRefetch';
+import { useSocketResource } from '../../hooks/useSocketResource';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
-import useMounted from '../../hooks/useMounted';
import { formatTimeOfDaySeconds } from '../../utils/formatters';
import { getVideoGenStatus } from '../../services/apiImageVideo.js';
import { listLorasFull } from '../../services/api';
@@ -34,6 +33,9 @@ import { isDeliveryVideoModel } from '../../lib/videoFinish';
import { loraFamilyOf, videoLoraFamily } from '../../lib/runnerFamilies';
import LoraPicker from '../imageGen/LoraPicker';
+const QUEUE_EVENTS = ['media-jobs:changed'];
+const CHECKPOINT_EVENTS = ['training:checkpoints:changed'];
+
const STATUS_BADGE = {
queued: 'bg-port-border text-port-text-muted',
running: 'bg-port-accent/30 text-port-accent',
@@ -132,35 +134,26 @@ function modelLabel(params, renderer) {
// Completed jobs are excluded from the recent reel — those render as preview
// cards on the gen page already, so listing them here is duplicate noise.
export default function MediaJobsQueue({ kind, recentLimit = 10, className = '' }) {
- const [jobs, setJobs] = useState([]);
- const [holds, setHolds] = useState([]);
- const [loading, setLoading] = useState(true);
- const [hasSnapshot, setHasSnapshot] = useState(false);
- const [loadError, setLoadError] = useState(false);
const [showRecent, setShowRecent] = useState(false);
const [resumingHold, setResumingHold] = useState(null);
-
- const fetchJobs = useCallback(async () => {
- const outcome = await Promise.all([
+ const { data, loading, error, refetch: fetchJobs, updateData } = useSocketResource(async () => {
+ const [jobs, holds] = await Promise.all([
listQueueMediaJobs({ ...(kind ? { kind } : {}), limit: recentLimit }),
!kind || kind === 'video' ? listMediaVideoHolds() : [],
- ]).then(
- (value) => ({ value }),
- () => ({ error: true }),
- );
- if (outcome.error || !outcome.value.every(Array.isArray)) {
- setLoadError(true);
- setLoading(false);
- return;
- }
- setJobs(outcome.value[0]);
- setHolds(outcome.value[1]);
- setHasSnapshot(true);
- setLoadError(false);
- setLoading(false);
- }, [kind, recentLimit]);
-
- useAutoRefetch(fetchJobs, 3000, { pollOnly: true });
+ ]);
+ if (!Array.isArray(jobs) || !Array.isArray(holds)) throw new Error('Invalid queue snapshot');
+ return { jobs, holds };
+ }, { events: QUEUE_EVENTS, resourceKey: JSON.stringify([kind, recentLimit]) });
+ const jobs = data?.jobs ?? [];
+ const holds = data?.holds ?? [];
+ const hasSnapshot = data !== null;
+ const loadError = !!error;
+ const setJobs = (updater) => updateData(previous => ({
+ jobs: updater(previous?.jobs ?? []), holds: previous?.holds ?? [],
+ }));
+ const setHolds = (updater) => updateData(previous => ({
+ jobs: previous?.jobs ?? [], holds: updater(previous?.holds ?? []),
+ }));
const handleCancel = (id) => cancelMediaJob(id, { silent: true })
.then(() => {
@@ -209,7 +202,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
toast.success(`Re-queued as ${jobId.slice(0, 8)}${overrides ? ' (edited)' : ''}`);
// Optimistic: drop the original failed/canceled row immediately. The
// server's retry endpoint already prunes it from the archive, but the
- // next 3s poll would otherwise leave the stale row + button visible.
+ // next event read would otherwise leave the stale row + button visible.
setJobs((prev) => prev.filter((j) => j.id !== id));
fetchJobs();
})
@@ -250,7 +243,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
cancelQueuedMediaJobs(kind ? { kind } : {}, { silent: true })
.then(({ canceled }) => {
// Optimistic flip: queued → canceled (running jobs stay untouched).
- // The next 3s poll will reconcile if anything raced through.
+ // The queue change event reconciles anything that raced through.
setJobs((prev) => prev.map((j) => (j.status === 'queued' ? { ...j, status: 'canceled' } : j)));
toast.success(`Cleared ${canceled} queued job${canceled === 1 ? '' : 's'}`);
})
@@ -391,27 +384,19 @@ function trainingSummary(params) {
// plus the latest sample thumbnails. The media-job record carries no loss /
// sample data, so fetch the run's checkpoint list (step + loss + previewUrl).
// Re-fetches while the run is live so the curve grows as checkpoints land.
-function TrainingJobDetail({ runId, status }) {
- const [checkpoints, setCheckpoints] = useState(null); // null = loading; [] = none yet
- const mountedRef = useMounted();
-
- const load = useCallback(() => {
- listLoraTrainingCheckpoints(runId)
- .then((res) => {
- if (mountedRef.current) setCheckpoints(Array.isArray(res?.checkpoints) ? res.checkpoints : []);
- })
- .catch(() => { if (mountedRef.current) setCheckpoints([]); });
- }, [runId]);
-
- useEffect(() => { load(); }, [load]);
- // Poll only while the run is live — a terminal run's checkpoints are fixed.
- // `immediate: false` because the effect above already owns the first load.
- useAutoRefetch(load, 5000, {
- enabled: status === 'running' || status === 'queued',
- immediate: false,
- pollOnly: true,
+function TrainingJobDetail({ runId }) {
+ const { data: checkpoints, error } = useSocketResource(async () => {
+ const res = await listLoraTrainingCheckpoints(runId);
+ return Array.isArray(res?.checkpoints) ? res.checkpoints : [];
+ }, {
+ events: CHECKPOINT_EVENTS,
+ resourceKey: runId,
+ matchesEvent: event => event?.runId === runId,
});
+ if (error && checkpoints === null) {
+ return <div className="mt-2 text-[11px] text-port-warning">Checkpoints unavailable.</div>;
+ }
if (checkpoints === null) {
return <div className="mt-2 text-[11px] text-port-text-muted">Loading checkpoints…</div>;
}
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
index b7e01394cc..4c317b6705 100644
--- a/client/src/components/media/MediaJobsQueue.test.jsx
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -5,7 +5,7 @@ import { retypeSettled } from '../../test/settledInput';
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.
+// the network. The socket resource fetches once on mount.
const listQueueMediaJobs = vi.fn();
const cancelMediaJob = vi.fn();
const retryMediaJob = vi.fn();
@@ -36,6 +36,20 @@ vi.mock('../../services/apiLoraTraining.js', () => ({
listLoraTrainingCheckpoints: (...a) => listLoraTrainingCheckpoints(...a),
}));
+const socketHandlers = vi.hoisted(() => new Map());
+vi.mock('../../services/socket', () => ({
+ default: {
+ on: (event, handler) => {
+ if (!socketHandlers.has(event)) socketHandlers.set(event, new Set());
+ socketHandlers.get(event).add(handler);
+ },
+ off: (event, handler) => socketHandlers.get(event)?.delete(handler),
+ },
+}));
+const emitSocket = (event, payload) => {
+ for (const handler of socketHandlers.get(event) ?? []) handler(payload);
+};
+
import MediaJobsQueue from './MediaJobsQueue';
const trainingJob = {
@@ -523,70 +537,54 @@ describe('MediaJobsQueue — training rows', () => {
});
});
-// #5697 — the checkpoint poll used to be a raw `useEffect` + `setInterval`, so
-// a live training run kept re-listing checkpoints every 5s from a background
-// tab. This is the gated (`enabled`) half of the migration; MemoryManagement
-// covers the unconditional half.
-describe('MediaJobsQueue — hidden-tab polling (#5697)', () => {
+// Queue and checkpoints advance from events, without timer-driven reads.
+describe('MediaJobsQueue — socket updates', () => {
beforeEach(() => { vi.useFakeTimers({ shouldAdvanceTime: true }); });
- afterEach(() => { vi.useRealTimers(); });
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); });
- it('pauses the checkpoint poll while the tab is hidden and re-fires on return', async () => {
+ it('updates from events and reconciles reconnect and tab show once', async () => {
listQueueMediaJobs.mockResolvedValue([trainingJob]);
listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
-
- render(<MediaJobsQueue kind="training" />);
- /*
- * Settle the mount on an OBSERVABLE state before taking the baseline call
- * counts below.
- *
- * The tick-counting form this replaced — `advanceTimersByTimeAsync(0)`
- * inside one `act` flush — settles a FIXED number of microtask turns, not
- * "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
- * `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.
- *
- * `TrainingJobDetail` renders this copy only once `listLoraTrainingCheckpoints`
- * has RESOLVED (`checkpoints` leaves its `null` loading sentinel), and it
- * only renders at all once the job list has landed and produced the row —
- * so it is the end of both mount chains.
- *
- * The fake clock stays armed across the mount, unlike BeeperTab's
- * settle-then-arm order (#7592): BOTH polls under test here are
- * `setInterval`s registered during mount, so a real-timer mount would leave
- * them on the real clock where `advanceTimersByTimeAsync` cannot reach them
- * — and both "did not fire while hidden" assertions would pass vacuously
- * again, for a new reason.
- *
- * `shouldAdvanceTime` is what makes the barrier possible under that armed
- * clock, and is NOT optional here. @testing-library/dom@10's
- * `jestFakeTimersAreEnabled` only recognizes JEST's fake timers, so with
- * vitest's installed `waitFor` takes its REAL-timer path and then waits on
- * a timer the fake clock owns: against a frozen clock it never polls again
- * and the test burns its whole timeout. Auto-advancing in step with real
- * time keeps that poll alive at the cost of a few ms of fake clock — three
- * orders below the 5s poll interval these assertions measure.
- */
+ const { unmount } = render(<MediaJobsQueue kind="training" />);
await screen.findByText(/No checkpoints yet/);
+ expect(listQueueMediaJobs).toHaveBeenCalledTimes(1);
expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
- const jobListCalls = listQueueMediaJobs.mock.calls.length;
- const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(listQueueMediaJobs).toHaveBeenCalledTimes(1);
expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
- // The queue's own job poll is paused by the same hook.
- expect(listQueueMediaJobs.mock.calls.length).toBe(jobListCalls);
- visibility.mockReturnValue('visible');
+ listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [
+ { step: 250, loss: 0.42, previewUrl: '/example-preview.png' },
+ ] });
+ await act(async () => { emitSocket('training:checkpoints:changed', { runId: 'other-run' }); });
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
+ await act(async () => { emitSocket('training:checkpoints:changed', { runId: 'run-abc' }); });
+ expect(screen.queryByText(/No checkpoints yet/)).not.toBeInTheDocument();
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(2);
+
+ await act(async () => { emitSocket('connect'); });
+ expect(listQueueMediaJobs).toHaveBeenCalledTimes(2);
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(3);
+
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });
await act(async () => {
- document.dispatchEvent(new Event('visibilitychange'));
- await vi.advanceTimersByTimeAsync(0);
+ emitSocket('media-jobs:changed', {});
+ await vi.advanceTimersByTimeAsync(60_000);
});
- expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(2);
- visibility.mockRestore();
+ expect(listQueueMediaJobs).toHaveBeenCalledTimes(2);
+ visibility.mockReturnValue('visible');
+ await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });
+ expect(listQueueMediaJobs).toHaveBeenCalledTimes(3);
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(4);
+
+ listQueueMediaJobs.mockResolvedValue([]);
+ await act(async () => { emitSocket('media-jobs:changed', {}); });
+ expect(screen.getByText('No training runs queued.')).toBeInTheDocument();
+ expect(listQueueMediaJobs).toHaveBeenCalledTimes(4);
+ unmount();
+ expect([...socketHandlers.values()].every(handlers => handlers.size === 0)).toBe(true);
});
});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index bf7a4b54d7..b357046540 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -141,6 +141,16 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
additionalProperties: false,
},
}),
+ 'media-jobs:changed': {
+ direction: 'server-to-client',
+ summary: 'Invalidate queue snapshots after job, progress, archive or hold changes.',
+ payloadSchema: { type: 'object', properties: {}, additionalProperties: false },
+ },
+ 'training:checkpoints:changed': {
+ direction: 'server-to-client',
+ summary: 'Training checkpoints or samples were persisted; reread this run.',
+ payloadSchema: { type: 'object', properties: { runId: { type: 'string' } }, required: ['runId'], additionalProperties: false },
+ },
'logs:subscribe': input(logsSubscribeSchema, 'Subscribe to a bounded process-log tail.'),
'logs:unsubscribe': input(logsUnsubscribeSchema, 'Release one process-log subscription or all legacy subscriptions.'),
'processes:changed': Object.freeze({
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 4d55c0f8b4..e53b16d759 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -736,7 +736,9 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
...(flushing.checkpoints ? { checkpoints: dedupeCheckpointsByStep([...current.artifacts.checkpoints, ...flushing.checkpoints]) } : {}),
...(flushing.samples ? { samples: [...new Set([...current.artifacts.samples, ...flushing.samples])] } : {}),
},
- })).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));
+ })).then(() => {
+ if (flushing.checkpoints || flushing.samples) trainingEvents.emit('checkpoints:changed', { runId });
+ }).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));
};
// Checkpoints/samples accumulate as arrays so two that land in one debounce
// window (common in the final post-exit scan) both survive — a single-value
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index dd5200a2f3..fd36f93fb4 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -460,8 +460,16 @@ let persistBlocked = false;
function persist() {
// Blocked: nothing is written, but callers awaiting durability (enqueueJob)
// must not inherit a stale rejection from a write that predates the latch.
- if (persistBlocked) return persistChain.catch(() => {});
- persistChain = persistChain.then(persistImpl, persistImpl);
+ if (persistBlocked) {
+ mediaJobEvents.emit('changed', {});
+ return persistChain.catch(() => {});
+ }
+ // Every queue mutation, including holds, deletion and debounced progress,
+ // converges here. Invalidate after the write settles so readers see the final
+ // in-memory state even when persistence is unavailable.
+ persistChain = persistChain.then(persistImpl, persistImpl).finally(() => {
+ mediaJobEvents.emit('changed', {});
+ });
return persistChain;
}
async function persistImpl() {
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index f9d5e88a74..7c4ce47828 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -209,6 +209,19 @@ afterEach(async () => {
});
describe('mediaJobQueue', () => {
+ it('invalidates snapshots after enqueue and cancellation so idle clients see changes', async () => {
+ const changed = vi.fn();
+ mediaJobQueue.mediaJobEvents.on('changed', changed);
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'example' } });
+ await flush();
+ expect(changed).toHaveBeenCalledWith({});
+ changed.mockClear();
+ await mediaJobQueue.cancelJob(jobId);
+ await flush();
+ expect(changed).toHaveBeenCalledWith({});
+ mediaJobQueue.mediaJobEvents.off('changed', changed);
+ });
+
it('enqueueJob returns jobId + queued status + position', async () => {
// Block the worker so the second enqueue lands behind the first in the
// pipeline rather than entering an empty queue after the first ran.
diff --git a/server/services/socket.js b/server/services/socket.js
index 4010619c92..33c64577c7 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -21,6 +21,7 @@ import { attachTailcatForwardsToPeers } from './tailcatPeer.js';
import { reviewEvents } from './review.js';
import { loopEvents } from './loops.js';
import { imageGenEvents } from './imageGenEvents.js';
+import { trainingEvents } from './loraTraining/events.js';
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { importerEvents, getImporterProgressFrames } from './importerEvents.js';
import { catalogEvents } from './catalogEvents.js';
@@ -758,6 +759,13 @@ function setupMediaGenEventForwarding() {
: kind === 'audio' ? 'audio-gen'
: null;
+ mediaJobEvents.on('changed', () => {
+ ioInstance?.emit('media-jobs:changed', {});
+ });
+ trainingEvents.on('checkpoints:changed', ({ runId }) => {
+ ioInstance?.emit('training:checkpoints:changed', { runId });
+ });
+
// Bridge media-job cancellation onto a `*-gen:canceled` socket event keyed by
// `generationId` (#1791). The internal gen modules emit started/progress/
// completed/failed but have NO 'canceled' — a job canceled *while queued*
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index e7a2050e32..13e8386080 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -1,5 +1,6 @@
import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './sharing/recordEvents.js';
import { fableLoomRunEvents } from './fableLoom/runEvents.js';
+import { trainingEvents } from './loraTraining/events.js';
import { authEvents } from './auth.js';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -412,6 +413,13 @@ describe('socket.js — initSocket', () => {
// media-job cancellation bridge (#1791): mediaJobEvents 'canceled' → a
// generationId-keyed *-gen:canceled broadcast so stuck render spinners clear.
// ===========================================================================
+ it('broadcasts bounded queue and checkpoint invalidations', () => {
+ mediaJobEvents.emit('changed', { privateRecord: 'must not be forwarded' });
+ trainingEvents.emit('checkpoints:changed', { runId: 'example-run', privateRecord: 'must not be forwarded' });
+ expect(io.emitted).toContainEqual(['media-jobs:changed', {}]);
+ expect(io.emitted).toContainEqual(['training:checkpoints:changed', { runId: 'example-run' }]);
+ });
+
it('bridges a canceled image job to image-gen:canceled keyed by generationId', () => {
mediaJobEvents.emit('canceled', { id: 'job-xyz', kind: 'image' });
expect(io.emitted).toContainEqual(['image-gen:canceled', { generationId: 'job-xyz' }]);