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
fix: show an error with Retry instead of 'no engine', 'no models' or 'no checkpoints' when LoRA training reads fail (#12807)
[._.]/ Adam Eivy280a68877824
diff --git a/client/src/components/loraTraining/CheckpointPicker.jsx b/client/src/components/loraTraining/CheckpointPicker.jsxindex d1494ce4bd..cdbf0e196e 100644--- a/client/src/components/loraTraining/CheckpointPicker.jsx+++ b/client/src/components/loraTraining/CheckpointPicker.jsx@@ -12,6 +12,8 @@import { useState, useCallback } from 'react';import useMounted from '../../hooks/useMounted';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';import { Layers, Loader2, CheckCircle2, AlertTriangle } from 'lucide-react';import toast from '../ui/Toast';import {@@ -21,25 +23,25 @@ import {export default function CheckpointPicker({ run, onPromoted }) {const [expanded, setExpanded] = useState(false);- const [checkpoints, setCheckpoints] = useState(null);- const [loading, setLoading] = useState(false);+ // Stays true after the first expand so collapsing does not drop a loaded (or+ // failed, retryable) list back to a refetch.+ const [opened, setOpened] = useState(false);const [promotingStep, setPromotingStep] = useState(null);// Guards the background preview-poll setTimeout chain from firing after the// component unmounts (deferred-work-respects-unmount rule).const mountedRef = useMounted();- const load = useCallback(() => {- setLoading(true);- listLoraTrainingCheckpoints(run.id)- .then((res) => setCheckpoints(Array.isArray(res?.checkpoints) ? res.checkpoints : []))- .catch(err => { console.warn('⚠️ Failed to load checkpoints: ' + err.message); setCheckpoints([]); })- .finally(() => setLoading(false));- }, [run.id]);+ const fetchCheckpoints = useCallback(+ () => listLoraTrainingCheckpoints(run.id, { silent: true }).then((res) => (Array.isArray(res?.checkpoints) ? res.checkpoints : [])),+ [run.id],+ );+ const { items: checkpoints, state, error, retry, setItems: setCheckpoints } = useListResource(fetchCheckpoints, { enabled: opened });+ const loading = state === 'loading';const toggle = () => {const next = !expanded;setExpanded(next);- if (next && checkpoints === null) load();+ if (next) setOpened(true);};const promote = async (step) => {@@ -48,14 +50,14 @@ export default function CheckpointPicker({ run, onPromoted }) {// background (its step wasn't on the sample cadence — e.g. the final step).// That render takes minutes, so poll a few times to surface it once ready// without a full page reload. (No socket event for this; bounded polling.)- const lacksPreview = !checkpoints?.find((c) => c.step === step)?.hasPreview;+ const lacksPreview = !checkpoints.find((c) => c.step === step)?.hasPreview;try {await promoteLoraTrainingCheckpoint(run.id, step, { silent: true });toast.success(`Promoted checkpoint @ step ${step}`);// Reactive: mark the chosen step deployed locally, then refetch + bubble// up so the parent's run record (loraFilename, selected step) refreshes.- setCheckpoints((prev) => prev?.map((c) => ({ ...c, deployed: c.step === step })) ?? prev);- load();+ setCheckpoints((prev) => prev.map((c) => ({ ...c, deployed: c.step === step })));+ retry();onPromoted?.();if (lacksPreview) {// Backstop poll for the background-rendered preview (~5 min on 9B).@@ -64,7 +66,7 @@ export default function CheckpointPicker({ run, onPromoted }) {const tick = () => {if (!mountedRef.current) return;attempts += 1;- listLoraTrainingCheckpoints(run.id)+ listLoraTrainingCheckpoints(run.id, { silent: true }).then((res) => {if (!mountedRef.current) return;const list = Array.isArray(res?.checkpoints) ? res.checkpoints : [];@@ -94,7 +96,7 @@ export default function CheckpointPicker({ run, onPromoted }) {aria-expanded={expanded}><Layers className="w-3.5 h-3.5 text-port-accent" />- Checkpoints{checkpoints ? ` (${checkpoints.length})` : ''}+ Checkpoints{state === 'ready' ? ` (${checkpoints.length})` : ''}<span className="text-gray-500">{expanded ? '▲' : '▼'}</span></button>@@ -112,10 +114,11 @@ export default function CheckpointPicker({ run, onPromoted }) {<Loader2 className="w-3.5 h-3.5 animate-spin" /> Loading checkpoints…</div>)}- {!loading && checkpoints?.length === 0 && (+ {state === 'error' && <ListLoadError what="checkpoints" error={error} onRetry={retry} />}+ {state === 'ready' && checkpoints.length === 0 && (<div className="text-xs text-gray-500">No checkpoints recorded for this run.</div>)}- {!loading && !!checkpoints?.length && (+ {!loading && checkpoints.length > 0 && (<><div className="text-[11px] text-gray-500 mb-1.5">Pick by the preview — loss is shown but is not a quality ranking.diff --git a/client/src/components/loraTraining/CheckpointPicker.test.jsx b/client/src/components/loraTraining/CheckpointPicker.test.jsxnew file mode 100644index 0000000000..681f990ed1--- /dev/null+++ b/client/src/components/loraTraining/CheckpointPicker.test.jsx@@ -0,0 +1,40 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+const listLoraTrainingCheckpoints = vi.fn();+vi.mock('../../services/api', () => ({+ listLoraTrainingCheckpoints: (...a) => listLoraTrainingCheckpoints(...a),+ promoteLoraTrainingCheckpoint: vi.fn(),+}));++import CheckpointPicker from './CheckpointPicker';++const expand = async () => {+ render(<CheckpointPicker run={{ id: 'run-1', output: {} }} />);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Checkpoints/ })); });+};++beforeEach(() => vi.clearAllMocks());++describe('CheckpointPicker', () => {+ it('shows a Retry — not "No checkpoints recorded" — when the list read fails, and lists them on retry', async () => {+ listLoraTrainingCheckpoints.mockRejectedValueOnce(new Error('Server unavailable'));+ await expand();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load checkpoints — Server unavailable');+ expect(screen.queryByText(/No checkpoints recorded/)).toBeNull();++ listLoraTrainingCheckpoints.mockResolvedValueOnce({ checkpoints: [{ step: 500, loss: 0.1, hasPreview: true, previewUrl: '/p.png' }] });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('step 500')).toBeInTheDocument();+ });++ it('says "No checkpoints recorded" only for a successful empty list', async () => {+ listLoraTrainingCheckpoints.mockResolvedValueOnce({ checkpoints: [] });+ await expand();+ expect(screen.getByText('No checkpoints recorded for this run.')).toBeInTheDocument();+ });+});diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsxindex 5f2519ce82..6088ab1756 100644--- a/client/src/components/loraTraining/TrainingPanel.jsx+++ b/client/src/components/loraTraining/TrainingPanel.jsx@@ -13,6 +13,8 @@ import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles, RotateCcw,import toast from '../ui/Toast';import { useSseProgress } from '../../hooks/useSseProgress';import { useAsyncAction } from '../../hooks/useAsyncAction';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';import CheckpointPicker from './CheckpointPicker';import LiveSampleGallery from './LiveSampleGallery';import {@@ -27,13 +29,33 @@ import {const isActive = (run) => run && ['queued', 'running'].includes(run.status);+// The status is a single object; wrapping it in a one-item list lets it ride+// the same loading | ready | error resource as the lists, so a failed read is+// never mistaken for "no engine installed".+const fetchStatus = () => getLoraTrainingStatus({ silent: true }).then((s) => [s]);++// FLUX.2 Klein only — mflux ≥0.17 dropped FLUX.1 training, and the torch+// fallback trains the same bf16 Klein bases.+const fetchTrainableModels = () => listImageModels({ silent: true })+ .then((list) => (Array.isArray(list) ? list : []).filter((m) => m.runner === 'flux2'));++// Default to the 9B base — it captures identity better than 4B and trains+// fine via 4-bit QLoRA (the server forces the panic-safe quant tier+// regardless of which inference id is picked). Prefer the plain 9B id we+// validated (flux2-klein-9b); avoid the explicit *-bf16 variant (the heavy+// path that GPU-watchdog-panics this M5). Fall back to any 9B, then first.+const defaultBaseModelId = (trainable) => {+ const nineB = trainable.filter((m) => /9b/i.test(m.id));+ const nonBf16 = nineB.find((m) => !/bf16/i.test(m.id));+ return (nonBf16 || nineB[0] || trainable[0])?.id || '';+};+export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunFinished }) {- const [status, setStatus] = useState(null);- const [models, setModels] = useState([]);+ const { items: statusItems, state: statusState, error: statusError, retry: retryStatus } = useListResource(fetchStatus);+ const status = statusItems[0] ?? null;+ const { items: models, state: modelsState, error: modelsError, retry: retryModels } = useListResource(fetchTrainableModels);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);const [resuming, setResuming] = useState(false);@@ -43,28 +65,12 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunconst [captionLeak, setCaptionLeak] = useState({ fragments: [], total: 0 });useEffect(() => {- getLoraTrainingStatus().then((s) => {- setStatus(s);- setParams((prev) => prev || { ...s.defaults });- }).catch(err => { console.warn('⚠️ Failed to load training status: ' + err.message); setStatus({ runtimes: {}, defaults: {} }); });- listImageModels().then((list) => {- // FLUX.2 Klein only — mflux ≥0.17 dropped FLUX.1 training, and the- // torch fallback trains the same bf16 Klein bases.- const trainable = (Array.isArray(list) ? list : []).filter((m) => m.runner === 'flux2');- setModels(trainable);- // Default to the 9B base — it captures identity better than 4B and trains- // fine via 4-bit QLoRA (the server forces the panic-safe quant tier- // regardless of which inference id is picked). Prefer the plain 9B id we- // validated (flux2-klein-9b); avoid the explicit *-bf16 variant (the heavy- // path that GPU-watchdog-panics this M5). Fall back to any 9B, then first.- setBaseModelId((prev) => {- if (prev) return prev;- const nineB = trainable.filter((m) => /9b/i.test(m.id));- const nonBf16 = nineB.find((m) => !/bf16/i.test(m.id));- return (nonBf16 || nineB[0] || trainable[0])?.id || '';- });- }).catch(err => { console.warn('⚠️ Failed to load image models: ' + err.message); setModels([]); });- }, []);+ if (status) setParams((prev) => prev || { ...status.defaults });+ }, [status]);++ useEffect(() => {+ if (modelsState === 'ready') setBaseModelId((prev) => prev || defaultBaseModelId(models));+ }, [models, modelsState]);// A reassigned dataset keeps its id but its old runs belong to the previous// subject. Re-fetch (and re-filter) whenever the subject identity moves,@@ -74,23 +80,30 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunconst charEntryId = dataset.character?.entryId;const charUniverseId = dataset.character?.universeId;const charEntryKind = dataset.character?.entryKind || 'characters';- const refreshRuns = useCallback(() => {+ const fetchRuns = useCallback(() => (// Query by dataset id, then guard by the full subject identity. That covers// character/object/place reassignments without relying on the legacy// `character_id` mirror column.- listLoraTrainingRuns({ datasetId: dataset.id, limit: 5 }).then((runs) => {- const own = (Array.isArray(runs) ? runs : []).filter(- (r) => !r.character || (- r.character.entryId === charEntryId- && r.character.universeId === charUniverseId- && (r.character.entryKind || 'characters') === charEntryKind- ),- );- setActiveRun(own.find(isActive) || null);- setLastRun(own.find((r) => !isActive(r)) || null);- }).catch(err => console.warn('⚠️ Failed to refresh training runs: ' + err.message));- }, [dataset.id, charEntryId, charEntryKind, charUniverseId]);- useEffect(() => { refreshRuns(); }, [refreshRuns]);+ listLoraTrainingRuns({ datasetId: dataset.id, limit: 5 }, { silent: true }).then((runs) => (Array.isArray(runs) ? runs : []).filter(+ (r) => !r.character || (+ r.character.entryId === charEntryId+ && r.character.universeId === charUniverseId+ && (r.character.entryKind || 'characters') === charEntryKind+ ),+ ))+ ), [dataset.id, charEntryId, charEntryKind, charUniverseId]);+ const { items: runs, state: runsState, error: runsError, retry: retryRuns, setItems: setRuns } = useListResource(fetchRuns);+ const activeRun = runs.find(isActive) || null;+ const lastRun = runs.find((r) => !isActive(r)) || null;+ // Re-read in place so the panel does not flash back to the launch form. A+ // failed re-read drops to the resource's error state, which disables Start:+ // an unknown run state must never offer a second multi-hour launch.+ const refreshRuns = useCallback(() => {+ fetchRuns().then(setRuns).catch((err) => {+ console.warn('⚠️ Failed to refresh training runs: ' + err.message);+ retryRuns();+ });+ }, [fetchRuns, setRuns, retryRuns]);const sseUrl = activeRun ? `/api/lora-training/runs/${activeRun.id}/events` : null;const { frames, latest, closed } = useSseProgress(sseUrl, { enabled: !!activeRun });@@ -181,8 +194,12 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRunconst disabledReason = !readiness?.trainable? `Needs ${readiness?.required ?? 10} captioned images (have ${readiness?.captioned ?? 0})`: triggerSaving ? 'Saving trigger word…'+ : statusState === 'error' ? 'Could not read training status'+ : runsState === 'error' ? 'Could not read training runs'+ : modelsState === 'error' ? 'Could not load base models'+ : (statusState === 'loading' || runsState === 'loading') ? 'Checking training status…': !baseModelId ? 'Pick a base model'- : (status && !engineReady) ? 'No training engine — install mflux ≥0.17 or run scripts/setup-image-video.sh'+ : !engineReady ? 'No training engine — install mflux ≥0.17 or run scripts/setup-image-video.sh': null;if (activeRun) {@@ -280,18 +297,27 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun{(lastRun?.status === 'completed' || lastRunCheckpoints > 0) && (<CheckpointPicker run={lastRun} onPromoted={refreshRuns} />)}+ {statusState === 'error' && <ListLoadError what="training status" error={statusError} onRetry={retryStatus} />}+ {runsState === 'error' && <ListLoadError what="training runs" error={runsError} onRetry={retryRuns} />}<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>+ {modelsState === 'error' ? (+ <ListLoadError what="base models" error={modelsError} onRetry={retryModels} />+ ) : (+ <>+ <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"+ >+ {modelsState === 'loading' && <option value="">Loading models…</option>}+ {modelsState === 'ready' && !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],diff --git a/client/src/components/loraTraining/TrainingPanel.test.jsx b/client/src/components/loraTraining/TrainingPanel.test.jsxnew file mode 100644index 0000000000..749509c59e--- /dev/null+++ b/client/src/components/loraTraining/TrainingPanel.test.jsx@@ -0,0 +1,109 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../hooks/useSseProgress', () => ({+ useSseProgress: () => ({ frames: [], latest: null, closed: false }),+}));+vi.mock('./LiveSampleGallery', () => ({ default: () => <div>live samples</div> }));+vi.mock('./CheckpointPicker', () => ({ default: () => null }));++const getLoraTrainingStatus = vi.fn();+const listLoraTrainingRuns = vi.fn();+const listImageModels = vi.fn();+vi.mock('../../services/api', () => ({+ getLoraTrainingStatus: (...a) => getLoraTrainingStatus(...a),+ listLoraTrainingRuns: (...a) => listLoraTrainingRuns(...a),+ listImageModels: (...a) => listImageModels(...a),+ startLoraTrainingRun: vi.fn(),+ cancelLoraTrainingRun: vi.fn(),+ resumeLoraTrainingRun: vi.fn(),+ stripLoraDatasetSharedCaptionFragments: vi.fn(),+}));++import TrainingPanel from './TrainingPanel';++const READY_STATUS = { runtimes: { mflux: { ready: true } }, defaults: { steps: 1000, rank: 16 } };+const MODELS = [{ id: 'flux2-klein-9b', name: 'Klein 9B', runner: 'flux2' }, { id: 'flux1-dev', runner: 'flux1' }];+const READINESS = { trainable: true, captioned: 12, required: 10, recommended: 20, quality: 'good' };+const ACTIVE_RUN = { id: 'run-1', status: 'running', runtime: 'mflux', baseModelId: 'flux2-klein-9b', progress: { step: 1, totalSteps: 10 } };++const renderPanel = async () => {+ render(+ <MemoryRouter>+ <TrainingPanel dataset={{ id: 'ds-1' }} readiness={READINESS} triggerSaving={false} />+ </MemoryRouter>,+ );+ await act(async () => {});+};++const trainButton = () => screen.getByRole('button', { name: /Train$/ });++beforeEach(() => {+ vi.clearAllMocks();+ getLoraTrainingStatus.mockResolvedValue(READY_STATUS);+ listLoraTrainingRuns.mockResolvedValue([]);+ listImageModels.mockResolvedValue(MODELS);+});++describe('TrainingPanel failed reads', () => {+ it('offers Start when every read succeeds', async () => {+ await renderPanel();+ expect(trainButton()).toBeEnabled();+ expect(screen.getByLabelText('Base model')).toHaveValue('flux2-klein-9b');+ });++ it('shows a Retry — not the mflux install message — when the status read fails, and recovers on retry', async () => {+ getLoraTrainingStatus.mockRejectedValueOnce(new Error('Gateway timeout'));+ await renderPanel();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load training status — Gateway timeout');+ expect(screen.getByText('Could not read training status')).toBeInTheDocument();+ expect(screen.queryByText(/No training engine/)).toBeNull();+ expect(trainButton()).toBeDisabled();++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByLabelText('Steps')).toHaveValue(1000);+ expect(trainButton()).toBeEnabled();+ });++ it('still reports a missing engine when the status read succeeds with no ready runtime', async () => {+ getLoraTrainingStatus.mockResolvedValue({ runtimes: {}, defaults: {} });+ await renderPanel();+ expect(screen.getByText(/No training engine/)).toBeInTheDocument();+ expect(trainButton()).toBeDisabled();+ });++ it('disables Start with a Retry when the runs read fails, then shows the in-progress view for an active run', async () => {+ listLoraTrainingRuns.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderPanel();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load training runs — Server unavailable');+ expect(trainButton()).toBeDisabled();++ listLoraTrainingRuns.mockResolvedValueOnce([ACTIVE_RUN]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.getByText(/Training mflux/)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Train$/ })).toBeNull();+ });++ it('shows an error row — not "No trainable models registered" — when the models read fails', async () => {+ listImageModels.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderPanel();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load base models — Server unavailable');+ expect(screen.queryByText('No trainable models registered')).toBeNull();+ expect(trainButton()).toBeDisabled();++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.getByLabelText('Base model')).toHaveValue('flux2-klein-9b');+ expect(trainButton()).toBeEnabled();+ });++ it('says "No trainable models registered" only for a successful empty list', async () => {+ listImageModels.mockResolvedValue([{ id: 'flux1-dev', runner: 'flux1' }]);+ await renderPanel();+ expect(screen.getByText('No trainable models registered')).toBeInTheDocument();+ });+});diff --git a/client/src/components/loraTraining/UniverseCharacterPicker.jsx b/client/src/components/loraTraining/UniverseCharacterPicker.jsxindex 2e63236773..a4b2bc4b03 100644--- a/client/src/components/loraTraining/UniverseCharacterPicker.jsx+++ b/client/src/components/loraTraining/UniverseCharacterPicker.jsx@@ -9,7 +9,9 @@* `onUniverseChange` handler should reset it.*/-import { useState, useEffect } from 'react';+import { useCallback } from 'react';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';import { listUniverses, getUniverse } from '../../services/api';const ENTRY_KINDS = [@@ -17,6 +19,7 @@ const ENTRY_KINDS = [{ value: 'objects', label: 'Object', empty: 'No objects in this universe', pick: 'Pick an object' },{ value: 'places', label: 'Place', empty: 'No places in this universe', pick: 'Pick a place' },];+const fetchUniverses = () => listUniverses({ silent: true });const kindConfig = (entryKind) => ENTRY_KINDS.find((k) => k.value === entryKind) || ENTRY_KINDS[0];export default function UniverseCharacterPicker({@@ -29,33 +32,13 @@ export default function UniverseCharacterPicker({idPrefix = 'ucp',disabledEntryIds = [],}) {- const [universes, setUniverses] = useState(null);- const [universe, setUniverse] = useState(null);- const [entries, setEntries] = useState(null);-- useEffect(() => {- listUniverses().then((list) => setUniverses(Array.isArray(list) ? list : []))- .catch(err => { console.warn('⚠️ Failed to load universes: ' + err.message); setUniverses([]); });- }, []);-- useEffect(() => {- if (!universeId) { setUniverse(null); setEntries(null); return undefined; }- let active = true;- setUniverse(null);- setEntries(null);- getUniverse(universeId, { silent: true })- .then((u) => { if (active) setUniverse(u || {}); })- .catch(err => {- console.warn('⚠️ Failed to load universe: ' + err.message);- if (active) setUniverse({});- });- return () => { active = false; };- }, [universeId]);-- useEffect(() => {- if (!universeId || !universe) return;- setEntries(Array.isArray(universe?.[entryKind]) ? universe[entryKind] : []);- }, [universeId, universe, entryKind]);+ const { items: universes, state: universesState, error: universesError, retry: retryUniverses } = useListResource(fetchUniverses);+ // One universe is a single object; a one-item list gives its read the same+ // loading | ready | error states, so a failed read never renders as an empty+ // subject list.+ const fetchUniverse = useCallback(() => getUniverse(universeId, { silent: true }).then((u) => [u || {}]), [universeId]);+ const { items: universeItems, state: universeState, error: universeError, retry: retryUniverse } = useListResource(fetchUniverse, { enabled: !!universeId });+ const entries = universeState === 'ready' && Array.isArray(universeItems[0]?.[entryKind]) ? universeItems[0][entryKind] : [];const disabled = new Set(disabledEntryIds);const kind = kindConfig(entryKind);@@ -70,9 +53,10 @@ export default function UniverseCharacterPicker({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>)}+ <option value="">{universesState === 'loading' ? 'Loading…' : 'Pick a universe'}</option>+ {universes.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</select>+ {universesState === 'error' && <ListLoadError className="mt-1" what="universes" error={universesError} onRetry={retryUniverses} />}</div>{universeId && (<>@@ -95,13 +79,16 @@ export default function UniverseCharacterPicker({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="">{entries === null ? 'Loading…' : entries.length ? kind.pick : kind.empty}</option>- {(entries || []).map((entry) => (+ <option value="">+ {universeState === 'loading' ? 'Loading…' : universeState === 'error' ? 'Unavailable' : entries.length ? kind.pick : kind.empty}+ </option>+ {entries.map((entry) => (<option key={entry.id} value={entry.id} disabled={disabled.has(entry.id)}>{entry.name || entry.slugline || entry.id}{disabled.has(entry.id) ? ' (current)' : ''}</option>))}</select>+ {universeState === 'error' && <ListLoadError className="mt-1" what="the universe" error={universeError} onRetry={retryUniverse} />}</div></>)}diff --git a/client/src/components/loraTraining/UniverseCharacterPicker.test.jsx b/client/src/components/loraTraining/UniverseCharacterPicker.test.jsxnew file mode 100644index 0000000000..cfdfab8a3d--- /dev/null+++ b/client/src/components/loraTraining/UniverseCharacterPicker.test.jsx@@ -0,0 +1,51 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';++const listUniverses = vi.fn();+const getUniverse = vi.fn();+vi.mock('../../services/api', () => ({+ listUniverses: (...a) => listUniverses(...a),+ getUniverse: (...a) => getUniverse(...a),+}));++import UniverseCharacterPicker from './UniverseCharacterPicker';++const renderPicker = async () => {+ render(<UniverseCharacterPicker universeId="u1" entryKind="characters" entryId="" onUniverseChange={vi.fn()} onEntryChange={vi.fn()} />);+ await act(async () => {});+};++beforeEach(() => {+ vi.clearAllMocks();+ listUniverses.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);+});++describe('UniverseCharacterPicker', () => {+ it('shows a Retry — not "No characters in this universe" — when the universe read fails, and lists them on retry', async () => {+ getUniverse.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderPicker();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load the universe — Server unavailable');+ expect(screen.queryByText('No characters in this universe')).toBeNull();++ getUniverse.mockResolvedValueOnce({ characters: [{ id: 'c1', name: 'Alice' }] });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('option', { name: 'Alice' })).toBeInTheDocument();+ });++ it('shows a Retry — not an empty universe picker — when the universe list read fails', async () => {+ listUniverses.mockRejectedValueOnce(new Error('Server unavailable'));+ getUniverse.mockResolvedValue({ characters: [] });+ await renderPicker();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load universes — Server unavailable');++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.getByRole('option', { name: 'Example Universe' })).toBeInTheDocument();+ });++ it('says "No characters in this universe" only after a successful empty read', async () => {+ getUniverse.mockResolvedValue({ characters: [] });+ await renderPicker();+ expect(screen.getByText('No characters in this universe')).toBeInTheDocument();+ });+});diff --git a/client/src/listFetchConventions.test.js b/client/src/listFetchConventions.test.jsindex 96977752bc..514a8c0e13 100644--- a/client/src/listFetchConventions.test.js+++ b/client/src/listFetchConventions.test.js@@ -18,13 +18,14 @@* stays honest. The page sweeps (#12169–#12171) and the app detail tabs* (#12591) are done; the remaining component sites are tracked by surface in* #12783 (Digital Twin), #12784 (Brain/MeatSpace/Messages/Privacy/Tribe),- * #12785 (creative panels) and #12786 (settings/sharing/CoS/providers).+ * #12785 (creative panels), #12807 (LoRA training panel) and #12786 (settings/sharing/CoS/providers).** ## What this guard CANNOT see** It is a source grep, not an AST pass:- * - A catch whose body does more than clear the list (`{ setX([]); setLoading(false); }`)- * is not matched; so is a `.catch` passed a named function.+ * - A catch whose body does more than clear the list after its leading+ * statements (`{ setX([]); setLoading(false); }`) is not matched; so is a+ * `.catch` passed a named function.* - A collapse moved into a hook or lib module is invisible (that is also where* a shared, state-carrying read belongs).* - A match inside a comment or string counts.@@ -48,12 +49,18 @@ const SCAN_PREFIXES = ['src/pages/', 'src/components/'];* `if (!cancelled)`), the keyed-map setter `setX((m) => ({ ...m, [id]: [] }))`* (bare or braced), and the object-literal spelling* `.catch(() => ({ agents: [], summary: {} }))` (a list under a key, one level- * of nested braces allowed). The setter must start with `set` + a capital, so+ * of nested braces allowed; an object that also carries an `error` key is a+ * handled failure, not a collapse). A named parameter (`err =>`) and leading+ * statements (`console.warn(...); setX([]);`) are allowed. The setter must start with `set` + a capital, so* `.catch(() => reset([]))` and a non-setter call stay out.*/const EMPTY_SETTER = String.raw`set[A-Z]\w*\(\s*(?:\[\]|\(\s*\w+\s*\)\s*=>\s*\(\s*\{\s*\.\.\.\w+\s*,\s*\[[^\]]+\]\s*:\s*\[\]\s*\}\s*\))\s*\)`;+// Leading statements of a braced arm, e.g. the `console.warn(...)` in+// `err => { console.warn(...); setX([]); }`. None may call a setter: a catch+// that also records the failure (`setLoadError(err)`) is a handled read.+const LEADING_STATEMENTS = String.raw`(?:(?:(?!\bset[A-Z])(?:[^{};]|\$\{[^{}]*\}))*;\s*)*`;export const LIST_COLLAPSE = new RegExp(- String.raw`\.catch\(\s*\(\s*\)\s*=>\s*(?:\[\]|\{\s*(?:if\s*\([^()]*\)\s*)?${EMPTY_SETTER}\s*;?\s*\}|${EMPTY_SETTER}|\(\s*\{(?:[^{}]|\{[^{}]*\})*?\b\w+\s*:\s*\[\](?:[^{}]|\{[^{}]*\})*\}\s*\))\s*\)`,+ String.raw`\.catch\(\s*(?:\(\s*\)|\(\s*\w+\s*\)|\w+)\s*=>\s*(?:\[\]|\{\s*${LEADING_STATEMENTS}(?:if\s*\([^()]*\)\s*)?${EMPTY_SETTER}\s*;?\s*\}|${EMPTY_SETTER}|\(\s*\{(?!(?:[^{}]|\{[^{}]*\})*\berror\b)(?:[^{}]|\{[^{}]*\})*?\b\w+\s*:\s*\[\](?:[^{}]|\{[^{}]*\})*\}\s*\))\s*\)`,'g',);@@ -63,6 +70,9 @@ export const LIST_COLLAPSE = new RegExp(*/const KNOWN = Object.freeze({'src/components/privacy/PrivacyOrgsTab.jsx': 2,+ // Named-parameter, multi-statement spelling (#12807); migrated under #12819.+ 'src/components/loraTraining/CharacterLoraChip.jsx': 1,+ 'src/components/meatspace/post/MemoryPractice.jsx': 1,// Spellings the widened pattern (#12790) newly sees; migrated under #12804.'src/components/CmdKSearch.jsx': 1,'src/components/TagPicker.jsx': 1,@@ -123,6 +133,9 @@ describe('page list fetches keep a failed read distinct from an empty list', ()'getBranches(p).catch(() => ({ summary: {}, branches: [] }))','getJiraBoards(i).catch(() => { if (!cancelled) setBoards([]); })','listShareInbox(id).catch(() => setInboxByBucket((m) => ({ ...m, [bucketId]: [] })))',+ 'getUniverses().catch(err => { console.warn(`⚠️ Failed: ${err.message}`); setUniverses([]); })',+ 'getChunks().catch(err => {\n console.warn(\'x: \' + err.message);\n if (active) setChunkMastery([]);\n })',+ 'listCheckpoints(id).catch((e) => setCheckpoints([]))','listShareActivity(id).catch(() => { setActivityByBucket((m) => ({ ...m, [id]: [] })); })',]) expect(countIn(sample), sample).toBe(1);for (const sample of [@@ -132,6 +145,10 @@ describe('page list fetches keep a failed read distinct from an empty list', ()'getAppTaskTypes(id).catch(() => ({ taskTypeOverrides: {} }))','load().catch(() => { if (!cancelled) { setRows([]); setFailed(true); } })','load().catch(() => setInboxByBucket((m) => ({ ...m, [bucketId]: m[bucketId] })))',+ 'load().catch(err => { console.warn(err.message); setRows([]); setLoadError(err); })',+ 'load().catch(err => { setLoadError(err); setRows([]); })',+ 'load().catch(error => ({ key, data: [], error }))',+ 'load().catch((err) => ({ error: err.message, posts: [] }))','load().catch(() => ({ providers: [], error: true }))'.replace('[], error', 'x, error'),]) expect(countIn(sample), sample).toBe(0);});diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.jsindex ea1e6f210c..1d20107806 100644--- a/client/src/services/apiLoraTraining.js+++ b/client/src/services/apiLoraTraining.js@@ -93,7 +93,7 @@ export const stripLoraDatasetSharedCaptionFragments = (id) =>// ---- Training runs -----export const getLoraTrainingStatus = () => request('/lora-training/status');+export const getLoraTrainingStatus = (options = {}) => request('/lora-training/status', options);export const startLoraTrainingRun = ({ datasetId, baseModelId, name, params, acknowledgeCaptionLeak }, options = {}) =>request('/lora-training/runs', {@@ -108,13 +108,13 @@ export const startLoraTrainingRun = ({ datasetId, baseModelId, name, params, ack}),});-export const listLoraTrainingRuns = (filters = {}) => {+export const listLoraTrainingRuns = (filters = {}, options = {}) => {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}` : ''}`);+ return request(`/lora-training/runs${qs ? `?${qs}` : ''}`, options);};export const cancelLoraTrainingRun = (runId) =>@@ -127,8 +127,8 @@ export const resumeLoraTrainingRun = (runId, { silent = false } = {}) =>// Checkpoints for a finished run — each with step, loss, preview thumbnail,// and which one is currently deployed. Drives the manual checkpoint picker.-export const listLoraTrainingCheckpoints = (runId) =>- request(`/lora-training/runs/${runId}/checkpoints`);+export const listLoraTrainingCheckpoints = (runId, options = {}) =>+ request(`/lora-training/runs/${runId}/checkpoints`, options);// Mid-training sample timeline (step + thumbnail URL) — seeds the live// progress gallery so a reload mid-run shows every sample rendered so far.