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 manual Add button to universe canon sections (characters/places/objects)
[._.]/ Adam Eivy4b40bec3f7ee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex be33e131ff..32239e2501 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Add canon characters / places / objects by hand** — Each canon section in the Universe editor (Cast, Places, Objects) now has an **Add** button next to "Pick from Catalog" — the same manual-add affordance the variation buckets already had. Click it, type a name (and optionally a description), and Save mints a new canon entry you can immediately render, refine, and fill in. The entry lands unlocked (so its inline editors are usable right away), dedupes case-insensitively against existing names, and persists through the same optimistic-append path as the catalog picker — so you no longer have to extract from prose, pick from the catalog, or promote a variation just to start a character. (`client/src/components/universe/UniverseCanonSection.jsx`)+- **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 FLUX.2 Klein LoRA locally** through one of two engines, picked automatically: mflux's MLX-native trainer (`mflux-train`, mflux ≥0.17 — wrapped by `scripts/train_mflux_lora.py`, preferred on Apple Silicon; the dataset stages in mflux's `NNNN.png`+`NNNN.txt` auto-discovery layout, and quantize/low-ram knobs derive from total RAM so a 48 GB machine trains QLoRA-style instead of OOMing) or a vendored torch/diffusers+peft trainer (`scripts/train_flux2_lora.py` — bf16 bases only, precompute-then-free text/VAE encoding, gradient checkpointing) as the fallback. Either engine exports diffusers-format adapters. 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 saves a checkpoint). The finished adapter lands in `data/loras/` with a sidecar carrying the character link + trigger word + size-variant compat key (`flux2-4b`/`flux2-9b`), 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`)## Changeddiff --git a/client/src/components/universe/UniverseCanonSection.add.test.jsx b/client/src/components/universe/UniverseCanonSection.add.test.jsxnew file mode 100644index 0000000000..5b847d4943--- /dev/null+++ b/client/src/components/universe/UniverseCanonSection.add.test.jsx@@ -0,0 +1,160 @@+/**+ * Tests for the manual "Add" affordance on UniverseCanonSection — minting a+ * blank canon entry from a typed name (+ optional description) without going+ * through Extract-from-prose / Pick-from-Catalog / promote-variation.+ *+ * Mirrors the optimistic-append-then-persist contract the catalog-pick path+ * uses: the new entry carries no `id` (server mints it), lands `locked: false`+ * so the card is immediately editable, and the typed description is written to+ * the kind's `descField` (physicalDescription for characters, description for+ * places/objects).+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++vi.mock('../../services/apiCatalog', () => ({+ listCatalogIngredients: vi.fn(),+ linkCatalogIngredient: vi.fn(),+}));++vi.mock('../../services/apiUniverseBuilder', () => ({+ extractUniverseCanon: vi.fn(),+ refineUniverseCharacter: vi.fn(),+ differentiateUniverseCast: vi.fn(),+ updateUniverse: vi.fn(),+ getUniverseCanonUsage: vi.fn(),+ setUniverseCanonLock: vi.fn(),+ setUniverseCanonLockAll: vi.fn(),+ expandUniverseCharacter: vi.fn(),+}));++vi.mock('../../services/apiSystem', () => ({ generateImage: vi.fn() }));++vi.mock('../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },+}));++import UniverseCanonSection from './UniverseCanonSection';+import { updateUniverse, getUniverseCanonUsage } from '../../services/apiUniverseBuilder';+import toast from '../ui/Toast';++const baseUniverse = (over = {}) => ({+ id: 'uni-1',+ name: 'Test World',+ characters: [],+ places: [],+ objects: [],+ ...over,+});++const renderSection = (props = {}) => render(+ <MemoryRouter>+ <UniverseCanonSection+ universe={baseUniverse(props.universe)}+ universeId="uni-1"+ onUniverseChange={props.onUniverseChange || vi.fn()}+ imageCfg={{}}+ kindFilter={props.kindFilter || 'characters'}+ {...props}+ />+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ getUniverseCanonUsage.mockResolvedValue({});+});++describe('UniverseCanonSection — manual Add', () => {+ it('opens the form and persists a new character with locked:false + description in physicalDescription', async () => {+ const onUniverseChange = vi.fn();+ updateUniverse.mockResolvedValue(baseUniverse({+ characters: [{ id: 'chr-server', name: 'Rust Vega', physicalDescription: 'drifter', locked: false }],+ }));++ renderSection({ onUniverseChange });++ fireEvent.click(screen.getByRole('button', { name: /add character/i }));+ fireEvent.change(screen.getByLabelText(/new character name/i), { target: { value: ' Rust Vega ' } });+ fireEvent.change(screen.getByLabelText(/new character description/i), { target: { value: 'drifter' } });+ fireEvent.click(screen.getByRole('button', { name: /^save$/i }));++ await waitFor(() => expect(updateUniverse).toHaveBeenCalled());+ const [, patch] = updateUniverse.mock.calls[0];+ expect(Array.isArray(patch.characters)).toBe(true);+ const appended = patch.characters[patch.characters.length - 1];+ expect(appended.name).toBe('Rust Vega'); // trimmed+ expect(appended.id).toBeUndefined(); // server mints it+ expect(appended.locked).toBe(false); // immediately editable+ expect(appended.physicalDescription).toBe('drifter');+ });++ it('writes the description to `description` for places', async () => {+ const onUniverseChange = vi.fn();+ updateUniverse.mockResolvedValue(baseUniverse({+ places: [{ id: 'plc-server', name: 'The Hollow', description: 'a tunnel', locked: false }],+ }));++ renderSection({ onUniverseChange, kindFilter: 'places' });++ fireEvent.click(screen.getByRole('button', { name: /add place/i }));+ fireEvent.change(screen.getByLabelText(/new place name/i), { target: { value: 'The Hollow' } });+ fireEvent.change(screen.getByLabelText(/new place description/i), { target: { value: 'a tunnel' } });+ fireEvent.click(screen.getByRole('button', { name: /^save$/i }));++ await waitFor(() => expect(updateUniverse).toHaveBeenCalled());+ const [, patch] = updateUniverse.mock.calls[0];+ const appended = patch.places[patch.places.length - 1];+ expect(appended.description).toBe('a tunnel');+ });++ it('omits the description field entirely when left blank', async () => {+ const onUniverseChange = vi.fn();+ updateUniverse.mockResolvedValue(baseUniverse({+ characters: [{ id: 'chr-server', name: 'Nameless', locked: false }],+ }));++ renderSection({ onUniverseChange });+ fireEvent.click(screen.getByRole('button', { name: /add character/i }));+ fireEvent.change(screen.getByLabelText(/new character name/i), { target: { value: 'Nameless' } });+ fireEvent.click(screen.getByRole('button', { name: /^save$/i }));++ await waitFor(() => expect(updateUniverse).toHaveBeenCalled());+ const [, patch] = updateUniverse.mock.calls[0];+ const appended = patch.characters[patch.characters.length - 1];+ expect('physicalDescription' in appended).toBe(false);+ });++ it('refuses to add a duplicate name (case-insensitive) without calling the server', async () => {+ const onUniverseChange = vi.fn();+ renderSection({+ onUniverseChange,+ universe: { characters: [{ id: 'chr-1', name: 'Dup' }] },+ });++ fireEvent.click(screen.getByRole('button', { name: /add character/i }));+ fireEvent.change(screen.getByLabelText(/new character name/i), { target: { value: 'dup' } });+ fireEvent.click(screen.getByRole('button', { name: /^save$/i }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/already in this universe/i)));+ expect(updateUniverse).not.toHaveBeenCalled();+ });++ it('reverts the optimistic append when the save fails', async () => {+ const onUniverseChange = vi.fn();+ updateUniverse.mockRejectedValue(new Error('boom'));++ renderSection({ onUniverseChange });+ fireEvent.click(screen.getByRole('button', { name: /add character/i }));+ fireEvent.change(screen.getByLabelText(/new character name/i), { target: { value: 'Rust Vega' } });+ fireEvent.click(screen.getByRole('button', { name: /^save$/i }));++ await waitFor(() => expect(updateUniverse).toHaveBeenCalled());+ // Optimistic append fires first; the failed save reverts to the empty list.+ await waitFor(() => {+ const lastPatch = onUniverseChange.mock.calls.at(-1)[0];+ expect(lastPatch.characters).toEqual([]);+ });+ });+});diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex df5f6daa83..47727fca35 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -14,7 +14,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';import {- Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus, Sparkles,+ Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus, Sparkles, Plus,} from 'lucide-react';import toast from '../ui/Toast';import IngredientPicker from '../IngredientPicker';@@ -590,6 +590,50 @@ export default function UniverseCanonSection({toast.success(`Added ${picked.name || 'ingredient'} from Catalog`);}, [universe, universeId, onUniverseChange, mountedRef, catalogLinking]);+ // Manual "Add" — mint a blank canon entry from a name the user types (and an+ // optional description), mirroring the optimistic-append-then-persist shape+ // of `handlePickFromCatalog`. The entry carries no `id` (the server's+ // `ensureId` mints a kind-prefixed one) and `locked: false` so the card's+ // inline editors are usable immediately without a separate unlock click —+ // the user explicitly created it to fill in, so the lock-by-default contract+ // (which guards AI-extracted/-arriving entries) doesn't apply here.+ const [creatingKindKey, setCreatingKindKey] = useState(null);+ const handleCreateEntry = useCallback(async (kind, { name, description }) => {+ const trimmedName = String(name || '').trim();+ if (!trimmedName || !universe || creatingKindKey) return false;+ const kindKey = kind.key;+ const list = getKindList(universe, kindKey);+ // Dedup by normalized name so a manual add of an existing entry is a clear+ // no-op (the server's sanitizeBibleList would otherwise silently merge it).+ if (list.some((e) => String(e?.name || '').trim().toLowerCase() === trimmedName.toLowerCase())) {+ toast.error(`${trimmedName} is already in this universe`);+ return false;+ }+ const entry = { name: trimmedName, locked: false };+ const desc = String(description || '').trim();+ if (desc && kind.descField) entry[kind.descField] = desc;+ setCreatingKindKey(kindKey);+ const capturedId = universeId;+ const nextList = [...list, entry];+ // Optimistic append so the new card shows immediately; the server response+ // (with the minted entry id) replaces it.+ onUniverseChange({ ...universe, [kindKey]: nextList });+ // `{ silent: true }` because the .catch below owns the error toast.+ const updated = await updateUniverse(universeId, { [kindKey]: nextList }, { silent: true })+ .catch((err) => { toast.error(`Add ${kind.singular} failed: ${err.message}`); return null; });+ const stillCurrent = mountedRef.current && currentUniverseIdRef.current === capturedId;+ if (!updated) {+ // Revert the optimistic append — the save didn't land. `list` is the+ // pre-append snapshot (canon edits are user-driven one-at-a-time).+ if (stillCurrent) onUniverseChange({ ...universe, [kindKey]: list });+ } else if (stillCurrent) {+ onUniverseChange(updated);+ }+ if (mountedRef.current) setCreatingKindKey(null);+ if (updated) toast.success(`Added ${trimmedName}`);+ return !!updated;+ }, [universe, universeId, onUniverseChange, mountedRef, creatingKindKey]);+// Inline-edit channel for canon fields the user types/picks directly// (setting intExt + timeOfDay chips, primaryImageRef pinning, wardrobe// edits). Optimistic — UI updates before the server roundtrip so chip@@ -773,6 +817,8 @@ export default function UniverseCanonSection({renderingAll={renderAllKindKey === kind.key}onPickFromCatalog={() => setCatalogPickerKind(kind)}catalogLinking={catalogLinking}+ onAddEntry={(payload) => handleCreateEntry(kind, payload)}+ creating={creatingKindKey === kind.key}/>))}@@ -792,7 +838,7 @@ export default function UniverseCanonSection({);}-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false, onPickFromCatalog = null, catalogLinking = false }) {+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false, onPickFromCatalog = null, catalogLinking = false, onAddEntry = null, creating = false }) {// Universe-only character wiring — `null` for non-character kinds so// CanonCard's gate stays `kind === 'characters' && characterExtensions`.// Memoized so the BASE object is stable across re-renders that aren't@@ -806,6 +852,25 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende[kind.key, universeId, onExpandCharacter, onSheetCompleted, onSheetDeleted],);const Icon = kind.icon;++ // Manual-add form state — local to the section (mirrors CategoryEditor's+ // `adding`/`newLabel` bucket-add form). Persistence is the parent's job via+ // `onAddEntry`; this just collects a name + optional description and resets+ // on a successful save.+ const [adding, setAdding] = useState(false);+ const [newName, setNewName] = useState('');+ const [newDesc, setNewDesc] = useState('');+ const submitAdd = async () => {+ if (!newName.trim() || !onAddEntry || creating) return;+ const ok = await onAddEntry({ name: newName, description: newDesc });+ if (ok) {+ setNewName('');+ setNewDesc('');+ setAdding(false);+ }+ };+ const cancelAdd = () => { setAdding(false); setNewName(''); setNewDesc(''); };+// Bulk lock-state summary computed off the FULL list (not the series-filtered// view) so the buttons reflect the universe-wide state the bulk action will// change. A mixed list (some locked, some not) enables BOTH buttons so the@@ -828,6 +893,20 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rendeconst controls = (<>+ {onAddEntry ? (+ <button+ type="button"+ onClick={() => setAdding((v) => !v)}+ disabled={creating}+ title={`Add a ${kind.singular} manually`}+ aria-label={`Add ${kind.singular}`}+ aria-expanded={adding}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed border border-port-border hover:border-port-accent/50"+ >+ {creating ? <Loader2 size={11} className="animate-spin" /> : <Plus size={11} />}+ Add+ </button>+ ) : null}{onPickFromCatalog ? (<buttontype="button"@@ -884,10 +963,52 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende</>);+ const addForm = adding ? (+ <div className="bg-port-bg border border-port-border rounded p-2 mb-2 flex flex-col gap-2">+ <input+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') submitAdd(); }}+ placeholder={`${kind.singular[0].toUpperCase()}${kind.singular.slice(1)} name`}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ maxLength={BIBLE_LIMITS.NAME_MAX}+ autoFocus+ aria-label={`New ${kind.singular} name`}+ />+ <textarea+ value={newDesc}+ onChange={(e) => setNewDesc(e.target.value)}+ placeholder={`Describe this ${kind.singular} (optional — image-gen-ready prose)`}+ className="bg-port-card border border-port-border rounded px-2 py-1 text-white text-sm"+ rows={2}+ maxLength={kind.descFieldMax}+ aria-label={`New ${kind.singular} description`}+ />+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={submitAdd}+ disabled={!newName.trim() || creating}+ className="inline-flex items-center gap-1 text-xs px-2 py-1 bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 text-white rounded"+ >+ {creating ? <Loader2 size={12} className="animate-spin" /> : null}+ Save+ </button>+ <button+ type="button"+ onClick={cancelAdd}+ className="text-xs px-2 py-1 bg-port-bg hover:bg-port-border text-gray-300 rounded"+ >+ Cancel+ </button>+ </div>+ </div>+ ) : null;+const list = all.length === 0 ? (filtered && totalCount > 0? <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} in the selected series. {totalCount} total in this universe — clear the filter to see them all.</p>- : <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} yet. Use <em>Extract from prose</em> above to populate this list from an issue.</p>+ : <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} yet. Use <em>Add</em> or <em>Extract from prose</em> above to populate this list.</p>) : (<ul className="space-y-2">{all.map((entry) => (@@ -937,6 +1058,7 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende</span>{controls}</div>+ {addForm}{list}</div>);@@ -954,7 +1076,7 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende{controls}</div></div>- <div className="p-3">{list}</div>+ <div className="p-3">{addForm}{list}</div></section>);}