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
add LoRA dataset reassignment to a different universe character
[._.]/ Adam Eivye89ec464ff47
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6a72049d6d..874a28cf54 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,8 @@## Changed+- **Reassign a LoRA training dataset to a different universe character** — A dataset was permanently bound to the character you picked when you created it — a mis-pick (or a character you later renamed/restructured) meant deleting the dataset and rebuilding all its images from scratch. The dataset workbench header (`/media/training/:id`) now has a **Reassign** button next to the character name: pick a different universe + character and the dataset's images, captions, and trigger word all move with it (the trigger word is left as-is — edit it separately if the new character needs its own token, which re-prefixes captions as before). Reassigning onto a character that already owns a dataset is refused (one dataset per character), and the picker is the same universe→character cascade the "New dataset" dialog uses, factored into a shared `UniverseCharacterPicker`. (`server/services/loraDatasets.js`, `server/routes/loraDatasets.js`, `client/src/pages/LoraDatasetDetail.jsx`, `client/src/components/loraTraining/UniverseCharacterPicker.jsx`, `client/src/pages/LoraTraining.jsx`)+- **LoRA dataset caption fields auto-size to their content** — Each image card's caption box was a fixed 3-row textarea, so anything longer than ~3 lines was clipped behind an internal scrollbar (and you had to drag the corner to read it). The caption field now grows to fit its full caption by default — no scrolling, no manual resize — with a comfortable minimum height for short/empty captions. Factored into a reusable `useAutoSizeTextarea` hook + `AutoSizeTextarea` component for any future auto-growing field. (`client/src/components/loraTraining/DatasetImageGrid.jsx`, `client/src/components/ui/AutoSizeTextarea.jsx`, `client/src/hooks/useAutoSizeTextarea.js`)- **LoRA dataset workbench gains a "Re-caption all" button — re-run every caption through a new model** — "Caption all" already skips images that already have a caption (it only fills in the uncaptioned ones), so there was no one-click way to re-run a whole dataset through a freshly-picked vision model. A new **Re-caption all** button next to it sends `overwrite: true`, re-captioning every ready image with the model chosen in the caption-model picker (overwriting existing captions, including manual edits — the button's tooltip says so). The single-image "Re-caption" button already overwrote one image; this extends the same intent to the whole set. (`client/src/pages/LoraDatasetDetail.jsx`)diff --git a/client/src/components/loraTraining/UniverseCharacterPicker.jsx b/client/src/components/loraTraining/UniverseCharacterPicker.jsxnew file mode 100644index 0000000000..8961d66463--- /dev/null+++ b/client/src/components/loraTraining/UniverseCharacterPicker.jsx@@ -0,0 +1,75 @@+/**+ * Universe → character cascading select. Shared by the "New dataset" dialog+ * and the dataset-reassignment dialog so both pick a (universeId, entryId)+ * pair through identical loading/empty states. The parent owns the selected+ * ids; this just renders the two <select>s and loads the option lists.+ *+ * When the universe changes the parent is responsible for clearing entryId+ * (a stale character id from the previous universe must not survive) — the+ * `onUniverseChange` handler should reset it.+ */++import { useState, useEffect } from 'react';+import { listUniverses, getUniverse } from '../../services/api';++export default function UniverseCharacterPicker({+ universeId,+ entryId,+ onUniverseChange,+ onEntryChange,+ idPrefix = 'ucp',+ disabledEntryIds = [],+}) {+ const [universes, setUniverses] = useState(null);+ const [characters, setCharacters] = useState(null);++ useEffect(() => {+ listUniverses().then((list) => setUniverses(Array.isArray(list) ? list : []))+ .catch(() => setUniverses([]));+ }, []);++ useEffect(() => {+ if (!universeId) { setCharacters(null); return; }+ setCharacters(null);+ getUniverse(universeId, { silent: true })+ .then((u) => setCharacters(Array.isArray(u?.characters) ? u.characters : []))+ .catch(() => setCharacters([]));+ }, [universeId]);++ const disabled = new Set(disabledEntryIds);++ return (+ <>+ <div>+ <label htmlFor={`${idPrefix}-universe`} className="block text-sm text-gray-400 mb-1">Universe</label>+ <select+ id={`${idPrefix}-universe`}+ value={universeId}+ onChange={(e) => onUniverseChange(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={`${idPrefix}-character`} className="block text-sm text-gray-400 mb-1">Character</label>+ <select+ id={`${idPrefix}-character`}+ value={entryId}+ onChange={(e) => onEntryChange(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} disabled={disabled.has(c.id)}>+ {c.name}{disabled.has(c.id) ? ' (current)' : ''}+ </option>+ ))}+ </select>+ </div>+ )}+ </>+ );+}diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsxindex 7b9b946481..8a6fb9a60a 100644--- a/client/src/pages/LoraDatasetDetail.jsx+++ b/client/src/pages/LoraDatasetDetail.jsx@@ -10,7 +10,7 @@import { useState, useEffect, useMemo, useRef, useCallback } from 'react';import { useParams, Link } from 'react-router-dom';import {- ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images,+ ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images, Replace,} from 'lucide-react';import toast from '../components/ui/Toast';import Modal from '../components/ui/Modal';@@ -20,6 +20,7 @@ import GenerateBatchDialog from '../components/loraTraining/GenerateBatchDialog'import TrainingPanel from '../components/loraTraining/TrainingPanel';import CaptionModelPicker from '../components/loraTraining/CaptionModelPicker';import ImportGalleryDialog from '../components/loraTraining/ImportGalleryDialog';+import UniverseCharacterPicker from '../components/loraTraining/UniverseCharacterPicker';import {getLoraDataset,patchLoraDataset,@@ -126,6 +127,65 @@ function SliceDialog({ dataset, onClose, onSliced }) {);}+function ReassignDialog({ dataset, onClose, onReassigned }) {+ // Default to the current assignment so the picker opens on the dataset's+ // own universe (characters pre-load) and the user only changes what they want.+ const [universeId, setUniverseId] = useState(dataset.character.universeId);+ const [entryId, setEntryId] = useState(dataset.character.entryId);+ const [submitting, setSubmitting] = useState(false);++ const unchanged = universeId === dataset.character.universeId+ && entryId === dataset.character.entryId;++ const submit = async () => {+ setSubmitting(true);+ try {+ const next = await patchLoraDataset(dataset.id, { universeId, entryId });+ toast.success(`Reassigned to ${next.character.name}`);+ onReassigned(next);+ } finally {+ setSubmitting(false);+ }+ };++ return (+ <Modal+ open+ onClose={onClose}+ size="sm"+ ariaLabelledBy="lt-reassign-title"+ panelClassName="bg-port-card border border-port-border rounded-lg p-5"+ >+ <div className="space-y-4">+ <h2 id="lt-reassign-title" className="text-base font-semibold text-white">Reassign character</h2>+ <p className="text-sm text-gray-400">+ Move this dataset's images and trigger word to a different universe character.+ The trigger word stays the same — edit it separately if the new character needs its own token.+ </p>+ <UniverseCharacterPicker+ idPrefix="lt-reassign"+ universeId={universeId}+ entryId={entryId}+ onUniverseChange={(id) => { setUniverseId(id); setEntryId(''); }}+ onEntryChange={setEntryId}+ />+ <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={!universeId || !entryId || unchanged || 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" /> : <Replace className="w-4 h-4" />}+ Reassign+ </button>+ </div>+ </div>+ </Modal>+ );+}+export default function LoraDatasetDetail() {const { datasetId } = useParams();const [dataset, setDataset] = useState(null);@@ -137,6 +197,7 @@ export default function LoraDatasetDetail() {const [showGenerate, setShowGenerate] = useState(false);const [showSlice, setShowSlice] = useState(false);const [showImport, setShowImport] = useState(false);+ const [showReassign, setShowReassign] = useState(false);const [captionRun, setCaptionRun] = useState(null);const [captionStarting, setCaptionStarting] = useState(false);// Chosen caption model { providerId, model } — null fields mean "let the@@ -304,15 +365,25 @@ export default function LoraDatasetDetail() {<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"+ <div className="flex items-center gap-2 min-w-0">+ <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>+ <button+ type="button"+ onClick={() => setShowReassign(true)}+ title="Reassign this dataset to a different universe character"+ className="shrink-0 text-xs text-gray-500 hover:text-port-accent flex items-center gap-1">- {dataset.character.name}- </Link>- </h2>+ <Replace className="w-3.5 h-3.5" /> Reassign+ </button>+ </div><div className="flex items-center gap-2 mt-1"><label htmlFor="lt-trigger" className="text-xs text-gray-500">Trigger word</label><input@@ -440,6 +511,13 @@ export default function LoraDatasetDetail() {}}/>)}+ {showReassign && (+ <ReassignDialog+ dataset={dataset}+ onClose={() => setShowReassign(false)}+ onReassigned={(next) => { setShowReassign(false); setDataset(next); }}+ />+ )}</div>);}diff --git a/client/src/pages/LoraTraining.jsx b/client/src/pages/LoraTraining.jsxindex 336f4e3865..de4e7723c5 100644--- a/client/src/pages/LoraTraining.jsx+++ b/client/src/pages/LoraTraining.jsx@@ -12,12 +12,11 @@ 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 UniverseCharacterPicker from '../components/loraTraining/UniverseCharacterPicker';import {listLoraDatasets,createLoraDataset,deleteLoraDataset,- listUniverses,- getUniverse,} from '../services/api';const STATUS_CHIP = {@@ -27,25 +26,10 @@ const STATUS_CHIP = {};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 {@@ -66,32 +50,13 @@ function NewDatasetDialog({ onClose, onCreated }) {><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>- )}+ <UniverseCharacterPicker+ idPrefix="lt-new"+ universeId={universeId}+ entryId={entryId}+ onUniverseChange={(id) => { setUniverseId(id); setEntryId(''); }}+ onEntryChange={setEntryId}+ /><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><buttondiff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.jsindex 17f45d32c1..b59dbbf91b 100644--- a/server/routes/loraDatasets.js+++ b/server/routes/loraDatasets.js@@ -62,7 +62,14 @@ router.get('/:id', asyncHandler(async (req, res) => {res.json({ ...dataset, readiness: computeDatasetReadiness(dataset) });}));-const patchSchema = z.object({ triggerWord: triggerWordSchema.optional() });+const patchSchema = z.object({+ triggerWord: triggerWordSchema.optional(),+ // Reassign the dataset to a different universe character. Both must be+ // present together; the service re-snapshots the character and refuses a+ // collision with an existing dataset for that character.+ universeId: idSchema.optional(),+ entryId: idSchema.optional(),+});router.patch('/:id', asyncHandler(async (req, res) => {const body = validateRequest(patchSchema, req.body);const dataset = await patchDataset(req.params.id, body);diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.jsindex 1f1eb82598..c2811a65c9 100644--- a/server/services/loraDatasets.js+++ b/server/services/loraDatasets.js@@ -108,11 +108,14 @@ export async function getDataset(id) {}/**- * 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 }`.+ * Resolve a universe character and the identity snapshot a dataset stores for+ * it. Validates the character exists in the universe (404 otherwise) and is the+ * single source of truth for the snapshot shape — both createDataset and+ * patchDataset's reassignment go through here so the stored `character` fields+ * can't drift between the two write paths. Returns `{ character, snapshot }`+ * (the live canon entry plus the persisted shape).*/-export async function createDataset({ universeId, entryId, triggerWord = null }) {+async function resolveCharacterSnapshot(universeId, entryId) {const universe = await getUniverse(universeId);const characters = Array.isArray(universe.characters) ? universe.characters : [];const character = characters.find((c) => c.id === entryId);@@ -121,6 +124,24 @@ export async function createDataset({ universeId, entryId, triggerWord = null })status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',});}+ return {+ character,+ snapshot: {+ entryId,+ ingredientId: character.ingredientId || null,+ universeId,+ name: character.name,+ },+ };+}++/**+ * 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 { character, snapshot } = await resolveCharacterSnapshot(universeId, entryId);const existingAll = await loraDatasetStore.loadAll();const existing = existingAll.find(@@ -140,12 +161,7 @@ export async function createDataset({ universeId, entryId, triggerWord = null })const record = sanitizeLoraDataset({schemaVersion: LORA_DATASET_SCHEMA_VERSION,id,- character: {- entryId,- ingredientId: character.ingredientId || null,- universeId,- name: character.name,- },+ character: snapshot,triggerWord: resolvedTrigger,status: 'draft',images: [],@@ -159,24 +175,77 @@ export async function createDataset({ universeId, entryId, triggerWord = null })return { dataset: { ...record, readiness: computeDatasetReadiness(record) }, created: true };}-export async function patchDataset(id, { triggerWord } = {}) {+/**+ * Patch a dataset's trigger word and/or reassign it to a different+ * universe character. `universeId` + `entryId` must travel together — a+ * reassignment re-snapshots the character identity (entryId, universeId,+ * ingredientId, name) exactly the way createDataset does, and is refused+ * if it would collide with another dataset already keyed on that+ * (universeId, entryId) pair (the one-dataset-per-character invariant).+ */+export async function patchDataset(id, { triggerWord, universeId, entryId } = {}) {if (triggerWord !== undefined && !isValidTriggerWord(triggerWord)) {throw new ServerError('Trigger word must be 2-64 chars of [a-z0-9_]', {status: 400, code: 'VALIDATION_ERROR',});}++ // Reassignment is all-or-nothing: a half-specified target (universe but no+ // character) can't resolve a character snapshot, so reject it up front.+ const reassigning = universeId !== undefined || entryId !== undefined;+ let nextCharacter = null;+ if (reassigning) {+ if (!universeId || !entryId) {+ throw new ServerError('Reassignment requires both universeId and entryId', {+ status: 400, code: 'VALIDATION_ERROR',+ });+ }+ // The character validation and the collision scan are independent reads —+ // run them together. resolveCharacterSnapshot keeps the snapshot shape in+ // lockstep with createDataset.+ const [{ character, snapshot }, all] = await Promise.all([+ resolveCharacterSnapshot(universeId, entryId),+ loraDatasetStore.loadAll(),+ ]);+ // Enforce the same find-or-create key createDataset uses: at most one+ // dataset per (universeId, entryId). Reassigning onto a character that+ // already owns a dataset would create a duplicate the list can't tell apart.+ const clash = all.find(+ (d) => d.id !== id && d.character.universeId === universeId && d.character.entryId === entryId,+ );+ if (clash) {+ throw new ServerError(`A dataset already exists for "${character.name}" in that universe`, {+ status: 409, code: 'DATASET_EXISTS',+ });+ }+ nextCharacter = snapshot;+ }+return updateDataset(id, (current) => {- if (triggerWord === undefined || triggerWord === current.triggerWord) return null;- // Re-prefix every captioned image so the binding token follows the+ const triggerChanged = triggerWord !== undefined && triggerWord !== current.triggerWord;+ const characterChanged = nextCharacter && (+ nextCharacter.entryId !== current.character.entryId+ || nextCharacter.universeId !== current.character.universeId+ || nextCharacter.ingredientId !== current.character.ingredientId+ || nextCharacter.name !== current.character.name);+ if (!triggerChanged && !characterChanged) return null;+ // Re-prefix every captioned image so the binding token follows a trigger// rename. Without this, computeDatasetReadiness (which gates `captioned`// on the caption containing the trigger word) silently drops every// previously-captioned image and any training binds the stale token.// Empty captions are left untouched — don't fabricate a caption.const prev = current.triggerWord;- const images = current.images.map((img) => (img.caption- ? { ...img, caption: prefixCaption(triggerWord, img.caption, { previousTriggerWord: prev }) }- : img));- return { ...current, triggerWord, images };+ const images = triggerChanged+ ? current.images.map((img) => (img.caption+ ? { ...img, caption: prefixCaption(triggerWord, img.caption, { previousTriggerWord: prev }) }+ : img))+ : current.images;+ return {+ ...current,+ ...(characterChanged ? { character: nextCharacter } : {}),+ ...(triggerChanged ? { triggerWord } : {}),+ images,+ };});}diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.jsindex a9900edbd3..d9b879e4d4 100644--- a/server/services/loraDatasets.test.js+++ b/server/services/loraDatasets.test.js@@ -128,6 +128,45 @@ describe('patchDataset / listDatasets', () => {expect(reread.readiness.captioned).toBe(1);});+ it('reassigns to another character, re-snapshotting identity', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const next = await patchDataset(dataset.id, { universeId: 'uni-1', entryId: 'char-2' });+ expect(next.character).toEqual({+ entryId: 'char-2', ingredientId: null, universeId: 'uni-1', name: 'Moss',+ });+ // Trigger word is left alone — reassignment doesn't rename the token.+ expect(next.triggerWord).toBe('kessa_brightwater');+ // The list now keys the dataset under the new character.+ expect(await listDatasets({ entryId: 'char-2' })).toHaveLength(1);+ expect(await listDatasets({ entryId: 'char-1' })).toHaveLength(0);+ });++ it('reassigns and renames the trigger word in one patch', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const next = await patchDataset(dataset.id, { universeId: 'uni-1', entryId: 'char-2', triggerWord: 'moss_v1' });+ expect(next.character.entryId).toBe('char-2');+ expect(next.triggerWord).toBe('moss_v1');+ });++ it('refuses to reassign onto a character that already owns a dataset', async () => {+ const a = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ await createDataset({ universeId: 'uni-1', entryId: 'char-2' });+ await expect(patchDataset(a.dataset.id, { universeId: 'uni-1', entryId: 'char-2' }))+ .rejects.toMatchObject({ status: 409 });+ });++ it('404s reassignment to a character missing from the universe', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ await expect(patchDataset(dataset.id, { universeId: 'uni-1', entryId: 'nope' }))+ .rejects.toMatchObject({ status: 404 });+ });++ it('400s a half-specified reassignment (universe without character)', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ await expect(patchDataset(dataset.id, { universeId: 'uni-1' }))+ .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' });