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
show live sample gallery while a LoRA trains, not just one thumbnail
[._.]/ Adam Eivy6712e9a6367f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b5887a4f23..c60ae2bc9e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Live LoRA training progress — watch the adapter learn, sample by sample** — A running training job used to show only a progress bar, a status line, and a single 32×32 thumbnail of the most recent preview. The active-run panel (`/media/training`) now renders a **live sample gallery**: a large current preview with its step label, a scrollable step-keyed thumbnail strip to scrub back through every earlier sample (so you can spot the moment a run starts to diverge), a **loss sparkline** that builds up over the session, and step / elapsed / **ETA** metrics. Samples merge two sources so a mid-run browser reload still shows the full timeline — a one-shot seed from a new `GET /api/lora-training/runs/:id/samples` endpoint (every preview persisted so far) plus the live SSE frames since re-subscribe. To drive the curve and key the thumbnails without re-parsing display strings, the trainer's STEP/SAMPLE line protocol now carries structured `loss` and `step` fields through the media-job SSE wire (additive — image/video gen frames are unaffected). (`server/services/loraTraining/progress.js`, `server/services/loraTraining/checkpoints.js`, `server/services/loraTraining/index.js`, `server/services/mediaJobQueue/index.js`, `server/routes/loraTraining.js`, `client/src/components/loraTraining/LiveSampleGallery.jsx`, `client/src/components/loraTraining/TrainingPanel.jsx`)+- **`/do:next` hot button on the app manage page** — The Agent Operations panel on an app's Overview tab gains a **`/do:next`** button alongside `/do:push`, `/do:review`, `/do:replan`, and the rest. One click queues a CoS agent that claims the next unclaimed `PLAN.md` item, works it in an isolated worktree, and ships a PR — the consumer counterpart to `/do:replan`. The bundled **slashdo** submodule was updated to the latest release (which ships the `do:next` command). (`lib/slashdo`, `client/src/components/apps/SlashDoPanel.jsx`, `server/routes/cosTaskRoutes.js`)- **Add canon characters / places / objects by hand** — Each canon section in the Universe editor (Cast, Places, Objects) now has an **Add** button next to "Pick from Catalog" — the same manual-add affordance the variation buckets already had. Click it, type a name (and optionally a description), and Save mints a new canon entry you can immediately render, refine, and fill in. The entry lands unlocked (so its inline editors are usable right away), dedupes case-insensitively against existing names, and persists through the same optimistic-append path as the catalog picker — so you no longer have to extract from prose, pick from the catalog, or promote a variation just to start a character. (`client/src/components/universe/UniverseCanonSection.jsx`)diff --git a/client/src/components/loraTraining/LiveSampleGallery.jsx b/client/src/components/loraTraining/LiveSampleGallery.jsxnew file mode 100644index 0000000000..1ed9b18dae--- /dev/null+++ b/client/src/components/loraTraining/LiveSampleGallery.jsx@@ -0,0 +1,196 @@+/**+ * Live sample gallery for an in-flight training run.+ *+ * The trainer renders a preview image every `sampleEvery` steps (SAMPLE lines+ * on the wire). This surfaces that evolution as it happens: a large current+ * preview, a step-keyed thumbnail strip to scrub back through earlier samples,+ * a loss sparkline, and step/ETA metrics — so you can watch the LoRA learn (and+ * catch a late divergence) instead of waiting for the run to finish.+ *+ * Samples merge two sources so a mid-run reload still shows the full timeline:+ * - a one-shot seed from GET /runs/:id/samples (every sample persisted so far)+ * - live SSE frames carrying { currentImage, step } (samples since subscribe)+ * Live wins on a duplicate step. The loss series is live-only (the run record+ * keeps just the last step), so it builds up over the session.+ */++import { useEffect, useMemo, useRef, useState } from 'react';+import { ImageOff, Radio } from 'lucide-react';+import { formatDurationMs } from '../../utils/formatters';+import { useTimeTick } from '../../hooks/useTimeTick';+import { listLoraTrainingSamples } from '../../services/api';++const SPARK_W = 240;+const SPARK_H = 36;++function LossSparkline({ series }) {+ if (series.length < 2) return null;+ const losses = series.map((p) => p.loss);+ const min = Math.min(...losses);+ const max = Math.max(...losses);+ const points = series+ .map((p, i) => {+ const x = (i / (series.length - 1)) * SPARK_W;+ const y = max === min ? SPARK_H / 2 : SPARK_H - ((p.loss - min) / (max - min)) * SPARK_H;+ return `${x.toFixed(1)},${y.toFixed(1)}`;+ })+ .join(' ');+ const last = series[series.length - 1].loss;+ return (+ <div>+ <div className="flex items-center justify-between text-[11px] text-gray-500 mb-0.5">+ <span>Loss</span>+ <span className="text-gray-400">{last.toFixed(4)}</span>+ </div>+ <svg+ viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}+ preserveAspectRatio="none"+ className="w-full h-9 bg-port-bg rounded border border-port-border"+ role="img"+ aria-label={`Training loss curve, latest ${last.toFixed(4)}`}+ >+ <polyline points={points} fill="none" stroke="#3b82f6" strokeWidth="1.5" vectorEffect="non-scaling-stroke" />+ </svg>+ </div>+ );+}++export default function LiveSampleGallery({ run, frames, progress, message }) {+ const [seed, setSeed] = useState([]);+ const [selectedStep, setSelectedStep] = useState(null);+ // Seconds-precision tick for the elapsed/ETA labels — shared, visibility-+ // aware timer (pauses when the tab is hidden) instead of a per-mount interval.+ const now = useTimeTick(1000);+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ // One-shot seed of every sample persisted so far (survives a mid-run reload).+ useEffect(() => {+ if (!run?.id) return;+ listLoraTrainingSamples(run.id)+ .then((res) => { if (mountedRef.current) setSeed(Array.isArray(res?.samples) ? res.samples : []); })+ .catch(() => {});+ }, [run?.id]);++ // Merge seed + live frames into a step-sorted, dedup'd sample list.+ const samples = useMemo(() => {+ const byStep = new Map();+ for (const s of seed) byStep.set(s.step, s.url);+ for (const f of frames) {+ if (typeof f.currentImage === 'string' && f.currentImage && typeof f.step === 'number') {+ byStep.set(f.step, f.currentImage);+ }+ }+ return [...byStep.entries()].map(([step, url]) => ({ step, url })).sort((a, b) => a.step - b.step);+ }, [seed, frames]);++ // Live loss series for the sparkline (progress frames carry numeric loss).+ const lossSeries = useMemo(() => {+ const out = [];+ for (const f of frames) {+ if (f.type === 'progress' && typeof f.loss === 'number' && typeof f.step === 'number') {+ out.push({ step: f.step, loss: f.loss });+ }+ }+ return out;+ }, [frames]);++ const latest = samples.length ? samples[samples.length - 1] : null;+ // `selectedStep == null` means "follow the latest sample"; a pinned step+ // shows that earlier sample until the user jumps back to live.+ const selected = (selectedStep != null && samples.find((s) => s.step === selectedStep)) || latest;++ const startedAt = run?.startedAt ? new Date(run.startedAt).getTime() : null;+ const elapsedMs = startedAt ? Math.max(0, now - startedAt) : null;+ const pct = typeof progress === 'number' ? Math.max(0, Math.min(1, progress)) : 0;+ const etaMs = elapsedMs != null && pct > 0.01 && pct < 1 ? (elapsedMs / pct) * (1 - pct) : null;++ return (+ <div className="space-y-2">+ <div className="flex flex-col sm:flex-row gap-3">+ {/* Current / selected preview */}+ <div className="sm:w-2/5 shrink-0">+ {selected ? (+ <div className="relative">+ <img+ src={selected.url}+ alt={`sample @ step ${selected.step}`}+ className="w-full aspect-square object-cover rounded border border-port-border"+ />+ <span className="absolute bottom-1 left-1 px-1.5 py-0.5 rounded bg-black/70 text-[11px] text-white">+ step {selected.step}+ </span>+ </div>+ ) : (+ <div className="w-full aspect-square rounded border border-port-border bg-port-bg flex flex-col items-center justify-center gap-1 text-gray-500">+ <ImageOff className="w-6 h-6" />+ <span className="text-[11px] text-center px-2">+ {(run?.params?.sampleEvery ?? 0) > 0+ ? `First preview renders at step ${run.params.sampleEvery}`+ : 'Sample previews disabled for this run'}+ </span>+ </div>+ )}+ </div>++ {/* Metrics + loss curve */}+ <div className="flex-1 min-w-0 space-y-2">+ <div className="text-xs text-gray-400 truncate">{message || 'Starting…'}</div>+ <div className="grid grid-cols-3 gap-2 text-center">+ <div className="bg-port-bg rounded border border-port-border py-1">+ <div className="text-sm text-white font-medium">{Math.round(pct * 100)}%</div>+ <div className="text-[10px] text-gray-500">progress</div>+ </div>+ <div className="bg-port-bg rounded border border-port-border py-1">+ <div className="text-sm text-white font-medium">{elapsedMs != null ? formatDurationMs(elapsedMs) : '—'}</div>+ <div className="text-[10px] text-gray-500">elapsed</div>+ </div>+ <div className="bg-port-bg rounded border border-port-border py-1">+ <div className="text-sm text-white font-medium">{etaMs != null ? `~${formatDurationMs(etaMs)}` : '—'}</div>+ <div className="text-[10px] text-gray-500">eta</div>+ </div>+ </div>+ <LossSparkline series={lossSeries} />+ </div>+ </div>++ {/* Thumbnail strip — scrub back through earlier samples */}+ {samples.length > 1 && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-[11px] text-gray-500">{samples.length} samples</span>+ {selectedStep != null && (+ <button+ type="button"+ onClick={() => setSelectedStep(null)}+ className="text-[11px] text-port-accent hover:underline flex items-center gap-1"+ >+ <Radio className="w-3 h-3" /> Jump to latest+ </button>+ )}+ </div>+ <div className="flex gap-1.5 overflow-x-auto pb-1">+ {samples.map((s) => {+ const active = selected && s.step === selected.step;+ return (+ <button+ key={s.step}+ type="button"+ onClick={() => setSelectedStep(selectedStep === s.step ? null : s.step)}+ title={`step ${s.step}`}+ className={`shrink-0 rounded border overflow-hidden ${active ? 'border-port-accent' : 'border-port-border'}`}+ >+ <img src={s.url} alt={`step ${s.step}`} className="w-14 h-14 object-cover" loading="lazy" />+ </button>+ );+ })}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsxindex 74db9c1f26..b89368ed27 100644--- a/client/src/components/loraTraining/TrainingPanel.jsx+++ b/client/src/components/loraTraining/TrainingPanel.jsx@@ -13,6 +13,7 @@ import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles } from 'luciimport toast from '../ui/Toast';import { useSseProgress } from '../../hooks/useSseProgress';import CheckpointPicker from './CheckpointPicker';+import LiveSampleGallery from './LiveSampleGallery';import {getLoraTrainingStatus,listLoraTrainingRuns,@@ -57,7 +58,7 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunuseEffect(() => { refreshRuns(); }, [refreshRuns]);const sseUrl = activeRun ? `/api/lora-training/runs/${activeRun.id}/events` : null;- const { latest, closed } = useSseProgress(sseUrl, { enabled: !!activeRun });+ const { frames, latest, closed } = useSseProgress(sseUrl, { enabled: !!activeRun });useEffect(() => {if (!closed || !activeRun) return;@@ -122,9 +123,10 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun<div className="h-2 bg-port-bg rounded overflow-hidden"><div className="h-full bg-port-accent transition-all" style={{ width: `${Math.round(progress * 100)}%` }} /></div>- <div className="text-xs text-gray-400">{latest?.message || (activeRun.status === 'queued' ? `Queued (position ${latest?.position ?? '…'})` : 'Starting…')}</div>- {latest?.currentImage && (- <img src={latest.currentImage} alt="training sample" className="w-32 h-32 object-cover rounded border border-port-border" />+ {activeRun.status === 'queued' ? (+ <div className="text-xs text-gray-400">Queued (position {latest?.position ?? '…'})</div>+ ) : (+ <LiveSampleGallery run={activeRun} frames={frames} progress={progress} message={latest?.message} />)}</div>);diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.jsindex b43942eb03..6ea86b1a42 100644--- a/client/src/services/apiLoraTraining.js+++ b/client/src/services/apiLoraTraining.js@@ -93,6 +93,11 @@ export const cancelLoraTrainingRun = (runId) =>export const listLoraTrainingCheckpoints = (runId) =>request(`/lora-training/runs/${runId}/checkpoints`);+// Mid-training sample timeline (step + thumbnail URL) — seeds the live+// progress gallery so a reload mid-run shows every sample rendered so far.+export const listLoraTrainingSamples = (runId) =>+ request(`/lora-training/runs/${runId}/samples`);+// Promote a checkpoint to be the deployed LoRA (re-extracts that step's// adapter and overwrites the run's registered .safetensors in place).export const promoteLoraTrainingCheckpoint = (runId, step, { silent = false } = {}) =>diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.jsindex 5254a08bc6..f34a481b8d 100644--- a/server/routes/loraTraining.js+++ b/server/routes/loraTraining.js@@ -22,6 +22,7 @@ import {isMfluxTrainAvailable,listCheckpoints,listRuns,+ listSamples,promoteCheckpoint,runDir,runSamplesDir,@@ -126,6 +127,15 @@ router.post('/runs/:id/promote-checkpoint', asyncHandler(async (req, res) => {res.json(await promoteCheckpoint(req.params.id, step));}));+// Mid-training sample timeline (step + thumbnail URL) — seeds the live+// progress gallery so a reload mid-run shows every sample so far, not just+// the ones streamed after re-subscribing. Registered before the+// `/samples/:filename` serve route (which needs the extra path segment).+router.get('/runs/:id/samples', asyncHandler(async (req, res) => {+ await getRunRequired(req.params.id); // 404 if the run is unknown+ res.json(await listSamples(req.params.id));+}));+router.get('/runs/:id/samples/:filename', asyncHandler(async (req, res) => {const run = await getRunRequired(req.params.id);assertSafeFilename(req.params.filename, { extensions: ['.png'], subject: 'sample filename' });diff --git a/server/services/loraTraining/checkpoints.js b/server/services/loraTraining/checkpoints.jsindex 7588749baa..fd0c9d932a 100644--- a/server/services/loraTraining/checkpoints.js+++ b/server/services/loraTraining/checkpoints.js@@ -121,6 +121,20 @@ export function listRunCheckpoints(run) {return checkpoints;}+/**+ * Every mid-training sample the run has recorded so far, as `{ step, url }`+ * sorted by step. Unlike listRunCheckpoints this is keyed off the SAMPLE+ * artifacts alone (samples are written on their own cadence, often denser than+ * checkpoints) — it seeds the live progress gallery so a mid-run reload shows+ * the full sample timeline, not just frames that arrived after re-subscribe.+ */+export function listRunSamples(run) {+ return (run.artifacts?.samples || [])+ .map((name) => ({ step: stepFromSampleName(name), url: sampleUrl(run.id, name) }))+ .filter((s) => s.step != null)+ .sort((a, b) => a.step - b.step);+}+/*** Decide whether a preview image is a degenerate collapse (near-black /* near-uniform). Conservative by design — only the catastrophic case. Adiff --git a/server/services/loraTraining/checkpoints.test.js b/server/services/loraTraining/checkpoints.test.jsindex d8310f3b4a..03f7411e57 100644--- a/server/services/loraTraining/checkpoints.test.js+++ b/server/services/loraTraining/checkpoints.test.js@@ -23,6 +23,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) =>const {listRunCheckpoints,+ listRunSamples,isPreviewCollapsed,resolveCheckpointAdapterBuffer,selectDeployableCheckpoint,@@ -118,6 +119,22 @@ describe('loraTraining/checkpoints', () => {expect(list[1].deployed).toBe(false);});+ it('lists samples as step+url sorted by step (seeds the live gallery)', () => {+ const samples = listRunSamples(buildRun());+ expect(samples.map((s) => s.step)).toEqual([250, 500]);+ expect(samples[0].url).toContain(`/runs/${RUN_ID}/samples/0000250_preview`);+ // flux2 naming + unparseable names: keep the parseable ones, sorted.+ const mixed = listRunSamples(buildRun({+ artifacts: { checkpoints: [], samples: ['step-000500.png', 'garbage.png', 'step-000250.png'] },+ }));+ expect(mixed.map((s) => s.step)).toEqual([250, 500]);+ });++ it('returns no samples when the run has none recorded', () => {+ expect(listRunSamples(buildRun({ artifacts: { checkpoints: [], samples: [] } }))).toEqual([]);+ expect(listRunSamples({ id: RUN_ID })).toEqual([]);+ });+it('joins preview by the filename-derived step even when the recorded step drifted', async () => {// mflux tags the CHECKPOINT line with the poll-time tqdm step, which can// lag the save boundary — here the record says 252/502 but the zip namesdiff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 957e091eda..adeb78d636 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -43,6 +43,7 @@ import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';import { validateDatasetReady } from './dataset.js';import {listRunCheckpoints,+ listRunSamples,resolveCheckpointAdapterBuffer,selectDeployableCheckpoint,} from './checkpoints.js';@@ -552,6 +553,12 @@ export async function listCheckpoints(runId) {return { runId, runtime: run.runtime, checkpoints: listRunCheckpoints(run) };}+/** Mid-training sample previews (step + url) for the live progress gallery. */+export async function listSamples(runId) {+ const run = await runsDb.getRunRequired(runId);+ return { runId, samples: listRunSamples(run) };+}+/*** Manually promote a checkpoint to be the deployed LoRA. Re-extracts that* checkpoint's adapter, registers it under the run's existing LoRA filenamediff --git a/server/services/loraTraining/progress.js b/server/services/loraTraining/progress.jsindex 21b1c51da3..08eb4fc8c3 100644--- a/server/services/loraTraining/progress.js+++ b/server/services/loraTraining/progress.js@@ -67,6 +67,9 @@ export function makeTrainingLineHandler({progress: Math.max(0, Math.min(1, cur / total)),step: cur,totalSteps: total,+ // Structured loss (null on nan) so the client plots a curve instead of+ // re-parsing it back out of the message string.+ loss: Number.isFinite(loss) ? loss : null,message: `Training step ${cur}/${total}${Number.isFinite(loss) ? ` · loss ${loss.toFixed(4)}` : ''}`,});return;@@ -83,11 +86,13 @@ export function makeTrainingLineHandler({const sample = line.match(/^SAMPLE:(.+):(\d+)$/);if (sample) {- onSample?.(sample[1], Number(sample[2]));+ const sampleStep = Number(sample[2]);+ onSample?.(sample[1], sampleStep);const url = sampleUrl ? sampleUrl(sample[1]) : null;if (url) {// currentImage without progress → dispatcher emits a 'preview' frame.- emit('progress', { generationId: jobId, currentImage: url, message: `Sample @ step ${sample[2]}` });+ // `step` rides along so the live gallery can key the thumbnail by step.+ emit('progress', { generationId: jobId, currentImage: url, step: sampleStep, message: `Sample @ step ${sampleStep}` });}return;}diff --git a/server/services/loraTraining/progress.test.js b/server/services/loraTraining/progress.test.jsindex f02463c80c..1a0f1dbf88 100644--- a/server/services/loraTraining/progress.test.js+++ b/server/services/loraTraining/progress.test.js@@ -25,15 +25,17 @@ describe('makeTrainingLineHandler', () => {expect(progress.progress).toBeCloseTo(0.25);expect(progress.step).toBe(250);expect(progress.totalSteps).toBe(1000);+ expect(progress.loss).toBeCloseTo(0.0812);expect(progress.message).toContain('250/1000');expect(progress.message).toContain('0.0812');});- it('handles nan loss without a loss suffix', () => {+ it('handles nan loss without a loss suffix (loss null)', () => {const { handleLine, emit } = setup();handleLine('STEP:5:100:nan');const progress = emit.mock.calls.find(([e]) => e === 'progress')[1];expect(progress.message).toBe('Training step 5/100');+ expect(progress.loss).toBeNull();});it('routes CHECKPOINT and SAMPLE lines to callbacks', () => {@@ -47,6 +49,7 @@ describe('makeTrainingLineHandler', () => {expect(onSample).toHaveBeenCalled();const preview = emit.mock.calls.find(([e, p]) => e === 'progress' && p.currentImage)[1];expect(preview.currentImage).toBe('/api/lora-training/runs/r1/samples/step-000250.png');+ expect(preview.step).toBe(250); // keys the live gallery thumbnail by stepexpect(preview.progress).toBeUndefined(); // preview frame, not a progress update});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 272bb92944..712178070b 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -512,10 +512,20 @@ function makeGenDispatcher(emitter, job, handlers) {const hasProgress = typeof e.progress === 'number' && Number.isFinite(e.progress);const hasCurrentImage = typeof e.currentImage === 'string' && e.currentImage.length > 0;const message = e.message !== undefined ? e.message : synthesizeMessage(e, job.kind);+ // Structured step/loss ride along on the wire when the emitter supplies+ // them (LoRA training does) so the client plots a loss curve and keys+ // sample thumbnails by step instead of re-parsing the message string.+ // Additive + presence-guarded — image/video gen omit them, unaffected.+ const addStepFields = (payload) => {+ if (typeof e.step === 'number') payload.step = e.step;+ if (typeof e.totalSteps === 'number') payload.totalSteps = e.totalSteps;+ if (typeof e.loss === 'number') payload.loss = e.loss;+ };if (hasProgress) {const payload = { type: 'progress', progress: e.progress };if (hasCurrentImage) payload.currentImage = e.currentImage;if (message !== undefined) payload.message = message;+ addStepFields(payload);handlers.progress(payload);return;}@@ -524,6 +534,7 @@ function makeGenDispatcher(emitter, job, handlers) {// existing consumers can keep their progress-bar value untouched.const payload = { type: 'preview', currentImage: e.currentImage };if (message !== undefined) payload.message = message;+ addStepFields(payload);handlers.progress(payload);}};