Skip to content

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

fix: show a failed list read with Retry instead of an empty picker

[._.]/ Adam Eivy1b18944ac732
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index e615541e69..90ee66bf18 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -17,6 +17,7 @@ import { formatCount } from '../../utils/formatters';
import ModelDownloadBadge, { deriveSizeEstimate } from '../media/ModelDownloadBadge';
import ResolutionField from '../media/ResolutionField';
import { FormField } from '../ui/FormField';
+import ListLoadError from '../ui/ListLoadError';
const QUANTIZE_OPTIONS = [
{ value: '3', label: '3-bit' },
@@ -29,6 +30,13 @@ const QUANTIZE_OPTIONS = [
export default function ImageGenControls({
mode,
models = [],
+ // `useListResource` state of the local model catalog. `null` (the default
+ // for callers that hand in a resolved list) renders as before; 'error' and
+ // an empty 'ready' list get their own rows so a failed read never looks
+ // like "no models".
+ modelsState = null,
+ modelsError = null,
+ onRetryModels,
modelId, onModelChange,
width, height, onResolutionChange,
steps, onStepsChange,
@@ -88,6 +96,14 @@ export default function ImageGenControls({
return (
<div className={className}>
+ {showModel && isLocal && modelsState === 'error' && (
+ <ListLoadError className="col-span-2 sm:col-span-3" what="the local model catalog" error={modelsError} onRetry={onRetryModels} />
+ )}
+ {showModel && isLocal && modelsState === 'ready' && models.length === 0 && (
+ <p role="status" className="col-span-2 sm:col-span-3 text-xs text-port-warning">
+ No local image models are compatible with this machine.
+ </p>
+ )}
{showModel && isLocal && models.length > 0 && (
<FormField label="Model" labelClassName="block text-xs font-medium text-gray-400 mb-1">
<select
diff --git a/client/src/components/imageGen/ImageGenFormEditor.jsx b/client/src/components/imageGen/ImageGenFormEditor.jsx
index b987d72539..af5b70956d 100644
--- a/client/src/components/imageGen/ImageGenFormEditor.jsx
+++ b/client/src/components/imageGen/ImageGenFormEditor.jsx
@@ -7,6 +7,7 @@ import RemoteMediaTargetPicker from '../federatedMedia/RemoteMediaTargetPicker';
import MusicVideoFilingSelect from '../media/MusicVideoFilingSelect';
import { FormField } from '../ui/FormField';
import Banner from '../ui/Banner';
+import ListLoadError from '../ui/ListLoadError';
import AutoSizeTextarea from '../ui/AutoSizeTextarea';
import ModelInputPreview from '../media/ModelInputPreview';
import HfTokenBanner from './HfTokenBanner';
@@ -214,6 +215,9 @@ export default function ImageGenFormEditor({ form, backend, generation }) {
<ImageGenControls
mode={effectiveMode}
models={catalogs.models}
+ modelsState={catalogs.modelsState}
+ modelsError={catalogs.modelsError}
+ onRetryModels={catalogs.retryModels}
modelId={fields.modelId}
onModelChange={actions.handleModelChange}
width={fields.width}
@@ -250,6 +254,9 @@ export default function ImageGenFormEditor({ form, backend, generation }) {
</p>
)}
+ {isLocalMode && catalogs.lorasState === 'error' && (
+ <ListLoadError what="the LoRA library" error={catalogs.lorasError} onRetry={catalogs.retryLoras} />
+ )}
{isLocalMode && (derived.remoteTargetActive || derived.currentModel?.supportsLoras !== false) && (
<LoraPicker
availableLoras={catalogs.availableLoras}
diff --git a/client/src/components/musicVideo/CreateProjectDrawer.jsx b/client/src/components/musicVideo/CreateProjectDrawer.jsx
index d18548075c..b08ce6c8ec 100644
--- a/client/src/components/musicVideo/CreateProjectDrawer.jsx
+++ b/client/src/components/musicVideo/CreateProjectDrawer.jsx
@@ -1,6 +1,7 @@
import MediaModePicker from './MediaModePicker.jsx';
import CharacterStyleSelect from './CharacterStyleSelect.jsx';
import { Bot, Clapperboard, Plus, Music, Sparkles, FileText, CheckCircle2 } from 'lucide-react';
+import ListLoadError from '../ui/ListLoadError';
import Drawer from '../Drawer.jsx';
import YoutubeImportControls from './YoutubeImportControls.jsx';
import AutomationBriefFields from './AutomationBriefFields.jsx';
@@ -21,7 +22,7 @@ const MODES = [
* 2. Lyrics, concept, and style info are automatically read from the chosen track.
* 3. Name, mode, character style, universe/moodboard, and brief settings.
*/
-export default function CreateProjectDrawer({ open, onClose, form, onFormChange, tracks, universes, trackName, youtube, onSubmit, submitting }) {
+export default function CreateProjectDrawer({ open, onClose, form, onFormChange, tracks, trackLibrary = null, universes, trackName, youtube, onSubmit, submitting }) {
const autopilot = form.mode === 'autonomous';
const optionLabels = trackOptionLabels(tracks || []);
const selectedTrack = (tracks || []).find((t) => t.id === form.trackId) || null;
@@ -72,6 +73,12 @@ export default function CreateProjectDrawer({ open, onClose, form, onFormChange,
</option>
))}
</select>
+ {trackLibrary?.state === 'error' && (
+ <ListLoadError what="the music library" error={trackLibrary.error} onRetry={trackLibrary.retry} />
+ )}
+ {trackLibrary?.state === 'ready' && !(tracks || []).length && (
+ <p className="text-xs text-port-text-muted">No tracks in the music library yet — import one below.</p>
+ )}
<div>
<span className="block text-xs text-port-text-muted mb-1">…or import a Suno song or YouTube audio</span>
diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsx
index 1130242eda..c064478f32 100644
--- a/client/src/components/musicVideo/TrackPanel.jsx
+++ b/client/src/components/musicVideo/TrackPanel.jsx
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { Music, Download } from 'lucide-react';
import toast from '../ui/Toast';
+import ListLoadError from '../ui/ListLoadError';
import MidiVisualization from '../songs/MidiVisualization.jsx';
import { trackAudioUrl } from '../../services/apiTracks.js';
import YoutubeImportControls from './YoutubeImportControls.jsx';
@@ -36,7 +37,7 @@ function timedDataLabels(project) {
* sound-design bed (#8988) mixes under the song only when explicitly chosen.
*/
export default function TrackPanel({
- project, tracks, trackName, audioFilename, youtube,
+ project, tracks, trackLibrary = null, trackName, audioFilename, youtube,
renderBound, midiBound, onChangeTrack,
}) {
// A pending change that would destroy timed data waits for explicit confirm.
@@ -77,6 +78,12 @@ export default function TrackPanel({
<option value="">Change track…</option>
{tracks.map((t) => <option key={t.id} value={t.id}>{optionLabels.get(t.id)}</option>)}
</select>
+ {trackLibrary?.state === 'error' && (
+ <ListLoadError className="basis-full" what="the music library" error={trackLibrary.error} onRetry={trackLibrary.retry} />
+ )}
+ {trackLibrary?.state === 'ready' && tracks.length === 0 && (
+ <span className="text-port-text-muted">No tracks in the music library yet.</span>
+ )}
<YoutubeImportControls
url={youtube.editUrl} onUrlChange={(e) => youtube.setEditUrl(e.target.value)}
job={youtube.editJob} disabled={renderBound || midiBound}
diff --git a/client/src/components/musicVideo/stages/SetupStage.jsx b/client/src/components/musicVideo/stages/SetupStage.jsx
index cc762dd07f..6d1beda5d1 100644
--- a/client/src/components/musicVideo/stages/SetupStage.jsx
+++ b/client/src/components/musicVideo/stages/SetupStage.jsx
@@ -89,6 +89,7 @@ export default function SetupStage({ board }) {
<TrackPanel
project={project}
tracks={tracks}
+ trackLibrary={board.trackLibrary}
trackName={trackName}
audioFilename={audioFilename}
youtube={youtube}
diff --git a/client/src/components/ui/ListLoadError.jsx b/client/src/components/ui/ListLoadError.jsx
new file mode 100644
index 0000000000..070a06bfd7
--- /dev/null
+++ b/client/src/components/ui/ListLoadError.jsx
@@ -0,0 +1,29 @@
+import { AlertTriangle } from 'lucide-react';
+
+/**
+ * Inline "this list failed to load" row with a Retry action, for a picker or
+ * a list section where a failed read must not render as "you have none".
+ * Pair with `useListResource`: render it on `state === 'error'` and the
+ * empty-list copy only on `state === 'ready'`. `LoadFailedState` is the
+ * page-sized version of the same contract.
+ */
+export default function ListLoadError({ what, error = null, onRetry, retrying = false, className = '' }) {
+ return (
+ <div role="alert" className={`flex flex-wrap items-center gap-2 rounded-lg border border-port-error/30 bg-port-error/5 px-3 py-2 text-xs text-port-error ${className}`}>
+ <AlertTriangle size={14} className="shrink-0" aria-hidden="true" />
+ <span className="min-w-0">
+ Could not load {what}{error?.message ? ` — ${error.message}` : ''}
+ </span>
+ {onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ disabled={retrying}
+ className="ml-auto min-h-[32px] rounded border border-port-border bg-port-card px-2 text-port-accent hover:text-white disabled:opacity-50"
+ >
+ {retrying ? 'Retrying…' : 'Retry'}
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.md
index e239197268..9570f4cf4b 100644
--- a/client/src/components/ui/README.md
+++ b/client/src/components/ui/README.md
@@ -26,6 +26,7 @@ accessibility). Feature-specific components live under their own feature directo
| `InfoTooltip` | Focusable info/help tooltip — hover, keyboard focus, or tap; opaque body portal with viewport-clamped numeric `width` (default 224), start/center/end alignment, keyboard scrolling, and Esc dismissal. |
| `InlineConfirmRow` | Inline "question + confirm + cancel" row — PortOS's preferred alternative to `window.confirm`. |
| `InlineDiff` | Stacked word-level diff — old row (red removals) over new row (green additions). |
+| `ListLoadError` | Inline failed-read row (message + Retry) for a picker or list section fed by `useListResource`; render on `state === 'error'` so a failed load never reads as an empty list. |
| `LoadFailedState` | Alert shown when a read failed (title, hint, Retry) so a failed load never renders as an empty-list sentence. |
| `Kbd` | Keycap for rendering a keyboard key in help/cheatsheet UI. |
| `Modal` | Shared modal chrome — backdrop, Esc handling, click-outside. |
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index edac2622cb..5f29f6437e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -298,6 +298,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useGeneratedPreview` | One OS-isolated generated-preview session. Emits `generated-preview:open` for `request` and returns inert JPEG frames, seek/command functions, and a recording blob. Reconnect opens a fresh session with the current controls and playhead; idle/capacity closure returns `status: 'idle'` until the viewer calls `resume()`. Film-look and title-card `controls` ride the open and later commands. A revision change reopens; a control change does not. Unsupported hosts surface `status: 'unavailable'` and never fall back to an iframe. | Music-video composition, code-video, and code-animation previews. |
| `useImageVariants` | Fetches the original-vs-cleaned variant set for the one open image (`GET /api/image-gen/:filename/variants`), normalized; reuses the held group across toggle clicks and aborts a superseded lookup. `null` while unfetched or failed, `[]` when the image is not indexed. | `MediaPreview` calls it for every image preview; neither a page-owned ref list nor a 60-row gallery window is a complete source of variant lineage. |
| `useGalleryPage` | Bounded image or mixed-media browsing with debounced server search, scopes, totals, stale-response cancellation and retryable next pages. `preserveLoadedOnRefresh` reloads the retained window in compact pages while keeping existing cards mounted. | Gallery grids and pickers; `getGalleryImages` hydrates known references separately. |
+| `useListResource` | `useListResource(fetcher, { enabled })` → `{ items, state: 'loading'\|'ready'\|'error', error, retry, setItems }` — one list read whose failure stays distinct from an empty result; a superseded response is dropped. `fetcher` must be referentially stable. | Any picker or list section fed by one list fetch (LoRA library, track library, model catalog) — render `<ListLoadError onRetry={retry}>` on `'error'` and the empty copy only on `'ready'`, never `.catch(() => [])`. |
| `usePagedCollection` | `usePagedCollection(fetchPage, { enabled })` — bounded cursor pages, deduplication by id, single-flight loading, abort/stale-query protection, retry, reset, and local mutation via setItems; an optional `meta` returned by `fetchPage` is exposed as the latest page's response-level data. | Growing cursor-based collections; pair with `InfiniteScrollFooter`. |
| `useGoalOrganize` / `useGoalCreate` | Shared goal suggestion preview, explicit apply, and guarded create flows for both Goals views. | Goals List and Tree views. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 0a5b7edbf4..ed906e6aed 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -213,6 +213,7 @@ export * from './useCmdKSearch.js';
export * from './useCooldownTick.js';
export { default as useDrawerTab } from './useDrawerTab.js';
export { default as useSettingsForm } from './useSettingsForm.js';
+export { default as useListResource } from './useListResource.js';
export { default as useDownloadPreflightConfirm } from './useDownloadPreflightConfirm.js';
export { default as useChordPlayer } from './useChordPlayer.js';
export { default as useDrumPlayer } from './useDrumPlayer.js';
diff --git a/client/src/hooks/useImageGenForm.js b/client/src/hooks/useImageGenForm.js
index 987992bb85..bed66288cc 100644
--- a/client/src/hooks/useImageGenForm.js
+++ b/client/src/hooks/useImageGenForm.js
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import useListResource from './useListResource';
import { getNavPageForPath } from '../../../server/lib/navManifest.js';
import { appendTriggerWords } from '../lib/loraTriggers';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
@@ -39,6 +40,11 @@ const revokeIfBlob = (url) => {
if (url?.startsWith('blob:')) URL.revokeObjectURL(url);
};
+// Stable fetchers for useListResource — the hook re-runs on identity change.
+// Silent: the form renders a failed catalog read itself, with Retry.
+const loadImageModels = () => listImageModels({ silent: true });
+const loadLoraLibrary = () => listLorasFull({ silent: true });
+
export function useImageGenForm({ searchParams, setSearchParams, backend }) {
const {
status,
@@ -53,12 +59,17 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {
setSelectedMode,
configureBackends,
} = backend;
- const [models, setModels] = useState([]);
- const [modelsLoaded, setModelsLoaded] = useState(false);
- const [modelsLoadFailed, setModelsLoadFailed] = useState(false);
- const [availableLoras, setAvailableLoras] = useState([]);
- const [lorasLoaded, setLorasLoaded] = useState(false);
- const [lorasLoadFailed, setLorasLoadFailed] = useState(false);
+ // The local model catalog and LoRA library. A failed read stays distinct
+ // from an empty list: the form shows it with Retry, and a Remix handoff that
+ // needs the catalog waits for it or reports the failure (never "no models").
+ const modelCatalog = useListResource(loadImageModels);
+ const loraCatalog = useListResource(loadLoraLibrary);
+ const models = modelCatalog.items;
+ const modelsLoaded = modelCatalog.state !== 'loading';
+ const modelsLoadFailed = modelCatalog.state === 'error';
+ const availableLoras = loraCatalog.items;
+ const lorasLoaded = loraCatalog.state !== 'loading';
+ const lorasLoadFailed = loraCatalog.state === 'error';
const [settingsLoadFailed, setSettingsLoadFailed] = useState(false);
const loraFilenameFromUrl = searchParams.get('lora');
const loraLookupSequenceRef = useRef(0);
@@ -161,31 +172,7 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {
setDenoise(savedDenoiseByMode[next] === true);
}, [savedCleanC2PAByMode, savedDenoiseByMode, setSelectedMode]);
- useEffect(() => {
- let active = true;
- listImageModels().then((loadedModels) => {
- if (!active) return;
- setModels(loadedModels);
- setModelsLoadFailed(false);
- setModelsLoaded(true);
- }).catch(() => {
- if (!active) return;
- setModelsLoadFailed(true);
- setModelsLoaded(true);
- });
- listLorasFull().then((loadedLoras) => {
- if (!active) return;
- setAvailableLoras(loadedLoras);
- setLorasLoadFailed(false);
- setLorasLoaded(true);
- }).catch(() => {
- if (!active) return;
- setLorasLoadFailed(true);
- setLorasLoaded(true);
- });
- reloadBackends();
- return () => { active = false; };
- }, [reloadBackends]);
+ useEffect(() => { reloadBackends(); }, [reloadBackends]);
const restoreActiveJob = useCallback((activeJob) => {
setStylePreset(null);
@@ -647,31 +634,11 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {
const filename = remixHandoff?.filename;
if (!filename) return;
if (remixHandoff.failure === 'catalog') {
- if (modelsLoadFailed) {
- setModelsLoaded(false);
- setModelsLoadFailed(false);
- listImageModels().then((loadedModels) => {
- setModels(loadedModels);
- setModelsLoaded(true);
- }).catch(() => {
- setModelsLoadFailed(true);
- setModelsLoaded(true);
- });
- }
- if (lorasLoadFailed) {
- setLorasLoaded(false);
- setLorasLoadFailed(false);
- listLorasFull().then((loadedLoras) => {
- setAvailableLoras(loadedLoras);
- setLorasLoaded(true);
- }).catch(() => {
- setLorasLoadFailed(true);
- setLorasLoaded(true);
- });
- }
+ if (modelsLoadFailed) modelCatalog.retry();
+ if (lorasLoadFailed) loraCatalog.retry();
}
lookupRemixHandoff(filename);
- }, [remixHandoff, modelsLoadFailed, lorasLoadFailed, lookupRemixHandoff]);
+ }, [remixHandoff, modelsLoadFailed, lorasLoadFailed, lookupRemixHandoff, modelCatalog.retry, loraCatalog.retry]);
const dismissRemixHandoff = useCallback(() => {
remixLookupSequenceRef.current += 1;
@@ -722,7 +689,13 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {
},
catalogs: {
models,
+ modelsState: modelCatalog.state,
+ modelsError: modelCatalog.error,
+ retryModels: modelCatalog.retry,
availableLoras,
+ lorasState: loraCatalog.state,
+ lorasError: loraCatalog.error,
+ retryLoras: loraCatalog.retry,
},
settings: {
savedAgyModel,
diff --git a/client/src/hooks/useListResource.js b/client/src/hooks/useListResource.js
new file mode 100644
index 0000000000..036ac67c2f
--- /dev/null
+++ b/client/src/hooks/useListResource.js
@@ -0,0 +1,53 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+const LOADING = Object.freeze({ items: [], state: 'loading', error: null });
+
+/**
+ * A list read that never collapses "failed" into "empty".
+ *
+ * Returns `{ items, state, error, retry, setItems }` where `state` is
+ * `'loading' | 'ready' | 'error'`. `items` is `[]` while loading and after a
+ * failure so consumers that only read the array keep working, but a picker
+ * gates its "you have none" copy on `state === 'ready'` and renders
+ * `<ListLoadError onRetry={retry}>` on `'error'` — the client side of the
+ * root AGENTS.md sentinel rule (absent vs failed vs legitimately empty).
+ *
+ * `fetcher` must be referentially stable (a module-level function or a
+ * `useCallback`); it re-runs when its identity changes and on `retry()`, and
+ * a response from a superseded run is dropped. `enabled: false` holds the
+ * resource at `'loading'` without a request. `setItems` applies a local
+ * mutation (an import appending a row) without a refetch.
+ */
+export default function useListResource(fetcher, { enabled = true } = {}) {
+ const [resource, setResource] = useState(LOADING);
+ const [attempt, setAttempt] = useState(0);
+ // Each run owns a generation: a retry issued while a request is in flight,
+ // or a changed fetcher, supersedes it and its late answer is ignored.
+ const generation = useRef(0);
+
+ useEffect(() => {
+ if (!enabled) return undefined;
+ generation.current += 1;
+ const current = generation.current;
+ setResource(LOADING);
+ Promise.resolve()
+ .then(() => fetcher())
+ .then((list) => {
+ if (generation.current !== current) return;
+ setResource({ items: Array.isArray(list) ? list : [], state: 'ready', error: null });
+ })
+ .catch((error) => {
+ if (generation.current !== current) return;
+ setResource({ items: [], state: 'error', error: error instanceof Error ? error : new Error('Request failed') });
+ });
+ return () => { generation.current += 1; };
+ }, [fetcher, enabled, attempt]);
+
+ const retry = useCallback(() => setAttempt((n) => n + 1), []);
+ const setItems = useCallback((update) => setResource((prev) => ({
+ ...prev,
+ items: typeof update === 'function' ? update(prev.items) : update,
+ })), []);
+
+ return { ...resource, retry, setItems };
+}
diff --git a/client/src/hooks/useListResource.test.jsx b/client/src/hooks/useListResource.test.jsx
new file mode 100644
index 0000000000..42863c36d3
--- /dev/null
+++ b/client/src/hooks/useListResource.test.jsx
@@ -0,0 +1,48 @@
+import { describe, it, expect, vi } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+import useListResource from './useListResource';
+
+describe('useListResource', () => {
+ it('reports loading, then ready with the list, and keeps a failure distinct from an empty list', async () => {
+ const fetcher = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce([]);
+ const { result } = renderHook(() => useListResource(fetcher));
+ expect(result.current).toMatchObject({ items: [], state: 'loading', error: null });
+ await waitFor(() => expect(result.current.state).toBe('error'));
+ expect(result.current.items).toEqual([]);
+ expect(result.current.error.message).toBe('offline');
+
+ act(() => { result.current.retry(); });
+ expect(result.current.state).toBe('loading');
+ await waitFor(() => expect(result.current.state).toBe('ready'));
+ expect(result.current.items).toEqual([]);
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops a superseded response and applies local mutations without a refetch', async () => {
+ const answers = [];
+ const fetcher = vi.fn(() => new Promise((resolve, reject) => answers.push({ resolve, reject })));
+ const { result } = renderHook(() => useListResource(fetcher));
+ await waitFor(() => expect(answers).toHaveLength(1));
+ act(() => { result.current.retry(); });
+ await waitFor(() => expect(answers).toHaveLength(2));
+ // The first run's late answer must not overwrite the retry's.
+ await act(async () => { answers[0].resolve([{ id: 'stale' }]); });
+ expect(result.current.state).toBe('loading');
+ await act(async () => { answers[1].resolve([{ id: 'fresh' }]); });
+ expect(result.current).toMatchObject({ state: 'ready', items: [{ id: 'fresh' }] });
+
+ act(() => { result.current.setItems((items) => [...items, { id: 'imported' }]); });
+ expect(result.current.items.map((i) => i.id)).toEqual(['fresh', 'imported']);
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it('holds at loading without a request while disabled', async () => {
+ const fetcher = vi.fn(async () => [1]);
+ const { result, rerender } = renderHook(({ enabled }) => useListResource(fetcher, { enabled }), { initialProps: { enabled: false } });
+ await act(async () => {});
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(result.current.state).toBe('loading');
+ rerender({ enabled: true });
+ await waitFor(() => expect(result.current).toMatchObject({ state: 'ready', items: [1] }));
+ });
+});
diff --git a/client/src/listFetchConventions.test.js b/client/src/listFetchConventions.test.js
new file mode 100644
index 0000000000..d17121682d
--- /dev/null
+++ b/client/src/listFetchConventions.test.js
@@ -0,0 +1,116 @@
+// @vitest-environment node
+
+/**
+ * Repo-wide guard: a page's list fetch does not collapse a failed read into
+ * an empty list.
+ *
+ * `listLorasFull().catch(() => [])` and `.catch(() => setTracks([]))` make a
+ * transient 5xx during page load render as "you have none" — no error, no
+ * retry, and no way to tell it from an empty library (#12040). The root
+ * AGENTS.md sentinel rule (absent vs failed vs legitimately empty) is enforced
+ * server-side; this is its client half. The shared primitive is
+ * `hooks/useListResource` (`{ items, state, error, retry }`) with
+ * `components/ui/ListLoadError` for the failed state.
+ *
+ * The rule is a ratchet. `KNOWN` records how many such sites each page still
+ * carries today; a NEW site, or a higher count in a listed page, fails. So does
+ * a count that DROPPED, so the row is lowered or removed and the baseline
+ * stays honest. The remaining sites are tracked by surface in the follow-up
+ * issues #12040 names.
+ *
+ * ## 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 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.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { trackedSourceFiles } from './test/trackedFiles.js';
+
+const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+// Page code only — the pickers and index lists users see.
+const SCAN_PREFIX = 'src/pages/';
+
+/**
+ * `.catch(() => [])`, `.catch(() => setX([]))` and the braced one-statement
+ * form `.catch(() => { setX([]); })`. The setter must start with `set` + a
+ * capital, so `.catch(() => reset([]))` and a non-setter call stay out.
+ */
+export const LIST_COLLAPSE = /\.catch\(\s*\(\s*\)\s*=>\s*(?:\[\]|\{?\s*set[A-Z]\w*\(\s*\[\]\s*\)\s*;?\s*\}?)\s*\)/g;
+
+/**
+ * Pages still carrying a collapse, with how many. Lower or remove a row when a
+ * site is migrated to `useListResource`; never raise one.
+ */
+const KNOWN = Object.freeze({
+ 'src/pages/AIProviders.jsx': 2,
+ 'src/pages/Catalog.jsx': 2,
+ 'src/pages/DeckDetail.jsx': 1,
+ 'src/pages/Decks.jsx': 1,
+ 'src/pages/FableLoom.jsx': 1,
+ 'src/pages/Game.jsx': 1,
+ 'src/pages/HistoryPage.jsx': 1,
+ 'src/pages/Importer.jsx': 2,
+ 'src/pages/LoraTraining.jsx': 1,
+ 'src/pages/MediaCollectionDetail.jsx': 1,
+ 'src/pages/MusicVideo.jsx': 1,
+ 'src/pages/Pipeline.jsx': 2,
+ 'src/pages/PipelineEditorialChecks.jsx': 1,
+ 'src/pages/PipelineSeries.jsx': 1,
+ 'src/pages/Privacy.jsx': 1,
+ 'src/pages/ProcessesPage.jsx': 1,
+ 'src/pages/RunnerPage.jsx': 2,
+ 'src/pages/Sprites.jsx': 3,
+ 'src/pages/StoryBuilder.jsx': 1,
+ 'src/pages/Templates.jsx': 1,
+ 'src/pages/Universes.jsx': 2,
+ 'src/pages/VideoDownloaderPage.jsx': 1,
+ 'src/pages/VideoTimeline.jsx': 2,
+ 'src/pages/WritersRoom.jsx': 1,
+});
+
+const countIn = (source) => (source.match(LIST_COLLAPSE) || []).length;
+
+describe('page list fetches keep a failed read distinct from an empty list', () => {
+ it('matches the collapse spellings it is meant to catch, and not a handled failure', () => {
+ for (const sample of [
+ 'listLorasFull().catch(() => [])',
+ 'listTracks({ silent: true }).then((t) => setTracks(t || [])).catch(() => setTracks([]))',
+ 'load().catch(() => { setRows([]); })',
+ ]) expect(countIn(sample), sample).toBe(1);
+ for (const sample of [
+ 'listTracks().catch(() => setLoadError(true))',
+ 'load().catch(() => { setRows([]); setFailed(true); })',
+ 'load().catch(() => FETCH_FAILED)',
+ ]) expect(countIn(sample), sample).toBe(0);
+ });
+
+ it('has no new page list fetch that collapses failure into an empty list', () => {
+ const found = {};
+ for (const file of trackedSourceFiles(CLIENT_ROOT)) {
+ if (!file.startsWith(SCAN_PREFIX)) continue;
+ const count = countIn(readFileSync(join(CLIENT_ROOT, file), 'utf8'));
+ if (count > 0) found[file] = count;
+ }
+ const added = Object.entries(found)
+ .filter(([file, count]) => count > (KNOWN[file] || 0))
+ .map(([file, count]) => `${file}: ${count} (known ${KNOWN[file] || 0})`);
+ expect(added, [
+ 'These page list fetches render a failed read as an empty list. Read the list through',
+ '`useListResource(fetcher)` and render `<ListLoadError onRetry={retry}>` on `state === "error"`,',
+ 'keeping the empty copy for `state === "ready"`; never `.catch(() => [])` / `setX([])`.',
+ ].join('\n')).toEqual([]);
+ const stale = Object.entries(KNOWN)
+ .filter(([file, count]) => (found[file] || 0) < count)
+ .map(([file, count]) => `${file}: now ${found[file] || 0} (known ${count})`);
+ expect(stale, 'A migrated site: lower or remove its KNOWN row so the ratchet holds.').toEqual([]);
+ });
+});
diff --git a/client/src/pages/ImageGen.modelCatalog.test.jsx b/client/src/pages/ImageGen.modelCatalog.test.jsx
new file mode 100644
index 0000000000..167071498b
--- /dev/null
+++ b/client/src/pages/ImageGen.modelCatalog.test.jsx
@@ -0,0 +1,40 @@
+/**
+ * The local model catalog read (#12040): a failed load shows an error row with
+ * Retry and a genuinely empty catalog its own copy — neither renders as the
+ * other, and the Model select only appears once a catalog has landed.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { screen, fireEvent, waitFor } from '@testing-library/react';
+import { state, resetImageGenMockState, imageGenModel, loadImageGenPage, renderImageGenPage } from '../test/imageGenPageMocks.jsx';
+
+await loadImageGenPage();
+
+const DEV = imageGenModel('dev', { name: 'FLUX.1 Dev' });
+
+describe('ImageGen local model catalog load state (#12040)', () => {
+ beforeEach(() => {
+ resetImageGenMockState();
+ });
+
+ it('shows a failed catalog read with Retry, then the Model select once the retry lands', async () => {
+ state.models = [DEV];
+ state.listImageModels.mockRejectedValueOnce(new Error('catalog down'));
+ await renderImageGenPage();
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('Could not load the local model catalog — catalog down');
+ expect(screen.queryByLabelText('Model')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(screen.getByLabelText('Model')).toBeInTheDocument());
+ expect(screen.getByRole('option', { name: 'FLUX.1 Dev' })).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('shows the empty copy for a genuinely empty catalog, not an error', async () => {
+ state.models = [];
+ await renderImageGenPage();
+ expect(await screen.findByRole('status', { name: '' })).toHaveTextContent('No local image models are compatible with this machine.');
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Model')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 0c37fb4e39..ac06a1f7e1 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -50,6 +50,7 @@ import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';
import useMusicVideoProduction from '../hooks/useMusicVideoProduction.js';
import useAutonomousMusicVideo from '../hooks/useAutonomousMusicVideo.js';
import useDrawerTab from '../hooks/useDrawerTab.js';
+import useListResource from '../hooks/useListResource.js';
import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';
import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';
import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';
@@ -146,6 +147,9 @@ const STAGE_VIEWS = {
+// Stable fetcher for useListResource — the hook re-runs on identity change.
+const loadTracks = () => listTracks({ silent: true });
+
export default function MusicVideo() {
// Deep-linkable project selection: the selected project lives in the URL
// (/music-video/:projectId) rather than local state, so a project's
@@ -185,7 +189,10 @@ export default function MusicVideo() {
// it mid-flight (a job finishing) can refetch instead of being folded into a
// response that may predate it.
const fetchingIdRef = useRef(null);
- const [tracks, setTracks] = useState([]);
+ // The music library the pickers read. A failed read is shown as such, with
+ // Retry, never as an empty library; an import appends to it locally.
+ const trackLibrary = useListResource(loadTracks);
+ const { items: tracks, setItems: setTracks } = trackLibrary;
const [universes, setUniverses] = useState(null);
// A project-less stage URL (/music-video/board, from the nav manifest) names a stage, not a project:
// treat it as the index until the summaries resolve, then redirect to the newest project at that stage.
@@ -417,7 +424,6 @@ export default function MusicVideo() {
};
useEffect(() => {
- listTracks({ silent: true }).then((t) => setTracks(t || [])).catch(() => setTracks([]));
listUniverseNames({ silent: true }).then((u) => setUniverses(u || [])).catch(() => setUniverses([]));
}, []);
@@ -592,6 +598,7 @@ export default function MusicVideo() {
form={form}
onFormChange={(patch) => setForm((f) => ({ ...f, ...patch }))}
tracks={tracks}
+ trackLibrary={trackLibrary}
universes={universes}
trackName={trackName}
youtube={youtube}
@@ -712,6 +719,7 @@ export default function MusicVideo() {
key={selected.id}
selected={selected}
tracks={tracks}
+ trackLibrary={trackLibrary}
trackName={trackName}
youtube={youtube}
separation={separation}
@@ -752,7 +760,7 @@ export default function MusicVideo() {
* binds to its project by id.
*/
function ProjectWorkspace({
- selected, tracks, trackName, youtube, separation, lyricAlign, midi, renderJob, videoSettings, publishing, analyzing, cloning,
+ selected, tracks, trackLibrary, trackName, youtube, separation, lyricAlign, midi, renderJob, videoSettings, publishing, analyzing, cloning,
replaceProject, patchProject, patchScene, openProject, prepareSong, onAnalyze, onClone, onTrackImported,
onRename, renameForm, deletion,
}) {
@@ -1537,6 +1545,7 @@ function ProjectWorkspace({
locked: creativeSetupPending || styleReferencesPending || compositionSavePending > 0,
busy: { analyzing, planning, arranging, cloning },
tracks,
+ trackLibrary,
onForkSong: () => onClone({}, {}, true),
trackName,
audioFilename,
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 000152e22f..1d4c202b51 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -637,6 +637,29 @@ describe('MusicVideo per-project workspace (#12039)', () => {
});
});
+describe('MusicVideo music library load state (#12040)', () => {
+ it('shows a failed library read with Retry in the create form, then the tracks once the retry lands', async () => {
+ listTracks.mockRejectedValueOnce(new Error('library offline'));
+ renderMV();
+ fireEvent.click(await screen.findByRole('button', { name: /New project/i }));
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('Could not load the music library — library offline');
+ expect(screen.queryByText(/No tracks in the music library yet/)).not.toBeInTheDocument();
+
+ listTracks.mockResolvedValueOnce([{ id: 't-example', title: 'Example Track' }]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByRole('option', { name: /Example Track/ })).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('shows the empty copy for a genuinely empty library, not an error', async () => {
+ renderMV();
+ fireEvent.click(await screen.findByRole('button', { name: /New project/i }));
+ expect(await screen.findByText(/No tracks in the music library yet/)).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+});
+
describe('MusicVideo project header', () => {
it('keeps only the picker beside the page title inside a project; fork and delete live in Project settings', async () => {
await openProject(PROJECT_WITH_CLIP);
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 94e27406ff..4b6ab1d162 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -82,6 +82,8 @@ import usePreviewRoute from '../hooks/usePreviewRoute';
import useMediaPreviewActions from '../hooks/useMediaPreviewActions';
import { useVideoGenForm } from '../hooks/useVideoGenForm.js';
import { useFederatedMediaTarget } from '../hooks/useFederatedMediaTarget';
+import useListResource from '../hooks/useListResource';
+import ListLoadError from '../components/ui/ListLoadError';
import { useModelInputPreview } from '../hooks/useModelInputPreview';
import ModelInputPreview from '../components/media/ModelInputPreview';
import RemoteMediaTargetPicker from '../components/federatedMedia/RemoteMediaTargetPicker';
@@ -124,6 +126,9 @@ const MODES = [
...IC_LORA_MODES.map((m) => ({ id: m.mode, label: m.label, icon: SlidersHorizontal, desc: m.description })),
];
+// Stable fetcher for useListResource — the hook re-runs on identity change.
+const loadLoraLibrary = () => listLorasFull({ silent: true });
+
export default function VideoGen() {
const [searchParams, setSearchParams] = useSearchParams();
const settingsOpen = searchParams.get('settings') === '1';
@@ -211,9 +216,10 @@ export default function VideoGen() {
}, []);
// Installed LoRA library — the picker filters this to the current model's
- // video family. Silent: a failure just hides the picker.
- const [availableLoras, setAvailableLoras] = useState([]);
- useEffect(() => { listLorasFull().then((l) => setAvailableLoras(Array.isArray(l) ? l : [])).catch(() => {}); }, []);
+ // video family. A failed read is shown as such, with Retry, never as an
+ // empty library.
+ const loraLibrary = useListResource(loadLoraLibrary);
+ const availableLoras = loraLibrary.items;
// Federated render target (#4348). Picking a peer replaces the local runtime
// outright — the clip is rendered there and imported back — so it feeds the
@@ -1739,6 +1745,17 @@ export default function VideoGen() {
{/* Video LoRAs — only on runtimes with a compatible video family
(loraFamily non-null) and when at least one matching LoRA is
installed (videoLoras is the strict family subset; see hook). */}
+ {loraFamily && loraLibrary.state === 'error' && (
+ <ListLoadError
+ className="col-span-2 sm:col-span-3"
+ what="the LoRA library"
+ error={loraLibrary.error}
+ onRetry={loraLibrary.retry}
+ />
+ )}
+ {loraFamily && loraLibrary.state === 'ready' && videoLoras.length === 0 && (
+ <p className="col-span-2 sm:col-span-3 text-xs text-gray-500">No installed LoRAs match this model&apos;s video family.</p>
+ )}
{loraFamily && videoLoras.length > 0 && (
<div className="col-span-2 sm:col-span-3">
<LoraPicker
diff --git a/client/src/pages/VideoGen.loraLibrary.test.jsx b/client/src/pages/VideoGen.loraLibrary.test.jsx
new file mode 100644
index 0000000000..8b29d18745
--- /dev/null
+++ b/client/src/pages/VideoGen.loraLibrary.test.jsx
@@ -0,0 +1,53 @@
+/**
+ * The LoRA picker's library read (#12040): a failed load shows an error row
+ * with Retry, and a genuinely empty library shows its own empty copy —
+ * neither renders as the other.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { screen, fireEvent, waitFor } from '@testing-library/react';
+import {
+ state, resetVideoGenMockState, videoGenModel, videoGenStatus, videoGenModelContext,
+ loadVideoGenPage, renderVideoGenPage,
+} from '../test/videoGenPageMocks.jsx';
+
+await loadVideoGenPage();
+
+const MODEL = videoGenModel('example-ltx', {
+ name: 'Example LTX',
+ runtime: 'ltx2',
+ supportedModes: ['text', 'image'],
+ defaultFrames: 121,
+ frameOptions: [121, 241],
+ fpsOptions: [24],
+});
+const LORA = { filename: 'lora-example.safetensors', name: 'Example LoRA', loraCompatKey: 'ltx-video' };
+
+describe('VideoGen LoRA library load state (#12040)', () => {
+ beforeEach(() => {
+ resetVideoGenMockState();
+ state.getVideoGenStatus.mockResolvedValue(videoGenStatus([MODEL]));
+ state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));
+ state.getModelStatus = () => ({ cached: true });
+ });
+
+ it('shows a failed library read with Retry, then the picker once the retry lands', async () => {
+ state.listLorasFull.mockRejectedValueOnce(new Error('library offline'));
+ await renderVideoGenPage();
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('Could not load the LoRA library — library offline');
+ expect(state.loraPicker).toBeNull();
+
+ state.availableLoras = [LORA];
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ await waitFor(() => expect(state.loraPicker?.availableLoras).toEqual([LORA]));
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(state.listLorasFull).toHaveBeenCalledTimes(2);
+ });
+
+ it('shows the empty copy for a genuinely empty library, not an error', async () => {
+ await renderVideoGenPage();
+ await waitFor(() => expect(state.listLorasFull).toHaveBeenCalled());
+ expect(await screen.findByText(/No installed LoRAs match this model/)).toBeInTheDocument();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+});
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 0a3807faab..075be20f13 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -595,6 +595,7 @@ export const structuralTestsFor = (changedFiles, trackedSet) => {
add('client/src/globalShadowConventions.test.js');
add('client/src/headingTruncationConventions.test.js');
add('client/src/hooks/mountedRefConventions.test.js');
+ add('client/src/listFetchConventions.test.js');
add('client/src/moduleContractConventions.test.js');
add('client/src/numberFormattingConventions.test.js');
add('client/src/pageShellConventions.test.js');
diff --git a/scripts/repo-scan-guards.test.js b/scripts/repo-scan-guards.test.js
index a8a5b07cd4..dc9c310971 100644
--- a/scripts/repo-scan-guards.test.js
+++ b/scripts/repo-scan-guards.test.js
@@ -62,6 +62,7 @@ const STRUCTURALLY_SELECTED = new Map([
['client/src/globalShadowConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/headingTruncationConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/hooks/mountedRefConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
+ ['client/src/listFetchConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/moduleContractConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/numberFormattingConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],
['client/src/pageShellConventions.test.js', 'structuralTestsFor: client/src/**.js(x)'],