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(client): handle list read failures with useListResource on media pages (#12170)
Adam Eivya3a10a7be852
diff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsxindex 7a440f28ac..8ed82435e9 100644--- a/client/src/components/games/GameBindings.jsx+++ b/client/src/components/games/GameBindings.jsx@@ -15,6 +15,7 @@ import {} from 'lucide-react';import { Link } from 'react-router';import Pill from '../ui/Pill.jsx';+import ListLoadError from '../ui/ListLoadError.jsx';const GalleryImagePicker = lazy(() => import('../imageGen/GalleryImagePicker'));const selectClass = 'w-full min-h-[44px] rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white';@@ -336,17 +337,17 @@ function ArtworkCard({onPublish,onUnbind,}) {- const [label, setLabel] = useState(binding.label);- const [role, setRole] = useState(binding.role);- const [destinationPath, setDestinationPath] = useState(binding.destinationPath);+ const [label, setLabel] = useState(binding.label || '');+ const [role, setRole] = useState(binding.role || '');+ const [destinationPath, setDestinationPath] = useState(binding.destinationPath || '');useEffect(() => {- setLabel(binding.label);- setRole(binding.role);- setDestinationPath(binding.destinationPath);+ setLabel(binding.label || '');+ setRole(binding.role || '');+ setDestinationPath(binding.destinationPath || '');}, [binding]);- const dirty = label.trim() !== binding.label+ const dirty = (label || '').trim() !== (binding.label || '')|| role !== binding.role- || destinationPath.trim() !== binding.destinationPath;+ || (destinationPath || '').trim() !== (binding.destinationPath || '');const publicationCurrent = health?.publicationStatus === 'current';return (<article className="overflow-hidden rounded-xl border border-port-border bg-port-bg/55">@@ -446,6 +447,8 @@ export default function GameBindings({sprites,tracks,gallery = [],+ galleryError = null,+ onRetryGallery = null,integrity,busy,onBindSprite,@@ -620,6 +623,15 @@ export default function GameBindings({</Link></div>+ {galleryError && (+ <ListLoadError+ what="artwork images"+ error={galleryError}+ onRetry={onRetryGallery}+ className="mt-4"+ />+ )}+<div className="mt-4 grid gap-3 rounded-xl border border-port-border bg-port-bg/35 p-3 lg:grid-cols-[minmax(0,1.3fr)_minmax(180px,.7fr)]"><div className="grid gap-3 sm:grid-cols-2"><div>diff --git a/client/src/components/media/BulkTargetPicker.jsx b/client/src/components/media/BulkTargetPicker.jsxindex 8067e04821..21ffbda7af 100644--- a/client/src/components/media/BulkTargetPicker.jsx+++ b/client/src/components/media/BulkTargetPicker.jsx@@ -22,6 +22,8 @@ export default function BulkTargetPicker({busy,title = 'Pick a collection',collections,+ error = null,+ onRetry = null,onPick,onClose,}) {@@ -54,6 +56,8 @@ export default function BulkTargetPicker({newCollectionPlaceholder="New collection"createTitle="Create and pick"collections={collections}+ error={error}+ onRetry={onRetry}renderItem={renderItem}onCreated={handleCreated}/>diff --git a/client/src/components/media/BulkTargetPicker.test.jsx b/client/src/components/media/BulkTargetPicker.test.jsxnew file mode 100644index 0000000000..d8e887318b--- /dev/null+++ b/client/src/components/media/BulkTargetPicker.test.jsx@@ -0,0 +1,67 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent, act } from '@testing-library/react';+import BulkTargetPicker from './BulkTargetPicker.jsx';++vi.mock('../../services/api', () => ({+ listMediaCollections: vi.fn(),+ createMediaCollection: vi.fn(),+}));++describe('BulkTargetPicker', () => {+ it('renders ListLoadError with retry on failed collections load', async () => {+ const onRetry = vi.fn();+ render(+ <BulkTargetPicker+ anchorRef={{ current: document.createElement('button') }}+ excludeId="col-1"+ collections={null}+ error={new Error('500 Server Error')}+ onRetry={onRetry}+ onPick={vi.fn()}+ onClose={vi.fn()}+ />+ );+ await act(async () => {});++ expect(screen.getByRole('alert')).toHaveTextContent('Could not load collections — 500 Server Error');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(screen.queryByText('No collections yet — create one below.')).not.toBeInTheDocument();++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ });+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('renders empty message on real empty collections', () => {+ render(+ <BulkTargetPicker+ anchorRef={{ current: document.createElement('button') }}+ excludeId="col-1"+ collections={[]}+ onPick={vi.fn()}+ onClose={vi.fn()}+ />+ );++ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText('No collections yet — create one below.')).toBeInTheDocument();+ });++ it('renders collection choices when collections are loaded', () => {+ render(+ <BulkTargetPicker+ anchorRef={{ current: document.createElement('button') }}+ excludeId="col-1"+ collections={[+ { id: 'col-2', name: 'Landscapes', items: [{ kind: 'image', ref: 'a.jpg' }] },+ ]}+ onPick={vi.fn()}+ onClose={vi.fn()}+ />+ );++ expect(screen.getByText('Landscapes')).toBeInTheDocument();+ expect(screen.queryByText('No collections yet — create one below.')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/media/CollectionPickerShell.jsx b/client/src/components/media/CollectionPickerShell.jsxindex 50019bd288..a0aa542c03 100644--- a/client/src/components/media/CollectionPickerShell.jsx+++ b/client/src/components/media/CollectionPickerShell.jsx@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';import { createPortal } from 'react-dom';import { Plus, Search } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import { listMediaCollections, createMediaCollection } from '../../services/api';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';@@ -77,6 +78,8 @@ export default function CollectionPickerShell({// every prop combination through the shell.renderItem,collections: collectionsProp,+ error = null,+ onRetry = null,onCollectionsLoaded,onCollectionsChange,onCreated,@@ -133,10 +136,10 @@ export default function CollectionPickerShell({if (collectionsProp !== undefined) setCollectionsState(collectionsProp);}, [collectionsProp]);- // Auto-load only when uncontrolled (no `collections` prop). Mirrors the old+ // Auto-load only when uncontrolled (no `collections` prop) and no error. Mirrors the old// AddToCollectionMenu behavior of fetching when the popover opens.useEffect(() => {- if (collectionsProp !== undefined) return undefined;+ if (collectionsProp !== undefined || error) return undefined;if (!open) return undefined;let cancelled = false;loadItems({ silent: true }).then(@@ -238,22 +241,30 @@ export default function CollectionPickerShell({</div>)}<div className="flex-1 min-h-0 overflow-y-auto">- {collectionsState == null && (- <div className="text-[11px] px-2 py-2"><BrailleSpinner text="Loading…" /></div>- )}- {collectionsState != null && collectionsState.length === 0 && (- <div className="text-[11px] text-gray-500 px-2 py-2">{emptyMessage}</div>- )}- {list != null && collectionsState?.length > 0 && list.length === 0 && (- <div className="text-[11px] text-gray-500 px-2 py-2">{noMatchMessage(query)}</div>- )}- {list != null && list.length > 0 && (- // A real list — "list, N items" is the honest announcement for these- // rows; the roles menu/menuitem promised arrow-key navigation this- // popover does not implement.- <ul>- {list.map((c) => <li key={c.id}>{renderItem(c, { updateCollections })}</li>)}- </ul>+ {error ? (+ <div className="p-2">+ <ListLoadError what="collections" error={error} onRetry={onRetry} />+ </div>+ ) : (+ <>+ {collectionsState == null && (+ <div className="text-[11px] px-2 py-2"><BrailleSpinner text="Loading…" /></div>+ )}+ {collectionsState != null && collectionsState.length === 0 && (+ <div className="text-[11px] text-gray-500 px-2 py-2">{emptyMessage}</div>+ )}+ {list != null && collectionsState?.length > 0 && list.length === 0 && (+ <div className="text-[11px] text-gray-500 px-2 py-2">{noMatchMessage(query)}</div>+ )}+ {list != null && list.length > 0 && (+ // A real list — "list, N items" is the honest announcement for these+ // rows; the roles menu/menuitem promised arrow-key navigation this+ // popover does not implement.+ <ul>+ {list.map((c) => <li key={c.id}>{renderItem(c, { updateCollections })}</li>)}+ </ul>+ )}+ </>)}</div><form onSubmit={handleCreate} className="mt-1.5 pt-1.5 border-t border-port-border flex gap-1 shrink-0">diff --git a/client/src/components/musicVideo/CreateProjectDrawer.jsx b/client/src/components/musicVideo/CreateProjectDrawer.jsxindex b08ce6c8ec..0ba9cef388 100644--- a/client/src/components/musicVideo/CreateProjectDrawer.jsx+++ b/client/src/components/musicVideo/CreateProjectDrawer.jsx@@ -22,8 +22,22 @@ 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, trackLibrary = null, universes, trackName, youtube, onSubmit, submitting }) {+export default function CreateProjectDrawer({+ open,+ onClose,+ form,+ onFormChange,+ tracks,+ trackLibrary = null,+ universes = null,+ universeResource = null,+ trackName,+ youtube,+ onSubmit,+ submitting,+}) {const autopilot = form.mode === 'autonomous';+ const availableUniverses = universes ?? universeResource?.items ?? [];const optionLabels = trackOptionLabels(tracks || []);const selectedTrack = (tracks || []).find((t) => t.id === form.trackId) || null;const sourceLabel = trackSourceLabel(selectedTrack);@@ -176,9 +190,17 @@ export default function CreateProjectDrawer({ open, onClose, form, onFormChange,onChange={(e) => onFormChange({ universeId: e.target.value })}className={inputClass}>- <option value="">{universes === null ? 'Loading…' : 'No universe'}</option>- {(universes || []).map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}+ <option value="">{universeResource?.state === 'loading' || (universes === null && !universeResource) ? 'Loading…' : 'No universe'}</option>+ {availableUniverses.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</select>+ {universeResource?.state === 'error' && (+ <ListLoadError+ what="universes"+ error={universeResource.error}+ onRetry={universeResource.retry}+ className="mt-2"+ />+ )}</div></div>diff --git a/client/src/components/sprites/AnimationProviderPicker.jsx b/client/src/components/sprites/AnimationProviderPicker.jsxindex d62a76c0f7..6f5e8f97cd 100644--- a/client/src/components/sprites/AnimationProviderPicker.jsx+++ b/client/src/components/sprites/AnimationProviderPicker.jsx@@ -17,9 +17,14 @@* lane exists or what would make it work, and per the repo's UI rules a warning* that lives only in a `title` is missed on touch.*/+import ListLoadError from '../ui/ListLoadError.jsx';+export default function AnimationProviderPicker({- id, providers, provider, onChange, disabled = false,+ id, providers, provider, onChange, disabled = false, error = null, onRetry = null,}) {+ if (error) {+ return <ListLoadError what="animation providers" error={error} onRetry={onRetry} />;+ }// `null` = not fetched yet (distinct from `[]` = fetched and empty), so a// slow or failed probe never flashes a picker that then disappears.if (!Array.isArray(providers) || providers.length < 2) return null;diff --git a/client/src/components/sprites/AnimationProviderPicker.test.jsx b/client/src/components/sprites/AnimationProviderPicker.test.jsxindex 93f1f8f1c9..0cb8de1d52 100644--- a/client/src/components/sprites/AnimationProviderPicker.test.jsx+++ b/client/src/components/sprites/AnimationProviderPicker.test.jsx@@ -95,4 +95,12 @@ describe('AnimationProviderPicker', () => {renderPicker({ disabled: true });expect(screen.getByLabelText(/Render on/)).toBeDisabled();});++ it('renders ListLoadError when error is present', () => {+ const onRetry = vi.fn();+ renderPicker({ error: new Error('Failed to load providers'), onRetry });+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load animation providers — Failed to load providers');+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(onRetry).toHaveBeenCalledTimes(1);+ });});diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex 5bd63e464d..3de33645b6 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -20,6 +20,7 @@ import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';import FilePickerButton from '../ui/FilePickerButton';import { IMAGE_ACCEPT } from '../../utils/fileUpload';import RecordRenderPinRow from '../imageGen/RecordRenderPinRow.jsx';+import ListLoadError from '../ui/ListLoadError.jsx';// Reference workflow (issues #2896, #2979): three ordered steps — generate a// turnaround sheet from text + an optional design image and freeze it, derive@@ -198,7 +199,10 @@ function StageHeading({ id, number, title, status, statusTone = 'text-gray-500');}-export default function ReferenceWorkflow({ record, reference, renders, corrections, onCorrectionChange, backends, trackDefinitions, mode, onModeChange, onChanged, onForked }) {+export default function ReferenceWorkflow({+ record, reference, renders, corrections, onCorrectionChange, backends, trackDefinitions, mode, onModeChange, onChanged, onForked,+ backendsError = null, onRetryBackends = null,+}) {const recordId = record.id;// Local shadow of record.imageModelId (#3231 Phase 3) — pin PATCHes update// this directly instead of refetching the whole detail payload; re-seeded@@ -537,7 +541,10 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti{manifest.chromaKeyWarning}</p>)}- {noBackend && (+ {backendsError && (+ <ListLoadError what="image backends" error={backendsError} onRetry={onRetryBackends} />+ )}+ {!backendsError && noBackend && (<p className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">No image backend configured — enable Codex or Grok, or set a local Python path, in Settings → Image Gen to generate references.</p>diff --git a/client/src/components/sprites/ReferenceWorkflow.test.jsx b/client/src/components/sprites/ReferenceWorkflow.test.jsxindex 07e9b8ee4c..009a24133c 100644--- a/client/src/components/sprites/ReferenceWorkflow.test.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.test.jsx@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { render, screen, within } from '@testing-library/react';+import { fireEvent, render, screen, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { typeSettled } from '../../test/settledInput';@@ -42,7 +42,10 @@ const renders = {cancelSubmit: vi.fn(),};-const renderWorkflow = ({ turnaround, trackDefinitions } = {}) => render(+const renderWorkflow = ({+ turnaround, trackDefinitions, backends = [{ id: 'codex', label: 'Codex' }],+ backendsError = null, onRetryBackends = null,+} = {}) => render(<ReferenceWorkflowrecord={{ id: 'example-pioneer', name: 'Example Pioneer', chromaKey: '#FF00FF' }}reference={{@@ -66,7 +69,9 @@ const renderWorkflow = ({ turnaround, trackDefinitions } = {}) => render(renders={renders}corrections={{}}onCorrectionChange={vi.fn()}- backends={[{ id: 'codex', label: 'Codex' }]}+ backends={backends}+ backendsError={backendsError}+ onRetryBackends={onRetryBackends}trackDefinitions={trackDefinitions}mode="codex"onModeChange={vi.fn()}@@ -273,4 +278,16 @@ describe('main-reference correction note (#3134)', () => {await user.click(within(main).getByRole('button', { name: 'Generate candidate' }));expect(generateSpriteReference.mock.calls[0][1]).not.toHaveProperty('correctionPrompt');});++ it('renders ListLoadError when backendsError is present and empty warning only when backends is empty with no error', () => {+ const onRetryBackends = vi.fn();+ renderWorkflow({ backendsError: new Error('Settings unavailable'), onRetryBackends, backends: [] });+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load image backends — Settings unavailable');+ expect(screen.queryByText(/No image backend configured/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(onRetryBackends).toHaveBeenCalledTimes(1);++ renderWorkflow({ backendsError: null, backends: [] });+ expect(screen.getByText(/No image backend configured/)).toBeInTheDocument();+ });});diff --git a/client/src/components/sprites/TrackWorkflow.jsx b/client/src/components/sprites/TrackWorkflow.jsxindex bcdfc7b196..d5c750ba7f 100644--- a/client/src/components/sprites/TrackWorkflow.jsx+++ b/client/src/components/sprites/TrackWorkflow.jsx@@ -30,6 +30,7 @@ import AnimationProviderPicker from './AnimationProviderPicker.jsx';export default function TrackWorkflow({record, reference, state, onGenerate, onChanged, corrections = null, onCorrectionChange = null,providers = null, provider = 'grok', onProviderChange = () => {},+ providersError = null, onRetryProviders = null,}) {const definition = state?.definition || null;const runs = state?.runs || [];@@ -94,6 +95,8 @@ export default function TrackWorkflow({provider={provider}onChange={onProviderChange}disabled={finalized}+ error={providersError}+ onRetry={onRetryProviders}/><span className="text-[11px] text-gray-500">directly requested {provider === 'local' ? 'local' : 'Grok'} render; local deterministic packingdiff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 8b65b153d0..84af53d518 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -545,6 +545,7 @@ export default function WalkWorkflow({record, reference, walk, renders, duration, onDurationChange, onGenerate,onOpenTrimmer = () => {}, onChanged, corrections = null, onCorrectionChange = null,providers = null, provider = 'grok', onProviderChange = () => {},+ providersError = null, onRetryProviders = null,}) {const recordId = record.id;// The cycle target is server-resolved (app contract → set pin → first approved@@ -726,6 +727,8 @@ export default function WalkWorkflow({provider={provider}onChange={onProviderChange}disabled={finalized}+ error={providersError}+ onRetry={onRetryProviders}/><label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-clip-${recordId}`} title={provider === 'local'? "The local model renders on a fixed frame grid, so this length is snapped to the nearest legal clip. Length only affects how much source footage the packer has to choose from, not the walk's speed."diff --git a/client/src/listFetchConventions.test.js b/client/src/listFetchConventions.test.jsindex b7df8b1f53..2191172b74 100644--- a/client/src/listFetchConventions.test.js+++ b/client/src/listFetchConventions.test.js@@ -52,18 +52,11 @@ export const LIST_COLLAPSE = /\.catch\(\s*\(\s*\)\s*=>\s*(?:\[\]|\{?\s*set[A-Z]\*/const KNOWN = Object.freeze({'src/pages/AIProviders.jsx': 2,- 'src/pages/Game.jsx': 1,'src/pages/HistoryPage.jsx': 1,- 'src/pages/LoraTraining.jsx': 1,- 'src/pages/MediaCollectionDetail.jsx': 1,- 'src/pages/MusicVideo.jsx': 1,'src/pages/Privacy.jsx': 1,'src/pages/ProcessesPage.jsx': 1,'src/pages/RunnerPage.jsx': 2,- 'src/pages/Sprites.jsx': 3,'src/pages/Templates.jsx': 1,- 'src/pages/VideoDownloaderPage.jsx': 1,- 'src/pages/VideoTimeline.jsx': 2,});const countIn = (source) => (source.match(LIST_COLLAPSE) || []).length;diff --git a/client/src/pages/Game.jsx b/client/src/pages/Game.jsxindex 9b5f4835b4..7805affa03 100644--- a/client/src/pages/Game.jsx+++ b/client/src/pages/Game.jsx@@ -10,6 +10,7 @@ import GameCompilePanel from '../components/games/GameCompilePanel.jsx';import GameFeedback from '../components/games/GameFeedback.jsx';import TabPills from '../components/ui/TabPills.jsx';import useDrawerTab from '../hooks/useDrawerTab.js';+import useListResource from '../hooks/useListResource.js';import {bindGameArtwork,bindGameMusic,@@ -59,7 +60,6 @@ export default function Game() {const [apps, setApps] = useState([]);const [sprites, setSprites] = useState([]);const [tracks, setTracks] = useState([]);- const [gallery, setGallery] = useState([]);// Integrity is keyed by the game it describes, never stored bare. `/game/A` →// `/game/B` reuses the same route, so the component does NOT remount: unkeyed// state would render B's panel with A's verdict — enabling "Start game" for a@@ -88,15 +88,13 @@ export default function Game() {toast.error('Failed to load the Game studio');} else {const [gameRows, appRows, spriteRows, trackRows] = result;- const galleryRows = await getGalleryImages((gameRows.find(game => game.id === id)?.artworkBindings || []).map(binding => binding.imageFilename), silent).catch(() => []);setGames(Array.isArray(gameRows) ? gameRows : []);setApps((Array.isArray(appRows) ? appRows : []).filter((app) => !app.archived));setSprites(Array.isArray(spriteRows) ? spriteRows : []);setTracks(Array.isArray(trackRows) ? trackRows : []);- setGallery((Array.isArray(galleryRows) ? galleryRows : []).filter((image) => !image.hidden));}setLoading(false);- }, [id]);+ }, []);useEffect(() => { load(); }, [load]);@@ -128,6 +126,24 @@ export default function Game() {const integrityLoading = integrityFetching || !matchesGame;const game = useMemo(() => games.find((entry) => entry.id === id) || null, [games, id]);++ const artworkFilenamesKey = useMemo(() => (+ (game?.artworkBindings || []).map((binding) => binding.imageFilename).join(',')+ ), [game?.artworkBindings]);++ const loadArtworkGallery = useCallback(async () => {+ const filenames = artworkFilenamesKey ? artworkFilenamesKey.split(',') : [];+ if (!filenames.length) return [];+ const rows = await getGalleryImages(filenames, silent);+ return (Array.isArray(rows) ? rows : []).filter((image) => !image.hidden);+ }, [artworkFilenamesKey]);++ const {+ items: gallery,+ error: galleryError,+ retry: retryGallery,+ } = useListResource(loadArtworkGallery);+const app = apps.find((entry) => entry.id === game?.appId);const replaceGame = (updated) => setGames((current) =>current.some((entry) => entry.id === updated.id)@@ -448,6 +464,8 @@ export default function Game() {sprites={sprites}tracks={tracks}gallery={gallery}+ galleryError={galleryError}+ onRetryGallery={retryGallery}integrity={integrity}busy={bindingBusy}onBindSprite={(spriteId) => mutate('bind-sprite', () => bindGameSprite(game.id, spriteId, silent), 'Sprite bound')}diff --git a/client/src/pages/Game.test.jsx b/client/src/pages/Game.test.jsxindex aa45614e6d..c6cc1abb7f 100644--- a/client/src/pages/Game.test.jsx+++ b/client/src/pages/Game.test.jsx@@ -9,7 +9,7 @@* so unkeyed integrity state would enable Start game on an unverified bundle).*/-import { render, screen, waitFor } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter, Route, Routes } from 'react-router';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -49,6 +49,17 @@ vi.mock('../services/api.js', () => ({compiledManifest: null,updatedAt: '2026-07-28T12:00:00.000Z',},+ {+ id: 'artwork-game',+ appId: 'app-1',+ name: 'Artwork Game',+ spriteBindings: [],+ musicBindings: [],+ artworkBindings: [{ id: 'art-1', role: 'title-key-art', imageFilename: 'cover.png', label: 'Cover', destinationPath: 'game/assets/art/title/title-key-art.png' }],+ feedbackHistory: [],+ compiledManifest: null,+ updatedAt: '2026-07-28T12:00:00.000Z',+ },]),getApps: vi.fn(async () => [{ id: 'app-1', name: 'Example App' }]),listSpriteRecords: vi.fn(async () => [{ id: 'hero', name: 'Hero', kind: 'character', status: 'ready' }]),@@ -121,6 +132,22 @@ describe('Game page', () => {},assets: { sprites: [], music: [], artwork: [] },},+ 'artwork-game': {+ readyToCompile: true,+ canLaunch: false,+ bundle: { status: 'missing' },+ issues: [],+ counts: {+ spriteReady: 0,+ spriteTotal: 0,+ musicReady: 0,+ musicTotal: 0,+ artworkReady: 1,+ artworkTotal: 1,+ verifiedFiles: 0,+ },+ assets: { sprites: [], music: [], artwork: [] },+ },};});@@ -173,4 +200,27 @@ describe('Game page', () => {await waitFor(() => expect(screen.getByText('Not built')).toBeInTheDocument());expect(screen.getByRole('button', { name: 'Start game' })).toBeDisabled();});++ it('renders ListLoadError with retry when gallery images fail to load', async () => {+ const { getGalleryImages } = await import('../services/api.js');+ getGalleryImages.mockReset();+ getGalleryImages.mockRejectedValueOnce(new Error('Gallery unavailable'));++ renderAt('/game/artwork-game?gameTab=assets');+ expect(await screen.findByText(/Could not load artwork images/)).toBeInTheDocument();+ expect(screen.queryByText(/No world or interface artwork is bound yet/)).not.toBeInTheDocument();++ getGalleryImages.mockResolvedValueOnce([{ filename: 'cover.png', prompt: 'Cover Art' }]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ await waitFor(() => {+ expect(screen.queryByText(/Could not load artwork images/)).not.toBeInTheDocument();+ });+ });++ it('renders empty copy when a game has no artwork bindings', async () => {+ renderAt('/game/verified-game?gameTab=assets');+ expect(await screen.findByText(/No world or interface artwork is bound yet/)).toBeInTheDocument();+ expect(screen.queryByText('Could not load artwork images.')).not.toBeInTheDocument();+ });});diff --git a/client/src/pages/LoraTraining.jsx b/client/src/pages/LoraTraining.jsxindex b20e053617..8e5fac1f0d 100644--- a/client/src/pages/LoraTraining.jsx+++ b/client/src/pages/LoraTraining.jsx@@ -6,7 +6,7 @@* universe → character and lands on the dataset workbench.*/-import { useState, useEffect, useCallback } from 'react';+import { useState } from 'react';import { Link, useNavigate } from 'react-router';import { GraduationCap, Plus, Loader2, Sparkles, Images } from 'lucide-react';import toast from '../components/ui/Toast';@@ -14,12 +14,16 @@ import Modal from '../components/ui/Modal';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import UniverseCharacterPicker from '../components/loraTraining/UniverseCharacterPicker';import MediaJobsQueue from '../components/media/MediaJobsQueue';+import ListLoadError from '../components/ui/ListLoadError';+import useListResource from '../hooks/useListResource';import {listLoraDatasets,createLoraDataset,deleteLoraDataset,} from '../services/api';+const loadLoraDatasets = () => listLoraDatasets({}, { silent: true });+const STATUS_CHIP = {draft: 'bg-port-border/40 text-gray-300',training: 'bg-port-warning/20 text-port-warning',@@ -81,16 +85,14 @@ function NewDatasetDialog({ onClose, onCreated }) {export default function LoraTraining() {const navigate = useNavigate();- const [datasets, setDatasets] = useState(null);+ const datasetsResource = useListResource(loadLoraDatasets);+ const {+ items: datasets, state, error, retry, setItems: setDatasets,+ } = datasetsResource;const [showNew, setShowNew] = useState(false);const [deletingId, setDeletingId] = useState(null);const [confirmingId, setConfirmingId] = useState(null);- const refresh = useCallback(() => {- listLoraDatasets().then(setDatasets).catch(() => setDatasets([]));- }, []);- useEffect(() => { refresh(); }, [refresh]);-const onDelete = async (id) => {setDeletingId(id);try {@@ -119,11 +121,15 @@ export default function LoraTraining() {</button></div>- {datasets === null && (+ {state === 'loading' && (<div className="text-gray-400 flex items-center gap-2"><Loader2 className="w-4 h-4 animate-spin" /> Loading datasets…</div>)}- {datasets?.length === 0 && (+ {state === 'error' && (+ <ListLoadError what="datasets" error={error} onRetry={retry} />+ )}++ {state === 'ready' && datasets.length === 0 && (<div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400"><Sparkles className="w-8 h-8 mx-auto mb-3 text-port-accent" /><p className="mb-1 text-white">Train a LoRA for consistent universe subjects.</p>@@ -131,7 +137,8 @@ export default function LoraTraining() {</div>)}- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">+ {state === 'ready' && datasets.length > 0 && (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">{(datasets || []).map((d) => (<div key={d.id} className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-3"><div className="flex items-start justify-between gap-2">@@ -185,7 +192,8 @@ export default function LoraTraining() {</div></div>))}- </div>+ </div>+ )}<div className="mt-6"><MediaJobsQueue kind="training" />diff --git a/client/src/pages/LoraTraining.test.jsx b/client/src/pages/LoraTraining.test.jsxnew file mode 100644index 0000000000..8303e1c03f--- /dev/null+++ b/client/src/pages/LoraTraining.test.jsx@@ -0,0 +1,59 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../services/api', () => ({+ listLoraDatasets: vi.fn(),+ createLoraDataset: vi.fn(),+ deleteLoraDataset: vi.fn(),+}));+vi.mock('../components/loraTraining/UniverseCharacterPicker', () => ({ default: () => null }));+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++import LoraTraining from './LoraTraining.jsx';+import { listLoraDatasets } from '../services/api';++describe('LoraTraining page', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('renders ListLoadError with retry on failed datasets load, and empty state on real empty list', async () => {+ listLoraDatasets.mockRejectedValueOnce(new Error('500 Internal Server Error'));+ render(+ <MemoryRouter>+ <LoraTraining />+ </MemoryRouter>+ );+ await act(async () => {});++ expect(screen.getByRole('alert')).toHaveTextContent('Could not load datasets — 500 Internal Server Error');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(screen.queryByText('Train a LoRA for consistent universe subjects.')).not.toBeInTheDocument();++ listLoraDatasets.mockResolvedValueOnce([]);+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ });++ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText('Train a LoRA for consistent universe subjects.')).toBeInTheDocument();+ });++ it('renders datasets when load succeeds', async () => {+ listLoraDatasets.mockResolvedValueOnce([+ { id: 'ds-1', character: { name: 'Captain Nova' }, status: 'draft', imageCount: 12 },+ ]);+ render(+ <MemoryRouter>+ <LoraTraining />+ </MemoryRouter>+ );+ await act(async () => {});++ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText('Captain Nova')).toBeInTheDocument();+ expect(screen.queryByText('Train a LoRA for consistent universe subjects.')).not.toBeInTheDocument();+ });+});diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex 1f5e3be355..9c265ade59 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -24,6 +24,9 @@ import socket from '../services/socket';import useMediaPreviewActions from '../hooks/useMediaPreviewActions';import usePreviewRoute from '../hooks/usePreviewRoute';import { useGalleryPage } from '../hooks/useGalleryPage';+import useListResource from '../hooks/useListResource';++const loadCollections = () => listMediaCollections({ silent: true });// Local-vs-remote state of one collection item. Local files (the normal case)// carry no badge; the header summarizes the peer-hosted count.@@ -60,7 +63,10 @@ export default function MediaCollectionDetail() {// Full collections list — fetched once for the bulk move/copy picker so it// doesn't pay a per-mount listMediaCollections() round-trip when opened.// Already loaded for the unsorted view as part of buildUnsortedCollection().- const [allCollections, setAllCollections] = useState(null);+ const collectionsResource = useListResource(loadCollections);+ const {+ items: allCollections, state: collectionsState, error: collectionsError, retry: retryCollections,+ } = collectionsResource;const [loading, setLoading] = useState(true);const [editingName, setEditingName] = useState(false);const [nameDraft, setNameDraft] = useState('');@@ -91,12 +97,12 @@ export default function MediaCollectionDetail() {const refresh = useCallback(async () => {setLoading(true);page.refresh();- const [c, cols] = await Promise.all([- isUnsorted ? Promise.resolve(buildUnsortedCollection([], [], [])) : getMediaCollection(id, { silent: true }).catch(err => { toast.error(err.message || 'Collection not found'); return null; }),- listMediaCollections({ silent: true }).catch(() => []),- ]);- setCollection(c); setAllCollections(cols); setNameDraft(c?.name || ''); setLoading(false);- }, [id, isUnsorted, page.refresh]);+ retryCollections();+ const c = await (isUnsorted+ ? Promise.resolve(buildUnsortedCollection([], [], []))+ : getMediaCollection(id, { silent: true }).catch(err => { toast.error(err.message || 'Collection not found'); return null; }));+ setCollection(c); setNameDraft(c?.name || ''); setLoading(false);+ }, [id, isUnsorted, page.refresh, retryCollections]);useEffect(() => { refresh(); }, [refresh]);// Where each item's bytes live (server-annotated): 'local' | 'remote' (hosted// by a peer and streamed on demand) | 'missing'. Items without an annotation@@ -583,7 +589,9 @@ export default function MediaCollectionDetail() {excludeId={collection.id}busy={bulkBusy}title={`${pickerMode === 'move' ? 'Move' : 'Copy'} ${selected.size} to…`}- collections={allCollections}+ collections={collectionsState === 'ready' ? allCollections : null}+ error={collectionsError}+ onRetry={retryCollections}onPick={bulkMoveOrCopy}onClose={() => setPickerMode(null)}/>diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex ac06a1f7e1..8061a179be 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -149,6 +149,7 @@ const STAGE_VIEWS = {// Stable fetcher for useListResource — the hook re-runs on identity change.const loadTracks = () => listTracks({ silent: true });+const loadUniverses = () => listUniverseNames({ silent: true });export default function MusicVideo() {// Deep-linkable project selection: the selected project lives in the URL@@ -193,7 +194,8 @@ export default function MusicVideo() {// 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);+ const universeResource = useListResource(loadUniverses);+ const universes = universeResource.items;// 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.const stageOnlyParam = !routeStage && !routeSceneId && !routeArtifactId ? resolveStageParam(routeProjectId) : null;@@ -423,10 +425,6 @@ export default function MusicVideo() {navigate(id ? `/music-video/${id}${stage ? `/${stage}` : ''}${search ? `?${search}` : ''}` : `/music-video${search ? `?${search}` : ''}`);};- useEffect(() => {- listUniverseNames({ silent: true }).then((u) => setUniverses(u || [])).catch(() => setUniverses([]));- }, []);-const trackName = useCallback((id) => tracks.find((t) => t.id === id)?.title || id || '—', [tracks]);const handleCreate = (e) => {@@ -600,6 +598,7 @@ export default function MusicVideo() {tracks={tracks}trackLibrary={trackLibrary}universes={universes}+ universeResource={universeResource}trackName={trackName}youtube={youtube}onSubmit={handleCreate}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 1d4c202b51..0a50568683 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -3705,4 +3705,28 @@ describe('MusicVideo deep-linking and drawer URL routing (#10168)', () => {act(() => routerNavigate(-1));await waitFor(() => expect(screen.queryByRole('heading', { level: 2, name: 'New music video' })).not.toBeInTheDocument());});++ it('renders ListLoadError with retry when universe names fail to load in create project drawer', async () => {+ const { listUniverseNames } = await import('../services/apiUniverseBuilder.js');+ listUniverseNames.mockReset();+ listUniverseNames.mockRejectedValueOnce(new Error('Universes offline'));+ listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP]);++ render(+ <MemoryRouter initialEntries={['/music-video?new=project']}>+ {MV_ROUTES}+ </MemoryRouter>+ );++ expect(await screen.findByRole('heading', { level: 2, name: 'New music video' })).toBeInTheDocument();+ expect(await screen.findByText(/Could not load universes/)).toBeInTheDocument();++ listUniverseNames.mockResolvedValueOnce([{ id: 'u1', name: 'Cyberverse' }]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ await waitFor(() => {+ expect(screen.queryByText(/Could not load universes/)).not.toBeInTheDocument();+ });+ expect(screen.getByRole('option', { name: 'Cyberverse' })).toBeInTheDocument();+ });});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex f9fc9d29e7..752a260e44 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -4,7 +4,9 @@ import { PersonStanding, LayoutGrid, Images, Scissors, Film } from 'lucide-reactimport PageHeader from '../components/PageHeader';import PageSkeleton from '../components/ui/PageSkeleton';import EmptyState from '../components/EmptyState';+import ListLoadError from '../components/ui/ListLoadError.jsx';import toast from '../components/ui/Toast';+import useListResource from '../hooks/useListResource.js';import {listSpriteRecords, getSpriteRecord,generateSpriteWalk, generateSpriteTrack, generateSpriteReference, listSpriteThumbnails,@@ -46,10 +48,23 @@ import { buildCollectionActions } from '../lib/spriteCollectionActions.js';const SPRITE_EVENTS = ['sprites:changed'];+const loadSpriteRecords = () => listSpriteRecords({ silent: true });+const loadAnimationProviders = async () => {+ const res = await listSpriteAnimationProviders({ silent: true });+ return Array.isArray(res?.providers) ? res.providers : [];+};+const loadImageBackends = async () => {+ const settings = await getSettings({ silent: true });+ return deriveAvailableBackends(settings, { excludeExternal: true });+};+export default function Sprites() {const { id } = useParams();const navigate = useNavigate();- const [records, setRecords] = useState(null);+ const spriteResource = useListResource(loadSpriteRecords);+ const {+ items: records, state: recordsState, error: recordsError, retry: retryRecords, setItems: setRecords,+ } = spriteResource;const {data: detail, error: detailError, refetch: refreshDetail, updateData: setDetail,} = useSocketResource(@@ -66,10 +81,8 @@ export default function Sprites() {const goto = useCallback((rid) => navigate(`/sprites/${rid}`), [navigate]);const refresh = useCallback(() => {- // request() already toasted; settle to an empty list so the header/catalog- // don't spin forever.- listSpriteRecords().then(setRecords).catch(() => setRecords([]));- }, []);+ retryRecords();+ }, [retryRecords]);// Catalog thumbnails are only shown on the Library view (`!id`), and// listSpriteThumbnails is an O(records) disk scan — so fetch them when the@@ -113,8 +126,6 @@ export default function Sprites() {return refreshDetail();}, [refresh, refreshDetail]);- useEffect(() => { refresh(); }, [refresh]);-// In-flight render tracking is owned HERE rather than inside each workflow// (#2931): the asset collection's Regenerate buttons fire the same two// endpoints the workflows do, so they must share one map — two hook@@ -207,39 +218,27 @@ export default function Sprites() {// MiniMax H3 one. Page state for the same reason `duration` is: a Regenerate// fired from an asset card must use the lane the user picked in the walk// panel, not a second copy that drifted from it.- //- // `null` = not fetched yet, `[]` = fetched and this install offers none —- // distinct on purpose, so a failed fetch never renders as "grok is gone".- // The selection stays on the server's own default until the list arrives,- // which keeps the pre-#4876 behavior for the first paint and for any install- // whose readiness probe fails.- const [animationProviders, setAnimationProviders] = useState(null);+ const animProvidersResource = useListResource(loadAnimationProviders);+ const {+ items: animationProviders, error: animProvidersError, retry: retryAnimProviders,+ } = animProvidersResource;const [animationProvider, setAnimationProvider] = useState('grok');- useEffect(() => {- listSpriteAnimationProviders({ silent: true })- .then((res) => setAnimationProviders(Array.isArray(res?.providers) ? res.providers : []))- .catch(() => setAnimationProviders([]));- }, []);// Image-backend availability + the selected backend `mode` are page-owned// (#2938): both ReferenceWorkflow's picker and the asset collection's anchor// Regenerate must read ONE mode, or a card re-roll would use a different- // backend than the one the user picked in the workflow. `null` = settings not- // loaded yet; `[]` = loaded with no image backend configured.- const [imageBackends, setImageBackends] = useState(null);+ // backend than the one the user picked in the workflow.+ const imageBackendsResource = useListResource(loadImageBackends);+ const {+ items: imageBackends, state: imageBackendsState, error: imageBackendsError, retry: retryImageBackends,+ } = imageBackendsResource;const [imageMode, setImageMode] = useState('');+useEffect(() => {- getSettings({ silent: true })- .then((settings) => {- const available = deriveAvailableBackends(settings, { excludeExternal: true });- setImageBackends(available);- // Prefer the configured dispatcher default when it's available, else- // the first list entry — matching ReferenceWorkflow's prior logic.- const configured = available.find((b) => b.id === settings?.imageGen?.mode)?.id;- setImageMode((m) => m || configured || available[0]?.id || '');- })- .catch(() => setImageBackends([]));- }, []);+ if (imageBackendsState === 'ready' && imageBackends.length > 0) {+ setImageMode((m) => m || imageBackends[0]?.id || '');+ }+ }, [imageBackendsState, imageBackends]);const hasImageBackend = Array.isArray(imageBackends) && imageBackends.length > 0;// Seed the page-owned backend picker from an opened record's persisted@@ -396,10 +395,12 @@ export default function Sprites() {providers={animationProviders}provider={animationProvider}onProviderChange={setAnimationProvider}+ providersError={animProvidersError}+ onRetryProviders={retryAnimProviders}/>)), [detail?.tracks, detail?.record, detail?.reference, generateTrack, onWorkflowChanged, corrections,- animationProviders, animationProvider,+ animationProviders, animationProvider, animProvidersError, retryAnimProviders,]);@@ -482,7 +483,7 @@ export default function Sprites() {<section className="min-w-0">{!id ? (// The bare /sprites route IS the Library catalog now.- records === null ? (+ recordsState === 'loading' ? (<PageSkeletonheader="none"label="Loading sprite library"@@ -490,6 +491,8 @@ export default function Sprites() {cards={10}gridColsClass="grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5"/>+ ) : recordsState === 'error' ? (+ <ListLoadError what="sprites" error={recordsError} onRetry={retryRecords} />) : records.length === 0 ? (<EmptyStateicon={PersonStanding}@@ -571,6 +574,8 @@ export default function Sprites() {onModeChange={setImageMode}onChanged={onWorkflowChanged}onForked={(rec) => { refresh(); navigate(`/sprites/${rec.id}`); }}+ backendsError={imageBackendsError}+ onRetryBackends={retryImageBackends}/><WalkWorkflowrecord={detail.record}@@ -587,6 +592,8 @@ export default function Sprites() {onChanged={onWorkflowChanged}corrections={corrections}onCorrectionChange={setCorrections}+ providersError={animProvidersError}+ onRetryProviders={retryAnimProviders}/>{trackSections}{/* Keyed by record so form state and an armed publish/overwritediff --git a/client/src/pages/Sprites.test.jsx b/client/src/pages/Sprites.test.jsxindex 476974b33f..eea5ec6428 100644--- a/client/src/pages/Sprites.test.jsx+++ b/client/src/pages/Sprites.test.jsx@@ -38,7 +38,7 @@ vi.mock('../components/sprites/NewSpritePanel.jsx', () => ({ default: () => nullvi.mock('../components/sprites/SpriteSearch.jsx', () => ({ default: () => null }));import Sprites from './Sprites.jsx';-import { getSpriteRecord } from '../services/apiSprites.js';+import { getSpriteRecord, listSpriteRecords } from '../services/apiSprites.js';import { listMediaJobs, getMediaJob } from '../services/apiMediaJobs.js';const detail = (status = 'rendering', id = 'example-sprite') => ({@@ -109,4 +109,24 @@ describe('persisted sprite events in the rendered page', () => {expect(screen.queryByRole('heading', { name: 'example-sprite' })).not.toBeInTheDocument();expect(getSpriteRecord).toHaveBeenCalledTimes(2);});++ it('renders ListLoadError with retry on failed sprite records load, and empty state on real empty list', async () => {+ listSpriteRecords.mockRejectedValueOnce(new Error('503 Service Unavailable'));+ render(+ <MemoryRouter initialEntries={['/sprites']}>+ <Routes><Route path="/sprites" element={<Page />} /></Routes>+ </MemoryRouter>+ );+ await act(async () => {});+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load sprites — 503 Service Unavailable');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(screen.queryByText('No sprites yet')).not.toBeInTheDocument();++ listSpriteRecords.mockResolvedValueOnce([]);+ await act(async () => {+ screen.getByRole('button', { name: 'Retry' }).click();+ });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText('No sprites yet')).toBeInTheDocument();+ });});diff --git a/client/src/pages/VideoDownloaderPage.jsx b/client/src/pages/VideoDownloaderPage.jsxindex 7da0e397a6..baade27bb1 100644--- a/client/src/pages/VideoDownloaderPage.jsx+++ b/client/src/pages/VideoDownloaderPage.jsx@@ -1,32 +1,31 @@-import { useEffect, useState } from 'react';+import { useState } from 'react';import { Download, Film, Loader2, Trash2, ExternalLink, Video } from 'lucide-react';import BrailleSpinner from '../components/BrailleSpinner';+import ListLoadError from '../components/ui/ListLoadError';import toast from '../components/ui/Toast';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import YtDlpUpdateCard from '../components/video/YtDlpUpdateCard';import { useVideoDownload, useConfirmDelete } from '../hooks';+import useListResource from '../hooks/useListResource';import { listVideoDownloads, deleteVideoDownload } from '../services/apiVideoDownload.js';import { timeAgo, formatTimecode } from '../utils/formatters';+const loadVideoDownloads = () => listVideoDownloads({ silent: true });+// Dev Tools video downloader (#1946) — paste a YouTube or x.com/Twitter URL,// download the full video via yt-dlp into data/videos (where it also shows up in// the media gallery), and browse/delete what's been downloaded.export default function VideoDownloaderPage() {const [url, setUrl] = useState('');- const [downloads, setDownloads] = useState([]);- const [loading, setLoading] = useState(true);+ const downloadsResource = useListResource(loadVideoDownloads);+ const {+ items: downloads, state, error, retry, setItems: setDownloads,+ } = downloadsResource;const [deletingId, setDeletingId] = useState(null);// Thumbnail filenames that failed to load; keyed by value so a new thumbnail retries.const [failedThumbs, setFailedThumbs] = useState(() => new Set());const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();- useEffect(() => {- listVideoDownloads()- .then((list) => setDownloads(Array.isArray(list) ? list : []))- .catch(() => setDownloads([]))- .finally(() => setLoading(false));- }, []);-// Prepend the finished clip to the list rather than refetching (reactive UI).const { active, percent, stage, start, cancel } = useVideoDownload({onComplete: (video) => {@@ -112,8 +111,10 @@ export default function VideoDownloaderPage() {<section><h2 className="text-sm font-semibold text-gray-300 mb-2">Downloaded ({downloads.length})</h2>- {loading ? (+ {state === 'loading' ? (<p className="text-sm"><BrailleSpinner text="Loading…" /></p>+ ) : state === 'error' ? (+ <ListLoadError what="downloads" error={error} onRetry={retry} />) : downloads.length === 0 ? (<p className="text-sm text-gray-500">No videos downloaded yet.</p>) : (diff --git a/client/src/pages/VideoDownloaderPage.test.jsx b/client/src/pages/VideoDownloaderPage.test.jsxindex 55014c724d..23813d4c65 100644--- a/client/src/pages/VideoDownloaderPage.test.jsx+++ b/client/src/pages/VideoDownloaderPage.test.jsx@@ -16,9 +16,14 @@ vi.mock('../components/video/YtDlpUpdateCard', () => ({ default: () => null }));vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));import VideoDownloaderPage from './VideoDownloaderPage';+import { listVideoDownloads } from '../services/apiVideoDownload.js';-describe('VideoDownloaderPage thumbnails', () => {+describe('VideoDownloaderPage', () => {it('swaps only the failed thumbnail for the placeholder', async () => {+ listVideoDownloads.mockResolvedValueOnce([+ { id: 'a', filename: 'a.mp4', thumbnail: 'a.jpg', title: 'Clip A', createdAt: new Date().toISOString() },+ { id: 'b', filename: 'b.mp4', thumbnail: 'b.jpg', title: 'Clip B', createdAt: new Date().toISOString() },+ ]);const { container } = render(<VideoDownloaderPage />);await waitFor(() => expect(container.querySelectorAll('img').length).toBe(2));const rows = screen.getAllByRole('listitem');@@ -31,4 +36,20 @@ describe('VideoDownloaderPage thumbnails', () => {expect(rows[1].querySelector('img')).not.toBeNull();expect(rowA.getByText('Clip A')).toBeTruthy();});++ it('renders ListLoadError with retry on failed downloads load, and empty copy on real empty list', async () => {+ listVideoDownloads.mockRejectedValueOnce(new Error('Downloads 500 error'));+ render(<VideoDownloaderPage />);+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());++ expect(screen.getByRole('alert')).toHaveTextContent('Could not load downloads — Downloads 500 error');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(screen.queryByText('No videos downloaded yet.')).not.toBeInTheDocument();++ listVideoDownloads.mockResolvedValueOnce([]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ await waitFor(() => expect(screen.getByText('No videos downloaded yet.')).toBeInTheDocument());+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });});diff --git a/client/src/pages/VideoTimeline.jsx b/client/src/pages/VideoTimeline.jsxindex e65480315d..48414e362c 100644--- a/client/src/pages/VideoTimeline.jsx+++ b/client/src/pages/VideoTimeline.jsx@@ -1,32 +1,31 @@-import { useEffect, useMemo, useState } from 'react';+import { useMemo, useState } from 'react';import { useNavigate } from 'react-router';import { Plus, Film, Trash2, Clock } from 'lucide-react';import PageSkeleton from '../components/ui/PageSkeleton';+import ListLoadError from '../components/ui/ListLoadError';import toast from '../components/ui/Toast';+import useListResource from '../hooks/useListResource';import * as api from '../services/api';import { formatDurationSec } from '../utils/formatters';import { projectSummary, historySourceDuration } from '../lib/videoTimelineModel';+const loadTimelineProjects = () => api.listTimelineProjects({ silent: true });+const loadVideoHistory = () => api.listVideoHistory({ silent: true });+export default function VideoTimeline() {const navigate = useNavigate();- const [projects, setProjects] = useState([]);- const [history, setHistory] = useState([]);- const [loading, setLoading] = useState(true);+ const projectsResource = useListResource(loadTimelineProjects);+ const {+ items: projects, state: projectsState, error: projectsError, retry: retryProjects, setItems: setProjects,+ } = projectsResource;+ const historyResource = useListResource(loadVideoHistory);+ const {+ items: history, state: historyState, error: historyError, retry: retryHistory,+ } = historyResource;+ const loading = projectsState === 'loading' || historyState === 'loading';const [creating, setCreating] = useState(false);const [name, setName] = useState('');- const refresh = async () => {- const [list, hist] = await Promise.all([- api.listTimelineProjects().catch(() => []),- api.listVideoHistory().catch(() => []),- ]);- setProjects(list);- setHistory(hist);- setLoading(false);- };-- useEffect(() => { refresh(); }, []);-const handleCreate = async (e) => {e.preventDefault();const trimmed = name.trim();@@ -47,7 +46,7 @@ export default function VideoTimeline() {setProjects((prev) => prev.filter((p) => p.id !== project.id));await api.deleteTimelineProject(project.id, { silent: true }).catch((err) => {toast.error(`Failed to delete: ${err.message}`);- refresh();+ retryProjects();});};@@ -81,14 +80,22 @@ export default function VideoTimeline() {{loading && <PageSkeleton header="none" label="Loading timeline projects" layout="grid" cards={3} gridColsClass="sm:grid-cols-2 lg:grid-cols-3" />}- {!loading && projects.length === 0 && (+ {projectsState === 'error' && (+ <ListLoadError what="timeline projects" error={projectsError} onRetry={retryProjects} />+ )}++ {historyState === 'error' && (+ <ListLoadError what="video history" error={historyError} onRetry={retryHistory} />+ )}++ {!loading && projectsState === 'ready' && projects.length === 0 && (<div className="text-center py-12 text-gray-500"><Film className="w-10 h-10 mx-auto mb-3 opacity-40" /><p className="text-sm">No timeline projects yet. Create one above to start compositing clips.</p></div>)}- {!loading && projects.length > 0 && (+ {!loading && projectsState === 'ready' && projects.length > 0 && (<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">{projects.map((project) => {const { totalSec, blockCount, firstThumb } = projectStats.get(project.id) || { totalSec: 0, blockCount: 0, firstThumb: null };diff --git a/client/src/pages/VideoTimeline.test.jsx b/client/src/pages/VideoTimeline.test.jsxnew file mode 100644index 0000000000..a30ba95cb8--- /dev/null+++ b/client/src/pages/VideoTimeline.test.jsx@@ -0,0 +1,72 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../services/api', () => ({+ listTimelineProjects: vi.fn(),+ listVideoHistory: vi.fn(),+ createTimelineProject: vi.fn(),+ deleteTimelineProject: vi.fn(),+}));+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++import VideoTimeline from './VideoTimeline.jsx';+import { listTimelineProjects, listVideoHistory } from '../services/api';++describe('VideoTimeline page', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ listTimelineProjects.mockResolvedValue([]);+ listVideoHistory.mockResolvedValue([]);+ });++ it('renders ListLoadError with retry on failed timeline projects load', async () => {+ listTimelineProjects.mockRejectedValueOnce(new Error('Projects 500 error'));+ render(+ <MemoryRouter>+ <VideoTimeline />+ </MemoryRouter>+ );+ await act(async () => {});++ expect(screen.getByRole('alert')).toHaveTextContent('Could not load timeline projects — Projects 500 error');+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ expect(screen.queryByText(/No timeline projects yet/)).not.toBeInTheDocument();++ listTimelineProjects.mockResolvedValueOnce([]);+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ });++ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText(/No timeline projects yet/)).toBeInTheDocument();+ });++ it('renders ListLoadError on failed video history load', async () => {+ listVideoHistory.mockRejectedValueOnce(new Error('History 500 error'));+ render(+ <MemoryRouter>+ <VideoTimeline />+ </MemoryRouter>+ );+ await act(async () => {});++ expect(screen.getByRole('alert')).toHaveTextContent('Could not load video history — History 500 error');+ });++ it('renders projects and duration when loaded', async () => {+ listTimelineProjects.mockResolvedValueOnce([+ { id: 'proj-1', name: 'Cyberpunk Chase', clips: [{ id: 'clip-1', durationSec: 10 }] },+ ]);+ render(+ <MemoryRouter>+ <VideoTimeline />+ </MemoryRouter>+ );+ await act(async () => {});++ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText('Cyberpunk Chase')).toBeInTheDocument();+ expect(screen.queryByText(/No timeline projects yet/)).not.toBeInTheDocument();+ });+});diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex fccb2e081e..7c71711953 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -374,7 +374,7 @@ export const previewVideoPrompt = (fields, options = {}) => request('/video-gen/});// Video timeline projects (non-linear editor)-export const listTimelineProjects = () => request('/video-timeline/projects');+export const listTimelineProjects = (options = {}) => request('/video-timeline/projects', options);export const getTimelineProject = (id, options) => request(`/video-timeline/projects/${encodeURIComponent(id)}`, options);export const createTimelineProject = (name, options = {}) => request('/video-timeline/projects', {method: 'POST',diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.jsindex 401f13f3d6..ea1e6f210c 100644--- a/client/src/services/apiLoraTraining.js+++ b/client/src/services/apiLoraTraining.js@@ -8,13 +8,13 @@ import { request } from './apiCore.js';// ---- Datasets -----export const listLoraDatasets = (filters = {}) => {+export const listLoraDatasets = (filters = {}, options = {}) => {const params = new URLSearchParams();for (const key of ['universeId', 'entryKind', 'entryId', 'ingredientId']) {if (filters[key]) params.set(key, filters[key]);}const qs = params.toString();- return request(`/lora-datasets${qs ? `?${qs}` : ''}`);+ return request(`/lora-datasets${qs ? `?${qs}` : ''}`, options);};export const createLoraDataset = ({