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
feat: character LoRA training — datasets, dual-runtime trainer, auto-apply
Adam Eivye1d0c47bd8cd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5b9e6f22ef..92aecd098b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,13 @@# Next Release+## Added++- **Character LoRA training — train consistent character adapters from your universe canon** — Create → Media Gen gains a **Training** tab (`/media/training`) that closes the loop from "character exists in a universe" to "every render of that character looks the same." Per character, a **dataset workbench** builds reference material three ways: batch-generate single-subject training renders from the character's canon descriptors (deterministic view/pose/expression/outfit variation matrix, queued through the normal image lane), upload your own images (normalized to PNG via sharp), or slice the character's existing reference-sheet turnaround into grid crops. A **vision-LLM captioner** (same provider pathway as the voice agent's visual describe) auto-captions every image prefixed with the character's trigger word, with per-image caption editing and re-captioning. Once ≥10 captioned images are ready, **train a LoRA locally** on either runtime: FLUX.1-dev via mflux's own MLX dreambooth CLI (wrapped by `scripts/train_mflux_lora.py`) or FLUX.2 Klein via a vendored diffusers+peft trainer (`scripts/train_flux2_lora.py` — bf16 bases only, precompute-then-free text/VAE encoding so the MPS memory peak stays survivable, gradient checkpointing, SIGTERM saves a cancel checkpoint). Training runs ride the media-job GPU lane (serialized with renders, SSE progress with per-step loss, mid-training sample previews, 30-min idle watchdog, cancel). The finished adapter lands in `data/loras/` with a sidecar carrying the character link + trigger word + size-variant compat key, so it appears in the existing LoRA library and picker with the right base-model gating immediately. **Auto-apply:** pipeline comic-page and storyboard renders that match a character with a trained LoRA automatically attach the adapter and weave its trigger word into the prompt (local mode; per-stage opt-out in Generation settings). Character cards in the universe editor and catalog detail pages show a trained-LoRA chip + dataset entry point; trained LoRAs in the library link back to their dataset. Datasets are machine-local (like the LoRA files themselves — never federated) and fully backed up; training checkpoints/caches are excluded as regenerable. Run records live in PostgreSQL (`lora_training_runs`). (`server/services/loraTraining/`, `server/services/loraDatasets.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraDatasetCaption.js`, `server/services/characterLoraResolver.js`, `client/src/pages/LoraTraining.jsx`, `client/src/pages/LoraDatasetDetail.jsx`)+## Changed- **[issue-1214] Staged upload images no longer pile up on disk** — init and reference images you upload for edit/image-to-image renders are now cleaned up automatically once they're a week old and no longer used by any saved image, so repeated edit-from-upload renders stop quietly growing your data folder.++## Fixed++- **`calendarSync` test no longer depends on the developer's machine state** — the "throws 401 when Google OAuth is not configured" test read the REAL Google credentials/tokens off disk, so on a machine with OAuth configured it failed with a `GaxiosError` (400 invalid_grant) instead of the pinned 401. The auth client is now mocked to the not-configured state. (`server/services/calendarSync.test.js`)diff --git a/client/src/App.jsx b/client/src/App.jsxindex d57bc1dcdd..fc8a7600c7 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -42,6 +42,8 @@ const MediaCollectionSyncView = lazyWithReload(() => import('./pages/MediaCollecconst SyncView = lazyWithReload(() => import('./pages/SyncView'));const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));const Loras = lazyWithReload(() => import('./pages/Loras'));+const LoraTraining = lazyWithReload(() => import('./pages/LoraTraining'));+const LoraDatasetDetail = lazyWithReload(() => import('./pages/LoraDatasetDetail'));const UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));const Universes = lazyWithReload(() => import('./pages/Universes'));const Catalog = lazyWithReload(() => import('./pages/Catalog'));@@ -259,6 +261,8 @@ export default function App() {<Route path="timeline/:projectId" element={<VideoTimelineEditor />} /><Route path="models" element={<MediaModels />} /><Route path="loras" element={<Loras />} />+ <Route path="training" element={<LoraTraining />} />+ <Route path="training/:datasetId" element={<LoraDatasetDetail />} />{/* Universes live at /universes (Create sidebar link). Theseredirects keep legacy /media/universe-builder bookmarks workingafter the MediaGen tab was removed. */}diff --git a/client/src/components/loraTraining/CharacterLoraChip.jsx b/client/src/components/loraTraining/CharacterLoraChip.jsxnew file mode 100644index 0000000000..c875d870bc--- /dev/null+++ b/client/src/components/loraTraining/CharacterLoraChip.jsx@@ -0,0 +1,84 @@+/**+ * "Trained LoRA" chip + dataset entry point for a universe/catalog+ * character. Resolves lazily via /api/loras/by-character ({ silent: true }+ * — no link is a normal state, not an error) and offers a Dataset button+ * that find-or-creates the character's dataset and navigates to it.+ */++import { useState, useEffect } from 'react';+import { useNavigate, Link } from 'react-router-dom';+import { Sparkles, GraduationCap, Loader2 } from 'lucide-react';+import { getCharacterLoras, createLoraDataset, listLoraDatasets } from '../../services/api';++export default function CharacterLoraChip({ entryId, ingredientId, universeId, showDatasetButton = true }) {+ const navigate = useNavigate();+ const [loras, setLoras] = useState(null);+ // Existing dataset (looked up by ingredientId) — the link target on+ // surfaces like the catalog detail page that don't know the universe+ // entryId and therefore can't find-or-create.+ const [existingDataset, setExistingDataset] = useState(null);+ const [opening, setOpening] = useState(false);++ useEffect(() => {+ if (!entryId && !ingredientId) return;+ getCharacterLoras({ entryId, ingredientId }, { silent: true })+ .then((list) => setLoras(Array.isArray(list) ? list : []))+ .catch(() => setLoras([]));+ }, [entryId, ingredientId]);++ const canCreate = !!(universeId && entryId);+ useEffect(() => {+ if (canCreate || (!entryId && !ingredientId)) return;+ listLoraDatasets(entryId ? { entryId } : { ingredientId })+ .then((list) => setExistingDataset(list?.[0] || null))+ .catch(() => {});+ }, [canCreate, entryId, ingredientId]);++ const openDataset = async () => {+ setOpening(true);+ try {+ const dataset = await createLoraDataset({ universeId, entryId });+ navigate(`/media/training/${dataset.id}`);+ } finally {+ setOpening(false);+ }+ };++ const lora = loras?.[0] || null;++ return (+ <div className="flex items-center gap-2 flex-wrap text-xs">+ {lora && (+ <Link+ to="/media/loras"+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-port-success/15 text-port-success border border-port-success/30 hover:bg-port-success/25"+ title={`Trained LoRA: ${lora.filename}${lora.triggerWords?.[0] ? ` · trigger: ${lora.triggerWords[0]}` : ''}`}+ >+ <Sparkles className="w-3 h-3" />+ LoRA{lora.triggerWords?.[0] ? ` · ${lora.triggerWords[0]}` : ''}+ </Link>+ )}+ {showDatasetButton && canCreate && (+ <button+ type="button"+ onClick={openDataset}+ disabled={opening}+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-port-card border border-port-border text-gray-400 hover:text-white disabled:opacity-50"+ title="Open the character's LoRA training dataset"+ >+ {opening ? <Loader2 className="w-3 h-3 animate-spin" /> : <GraduationCap className="w-3 h-3" />}+ {lora ? 'Dataset' : 'Train LoRA'}+ </button>+ )}+ {showDatasetButton && !canCreate && existingDataset && (+ <Link+ to={`/media/training/${existingDataset.id}`}+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-port-card border border-port-border text-gray-400 hover:text-white"+ title="Open the character's LoRA training dataset"+ >+ <GraduationCap className="w-3 h-3" /> Dataset+ </Link>+ )}+ </div>+ );+}diff --git a/client/src/components/loraTraining/DatasetImageGrid.jsx b/client/src/components/loraTraining/DatasetImageGrid.jsxnew file mode 100644index 0000000000..bf77d9b6ab--- /dev/null+++ b/client/src/components/loraTraining/DatasetImageGrid.jsx@@ -0,0 +1,150 @@+/**+ * Dataset image grid — caption editing, per-image re-caption, delete.+ * Captions blur-save; local state updates reactively (no list refetch).+ */++import { useState } from 'react';+import { Loader2, RefreshCw, AlertTriangle } from 'lucide-react';+import toast from '../ui/Toast';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';+import {+ updateLoraDatasetImageCaption,+ deleteLoraDatasetImage,+ startLoraCaptionRun,+} from '../../services/api';++const SOURCE_BADGE = {+ generated: { label: 'generated', cls: 'bg-port-accent/20 text-port-accent' },+ upload: { label: 'upload', cls: 'bg-emerald-600/20 text-emerald-300' },+ 'refsheet-slice': { label: 'sheet crop', cls: 'bg-purple-600/20 text-purple-300' },+};++export default function DatasetImageGrid({ dataset, onImagesChange, onCaptionRunStarted }) {+ const [drafts, setDrafts] = useState({});+ const [savingId, setSavingId] = useState(null);+ const [confirmingId, setConfirmingId] = useState(null);+ const [deletingId, setDeletingId] = useState(null);+ const [recaptioningId, setRecaptioningId] = useState(null);++ const saveCaption = async (img) => {+ const draft = drafts[img.id];+ if (draft === undefined || draft === img.caption) return;+ setSavingId(img.id);+ try {+ const updated = await updateLoraDatasetImageCaption(dataset.id, img.id, draft);+ onImagesChange((prev) => prev.map((i) => (i.id === img.id ? { ...i, ...updated } : i)));+ setDrafts((prev) => { const next = { ...prev }; delete next[img.id]; return next; });+ } finally {+ setSavingId(null);+ }+ };++ const removeImage = async (img) => {+ setDeletingId(img.id);+ try {+ await deleteLoraDatasetImage(dataset.id, img.id);+ onImagesChange((prev) => prev.filter((i) => i.id !== img.id));+ } finally {+ setDeletingId(null);+ setConfirmingId(null);+ }+ };++ const recaption = async (img) => {+ setRecaptioningId(img.id);+ try {+ const run = await startLoraCaptionRun(dataset.id, { imageIds: [img.id], overwrite: true });+ onCaptionRunStarted?.(run);+ toast.success('Re-captioning image…');+ } finally {+ setRecaptioningId(null);+ }+ };++ if (!dataset.images.length) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400 text-sm">+ No images yet — generate reference renders, upload your own, or slice the character's reference sheet.+ </div>+ );+ }++ return (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">+ {dataset.images.map((img) => {+ const badge = SOURCE_BADGE[img.source] || SOURCE_BADGE.upload;+ return (+ <div key={img.id} className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">+ <div className="relative aspect-square bg-port-bg">+ {img.status === 'rendering' ? (+ <div className="absolute inset-0 flex flex-col items-center justify-center text-gray-400 gap-2">+ <Loader2 className="w-6 h-6 animate-spin" />+ <span className="text-xs">rendering…</span>+ </div>+ ) : img.status === 'failed' ? (+ <div className="absolute inset-0 flex flex-col items-center justify-center text-port-error gap-2">+ <AlertTriangle className="w-6 h-6" />+ <span className="text-xs">render failed</span>+ </div>+ ) : (+ <img+ src={`/data/lora-datasets/${dataset.id}/images/${img.file}`}+ alt={img.caption || 'dataset image'}+ className="absolute inset-0 w-full h-full object-cover"+ loading="lazy"+ />+ )}+ <span className={`absolute top-2 left-2 text-[10px] px-1.5 py-0.5 rounded ${badge.cls}`}>{badge.label}</span>+ {img.variation?.view && (+ <span className="absolute top-2 right-2 text-[10px] px-1.5 py-0.5 rounded bg-black/60 text-gray-300">+ {img.variation.view}+ </span>+ )}+ </div>+ <div className="p-2 flex flex-col gap-2 flex-1">+ <textarea+ value={drafts[img.id] ?? img.caption}+ onChange={(e) => setDrafts((prev) => ({ ...prev, [img.id]: e.target.value }))}+ onBlur={() => saveCaption(img)}+ placeholder={img.status === 'ready' ? 'Caption (must include the trigger word)…' : ''}+ disabled={img.status !== 'ready'}+ rows={3}+ className="w-full bg-port-bg border border-port-border rounded p-2 text-xs text-gray-200 resize-y disabled:opacity-50"+ />+ <div className="flex items-center justify-between text-xs">+ <button+ type="button"+ onClick={() => recaption(img)}+ disabled={img.status !== 'ready' || recaptioningId === img.id}+ className="text-gray-400 hover:text-white flex items-center gap-1 disabled:opacity-50"+ title="Re-caption with the vision model"+ >+ {recaptioningId === img.id || savingId === img.id+ ? <Loader2 className="w-3.5 h-3.5 animate-spin" />+ : <RefreshCw className="w-3.5 h-3.5" />}+ Re-caption+ </button>+ {confirmingId === img.id ? (+ <ConfirmButtonPair+ prompt="Delete?"+ busy={deletingId === img.id}+ onConfirm={() => removeImage(img)}+ onCancel={() => setConfirmingId(null)}+ />+ ) : (+ <button+ type="button"+ onClick={() => setConfirmingId(img.id)}+ className="text-gray-500 hover:text-port-error"+ >+ Delete+ </button>+ )}+ </div>+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/loraTraining/GenerateBatchDialog.jsx b/client/src/components/loraTraining/GenerateBatchDialog.jsxnew file mode 100644index 0000000000..51816f1280--- /dev/null+++ b/client/src/components/loraTraining/GenerateBatchDialog.jsx@@ -0,0 +1,121 @@+/**+ * Generate-batch dialog — count + optional variation-axis overrides+ * (views/expressions/outfits prefilled from the character's canon when the+ * caller passes them). Submits to POST /api/lora-datasets/:id/generate.+ */++import { useState } from 'react';+import { Loader2, Wand2 } from 'lucide-react';+import toast from '../ui/Toast';+import Modal from '../ui/Modal';+import { generateLoraDatasetImages } from '../../services/api';++const ChipToggleList = ({ idPrefix, label, options, selected, onToggle }) => (+ <div>+ <span className="block text-sm text-gray-400 mb-1">{label}</span>+ <div className="flex flex-wrap gap-1.5">+ {options.map((opt, i) => {+ const on = selected.includes(opt);+ return (+ <button+ key={`${idPrefix}-${i}`}+ type="button"+ onClick={() => onToggle(opt)}+ className={`text-xs px-2 py-1 rounded-full border ${on+ ? 'bg-port-accent/20 border-port-accent/40 text-port-accent'+ : 'bg-port-bg border-port-border text-gray-400 hover:text-white'}`}+ >+ {opt}+ </button>+ );+ })}+ </div>+ </div>+);++export default function GenerateBatchDialog({ dataset, expressionOptions = [], outfitOptions = [], onClose, onStarted }) {+ const [count, setCount] = useState(12);+ const [expressions, setExpressions] = useState(expressionOptions);+ const [outfits, setOutfits] = useState(outfitOptions);+ const [submitting, setSubmitting] = useState(false);++ const toggle = (setter) => (value) =>+ setter((prev) => (prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value]));++ const submit = async () => {+ setSubmitting(true);+ try {+ const result = await generateLoraDatasetImages(dataset.id, {+ count,+ ...(expressions.length ? { expressions } : {}),+ ...(outfits.length ? { outfits } : {}),+ });+ toast.success(`Queued ${result.images.length} reference render${result.images.length === 1 ? '' : 's'} (${result.mode})`);+ onStarted(result);+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Modal+ open+ onClose={onClose}+ size="md"+ ariaLabelledBy="lt-generate-title"+ panelClassName="bg-port-card border border-port-border rounded-lg p-5"+ >+ <div className="space-y-4">+ <h2 id="lt-generate-title" className="text-base font-semibold text-white">+ Generate reference images — {dataset.character?.name}+ </h2>+ <p className="text-sm text-gray-400">+ Renders single-subject training images from the character's canon, varying view, pose,+ expression, and outfit. Renders queue on the image lane; results stream into the dataset.+ </p>+ <div>+ <label htmlFor="lt-gen-count" className="block text-sm text-gray-400 mb-1">Images ({count})</label>+ <input+ id="lt-gen-count"+ type="range"+ min={1}+ max={40}+ value={count}+ onChange={(e) => setCount(Number(e.target.value))}+ className="w-full"+ />+ </div>+ {expressionOptions.length > 0 && (+ <ChipToggleList+ idPrefix="lt-exp"+ label="Expressions"+ options={expressionOptions}+ selected={expressions}+ onToggle={toggle(setExpressions)}+ />+ )}+ {outfitOptions.length > 0 && (+ <ChipToggleList+ idPrefix="lt-outfit"+ label="Outfits"+ options={outfitOptions}+ selected={outfits}+ onToggle={toggle(setOutfits)}+ />+ )}+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onClose} className="px-3 py-2 text-sm text-gray-400 hover:text-white">Cancel</button>+ <button+ type="button"+ onClick={submit}+ disabled={submitting}+ className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"+ >+ {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />}+ Generate {count}+ </button>+ </div>+ </div>+ </Modal>+ );+}diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsxnew file mode 100644index 0000000000..e7658c5e82--- /dev/null+++ b/client/src/components/loraTraining/TrainingPanel.jsx@@ -0,0 +1,234 @@+/**+ * Training launch + live-run panel for a dataset.+ *+ * Launch gates on dataset readiness AND no in-flight trigger-word save+ * (the run reads the persisted trigger word, not the form). Live progress+ * streams over the run's media-job SSE; sample previews ride the 'preview'+ * frames. Completed runs surface the registered LoRA with a deep link.+ */++import { useState, useEffect, useMemo, useCallback } from 'react';+import { Link } from 'react-router-dom';+import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles } from 'lucide-react';+import toast from '../ui/Toast';+import { useSseProgress } from '../../hooks/useSseProgress';+import {+ getLoraTrainingStatus,+ listLoraTrainingRuns,+ startLoraTrainingRun,+ cancelLoraTrainingRun,+ listImageModels,+} from '../../services/api';++const isActive = (run) => run && ['queued', 'running'].includes(run.status);++export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunFinished }) {+ const [status, setStatus] = useState(null);+ const [models, setModels] = useState([]);+ const [baseModelId, setBaseModelId] = useState('');+ const [params, setParams] = useState(null);+ const [activeRun, setActiveRun] = useState(null);+ const [lastRun, setLastRun] = useState(null);+ const [starting, setStarting] = useState(false);+ const [canceling, setCanceling] = useState(false);++ useEffect(() => {+ getLoraTrainingStatus().then((s) => {+ setStatus(s);+ setParams((prev) => prev || { ...s.defaults });+ }).catch(() => setStatus({ runtimes: {}, defaults: {} }));+ listImageModels().then((list) => {+ const trainable = (Array.isArray(list) ? list : []).filter(+ (m) => m.id === 'dev' || m.runner === 'flux2',+ );+ setModels(trainable);+ setBaseModelId((prev) => prev || trainable[0]?.id || '');+ }).catch(() => setModels([]));+ }, []);++ const refreshRuns = useCallback(() => {+ listLoraTrainingRuns({ datasetId: dataset.id, limit: 5 }).then((runs) => {+ const active = runs.find(isActive) || null;+ setActiveRun(active);+ setLastRun(runs.find((r) => !isActive(r)) || null);+ }).catch(() => {});+ }, [dataset.id]);+ useEffect(() => { refreshRuns(); }, [refreshRuns]);++ const sseUrl = activeRun ? `/api/lora-training/runs/${activeRun.id}/events` : null;+ const { latest, closed } = useSseProgress(sseUrl, { enabled: !!activeRun });++ useEffect(() => {+ if (!closed || !activeRun) return;+ // Terminal frame (or stream loss) — re-read the run record for truth.+ refreshRuns();+ onRunFinished?.();+ }, [closed, activeRun, refreshRuns, onRunFinished]);++ const runtimeForModel = useMemo(() => {+ const model = models.find((m) => m.id === baseModelId);+ return model?.runner === 'flux2' ? 'flux2' : 'mflux';+ }, [models, baseModelId]);+ const runtimeReady = status?.runtimes?.[runtimeForModel]?.ready;++ const start = async () => {+ setStarting(true);+ try {+ await startLoraTrainingRun({ datasetId: dataset.id, baseModelId, params });+ toast.success('Training queued');+ refreshRuns();+ } finally {+ setStarting(false);+ }+ };++ const cancel = async () => {+ if (!activeRun) return;+ setCanceling(true);+ try {+ await cancelLoraTrainingRun(activeRun.id);+ toast.success('Cancel requested — the trainer saves a checkpoint first');+ } finally {+ setCanceling(false);+ }+ };++ const setParam = (key, value) => setParams((prev) => ({ ...prev, [key]: value }));++ const disabledReason = !readiness?.trainable+ ? `Needs ${readiness?.required ?? 10} captioned images (have ${readiness?.captioned ?? 0})`+ : triggerSaving ? 'Saving trigger word…'+ : !baseModelId ? 'Pick a base model'+ : runtimeReady === false ? `${runtimeForModel} environment not ready — run scripts/setup-image-video.sh`+ : null;++ if (activeRun) {+ const progress = typeof latest?.progress === 'number' ? latest.progress : (activeRun.progress?.step || 0) / (activeRun.progress?.totalSteps || 1);+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2 text-white font-medium">+ <Loader2 className="w-4 h-4 animate-spin text-port-warning" />+ Training {activeRun.runtime} · {activeRun.baseModelId}+ </div>+ <button+ type="button"+ onClick={cancel}+ disabled={canceling}+ className="px-2 py-1 text-xs rounded bg-port-error/20 text-port-error hover:bg-port-error/30 flex items-center gap-1 disabled:opacity-50"+ >+ <Square className="w-3 h-3" /> {canceling ? 'Canceling…' : 'Cancel'}+ </button>+ </div>+ <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" />+ )}+ </div>+ );+ }++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-center gap-2 text-white font-medium">+ <Dumbbell className="w-4 h-4 text-port-accent" /> Train LoRA+ </div>+ {lastRun && (+ <div className="text-xs flex items-center gap-1.5">+ {lastRun.status === 'completed' ? (+ <>+ <CheckCircle2 className="w-3.5 h-3.5 text-port-success" />+ <span className="text-gray-300">+ Last run completed+ {lastRun.output?.loraFilename && (+ <> — <Link to="/media/loras" className="text-port-accent hover:underline inline-flex items-center gap-1"><Sparkles className="w-3 h-3" />{lastRun.output.loraFilename}</Link></>+ )}+ </span>+ </>+ ) : (+ <>+ <XCircle className="w-3.5 h-3.5 text-port-error" />+ <span className="text-gray-400" title={lastRun.error || ''}>Last run {lastRun.status}{lastRun.error ? ` — ${lastRun.error.slice(0, 120)}` : ''}</span>+ </>+ )}+ </div>+ )}+ <div className="grid grid-cols-2 gap-3">+ <div className="col-span-2">+ <label htmlFor="lt-base-model" className="block text-xs text-gray-400 mb-1">Base model</label>+ <select+ id="lt-base-model"+ value={baseModelId}+ onChange={(e) => setBaseModelId(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ >+ {!models.length && <option value="">No trainable models registered</option>}+ {models.map((m) => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}+ </select>+ </div>+ {params && [+ ['steps', 'Steps', 10, 10000],+ ['rank', 'Rank', 1, 128],+ ['checkpointEvery', 'Checkpoint every', 0, 5000],+ ['sampleEvery', 'Sample every', 0, 5000],+ ].map(([key, label, min, max]) => (+ <div key={key}>+ <label htmlFor={`lt-param-${key}`} className="block text-xs text-gray-400 mb-1">{label}</label>+ <input+ id={`lt-param-${key}`}+ type="number"+ min={min}+ max={max}+ value={params[key] ?? ''}+ onChange={(e) => setParam(key, Number(e.target.value))}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ ))}+ {params && (+ <div>+ <label htmlFor="lt-param-resolution" className="block text-xs text-gray-400 mb-1">Resolution</label>+ <select+ id="lt-param-resolution"+ value={params.resolution ?? 512}+ onChange={(e) => setParam('resolution', Number(e.target.value))}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ >+ {[512, 768, 1024].map((r) => <option key={r} value={r}>{r}px</option>)}+ </select>+ </div>+ )}+ {params && (+ <div>+ <label htmlFor="lt-param-lr" className="block text-xs text-gray-400 mb-1">Learning rate</label>+ <input+ id="lt-param-lr"+ type="number"+ step="0.00001"+ min="0.000001"+ max="0.1"+ value={params.learningRate ?? ''}+ onChange={(e) => setParam('learningRate', Number(e.target.value))}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ )}+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs text-gray-500">{disabledReason || `Trains on ${readiness?.captioned ?? 0} captioned images`}</span>+ <button+ type="button"+ onClick={start}+ disabled={!!disabledReason || starting}+ className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"+ >+ {starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Dumbbell className="w-4 h-4" />}+ Train+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 3b47a9e285..bc0918a2e1 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -21,6 +21,7 @@ import EntryCard from '../universe/EntryCard';import EntryThumbSlot from '../universe/EntryThumbSlot';import CharacterDetailEditor from '../universe/CharacterDetailEditor';import CharacterReferenceSheetPanel from '../universe/CharacterReferenceSheetPanel';+import CharacterLoraChip from '../loraTraining/CharacterLoraChip';import { BIBLE_LIMITS } from '../../lib/bibleLimits';// Place metadata enums — kept in lock-step with `PLACE_INT_EXT` and@@ -403,6 +404,15 @@ export default function CanonCard({onSheetDeleted={characterExtensions.onSheetDeleted}onOpenLightbox={(filename) => onPreview?.(filename, { isSheet: true })}/>+ {/* Trained-LoRA link + dataset entry point (machine-local — the+ chip resolves from this machine's lora sidecars). */}+ <div className="mt-2">+ <CharacterLoraChip+ entryId={entry.id}+ ingredientId={entry.ingredientId || null}+ universeId={characterExtensions.universeId}+ />+ </div></CharacterDetailsToggle>) : null}</>diff --git a/client/src/components/pipeline/stages/VisualGenSettings.jsx b/client/src/components/pipeline/stages/VisualGenSettings.jsxindex 7b937196fd..afef1a0ee1 100644--- a/client/src/components/pipeline/stages/VisualGenSettings.jsx+++ b/client/src/components/pipeline/stages/VisualGenSettings.jsx@@ -28,6 +28,9 @@ const DEFAULT_CONFIG = Object.freeze({imageModelId: null,refineProvider: null,refineModel: null,+ // Trained character-LoRA auto-apply (local renders). Default on; the+ // server only honors an explicit false.+ applyCharacterLoras: true,});// "auto" is the default sentinel — the backend strip displays it as a@@ -122,6 +125,20 @@ function VisualGenSettingsBody({ cfg, update, stageLabel, systemSettings, imageM)}</div>+ <div>+ <label className="text-[10px] text-gray-500 inline-flex items-center gap-1.5">+ <input+ type="checkbox"+ checked={cfg.applyCharacterLoras !== false}+ onChange={(e) => update({ applyCharacterLoras: e.target.checked })}+ />+ Auto-apply trained character LoRAs+ </label>+ <p className="text-[10px] text-gray-500 mt-0.5 ml-5">+ Local renders attach a matched character's trained LoRA + trigger word automatically (codex has no LoRA support).+ </p>+ </div>+{cfg.imageMode === IMAGE_GEN_MODE.LOCAL && (<div><div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">@@ -310,6 +327,8 @@ export function genConfigToImageOptions(cfg) {const out = {};if (cfg.imageMode && cfg.imageMode !== 'auto') out.mode = cfg.imageMode;if (cfg.imageMode === IMAGE_GEN_MODE.LOCAL && cfg.imageModelId) out.modelId = cfg.imageModelId;+ // Server default is ON — only the explicit opt-out travels.+ if (cfg.applyCharacterLoras === false) out.applyCharacterLoras = false;return out;}diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex 6cba4d16e8..39f1c45f2b 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -26,6 +26,7 @@ import {import { listImageGallery } from '../services/apiImageVideo';import IngredientPicker from '../components/IngredientPicker';import MediaImage from '../components/MediaImage';+import CharacterLoraChip from '../components/loraTraining/CharacterLoraChip';import TagPicker from '../components/TagPicker';import GenericIngredientFields from '../components/GenericIngredientFields';import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';@@ -391,7 +392,17 @@ export default function CatalogIngredient() {</div>{record.type === 'character' && (- <ReferenceSheetPanel payload={payload} universeRef={universeRef} />+ <>+ <ReferenceSheetPanel payload={payload} universeRef={universeRef} />+ {/* Trained-LoRA link + dataset entry point. The catalog id IS the+ ingredientId the trained sidecars carry; the universe entryId+ isn't known on this surface, so the chip links an existing+ dataset rather than offering find-or-create. */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="text-xs uppercase tracking-wider text-gray-500 mb-2">Character LoRA</div>+ <CharacterLoraChip ingredientId={record.id} />+ </div>+ </>)}<div className="grid grid-cols-1 md:grid-cols-2 gap-4">diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsxnew file mode 100644index 0000000000..a218e5dbdb--- /dev/null+++ b/client/src/pages/LoraDatasetDetail.jsx@@ -0,0 +1,330 @@+/**+ * LoRA dataset workbench (/media/training/:datasetId).+ *+ * Build reference material for one character (generate via the image+ * queue, upload, slice the reference-sheet turnaround), caption it with+ * the vision model, then launch a training run. The dataset record is the+ * single source of truth; rendering images poll-refresh until they land.+ */++import { useState, useEffect, useMemo, useRef, useCallback } from 'react';+import { useParams, Link } from 'react-router-dom';+import {+ ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, AlertTriangle,+} from 'lucide-react';+import toast from '../components/ui/Toast';+import Modal from '../components/ui/Modal';+import { useSseProgress } from '../hooks/useSseProgress';+import DatasetImageGrid from '../components/loraTraining/DatasetImageGrid';+import GenerateBatchDialog from '../components/loraTraining/GenerateBatchDialog';+import TrainingPanel from '../components/loraTraining/TrainingPanel';+import {+ getLoraDataset,+ patchLoraDataset,+ uploadLoraDatasetImages,+ sliceLoraDatasetRefSheet,+ startLoraCaptionRun,+ getUniverse,+} from '../services/api';++const TRIGGER_RE = /^[a-z0-9_]{2,64}$/;++function SliceDialog({ dataset, onClose, onSliced }) {+ const [cols, setCols] = useState(3);+ const [rows, setRows] = useState(2);+ const [submitting, setSubmitting] = useState(false);++ const submit = async () => {+ setSubmitting(true);+ try {+ const result = await sliceLoraDatasetRefSheet(dataset.id, { cols, rows });+ toast.success(`Added ${result.images.length} crops from the reference sheet — prune any bad ones`);+ onSliced(result);+ } finally {+ setSubmitting(false);+ }+ };++ const numberInput = (id, label, value, set) => (+ <div>+ <label htmlFor={id} className="block text-xs text-gray-400 mb-1">{label}</label>+ <input+ id={id}+ type="number"+ min={1}+ max={6}+ value={value}+ onChange={(e) => set(Math.max(1, Math.min(6, Number(e.target.value) || 1)))}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </div>+ );++ return (+ <Modal+ open+ onClose={onClose}+ size="sm"+ ariaLabelledBy="lt-slice-title"+ panelClassName="bg-port-card border border-port-border rounded-lg p-5"+ >+ <div className="space-y-4">+ <h2 id="lt-slice-title" className="text-base font-semibold text-white">Slice reference sheet</h2>+ <p className="text-sm text-gray-400">+ Cuts the character's reference-sheet turnaround into a fixed grid of training crops.+ Sheet layouts vary, so expect to delete cells that caught labels or palette swatches.+ </p>+ <div className="grid grid-cols-2 gap-3">+ {numberInput('lt-slice-cols', 'Columns', cols, setCols)}+ {numberInput('lt-slice-rows', 'Rows', rows, setRows)}+ </div>+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onClose} className="px-3 py-2 text-sm text-gray-400 hover:text-white">Cancel</button>+ <button+ type="button"+ onClick={submit}+ disabled={submitting}+ className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"+ >+ {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Scissors className="w-4 h-4" />}+ Slice {cols}×{rows}+ </button>+ </div>+ </div>+ </Modal>+ );+}++export default function LoraDatasetDetail() {+ const { datasetId } = useParams();+ const [dataset, setDataset] = useState(null);+ const [loadError, setLoadError] = useState(null);+ const [character, setCharacter] = useState(null);+ const [triggerDraft, setTriggerDraft] = useState(null);+ const [triggerSaving, setTriggerSaving] = useState(false);+ const [uploading, setUploading] = useState(false);+ const [showGenerate, setShowGenerate] = useState(false);+ const [showSlice, setShowSlice] = useState(false);+ const [captionRun, setCaptionRun] = useState(null);+ const [captionStarting, setCaptionStarting] = useState(false);+ const fileInputRef = useRef(null);++ const refresh = useCallback(() => getLoraDataset(datasetId)+ .then((d) => { setDataset(d); return d; })+ .catch((err) => { setLoadError(err?.message || 'Dataset not found'); return null; }), [datasetId]);++ useEffect(() => { refresh(); }, [refresh]);++ // Pull the live canon character once for variation-axis options + sheet link.+ useEffect(() => {+ if (!dataset?.character?.universeId) return;+ getUniverse(dataset.character.universeId, { silent: true })+ .then((u) => setCharacter((u?.characters || []).find((c) => c.id === dataset.character.entryId) || null))+ .catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dataset?.character?.universeId, dataset?.character?.entryId]);++ // Poll while any image renders — the server heals stuck images on read.+ const renderingCount = dataset?.readiness?.rendering || 0;+ useEffect(() => {+ if (!renderingCount) return undefined;+ const timer = setInterval(refresh, 5000);+ return () => clearInterval(timer);+ }, [renderingCount, refresh]);++ // Caption-run SSE — refetch on terminal so captions land in the grid.+ const captionSseUrl = captionRun ? `/api/lora-datasets/${datasetId}/caption-runs/${captionRun.runId}/events` : null;+ const captionSse = useSseProgress(captionSseUrl, { enabled: !!captionRun });+ useEffect(() => {+ if (captionRun && captionSse.closed) {+ setCaptionRun(null);+ refresh();+ }+ }, [captionRun, captionSse.closed, refresh]);++ const onImagesChange = (mutate) => setDataset((prev) => (prev ? { ...prev, images: mutate(prev.images) } : prev));++ const saveTriggerWord = async () => {+ if (triggerDraft === null || triggerDraft === dataset.triggerWord) { setTriggerDraft(null); return; }+ if (!TRIGGER_RE.test(triggerDraft)) {+ toast.error('Trigger word must be 2-64 chars of a-z, 0-9, _');+ return;+ }+ setTriggerSaving(true);+ try {+ const next = await patchLoraDataset(datasetId, { triggerWord: triggerDraft });+ setDataset(next);+ setTriggerDraft(null);+ toast.success('Trigger word saved — re-caption images so captions carry the new token');+ } finally {+ setTriggerSaving(false);+ }+ };++ const onUpload = async (e) => {+ const files = e.target.files;+ if (!files?.length) return;+ setUploading(true);+ try {+ const { images } = await uploadLoraDatasetImages(datasetId, files);+ onImagesChange((prev) => [...prev, ...images]);+ refresh();+ toast.success(`Added ${images.length} image${images.length === 1 ? '' : 's'}`);+ } finally {+ setUploading(false);+ e.target.value = '';+ }+ };++ const captionAll = async () => {+ setCaptionStarting(true);+ try {+ const run = await startLoraCaptionRun(datasetId, { overwrite: false });+ setCaptionRun(run);+ } finally {+ setCaptionStarting(false);+ }+ };++ const expressionOptions = useMemo(+ () => (character?.expressions || []).map((e) => e?.name).filter(Boolean),+ [character],+ );+ const outfitOptions = useMemo(+ () => (character?.wardrobes || []).map((w) => w?.name).filter(Boolean),+ [character],+ );+ const hasReferenceSheet = !!(character?.referenceSheetImageRef+ || Object.values(character?.referenceSheets || {}).some(Boolean));++ if (loadError) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-400">+ <AlertTriangle className="w-6 h-6 mx-auto mb-2 text-port-error" />+ {loadError} — <Link to="/media/training" className="text-port-accent hover:underline">back to datasets</Link>+ </div>+ );+ }+ if (!dataset) {+ return <div className="text-gray-400 flex items-center gap-2"><Loader2 className="w-4 h-4 animate-spin" /> Loading dataset…</div>;+ }++ const readiness = dataset.readiness || {};++ return (+ <div className="space-y-4">+ <div className="flex items-start justify-between gap-3 flex-wrap">+ <div className="min-w-0">+ <Link to="/media/training" className="text-xs text-gray-400 hover:text-white flex items-center gap-1 mb-1">+ <ArrowLeft className="w-3 h-3" /> Datasets+ </Link>+ <h2 className="text-lg font-semibold text-white truncate">+ <Link+ to={`/universes/${dataset.character.universeId}`}+ className="hover:text-port-accent"+ title="Open in universe editor"+ >+ {dataset.character.name}+ </Link>+ </h2>+ <div className="flex items-center gap-2 mt-1">+ <label htmlFor="lt-trigger" className="text-xs text-gray-500">Trigger word</label>+ <input+ id="lt-trigger"+ value={triggerDraft ?? dataset.triggerWord}+ onChange={(e) => setTriggerDraft(e.target.value)}+ onBlur={saveTriggerWord}+ disabled={triggerSaving}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs font-mono text-white w-56 disabled:opacity-50"+ />+ {triggerSaving && <Loader2 className="w-3 h-3 animate-spin text-gray-400" />}+ </div>+ </div>+ <div className="text-right text-sm">+ <div className={readiness.trainable ? 'text-port-success' : 'text-gray-400'}>+ {readiness.ready ?? 0} images · {readiness.captioned ?? 0}/{readiness.required ?? 10} captioned+ {renderingCount ? ` · ${renderingCount} rendering` : ''}+ </div>+ <div className="text-xs text-gray-500">{readiness.trainable ? 'Ready to train' : 'Add + caption more images to train'}</div>+ </div>+ </div>++ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={() => setShowGenerate(true)}+ className="px-3 py-2 text-sm rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 flex items-center gap-2"+ >+ <Wand2 className="w-4 h-4" /> Generate+ </button>+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={uploading}+ className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50"+ >+ {uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />} Upload+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ multiple+ className="hidden"+ onChange={onUpload}+ />+ <button+ type="button"+ onClick={() => setShowSlice(true)}+ disabled={!hasReferenceSheet}+ title={hasReferenceSheet ? '' : 'Render a reference sheet in the universe editor first'}+ className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50"+ >+ <Scissors className="w-4 h-4" /> Slice sheet+ </button>+ <button+ type="button"+ onClick={captionAll}+ disabled={captionStarting || !!captionRun}+ className="px-3 py-2 text-sm rounded bg-port-card border border-port-border text-gray-300 hover:text-white flex items-center gap-2 disabled:opacity-50"+ >+ {captionStarting || captionRun ? <Loader2 className="w-4 h-4 animate-spin" /> : <Tags className="w-4 h-4" />}+ {captionRun+ ? `Captioning ${captionSse.latest?.done ?? 0}/${captionSse.latest?.total ?? '…'}`+ : 'Caption all'}+ </button>+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-4 items-start">+ <DatasetImageGrid+ dataset={dataset}+ onImagesChange={onImagesChange}+ onCaptionRunStarted={setCaptionRun}+ />+ <TrainingPanel+ dataset={dataset}+ readiness={readiness}+ triggerSaving={triggerSaving}+ onRunFinished={refresh}+ />+ </div>++ {showGenerate && (+ <GenerateBatchDialog+ dataset={dataset}+ expressionOptions={expressionOptions}+ outfitOptions={outfitOptions}+ onClose={() => setShowGenerate(false)}+ onStarted={() => { setShowGenerate(false); refresh(); }}+ />+ )}+ {showSlice && (+ <SliceDialog+ dataset={dataset}+ onClose={() => setShowSlice(false)}+ onSliced={() => { setShowSlice(false); refresh(); }}+ />+ )}+ </div>+ );+}diff --git a/client/src/pages/LoraTraining.jsx b/client/src/pages/LoraTraining.jsxnew file mode 100644index 0000000000..336f4e3865--- /dev/null+++ b/client/src/pages/LoraTraining.jsx@@ -0,0 +1,224 @@+/**+ * LoRA Training — dataset list (/media/training).+ *+ * One dataset per universe character. Cards show the character, a thumb+ * strip, image/caption counts, and training status; "New dataset" walks+ * universe → character and lands on the dataset workbench.+ */++import { useState, useEffect, useCallback } from 'react';+import { Link, useNavigate } from 'react-router-dom';+import { GraduationCap, Plus, Loader2, Sparkles, Images } from 'lucide-react';+import toast from '../components/ui/Toast';+import Modal from '../components/ui/Modal';+import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';+import {+ listLoraDatasets,+ createLoraDataset,+ deleteLoraDataset,+ listUniverses,+ getUniverse,+} from '../services/api';++const STATUS_CHIP = {+ draft: 'bg-port-border/40 text-gray-300',+ training: 'bg-port-warning/20 text-port-warning',+ trained: 'bg-port-success/20 text-port-success',+};++function NewDatasetDialog({ onClose, onCreated }) {+ const [universes, setUniverses] = useState(null);+ const [universeId, setUniverseId] = useState('');+ const [characters, setCharacters] = useState(null);+ const [entryId, setEntryId] = useState('');+ const [creating, setCreating] = useState(false);++ useEffect(() => {+ listUniverses().then((list) => setUniverses(Array.isArray(list) ? list : []))+ .catch(() => setUniverses([]));+ }, []);++ useEffect(() => {+ if (!universeId) { setCharacters(null); setEntryId(''); return; }+ setCharacters(null);+ getUniverse(universeId)+ .then((u) => setCharacters(Array.isArray(u?.characters) ? u.characters : []))+ .catch(() => setCharacters([]));+ }, [universeId]);++ const create = async () => {+ setCreating(true);+ try {+ const dataset = await createLoraDataset({ universeId, entryId });+ onCreated(dataset);+ } finally {+ setCreating(false);+ }+ };++ return (+ <Modal+ open+ onClose={onClose}+ size="sm"+ ariaLabelledBy="lt-new-dataset-title"+ panelClassName="bg-port-card border border-port-border rounded-lg p-5"+ >+ <div className="space-y-4">+ <h2 id="lt-new-dataset-title" className="text-base font-semibold text-white">New training dataset</h2>+ <div>+ <label htmlFor="lt-universe" className="block text-sm text-gray-400 mb-1">Universe</label>+ <select+ id="lt-universe"+ value={universeId}+ onChange={(e) => setUniverseId(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white"+ >+ <option value="">{universes === null ? 'Loading…' : 'Pick a universe'}</option>+ {(universes || []).map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}+ </select>+ </div>+ {universeId && (+ <div>+ <label htmlFor="lt-character" className="block text-sm text-gray-400 mb-1">Character</label>+ <select+ id="lt-character"+ value={entryId}+ onChange={(e) => setEntryId(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white"+ >+ <option value="">{characters === null ? 'Loading…' : characters.length ? 'Pick a character' : 'No characters in this universe'}</option>+ {(characters || []).map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}+ </select>+ </div>+ )}+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onClose} className="px-3 py-2 text-sm text-gray-400 hover:text-white">Cancel</button>+ <button+ type="button"+ onClick={create}+ disabled={!universeId || !entryId || creating}+ className="px-3 py-2 text-sm rounded bg-port-accent text-white disabled:opacity-50 flex items-center gap-2"+ >+ {creating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}+ Open dataset+ </button>+ </div>+ </div>+ </Modal>+ );+}++export default function LoraTraining() {+ const navigate = useNavigate();+ const [datasets, setDatasets] = useState(null);+ const [showNew, setShowNew] = useState(false);+ const [deletingId, setDeletingId] = useState(null);+ const [confirmingId, setConfirmingId] = useState(null);++ const refresh = useCallback(() => {+ listLoraDatasets().then(setDatasets).catch(() => setDatasets([]));+ }, []);+ useEffect(() => { refresh(); }, [refresh]);++ const onDelete = async (id) => {+ setDeletingId(id);+ try {+ await deleteLoraDataset(id);+ setDatasets((prev) => (prev || []).filter((d) => d.id !== id));+ toast.success('Dataset deleted');+ } finally {+ setDeletingId(null);+ setConfirmingId(null);+ }+ };++ return (+ <div>+ <div className="flex items-center justify-between mb-4 flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <GraduationCap className="w-5 h-5 text-port-accent" />+ <h2 className="text-lg font-semibold text-white">Character LoRA Training</h2>+ </div>+ <button+ type="button"+ onClick={() => setShowNew(true)}+ className="px-3 py-2 text-sm rounded bg-port-accent text-white flex items-center gap-2"+ >+ <Plus className="w-4 h-4" /> New dataset+ </button>+ </div>++ {datasets === null && (+ <div className="text-gray-400 flex items-center gap-2"><Loader2 className="w-4 h-4 animate-spin" /> Loading datasets…</div>+ )}++ {datasets?.length === 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400">+ <Sparkles className="w-8 h-8 mx-auto mb-3 text-port-accent" />+ <p className="mb-1 text-white">Train a LoRA for consistent character renders.</p>+ <p className="text-sm">Pick a universe character, build reference material (generated renders, uploads, reference-sheet crops), caption it, and train a FLUX.1 or FLUX.2 adapter.</p>+ </div>+ )}++ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">+ {(datasets || []).map((d) => (+ <div key={d.id} className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-3">+ <div className="flex items-start justify-between gap-2">+ <Link to={`/media/training/${d.id}`} className="min-w-0">+ <div className="text-white font-medium truncate">{d.character?.name || 'Unnamed'}</div>+ <div className="text-xs text-gray-500 font-mono truncate">{d.triggerWord}</div>+ </Link>+ <span className={`text-xs px-2 py-0.5 rounded-full shrink-0 ${STATUS_CHIP[d.status] || STATUS_CHIP.draft}`}>+ {d.status}+ </span>+ </div>+ {d.thumbnails?.length > 0 && (+ <Link to={`/media/training/${d.id}`} className="flex gap-1 overflow-hidden">+ {d.thumbnails.map((file) => (+ <img+ key={file}+ src={`/data/lora-datasets/${d.id}/images/${file}`}+ alt=""+ className="w-16 h-16 object-cover rounded border border-port-border"+ loading="lazy"+ />+ ))}+ </Link>+ )}+ <div className="flex items-center justify-between text-xs text-gray-400">+ <span className="flex items-center gap-1">+ <Images className="w-3.5 h-3.5" />+ {d.readiness?.ready ?? 0} images · {d.readiness?.captioned ?? 0} captioned+ {d.readiness?.rendering ? ` · ${d.readiness.rendering} rendering` : ''}+ </span>+ {confirmingId === d.id ? (+ <ConfirmButtonPair+ prompt="Delete?"+ busy={deletingId === d.id}+ onConfirm={() => onDelete(d.id)}+ onCancel={() => setConfirmingId(null)}+ />+ ) : (+ <button+ type="button"+ onClick={() => setConfirmingId(d.id)}+ className="text-gray-500 hover:text-port-error"+ >+ Delete+ </button>+ )}+ </div>+ </div>+ ))}+ </div>++ {showNew && (+ <NewDatasetDialog+ onClose={() => setShowNew(false)}+ onCreated={(dataset) => navigate(`/media/training/${dataset.id}`)}+ />+ )}+ </div>+ );+}diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsxindex 2ee1ac970f..9bce9cb78c 100644--- a/client/src/pages/Loras.jsx+++ b/client/src/pages/Loras.jsx@@ -710,6 +710,20 @@ function LoraCard({ lora, onDelete, deleting }) {</span></div>+ {/* Trained-in-PortOS lineage: character chip links back to the+ training dataset that produced this adapter. */}+ {lora.source === 'trained' && lora.character && (+ <div className="mb-2">+ <Link+ to={lora.trainedFromDatasetId ? `/media/training/${lora.trainedFromDatasetId}` : '/media/training'}+ className="inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-port-success/15 text-port-success border border-port-success/30 hover:bg-port-success/25"+ title="Trained in PortOS — open the training dataset"+ >+ <Sparkles size={11} /> Character: {lora.character.name}+ </Link>+ </div>+ )}+{triggerWords.length > 0 && (<div className="mb-2"><div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">Trigger words</div>diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsxindex 3e9e3f8d81..5c5c1272df 100644--- a/client/src/pages/MediaGen.jsx+++ b/client/src/pages/MediaGen.jsx@@ -1,5 +1,5 @@import { useNavigate, useLocation, Outlet } from 'react-router-dom';-import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, Sparkles } from 'lucide-react';+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen, Clapperboard, Sparkles, GraduationCap } from 'lucide-react';import TabPills from '../components/ui/TabPills';const TABS = [@@ -10,6 +10,7 @@ const TABS = [{ id: 'history', label: 'History', icon: History },{ id: 'collections', label: 'Collections', icon: FolderOpen },{ id: 'loras', label: 'LoRAs', icon: Sparkles },+ { id: 'training', label: 'Training', icon: GraduationCap },{ id: 'models', label: 'Models', icon: HardDrive }];diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 57f4b505b9..e1efa6531e 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -80,6 +80,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| File | Purpose ||---|---|| `apiImageVideo.js` | Image-gen local backend extras (gallery, models, LoRAs, cancel, delete). |+| `apiLoraTraining.js` | Character LoRA training — datasets (CRUD, upload, generate, slice, caption), training runs (start/list/cancel/delete + status), character→LoRA link lookup. || `apiMedia.js` | Screenshots + media assets. || `apiMediaJobs.js` | Media generation job tracking. || `apiCreativeDirector.js` | Creative Director (video production). |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex b826856fb9..43db3f4500 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -41,6 +41,7 @@ export * from './apiPalette.js';export * from './apiDashboard.js';export * from './apiAsk.js';export * from './apiImageVideo.js';+export * from './apiLoraTraining.js';export * from './apiMediaJobs.js';export * from './apiWritersRoom.js';export * from './apiUniverseBuilder.js';diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.jsnew file mode 100644index 0000000000..a0d98e60d2--- /dev/null+++ b/client/src/services/apiLoraTraining.js@@ -0,0 +1,95 @@+/**+ * Character LoRA training API — datasets (/api/lora-datasets), training+ * runs (/api/lora-training), and the character→LoRA link lookup+ * (/api/loras/by-character).+ */++import { request } from './apiCore.js';++// ---- Datasets ----++export const listLoraDatasets = (filters = {}) => {+ const params = new URLSearchParams();+ for (const key of ['universeId', 'entryId', 'ingredientId']) {+ if (filters[key]) params.set(key, filters[key]);+ }+ const qs = params.toString();+ return request(`/lora-datasets${qs ? `?${qs}` : ''}`);+};++export const createLoraDataset = ({ universeId, entryId, triggerWord }, { silent = false } = {}) =>+ request('/lora-datasets', {+ method: 'POST',+ body: JSON.stringify({ universeId, entryId, ...(triggerWord ? { triggerWord } : {}) }),+ silent,+ });++export const getLoraDataset = (id) => request(`/lora-datasets/${id}`);++export const patchLoraDataset = (id, patch) =>+ request(`/lora-datasets/${id}`, { method: 'PATCH', body: JSON.stringify(patch) });++export const deleteLoraDataset = (id) => request(`/lora-datasets/${id}`, { method: 'DELETE' });++// `files` is a FileList/array — field names image1…image10 per the route.+export const uploadLoraDatasetImages = (id, files) => {+ const form = new FormData();+ [...files].slice(0, 10).forEach((file, i) => form.append(`image${i + 1}`, file));+ return request(`/lora-datasets/${id}/images`, { method: 'POST', body: form });+};++export const generateLoraDatasetImages = (id, options = {}) =>+ request(`/lora-datasets/${id}/generate`, { method: 'POST', body: JSON.stringify(options) });++export const sliceLoraDatasetRefSheet = (id, { variant, cols, rows } = {}) =>+ request(`/lora-datasets/${id}/slice-reference-sheet`, {+ method: 'POST',+ body: JSON.stringify({ ...(variant ? { variant } : {}), ...(cols ? { cols } : {}), ...(rows ? { rows } : {}) }),+ });++export const startLoraCaptionRun = (id, options = {}) =>+ request(`/lora-datasets/${id}/caption`, { method: 'POST', body: JSON.stringify(options) });++export const updateLoraDatasetImageCaption = (id, imageId, caption) =>+ request(`/lora-datasets/${id}/images/${imageId}`, {+ method: 'PATCH', body: JSON.stringify({ caption }),+ });++export const deleteLoraDatasetImage = (id, imageId) =>+ request(`/lora-datasets/${id}/images/${imageId}`, { method: 'DELETE' });++// ---- Training runs ----++export const getLoraTrainingStatus = () => request('/lora-training/status');++export const startLoraTrainingRun = ({ datasetId, baseModelId, name, params }) =>+ request('/lora-training/runs', {+ method: 'POST',+ body: JSON.stringify({ datasetId, baseModelId, ...(name ? { name } : {}), ...(params ? { params } : {}) }),+ });++export const listLoraTrainingRuns = (filters = {}) => {+ const params = new URLSearchParams();+ for (const key of ['status', 'characterId', 'datasetId', 'limit']) {+ if (filters[key]) params.set(key, filters[key]);+ }+ const qs = params.toString();+ return request(`/lora-training/runs${qs ? `?${qs}` : ''}`);+};++export const getLoraTrainingRun = (runId) => request(`/lora-training/runs/${runId}`);++export const cancelLoraTrainingRun = (runId) =>+ request(`/lora-training/runs/${runId}/cancel`, { method: 'POST' });++export const deleteLoraTrainingRun = (runId, { deleteLora = false } = {}) =>+ request(`/lora-training/runs/${runId}${deleteLora ? '?deleteLora=true' : ''}`, { method: 'DELETE' });++// ---- Character → trained-LoRA link ----++export const getCharacterLoras = ({ entryId, ingredientId } = {}, { silent = false } = {}) => {+ const params = new URLSearchParams();+ if (entryId) params.set('entryId', entryId);+ if (ingredientId) params.set('ingredientId', ingredientId);+ return request(`/loras/by-character?${params.toString()}`, { silent });+};diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 41381a5fd9..68fc6911e4 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -51,6 +51,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- Writers Room draft bodies — `data/writers-room/works/{workId}/drafts/{draftId}.md`. Keep `.md` file-backed; store metadata/index rows in DB.- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.+- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.---diff --git a/docs/plans/2026-06-12-character-lora-training.md b/docs/plans/2026-06-12-character-lora-training.mdnew file mode 100644index 0000000000..2e5d4f5149--- /dev/null+++ b/docs/plans/2026-06-12-character-lora-training.md@@ -0,0 +1,121 @@+# Character LoRA Training — Create > Image Gen ↔ Universe/Character/Catalog++## Context++PortOS can render characters (mflux FLUX.1 + FLUX.2/diffusers + Codex) and already manages LoRAs for inference (`data/loras/` + `.metadata.json` sidecars, Civitai trigger words, 8-LoRA stacking, compat-key gating), and characters already have rich visual canon (25+ descriptor fields, reference-sheet turnarounds in `data/image-refs/`). What's missing is the loop closer: build a training dataset from a character's reference material, train a LoRA locally, and have that LoRA automatically applied whenever the character is rendered — giving consistent character design, outfits, and props across Image Gen and the comic pipeline.++**User decisions:** pluggable runtime (mflux FLUX.1 + diffusers/peft FLUX.2 in one PR); dataset builder = generate + upload + caption-edit; auto-caption via vision LLM; trained LoRA links to character AND auto-applies in pipeline renders.++**Federation decision:** datasets and character→LoRA links are **machine-local** (like `data/loras/` itself). No pointer is stamped onto the federating character/universe record — resolution is always a local sidecar scan, so peers without the weights gracefully see no link. No `schemaVersions.js` bump anywhere.++## Part A — Dataset builder (character → training-ready dataset)++### Data model — `data/lora-datasets/<id>/` via `createCollectionStore` (file-primary, machine-local; add STORAGE.md row)++```json+{ "schemaVersion": 1, "id": "uuid",+ "character": { "entryId": "<universe entry id>", "ingredientId": "<catalog id|null>", "universeId": "...", "name": "..." },+ "triggerWord": "kessa_brightwater", "status": "draft|training|trained",+ "images": [{ "id": "img-uuid", "file": "img-uuid.png", "caption": "kessa_brightwater, ...",+ "captionSource": "vision|manual|null", "source": "generated|upload|refsheet-slice",+ "sourceJobId": null, "variation": { "view": "...", "pose": "...", "expression": "...", "outfit": "..." },+ "status": "rendering|ready|failed", "width": 1024, "height": 1024 }],+ "training": { "lastJobId": null, "loraFilename": null, "completedAt": null } }+```++Characters carry two ids (`entry.id` per-universe + `ingredientId` catalog row) — store both; all resolution matches either. Image bytes live at `images/<imageId>.png` (sharp-normalized PNG). One dataset per character (find-or-create on `(universeId, entryId)`). **No backup exclude** — uploads + curation are not re-creatable. Add `PATHS.loraDatasets` to `server/lib/fileUtils.js`; register store with the boot verifier in `server/index.js`.++### New server modules (each barrel-exported + README row)++1. **`server/lib/loraDataset.js`** (pure): `sanitizeLoraDataset`, `deriveTriggerWord(name, {taken})` (slug + collision suffix), `prefixCaption(triggerWord, text)` (idempotent), `buildVariationMatrix(character, opts)` (deterministic round-robin over views × poses × `character.expressions` × `character.wardrobes`, with fallbacks), `buildDatasetImagePrompt(universe, character, variation)` — style clause (`buildStyleClause` from `universeCanon.js`) + identity block (export `extractCharacterPromptCommon` from `universeCharacterSheet.js` — one-line change) + solo-subject/plain-background/negative-prompt clauses.+2. **`server/services/loraDatasets.js`**: collectionStore CRUD, `addUploadedImage` (sharp→PNG), `updateImageCaption`, `deleteImage`, `reconcileRenderingImages` (read-time healer: look up `sourceJobId` in the media-job archive; completed→copy+ready, failed/missing→failed — covers restarts).+3. **`server/services/loraDatasetGenerate.js`**: `generateDatasetImages(datasetId, opts)` — per variation: append `status:'rendering'` entry, build params like `renderCharacterReferenceSheet` does (`resolveSheetModelId`, codex/local mode, `cleanC2PA:true`, 1024×1024), `enqueueJob({kind:'image'})`, subscribe via the `sheetSubscribers` single-dispatcher pattern (`universeCharacterSheet.js:357-372`), on complete copy from `data/images/` into the dataset and flip status inside the per-id write queue. `sliceReferenceSheet(datasetId, {variant, cols, rows})` — sharp grid-crop of the existing turnaround (`readSheetPointer` from `server/lib/storyBible.js`); v1 = fixed grid + user prunes bad crops (auto panel detection deferred — layouts are model-generated/non-deterministic).+4. **`server/services/loraDatasetCaption.js`**: `startCaptionRun(datasetId, {imageIds?, providerId?, model?, overwrite})` → sequential loop, reuse `describeImageDataUrl` from `server/services/visionTest.js:226` (provider: request → `settings.loraTraining.captionProviderId` → `'lmstudio'`), `prefixCaption`, persist, SSE progress via `server/lib/sseUtils.js`. Loop body wrapped in try/catch (outside request lifecycle).+5. **`server/services/characterLoraResolver.js`**: `resolveCharacterLoras(matchedCharacters, {compatKey, max=3})` + `findLorasByCharacter({entryId, ingredientId})` — scan `listLoras()` sidecars for `character` match, filter by compat key, cap at 3 (room under MAX_LORAS=8). Missing file ⇒ no match (inherent peer grace).++### Routes — `server/routes/loraDatasets.js` (`/api/lora-datasets`), Zod-validated; static mount `/data/lora-datasets`++CRUD; `POST /:id/images` (multipart via `server/lib/multipart.js` `uploadFields`, 25MB, image mimetypes); `POST /:id/generate` (count 1–40 + variation overrides + modelId/mode); `POST /:id/slice-reference-sheet`; `POST /:id/caption` → `{runId}` + `GET /:id/caption-runs/:runId/events` SSE; `PATCH /:id/images/:imageId` (caption); `POST /:id/train` (validates readiness ≥10 ready+captioned images, then hands off to Part B). Plus `GET /api/loras/by-character?entryId=&ingredientId=` in `server/routes/loras.js` (registered ABOVE `GET /:filename`).++Settings slice: `loraTraining: { captionProviderId, captionModel, defaults: { steps, rank, learningRate, resolution, checkpointEvery, sampleEvery } }` — Zod schema in `server/lib/validation.js`, wired into `PUT /api/settings` via the `backupConfigSchema.partial()` pattern.++## Part B — Training engine++### Service — `server/services/loraTraining/` (index.js, events.js, runtimes.js, progress.js, sidecar.js, dataset.js, failure.js, db.js)++- `resolveTrainingRuntime(baseModelId)` via `getImageModels()`: `runner==='flux2'`→`'flux2'`; mflux family (`dev`/`schnell`)→`'mflux'`; else 400. Diffusers families (z-image/qwen/etc.) out of scope.+- `runTraining({...params, jobId})` mirrors `videoGen/local.js#generateVideo`: spawn venv python with `PYTHONUNBUFFERED`, `safeChildProcessEnv(hfTokenEnv())`, caffeinate on darwin, stdout line protocol → `trainingEvents` → SSE; `cancel(jobId)` = SIGTERM → 8s SIGKILL escalation. `classifyTrainingFailure` regexes stderr tail (OOM / MODULE_NOT_FOUND / USER_ERROR / HF_AUTH).++### Python trainers (`scripts/`)++- **`scripts/train_mflux_lora.py`** — wrapper that subprocesses mflux's own training CLI (`python -m mflux.dreambooth --train-config <json>`; fallback `mflux-train`) in the existing `~/.portos/venv`; Node-side `buildMfluxTrainConfig()` writes the config JSON (model/steps/lora_layers/examples with per-image prompts). Wrapper translates output to `STAGE:`/`STEP:<cur>:<total>:<loss>`/`CHECKPOINT:`/result-JSON protocol, reuses `scripts/_runner_common.py` heartbeat, forwards SIGTERM. **NEEDS-VERIFICATION**: exact mflux training entrypoint/config keys for the installed version (venv absent on this machine — verify via `setup-image-video.sh` then `--help` + site-packages read; pin mflux if its training surface churns).+- **`scripts/train_flux2_lora.py`** — vendored diffusers/peft trainer in `~/.portos/venv-flux2` (torch 2.11 + diffusers-git + peft 0.19 already installed — **no new venv, no new pips**). Two phases: `STAGE:precompute-latents` (encode all images+captions once, cache, free VAE/text-encoder — the make-or-break MPS memory move) then `STAGE:training` (transformer-only bf16, LoraConfig rank r on attn projections, grad checkpointing, AdamW, flow-matching loss). `CHECKPOINT:` every N steps via `save_lora_weights`; `SAMPLE:` images flow through the existing `preview` SSE type; SIGTERM → checkpoint-then-exit-143. Train against **bf16 repos only** (never SDNQ/int8); trained LoRA still loads on quantized inference of the same size variant.++### mediaJobQueue integration (`server/services/mediaJobQueue/index.js`)++`JOB_KINDS` → `['video','image','training']` (line 103); dispatch/emitter/runJob branches at the verified seams (110, 687, 760); `WATCHDOG_TRAINING_MS` = idle-based 30min (STEP lines + heartbeats reset it); GPU lane (serialized with renders — correct, shared Metal); progress % from step/totalSteps; cancel + boot-orphan handling already work via existing machinery; `PARAM_ALLOWLIST` in `routes/mediaJobs.js` gains training fields so the Render Queue labels rows.++### Run persistence — Postgres `lora_training_runs` (db-primary per STORAGE.md; `creative_director_projects` adapter precedent)++`id/status/character_id/timestamps + data JSONB` (runtime, baseModelId, datasetId, triggerWord, params, progress, artifacts, output, error), added idempotently to `server/scripts/init-db.sql`. Progress DB writes debounced ~2s (SSE is the live channel). Artifacts on disk at `data/training-runs/<runId>/{checkpoints,samples,cache}`; backup excludes (rsync-anchored): `/training-runs/*/checkpoints/` (overridable) + `/training-runs/*/cache/` (not overridable).++### Routes — `server/routes/loraTraining.js` (`/api/lora-training`)++`POST /runs` (validate dataset ready + runtime health gate: mflux probe / `isFlux2VenvHealthy()` → 412), `GET /runs`, `GET /runs/:id`, `GET /runs/:id/events` (→ `attachSseClient(run.jobId)`), `POST /runs/:id/cancel`, `DELETE /runs/:id` (409 while active; optional `?deleteLora=true`), `GET /runs/:id/samples/:filename` (assertSafeFilename), `GET /status` (runtime readiness + defaults + memory expectations). `startTrainingRunSchema` + `loraTrainingSettingsSchema` in `server/lib/validation.js` (trigger word `^[a-zA-Z0-9_-]+$`).++### Trained-LoRA registration — `buildTrainedSidecar()`++Copy adapter → `data/loras/lora-trained-<slug>-<runId8>.safetensors` + sidecar: `source:'trained'`, `character` block (entryId+ingredientId+universeId+name), `datasetId`, `runId`, `triggerWords:[triggerWord]`, `runnerFamily` (`mflux`|`flux2`) + `fluxVariant` (4b/9b) so `composeCompatKey` gates it to the right base models in the existing picker **with zero picker changes**, `training` params block, `previewImageUrl` → last sample. Small `loras.js` edit: pass `source`/`character`/`trainedFromDatasetId` through `listLoras()` mapEntry.++## Part C — Client UI + auto-apply++### Pages (deep-linkable, plain-scroll, mobile-responsive)++- `client/src/pages/LoraTraining.jsx` → `/media/training` — dataset cards (character, thumb strip, counts, status chip, trained badge) + new-dataset character picker.+- `client/src/pages/LoraDatasetDetail.jsx` → `/media/training/:datasetId` — workbench: header (trigger-word inline edit, readiness summary), action bar (Generate dialog / Upload / Slice sheet / Caption all with `useSseProgress` / Train), `DatasetImageGrid` (caption textarea blur-save, source badges, per-image rendering spinner, re-caption, delete with inline confirm), `TrainingLaunchPanel` (params form gated on readiness + no in-flight save; run progress via SSE; cancel).+- New components under `client/src/components/loraTraining/`; API wrapper `client/src/services/apiLoraTraining.js` (barrel + README).+- `NAV_COMMANDS` entry `nav.media.training` (`/media/training`, section Create, aliases: training/lora-training/train-lora/datasets) + alphabetical sidebar link in `Layout.jsx` + Routes in `App.jsx`.++### Auto-apply (pipeline renders)++- `server/services/pipeline/visualStages.js`: after character matching (comic pages + storyboards, local mode only), `resolveCharacterLoras(matched, {compatKey: <selected model's loraCompatKey>})` → pass `loraFilenames`/`loraScales` into `enqueueImageJob` baseParams (seam at line 154 — currently passes none); codex mode skips with one log line. Trigger word woven into the Featuring fragment in `composeComicPagePrompt` via a `loraByCharacterId` map param (compose stays pure).+- Per-render opt-out: `applyCharacterLoras` boolean (default true) on `comicPageRenderSchema` + storyboard schema + checkbox in `PipelineIssue.jsx` render controls.++### Character surfacing++- `CanonCard.jsx` (universe editor): `CharacterLoraChip` (lazy resolve via `/api/loras/by-character`, `{silent:true}`) + "Dataset" button (find-or-create → navigate) + "training…" chip while active.+- `CatalogIngredient.jsx`: `TrainedLoraPanel` beside `ReferenceSheetPanel` (resolves via ingredientId).+- `Loras.jsx`: "Character: <name>" chip on trained LoRAs linking to the dataset.++## Build order++1. `lib/loraDataset.js` + tests; export `extractCharacterPromptCommon`; `PATHS.loraDatasets`; STORAGE.md row.+2. `services/loraDatasets.js` + routes + static mount; upload + refsheet slicing.+3. Generation batch (enqueue→subscribe→copy) + reconcile healer.+4. Captioning service + settings slice + SSE.+5. Training engine: runtimes/progress/sidecar/failure pure modules + tests → python trainers (verify mflux surface first) → mediaJobQueue kind → db adapter + init-db.sql → routes → backup excludes.+6. Client: api wrapper → pages → components → nav/sidebar/routes.+7. Resolver + pipeline auto-apply + opt-out toggle; character/catalog/LoRA-library surfacing.+8. Changelog in `.changelog/NEXT.md`; `/simplify` pass.++## Tests (vitest, beside source — pure-logic-first per repo convention)++`loraDataset.test.js` (sanitizer, trigger-word slug/collision, caption prefix idempotence, variation matrix determinism, prompt builder clauses); `loraTraining/runtimes.test.js` (arg/config builders, runtime resolution, bf16-repo enforcement); `progress.test.js` (STEP/CHECKPOINT/SAMPLE/USER_ERROR/result-JSON parsing); `sidecar.test.js` (parity with Civitai sidecar fields, compat keys); `failure.test.js`; `dataset.test.js` (readiness validation); `db.test.js` (mock-pg); `characterLoraResolver.test.js` (entryId/ingredientId match, compat filter, cap, missing-file grace); route tests (Zod rejections, multipart, 412 venv-missing, cancel mapping); `visualStages.test.js` additions (lora passthrough local-only, opt-out, trigger word in prompt); nav-manifest + barrel tests auto-cover new entries.++## Verification (end-to-end on Apple Silicon)++1. `cd server && npm test` (all suites).+2. Create a character in a universe → "Dataset" from its card → generate 12 reference images (watch them stream in via the image queue) → upload 2 → slice the reference sheet → "Caption all" (SSE progress, captions land trigger-word-prefixed, edit one).+3. Train with `steps:20, checkpointEvery:10, sampleEvery:10` on mflux/dev: watch STEP progress + sample preview frames in the run panel; cancel mid-run → assert checkpoint saved + `canceled` state; re-run to completion.+4. Assert: LoRA + sidecar in `data/loras/`, visible in `/media/loras` with correct compat badge + character chip; manual render in `/media/image` with the LoRA + trigger word works.+5. Render a comic page featuring the character → confirm `loraFilenames` in the job params + trigger word in the prompt; toggle `applyCharacterLoras` off → confirm absent.+6. Repeat step 3–4 once on flux2 (klein bf16) to validate the second runtime.++## NEEDS-VERIFICATION ledger (resolve during implementation)++- mflux training entrypoint/config schema + native output format (venv absent here; verify via `--help` + site-packages, run a 10-step smoke before finalizing the wrapper regexes; pin mflux version if needed).+- Whether diffusers-git already ships a FLUX.2 dreambooth-lora example to vendor/trim vs adapting the FLUX.1 script; `Flux2KleinPipeline.save_lora_weights`/`load_lora_weights` round-trip.+- bf16 4B repo existence (`black-forest-labs/FLUX.2-klein-4B`); fall back to 9B bf16 (64GB floor) if only quantized 4B exists.+- bf16-trained LoRA applying cleanly on SDNQ-quantized inference (`scripts/lora_utils.py` logs-and-continues — watch for silent skip).+- Exact exported job-archive getter name in mediaJobQueue for the reconcile healer; where pipeline resolves modelId → `loraCompatKey` (fallback: no compat filter in v1).+- Whether `docs/BACKUP.md` inventories paths (add dataset row if so).diff --git a/scripts/train_flux2_lora.py b/scripts/train_flux2_lora.pynew file mode 100644index 0000000000..39f7c75fd5--- /dev/null+++ b/scripts/train_flux2_lora.py@@ -0,0 +1,349 @@+#!/usr/bin/env python3+"""FLUX.2 Klein LoRA trainer — vendored, MPS-aware (PortOS).++Trains a character LoRA on the bf16 Klein base (NEVER the SDNQ/int8+quantized inference repos — no useful gradients through quant layers).+The trained adapter loads onto quantized inference pipelines of the same+size variant because the transformer hidden dims match.++Two phases keep peak memory survivable on Apple Silicon:++ 1. STAGE:precompute-latents — encode every dataset image to VAE latents+ and every caption to Qwen3 text embeddings ONCE, then free the text+ encoder and move the VAE off-device. Only the transformer stays+ resident for the training loop.+ 2. STAGE:training — bf16 transformer + peft LoRA adapter on the attention+ projections, gradient checkpointing, AdamW, flow-matching loss+ (target = noise - latents, logit-normal timestep sampling — matches+ the FLUX family training recipes).++Line protocol (parsed by server/services/loraTraining/progress.js):+ STEP:<cur>:<total>:<loss> CHECKPOINT:<path>:<step> SAMPLE:<path>:<step>+ STAGE:<name>[...heartbeat] STATUS:<msg> USER_ERROR:<kind>:<msg>+ RESULT:{"adapter_path": ..., "steps": N, "final_loss": F}++SIGTERM → finish the current step, save a cancel checkpoint, exit 143.+"""++import argparse+import gc+import json+import math+import os+import signal+import sys+from pathlib import Path++os.environ.setdefault("PYTORCH_MPS_FAST_MATH", "1")++import torch+from PIL import Image++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import ( # noqa: E402+ heartbeat,+ install_hf_error_handler,+ pick_device,+)++STOP_REQUESTED = False+++def _on_sigterm(_sig, _frame):+ global STOP_REQUESTED+ STOP_REQUESTED = True+ print("STATUS:cancel requested — finishing current step and checkpointing", flush=True)+++signal.signal(signal.SIGTERM, _on_sigterm)+++def log(msg: str) -> None:+ print(msg, flush=True)+++def parse_args():+ p = argparse.ArgumentParser(description="FLUX.2 Klein LoRA trainer")+ p.add_argument("--model-repo", required=True, help="bf16 base repo (black-forest-labs/FLUX.2-klein-4B|9B)")+ p.add_argument("--manifest", required=True, help="JSON manifest: { triggerWord, images: [{ path, caption }] }")+ p.add_argument("--output-dir", required=True)+ p.add_argument("--trigger-word", required=True)+ p.add_argument("--steps", type=int, default=1000)+ p.add_argument("--rank", type=int, default=16)+ p.add_argument("--lr", type=float, default=1e-4)+ p.add_argument("--resolution", type=int, default=512)+ p.add_argument("--checkpoint-every", type=int, default=250)+ p.add_argument("--sample-every", type=int, default=250)+ p.add_argument("--sample-prompt", default=None)+ p.add_argument("--seed", type=int, default=42)+ p.add_argument("--device", default="auto")+ p.add_argument("--resume-from", default=None, help="checkpoint dir to load adapter weights from")+ return p.parse_args()+++def load_image_tensor(path: str, resolution: int) -> torch.Tensor:+ """Open → RGB → shortest-side resize → center crop → [-1, 1] CHW tensor."""+ img = Image.open(path).convert("RGB")+ w, h = img.size+ scale = resolution / min(w, h)+ img = img.resize((max(resolution, round(w * scale)), max(resolution, round(h * scale))), Image.LANCZOS)+ w, h = img.size+ left, top = (w - resolution) // 2, (h - resolution) // 2+ img = img.crop((left, top, left + resolution, top + resolution))+ t = torch.from_numpy(__import__("numpy").asarray(img)).float() / 127.5 - 1.0+ return t.permute(2, 0, 1).unsqueeze(0) # (1, 3, H, W)+++def lora_target_modules(transformer) -> list:+ """Collect attention-projection Linear module name suffixes that actually+ exist in this transformer — robust to naming drift across diffusers+ versions (to_q vs add_q_proj etc.)."""+ wanted = ("to_q", "to_k", "to_v", "to_out.0", "add_q_proj", "add_k_proj", "add_v_proj", "to_add_out")+ found = set()+ for name, module in transformer.named_modules():+ if not isinstance(module, torch.nn.Linear):+ continue+ if ".attn" not in name and "attention" not in name:+ continue+ for suffix in wanted:+ if name.endswith(suffix):+ found.add(suffix)+ if not found:+ raise RuntimeError("No attention projection Linears found to target with LoRA")+ return sorted(found)+++def save_checkpoint(pipe_cls, transformer, out_dir: Path, step: int) -> Path:+ from peft.utils import get_peft_model_state_dict++ ckpt_dir = out_dir / "checkpoints" / f"step-{step:06d}"+ ckpt_dir.mkdir(parents=True, exist_ok=True)+ state = get_peft_model_state_dict(transformer)+ pipe_cls.save_lora_weights(str(ckpt_dir), transformer_lora_layers=state)+ (ckpt_dir / "state.json").write_text(json.dumps({"step": step}))+ return ckpt_dir++[email protected]_grad()+def render_sample(pipe, transformer, embeds, text_ids, resolution, device, dtype, seed, out_path: Path):+ """Quick 8-step Euler flow-matching sample with the in-training adapter.+ Best-effort — callers wrap in try/except; a failed sample never fails+ the run."""+ latent_h = 2 * (resolution // (pipe.vae_scale_factor * 2))+ latent_w = 2 * (resolution // (pipe.vae_scale_factor * 2))+ channels = pipe.transformer.config.in_channels // 4 * 4 # packed channel count+ gen = torch.Generator(device="cpu").manual_seed(seed)+ raw = torch.randn((1, channels, latent_h // 2, latent_w // 2), generator=gen).to(device, dtype)+ latent_ids = pipe._prepare_latent_ids(raw).to(device)+ latents = pipe._pack_latents(raw)+ sigmas = torch.linspace(1.0, 0.0, 9)+ for i in range(8):+ sigma = sigmas[i]+ t = sigma.expand(1).to(device, dtype)+ pred = transformer(+ hidden_states=latents.to(dtype),+ timestep=t,+ guidance=None,+ encoder_hidden_states=embeds,+ txt_ids=text_ids,+ img_ids=latent_ids,+ return_dict=False,+ )[0]+ latents = latents - (sigmas[i] - sigmas[i + 1]).to(device, dtype) * pred+ unpacked = pipe._unpack_latents_with_ids(latents, latent_ids, latent_h // 2, latent_w // 2)+ bn_mean = pipe.vae.bn.running_mean.view(1, -1, 1, 1).to(unpacked.device, unpacked.dtype)+ bn_std = torch.sqrt(pipe.vae.bn.running_var.view(1, -1, 1, 1) + pipe.vae.config.batch_norm_eps).to(+ unpacked.device, unpacked.dtype+ )+ unpacked = unpacked * bn_std + bn_mean+ unpacked = pipe._unpatchify_latents(unpacked)+ vae_device = next(pipe.vae.parameters()).device+ image = pipe.vae.decode(unpacked.to(vae_device, pipe.vae.dtype), return_dict=False)[0]+ image = pipe.image_processor.postprocess(image, output_type="pil")[0]+ image.save(out_path)+++@install_hf_error_handler+def main():+ args = parse_args()+ from diffusers import Flux2KleinPipeline+ from peft import LoraConfig+ from peft.utils import get_peft_model_state_dict++ device = pick_device(args.device)+ dtype = torch.bfloat16 if device != "cpu" else torch.float32+ torch.manual_seed(args.seed)++ out_dir = Path(args.output_dir)+ (out_dir / "samples").mkdir(parents=True, exist_ok=True)+ (out_dir / "checkpoints").mkdir(parents=True, exist_ok=True)++ manifest = json.loads(Path(args.manifest).read_text())+ images = manifest.get("images") or []+ if not images:+ print("USER_ERROR:DATASET_ERROR:manifest contains no images", file=sys.stderr, flush=True)+ sys.exit(2)++ log("STAGE:load-pipeline")+ with heartbeat("load-pipeline"):+ pipe = Flux2KleinPipeline.from_pretrained(args.model_repo, torch_dtype=dtype)++ # ---- Phase 1: precompute text embeddings + image latents ----+ log("STAGE:precompute-latents")+ sample_prompt = args.sample_prompt or f"{args.trigger_word} portrait, neutral background"+ examples = []+ with heartbeat("precompute-latents"):+ pipe.text_encoder.to(device)+ embed_cache = {}+ for entry in images + [{"caption": sample_prompt, "path": None}]:+ caption = entry["caption"]+ if caption not in embed_cache:+ embeds, text_ids = pipe.encode_prompt(caption, device=device)+ embed_cache[caption] = (embeds.to("cpu"), text_ids.to("cpu"))+ sample_embeds = embed_cache[sample_prompt]+ # Free the text encoder — the make-or-break memory move on MPS.+ pipe.text_encoder.to("cpu")+ pipe.text_encoder = None+ gc.collect()+ if device == "mps":+ torch.mps.empty_cache()++ pipe.vae.to(device)+ gen = torch.Generator(device="cpu").manual_seed(args.seed)+ for i, entry in enumerate(images):+ pixel = load_image_tensor(entry["path"], args.resolution).to(device, pipe.vae.dtype)+ latents = pipe._encode_vae_image(pixel, generator=gen) # (1, C, H, W) normalized+ latent_ids = pipe._prepare_latent_ids(latents)+ packed = pipe._pack_latents(latents)+ embeds, text_ids = embed_cache[entry["caption"]]+ examples.append({+ "packed": packed.to("cpu"),+ "latent_ids": latent_ids.to("cpu"),+ "embeds": embeds,+ "text_ids": text_ids,+ })+ log(f"STATUS:encoded {i + 1}/{len(images)} dataset images")+ # VAE only needed again for samples — keep it, but off-device.+ pipe.vae.to("cpu")+ gc.collect()+ if device == "mps":+ torch.mps.empty_cache()++ # ---- Phase 2: training ----+ log("STAGE:training")+ transformer = pipe.transformer+ transformer.requires_grad_(False)+ targets = lora_target_modules(transformer)+ log(f"STATUS:LoRA targets: {', '.join(targets)} (rank {args.rank})")+ transformer.add_adapter(LoraConfig(+ r=args.rank,+ lora_alpha=args.rank,+ init_lora_weights="gaussian",+ target_modules=targets,+ ))+ if args.resume_from:+ resume_dir = Path(args.resume_from)+ if resume_dir.exists():+ pipe.load_lora_weights(str(resume_dir))+ log(f"STATUS:resumed adapter weights from {resume_dir}")+ transformer.enable_gradient_checkpointing()+ transformer.to(device)+ transformer.train()++ trainable = [p for p in transformer.parameters() if p.requires_grad]+ # LoRA params train in fp32 for AdamW stability even when the base is bf16.+ for p in trainable:+ p.data = p.data.to(torch.float32)+ optimizer = torch.optim.AdamW(trainable, lr=args.lr, weight_decay=0.01)++ order = list(range(len(examples)))+ rng = torch.Generator().manual_seed(args.seed)+ final_loss = None+ last_checkpoint = None++ for step in range(1, args.steps + 1):+ if (step - 1) % len(order) == 0:+ order = torch.randperm(len(examples), generator=rng).tolist()+ ex = examples[order[(step - 1) % len(order)]]+ packed = ex["packed"].to(device, dtype)+ latent_ids = ex["latent_ids"].to(device)+ embeds = ex["embeds"].to(device, dtype)+ text_ids = ex["text_ids"].to(device)++ noise = torch.randn_like(packed)+ # Logit-normal timestep sampling (FLUX training recipe).+ sigma = torch.sigmoid(torch.randn((1,), generator=rng)).to(device, dtype)+ noisy = (1.0 - sigma) * packed + sigma * noise+ target = noise - packed++ pred = transformer(+ hidden_states=noisy,+ timestep=sigma.expand(1),+ guidance=None,+ encoder_hidden_states=embeds,+ txt_ids=text_ids,+ img_ids=latent_ids,+ return_dict=False,+ )[0]+ loss = torch.nn.functional.mse_loss(pred.float(), target.float())+ loss.backward()+ torch.nn.utils.clip_grad_norm_(trainable, 1.0)+ optimizer.step()+ optimizer.zero_grad(set_to_none=True)++ final_loss = float(loss.detach().item())+ log(f"STEP:{step}:{args.steps}:{final_loss:.4f}")++ if STOP_REQUESTED:+ ckpt = save_checkpoint(Flux2KleinPipeline, transformer, out_dir, step)+ log(f"CHECKPOINT:{ckpt}:{step}")+ log("STATUS:canceled-checkpoint-saved")+ os._exit(143)++ if args.checkpoint_every > 0 and step % args.checkpoint_every == 0 and step < args.steps:+ ckpt = save_checkpoint(Flux2KleinPipeline, transformer, out_dir, step)+ last_checkpoint = ckpt+ log(f"CHECKPOINT:{ckpt}:{step}")++ if args.sample_every > 0 and step % args.sample_every == 0:+ sample_path = out_dir / "samples" / f"step-{step:06d}.png"+ transformer.eval()+ try:+ render_sample(+ pipe, transformer, sample_embeds[0].to(device, dtype), sample_embeds[1].to(device),+ args.resolution, device, dtype, args.seed, sample_path,+ )+ log(f"SAMPLE:{sample_path}:{step}")+ except Exception as err: # noqa: BLE001 — samples are best-effort, never fail the run+ log(f"STATUS:sample render failed (training continues): {err}")+ finally:+ transformer.train()+ if device == "mps":+ torch.mps.empty_cache()++ # ---- Finalize ----+ adapter_dir = out_dir / "adapter"+ adapter_dir.mkdir(parents=True, exist_ok=True)+ state = get_peft_model_state_dict(transformer)+ Flux2KleinPipeline.save_lora_weights(str(adapter_dir), transformer_lora_layers=state)+ adapter_path = adapter_dir / "pytorch_lora_weights.safetensors"+ if not adapter_path.exists():+ candidates = list(adapter_dir.glob("*.safetensors"))+ if not candidates:+ print("USER_ERROR:TRAINING_FAILED:adapter save produced no .safetensors", file=sys.stderr, flush=True)+ sys.exit(1)+ adapter_path = candidates[0]+ log("RESULT:" + json.dumps({+ "adapter_path": str(adapter_path),+ "steps": args.steps,+ "final_loss": final_loss,+ "last_checkpoint": str(last_checkpoint) if last_checkpoint else None,+ }))+ # Hard-exit defense against teardown hangs (mirrors the video runtimes).+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++if __name__ == "__main__":+ main()diff --git a/scripts/train_mflux_lora.py b/scripts/train_mflux_lora.pynew file mode 100644index 0000000000..56faf4e0ed--- /dev/null+++ b/scripts/train_mflux_lora.py@@ -0,0 +1,251 @@+#!/usr/bin/env python3+"""mflux FLUX.1-dev LoRA training wrapper (PortOS).++Wraps mflux's own DreamBooth training CLI in a subprocess and translates+its native output into the PortOS trainer line protocol (see+train_flux2_lora.py header / server/services/loraTraining/progress.js).+We deliberately do NOT import mflux's training internals in-process —+their API churns across versions; the CLI + train-config JSON is the+stable-ish surface (same wrap-don't-import strategy as generate_wan22.py).++Entrypoint probing (mflux moved this across versions):+ 1. <venv python> -m mflux.dreambooth --train-config <json>+ 2. mflux-train (console script next to the interpreter)++Artifacts: mflux writes checkpoints (zips) + validation images into the+config's save.output_path (our <runDir>/checkpoints). A watcher thread+surfaces new checkpoints as CHECKPOINT: lines and copies validation PNGs+into <runDir>/samples for SAMPLE: lines. On success, the newest adapter+.safetensors (extracted from the newest checkpoint zip when necessary) is+reported via RESULT: JSON.++SIGTERM → forwarded to the mflux child; exit 143 after it stops.+"""++import argparse+import json+import re+import shutil+import signal+import subprocess+import sys+import threading+import time+import zipfile+from pathlib import Path++CHILD = None+STOP_REQUESTED = False+++def log(msg: str) -> None:+ print(msg, flush=True)+++def _on_sigterm(_sig, _frame):+ global STOP_REQUESTED+ STOP_REQUESTED = True+ log("STATUS:cancel requested — stopping mflux trainer")+ if CHILD and CHILD.poll() is None:+ CHILD.terminate()+++signal.signal(signal.SIGTERM, _on_sigterm)+++def parse_args():+ p = argparse.ArgumentParser(description="mflux LoRA training wrapper")+ p.add_argument("--train-config", required=True)+ p.add_argument("--output-dir", required=True)+ p.add_argument("--total-steps", type=int, default=1000,+ help="step budget for progress mapping when mflux reports epoch-relative counts")+ p.add_argument("--resume-checkpoint", default=None)+ return p.parse_args()+++def build_command(config_path: str, resume: str | None) -> list:+ """Probe for mflux's training entrypoint. Prefer the module form (uses+ THIS interpreter, no PATH ambiguity); fall back to the console script."""+ module_probe = subprocess.run(+ [sys.executable, "-c", "import importlib.util as u; raise SystemExit(0 if u.find_spec('mflux.dreambooth') else 1)"],+ capture_output=True,+ )+ if module_probe.returncode == 0:+ cmd = [sys.executable, "-m", "mflux.dreambooth", "--train-config", config_path]+ else:+ console = Path(sys.executable).parent / "mflux-train"+ if not console.exists():+ print(+ "USER_ERROR:MODULE_NOT_FOUND:mflux training entrypoint not found "+ "(neither mflux.dreambooth module nor mflux-train script) — "+ "update mflux via scripts/setup-image-video.sh",+ file=sys.stderr, flush=True,+ )+ sys.exit(2)+ cmd = [str(console), "--train-config", config_path]+ if resume:+ cmd += ["--resume-checkpoint", resume]+ return cmd+++# mflux progress lines vary by version — try, in order:+# "... step 12/400 ... loss: 0.123" / "Step 12/400, loss=0.123"+# "Epoch 3/100 ... loss 0.123" (epoch-relative; scaled by --total-steps)+STEP_RES = [+ re.compile(r"[Ss]teps?[\s:=]+(\d+)\s*/\s*(\d+).*?[Ll]oss[\s:=]+([\d.eE+-]+)"),+ re.compile(r"(\d+)\s*/\s*(\d+).*?[Ll]oss[\s:=]+([\d.eE+-]+)"),+]+EPOCH_RE = re.compile(r"[Ee]poch[\s:=]+(\d+)\s*/\s*(\d+)")+NOISE_RE = re.compile(r"FutureWarning|UserWarning|DeprecationWarning", re.I)+++class ArtifactWatcher(threading.Thread):+ """Poll the checkpoints dir for new checkpoint files + validation PNGs.+ PNGs copy into samples/ so the server's sample route can serve them."""++ def __init__(self, checkpoints_dir: Path, samples_dir: Path, get_step):+ super().__init__(daemon=True)+ self.checkpoints_dir = checkpoints_dir+ self.samples_dir = samples_dir+ self.get_step = get_step+ self.seen = set()+ self.stop_event = threading.Event()++ def scan(self):+ if not self.checkpoints_dir.exists():+ return+ for f in sorted(self.checkpoints_dir.rglob("*")):+ if not f.is_file() or f in self.seen:+ continue+ self.seen.add(f)+ step = self.get_step()+ if f.suffix in (".zip", ".safetensors") and "checkpoint" in f.name.lower() or f.suffix == ".zip":+ log(f"CHECKPOINT:{f}:{step}")+ elif f.suffix == ".png":+ dest = self.samples_dir / f"step-{step:06d}-{f.name}"+ try:+ shutil.copyfile(f, dest)+ log(f"SAMPLE:{dest}:{step}")+ except OSError as err:+ log(f"STATUS:sample copy failed: {err}")++ def run(self):+ while not self.stop_event.wait(5.0):+ self.scan()+ self.scan() # final sweep+++def find_adapter(checkpoints_dir: Path, output_dir: Path) -> Path | None:+ """Newest adapter .safetensors — direct file first, else extract from+ the newest checkpoint zip."""+ direct = sorted(checkpoints_dir.rglob("*.safetensors"), key=lambda f: f.stat().st_mtime)+ if direct:+ return direct[-1]+ zips = sorted(checkpoints_dir.rglob("*.zip"), key=lambda f: f.stat().st_mtime)+ for z in reversed(zips):+ with zipfile.ZipFile(z) as zf:+ members = [m for m in zf.namelist() if m.endswith(".safetensors")]+ if not members:+ continue+ extract_dir = output_dir / "adapter"+ extract_dir.mkdir(parents=True, exist_ok=True)+ zf.extract(members[0], extract_dir)+ return extract_dir / members[0]+ return None+++def main():+ global CHILD+ args = parse_args()+ output_dir = Path(args.output_dir)+ samples_dir = output_dir / "samples"+ samples_dir.mkdir(parents=True, exist_ok=True)+ config = json.loads(Path(args.train_config).read_text())+ checkpoints_dir = Path(config.get("save", {}).get("output_path") or (output_dir / "checkpoints"))+ checkpoints_dir.mkdir(parents=True, exist_ok=True)++ total_steps = max(1, args.total_steps)+ state = {"step": 0, "loss": None}++ watcher = ArtifactWatcher(checkpoints_dir, samples_dir, lambda: state["step"])+ watcher.start()++ cmd = build_command(args.train_config, args.resume_checkpoint)+ log("STAGE:load-model")+ log(f"STATUS:launching {' '.join(Path(cmd[0]).name if i == 0 else c for i, c in enumerate(cmd))}")+ CHILD = subprocess.Popen(+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,+ )+ if STOP_REQUESTED: # SIGTERM raced the spawn+ CHILD.terminate()++ in_training = False+ for raw in CHILD.stdout:+ line = raw.rstrip("\n")+ if not line.strip() or NOISE_RE.search(line):+ continue++ matched = False+ for step_re in STEP_RES:+ m = step_re.search(line)+ if m:+ cur, total = int(m.group(1)), int(m.group(2))+ # mflux totals can be epoch-relative; trust them when they+ # look like our budget, else scale into --total-steps space.+ if total != total_steps and total > 0:+ cur = round(cur / total * total_steps)+ total = total_steps+ state["step"] = cur+ try:+ state["loss"] = float(m.group(3))+ except ValueError:+ pass+ if not in_training:+ in_training = True+ log("STAGE:training")+ log(f"STEP:{cur}:{total}:{state['loss'] if state['loss'] is not None else 'nan'}")+ matched = True+ break+ if matched:+ continue++ em = EPOCH_RE.search(line)+ if em:+ if not in_training:+ in_training = True+ log("STAGE:training")+ log(f"STATUS:epoch {em.group(1)}/{em.group(2)}")+ continue++ # Forward everything else (truncated) — keeps the JS idle watchdog+ # fed during model load/quantize phases and aids debugging.+ log(f"STATUS:{line[:300]}")++ code = CHILD.wait()+ watcher.stop_event.set()+ watcher.join(timeout=10)++ if STOP_REQUESTED:+ log("STATUS:canceled-checkpoint-saved" if state["step"] else "STATUS:canceled")+ sys.exit(143)++ if code != 0:+ print(f"❌ mflux trainer exited with code {code}", file=sys.stderr, flush=True)+ sys.exit(code or 1)++ adapter = find_adapter(checkpoints_dir, output_dir)+ if not adapter:+ print(+ "USER_ERROR:TRAINING_FAILED:mflux finished but no adapter .safetensors found under "+ f"{checkpoints_dir}", file=sys.stderr, flush=True,+ )+ sys.exit(1)+ log("RESULT:" + json.dumps({+ "adapter_path": str(adapter),+ "steps": state["step"] or total_steps,+ "final_loss": state["loss"],+ }))+++if __name__ == "__main__":+ main()diff --git a/server/index.js b/server/index.jsindex 9c999d4d47..0d8e6ed05d 100644--- a/server/index.js+++ b/server/index.js@@ -117,6 +117,10 @@ import { initMediaJobQueue } from './services/mediaJobQueue/index.js';import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';import imageVideoModelsRoutes from './routes/imageVideoModels.js';import lorasRoutes from './routes/loras.js';+import loraDatasetsRoutes from './routes/loraDatasets.js';+import loraTrainingRoutes from './routes/loraTraining.js';+import { loraDatasetStore } from './services/loraDatasets.js';+import { initLoraTraining } from './services/loraTraining/index.js';import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';import sharingRoutes from './routes/sharing.js';@@ -228,7 +232,7 @@ await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore()]).catch(err => {+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore]).catch(err => {console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);});@@ -520,6 +524,8 @@ app.use('/api/importer', importerRoutes);app.use('/api/story-builder', storyBuilderRoutes);app.use('/api/image-video/models', imageVideoModelsRoutes);app.use('/api/loras', lorasRoutes);+app.use('/api/lora-datasets', loraDatasetsRoutes);+app.use('/api/lora-training', loraTrainingRoutes);// AUTOMATIC1111-compatible surface for tailnet clients — gated by// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.app.use('/sdapi/v1', sdapiRoutes);@@ -663,6 +669,8 @@ app.use('/data/images', express.static(PATHS.images, ASSET_STATIC_OPTS));// Reference images (multi-ref upload inputs + generated character reference// sheets) — served read-only so the UI can render thumbnails by URL.app.use('/data/image-refs', express.static(PATHS.imageRefs, ASSET_STATIC_OPTS));+// LoRA training dataset images (lora-datasets/<id>/images/*.png).+app.use('/data/lora-datasets', express.static(PATHS.loraDatasets, ASSET_STATIC_OPTS));// Serve generated videos + thumbnails so the Media UI and tailnet clients// can pull them by URL without going through an explicit download route.app.use('/data/videos', express.static(PATHS.videos, ASSET_STATIC_OPTS));@@ -734,6 +742,10 @@ ensureSelf()}).then(() => initMediaJobQueue()).then(() => {+ // LoRA training run records reconcile against the live queue (interrupted+ // runs → failed) and mirror queue-side cancels — must run after the queue+ // has loaded its persisted jobs.+ initLoraTraining().catch(err => console.error(`❌ loraTraining init failed: ${err.message}`));// Universe Builder needs the media job queue running before it can listen// for `completed` events — so initialize the hook here.initUniverseBuilderCollectionHook();diff --git a/server/lib/README.md b/server/lib/README.mdindex 2b43b327b5..aedb95e928 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -180,6 +180,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. || `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection). || `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel` in `client/src/utils/providers.js`. |+| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. || `issueLength.js` | Per-issue size targets fed into text stages. || `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. || `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 7f0a91017a..e2975b159f 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -76,6 +76,13 @@ export const PATHS = {// the whole dir without touching the gallery.imageRefs: join(__lib_dirname, '../../data/image-refs'),loras: join(__lib_dirname, '../../data/loras'),+ // Per-character LoRA training datasets (collectionStore layout:+ // lora-datasets/<id>/index.json + lora-datasets/<id>/images/*.png).+ // Machine-local like `loras/` — datasets never federate.+ loraDatasets: join(__lib_dirname, '../../data/lora-datasets'),+ // LoRA training run artifacts (checkpoints/samples/cache per run). Run+ // RECORDS live in Postgres (lora_training_runs); only artifacts live here.+ trainingRuns: join(__lib_dirname, '../../data/training-runs'),videos: join(__lib_dirname, '../../data/videos'),videoThumbnails: join(__lib_dirname, '../../data/video-thumbnails'),// Persisted audio renders (voice-over lines). Kept distinct fromdiff --git a/server/lib/index.js b/server/lib/index.jsindex 13bda9da13..e9ff22803c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -153,6 +153,7 @@ export * from './civitai.js';export * from './localLlmCatalog.js';export * from './localLlmDisk.js';export * from './localModelHeuristics.js';+export * from './loraDataset.js';export * from './issueLength.js';export * from './mediaItemKey.js';export * from './navManifest.js';diff --git a/server/lib/loraDataset.js b/server/lib/loraDataset.jsnew file mode 100644index 0000000000..67cc2e4fc7--- /dev/null+++ b/server/lib/loraDataset.js@@ -0,0 +1,226 @@+/**+ * LoRA training dataset — pure helpers (no I/O, no service imports).+ *+ * A dataset is the curated set of captioned reference images for ONE+ * universe character, stored machine-locally at+ * `data/lora-datasets/<id>/index.json` (+ `images/*.png`) via+ * collectionStore. These helpers cover the record sanitizer, trigger-word+ * derivation, caption prefixing, the generation variation matrix, and+ * training readiness. The dataset-image PROMPT builder lives in+ * `server/services/loraDatasetGenerate.js` (it needs canon/service+ * imports that don't belong in the lib barrel); all dataset I/O lives in+ * `server/services/loraDatasets.js`.+ */++export const LORA_DATASET_SCHEMA_VERSION = 1;++// Minimum ready+captioned images before a training run is allowed. Below+// ~10 images a character LoRA badly overfits the few poses it has seen.+export const MIN_TRAINING_IMAGES = 10;++export const DATASET_IMAGE_SOURCES = Object.freeze(['generated', 'upload', 'refsheet-slice']);+export const DATASET_IMAGE_STATUSES = Object.freeze(['rendering', 'ready', 'failed']);+export const DATASET_STATUSES = Object.freeze(['draft', 'training', 'trained']);+export const CAPTION_SOURCES = Object.freeze(['vision', 'manual']);++const TRIGGER_WORD_RE = /^[a-z0-9_]{2,64}$/;+export const isValidTriggerWord = (word) => typeof word === 'string' && TRIGGER_WORD_RE.test(word);++const trim = (s) => (typeof s === 'string' ? s.trim() : '');+const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+const oneOf = (v, list, fallback) => (list.includes(v) ? v : fallback);+const isoOrNull = (v) => (typeof v === 'string' && v ? v : null);++// Default variation axes for the generation matrix. Views/poses are fixed+// vocabularies the service may override with canon-derived lists.+export const DEFAULT_VIEWS = Object.freeze([+ 'front view', 'three-quarter view', 'side profile', 'back view',+]);+export const DEFAULT_POSES = Object.freeze([+ 'standing relaxed', 'walking', 'sitting', 'action pose', 'arms crossed',+]);++/**+ * Sanitize one dataset image entry. Returns null for entries with no id or+ * file (unrecoverable). Captions clamp to 2000 chars to match the route's+ * Zod bound so a hand-edited record can't smuggle an oversized caption past+ * validation.+ */+export function sanitizeDatasetImage(raw) {+ if (!isPlainObject(raw)) return null;+ const id = trim(raw.id);+ const file = trim(raw.file);+ if (!id || !file) return null;+ const variation = isPlainObject(raw.variation)+ ? {+ view: trim(raw.variation.view) || null,+ pose: trim(raw.variation.pose) || null,+ expression: trim(raw.variation.expression) || null,+ outfit: trim(raw.variation.outfit) || null,+ }+ : null;+ return {+ id,+ file,+ caption: trim(raw.caption).slice(0, 2000),+ captionSource: oneOf(raw.captionSource, CAPTION_SOURCES, null),+ captionedAt: isoOrNull(raw.captionedAt),+ source: oneOf(raw.source, DATASET_IMAGE_SOURCES, 'upload'),+ sourceJobId: trim(raw.sourceJobId) || null,+ variation,+ status: oneOf(raw.status, DATASET_IMAGE_STATUSES, 'ready'),+ width: Number.isInteger(raw.width) && raw.width > 0 ? raw.width : null,+ height: Number.isInteger(raw.height) && raw.height > 0 ? raw.height : null,+ createdAt: isoOrNull(raw.createdAt),+ };+}++/**+ * Record-level sanitizer fed to collectionStore — runs on every loadOne.+ * Returns null when the record is missing its identity (id or character),+ * which collectionStore treats as "invalid record".+ */+export function sanitizeLoraDataset(raw) {+ if (!isPlainObject(raw)) return null;+ const id = trim(raw.id);+ const character = isPlainObject(raw.character) ? raw.character : null;+ if (!id || !character) return null;+ const entryId = trim(character.entryId);+ const universeId = trim(character.universeId);+ if (!entryId || !universeId) return null;+ const training = isPlainObject(raw.training) ? raw.training : {};+ return {+ schemaVersion: LORA_DATASET_SCHEMA_VERSION,+ id,+ character: {+ entryId,+ ingredientId: trim(character.ingredientId) || null,+ universeId,+ name: trim(character.name) || 'Unnamed',+ },+ triggerWord: isValidTriggerWord(raw.triggerWord) ? raw.triggerWord : '',+ status: oneOf(raw.status, DATASET_STATUSES, 'draft'),+ images: Array.isArray(raw.images) ? raw.images.map(sanitizeDatasetImage).filter(Boolean) : [],+ training: {+ lastJobId: trim(training.lastJobId) || null,+ lastRunId: trim(training.lastRunId) || null,+ loraFilename: trim(training.loraFilename) || null,+ completedAt: isoOrNull(training.completedAt),+ },+ createdAt: isoOrNull(raw.createdAt),+ updatedAt: isoOrNull(raw.updatedAt),+ };+}++/**+ * Derive a trigger word from a character name: lowercase, [a-z0-9_],+ * underscore-joined, numeric suffix on collision with `taken`. Trigger+ * words are single rare-ish tokens the trainer binds the character to —+ * the underscore join keeps multi-word names a single token.+ */+export function deriveTriggerWord(name, { taken = [] } = {}) {+ const base = trim(name)+ .toLowerCase()+ .normalize('NFKD')+ .replace(/[̀-ͯ]/g, '') // strip diacritics post-decompose+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .slice(0, 60)+ || 'character';+ const candidate = base.length >= 2 ? base : `${base}_x`;+ const takenSet = new Set(taken);+ if (!takenSet.has(candidate)) return candidate;+ for (let i = 2; i < 1000; i += 1) {+ const next = `${candidate}${i}`;+ if (!takenSet.has(next)) return next;+ }+ // 999 collisions on one name never happens in practice; timestamp suffix+ // keeps the function total rather than throwing.+ return `${candidate}_${Date.now().toString(36)}`;+}++const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');++/**+ * Ensure a caption starts with exactly one `"<triggerWord>, "` prefix.+ * Idempotent; also strips a stale prefix when the trigger word changed+ * (`previousTriggerWord`). Empty caption text → just the trigger word, so+ * a not-yet-captioned image still carries the binding token.+ */+export function prefixCaption(triggerWord, text, { previousTriggerWord = null } = {}) {+ const word = trim(triggerWord);+ let body = trim(text);+ const stripPrefix = (value, token) => {+ if (!token) return value;+ return value.replace(new RegExp(`^${escapeRe(token)}\\s*,?\\s*`, 'i'), '');+ };+ body = stripPrefix(body, word);+ const prev = trim(previousTriggerWord);+ if (prev && prev !== word) body = stripPrefix(body, prev);+ if (!word) return body;+ return body ? `${word}, ${body}` : word;+}++/**+ * Build `count` deterministic variation tuples for dataset generation.+ * Round-robin over each axis independently (not a full cartesian product)+ * so a small count still spans every view before repeating poses, and the+ * same inputs always produce the same tuples (testable, resumable). Pose+ * and expression cycles are phase-shifted by the wrap count so the axes+ * don't lock into repeating pairs.+ *+ * Axes are plain string arrays; the SERVICE derives expression/outfit axes+ * from character canon before calling (this module stays canon-agnostic).+ */+export function buildVariationMatrix({+ count = 12,+ views = null,+ poses = null,+ expressions = null,+ outfits = null,+} = {}) {+ const pickAxis = (axis, fallback) => (Array.isArray(axis) && axis.length+ ? axis.map((v) => trim(v)).filter(Boolean)+ : [...fallback]);+ const axisViews = pickAxis(views, DEFAULT_VIEWS);+ const axisPoses = pickAxis(poses, DEFAULT_POSES);+ const axisExpressions = pickAxis(expressions, ['neutral']);+ const axisOutfits = pickAxis(outfits, ['signature outfit']);+ const n = Math.max(1, Math.min(40, Number.isInteger(count) ? count : 12));+ const tuples = [];+ for (let i = 0; i < n; i += 1) {+ tuples.push({+ view: axisViews[i % axisViews.length],+ pose: axisPoses[(i + Math.floor(i / axisViews.length)) % axisPoses.length],+ expression: axisExpressions[(i + Math.floor(i / axisPoses.length)) % axisExpressions.length],+ // Block-assign outfits (first chunk of renders in outfit 1, next in+ // outfit 2, …) so each outfit gets contiguous view coverage instead+ // of a different outfit every frame.+ outfit: axisOutfits[Math.floor(i / Math.max(1, Math.ceil(n / axisOutfits.length))) % axisOutfits.length],+ });+ }+ return tuples;+}++/**+ * Compute dataset readiness for training. Pure — callers pass the sanitized+ * record. `trainable` requires a trigger word plus MIN_TRAINING_IMAGES+ * images that are status 'ready' AND carry a caption containing it.+ */+export function computeDatasetReadiness(dataset) {+ const images = Array.isArray(dataset?.images) ? dataset.images : [];+ const triggerWord = trim(dataset?.triggerWord);+ const readyImages = images.filter((img) => img.status === 'ready');+ const captioned = readyImages.filter((img) => {+ const caption = trim(img.caption);+ return caption && (!triggerWord || caption.toLowerCase().includes(triggerWord.toLowerCase()));+ });+ return {+ total: images.length,+ ready: readyImages.length,+ captioned: captioned.length,+ rendering: images.filter((img) => img.status === 'rendering').length,+ required: MIN_TRAINING_IMAGES,+ trainable: !!triggerWord && captioned.length >= MIN_TRAINING_IMAGES,+ };+}diff --git a/server/lib/loraDataset.test.js b/server/lib/loraDataset.test.jsnew file mode 100644index 0000000000..9b7d19e47a--- /dev/null+++ b/server/lib/loraDataset.test.js@@ -0,0 +1,189 @@+import { describe, it, expect } from 'vitest';+import {+ buildVariationMatrix,+ computeDatasetReadiness,+ deriveTriggerWord,+ isValidTriggerWord,+ MIN_TRAINING_IMAGES,+ prefixCaption,+ sanitizeDatasetImage,+ sanitizeLoraDataset,+ LORA_DATASET_SCHEMA_VERSION,+} from './loraDataset.js';++const baseRecord = () => ({+ id: 'ds-1',+ character: { entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa' },+ triggerWord: 'kessa_brightwater',+ status: 'draft',+ images: [],+ training: {},+});++describe('sanitizeLoraDataset', () => {+ it('stamps schemaVersion and normalizes shape', () => {+ const out = sanitizeLoraDataset(baseRecord());+ expect(out.schemaVersion).toBe(LORA_DATASET_SCHEMA_VERSION);+ expect(out.character).toEqual({+ entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa',+ });+ expect(out.training).toEqual({+ lastJobId: null, lastRunId: null, loraFilename: null, completedAt: null,+ });+ });++ it('rejects records missing identity', () => {+ expect(sanitizeLoraDataset(null)).toBeNull();+ expect(sanitizeLoraDataset({ id: 'x' })).toBeNull();+ expect(sanitizeLoraDataset({ ...baseRecord(), character: { entryId: '', universeId: 'u' } })).toBeNull();+ });++ it('drops invalid trigger words and unknown statuses', () => {+ const out = sanitizeLoraDataset({ ...baseRecord(), triggerWord: 'Has Spaces!', status: 'bogus' });+ expect(out.triggerWord).toBe('');+ expect(out.status).toBe('draft');+ });++ it('filters unrecoverable image entries and clamps captions', () => {+ const out = sanitizeLoraDataset({+ ...baseRecord(),+ images: [+ { id: 'img-1', file: 'img-1.png', caption: 'x'.repeat(3000), source: 'nope', status: 'weird' },+ { id: '', file: 'orphan.png' },+ 'not-an-object',+ ],+ });+ expect(out.images).toHaveLength(1);+ expect(out.images[0].caption).toHaveLength(2000);+ expect(out.images[0].source).toBe('upload');+ expect(out.images[0].status).toBe('ready');+ });+});++describe('sanitizeDatasetImage', () => {+ it('normalizes variation and numeric dimensions', () => {+ const out = sanitizeDatasetImage({+ id: 'img-1', file: 'img-1.png',+ variation: { view: ' front view ', pose: '', expression: 'amused' },+ width: 1024, height: -5,+ });+ expect(out.variation).toEqual({ view: 'front view', pose: null, expression: 'amused', outfit: null });+ expect(out.width).toBe(1024);+ expect(out.height).toBeNull();+ });+});++describe('deriveTriggerWord', () => {+ it('slugs names to single lowercase tokens', () => {+ expect(deriveTriggerWord('Kessa Brightwater')).toBe('kessa_brightwater');+ expect(deriveTriggerWord("D'Artagnan-El Niño")).toBe('d_artagnan_el_nino');+ });++ it('suffixes on collision', () => {+ expect(deriveTriggerWord('Kessa', { taken: ['kessa'] })).toBe('kessa2');+ expect(deriveTriggerWord('Kessa', { taken: ['kessa', 'kessa2'] })).toBe('kessa3');+ });++ it('falls back for empty / too-short names', () => {+ expect(deriveTriggerWord('')).toBe('character');+ expect(isValidTriggerWord(deriveTriggerWord('武'))).toBe(true);+ });+});++describe('prefixCaption', () => {+ it('prefixes once and is idempotent', () => {+ const once = prefixCaption('kessa', 'a woman with copper hair');+ expect(once).toBe('kessa, a woman with copper hair');+ expect(prefixCaption('kessa', once)).toBe(once);+ });++ it('re-prefixes when the trigger word changed', () => {+ const out = prefixCaption('kessa_v2', 'kessa, a woman with copper hair', { previousTriggerWord: 'kessa' });+ expect(out).toBe('kessa_v2, a woman with copper hair');+ });++ it('returns just the trigger word for empty text', () => {+ expect(prefixCaption('kessa', '')).toBe('kessa');+ expect(prefixCaption('kessa', ' ')).toBe('kessa');+ });++ it('passes text through when no trigger word', () => {+ expect(prefixCaption('', 'plain caption')).toBe('plain caption');+ });+});++describe('buildVariationMatrix', () => {+ it('returns exactly count deterministic tuples', () => {+ const a = buildVariationMatrix({ count: 12 });+ const b = buildVariationMatrix({ count: 12 });+ expect(a).toHaveLength(12);+ expect(a).toEqual(b);+ for (const t of a) {+ expect(t.view).toBeTruthy();+ expect(t.pose).toBeTruthy();+ expect(t.expression).toBeTruthy();+ expect(t.outfit).toBeTruthy();+ }+ });++ it('spans all views before repeating', () => {+ const tuples = buildVariationMatrix({ count: 4 });+ expect(new Set(tuples.map((t) => t.view)).size).toBe(4);+ });++ it('uses caller-supplied axes and blank-filters them', () => {+ const tuples = buildVariationMatrix({+ count: 4,+ expressions: [' smug ', ''],+ outfits: ['armor', 'gala dress'],+ });+ expect(tuples.every((t) => t.expression === 'smug')).toBe(true);+ expect(new Set(tuples.map((t) => t.outfit))).toEqual(new Set(['armor', 'gala dress']));+ });++ it('block-assigns outfits contiguously', () => {+ const tuples = buildVariationMatrix({ count: 8, outfits: ['a', 'b'] });+ expect(tuples.slice(0, 4).every((t) => t.outfit === 'a')).toBe(true);+ expect(tuples.slice(4).every((t) => t.outfit === 'b')).toBe(true);+ });++ it('clamps count to [1, 40]', () => {+ expect(buildVariationMatrix({ count: 0 })).toHaveLength(1);+ expect(buildVariationMatrix({ count: 999 })).toHaveLength(40);+ expect(buildVariationMatrix({ count: 1.5 })).toHaveLength(12);+ });+});++describe('computeDatasetReadiness', () => {+ const img = (overrides = {}) => ({+ id: 'i', file: 'i.png', status: 'ready', caption: 'kessa, portrait', ...overrides,+ });++ it('counts ready vs captioned vs rendering', () => {+ const out = computeDatasetReadiness({+ triggerWord: 'kessa',+ images: [+ img(),+ img({ caption: 'no trigger here' }),+ img({ status: 'rendering', caption: '' }),+ img({ status: 'failed' }),+ ],+ });+ expect(out).toMatchObject({ total: 4, ready: 2, captioned: 1, rendering: 1 });+ expect(out.trainable).toBe(false);+ });++ it('flips trainable at MIN_TRAINING_IMAGES captioned images', () => {+ const images = Array.from({ length: MIN_TRAINING_IMAGES }, (_, i) => img({ id: `i${i}` }));+ expect(computeDatasetReadiness({ triggerWord: 'kessa', images }).trainable).toBe(true);+ expect(computeDatasetReadiness({ triggerWord: '', images }).trainable).toBe(false);+ });++ it('matches trigger word case-insensitively', () => {+ const out = computeDatasetReadiness({+ triggerWord: 'kessa',+ images: [img({ caption: 'KESSA, shouting' })],+ });+ expect(out.captioned).toBe(1);+ });+});diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 504cd8c7c2..f6dd421bdb 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -31,6 +31,7 @@ export const NAV_COMMANDS = [{ id: 'nav.create.songs-guide', path: '/songs/guide', label: 'Songs Guide', section: 'Create', aliases: ['songs-guide', 'song-guide', 'singing-guide', 'song-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn song', 'a cappella', 'singing help'] },{ id: 'nav.create.sharing-conflicts', path: '/sharing/conflicts', label: 'Conflicts', section: 'Create', aliases: ['conflicts', 'sync-conflicts', 'edit-conflicts', 'conflict-journal'], keywords: ['conflict', 'overwrite', 'lost edit', 'restore', 'merge fields', 'last write wins', 'diverged', 'recover'] },{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },+ { id: 'nav.media.training', path: '/media/training', label: 'LoRA Training', section: 'Create', aliases: ['training', 'lora-training', 'train-lora', 'datasets', 'character-lora'], keywords: ['fine-tune', 'dataset', 'caption', 'dreambooth', 'character consistency', 'train', 'flux lora'] },{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },{ id: 'nav.writers-room.guide', path: '/writers-room/guide', label: 'Writers Room Guide', section: 'Create', aliases: ['writers-room-guide', 'writing-guide', 'writing-rules', 'word-count', 'length-targets'], keywords: ['microfiction', 'flash fiction', 'short story', 'novelette', 'novella', 'novel length', 'word count', 'character count', 'book length', 'craft', 'writing advice', 'emotional roadmap', 'documentation', 'help'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex cefe27829d..8f2e475103 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -822,6 +822,36 @@ export const citySnapshotConfigSchema = z.object({maxSnapshots: z.number().int().min(10).max(100000).optional()});+// Shared LoRA-training parameter bounds — used by both the settings-slice+// defaults and the per-run override on POST /api/lora-training/runs.+const loraTrainingParamsSchema = z.object({+ steps: z.number().int().min(10).max(10000).optional(),+ rank: z.number().int().min(1).max(128).optional(),+ learningRate: z.number().positive().max(0.1).optional(),+ resolution: z.union([z.literal(512), z.literal(768), z.literal(1024)]).optional(),+ seed: z.number().int().optional(),+ checkpointEvery: z.number().int().min(0).max(5000).optional(),+ sampleEvery: z.number().int().min(0).max(5000).optional(),+ samplePrompt: z.string().max(2000).optional(),+});++// LoRA training settings slice (`settings.loraTraining`) — vision-caption+// provider pick + training parameter defaults. Code-level defaults live in+// `services/loraTraining/runtimes.js` so an absent slice needs no migration.+export const loraTrainingConfigSchema = z.object({+ captionProviderId: z.string().max(128).optional(),+ captionModel: z.string().max(256).nullable().optional(),+ defaults: loraTrainingParamsSchema.optional(),+});++// POST /api/lora-training/runs — start a training run for a dataset.+export const startTrainingRunSchema = z.object({+ datasetId: z.string().min(1).max(128),+ baseModelId: z.string().min(1).max(128),+ name: z.string().trim().max(120).optional(),+ params: loraTrainingParamsSchema.optional(),+});+// Query for GET /api/city/snapshots — `since` (ISO timestamp) and `limit`// (most-recent N) both arrive as strings on the query string.export const citySnapshotsQuerySchema = z.object({diff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.jsnew file mode 100644index 0000000000..025cb00fdf--- /dev/null+++ b/server/routes/loraDatasets.js@@ -0,0 +1,149 @@+/**+ * LoRA training dataset routes — `/api/lora-datasets`.+ *+ * CRUD + image upload (multipart) + batch generation + reference-sheet+ * slicing + vision captioning (SSE) for the per-character training+ * datasets behind /media/training. Training-run launch lives at+ * `/api/lora-training` (routes/loraTraining.js); this surface ends at+ * "dataset ready to train".+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { uploadFields } from '../lib/multipart.js';+import {+ addUploadedImage,+ createDataset,+ deleteDataset,+ deleteImage,+ getDataset,+ listDatasets,+ patchDataset,+ reconcileRenderingImages,+ updateImageCaption,+} from '../services/loraDatasets.js';+import { generateDatasetImages, sliceReferenceSheet } from '../services/loraDatasetGenerate.js';+import { attachCaptionSseClient, startCaptionRun } from '../services/loraDatasetCaption.js';+import { computeDatasetReadiness } from '../lib/loraDataset.js';++const router = Router();++const triggerWordSchema = z.string().regex(/^[a-z0-9_]{2,64}$/, 'trigger word must be 2-64 chars of [a-z0-9_]');+const idSchema = z.string().min(1).max(128);++const listQuerySchema = z.object({+ universeId: idSchema.optional(),+ entryId: idSchema.optional(),+ ingredientId: idSchema.optional(),+});+router.get('/', asyncHandler(async (req, res) => {+ const filters = validateRequest(listQuerySchema, req.query);+ res.json(await listDatasets(filters));+}));++const createSchema = z.object({+ universeId: idSchema,+ entryId: idSchema,+ triggerWord: triggerWordSchema.optional(),+});+router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(createSchema, req.body);+ const { dataset, created } = await createDataset(body);+ res.status(created ? 201 : 200).json(dataset);+}));++router.get('/:id', asyncHandler(async (req, res) => {+ // Heal any images stuck in 'rendering' (server restart dropped the live+ // completion hook) before returning — the grid then shows truth.+ const dataset = await reconcileRenderingImages(req.params.id);+ res.json({ ...dataset, readiness: computeDatasetReadiness(dataset) });+}));++const patchSchema = z.object({ triggerWord: triggerWordSchema.optional() });+router.patch('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(patchSchema, req.body);+ const dataset = await patchDataset(req.params.id, body);+ res.json({ ...dataset, readiness: computeDatasetReadiness(dataset) });+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ res.json(await deleteDataset(req.params.id));+}));++// Image upload — up to 10 files per request on image1…image10 field names.+const UPLOAD_FIELDS = Array.from({ length: 10 }, (_, i) => `image${i + 1}`);+const ACCEPTED_MIME = new Set(['image/png', 'image/jpeg', 'image/webp']);+const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;+const datasetUploads = uploadFields(UPLOAD_FIELDS, {+ limits: { fileSize: MAX_UPLOAD_BYTES },+ fileFilter: (_req, file, cb) => cb(null, ACCEPTED_MIME.has((file.mimetype || '').toLowerCase())),+});+router.post('/:id/images', datasetUploads, asyncHandler(async (req, res) => {+ const staged = Object.values(req.files || {});+ if (!staged.length) {+ throw new ServerError('No image files in request (use field names image1…image10)', {+ status: 400, code: 'VALIDATION_ERROR',+ });+ }+ const entries = [];+ for (const file of staged) {+ entries.push(await addUploadedImage(req.params.id, {+ tmpPath: file.path, originalname: file.originalname,+ }));+ }+ res.status(201).json({ images: entries });+}));++const generateSchema = z.object({+ count: z.number().int().min(1).max(40).default(12),+ views: z.array(z.string().max(120)).max(12).optional(),+ poses: z.array(z.string().max(120)).max(12).optional(),+ expressions: z.array(z.string().max(120)).max(12).optional(),+ outfits: z.array(z.string().max(120)).max(12).optional(),+ modelId: z.string().max(128).optional(),+});+router.post('/:id/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(generateSchema, req.body);+ res.status(202).json(await generateDatasetImages(req.params.id, body));+}));++const sliceSchema = z.object({+ variant: z.string().max(64).default('standard'),+ cols: z.number().int().min(1).max(6).default(3),+ rows: z.number().int().min(1).max(6).default(2),+});+router.post('/:id/slice-reference-sheet', asyncHandler(async (req, res) => {+ const body = validateRequest(sliceSchema, req.body);+ res.status(201).json(await sliceReferenceSheet(req.params.id, body));+}));++const captionSchema = z.object({+ imageIds: z.array(idSchema).max(200).optional(),+ providerId: z.string().max(128).optional(),+ model: z.string().max(256).optional(),+ overwrite: z.boolean().default(false),+});+router.post('/:id/caption', asyncHandler(async (req, res) => {+ const body = validateRequest(captionSchema, req.body);+ res.status(202).json(await startCaptionRun(req.params.id, body));+}));++router.get('/:id/caption-runs/:runId/events', asyncHandler(async (req, res) => {+ if (!attachCaptionSseClient(req.params.runId, res)) {+ throw new ServerError(`Caption run not found: ${req.params.runId}`, { status: 404, code: 'NOT_FOUND' });+ }+}));++const imagePatchSchema = z.object({ caption: z.string().max(2000) });+router.patch('/:id/images/:imageId', asyncHandler(async (req, res) => {+ const { caption } = validateRequest(imagePatchSchema, req.body);+ res.json(await updateImageCaption(req.params.id, req.params.imageId, caption));+}));++router.delete('/:id/images/:imageId', asyncHandler(async (req, res) => {+ res.json(await deleteImage(req.params.id, req.params.imageId));+}));++export default router;diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.jsnew file mode 100644index 0000000000..53a91459a5--- /dev/null+++ b/server/routes/loraTraining.js@@ -0,0 +1,116 @@+/**+ * LoRA training run routes — `/api/lora-training`.+ *+ * Run lifecycle (start/list/detail/cancel/delete), per-run SSE progress+ * (delegated to the media-job queue's stream for the run's jobId), sample+ * image serving, and a runtime-readiness status endpoint for the UI.+ */++import { Router } from 'express';+import { rm } from 'fs/promises';+import { join } from 'path';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { startTrainingRunSchema, validateRequest } from '../lib/validation.js';+import { assertSafeFilename } from '../lib/fileUtils.js';+import { resolveFlux2Python, isFlux2VenvHealthy } from '../lib/pythonSetup.js';+import { getSettings } from '../services/settings.js';+import { attachSseClient, cancelJob } from '../services/mediaJobQueue/index.js';+import {+ deleteRun,+ getRunRequired,+ listRuns,+ runDir,+ runSamplesDir,+ startTrainingRun,+} from '../services/loraTraining/index.js';+import { TRAINING_DEFAULTS } from '../services/loraTraining/runtimes.js';+import { deleteLora } from '../services/loras.js';++const router = Router();++// Runtime readiness + defaults — drives the launch panel's enable/disable+// state and the params form's initial values.+router.get('/status', asyncHandler(async (_req, res) => {+ const settings = await getSettings();+ const mfluxPython = settings?.imageGen?.local?.pythonPath || null;+ const flux2Python = resolveFlux2Python();+ res.json({+ runtimes: {+ mflux: { ready: !!mfluxPython, pythonPath: mfluxPython },+ flux2: { ready: !!flux2Python && await isFlux2VenvHealthy(), venvPython: flux2Python },+ },+ defaults: { ...TRAINING_DEFAULTS, ...(settings?.loraTraining?.defaults || {}) },+ });+}));++router.post('/runs', asyncHandler(async (req, res) => {+ const body = validateRequest(startTrainingRunSchema, req.body);+ res.status(202).json(await startTrainingRun(body));+}));++const listQuerySchema = z.object({+ status: z.enum(['queued', 'running', 'completed', 'failed', 'canceled']).optional(),+ characterId: z.string().max(128).optional(),+ datasetId: z.string().max(128).optional(),+ limit: z.coerce.number().int().min(1).max(500).optional(),+});+router.get('/runs', asyncHandler(async (req, res) => {+ const query = validateRequest(listQuerySchema, req.query);+ res.json(await listRuns(query));+}));++router.get('/runs/:id', asyncHandler(async (req, res) => {+ res.json(await getRunRequired(req.params.id));+}));++// Live progress — the run's SSE stream IS the media-job stream. The queue+// synthesizes a terminal frame for archived jobs, so late attaches after+// completion still resolve.+router.get('/runs/:id/events', asyncHandler(async (req, res) => {+ const run = await getRunRequired(req.params.id);+ if (!run.jobId || !attachSseClient(run.jobId, res)) {+ throw new ServerError(`No live stream for run ${req.params.id} (status: ${run.status})`, {+ status: 404, code: 'NOT_FOUND',+ });+ }+}));++router.post('/runs/:id/cancel', asyncHandler(async (req, res) => {+ const run = await getRunRequired(req.params.id);+ if (!run.jobId) {+ throw new ServerError('Run has no job to cancel', { status: 409, code: 'ALREADY_TERMINAL' });+ }+ const result = await cancelJob(run.jobId);+ if (!result.ok) {+ const status = result.code === 'NOT_FOUND' ? 404 : 409;+ throw new ServerError(result.error || 'Cancel failed', { status, code: result.code });+ }+ res.json(result);+}));++router.delete('/runs/:id', asyncHandler(async (req, res) => {+ const run = await getRunRequired(req.params.id);+ if (['queued', 'running'].includes(run.status)) {+ throw new ServerError('Cancel the run before deleting it', { status: 409, code: 'RUN_ACTIVE' });+ }+ // Artifact dir is server-derived from the run id (uuid) — confined under+ // PATHS.trainingRuns by construction.+ await rm(runDir(run.id), { recursive: true, force: true });+ if (req.query.deleteLora === 'true' && run.output?.loraFilename) {+ await deleteLora(run.output.loraFilename).catch((err) => {+ console.log(`⚠️ trained LoRA delete skipped: ${err?.message}`);+ });+ }+ res.json(await deleteRun(run.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' });+ res.sendFile(join(runSamplesDir(run.id), req.params.filename), (err) => {+ if (err && !res.headersSent) res.status(404).json({ error: 'Sample not found' });+ });+}));++export default router;diff --git a/server/routes/loras.js b/server/routes/loras.jsindex c5de83d461..e3f1553479 100644--- a/server/routes/loras.js+++ b/server/routes/loras.js@@ -20,6 +20,7 @@ import {patchLoraSidecar,} from '../services/loras.js';import { getSuggestions, searchLorasInFamily } from '../services/civitaiSuggestions.js';+import { findLorasByCharacter } from '../services/characterLoraResolver.js';import { getSettings, updateSettingsWith } from '../services/settings.js';import { RUNNER_FAMILIES } from '../lib/runners.js';@@ -118,6 +119,18 @@ router.post('/install', asyncHandler(async (req, res) => {res.status(201).json(sidecar);}));+// Trained LoRAs linked to a universe character — used by the character card+// chip in the universe editor + catalog detail page. 2-segment path keeps it+// off the `/:filename` wildcard below.+const byCharacterSchema = z.object({+ entryId: z.preprocess(emptyToUndefined, z.string().max(128).optional()),+ ingredientId: z.preprocess(emptyToUndefined, z.string().max(128).optional()),+}).refine((q) => q.entryId || q.ingredientId, { message: 'entryId or ingredientId required' });+router.get('/by-character', asyncHandler(async (req, res) => {+ const { entryId, ingredientId } = validateRequest(byCharacterSchema, req.query);+ res.json(await findLorasByCharacter({ entryId: entryId || null, ingredientId: ingredientId || null }));+}));+router.get('/:filename', asyncHandler(async (req, res) => {const lora = await getLora(req.params.filename);res.json(lora);diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.jsindex 93f5292dac..a9bb6edb2e 100644--- a/server/routes/mediaJobs.js+++ b/server/routes/mediaJobs.js@@ -76,6 +76,10 @@ const PARAM_ALLOWLIST = new Set(['width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale','seed', 'tiling', 'disableAudio', 'mode', 'imageStrength','cfgScale', 'guidance', 'quantize',+ // Training-kind label fields so the Render Queue UI can title training+ // rows ("Training: Kessa · mflux · 1000 steps") without exposing paths.+ 'runId', 'runtime', 'datasetId', 'characterId', 'characterName',+ 'triggerWord', 'rank', 'baseModelId',]);function sanitizeJob(job) {if (!job) return job;diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex e7ba7e7cac..fbbfce09ec 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -96,6 +96,7 @@ const visualStageInputSchema = stageInputSchema.extend({imageModelId: z.string().trim().max(200).nullable().optional(),refineProvider: z.string().trim().max(200).nullable().optional(),refineModel: z.string().trim().max(200).nullable().optional(),+ applyCharacterLoras: z.boolean().optional(),}).nullable().optional(),// Comic-issue front cover. Only meaningful on the comicPages stage; the// service-side sanitizer drops the field on other visual stages.@@ -197,6 +198,8 @@ const visualGenerateSchema = z.object({characterId: z.string().trim().min(1).max(120),wardrobeId: z.string().trim().min(1).max(120).nullable().optional(),})).max(50).optional(),+ // Per-render opt-out for trained character-LoRA auto-apply (local mode).+ applyCharacterLoras: z.boolean().optional().default(true),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });// Full-comic-page render: same knobs as panel render minus `description` /@@ -216,6 +219,8 @@ const comicPageRenderSchema = z.object({// See covers.js's makeCoverRenderSchema for the proof/final semantics.target: z.enum(COMIC_PAGE_VARIANTS).optional().default('proof'),useProofAsBase: z.boolean().optional().default(false),+ // Per-render opt-out for trained character-LoRA auto-apply (local mode).+ applyCharacterLoras: z.boolean().optional().default(true),}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });const episodeVideoSchema = z.object({diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 0f8d8ffdb0..4ef859cb20 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -9,7 +9,7 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, apiAccessSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -96,6 +96,12 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.citySnapshots !== undefined) {validateRequest(citySnapshotConfigSchema.partial(), req.body.citySnapshots);}+ // LoRA training config (caption provider + training defaults) — validate+ // the slice when present so a malformed save can't write bad bounds the+ // trainer would then pass to the python child.+ if (req.body?.loraTraining !== undefined) {+ validateRequest(loraTrainingConfigSchema.partial(), req.body.loraTraining);+ }// Per-API external-access flags (voice/sdapi). Validate the slice when present// so a malformed toggle save can't write a non-boolean exposed/requireAuth to// disk (the registry would then silently treat it as its default).diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex b8de39563f..c6d8d9528d 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -834,3 +834,18 @@ CREATE TABLE IF NOT EXISTS writers_room_exercises (finished_at TIMESTAMPTZ);CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work_id, started_at DESC);++-- LoRA training runs (character LoRA training, /api/lora-training). One row+-- per run: id/status/character_id mirrored as columns for filtering, the+-- full record in `data` JSONB. Machine-local — no sync cursor/tombstones+-- (training artifacts live on this machine's disk under data/training-runs/).+CREATE TABLE IF NOT EXISTS lora_training_runs (+ id TEXT PRIMARY KEY,+ status TEXT NOT NULL,+ character_id TEXT,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_lora_training_runs_status ON lora_training_runs (status);+CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_runs (character_id);diff --git a/server/services/backup.js b/server/services/backup.jsindex 740fdca1b4..834e6db0d6 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -44,6 +44,8 @@ export const DEFAULT_EXCLUDES = [{ path: '/cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand', overridable: false },{ path: '/cos/feature-agents/*/worktree/', reason: 'Per-feature-agent git worktrees — recreated on demand', overridable: false },{ path: '/loras/*.safetensors', reason: 'LoRA adapter weight files — large, re-downloadable. .metadata.json sidecars (Civitai metadata, user-editable name/notes) ARE backed up.', overridable: true },+ { path: '/training-runs/*/checkpoints/', reason: 'LoRA training checkpoints — large intermediate adapter state, resumable-but-regenerable. Final trained adapters land in data/loras/ (weights excluded there too); run samples + configs ARE backed up.', overridable: true },+ { path: '/training-runs/*/cache/', reason: 'Precomputed latent/text-embedding training cache — regenerated from the dataset on the next run', overridable: false },{ path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true }diff --git a/server/services/characterLoraResolver.js b/server/services/characterLoraResolver.jsnew file mode 100644index 0000000000..913848f2a9--- /dev/null+++ b/server/services/characterLoraResolver.js@@ -0,0 +1,80 @@+/**+ * Character → trained-LoRA resolution. Always a LOCAL sidecar scan — the+ * character/universe record never stores a LoRA pointer (those records+ * federate; the weights don't). On a peer without the file, listLoras()+ * simply doesn't list it, so resolution degrades to "no LoRA" with no+ * dangling links.+ *+ * Matching: a trained sidecar carries `character: { entryId, ingredientId,+ * universeId, name }`. Canon entries are keyed by per-universe `entryId`+ * AND catalog `ingredientId` — match on either, since some surfaces (the+ * catalog detail page) only know the ingredient id.+ */++import { listLoras } from './loras.js';++const matchesCharacter = (sidecarCharacter, { entryId = null, ingredientId = null }) => {+ if (!sidecarCharacter) return false;+ if (entryId && sidecarCharacter.entryId === entryId) return true;+ if (ingredientId && sidecarCharacter.ingredientId === ingredientId) return true;+ return false;+};++const isCompat = (lora, compatKey) => {+ if (!compatKey) return true;+ if (!lora.loraCompatKey) return false;+ // Bare 'flux2' (size unknown) is compatible with either sized key — same+ // tolerance the picker applies.+ return lora.loraCompatKey === compatKey+ || (compatKey.startsWith('flux2') && lora.loraCompatKey === 'flux2');+};++/**+ * Resolve trained LoRAs for a list of matched canon characters+ * (`[{ id?, ingredientId?, name }]` — pipeline character matches). Caps at+ * `max` so character LoRAs leave stacking room (MAX_LORAS=8) for the+ * user's style LoRAs. Returns+ * `[{ filename, scale, triggerWord, character }]`.+ */+export async function resolveCharacterLoras(matchedCharacters, { compatKey = null, max = 3 } = {}) {+ const characters = (matchedCharacters || []).filter(Boolean);+ if (!characters.length) return [];+ const loras = await listLoras();+ const trained = loras.filter((l) => l.source === 'trained' && l.character);+ const out = [];+ const usedFilenames = new Set();+ for (const character of characters) {+ if (out.length >= max) break;+ const match = trained.find((l) =>+ !usedFilenames.has(l.filename)+ && matchesCharacter(l.character, { entryId: character.id, ingredientId: character.ingredientId })+ && isCompat(l, compatKey));+ if (!match) continue;+ usedFilenames.add(match.filename);+ out.push({+ filename: match.filename,+ scale: Number.isFinite(match.recommendedScale) ? match.recommendedScale : 1.0,+ triggerWord: match.triggerWords?.[0] || null,+ character: match.character,+ });+ }+ return out;+}++/** Single-character variant for UI chips — returns all matches, newest first. */+export async function findLorasByCharacter({ entryId = null, ingredientId = null }) {+ if (!entryId && !ingredientId) return [];+ const loras = await listLoras();+ return loras+ .filter((l) => l.source === 'trained' && matchesCharacter(l.character, { entryId, ingredientId }))+ .map((l) => ({+ filename: l.filename,+ name: l.name,+ loraCompatKey: l.loraCompatKey,+ triggerWords: l.triggerWords,+ recommendedScale: l.recommendedScale,+ character: l.character,+ datasetId: l.trainedFromDatasetId || null,+ installedAt: l.installedAt,+ }));+}diff --git a/server/services/characterLoraResolver.test.js b/server/services/characterLoraResolver.test.jsnew file mode 100644index 0000000000..3bc4c3aa4c--- /dev/null+++ b/server/services/characterLoraResolver.test.js@@ -0,0 +1,89 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const listLoras = vi.fn();+vi.mock('./loras.js', () => ({ listLoras: (...args) => listLoras(...args) }));++const { resolveCharacterLoras, findLorasByCharacter } = await import('./characterLoraResolver.js');++const trainedLora = (overrides = {}) => ({+ filename: 'lora-trained-kessa-3f9a21c0.safetensors',+ name: 'Kessa (trained)',+ source: 'trained',+ character: { entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa' },+ loraCompatKey: 'mflux',+ triggerWords: ['kessa'],+ recommendedScale: 1.0,+ trainedFromDatasetId: 'ds-1',+ installedAt: '2026-06-12T00:00:00Z',+ ...overrides,+});++beforeEach(() => {+ listLoras.mockReset();+});++describe('resolveCharacterLoras', () => {+ it('matches on entryId OR ingredientId', async () => {+ listLoras.mockResolvedValue([trainedLora()]);+ const byEntry = await resolveCharacterLoras([{ id: 'char-1', name: 'Kessa' }]);+ expect(byEntry).toHaveLength(1);+ expect(byEntry[0]).toMatchObject({ filename: trainedLora().filename, triggerWord: 'kessa', scale: 1.0 });+ const byIngredient = await resolveCharacterLoras([{ ingredientId: 'ing-1', name: 'Kessa' }]);+ expect(byIngredient).toHaveLength(1);+ });++ it('ignores non-trained LoRAs and unmatched characters', async () => {+ listLoras.mockResolvedValue([+ trainedLora({ source: null }),+ trainedLora({ filename: 'other.safetensors', character: { entryId: 'char-9' } }),+ ]);+ expect(await resolveCharacterLoras([{ id: 'char-1' }])).toHaveLength(0);+ });++ it('filters by compat key, tolerating bare flux2', async () => {+ listLoras.mockResolvedValue([+ trainedLora({ loraCompatKey: 'flux2-4b' }),+ trainedLora({ filename: 'bare.safetensors', loraCompatKey: 'flux2', character: { entryId: 'char-2' } }),+ ]);+ const out = await resolveCharacterLoras(+ [{ id: 'char-1' }, { id: 'char-2' }],+ { compatKey: 'flux2-4b' },+ );+ expect(out.map((l) => l.filename)).toEqual([trainedLora().filename, 'bare.safetensors']);+ // mflux render: a flux2-trained LoRA must not apply.+ expect(await resolveCharacterLoras([{ id: 'char-1' }], { compatKey: 'mflux' })).toHaveLength(0);+ });++ it('caps at max and never reuses a filename', async () => {+ listLoras.mockResolvedValue(+ ['a', 'b', 'c', 'd'].map((n, i) => trainedLora({+ filename: `${n}.safetensors`,+ character: { entryId: `char-${i}` },+ })),+ );+ const out = await resolveCharacterLoras(+ [0, 1, 2, 3].map((i) => ({ id: `char-${i}` })),+ { max: 3 },+ );+ expect(out).toHaveLength(3);+ });++ it('returns [] for empty matches without touching the lora list', async () => {+ expect(await resolveCharacterLoras([])).toEqual([]);+ expect(listLoras).not.toHaveBeenCalled();+ });+});++describe('findLorasByCharacter', () => {+ it('returns the UI projection for a character', async () => {+ listLoras.mockResolvedValue([trainedLora(), trainedLora({ filename: 'x.safetensors', source: null })]);+ const out = await findLorasByCharacter({ entryId: 'char-1' });+ expect(out).toHaveLength(1);+ expect(out[0]).toMatchObject({ name: 'Kessa (trained)', datasetId: 'ds-1' });+ });++ it('requires at least one id', async () => {+ expect(await findLorasByCharacter({})).toEqual([]);+ expect(listLoras).not.toHaveBeenCalled();+ });+});diff --git a/server/services/loraDatasetCaption.js b/server/services/loraDatasetCaption.jsnew file mode 100644index 0000000000..7cde27d44f--- /dev/null+++ b/server/services/loraDatasetCaption.js@@ -0,0 +1,128 @@+/**+ * LoRA dataset captioning — vision-LLM auto-captions with SSE progress.+ *+ * Sequential loop (vision backends are local; concurrency 1) over the+ * dataset's ready images: read file → base64 data URL →+ * `describeImageDataUrl` (the same provider pathway the voice agent's+ * ui_describe_visually tool uses) → trigger-word prefix → persist.+ * Progress streams over the shared per-job SSE helpers; the client+ * subscribes via `GET /api/lora-datasets/:id/caption-runs/:runId/events`+ * and refetches the dataset on the terminal frame.+ *+ * Provider resolution: request override → `settings.loraTraining.captionProviderId`+ * → 'lmstudio' (the default local vision backend).+ */++import { readFile } from 'fs/promises';+import { ServerError } from '../lib/errorHandler.js';+import { shortId } from '../lib/fileUtils.js';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { prefixCaption } from '../lib/loraDataset.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';+import { describeImageDataUrl } from './visionTest.js';+import { getSettings } from './settings.js';+import { getDataset, updateDataset, datasetImagePath } from './loraDatasets.js';++export const CAPTION_PROMPT = [+ 'Describe the person or character in this image for image-generation training:',+ 'pose, camera angle, expression, clothing, visible accessories, and framing',+ '(full body / bust / close-up). Reply with ONE comma-separated list of short',+ 'fragments. Do not mention art style, the character\'s name, or that this is',+ 'an illustration.',+].join(' ');++const CAPTION_MAX_TOKENS = 300;++// runId → { clients: [], lastPayload } — same shape the imageGen/videoGen+// SSE helpers operate on.+const captionRuns = new Map();++export const attachCaptionSseClient = (runId, res) => attachSse(captionRuns, runId, res);++const emit = (runId, payload) => {+ const run = captionRuns.get(runId);+ if (run) broadcastSse(run, payload);+};++/**+ * Start a caption run. Returns `{ runId, total }` immediately; the loop+ * runs detached. `imageIds` limits the run to specific images (single+ * re-caption = one-element array); `overwrite: false` skips images that+ * already have a caption.+ */+export async function startCaptionRun(datasetId, {+ imageIds = null, providerId = null, model = null, overwrite = false,+} = {}) {+ const dataset = await getDataset(datasetId);+ const wanted = new Set(Array.isArray(imageIds) && imageIds.length ? imageIds : null);+ const targets = dataset.images.filter((img) => {+ if (img.status !== 'ready') return false;+ if (wanted.size && !wanted.has(img.id)) return false;+ if (!overwrite && !wanted.size && img.caption) return false;+ return true;+ });+ if (!targets.length) {+ throw new ServerError('No images to caption (all captioned, or none ready)', {+ status: 409, code: 'LORA_DATASET_NOTHING_TO_CAPTION',+ });+ }++ const settings = await getSettings();+ const resolvedProvider = providerId || settings?.loraTraining?.captionProviderId || 'lmstudio';+ const resolvedModel = model || settings?.loraTraining?.captionModel || undefined;++ const runId = uuidv4();+ captionRuns.set(runId, { clients: [], lastPayload: null });+ console.log(`🏷️ Caption run ${shortId(runId)} — dataset=${shortId(datasetId)} images=${targets.length} provider=${resolvedProvider}`);++ // Detached loop — runs outside the request lifecycle, so each iteration+ // wraps its fallible work in try/catch (the async-boundary exception to+ // the no-try/catch rule) and failures route into the SSE error frames.+ (async () => {+ let done = 0;+ let failed = 0;+ for (const img of targets) {+ let caption = null;+ try {+ const bytes = await readFile(datasetImagePath(datasetId, img.file));+ const dataUrl = `data:image/png;base64,${bytes.toString('base64')}`;+ const text = await describeImageDataUrl({+ dataUrl,+ prompt: CAPTION_PROMPT,+ providerId: resolvedProvider,+ model: resolvedModel,+ maxTokens: CAPTION_MAX_TOKENS,+ });+ caption = prefixCaption(dataset.triggerWord, text);+ } catch (err) {+ failed += 1;+ console.error(`❌ Caption failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);+ emit(runId, { type: 'progress', done, total: targets.length, imageId: img.id, error: String(err?.message || err) });+ continue;+ }+ try {+ await updateDataset(datasetId, (current) => ({+ ...current,+ images: current.images.map((i) => (i.id === img.id+ ? { ...i, caption, captionSource: 'vision', captionedAt: new Date().toISOString() }+ : i)),+ }));+ } catch (err) {+ failed += 1;+ console.error(`❌ Caption persist failed [${shortId(runId)} ${img.id}]: ${err?.message || err}`);+ emit(runId, { type: 'progress', done, total: targets.length, imageId: img.id, error: String(err?.message || err) });+ continue;+ }+ done += 1;+ emit(runId, { type: 'progress', done, total: targets.length, imageId: img.id, caption });+ }+ const terminal = failed && !done+ ? { type: 'error', message: `All ${failed} caption(s) failed — check the vision provider (${resolvedProvider})` }+ : { type: 'complete', done, failed, total: targets.length };+ emit(runId, terminal);+ console.log(`🏷️ Caption run ${shortId(runId)} finished — ${done}/${targets.length} captioned, ${failed} failed`);+ closeJobAfterDelay(captionRuns, runId);+ })();++ return { runId, total: targets.length, provider: resolvedProvider };+}diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.jsnew file mode 100644index 0000000000..2928dfc6de--- /dev/null+++ b/server/services/loraDatasetGenerate.js@@ -0,0 +1,369 @@+/**+ * LoRA dataset generation — reference-material renders + sheet slicing.+ *+ * Builds single-subject training prompts from a character's canon (the+ * inverse of the dense reference-sheet layout: one clean figure on a+ * neutral background per image), enqueues them on the media-job queue, and+ * copies completed renders into the dataset. Also slices an existing+ * reference-sheet turnaround into individual training crops via sharp+ * (fixed grid — the model-generated sheet layout is non-deterministic, so+ * automatic panel detection is deferred; the user prunes bad crops in the+ * dataset grid UI).+ *+ * Mirrors `universeCharacterSheet.js`'s enqueue → single-dispatcher+ * subscribe → copy pattern, including the two-stage queue-wait/run+ * timeout. See that module for the rationale on each piece.+ */++import { copyFile } from 'fs/promises';+import { join, basename } from 'path';+import sharp from 'sharp';+import { PATHS, ensureDir, shortId } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { buildVariationMatrix } from '../lib/loraDataset.js';+import { readSheetPointer, LEGACY_SHEET_VARIANT_ID } from '../lib/storyBible.js';+import { getSettings } from './settings.js';+import { getUniverse } from './universeBuilder.js';+import { buildStyleClause } from './universeCanon.js';+import {+ extractCharacterPromptCommon,+ resolveSheetModelId,+ REFERENCE_SHEET_CONSTANTS,+} from './universeCharacterSheet.js';+import { getImageModels } from '../lib/mediaModels.js';+import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';+import { IMAGE_GEN_MODE } from './imageGen/modes.js';+import {+ datasetImagePath,+ datasetImagesDir,+ getDataset,+ updateDataset,+} from './loraDatasets.js';++// Training images render square — FLUX trains at square resolutions and a+// consistent aspect keeps the latent-precompute path simple.+const DATASET_IMAGE_SIZE = 1024;++const trim = (s) => (typeof s === 'string' ? s.trim() : '');++/**+ * Build the image-gen prompt + negative prompt for ONE dataset image.+ * Leads with the universe style, then the character identity block, then+ * the variation clause, and hard-bans collage/sheet/text artifacts.+ * Pure — exported for tests.+ */+export function buildDatasetImagePrompt(universe, character, variation = {}) {+ const styleClause = buildStyleClause(universe || {});+ const styleBits = styleClause.startsWith('(none provided') ? '' : styleClause;+ const {+ name, role, physical, silhouette, posture, special, visualIdentity,+ paletteLine, wardrobeLine, propsLine,+ } = extractCharacterPromptCommon(character || {});++ const identityBits = [+ `Character: ${name}.`,+ role ? `Role: ${role}.` : '',+ physical ? `Physical description: ${physical}` : '',+ silhouette ? `Silhouette: ${silhouette}` : '',+ posture ? `Posture: ${posture}` : '',+ special ? `Special traits: ${special}` : '',+ visualIdentity ? `Visual identity: ${visualIdentity}` : '',+ paletteLine ? `Color palette: ${paletteLine}.` : '',+ ].filter(Boolean).join(' ');++ const outfitBit = trim(variation.outfit) && variation.outfit !== 'signature outfit'+ ? `wearing ${variation.outfit}`+ : (wardrobeLine ? `wearing their signature wardrobe — ${wardrobeLine}` : 'wearing their signature outfit');++ const variationBits = [+ 'Solo subject',+ trim(variation.view) || 'three-quarter view',+ trim(variation.pose) || 'standing relaxed',+ trim(variation.expression) ? `${variation.expression} expression` : '',+ outfitBit,+ 'full body in frame',+ ].filter(Boolean).join(', ');++ const promptParts = [+ styleBits || 'Style: contemporary illustrated character design with confident line work and saturated, intentional color.',+ identityBits,+ propsLine ? `Signature props (carry or wear where natural): ${propsLine}.` : '',+ `${variationBits}, plain neutral studio background, even lighting, no text, no panels, no labels.`,+ ].filter(Boolean);++ return {+ prompt: promptParts.join('\n\n'),+ negativePrompt: 'multiple people, reference sheet, panel borders, grid, collage, text, labels, watermark, signature, blurry, distorted anatomy, cropped head, cropped feet',+ };+}++/**+ * Derive the expression/outfit variation axes from character canon.+ * Pure — exported for tests.+ */+export function deriveVariationAxes(character) {+ const names = (list) => (Array.isArray(list)+ ? list.map((e) => trim(e?.name)).filter(Boolean)+ : []);+ const expressions = names(character?.expressions);+ const outfits = names(character?.wardrobes);+ return {+ expressions: expressions.length ? expressions : [...REFERENCE_SHEET_CONSTANTS.DEFAULT_EXPRESSIONS],+ outfits: outfits.length ? outfits : ['signature outfit'],+ };+}++// Load the dataset's live canon character (generation + slicing both need+// the current canon, not the dataset's snapshot). 409 when the character+// was deleted from the universe after the dataset was created.+async function loadDatasetCharacter(dataset) {+ const universe = await getUniverse(dataset.character.universeId);+ const characters = Array.isArray(universe.characters) ? universe.characters : [];+ const character = characters.find((c) => c.id === dataset.character.entryId);+ if (!character) {+ throw new ServerError(+ `Character ${dataset.character.entryId} no longer exists in universe ${dataset.character.universeId}`,+ { status: 409, code: 'UNIVERSE_CANON_NOT_FOUND' },+ );+ }+ return { universe, character };+}++// Single-dispatcher subscription on mediaJobEvents — same shape as+// universeCharacterSheet's sheetSubscribers so N pending dataset renders+// attach 3 module-level listeners total instead of 3*N.+const datasetSubscribers = new Map(); // jobId → { onStarted, onCompleted, onFailed }+let _listenersAttached = false;+function ensureDispatchListeners() {+ if (_listenersAttached) return;+ _listenersAttached = true;+ mediaJobEvents.on('started', (job) => datasetSubscribers.get(job?.id)?.onStarted?.(job));+ mediaJobEvents.on('completed', (job) => datasetSubscribers.get(job?.id)?.onCompleted?.(job));+ const onTerminal = (job) => datasetSubscribers.get(job?.id)?.onFailed?.(job);+ mediaJobEvents.on('failed', onTerminal);+ mediaJobEvents.on('canceled', onTerminal);+}+function subscribeToDatasetJob(jobId, handlers) {+ ensureDispatchListeners();+ datasetSubscribers.set(jobId, handlers);+ return () => { datasetSubscribers.delete(jobId); };+}++const QUEUE_WAIT_MS = 4 * 60 * 60 * 1000; // survives queueing behind long video jobs+const RUN_TIMEOUT_MS = 30 * 60 * 1000;++const setImageStatus = (datasetId, imageId, status) =>+ updateDataset(datasetId, (current) => ({+ ...current,+ images: current.images.map((img) => (img.id === imageId ? { ...img, status } : img)),+ })).catch((err) => {+ console.error(`❌ Dataset ${datasetId} image ${imageId} status→${status} failed: ${err?.message}`);+ });++async function onRenderComplete({ datasetId, imageId, file, sourceFilename }) {+ if (!sourceFilename) {+ await setImageStatus(datasetId, imageId, 'failed');+ return;+ }+ await ensureDir(datasetImagesDir(datasetId));+ const srcPath = join(PATHS.images, basename(sourceFilename));+ await copyFile(srcPath, datasetImagePath(datasetId, file));+ await setImageStatus(datasetId, imageId, 'ready');+ console.log(`📸 Dataset ${shortId(datasetId)} ← render ${file}`);+}++/**+ * Resolve the render mode + base job params from current settings — the+ * same mode contract as the reference-sheet renderer (codex and local are+ * first-class; external SD-API is rejected with remediation).+ */+async function resolveRenderParams({ modelId: modelOverride = null } = {}) {+ const settings = await getSettings();+ const activeMode = settings.imageGen?.mode || IMAGE_GEN_MODE.LOCAL;+ const base = {+ mode: activeMode,+ width: DATASET_IMAGE_SIZE,+ height: DATASET_IMAGE_SIZE,+ cleanC2PA: true,+ denoise: false,+ };+ if (activeMode === IMAGE_GEN_MODE.CODEX) {+ const c = settings.imageGen?.codex || {};+ if (!c.enabled) {+ throw new ServerError(+ 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',+ { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },+ );+ }+ return { base: { ...base, codexPath: c.codexPath, model: c.model }, activeMode, modelId: c.model || 'codex' };+ }+ if (activeMode === IMAGE_GEN_MODE.LOCAL) {+ const allModels = getImageModels();+ const modelId = resolveSheetModelId({ override: modelOverride, settings, allModels });+ if (!modelId) {+ throw new ServerError(+ 'No local image-gen models are registered. Install a model via `bash scripts/setup-image-video.sh` before generating dataset images.',+ { status: 400, code: 'LORA_DATASET_NO_MODEL' },+ );+ }+ return {+ base: { ...base, pythonPath: settings.imageGen?.local?.pythonPath || null, modelId },+ activeMode,+ modelId,+ };+ }+ throw new ServerError(+ `Dataset generation needs codex or local image-gen mode (currently: ${activeMode}). Switch in Settings → Image Gen.`,+ { status: 400, code: 'LORA_DATASET_UNSUPPORTED_MODE' },+ );+}++/**+ * Generate `count` reference images for the dataset's character. Appends a+ * `rendering` image entry per variation, enqueues each render on the image+ * queue, and flips entries to `ready` (with the file copied in) as jobs+ * complete. Returns `{ images: [{ imageId, jobId, variation }], mode, modelId }`+ * immediately — the client tracks per-image progress by refetching.+ */+export async function generateDatasetImages(datasetId, options = {}) {+ const dataset = await getDataset(datasetId);+ const { universe, character } = await loadDatasetCharacter(dataset);++ const axes = deriveVariationAxes(character);+ const variations = buildVariationMatrix({+ count: options.count,+ views: options.views,+ poses: options.poses,+ expressions: options.expressions || axes.expressions,+ outfits: options.outfits || axes.outfits,+ });++ const { base, activeMode, modelId } = await resolveRenderParams(options);++ const launched = [];+ for (const variation of variations) {+ const imageId = uuidv4();+ const file = `${imageId}.png`;+ const { prompt, negativePrompt } = buildDatasetImagePrompt(universe, character, variation);+ const queued = enqueueJob({ kind: 'image', params: { ...base, prompt, negativePrompt } });+ const jobId = queued.jobId;++ const entry = {+ id: imageId,+ file,+ caption: '',+ captionSource: null,+ captionedAt: null,+ source: 'generated',+ sourceJobId: jobId,+ variation,+ status: 'rendering',+ width: DATASET_IMAGE_SIZE,+ height: DATASET_IMAGE_SIZE,+ createdAt: new Date().toISOString(),+ };+ await updateDataset(datasetId, (current) => ({ ...current, images: [...current.images, entry] }));++ let timeoutHandle = null;+ let unsubscribe = null;+ const armTimeout = (ms, reason) => {+ if (timeoutHandle) clearTimeout(timeoutHandle);+ timeoutHandle = setTimeout(() => {+ console.log(`⏱️ Dataset render ${reason} [${shortId(jobId)}] — detaching (reconcile heals on next read)`);+ detach();+ }, ms);+ timeoutHandle.unref?.();+ };+ const detach = () => {+ if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }+ if (unsubscribe) { unsubscribe(); unsubscribe = null; }+ };+ unsubscribe = subscribeToDatasetJob(jobId, {+ onStarted: () => armTimeout(RUN_TIMEOUT_MS, 'exceeded run window'),+ onCompleted: async (job) => {+ detach();+ await onRenderComplete({+ datasetId, imageId, file, sourceFilename: job.result?.filename,+ }).catch((err) => {+ console.error(`❌ Dataset render post-completion failed [${shortId(jobId)}]: ${err?.message}`);+ });+ },+ onFailed: async (job) => {+ detach();+ console.log(`⚠️ Dataset render ${job.status} [${shortId(jobId)}]: ${job.error || 'unknown'}`);+ await setImageStatus(datasetId, imageId, 'failed');+ },+ });+ armTimeout(QUEUE_WAIT_MS, 'queue-wait timeout');++ launched.push({ imageId, jobId, variation });+ }++ console.log(`🎨 Dataset ${shortId(datasetId)} generation batch — ${launched.length} render(s), mode=${activeMode}, model=${modelId}`);+ return { images: launched, mode: activeMode, modelId };+}++/**+ * Slice the character's existing reference-sheet turnaround into a fixed+ * `cols × rows` grid of training crops. Each crop lands as a `ready`+ * dataset image with source 'refsheet-slice' — the user prunes bad crops+ * (label strips, palette swatches) in the grid UI.+ */+export async function sliceReferenceSheet(datasetId, { variant = LEGACY_SHEET_VARIANT_ID, cols = 3, rows = 2 } = {}) {+ const dataset = await getDataset(datasetId);+ const { character } = await loadDatasetCharacter(dataset);+ const sheetFilename = readSheetPointer(character, variant);+ if (!sheetFilename) {+ throw new ServerError(+ `Character "${character.name}" has no ${variant} reference sheet — render one first`,+ { status: 409, code: 'LORA_DATASET_NO_SHEET' },+ );+ }++ const sheetPath = join(PATHS.imageRefs, basename(sheetFilename));+ const image = sharp(sheetPath);+ const meta = await image.metadata().catch((err) => {+ throw new ServerError(`Reference sheet unreadable: ${err?.message || err}`, {+ status: 422, code: 'INVALID_IMAGE',+ });+ });+ const cellW = Math.floor(meta.width / cols);+ const cellH = Math.floor(meta.height / rows);+ if (cellW < 64 || cellH < 64) {+ throw new ServerError(+ `Grid ${cols}×${rows} produces cells smaller than 64px on this sheet (${meta.width}×${meta.height})`,+ { status: 400, code: 'VALIDATION_ERROR' },+ );+ }++ await ensureDir(datasetImagesDir(datasetId));+ const entries = [];+ for (let r = 0; r < rows; r += 1) {+ for (let c = 0; c < cols; c += 1) {+ const imageId = uuidv4();+ const file = `${imageId}.png`;+ await sharp(sheetPath)+ .extract({ left: c * cellW, top: r * cellH, width: cellW, height: cellH })+ .png()+ .toFile(datasetImagePath(datasetId, file));+ entries.push({+ id: imageId,+ file,+ caption: '',+ captionSource: null,+ captionedAt: null,+ source: 'refsheet-slice',+ sourceJobId: null,+ variation: null,+ status: 'ready',+ width: cellW,+ height: cellH,+ createdAt: new Date().toISOString(),+ });+ }+ }+ await updateDataset(datasetId, (current) => ({ ...current, images: [...current.images, ...entries] }));+ console.log(`✂️ Dataset ${shortId(datasetId)} ← ${entries.length} crops from ${basename(sheetFilename)} (${cols}×${rows})`);+ return { images: entries, sheet: basename(sheetFilename) };+}diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.jsnew file mode 100644index 0000000000..065619ec4d--- /dev/null+++ b/server/services/loraDatasets.js@@ -0,0 +1,300 @@+/**+ * LoRA training datasets — collectionStore CRUD + image file management.+ *+ * One dataset per universe character (find-or-create keyed on+ * `(universeId, entryId)`), stored machine-locally at+ * `data/lora-datasets/<id>/index.json` with image bytes at+ * `data/lora-datasets/<id>/images/<imageId>.png`. Datasets never federate+ * — like `data/loras/` itself, they organize artifacts tied to this+ * machine's GPU output (see docs/STORAGE.md).+ *+ * Generation (batch renders via the media-job queue) lives in+ * `loraDatasetGenerate.js`; vision captioning in `loraDatasetCaption.js`;+ * pure helpers in `lib/loraDataset.js`.+ */++import { copyFile, unlink } from 'fs/promises';+import { join, basename } from 'path';+import sharp from 'sharp';+import { PATHS, ensureDir } from '../lib/fileUtils.js';+import { createCollectionStore } from '../lib/collectionStore.js';+import {+ LORA_DATASET_SCHEMA_VERSION,+ computeDatasetReadiness,+ deriveTriggerWord,+ isValidTriggerWord,+ sanitizeLoraDataset,+} from '../lib/loraDataset.js';+import { ServerError } from '../lib/errorHandler.js';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { getUniverse } from './universeBuilder.js';+import { getJob } from './mediaJobQueue/index.js';++export const loraDatasetStore = createCollectionStore({+ dir: PATHS.loraDatasets,+ type: 'lora-datasets',+ schemaVersion: LORA_DATASET_SCHEMA_VERSION,+ sanitizeRecord: sanitizeLoraDataset,+});++export const datasetImagesDir = (datasetId) => join(loraDatasetStore.recordDir(datasetId), 'images');+export const datasetImagePath = (datasetId, file) => join(datasetImagesDir(datasetId), file);++const nowIso = () => new Date().toISOString();++const requireDataset = async (id) => {+ const dataset = await loraDatasetStore.loadOne(id);+ if (!dataset) {+ throw new ServerError(`LoRA dataset not found: ${id}`, { status: 404, code: 'NOT_FOUND' });+ }+ return dataset;+};++/**+ * Read-modify-write a dataset inside its per-id write queue so concurrent+ * mutations (caption blur-save + render-completion hook) merge against the+ * freshest persisted record. `mutate` receives the sanitized record and+ * returns the next record (or null to abort without writing).+ */+export async function updateDataset(id, mutate) {+ return loraDatasetStore.queueRecordWrite(id, async () => {+ const current = await loraDatasetStore.loadOne(id);+ if (!current) {+ throw new ServerError(`LoRA dataset not found: ${id}`, { status: 404, code: 'NOT_FOUND' });+ }+ const next = await mutate(current);+ if (!next) return current;+ next.updatedAt = nowIso();+ await loraDatasetStore.saveOneNow(id, next);+ return next;+ });+}++const summarize = (dataset) => ({+ id: dataset.id,+ character: dataset.character,+ triggerWord: dataset.triggerWord,+ status: dataset.status,+ readiness: computeDatasetReadiness(dataset),+ // First few image files for the list page's thumb strip.+ thumbnails: dataset.images+ .filter((img) => img.status === 'ready')+ .slice(0, 4)+ .map((img) => img.file),+ training: dataset.training,+ createdAt: dataset.createdAt,+ updatedAt: dataset.updatedAt,+});++export async function listDatasets({ universeId = null, entryId = null, ingredientId = null } = {}) {+ const all = await loraDatasetStore.loadAll();+ const filtered = all.filter((d) => {+ if (universeId && d.character.universeId !== universeId) return false;+ if (entryId && d.character.entryId !== entryId) return false;+ if (ingredientId && d.character.ingredientId !== ingredientId) return false;+ return true;+ });+ return filtered+ .map(summarize)+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));+}++export async function getDataset(id) {+ const dataset = await requireDataset(id);+ return { ...dataset, readiness: computeDatasetReadiness(dataset) };+}++/**+ * Find-or-create the dataset for one universe character. Validates the+ * character exists in the universe and snapshots its identity (entryId ++ * catalog ingredientId + name) into the record. Returns `{ dataset, created }`.+ */+export async function createDataset({ universeId, entryId, triggerWord = null }) {+ const universe = await getUniverse(universeId);+ const characters = Array.isArray(universe.characters) ? universe.characters : [];+ const character = characters.find((c) => c.id === entryId);+ if (!character) {+ throw new ServerError(`Character ${entryId} not found in universe`, {+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',+ });+ }++ const existingAll = await loraDatasetStore.loadAll();+ const existing = existingAll.find(+ (d) => d.character.universeId === universeId && d.character.entryId === entryId,+ );+ if (existing) return { dataset: { ...existing, readiness: computeDatasetReadiness(existing) }, created: false };++ if (triggerWord != null && !isValidTriggerWord(triggerWord)) {+ throw new ServerError('Trigger word must be 2-64 chars of [a-z0-9_]', {+ status: 400, code: 'VALIDATION_ERROR',+ });+ }+ const taken = existingAll.map((d) => d.triggerWord).filter(Boolean);+ const resolvedTrigger = triggerWord || deriveTriggerWord(character.name, { taken });++ const id = uuidv4();+ const record = sanitizeLoraDataset({+ schemaVersion: LORA_DATASET_SCHEMA_VERSION,+ id,+ character: {+ entryId,+ ingredientId: character.ingredientId || null,+ universeId,+ name: character.name,+ },+ triggerWord: resolvedTrigger,+ status: 'draft',+ images: [],+ training: {},+ createdAt: nowIso(),+ updatedAt: nowIso(),+ });+ await loraDatasetStore.saveOne(id, record);+ await ensureDir(datasetImagesDir(id));+ console.log(`🧬 Created LoRA dataset ${id} for character "${character.name}" (trigger=${resolvedTrigger})`);+ return { dataset: { ...record, readiness: computeDatasetReadiness(record) }, created: true };+}++export async function patchDataset(id, { triggerWord } = {}) {+ if (triggerWord !== undefined && !isValidTriggerWord(triggerWord)) {+ throw new ServerError('Trigger word must be 2-64 chars of [a-z0-9_]', {+ status: 400, code: 'VALIDATION_ERROR',+ });+ }+ return updateDataset(id, (current) => {+ if (triggerWord === undefined || triggerWord === current.triggerWord) return null;+ return { ...current, triggerWord };+ });+}++export async function deleteDataset(id) {+ await requireDataset(id);+ // deleteOne removes the whole `lora-datasets/<id>/` subtree — record AND+ // the images/ sidecar dir go together.+ await loraDatasetStore.deleteOne(id);+ console.log(`🗑️ Deleted LoRA dataset ${id}`);+ return { ok: true, id };+}++/**+ * Normalize an uploaded image to PNG inside the dataset's images dir and+ * append its entry. `tmpPath` is the multipart parser's staged temp file —+ * always unlinked, success or failure.+ */+export async function addUploadedImage(id, { tmpPath, originalname = '' }) {+ await requireDataset(id);+ const imageId = uuidv4();+ const file = `${imageId}.png`;+ await ensureDir(datasetImagesDir(id));+ const destPath = datasetImagePath(id, file);+ const cleanup = () => unlink(tmpPath).catch(() => {});+ const info = await sharp(tmpPath).rotate().png().toFile(destPath).catch(async (err) => {+ await cleanup();+ throw new ServerError(+ `"${originalname || 'upload'}" is not a decodable image: ${err?.message || err}`,+ { status: 422, code: 'INVALID_IMAGE' },+ );+ });+ await cleanup();+ const width = info.width || null;+ const height = info.height || null;++ const entry = {+ id: imageId,+ file,+ caption: '',+ captionSource: null,+ captionedAt: null,+ source: 'upload',+ sourceJobId: null,+ variation: null,+ status: 'ready',+ width,+ height,+ createdAt: nowIso(),+ };+ await updateDataset(id, (current) => ({ ...current, images: [...current.images, entry] }));+ console.log(`📥 Dataset ${id} ← upload ${file} (${width}×${height})`);+ return entry;+}++export async function updateImageCaption(id, imageId, caption) {+ const next = await updateDataset(id, (current) => {+ if (!current.images.some((img) => img.id === imageId)) {+ throw new ServerError(`Image ${imageId} not found in dataset`, { status: 404, code: 'NOT_FOUND' });+ }+ return {+ ...current,+ images: current.images.map((img) => (img.id === imageId+ ? { ...img, caption, captionSource: 'manual', captionedAt: nowIso() }+ : img)),+ };+ });+ return next.images.find((img) => img.id === imageId);+}++export async function deleteImage(id, imageId) {+ let removed = null;+ await updateDataset(id, (current) => {+ removed = current.images.find((img) => img.id === imageId) || null;+ if (!removed) {+ throw new ServerError(`Image ${imageId} not found in dataset`, { status: 404, code: 'NOT_FOUND' });+ }+ return { ...current, images: current.images.filter((img) => img.id !== imageId) };+ });+ await unlink(datasetImagePath(id, removed.file)).catch(() => {});+ return { ok: true, imageId };+}++/**+ * Read-time healer for images stuck in `rendering`. The generation hook+ * normally flips them on the media-job 'completed' event, but a server+ * restart drops that in-memory subscription (the queue marks interrupted+ * jobs failed on boot). For each rendering image, consult the job archive:+ * completed → copy the result into the dataset + mark ready; failed /+ * canceled / unknown → mark failed. Returns the (possibly updated) record.+ *+ * `jobLookup` is injectable for tests; defaults to the queue's getJob.+ */+export async function reconcileRenderingImages(id, { jobLookup = getJob } = {}) {+ const dataset = await requireDataset(id);+ const pending = dataset.images.filter((img) => img.status === 'rendering');+ if (!pending.length) return dataset;++ const resolutions = new Map(); // imageId → { status, sourceFilename? , dims? }+ for (const img of pending) {+ const job = img.sourceJobId ? jobLookup(img.sourceJobId) : null;+ if (!job || job.status === 'failed' || job.status === 'canceled') {+ resolutions.set(img.id, { status: 'failed' });+ } else if (job.status === 'completed' && job.result?.filename) {+ resolutions.set(img.id, { status: 'ready', sourceFilename: job.result.filename });+ }+ // queued/running jobs stay 'rendering' — the live hook will land them.+ }+ if (!resolutions.size) return dataset;++ for (const [imageId, res] of resolutions) {+ if (res.status !== 'ready') continue;+ const img = pending.find((p) => p.id === imageId);+ await ensureDir(datasetImagesDir(id));+ // basename() so a hand-edited media-jobs.json filename can't traverse+ // out of the gallery (mirrors onRenderComplete in loraDatasetGenerate).+ await copyFile(join(PATHS.images, basename(res.sourceFilename)), datasetImagePath(id, img.file))+ .catch((err) => {+ console.error(`❌ Dataset ${id} reconcile copy failed [${imageId}]: ${err?.message}`);+ resolutions.set(imageId, { status: 'failed' });+ });+ }++ const updated = await updateDataset(id, (current) => ({+ ...current,+ images: current.images.map((img) => {+ const res = resolutions.get(img.id);+ return res ? { ...img, status: res.status } : img;+ }),+ }));+ const healed = [...resolutions.values()];+ console.log(`🩹 Dataset ${id} reconciled ${healed.length} rendering image(s) (${healed.filter((r) => r.status === 'ready').length} ready)`);+ return updated;+}diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.jsnew file mode 100644index 0000000000..01e96f1933--- /dev/null+++ b/server/services/loraDatasets.test.js@@ -0,0 +1,214 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, existsSync } from 'fs';+import { writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import sharp from 'sharp';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'lora-datasets-test-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), {+ dataRoot: TEST_DATA_ROOT,+ extraOverrides: (root) => ({+ loraDatasets: join(root, 'lora-datasets'),+ images: join(root, 'images'),+ }),+ }));++const getUniverse = vi.fn();+vi.mock('./universeBuilder.js', () => ({ getUniverse: (...args) => getUniverse(...args) }));+vi.mock('./mediaJobQueue/index.js', () => ({+ getJob: vi.fn(() => null),+ enqueueJob: vi.fn(),+ mediaJobEvents: { on: vi.fn() },+}));++const {+ addUploadedImage,+ createDataset,+ deleteDataset,+ deleteImage,+ datasetImagePath,+ getDataset,+ listDatasets,+ patchDataset,+ reconcileRenderingImages,+ updateDataset,+ updateImageCaption,+} = await import('./loraDatasets.js');++const UNIVERSE = {+ id: 'uni-1',+ name: 'Testverse',+ characters: [+ { id: 'char-1', ingredientId: 'ing-1', name: 'Kessa Brightwater' },+ { id: 'char-2', ingredientId: null, name: 'Moss' },+ ],+};++const makePng = (path, size = 64) => sharp({+ create: { width: size, height: size, channels: 3, background: { r: 200, g: 100, b: 50 } },+}).png().toFile(path);++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ getUniverse.mockReset();+ getUniverse.mockResolvedValue(UNIVERSE);+});++describe('createDataset', () => {+ it('creates with a derived trigger word and character snapshot', async () => {+ const { dataset, created } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ expect(created).toBe(true);+ expect(dataset.triggerWord).toBe('kessa_brightwater');+ expect(dataset.character).toEqual({+ entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa Brightwater',+ });+ expect(dataset.readiness.trainable).toBe(false);+ });++ it('is find-or-create per (universeId, entryId)', async () => {+ const first = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const second = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ expect(second.created).toBe(false);+ expect(second.dataset.id).toBe(first.dataset.id);+ });++ it('avoids trigger-word collisions across datasets', async () => {+ await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ getUniverse.mockResolvedValue({+ ...UNIVERSE,+ characters: [...UNIVERSE.characters, { id: 'char-3', name: 'Kessa Brightwater' }],+ });+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-3' });+ expect(dataset.triggerWord).toBe('kessa_brightwater2');+ });++ it('404s for a character missing from the universe', async () => {+ await expect(createDataset({ universeId: 'uni-1', entryId: 'nope' }))+ .rejects.toMatchObject({ status: 404 });+ });+});++describe('patchDataset / listDatasets', () => {+ it('updates trigger word and rejects invalid ones', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const next = await patchDataset(dataset.id, { triggerWord: 'kessa_v2' });+ expect(next.triggerWord).toBe('kessa_v2');+ await expect(patchDataset(dataset.id, { triggerWord: 'Bad Word!' }))+ .rejects.toMatchObject({ status: 400 });+ });++ it('filters list by character ids', async () => {+ await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ await createDataset({ universeId: 'uni-1', entryId: 'char-2' });+ expect(await listDatasets()).toHaveLength(2);+ expect(await listDatasets({ entryId: 'char-1' })).toHaveLength(1);+ expect(await listDatasets({ ingredientId: 'ing-1' })).toHaveLength(1);+ expect(await listDatasets({ universeId: 'other' })).toHaveLength(0);+ });+});++describe('images', () => {+ it('normalizes uploads to PNG and records dimensions', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const tmpPath = join(TEST_DATA_ROOT, 'upload.jpg');+ await sharp({ create: { width: 80, height: 60, channels: 3, background: '#888' } })+ .jpeg().toFile(tmpPath);+ const entry = await addUploadedImage(dataset.id, { tmpPath, originalname: 'photo.jpg' });+ expect(entry.source).toBe('upload');+ expect(entry.status).toBe('ready');+ expect(entry.width).toBe(80);+ expect(entry.height).toBe(60);+ expect(existsSync(datasetImagePath(dataset.id, entry.file))).toBe(true);+ expect(existsSync(tmpPath)).toBe(false); // staged temp always cleaned+ });++ it('422s on non-image uploads and cleans the temp file', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const tmpPath = join(TEST_DATA_ROOT, 'not-an-image.png');+ await writeFile(tmpPath, 'plain text');+ await expect(addUploadedImage(dataset.id, { tmpPath, originalname: 'x.png' }))+ .rejects.toMatchObject({ status: 422 });+ expect(existsSync(tmpPath)).toBe(false);+ });++ it('edits captions as manual and deletes images with their files', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const tmpPath = join(TEST_DATA_ROOT, 'u.png');+ await makePng(tmpPath);+ const entry = await addUploadedImage(dataset.id, { tmpPath });++ const updated = await updateImageCaption(dataset.id, entry.id, 'kessa_brightwater, side profile');+ expect(updated.captionSource).toBe('manual');+ expect(updated.caption).toContain('side profile');++ await deleteImage(dataset.id, entry.id);+ const after = await getDataset(dataset.id);+ expect(after.images).toHaveLength(0);+ expect(existsSync(datasetImagePath(dataset.id, entry.file))).toBe(false);+ });++ it('404s caption edits for unknown images', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ await expect(updateImageCaption(dataset.id, 'ghost', 'x'))+ .rejects.toMatchObject({ status: 404 });+ });+});++describe('reconcileRenderingImages', () => {+ const seedRendering = async (jobId) => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ await updateDataset(dataset.id, (current) => ({+ ...current,+ images: [{+ id: 'img-r', file: 'img-r.png', caption: '', captionSource: null, captionedAt: null,+ source: 'generated', sourceJobId: jobId, variation: null, status: 'rendering',+ width: 1024, height: 1024, createdAt: new Date().toISOString(),+ }],+ }));+ return dataset.id;+ };++ it('copies completed renders in and marks ready', async () => {+ const id = await seedRendering('job-1');+ mkdirSync(join(TEST_DATA_ROOT, 'images'), { recursive: true });+ await makePng(join(TEST_DATA_ROOT, 'images', 'job-1.png'));+ const out = await reconcileRenderingImages(id, {+ jobLookup: () => ({ status: 'completed', result: { filename: 'job-1.png' } }),+ });+ expect(out.images[0].status).toBe('ready');+ expect(existsSync(datasetImagePath(id, 'img-r.png'))).toBe(true);+ });++ it('marks failed when the job is gone or failed', async () => {+ const id = await seedRendering('job-2');+ const out = await reconcileRenderingImages(id, { jobLookup: () => null });+ expect(out.images[0].status).toBe('failed');+ });++ it('leaves queued/running jobs as rendering', async () => {+ const id = await seedRendering('job-3');+ const out = await reconcileRenderingImages(id, {+ jobLookup: () => ({ status: 'running' }),+ });+ expect(out.images[0].status).toBe('rendering');+ });+});++describe('deleteDataset', () => {+ it('removes the record and its images dir', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const tmpPath = join(TEST_DATA_ROOT, 'd.png');+ await makePng(tmpPath);+ await addUploadedImage(dataset.id, { tmpPath });+ await deleteDataset(dataset.id);+ expect(existsSync(join(TEST_DATA_ROOT, 'lora-datasets', dataset.id))).toBe(false);+ await expect(getDataset(dataset.id)).rejects.toMatchObject({ status: 404 });+ });+});diff --git a/server/services/loraTraining/dataset.js b/server/services/loraTraining/dataset.jsnew file mode 100644index 0000000000..e00f9571fe--- /dev/null+++ b/server/services/loraTraining/dataset.js@@ -0,0 +1,55 @@+/**+ * Dataset readiness validation for training launch. Re-checked both at+ * route time (fast 409 before a run record exists) and at run start+ * (defense vs. the dataset being deleted/edited while queued).+ */++import { access } from 'fs/promises';+import { ServerError } from '../../lib/errorHandler.js';+import { computeDatasetReadiness } from '../../lib/loraDataset.js';+import { getDataset, datasetImagePath, datasetImagesDir } from '../loraDatasets.js';++/**+ * Load + validate the dataset, returning `{ dataset, manifest }` where+ * manifest is the trainer-facing image list:+ * `{ triggerWord, imagesDir, images: [{ file, path, caption }] }`.+ */+export async function validateDatasetReady(datasetId) {+ const dataset = await getDataset(datasetId);+ const readiness = computeDatasetReadiness(dataset);+ if (!readiness.trainable) {+ throw new ServerError(+ `Dataset is not ready to train — needs ≥${readiness.required} ready images captioned with the trigger word `+ + `(have ${readiness.captioned}/${readiness.required}${readiness.rendering ? `, ${readiness.rendering} still rendering` : ''})`,+ { status: 409, code: 'DATASET_NOT_READY' },+ );+ }+ const trainImages = dataset.images.filter((img) => {+ if (img.status !== 'ready') return false;+ const caption = (img.caption || '').trim();+ return caption && caption.toLowerCase().includes(dataset.triggerWord.toLowerCase());+ });+ // Every file must actually exist on disk — a missing file at trainer+ // start would fail minutes later with an opaque python traceback.+ for (const img of trainImages) {+ const path = datasetImagePath(datasetId, img.file);+ await access(path).catch(() => {+ throw new ServerError(+ `Dataset image missing on disk: ${img.file} — delete it from the dataset and retry`,+ { status: 409, code: 'DATASET_NOT_READY' },+ );+ });+ }+ return {+ dataset,+ manifest: {+ triggerWord: dataset.triggerWord,+ imagesDir: datasetImagesDir(datasetId),+ images: trainImages.map((img) => ({+ file: img.file,+ path: datasetImagePath(datasetId, img.file),+ caption: img.caption.trim(),+ })),+ },+ };+}diff --git a/server/services/loraTraining/db.js b/server/services/loraTraining/db.jsnew file mode 100644index 0000000000..5894e096be--- /dev/null+++ b/server/services/loraTraining/db.js@@ -0,0 +1,91 @@+/**+ * LoRA training run records — PostgreSQL adapter (`lora_training_runs`).+ *+ * One row per run: id/status/character_id mirrored as columns for+ * filtering, the full record in `data` JSONB (returned verbatim — columns+ * are never read back). Single writer (the training service) per run, so+ * plain read-modify-write suffices; no row locking needed. Mirrors the+ * `creative_director_projects` adapter pattern.+ */++import { query } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';++const rowToRun = (row) => row?.data ?? null;++async function persist(run) {+ await query(+ `INSERT INTO lora_training_runs (id, status, character_id, data, created_at, updated_at)+ VALUES ($1, $2, $3, $4::jsonb, $5, $6)+ ON CONFLICT (id) DO UPDATE SET+ status = EXCLUDED.status,+ character_id = EXCLUDED.character_id,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at`,+ [+ run.id,+ run.status,+ run.character?.entryId || null,+ JSON.stringify(run),+ run.createdAt || new Date().toISOString(),+ new Date().toISOString(),+ ],+ );+ return run;+}++export async function createRun(run) {+ return persist(run);+}++export async function getRun(id) {+ const result = await query('SELECT data FROM lora_training_runs WHERE id = $1', [id]);+ return rowToRun(result.rows[0]);+}++export async function getRunRequired(id) {+ const run = await getRun(id);+ if (!run) {+ throw new ServerError(`Training run not found: ${id}`, { status: 404, code: 'NOT_FOUND' });+ }+ return run;+}++/** Read-modify-write. `patch` is an object merged shallowly, or a function. */+export async function updateRun(id, patch) {+ const current = await getRunRequired(id);+ const next = typeof patch === 'function' ? patch(current) : { ...current, ...patch };+ if (!next) return current;+ next.updatedAt = new Date().toISOString();+ return persist(next);+}++export async function listRuns({ status = null, characterId = null, datasetId = null, limit = 50 } = {}) {+ const where = [];+ const params = [];+ if (status) { params.push(status); where.push(`status = $${params.length}`); }+ if (characterId) { params.push(characterId); where.push(`character_id = $${params.length}`); }+ if (datasetId) { params.push(datasetId); where.push(`data->>'datasetId' = $${params.length}`); }+ params.push(Math.max(1, Math.min(500, limit)));+ const result = await query(+ `SELECT data FROM lora_training_runs+ ${where.length ? `WHERE ${where.join(' AND ')}` : ''}+ ORDER BY created_at DESC+ LIMIT $${params.length}`,+ params,+ );+ return result.rows.map(rowToRun).filter(Boolean);+}++export async function deleteRun(id) {+ await query('DELETE FROM lora_training_runs WHERE id = $1', [id]);+ return { ok: true, id };+}++/** Runs persisted as queued/running — boot-time reconcile targets. */+export async function listActiveRuns() {+ const result = await query(+ `SELECT data FROM lora_training_runs WHERE status IN ('queued', 'running')`,+ );+ return result.rows.map(rowToRun).filter(Boolean);+}diff --git a/server/services/loraTraining/events.js b/server/services/loraTraining/events.jsnew file mode 100644index 0000000000..45d9d54781--- /dev/null+++ b/server/services/loraTraining/events.js@@ -0,0 +1,6 @@+// Shared emitter for LoRA training progress — mirrors videoGen/events.js.+// mediaJobQueue's dispatcher subscribes to 'progress'/'status'/'completed'/+// 'failed' (+ 'activity' for the idle watchdog) filtered by generationId.+import { EventEmitter } from 'events';++export const trainingEvents = new EventEmitter();diff --git a/server/services/loraTraining/failure.js b/server/services/loraTraining/failure.jsnew file mode 100644index 0000000000..539f3570f8--- /dev/null+++ b/server/services/loraTraining/failure.js@@ -0,0 +1,45 @@+/**+ * Trainer failure classification — pure. Maps a dead child's stderr tail ++ * exit code/signal (+ any USER_ERROR the line handler captured) to a+ * stable `{ code, message }` the run record and SSE error frame carry.+ */++const OOM_RE = /MPS backend out of memory|CUDA out of memory|Insufficient Memory|Metal.*out of memory|std::bad_alloc/i;+const MODULE_NOT_FOUND_RE = /ModuleNotFoundError|No module named/i;+const HF_AUTH_RE = /GatedRepoError|401 Client Error|Repo.*is gated|Access to model .* is restricted/i;++export function classifyTrainingFailure({ stderrTail = [], exitCode = null, signal = null, userError = null } = {}) {+ if (userError?.message) {+ return { code: userError.kind || 'DATASET_ERROR', message: userError.message };+ }+ const tail = stderrTail.join('\n');+ if (OOM_RE.test(tail)) {+ return {+ code: 'OOM',+ message: 'Training ran out of memory — lower the resolution (512), reduce rank, or switch to a smaller base model.',+ };+ }+ if (MODULE_NOT_FOUND_RE.test(tail)) {+ return {+ code: 'MODULE_NOT_FOUND',+ message: 'Python environment is missing training packages — re-run `bash scripts/setup-image-video.sh` to repair the venv.',+ };+ }+ if (HF_AUTH_RE.test(tail)) {+ return {+ code: 'HF_AUTH',+ message: 'Hugging Face rejected the model download — set HUGGINGFACE_API_KEY and accept the model license on huggingface.co.',+ };+ }+ if (signal === 'SIGKILL') {+ return {+ code: 'KILLED',+ message: 'Trainer was killed (likely the OS reclaiming memory) — lower resolution/rank or free up RAM.',+ };+ }+ const lastLines = stderrTail.slice(-5).join(' · ');+ return {+ code: 'TRAINING_FAILED',+ message: `Training exited with code ${exitCode ?? 'unknown'}${signal ? ` (signal ${signal})` : ''}${lastLines ? ` — ${lastLines}` : ''}`.slice(0, 1000),+ };+}diff --git a/server/services/loraTraining/failure.test.js b/server/services/loraTraining/failure.test.jsnew file mode 100644index 0000000000..8429f83690--- /dev/null+++ b/server/services/loraTraining/failure.test.js@@ -0,0 +1,35 @@+import { describe, it, expect } from 'vitest';+import { classifyTrainingFailure } from './failure.js';++describe('classifyTrainingFailure', () => {+ it('prefers the trainer-reported USER_ERROR', () => {+ const out = classifyTrainingFailure({+ userError: { kind: 'DATASET_ERROR', message: 'manifest contains no images' },+ stderrTail: ['CUDA out of memory'], // would otherwise classify as OOM+ });+ expect(out).toEqual({ code: 'DATASET_ERROR', message: 'manifest contains no images' });+ });++ it('classifies OOM variants', () => {+ for (const line of ['MPS backend out of memory', 'CUDA out of memory. Tried to allocate']) {+ expect(classifyTrainingFailure({ stderrTail: [line] }).code).toBe('OOM');+ }+ });++ it('classifies missing modules and HF auth', () => {+ expect(classifyTrainingFailure({ stderrTail: ["ModuleNotFoundError: No module named 'peft'"] }).code)+ .toBe('MODULE_NOT_FOUND');+ expect(classifyTrainingFailure({ stderrTail: ['GatedRepoError: 403'] }).code).toBe('HF_AUTH');+ });++ it('flags SIGKILL as memory reclaim', () => {+ expect(classifyTrainingFailure({ signal: 'SIGKILL' }).code).toBe('KILLED');+ });++ it('falls back to a generic message with the stderr tail', () => {+ const out = classifyTrainingFailure({ exitCode: 1, stderrTail: ['Traceback', 'ValueError: bad shape'] });+ expect(out.code).toBe('TRAINING_FAILED');+ expect(out.message).toContain('ValueError: bad shape');+ expect(out.message).toContain('code 1');+ });+});diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsnew file mode 100644index 0000000000..05f84a7c5b--- /dev/null+++ b/server/services/loraTraining/index.js@@ -0,0 +1,443 @@+/**+ * LoRA training engine — run lifecycle + python trainer spawn.+ *+ * Routed through mediaJobQueue's GPU lane as `kind: 'training'` (training+ * shares the Metal/MLX runtime with renders, so serialization is correct).+ * The queue owns job status / SSE / watchdog / cancel escalation; this+ * module owns the run RECORD (PostgreSQL `lora_training_runs`), the child+ * process, artifact collection under `data/training-runs/<runId>/`, and+ * trained-LoRA registration into `data/loras/`.+ *+ * Spawn/cancel mirrors videoGen/local.js: SIGTERM → 8s SIGKILL escalation,+ * PYTHONUNBUFFERED, safeChildProcessEnv + hfTokenEnv, caffeinate on darwin.+ * The trainers checkpoint on SIGTERM, so a cancel keeps its progress.+ */++import { spawn } from 'child_process';+import { copyFile, mkdir, stat, writeFile } from 'fs/promises';+import { join, basename } from 'path';+import { platform } from 'os';+import { PATHS, ensureDir, atomicWrite, shortId } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { v4 as uuidv4 } from '../../lib/uuid.js';+import { hfTokenEnv } from '../../lib/hfToken.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';+import { getImageModels } from '../../lib/mediaModels.js';+import { resolveFlux2Python, isFlux2VenvHealthy } from '../../lib/pythonSetup.js';+import { getSettings } from '../settings.js';+import { enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';+import { updateDataset } from '../loraDatasets.js';+import { trainingEvents } from './events.js';+import {+ TRAINING_DEFAULTS,+ TRAINING_RUNTIMES,+ buildFlux2TrainArgs,+ buildMfluxTrainArgs,+ buildMfluxTrainConfig,+ resolveTrainingRuntime,+} from './runtimes.js';+import { makeTrainingLineHandler } from './progress.js';+import { classifyTrainingFailure } from './failure.js';+import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';+import { validateDatasetReady } from './dataset.js';+import * as runsDb from './db.js';++export { listRuns, getRun, getRunRequired, deleteRun } from './db.js';+export { trainingEvents } from './events.js';++const TRAINER_SCRIPTS = {+ [TRAINING_RUNTIMES.MFLUX]: join(PATHS.root, 'scripts', 'train_mflux_lora.py'),+ [TRAINING_RUNTIMES.FLUX2]: join(PATHS.root, 'scripts', 'train_flux2_lora.py'),+};++export const runDir = (runId) => join(PATHS.trainingRuns, runId);+export const runSamplesDir = (runId) => join(runDir(runId), 'samples');++// GPU lane serializes training with renders, so at most one trainer child+// exists at a time. Keyed by jobId anyway so a stale cancel can't kill a+// newer run.+let activeProcess = null;+let activeJobId = null;++export const cancel = (jobId) => {+ if (!activeProcess || (jobId && activeJobId !== jobId)) return false;+ const proc = activeProcess;+ proc.kill('SIGTERM');+ // Keep activeProcess set until 'close' clears it — the trainer may spend+ // a few seconds writing its cancel checkpoint. Escalate after 8s.+ setTimeout(() => {+ if (activeProcess === proc && proc.exitCode === null && proc.signalCode === null) {+ console.log('⚠️ training child ignored SIGTERM — escalating to SIGKILL');+ proc.kill('SIGKILL');+ }+ }, 8000).unref?.();+ return true;+};++/** Merge order: code defaults ← settings slice ← request params. */+const mergeParams = (settings, requestParams = {}) => ({+ ...TRAINING_DEFAULTS,+ ...(settings?.loraTraining?.defaults || {}),+ ...requestParams,+});++/**+ * Route-facing run launcher. Validates dataset readiness + runtime health,+ * creates the run record, and enqueues the training job. Returns+ * `{ runId, jobId, position }` (202-shaped).+ */+export async function startTrainingRun({ datasetId, baseModelId, name = null, params = {} }) {+ const routing = resolveTrainingRuntime(baseModelId, getImageModels());+ const { dataset } = await validateDatasetReady(datasetId);+ const settings = await getSettings();++ let pythonPath = null;+ if (routing.runtime === TRAINING_RUNTIMES.FLUX2) {+ const healthy = await isFlux2VenvHealthy();+ if (!healthy) {+ throw new ServerError(+ 'FLUX.2 python environment is not ready — run `bash scripts/setup-image-video.sh` (FLUX.2 option) first',+ { status: 412, code: 'FLUX2_VENV_MISSING' },+ );+ }+ } else {+ pythonPath = settings?.imageGen?.local?.pythonPath || null;+ if (!pythonPath) {+ throw new ServerError(+ 'mflux python environment is not configured — set Settings → Image Gen → Local python path (or run `bash scripts/setup-image-video.sh`)',+ { status: 412, code: 'MFLUX_VENV_MISSING' },+ );+ }+ }++ const mergedParams = mergeParams(settings, params);+ const runId = uuidv4();+ const run = {+ id: runId,+ jobId: null,+ status: 'queued',+ runtime: routing.runtime,+ baseModelId,+ fluxVariant: routing.variant,+ trainRepo: routing.trainRepo,+ name: name || null,+ character: dataset.character,+ datasetId,+ triggerWord: dataset.triggerWord,+ params: mergedParams,+ progress: { step: 0, totalSteps: mergedParams.steps, loss: null, lastCheckpointStep: null },+ artifacts: { dir: `training-runs/${runId}`, checkpoints: [], samples: [] },+ output: { loraFilename: null, finalLoss: null },+ error: null,+ createdAt: new Date().toISOString(),+ startedAt: null,+ completedAt: null,+ };+ await runsDb.createRun(run);++ const queued = enqueueJob({+ kind: 'training',+ owner: 'lora-training',+ params: {+ runId,+ runtime: routing.runtime,+ datasetId,+ characterId: dataset.character.entryId,+ characterName: dataset.character.name,+ triggerWord: dataset.triggerWord,+ baseModelId,+ steps: mergedParams.steps,+ rank: mergedParams.rank,+ pythonPath,+ },+ });+ await runsDb.updateRun(runId, { jobId: queued.jobId });+ await updateDataset(datasetId, (current) => ({+ ...current,+ status: 'training',+ training: { ...current.training, lastJobId: queued.jobId, lastRunId: runId },+ })).catch((err) => console.error(`❌ dataset training-status stamp failed: ${err?.message}`));++ console.log(`🏋️ Training run ${shortId(runId)} queued — ${routing.runtime}/${baseModelId} dataset=${shortId(datasetId)} job=${shortId(queued.jobId)}`);+ return { runId, jobId: queued.jobId, position: queued.position, status: 'queued' };+}++const emitFailed = (jobId, error) => trainingEvents.emit('failed', { generationId: jobId, error });++const flipDatasetAfterRun = (datasetId, { trained, loraFilename = null }) =>+ updateDataset(datasetId, (current) => ({+ ...current,+ status: trained ? 'trained' : 'draft',+ training: {+ ...current.training,+ ...(trained ? { loraFilename, completedAt: new Date().toISOString() } : {}),+ },+ })).catch((err) => console.error(`❌ dataset post-run stamp failed: ${err?.message}`));++/**+ * Queue-worker entry — `mediaJobQueue.runJob` calls this for kind+ * 'training'. Resolves the trainer binary + args, spawns, parses the line+ * protocol into trainingEvents, and finalizes (LoRA registration or+ * failure classification) on close. Terminal status flows through the+ * queue's dispatcher; this function resolves once the child is spawned+ * (the queue awaits the terminal event separately).+ */+export async function runTraining({ jobId, runId, pythonPath = null }) {+ const fail = (message) => {+ console.error(`❌ training [${shortId(jobId)}] ${message}`);+ emitFailed(jobId, message);+ };++ const run = await runsDb.getRun(runId);+ if (!run) return fail(`run record missing: ${runId}`);++ // Re-validate — the dataset may have been edited/deleted while queued.+ let manifest;+ try {+ ({ manifest } = await validateDatasetReady(run.datasetId));+ } catch (err) {+ await runsDb.updateRun(runId, { status: 'failed', error: err.message }).catch(() => {});+ return fail(err.message);+ }++ const dir = runDir(runId);+ const checkpointsDir = join(dir, 'checkpoints');+ const samplesDir = join(dir, 'samples');+ await mkdir(checkpointsDir, { recursive: true });+ await mkdir(samplesDir, { recursive: true });++ let bin;+ let args;+ if (run.runtime === TRAINING_RUNTIMES.FLUX2) {+ bin = resolveFlux2Python();+ if (!bin) {+ await runsDb.updateRun(runId, { status: 'failed', error: 'FLUX.2 venv missing' }).catch(() => {});+ return fail('FLUX.2 python environment disappeared — re-run scripts/setup-image-video.sh');+ }+ const manifestPath = join(dir, 'manifest.json');+ await atomicWrite(manifestPath, {+ triggerWord: manifest.triggerWord,+ images: manifest.images.map((img) => ({ path: img.path, caption: img.caption })),+ });+ args = buildFlux2TrainArgs({+ scriptPath: TRAINER_SCRIPTS.flux2,+ trainRepo: run.trainRepo,+ manifestPath,+ runDir: dir,+ triggerWord: run.triggerWord,+ params: run.params,+ samplePrompt: run.params?.samplePrompt || null,+ });+ } else {+ bin = pythonPath;+ if (!bin) {+ await runsDb.updateRun(runId, { status: 'failed', error: 'mflux python path not configured' }).catch(() => {});+ return fail('mflux python path not configured — set it in Settings → Image Gen');+ }+ const config = buildMfluxTrainConfig({+ params: run.params,+ triggerWord: run.triggerWord,+ samplePrompt: run.params?.samplePrompt || null,+ datasetImagesDir: manifest.imagesDir,+ manifestImages: manifest.images,+ checkpointsDir,+ });+ const configPath = join(dir, 'mflux-train.json');+ await atomicWrite(configPath, config);+ args = buildMfluxTrainArgs({+ scriptPath: TRAINER_SCRIPTS.mflux,+ configPath,+ runDir: dir,+ totalSteps: run.params?.steps || TRAINING_DEFAULTS.steps,+ });+ }++ await runsDb.updateRun(runId, { status: 'running', startedAt: new Date().toISOString() });+ trainingEvents.emit('status', { generationId: jobId, message: `Starting ${run.runtime} training (${run.params.steps} steps)` });++ const childEnv = safeChildProcessEnv(await hfTokenEnv());+ delete childEnv.PYTHONPATH;+ childEnv.PYTHONUNBUFFERED = '1';++ console.log(`🏋️ training [${shortId(jobId)}] spawn ${basename(bin)} ${run.runtime} steps=${run.params.steps} rank=${run.params.rank} images=${manifest.images.length}`);+ const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });+ activeProcess = proc;+ activeJobId = jobId;++ // Keep the Mac awake for the duration of the training child (display can+ // sleep; system must not). Best-effort — caffeinate exits with the child.+ if (platform() === 'darwin' && proc.pid) {+ const caf = spawn('caffeinate', ['-dis', '-w', String(proc.pid)], { stdio: 'ignore' });+ caf.on('error', () => {});+ caf.unref();+ }++ // Debounced run-record progress mirror (~2s). Per-step DB writes from a+ // hot loop are the high-frequency-write anti-pattern; SSE is the live+ // channel, the row is the durable snapshot.+ let progressDirty = null;+ let progressTimer = null;+ const scheduleProgressPersist = (patch) => {+ progressDirty = { ...progressDirty, ...patch };+ if (progressTimer) return;+ progressTimer = setTimeout(() => {+ progressTimer = null;+ const flushing = progressDirty;+ progressDirty = null;+ runsDb.updateRun(runId, (current) => ({+ ...current,+ progress: { ...current.progress, ...flushing.progress },+ artifacts: {+ ...current.artifacts,+ ...(flushing.checkpoint ? { checkpoints: [...current.artifacts.checkpoints, flushing.checkpoint] } : {}),+ ...(flushing.sample ? { samples: [...current.artifacts.samples, flushing.sample] } : {}),+ },+ })).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));+ }, 2000);+ progressTimer.unref?.();+ };++ const { handleLine, getState } = makeTrainingLineHandler({+ jobId,+ totalSteps: run.params.steps,+ emit: (event, payload) => {+ trainingEvents.emit(event, payload);+ if (event === 'progress' && typeof payload.step === 'number') {+ scheduleProgressPersist({ progress: { step: payload.step, totalSteps: payload.totalSteps } });+ }+ },+ onCheckpoint: (path, step) => scheduleProgressPersist({+ checkpoint: { step, path: basename(path) },+ progress: { lastCheckpointStep: step },+ }),+ onSample: (path) => scheduleProgressPersist({ sample: basename(path) }),+ sampleUrl: (path) => `/api/lora-training/runs/${runId}/samples/${basename(path)}`,+ });++ const makeSplitter = (stream) => {+ let buf = '';+ return (chunk) => {+ buf += chunk.toString();+ let idx;+ while ((idx = buf.indexOf('\n')) >= 0) {+ // try/catch: this runs inside a child-process data callback — an+ // uncaught throw here would crash the server process.+ try { handleLine(buf.slice(0, idx), stream); } catch (err) {+ console.error(`❌ training [${shortId(jobId)}] line handler failed: ${err?.message}`);+ }+ buf = buf.slice(idx + 1);+ }+ };+ };+ proc.stdout.on('data', makeSplitter('stdout'));+ proc.stderr.on('data', makeSplitter('stderr'));++ proc.on('error', (err) => {+ if (activeProcess === proc) { activeProcess = null; activeJobId = null; }+ fail(`trainer spawn failed: ${err.message}`);+ });++ proc.on('close', (code, signal) => {+ if (activeProcess === proc) { activeProcess = null; activeJobId = null; }+ if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }+ // Async finalize wrapped so a rejection can't escape the event handler+ // (unhandled rejection kills the process on Node ≥15).+ finalizeTraining({ jobId, runId, code, signal, state: getState() }).catch((err) => {+ console.error(`❌ training [${shortId(jobId)}] finalize failed: ${err?.message}`);+ fail(`finalize failed: ${err?.message}`);+ });+ });+}++async function finalizeTraining({ jobId, runId, code, signal, state }) {+ const run = await runsDb.getRun(runId);+ const job = getJob(jobId);+ const canceled = !!job?.cancelRequested;++ if (code === 0 && state.result?.adapter_path) {+ const filename = trainedLoraFilename({+ name: run?.name, characterName: run?.character?.name, runId,+ });+ await ensureDir(PATHS.loras);+ await copyFile(state.result.adapter_path, join(PATHS.loras, filename));+ const sizeBytes = await stat(join(PATHS.loras, filename)).then((s) => s.size).catch(() => null);+ const lastSample = run?.artifacts?.samples?.length+ ? `/api/lora-training/runs/${runId}/samples/${run.artifacts.samples[run.artifacts.samples.length - 1]}`+ : null;+ const sidecar = buildTrainedSidecar({+ run, result: state.result, filename, previewImageUrl: lastSample, sizeBytes,+ });+ await writeFile(join(PATHS.loras, `${filename}.metadata.json`), JSON.stringify(sidecar, null, 2) + '\n');+ await runsDb.updateRun(runId, {+ status: 'completed',+ completedAt: new Date().toISOString(),+ output: {+ loraFilename: filename,+ finalLoss: Number.isFinite(state.result.final_loss) ? state.result.final_loss : null,+ },+ });+ await flipDatasetAfterRun(run.datasetId, { trained: true, loraFilename: filename });+ console.log(`✅ training [${shortId(jobId)}] complete — registered ${filename}`);+ trainingEvents.emit('completed', {+ generationId: jobId, runId, loraFilename: filename, filename,+ });+ return;+ }++ if (canceled) {+ // Queue's cancelRequested flips the failed event into a clean cancel;+ // record keeps the checkpoint lineage for a future resume.+ await runsDb.updateRun(runId, { status: 'canceled', completedAt: new Date().toISOString(), error: 'Canceled' })+ .catch(() => {});+ await flipDatasetAfterRun(run?.datasetId, { trained: false });+ trainingEvents.emit('failed', { generationId: jobId, error: 'Canceled' });+ return;+ }++ const { code: failCode, message } = classifyTrainingFailure({+ stderrTail: state.stderrTail, exitCode: code, signal, userError: state.userError,+ });+ await runsDb.updateRun(runId, {+ status: 'failed', completedAt: new Date().toISOString(), error: message, errorCode: failCode,+ }).catch(() => {});+ await flipDatasetAfterRun(run?.datasetId, { trained: false });+ console.error(`❌ training [${shortId(jobId)}] ${failCode}: ${message}`);+ trainingEvents.emit('failed', { generationId: jobId, error: message });+}++/**+ * Boot reconcile + terminal-state mirror. Called from server/index.js after+ * initMediaJobQueue(). Any run persisted as queued/running whose job isn't+ * live in the queue is marked failed (the queue does the same for its own+ * interrupted jobs — this keeps the two stores agreeing). Also subscribes+ * to mediaJobEvents so a queue-side cancel (user hits cancel while QUEUED,+ * which never reaches runTraining) still lands in the run record.+ */+export async function initLoraTraining() {+ const active = await runsDb.listActiveRuns().catch((err) => {+ console.error(`❌ loraTraining boot reconcile failed: ${err?.message}`);+ return [];+ });+ for (const run of active) {+ const job = run.jobId ? getJob(run.jobId) : null;+ if (!job || ['failed', 'canceled', 'completed'].includes(job.status)) {+ await runsDb.updateRun(run.id, {+ status: 'failed', error: 'interrupted by restart', completedAt: new Date().toISOString(),+ }).catch(() => {});+ await flipDatasetAfterRun(run.datasetId, { trained: false });+ console.log(`🧹 training run ${shortId(run.id)} marked failed (interrupted by restart)`);+ }+ }++ // Queued-job cancels never reach runTraining, so mirror them here.+ mediaJobEvents.on('canceled', (job) => {+ if (job?.kind !== 'training' || !job?.params?.runId) return;+ runsDb.getRun(job.params.runId).then((run) => {+ if (!run || ['completed', 'failed', 'canceled'].includes(run.status)) return null;+ return runsDb.updateRun(run.id, {+ status: 'canceled', completedAt: new Date().toISOString(), error: job.error || 'Canceled',+ }).then(() => flipDatasetAfterRun(run.datasetId, { trained: false }));+ }).catch((err) => console.error(`❌ training cancel mirror failed: ${err?.message}`));+ });+ console.log('🏋️ loraTraining initialized');+}diff --git a/server/services/loraTraining/progress.js b/server/services/loraTraining/progress.jsnew file mode 100644index 0000000000..5367cd22cc--- /dev/null+++ b/server/services/loraTraining/progress.js@@ -0,0 +1,120 @@+/**+ * Trainer stdout/stderr line protocol parser. Pure factory — no I/O.+ *+ * Both trainer scripts speak the same protocol:+ * STEP:<cur>:<total>:<loss> per-step progress (loss may be 'nan')+ * STAGE:<name> phase transition (load-model, training, …)+ * STAGE:<name>:heartbeat:<N>s keep-alive while a phase is silent+ * CHECKPOINT:<path>:<step> adapter checkpoint written+ * SAMPLE:<path>:<step> mid-training sample image written+ * STATUS:<message> human status line+ * USER_ERROR:<kind>:<message> actionable user-facing failure+ * RESULT:<json> terminal result ({ adapter_path, steps, final_loss })+ *+ * `emit(event, payload)` receives ('activity'|'progress'|'status', payload)+ * shapes matching what mediaJobQueue's dispatcher expects. The factory+ * tracks parser state (result JSON, USER_ERROR, stderr tail for failure+ * classification) retrievable via getState().+ */++import { PYTHON_NOISE_RE } from '../../lib/sseUtils.js';++const STDERR_TAIL_LINES = 50;++export function makeTrainingLineHandler({+ jobId,+ totalSteps,+ emit,+ onCheckpoint = null,+ onSample = null,+ sampleUrl = null,+}) {+ const state = {+ result: null,+ userError: null,+ stderrTail: [],+ lastStep: 0,+ lastLoss: null,+ stage: null,+ };++ const handleLine = (rawLine, stream = 'stdout') => {+ const line = String(rawLine).trim();+ if (!line) return;+ if (PYTHON_NOISE_RE.test(line)) return;++ if (stream === 'stderr') {+ state.stderrTail.push(line);+ if (state.stderrTail.length > STDERR_TAIL_LINES) state.stderrTail.shift();+ }++ // Any non-noise output is activity — resets the queue's idle watchdog.+ emit('activity', { generationId: jobId });++ const step = line.match(/^STEP:(\d+):(\d+):([-\d.naN]+)/);+ if (step) {+ const cur = Number(step[1]);+ const total = Number(step[2]) || totalSteps || 1;+ const loss = Number.parseFloat(step[3]);+ state.lastStep = cur;+ state.lastLoss = Number.isFinite(loss) ? loss : null;+ emit('progress', {+ generationId: jobId,+ progress: Math.max(0, Math.min(1, cur / total)),+ step: cur,+ totalSteps: total,+ message: `Training step ${cur}/${total}${Number.isFinite(loss) ? ` · loss ${loss.toFixed(4)}` : ''}`,+ });+ return;+ }++ const checkpoint = line.match(/^CHECKPOINT:(.+):(\d+)$/);+ if (checkpoint) {+ onCheckpoint?.(checkpoint[1], Number(checkpoint[2]));+ emit('status', { generationId: jobId, message: `Checkpoint saved @ step ${checkpoint[2]}` });+ return;+ }++ const sample = line.match(/^SAMPLE:(.+):(\d+)$/);+ if (sample) {+ onSample?.(sample[1], Number(sample[2]));+ 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]}` });+ }+ return;+ }++ const stage = line.match(/^STAGE:([a-zA-Z0-9_-]+)(?::heartbeat:(\d+)s)?/);+ if (stage) {+ if (!stage[2] && state.stage !== stage[1]) {+ state.stage = stage[1];+ emit('status', { generationId: jobId, message: `Stage: ${stage[1]}` });+ }+ return;+ }++ const status = line.match(/^STATUS:(.+)$/);+ if (status) {+ emit('status', { generationId: jobId, message: status[1].trim() });+ return;+ }++ const userError = line.match(/^USER_ERROR:([a-zA-Z0-9_-]+):(.+)$/);+ if (userError) {+ state.userError = { kind: userError[1], message: userError[2].trim() };+ return;+ }++ const result = line.match(/^RESULT:(\{.*\})\s*$/);+ if (result) {+ let parsed = null;+ try { parsed = JSON.parse(result[1]); } catch { parsed = null; }+ if (parsed && typeof parsed === 'object') state.result = parsed;+ return;+ }+ };++ return { handleLine, getState: () => state };+}diff --git a/server/services/loraTraining/progress.test.js b/server/services/loraTraining/progress.test.jsnew file mode 100644index 0000000000..28eb634728--- /dev/null+++ b/server/services/loraTraining/progress.test.js@@ -0,0 +1,82 @@+import { describe, it, expect, vi } from 'vitest';+import { makeTrainingLineHandler } from './progress.js';++const setup = (overrides = {}) => {+ const emit = vi.fn();+ const onCheckpoint = vi.fn();+ const onSample = vi.fn();+ const handler = makeTrainingLineHandler({+ jobId: 'job-1',+ totalSteps: 1000,+ emit,+ onCheckpoint,+ onSample,+ sampleUrl: (p) => `/api/lora-training/runs/r1/samples/${p.split('/').pop()}`,+ ...overrides,+ });+ return { ...handler, emit, onCheckpoint, onSample };+};++describe('makeTrainingLineHandler', () => {+ it('parses STEP lines into progress events with loss', () => {+ const { handleLine, emit } = setup();+ handleLine('STEP:250:1000:0.0812');+ const progress = emit.mock.calls.find(([e]) => e === 'progress')[1];+ expect(progress.progress).toBeCloseTo(0.25);+ expect(progress.step).toBe(250);+ expect(progress.totalSteps).toBe(1000);+ expect(progress.message).toContain('250/1000');+ expect(progress.message).toContain('0.0812');+ });++ it('handles nan loss without a loss suffix', () => {+ 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');+ });++ it('routes CHECKPOINT and SAMPLE lines to callbacks', () => {+ const { handleLine, emit, onCheckpoint, onSample } = setup();+ handleLine('CHECKPOINT:/runs/r1/checkpoints/step-000250:250');+ expect(onCheckpoint).toHaveBeenCalledWith('/runs/r1/checkpoints/step-000250', 250);+ handleLine('SAMPLE:/runs/r1/samples/step-000250.png:250');+ 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.progress).toBeUndefined(); // preview frame, not a progress update+ });++ it('emits stage transitions once and swallows heartbeats', () => {+ const { handleLine, emit } = setup();+ handleLine('STAGE:training');+ handleLine('STAGE:training:heartbeat:20s');+ handleLine('STAGE:training');+ const stageEvents = emit.mock.calls.filter(([e, p]) => e === 'status' && p.message?.startsWith('Stage:'));+ expect(stageEvents).toHaveLength(1);+ });++ it('captures USER_ERROR and RESULT into state', () => {+ const { handleLine, getState } = setup();+ handleLine('USER_ERROR:DATASET_ERROR:caption file missing', 'stderr');+ handleLine('RESULT:{"adapter_path":"/r/adapter/x.safetensors","steps":1000,"final_loss":0.08}');+ const state = getState();+ expect(state.userError).toEqual({ kind: 'DATASET_ERROR', message: 'caption file missing' });+ expect(state.result.adapter_path).toBe('/r/adapter/x.safetensors');+ });++ it('keeps a bounded stderr tail and suppresses python noise', () => {+ const { handleLine, getState, emit } = setup();+ for (let i = 0; i < 60; i += 1) handleLine(`error line ${i}`, 'stderr');+ expect(getState().stderrTail).toHaveLength(50);+ emit.mockClear();+ handleLine('FutureWarning: torch.distributed deprecated thing', 'stderr');+ expect(emit).not.toHaveBeenCalled();+ });++ it('emits activity for every non-noise line', () => {+ const { handleLine, emit } = setup();+ handleLine('some unstructured trainer output');+ expect(emit.mock.calls.filter(([e]) => e === 'activity')).toHaveLength(1);+ });+});diff --git a/server/services/loraTraining/runtimes.js b/server/services/loraTraining/runtimes.jsnew file mode 100644index 0000000000..5e9fe9fa14--- /dev/null+++ b/server/services/loraTraining/runtimes.js@@ -0,0 +1,184 @@+/**+ * LoRA training runtime routing + argument/config builders. Pure — no I/O.+ *+ * Two runtimes ship:+ * - 'mflux' — FLUX.1-dev MLX training via mflux's own dreambooth CLI,+ * wrapped by scripts/train_mflux_lora.py (runs in the user's mflux venv,+ * the same python the image renders use).+ * - 'flux2' — FLUX.2 Klein diffusers+peft training via the vendored+ * scripts/train_flux2_lora.py (runs in ~/.portos/venv-flux2).+ *+ * FLUX.2 training ALWAYS targets the bf16 base repos — never the SDNQ/int8+ * quantized inference repos (no useful gradients through quant layers). The+ * trained LoRA still loads onto quantized pipelines of the same size+ * variant because the transformer hidden dims match.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { RUNNER_FAMILIES, isFlux2, flux2VariantFromModel } from '../../lib/runners.js';++export const TRAINING_RUNTIMES = Object.freeze({ MFLUX: 'mflux', FLUX2: 'flux2' });++export const TRAINING_DEFAULTS = Object.freeze({+ steps: 1000,+ rank: 16,+ learningRate: 0.0001,+ resolution: 512,+ checkpointEvery: 250,+ sampleEvery: 250,+});++// bf16 training bases per FLUX.2 size variant. Inference may run quantized+// repos; training resolves to these regardless of which flux2-* model id+// the user picked.+export const FLUX2_TRAIN_REPOS = Object.freeze({+ '4b': 'black-forest-labs/FLUX.2-klein-4B',+ '9b': 'black-forest-labs/FLUX.2-klein-9B',+});++/**+ * Resolve which training runtime a base model id routes to. `models` is the+ * getImageModels() registry (injected so this stays pure/testable).+ */+export function resolveTrainingRuntime(baseModelId, models) {+ const entry = (models || []).find((m) => m.id === baseModelId);+ if (!entry) {+ throw new ServerError(`Unknown image model: ${baseModelId}`, {+ status: 400, code: 'TRAINING_UNSUPPORTED_MODEL',+ });+ }+ if (isFlux2(entry)) {+ const variant = flux2VariantFromModel(entry);+ if (!variant || !FLUX2_TRAIN_REPOS[variant]) {+ throw new ServerError(+ `Cannot determine FLUX.2 size variant for ${baseModelId} — training needs a klein-4B/9B model`,+ { status: 400, code: 'TRAINING_UNSUPPORTED_MODEL' },+ );+ }+ return { runtime: TRAINING_RUNTIMES.FLUX2, entry, variant, trainRepo: FLUX2_TRAIN_REPOS[variant] };+ }+ // mflux family (no `runner` field). Only FLUX.1-dev trains — schnell is+ // guidance-distilled and not a supported mflux fine-tune target.+ if (!entry.runner && entry.id === 'dev') {+ return { runtime: TRAINING_RUNTIMES.MFLUX, entry, variant: null, trainRepo: null };+ }+ throw new ServerError(+ `LoRA training supports FLUX.1-dev (mflux) and FLUX.2 Klein (flux2) — not ${baseModelId}`,+ { status: 400, code: 'TRAINING_UNSUPPORTED_MODEL' },+ );+}++/** Runner family stamped into the trained LoRA's sidecar per runtime. */+export const runnerFamilyForRuntime = (runtime) =>+ (runtime === TRAINING_RUNTIMES.FLUX2 ? RUNNER_FAMILIES.FLUX2 : RUNNER_FAMILIES.MFLUX);++const mergedParams = (params = {}) => ({ ...TRAINING_DEFAULTS, ...params });++/**+ * Build the mflux dreambooth train-config JSON. The wrapper script hands+ * this to `python -m mflux.dreambooth --train-config <file>`. mflux trains+ * in epochs over the example set; we translate the requested step budget+ * into epochs (steps / images, min 1) so "steps" means the same thing+ * across both runtimes. Shape follows mflux's documented dreambooth config;+ * the wrapper tolerates unknown-key errors by surfacing mflux's own+ * message (USER_ERROR) rather than guessing.+ */+export function buildMfluxTrainConfig({+ params = {},+ triggerWord,+ samplePrompt = null,+ datasetImagesDir,+ manifestImages = [],+ checkpointsDir,+}) {+ const p = mergedParams(params);+ if (!manifestImages.length) {+ throw new ServerError('mflux train config needs at least one example image', {+ status: 400, code: 'VALIDATION_ERROR',+ });+ }+ const totalSteps = p.steps;+ const epochs = Math.max(1, Math.round(totalSteps / manifestImages.length));+ return {+ model: 'dev',+ seed: Number.isInteger(p.seed) ? p.seed : 42,+ steps: 20,+ guidance: 3.0,+ quantize: null,+ width: p.resolution,+ height: p.resolution,+ training_loop: { num_epochs: epochs, batch_size: 1 },+ optimizer: { name: 'AdamW', learning_rate: p.learningRate },+ save: {+ output_path: checkpointsDir,+ checkpoint_frequency: p.checkpointEvery > 0 ? p.checkpointEvery : totalSteps,+ },+ instrumentation: {+ plot_frequency: 0,+ generate_image_frequency: p.sampleEvery > 0 ? p.sampleEvery : 0,+ validation_prompt: samplePrompt || `${triggerWord} portrait, neutral background`,+ },+ lora_layers: {+ transformer_blocks: {+ block_range: { start: 0, end: 19 },+ layer_types: ['attn.to_q', 'attn.to_k', 'attn.to_v', 'attn.to_out'],+ lora_rank: p.rank,+ },+ },+ examples: {+ path: datasetImagesDir,+ images: manifestImages.map((img) => ({ image: img.file, prompt: img.caption })),+ },+ };+}++/** Argv for the mflux wrapper script. */+export function buildMfluxTrainArgs({ scriptPath, configPath, runDir, totalSteps, resumeCheckpoint = null }) {+ const args = [+ scriptPath,+ '--train-config', configPath,+ '--output-dir', runDir,+ '--total-steps', String(totalSteps),+ ];+ if (resumeCheckpoint) args.push('--resume-checkpoint', resumeCheckpoint);+ return args;+}++/** Argv for the vendored FLUX.2 trainer. */+export function buildFlux2TrainArgs({+ scriptPath,+ trainRepo,+ manifestPath,+ runDir,+ triggerWord,+ params = {},+ samplePrompt = null,+ resumeFrom = null,+}) {+ if (!trainRepo || !/^black-forest-labs\//.test(trainRepo)) {+ // Belt-and-suspenders: training against a quantized repo silently+ // produces garbage gradients — refuse anything but the bf16 bases.+ throw new ServerError(`FLUX.2 training requires a bf16 base repo (got: ${trainRepo})`, {+ status: 400, code: 'TRAINING_UNSUPPORTED_MODEL',+ });+ }+ const p = mergedParams(params);+ const args = [+ scriptPath,+ '--model-repo', trainRepo,+ '--manifest', manifestPath,+ '--output-dir', runDir,+ '--trigger-word', triggerWord,+ '--steps', String(p.steps),+ '--rank', String(p.rank),+ '--lr', String(p.learningRate),+ '--resolution', String(p.resolution),+ '--checkpoint-every', String(p.checkpointEvery),+ '--sample-every', String(p.sampleEvery),+ '--sample-prompt', samplePrompt || `${triggerWord} portrait, neutral background`,+ '--seed', String(Number.isInteger(p.seed) ? p.seed : 42),+ '--device', 'auto',+ ];+ if (resumeFrom) args.push('--resume-from', resumeFrom);+ return args;+}diff --git a/server/services/loraTraining/runtimes.test.js b/server/services/loraTraining/runtimes.test.jsnew file mode 100644index 0000000000..f60acf6d99--- /dev/null+++ b/server/services/loraTraining/runtimes.test.js@@ -0,0 +1,118 @@+import { describe, it, expect } from 'vitest';+import {+ TRAINING_DEFAULTS,+ buildFlux2TrainArgs,+ buildMfluxTrainArgs,+ buildMfluxTrainConfig,+ resolveTrainingRuntime,+ runnerFamilyForRuntime,+} from './runtimes.js';++const MODELS = [+ { id: 'dev', name: 'Flux 1 Dev' },+ { id: 'schnell', name: 'Flux 1 Schnell' },+ { id: 'flux2-klein-4b', runner: 'flux2', repo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic' },+ { id: 'flux2-klein-9b-bf16', runner: 'flux2', repo: 'black-forest-labs/FLUX.2-klein-9B' },+ { id: 'z-image-turbo', runner: 'z-image', repo: 'Tongyi/Z-Image-Turbo' },+];++describe('resolveTrainingRuntime', () => {+ it('routes dev to mflux', () => {+ const out = resolveTrainingRuntime('dev', MODELS);+ expect(out.runtime).toBe('mflux');+ expect(out.trainRepo).toBeNull();+ });++ it('routes flux2 models to the bf16 train repo for their variant', () => {+ expect(resolveTrainingRuntime('flux2-klein-4b', MODELS).trainRepo)+ .toBe('black-forest-labs/FLUX.2-klein-4B');+ expect(resolveTrainingRuntime('flux2-klein-9b-bf16', MODELS).trainRepo)+ .toBe('black-forest-labs/FLUX.2-klein-9B');+ });++ it('rejects schnell, diffusers families, and unknown ids', () => {+ expect(() => resolveTrainingRuntime('schnell', MODELS)).toThrow(/training supports/);+ expect(() => resolveTrainingRuntime('z-image-turbo', MODELS)).toThrow(/training supports/);+ expect(() => resolveTrainingRuntime('ghost', MODELS)).toThrow(/Unknown image model/);+ });++ it('maps runtimes to runner families', () => {+ expect(runnerFamilyForRuntime('mflux')).toBe('mflux');+ expect(runnerFamilyForRuntime('flux2')).toBe('flux2');+ });+});++describe('buildMfluxTrainConfig', () => {+ const base = {+ triggerWord: 'kessa',+ datasetImagesDir: '/data/lora-datasets/ds1/images',+ checkpointsDir: '/data/training-runs/r1/checkpoints',+ manifestImages: [+ { file: 'a.png', caption: 'kessa, front view' },+ { file: 'b.png', caption: 'kessa, side view' },+ ],+ };++ it('translates the step budget into epochs over the example set', () => {+ const config = buildMfluxTrainConfig({ ...base, params: { steps: 100 } });+ expect(config.training_loop.num_epochs).toBe(50); // 100 steps / 2 images+ expect(config.examples.images).toEqual([+ { image: 'a.png', prompt: 'kessa, front view' },+ { image: 'b.png', prompt: 'kessa, side view' },+ ]);+ });++ it('applies defaults and per-run params', () => {+ const config = buildMfluxTrainConfig({ ...base, params: { rank: 8, learningRate: 0.0002, resolution: 768 } });+ expect(config.lora_layers.transformer_blocks.lora_rank).toBe(8);+ expect(config.optimizer.learning_rate).toBe(0.0002);+ expect(config.width).toBe(768);+ expect(config.model).toBe('dev');+ expect(config.save.checkpoint_frequency).toBe(TRAINING_DEFAULTS.checkpointEvery);+ });++ it('disables checkpoint/sample frequency at 0', () => {+ const config = buildMfluxTrainConfig({ ...base, params: { steps: 200, checkpointEvery: 0, sampleEvery: 0 } });+ expect(config.save.checkpoint_frequency).toBe(200); // only the final save+ expect(config.instrumentation.generate_image_frequency).toBe(0);+ });++ it('throws on an empty example set', () => {+ expect(() => buildMfluxTrainConfig({ ...base, manifestImages: [] })).toThrow(/at least one/);+ });+});++describe('buildMfluxTrainArgs / buildFlux2TrainArgs', () => {+ it('builds the wrapper argv', () => {+ const args = buildMfluxTrainArgs({+ scriptPath: '/x/train_mflux_lora.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 500,+ });+ expect(args).toEqual([+ '/x/train_mflux_lora.py', '--train-config', '/r/cfg.json',+ '--output-dir', '/r', '--total-steps', '500',+ ]);+ });++ it('builds the flux2 argv with merged params', () => {+ const args = buildFlux2TrainArgs({+ scriptPath: '/x/train_flux2_lora.py',+ trainRepo: 'black-forest-labs/FLUX.2-klein-4B',+ manifestPath: '/r/manifest.json',+ runDir: '/r',+ triggerWord: 'kessa',+ params: { steps: 20, rank: 4 },+ });+ expect(args).toContain('--model-repo');+ expect(args[args.indexOf('--steps') + 1]).toBe('20');+ expect(args[args.indexOf('--rank') + 1]).toBe('4');+ expect(args[args.indexOf('--lr') + 1]).toBe(String(TRAINING_DEFAULTS.learningRate));+ expect(args[args.indexOf('--sample-prompt') + 1]).toContain('kessa');+ });++ it('refuses non-bf16 train repos', () => {+ expect(() => buildFlux2TrainArgs({+ scriptPath: '/x.py', trainRepo: 'Disty0/FLUX.2-klein-4B-SDNQ-4bit-dynamic',+ manifestPath: '/m.json', runDir: '/r', triggerWord: 'kessa',+ })).toThrow(/bf16/);+ });+});diff --git a/server/services/loraTraining/sidecar.js b/server/services/loraTraining/sidecar.jsnew file mode 100644index 0000000000..6aac02baf7--- /dev/null+++ b/server/services/loraTraining/sidecar.js@@ -0,0 +1,50 @@+/**+ * Trained-LoRA sidecar builder — pure. Mirrors the Civitai sidecar shape+ * (`lib/civitai.js#buildSidecar`) so `listLoras()` surfaces a trained LoRA+ * with zero picker changes, plus a `source: 'trained'` marker, the+ * character identity block, and the training lineage.+ */++import { slugifyForFilename } from '../../lib/civitai.js';+import { TRAINING_RUNTIMES, runnerFamilyForRuntime } from './runtimes.js';++/** `lora-trained-<slug>-<runId8>.safetensors` — runId suffix prevents collisions. */+export function trainedLoraFilename({ name, characterName, runId }) {+ const slug = slugifyForFilename(name || characterName || 'character');+ return `lora-trained-${slug}-${String(runId).replace(/-/g, '').slice(0, 8)}.safetensors`;+}++export function buildTrainedSidecar({ run, result = {}, filename, previewImageUrl = null, sizeBytes = null }) {+ const runtime = run.runtime;+ const params = run.params || {};+ return {+ filename,+ name: run.name || `${run.character?.name || 'Character'} (trained)`,+ description: `Trained in PortOS · ${params.steps ?? '?'} steps · rank ${params.rank ?? '?'} · dataset ${run.datasetId}`,+ source: 'trained',+ character: run.character || null,+ datasetId: run.datasetId || null,+ runId: run.id,+ civitai: null,+ runnerFamily: runnerFamilyForRuntime(runtime),+ // '4b' | '9b' for flux2 (composeCompatKey → flux2-4b/flux2-9b in the+ // picker); null for mflux (bare 'mflux' compat key).+ fluxVariant: runtime === TRAINING_RUNTIMES.FLUX2 ? (run.fluxVariant || null) : null,+ triggerWords: run.triggerWord ? [run.triggerWord] : [],+ recommendedScale: 1.0,+ training: {+ baseModelId: run.baseModelId,+ runtime,+ steps: params.steps ?? null,+ rank: params.rank ?? null,+ learningRate: params.learningRate ?? null,+ resolution: params.resolution ?? null,+ seed: params.seed ?? null,+ finalLoss: Number.isFinite(result.final_loss) ? result.final_loss : null,+ trainedSteps: Number.isInteger(result.steps) ? result.steps : null,+ },+ file: { sizeKB: Number.isFinite(sizeBytes) ? Math.round(sizeBytes / 1024) : null, hashes: {}, downloadUrl: null },+ previewImageUrl,+ installedAt: new Date().toISOString(),+ };+}diff --git a/server/services/loraTraining/sidecar.test.js b/server/services/loraTraining/sidecar.test.jsnew file mode 100644index 0000000000..b3679369e0--- /dev/null+++ b/server/services/loraTraining/sidecar.test.js@@ -0,0 +1,57 @@+import { describe, it, expect } from 'vitest';+import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';++const baseRun = {+ id: '3f9a21c0-aaaa-bbbb-cccc-dddddddddddd',+ runtime: 'mflux',+ baseModelId: 'dev',+ fluxVariant: null,+ name: null,+ character: { entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa Brightwater' },+ datasetId: 'ds-1',+ triggerWord: 'kessa_brightwater',+ params: { steps: 1000, rank: 16, learningRate: 0.0001, resolution: 512, seed: 42 },+};++describe('trainedLoraFilename', () => {+ it('slugs the name with a runId suffix', () => {+ const filename = trainedLoraFilename({ name: null, characterName: 'Kessa Brightwater', runId: baseRun.id });+ expect(filename).toBe('lora-trained-kessa-brightwater-3f9a21c0.safetensors');+ });+});++describe('buildTrainedSidecar', () => {+ it('carries every field listLoras reads, plus training lineage', () => {+ const sidecar = buildTrainedSidecar({+ run: baseRun,+ result: { adapter_path: '/x/a.safetensors', steps: 1000, final_loss: 0.0812 },+ filename: 'lora-trained-kessa-3f9a21c0.safetensors',+ previewImageUrl: '/api/lora-training/runs/r/samples/step-001000.png',+ sizeBytes: 50 * 1024 * 1024,+ });+ // Fields the existing listLoras mapEntry consumes:+ expect(sidecar.name).toBe('Kessa Brightwater (trained)');+ expect(sidecar.civitai).toBeNull();+ expect(sidecar.runnerFamily).toBe('mflux');+ expect(sidecar.fluxVariant).toBeNull();+ expect(sidecar.triggerWords).toEqual(['kessa_brightwater']);+ expect(sidecar.recommendedScale).toBe(1.0);+ expect(sidecar.installedAt).toBeTruthy();+ // Trained-LoRA additions:+ expect(sidecar.source).toBe('trained');+ expect(sidecar.character.entryId).toBe('char-1');+ expect(sidecar.character.ingredientId).toBe('ing-1');+ expect(sidecar.datasetId).toBe('ds-1');+ expect(sidecar.training.finalLoss).toBe(0.0812);+ expect(sidecar.file.sizeKB).toBe(51200);+ });++ it('stamps fluxVariant for flux2 runs so the compat key gates by size', () => {+ const sidecar = buildTrainedSidecar({+ run: { ...baseRun, runtime: 'flux2', baseModelId: 'flux2-klein-4b', fluxVariant: '4b' },+ filename: 'x.safetensors',+ });+ expect(sidecar.runnerFamily).toBe('flux2');+ expect(sidecar.fluxVariant).toBe('4b');+ });+});diff --git a/server/services/loras.js b/server/services/loras.jsindex b59c23a208..2c1a5f1626 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -149,6 +149,13 @@ export const listLoras = async () => {// before the URL-normalize fix) also benefit without a reinstall.previewImageUrl: normalizeCivitaiImageUrl(sidecar?.previewImageUrl) || null,description: sidecar?.description || '',+ // Trained-LoRA surfacing (sidecars written by services/loraTraining):+ // 'trained' source + the character identity block let the library UI+ // badge them and characterLoraResolver match them. Null for Civitai+ // installs and legacy drops.+ source: sidecar?.source || null,+ character: sidecar?.character || null,+ trainedFromDatasetId: sidecar?.datasetId || null,};},});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex fb360ebe0c..272bb92944 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -40,6 +40,7 @@ import {} from '../../lib/sseUtils.js';import { videoGenEvents } from '../videoGen/events.js';import { imageGenEvents } from '../imageGenEvents.js';+import { trainingEvents } from '../loraTraining/events.js';import { getSettings } from '../settings.js';import { IMAGE_GEN_MODE } from '../imageGen/modes.js';@@ -64,6 +65,10 @@ 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);+// Training is idle-based like video — per-step STEP: lines and the python+// heartbeat thread reset it, so 30 minutes only trips on true hangs (model+// download stalls emit tqdm lines; GIL-pinned wedges emit nothing).+const WATCHDOG_TRAINING_MS = watchdogMs(process.env.MEDIA_JOB_WATCHDOG_TRAINING_MS, 30 * 60 * 1000);const PROGRESS_PERSIST_DEBOUNCE_MS = 250;// Returns true if `p` resolves strictly under PATHS.uploads. Shared by@@ -100,7 +105,7 @@ async function safeUnlinkUpload(path) {await unlink(path).catch(() => {});}-export const JOB_KINDS = Object.freeze(['video', 'image']);+export const JOB_KINDS = Object.freeze(['video', 'image', 'training']);export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);// Returns a Promise that resolves to the gen module for the given job's@@ -109,6 +114,7 @@ export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'fa// so a new provider addition is one edit instead of three.function getGenModuleForJob(job) {if (job.kind === 'video') return import('../videoGen/local.js');+ if (job.kind === 'training') return import('../loraTraining/index.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');if (job.kind === 'image') return import('../imageGen/local.js');return Promise.resolve(null);@@ -120,7 +126,12 @@ function getGenModuleForJob(job) {// here so the seam stays in one place instead of accreting into runJob.// Mutates safeParams in place.async function resolveLiveParams(job, safeParams) {- const usesLocalPython = job.kind === 'video' || (job.kind === 'image' && job.params?.mode !== IMAGE_GEN_MODE.CODEX);+ // mflux training runs in the same venv as local image renders, so the+ // live settings pythonPath wins there too. flux2 training resolves its+ // own venv (resolveFlux2Python) inside runTraining — skip it here.+ const usesLocalPython = job.kind === 'video'+ || (job.kind === 'image' && job.params?.mode !== IMAGE_GEN_MODE.CODEX)+ || (job.kind === 'training' && job.params?.runtime === 'mflux');if (!usesLocalPython) return;const live = await getSettings().catch(() => null);const livePythonPath = live?.imageGen?.local?.pythonPath || null;@@ -490,7 +501,7 @@ function recomputeQueuePositions() {// the queue, even though the underlying emitters don't supply one.function synthesizeMessage(e, kind) {if (typeof e.step === 'number' && typeof e.totalSteps === 'number' && e.totalSteps > 0) {- const verb = kind === 'video' ? 'Rendering' : 'Generating';+ const verb = kind === 'video' ? 'Rendering' : kind === 'training' ? 'Training' : 'Generating';return `${verb} step ${e.step}/${e.totalSteps}`;}return undefined;@@ -684,7 +695,9 @@ async function runJob(job) {await resolveLiveParams(job, safeParams);- const emitter = job.kind === 'video' ? videoGenEvents : imageGenEvents;+ const emitter = job.kind === 'video' ? videoGenEvents+ : job.kind === 'training' ? trainingEvents+ : imageGenEvents;const dispatcher = makeGenDispatcher(emitter, job, handlers);dispatcher.attach();@@ -698,6 +711,7 @@ async function runJob(job) {// lastActivityAt; only true hangs (process wedged, no output) trip it.const idleTimeoutMs = (() => {if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);+ if (job.kind === 'training') return WATCHDOG_TRAINING_MS;if (isCodexJob(job)) return WATCHDOG_CODEX_MS;return WATCHDOG_IMAGE_MS;})();@@ -761,6 +775,8 @@ async function runJob(job) {await mod.generateChainedVideo({ ...safeParams, jobId: job.id });} else if (job.kind === 'video') {await mod.generateVideo({ ...safeParams, jobId: job.id });+ } else if (job.kind === 'training') {+ await mod.runTraining({ ...safeParams, jobId: job.id });} else {await mod.generateImage({ ...safeParams, jobId: job.id });}diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex be557b65cf..1d663e518b 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -322,10 +322,13 @@ const sanitizeGenConfig = (raw) => {: null;const refineProvider = trimTo(raw.refineProvider, GEN_CONFIG_STR_MAX) || null;const refineModel = trimTo(raw.refineModel, GEN_CONFIG_STR_MAX) || null;- if (imageMode === 'auto' && !imageModelId && !refineProvider && !refineModel) {+ // Trained character-LoRA auto-apply opt-out. Default ON — only an explicit+ // false persists, so issues that never touched the toggle stay clean.+ const applyCharacterLoras = raw.applyCharacterLoras !== false;+ if (imageMode === 'auto' && !imageModelId && !refineProvider && !refineModel && applyCharacterLoras) {return null;}- return { imageMode, imageModelId, refineProvider, refineModel };+ return { imageMode, imageModelId, refineProvider, refineModel, applyCharacterLoras };};// Page records (pages[]) are pass-through in sanitizeVisualStage's arraydiff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex 81b47fbb4f..a3904df4cd 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -589,6 +589,7 @@ describe('pipeline issues service', () => {expect(afterStoryboards.stages.storyboards.scenes[0].slugline).toBe('INT. LAB');expect(afterStoryboards.stages.storyboards.genConfig).toEqual({imageMode: 'codex', imageModelId: null, refineProvider: null, refineModel: null,+ applyCharacterLoras: true,});// Patch only cover on comicPages — pages must survive.diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 19ad6d9405..07fbcd8382 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -38,7 +38,9 @@ import {} from '../../lib/scenePrompt.js';import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../../lib/canonPrompt.js';import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';-import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';+import { getDefaultVideoModelId, getVideoModels, getImageModels } from '../../lib/mediaModels.js';+import { loraCompatKey } from '../../lib/runners.js';+import { resolveCharacterLoras } from '../characterLoraResolver.js';import { runStagedLLM } from '../../lib/stageRunner.js';import { runPromptRefine } from './refineHelpers.js';import { pickCanon } from './seriesCanon.js';@@ -98,6 +100,50 @@ const resolveMode = (options, settings) => {return IMAGE_GEN_MODE.LOCAL;};+/**+ * Resolve trained character LoRAs for a pipeline render. Local mode only —+ * codex has no LoRA support, so resolution is skipped there with one log+ * line. `options.applyCharacterLoras === false` is the per-render opt-out+ * (default on). The compat key comes from the model the local render will+ * actually use (request override → saved local model → first registered),+ * mirroring resolveSheetModelId's order; an unresolvable model just means+ * no compat filtering.+ *+ * Returns `{ loras, triggerByKey }` — `triggerByKey` maps canon+ * entryId/ingredientId → trigger word for prompt weaving.+ */+async function applyCharacterLorasToRender({ matchedCharacters, mode, options, settings }) {+ const none = { loras: [], triggerByKey: new Map() };+ if (options.applyCharacterLoras === false || !matchedCharacters?.length) return none;+ if (mode !== IMAGE_GEN_MODE.LOCAL) {+ console.log(`⚠️ character LoRA skipped — ${mode} mode has no LoRA support`);+ return none;+ }+ const allModels = getImageModels();+ const model = allModels.find((m) => m.id === options.modelId)+ || allModels.find((m) => m.id === settings?.imageGen?.local?.modelId)+ || allModels[0]+ || null;+ const compatKey = model ? loraCompatKey(model) : null;+ const loras = await resolveCharacterLoras(matchedCharacters, { compatKey }).catch((err) => {+ console.error(`❌ character LoRA resolution failed: ${err?.message}`);+ return [];+ });+ if (!loras.length) return none;+ const triggerByKey = new Map();+ for (const lora of loras) {+ if (!lora.triggerWord || !lora.character) continue;+ if (lora.character.entryId) triggerByKey.set(lora.character.entryId, lora.triggerWord);+ if (lora.character.ingredientId) triggerByKey.set(lora.character.ingredientId, lora.triggerWord);+ }+ console.log(`🧬 character LoRA auto-apply — ${loras.map((l) => `${l.character?.name || '?'}→${l.filename}`).join(', ')}`);+ return { loras, triggerByKey };+}++const loraRenderOptions = (loras) => (loras.length+ ? { loraFilenames: loras.map((l) => l.filename), loraScales: loras.map((l) => l.scale) }+ : {});+// Defensive fallback — an unrecognized value must never land in the final// slot, even if a future client bypasses the route schema.const resolveVariant = (target) => (target === 'final' ? 'final' : 'proof');@@ -179,6 +225,10 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin// at the dispatcher....(options.initImagePath ? { initImagePath: options.initImagePath } : {}),...(Number.isFinite(options.initImageStrength) ? { initImageStrength: options.initImageStrength } : {}),+ // Character LoRAs resolved by applyCharacterLorasToRender — only the+ // local runner honors these (codex has no LoRA support; the resolver is+ // skipped there so the spread stays empty).+ ...(options.loraFilenames?.length ? { loraFilenames: options.loraFilenames, loraScales: options.loraScales } : {}),};// The queue dispatches directly to imageGen/{codex,local}.generateImage,// bypassing imageGen/index.js's dispatcher that resolves cleaners for@@ -596,16 +646,25 @@ export async function enqueueVolumeBackCover(seriesId, seasonId, options = {}) {export function composeComicPagePrompt({series, world, page, pageNumber, extraStyle = '',matchedCharacters = [], matchedPlaces = [], matchedObjects = [],+ // entryId/ingredientId → trained-LoRA trigger word (see+ // applyCharacterLorasToRender). Passed as a map so this compose stays pure.+ loraTriggerByKey = null,}) {const panels = Array.isArray(page?.panels) ? page.panels : [];if (panels.length === 0) return '';// Placed AFTER the layout clause: diffusion models weight earlier tokens// more heavily, and the page-shape instruction has to claim that position.+ // A character with a trained LoRA gets its trigger word parenthesized+ // after the name — the token the adapter binds the identity to.const featuring = (matchedCharacters || [])- .map((c) => ({ name: c.name, desc: (c.physicalDescription || c.description || '').trim() }))+ .map((c) => ({+ name: c.name,+ trigger: loraTriggerByKey?.get(c.id) || loraTriggerByKey?.get(c.ingredientId) || null,+ desc: (c.physicalDescription || c.description || '').trim(),+ })).filter((c) => c.name && c.desc)- .map((c) => `${c.name}: ${c.desc}`)+ .map((c) => `${c.name}${c.trigger ? ` (${c.trigger})` : ''}: ${c.desc}`).join('; ');// Place baseline: pull the full RICH descriptor set per matched place@@ -757,15 +816,20 @@ export async function enqueueVisualComicPage(issueId, options = {}) {// composeComicPagePrompt only returns '' when panels.length === 0, which is// already rejected above. The "(continuation of previous beat)" placeholder// covers panels with no description, so the prompt is non-empty by here.+ const { loras: characterLoras, triggerByKey } = await applyCharacterLorasToRender({+ matchedCharacters, mode, options, settings,+ });+const prompt = composeComicPagePrompt({series, world, page, pageNumber: pageIndex + 1,extraStyle: options.extraStyle || '',matchedCharacters, matchedPlaces, matchedObjects,+ loraTriggerByKey: triggerByKey,});const jobId = enqueueImageJob({prompt, world, settings, mode,- options: { ...options, initImagePath, initImageStrength },+ options: { ...options, initImagePath, initImageStrength, ...loraRenderOptions(characterLoras) },owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length} variant=${variant}${fromProof ? ' (from proof)' : ''}`,});@@ -848,7 +912,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {`${options.description || ''} ${options.slugline || ''}`,canon.characters,);- const prompt = composeVisualPrompt({+ const composedPrompt = composeVisualPrompt({series,description: options.description,slugline: options.slugline,@@ -860,14 +924,26 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {// generic visual-image route, which has no scene index to look them up.characterAppearances: options.characterAppearances,});- if (!prompt) {+ if (!composedPrompt) {throw new ServerError('visual prompt is empty (no description, no style)', {status: 400, code: 'PIPELINE_VISUAL_EMPTY_PROMPT',});}+ const { loras: characterLoras } = await applyCharacterLorasToRender({+ matchedCharacters, mode, options, settings,+ });+ // composeVisualPrompt is shared with the episode-video batch path, so the+ // trigger words append here rather than threading a new param through it.+ const triggerClause = characterLoras+ .filter((l) => l.triggerWord)+ .map((l) => `${l.character?.name || 'character'} (${l.triggerWord})`)+ .join(', ');+ const prompt = triggerClause ? `${composedPrompt}\n\nFeaturing ${triggerClause}.` : composedPrompt;+const jobId = enqueueImageJob({- prompt, world, settings, options, mode,+ prompt, world, settings, mode,+ options: { ...options, ...loraRenderOptions(characterLoras) },owner: `pipeline:${issueId}:${stageId}`,logLine: `🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId}`,});diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.jsindex 8446a57d5a..67b8f60948 100644--- a/server/services/pipeline/visualStages.test.js+++ b/server/services/pipeline/visualStages.test.js@@ -69,6 +69,16 @@ vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLvi.mock('../../lib/mediaModels.js', () => ({getDefaultVideoModelId: () => 'ltx-default',getVideoModels: () => [{ id: 'ltx-default' }, { id: 'ltx-extra' }],+ // Character-LoRA auto-apply resolves the render model's compat key from+ // the image registry; empty registry → no compat filtering in tests.+ getImageModels: () => [],+}));++// Keep the character-LoRA resolver off the real data/loras directory; tests+// that assert auto-apply behavior override this mock's return value.+const resolveCharacterLorasMock = vi.fn(async () => []);+vi.mock('../characterLoraResolver.js', () => ({+ resolveCharacterLoras: (...a) => resolveCharacterLorasMock(...a),}));const {@@ -948,3 +958,82 @@ describe('enqueueVisualImage characterAppearances enforcement', () => {expect(enqueueJobMock).toHaveBeenCalledTimes(1);});});++// Guards the character-LoRA auto-apply WIRING: trained LoRAs resolved for+// matched characters must reach enqueueJob params (local mode), weave their+// trigger words into the prompt, and stay out entirely on opt-out.+describe('enqueueVisualImage character-LoRA auto-apply', () => {+ beforeEach(() => {+ resolveCharacterLorasMock.mockClear();+ resolveCharacterLorasMock.mockResolvedValue([]);+ });++ const canonWorld = {+ characters: [+ { id: 'char-aria', name: 'Aria', physicalDescription: 'tall, copper hair' },+ ],+ };+ const ariaLora = {+ filename: 'lora-trained-aria-12345678.safetensors',+ scale: 1.0,+ triggerWord: 'aria_tok',+ character: { entryId: 'char-aria', ingredientId: null, name: 'Aria' },+ };++ it('passes resolved LoRAs into job params and appends trigger words', async () => {+ getUniverse.mockResolvedValueOnce(canonWorld);+ resolveCharacterLorasMock.mockResolvedValueOnce([ariaLora]);+ const result = await enqueueVisualImage('iss-test', 'storyboards', {+ description: 'A scene with Aria',+ });+ const { params } = enqueueJobMock.mock.calls.at(-1)[0];+ expect(params.loraFilenames).toEqual([ariaLora.filename]);+ expect(params.loraScales).toEqual([1.0]);+ expect(result.prompt).toContain('Aria (aria_tok)');+ });++ it('skips resolution entirely when applyCharacterLoras is false', async () => {+ getUniverse.mockResolvedValueOnce(canonWorld);+ await enqueueVisualImage('iss-test', 'storyboards', {+ description: 'A scene with Aria',+ applyCharacterLoras: false,+ });+ expect(resolveCharacterLorasMock).not.toHaveBeenCalled();+ const { params } = enqueueJobMock.mock.calls.at(-1)[0];+ expect(params.loraFilenames).toBeUndefined();+ });++ it('omits lora params when no trained LoRA matches', async () => {+ getUniverse.mockResolvedValueOnce(canonWorld);+ resolveCharacterLorasMock.mockResolvedValueOnce([]);+ const result = await enqueueVisualImage('iss-test', 'storyboards', {+ description: 'A scene with Aria',+ });+ const { params } = enqueueJobMock.mock.calls.at(-1)[0];+ expect(params.loraFilenames).toBeUndefined();+ expect(result.prompt).not.toContain('aria_tok');+ });+});++describe('composeComicPagePrompt trigger-word weaving', () => {+ const page = { panels: [{ description: 'Aria stands on the cliff' }] };+ const matched = [{ id: 'char-aria', name: 'Aria', physicalDescription: 'tall, copper hair' }];++ it('parenthesizes the trigger word after the character name', () => {+ const prompt = composeComicPagePrompt({+ series: { name: 'Test' }, world: null, page, pageNumber: 1,+ matchedCharacters: matched,+ loraTriggerByKey: new Map([['char-aria', 'aria_tok']]),+ });+ expect(prompt).toContain('Aria (aria_tok): tall, copper hair');+ });++ it('renders plain names without a trigger map', () => {+ const prompt = composeComicPagePrompt({+ series: { name: 'Test' }, world: null, page, pageNumber: 1,+ matchedCharacters: matched,+ });+ expect(prompt).toContain('Aria: tall, copper hair');+ expect(prompt).not.toContain('aria_tok');+ });+});diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex 91ecb6d9ef..d1b717941d 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -86,7 +86,9 @@ const trim = (s) => (typeof s === 'string' ? s.trim() : '');// Shared field bag used by every variant's prompt builder. Centralizes the// trim/flatten calls so a new variant only writes the style-specific layout// sentences. Pure — caller decides which fields to weave into its prompt.-function extractCharacterPromptCommon(character) {+// Exported for reuse by the LoRA training dataset prompt builder+// (server/lib/loraDataset.js), which needs the same canon field extraction.+export function extractCharacterPromptCommon(character) {return {name: trim(character.name) || 'Unnamed',aliases: Array.isArray(character.aliases) ? character.aliases.filter(Boolean).join(', ') : '',