Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: show a load error with Retry instead of an empty list when creative-panel reads fail (#12785)
Adam Eivy3b994aee774a
diff --git a/client/src/asyncEffectDisposalConventions.test.js b/client/src/asyncEffectDisposalConventions.test.jsindex e16b30ba6f..031da44b0b 100644--- a/client/src/asyncEffectDisposalConventions.test.js+++ b/client/src/asyncEffectDisposalConventions.test.js@@ -97,8 +97,6 @@ const ALLOWED = {'setLoading(false) is a load-finished latch, not a response written into state','src/components/codeAnimation/CodeAnimationGallery.jsx':'deps are [items] of one fixed gallery query; each poster answer is applied by its own job id, so none can land under another record',- 'src/components/sprites/ImportPanel.jsx':- 'deps are [open] only — a drawer preload with no record identity to switch','src/components/voice/VoiceWidget.jsx':'deps are [enabled, navigate] — a session toggle, not a record identity','src/hooks/useImageGenPageRuntime.js':diff --git a/client/src/components/fableloom/LoomProductionPanel.jsx b/client/src/components/fableloom/LoomProductionPanel.jsxindex f31c26c995..6a73039a8a 100644--- a/client/src/components/fableloom/LoomProductionPanel.jsx+++ b/client/src/components/fableloom/LoomProductionPanel.jsx@@ -23,7 +23,9 @@ import {} from 'lucide-react';import { useAsyncAction } from '../../hooks/useAsyncAction';import { useFableLoomRun } from '../../hooks/useFableLoomRun';+import useListResource from '../../hooks/useListResource';import BackendChipStrip from '../media/BackendChipStrip';+import ListLoadError from '../ui/ListLoadError';import {cancelLoomEpisodeProductionBatch,getLoomEpisodeProductionBatchStatus,@@ -55,6 +57,9 @@ const VIDEO_BACKENDS = [{ id: 'grok', label: 'Grok', icon: Cloud },];+const fetchImageModels = () => listImageModels({ silent: true });+const fetchVideoModels = () => listVideoModels({ silent: true });+const modelOptions = (models, selected) => {const options = (Array.isArray(models) ? models : []).filter((model) => model?.id)@@ -84,8 +89,10 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLooconst [videoMode, setVideoMode] = useState(savedRender.videoMode);const [videoModel, setVideoModel] = useState(savedRender.videoModel);const [effort, setEffort] = useState(savedRender.effort);- const [imageModels, setImageModels] = useState([]);- const [videoModels, setVideoModels] = useState([]);+ const imageModelList = useListResource(fetchImageModels);+ const videoModelList = useListResource(fetchVideoModels);+ const imageModels = imageModelList.items;+ const videoModels = videoModelList.items;const renderFormat = asFableLoomRenderSettings(loom.renderSettings);const productionIdentity = `${loom.id}:${episode.id}`;const productionIdentityRef = useRef(productionIdentity);@@ -144,19 +151,6 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLooonLoomUpdate?.(updated);}, { errorMessage: 'Saving output format failed' });- useEffect(() => {- const load = (loader) => (typeof loader === 'function'- ? Promise.resolve().then(() => loader({ silent: true })).catch(() => [])- : Promise.resolve([]));- let mounted = true;- Promise.all([load(listImageModels), load(listVideoModels)]).then(([images, videos]) => {- if (!mounted) return;- setImageModels(images);- setVideoModels(videos);- });- return () => { mounted = false; };- }, []);-// Story settings are durable defaults; keep the per-run controls in sync// when those defaults change while this panel remains mounted. A one-off// panel change does not touch the loom, so it remains an intentional override.@@ -417,6 +411,9 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLoo))}</select>)}+ {imageModelList.state === 'error' && (+ <ListLoadError className="basis-full" what="image models" error={imageModelList.error} onRetry={imageModelList.retry} />+ )}</div>{assetScope === 'all' && (<div className="flex flex-wrap items-center gap-2">@@ -448,6 +445,9 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLoo))}</select>)}+ {videoModelList.state === 'error' && (+ <ListLoadError className="basis-full" what="video models" error={videoModelList.error} onRetry={videoModelList.retry} />+ )}</div>)}<div className="flex items-center gap-2">diff --git a/client/src/components/fableloom/LoomProductionPanel.test.jsx b/client/src/components/fableloom/LoomProductionPanel.test.jsxindex 51a3ff6f69..2505d9f62c 100644--- a/client/src/components/fableloom/LoomProductionPanel.test.jsx+++ b/client/src/components/fableloom/LoomProductionPanel.test.jsx@@ -77,6 +77,18 @@ describe('LoomProductionPanel', () => {});});+ it('shows a model-catalog error with Retry when the image model read fails, instead of an empty model picker', async () => {+ api.listImageModels.mockRejectedValueOnce(new Error('Models unavailable'));+ render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load image models — Models unavailable');++ api.listImageModels.mockResolvedValueOnce([{ id: 'image-model-a', name: 'Image Model A' }]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('option', { name: 'Image Model A' })).toBeInTheDocument();+ });+it('renders plan summary and allows switching mode', async () => {render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} onSelectNode={vi.fn()} />);diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsxindex b336fc0e5f..46251ddfce 100644--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx@@ -26,9 +26,11 @@ import Drawer from '../Drawer';import BackendChipStrip from '../media/BackendChipStrip';import ProviderModelSelector from '../ProviderModelSelector';import { FormField } from '../ui/FormField.jsx';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import useProviderModels from '../../hooks/useProviderModels';import { useAsyncAction } from '../../hooks/useAsyncAction';+import useListResource from '../../hooks/useListResource';import { CODEX_EFFORT_LEVELS, effectiveModelFor, effortAwareModelOptions } from '../../utils/providers';import { listImageModels, listVideoModels, reformatLoomEpisode, updateLoom } from '../../services/api';import { fieldClass, labelClass } from './fieldStyles';@@ -67,13 +69,8 @@ const modelOptions = (models, selected) => {return options;};-const replaceModelList = (setModels, nextModels) => setModels((currentModels) => {- const unchanged = currentModels.length === nextModels.length- && currentModels.every((model, index) => (- model?.id === nextModels[index]?.id && model?.name === nextModels[index]?.name- ));- return unchanged ? currentModels : nextModels;-});+const fetchImageModels = () => listImageModels({ silent: true });+const fetchVideoModels = () => listVideoModels({ silent: true });/*** The one line of feedback a multi-minute rewrite gives. Built as a single@@ -108,8 +105,10 @@ export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLoconst [videoMode, setVideoMode] = useState(savedRender.videoMode);const [videoModel, setVideoModel] = useState(savedRender.videoModel);const [renderEffort, setRenderEffort] = useState(savedRender.effort);- const [imageModels, setImageModels] = useState([]);- const [videoModels, setVideoModels] = useState([]);+ const imageModelList = useListResource(fetchImageModels, { enabled: open });+ const videoModelList = useListResource(fetchVideoModels, { enabled: open });+ const imageModels = imageModelList.items;+ const videoModels = videoModelList.items;useEffect(() => {if (open) return;setParticipationMode(loom.participationMode || 'protagonist');@@ -151,20 +150,6 @@ export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLo{ errorMessage: 'Save failed' },);- useEffect(() => {- if (!open) return undefined;- const load = (loader) => Promise.resolve()- .then(() => loader({ silent: true }))- .catch(() => []);- let mounted = true;- Promise.all([load(listImageModels), load(listVideoModels)]).then(([images, videos]) => {- if (!mounted) return;- replaceModelList(setImageModels, images);- replaceModelList(setVideoModels, videos);- });- return () => { mounted = false; };- }, [open]);-const pendingRender = useRef(null);if (!pendingRender.current || !saving) {pendingRender.current = {@@ -580,6 +565,9 @@ export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLo<option key={option.id} value={option.id}>{option.label}</option>))}</select>+ {imageModelList.state === 'error' && (+ <ListLoadError className="mt-1" what="image models" error={imageModelList.error} onRetry={imageModelList.retry} />+ )}</FormField>)}</div>@@ -616,6 +604,9 @@ export default function LoomSettingsDrawer({ open, onClose, loom, universe, onLo<option key={option.id} value={option.id}>{option.label}</option>))}</select>+ {videoModelList.state === 'error' && (+ <ListLoadError className="mt-1" what="video models" error={videoModelList.error} onRetry={videoModelList.retry} />+ )}</FormField>)}</div>diff --git a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx b/client/src/components/fableloom/LoomSettingsDrawer.test.jsxindex 8a96ce4c10..3e802a5582 100644--- a/client/src/components/fableloom/LoomSettingsDrawer.test.jsx+++ b/client/src/components/fableloom/LoomSettingsDrawer.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor, within } from '@testing-library/react';+import { act, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter } from 'react-router';import userEvent from '@testing-library/user-event';@@ -13,7 +13,7 @@ vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [vi.mock('../ProviderModelSelector', () => ({ default: () => null }));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));-import { reformatLoomEpisode, updateLoom } from '../../services/api';+import { listVideoModels, reformatLoomEpisode, updateLoom } from '../../services/api';import toast from '../ui/Toast';import LoomSettingsDrawer from './LoomSettingsDrawer';@@ -34,7 +34,9 @@ const twoEpisodes = () => makeLoom([{ id: 'ep-2', title: 'Second', nodes: [scene('s3')] },]);-const renderDrawer = (loom, props = {}) => {+// Settles the model-catalog reads the drawer starts on mount, so their state+// update lands inside act().+const renderDrawer = async (loom, props = {}) => {const onLoomUpdate = vi.fn();const onRewritten = vi.fn();render(@@ -49,6 +51,7 @@ const renderDrawer = (loom, props = {}) => {/></MemoryRouter>,);+ await act(async () => {});return { onLoomUpdate, onRewritten };};@@ -63,7 +66,7 @@ describe('LoomSettingsDrawer rewrite', () => {reformatLoomEpisode.mockResolvedValueOnce({ loom, rewritten: 2, episodeRemaining: 0, remaining: 1, capped: false }).mockResolvedValueOnce({ loom, rewritten: 1, episodeRemaining: 0, remaining: 0, capped: false });- const { onLoomUpdate } = renderDrawer(loom);+ const { onLoomUpdate } = await renderDrawer(loom);// The count is the scenes that still need converting, not every scene.expect(screen.getByRole('button', { name: 'Rewrite 3 scenes as teleplay' })).toBeInTheDocument();@@ -84,7 +87,7 @@ describe('LoomSettingsDrawer rewrite', () => {// observable rather than a frame that flashes past.const release = [];reformatLoomEpisode.mockImplementation(() => new Promise((resolve) => { release.push(resolve); }));- renderDrawer(loom);+ await renderDrawer(loom);await clickRewrite(user);expect(await screen.findByText('Rewriting episode 1 of 2 — Pilot…')).toBeInTheDocument();@@ -101,7 +104,7 @@ describe('LoomSettingsDrawer rewrite', () => {const loom = makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1')] }]);const release = [];reformatLoomEpisode.mockImplementation(() => new Promise((resolve) => { release.push(resolve); }));- renderDrawer(loom);+ await renderDrawer(loom);await clickRewrite(user);expect(await screen.findByText('Rewriting episode 1 of 1 — Pilot…')).toBeInTheDocument();@@ -117,7 +120,7 @@ describe('LoomSettingsDrawer rewrite', () => {reformatLoomEpisode.mockResolvedValueOnce({ loom, rewritten: 20, episodeRemaining: 5, remaining: 5, capped: true }).mockResolvedValueOnce({ loom, rewritten: 5, episodeRemaining: 0, remaining: 0, capped: false });- renderDrawer(loom);+ await renderDrawer(loom);await clickRewrite(user);await waitFor(() => expect(reformatLoomEpisode).toHaveBeenCalledTimes(2));@@ -131,7 +134,7 @@ describe('LoomSettingsDrawer rewrite', () => {// Not capped: nothing went unsent, so asking again would only re-send a// refusal. The leftover rides the toast instead.reformatLoomEpisode.mockResolvedValue({ loom, rewritten: 1, episodeRemaining: 1, remaining: 1, capped: false });- renderDrawer(loom);+ await renderDrawer(loom);await clickRewrite(user);await waitFor(() => expect(toast.success).toHaveBeenCalledWith(@@ -146,7 +149,7 @@ describe('LoomSettingsDrawer rewrite', () => {reformatLoomEpisode.mockResolvedValueOnce({ loom, rewritten: 2, episodeRemaining: 0, remaining: 1, capped: false }).mockRejectedValueOnce(new Error('provider unreachable'));- const { onRewritten } = renderDrawer(loom);+ const { onRewritten } = await renderDrawer(loom);await clickRewrite(user);await waitFor(() => expect(toast.error).toHaveBeenCalledWith('provider unreachable'));@@ -158,8 +161,8 @@ describe('LoomSettingsDrawer rewrite', () => {expect(screen.queryByText(/Rewriting episode/)).not.toBeInTheDocument();});- it('offers no rewrite at all once every scene is already in the target format', () => {- renderDrawer(makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1', 'teleplay')] }]));+ it('offers no rewrite at all once every scene is already in the target format', async () => {+ await renderDrawer(makeLoom([{ id: 'ep-1', title: 'Pilot', nodes: [scene('s1', 'teleplay')] }]));expect(screen.queryByRole('button', { name: /^Rewrite/ })).not.toBeInTheDocument();expect(screen.getByText(/Every scene you have is already written as teleplay/)).toBeInTheDocument();});@@ -173,7 +176,7 @@ describe('LoomSettingsDrawer audience participation', () => {audienceCommunicationMedium: 'A silver mirror.',});const user = userEvent.setup();- renderDrawer({ ...makeLoom([]), participationMode: 'protagonist' });+ await renderDrawer({ ...makeLoom([]), participationMode: 'protagonist' });await user.selectOptions(screen.getByLabelText('Audience role'), 'helper');expect(screen.getByText(/need a communication medium before the role can be saved/i)).toBeInTheDocument();@@ -196,11 +199,13 @@ describe('LoomSettingsDrawer audience participation', () => {onRewritten: vi.fn(),};const { rerender } = render(<LoomSettingsDrawer open {...props} />);+ await act(async () => {});await user.selectOptions(screen.getByLabelText('Audience role'), 'helper');expect(updateLoom).not.toHaveBeenCalled();rerender(<LoomSettingsDrawer open={false} {...props} />);rerender(<LoomSettingsDrawer open {...props} />);+ await act(async () => {});expect(screen.getByLabelText('Audience role')).toHaveValue('protagonist');});@@ -216,7 +221,7 @@ describe('LoomSettingsDrawer character continuity', () => {protagonistWardrobeId: 'coat',protagonistWardrobeLocked: true,});- renderDrawer(loom, {+ await renderDrawer(loom, {universe: {id: 'universe-1',characters: [{@@ -242,9 +247,23 @@ describe('LoomSettingsDrawer character continuity', () => {});});+describe('LoomSettingsDrawer model catalogs', () => {+ it('shows a load error with Retry when the video model read fails, instead of an empty model picker', async () => {+ listVideoModels.mockRejectedValueOnce(new Error('Models unavailable'));+ await renderDrawer(makeLoom([]));++ expect(screen.getByRole('alert')).toHaveTextContent('Could not load video models — Models unavailable');++ listVideoModels.mockResolvedValueOnce([{ id: 'video-model-a', name: 'Video Model A' }]);+ await act(async () => { screen.getByRole('button', { name: 'Retry' }).click(); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('option', { name: 'Video Model A' })).toBeInTheDocument();+ });+});+describe('LoomSettingsDrawer rendering defaults', () => {- it('shows the saved aspect ratio, renderers, models, and effort', () => {- renderDrawer({+ it('shows the saved aspect ratio, renderers, models, and effort', async () => {+ await renderDrawer({...makeLoom([]),renderSettings: {formatId: 'portrait-9-16',@@ -266,7 +285,7 @@ describe('LoomSettingsDrawer rendering defaults', () => {it('saves rendering defaults as one story-level pin', async () => {const user = userEvent.setup();- renderDrawer(makeLoom([]));+ await renderDrawer(makeLoom([]));await user.selectOptions(screen.getByLabelText('Aspect ratio'), 'square-1-1');diff --git a/client/src/components/loraTraining/CaptionModelPicker.jsx b/client/src/components/loraTraining/CaptionModelPicker.jsxindex 6661fa9438..21b62e898b 100644--- a/client/src/components/loraTraining/CaptionModelPicker.jsx+++ b/client/src/components/loraTraining/CaptionModelPicker.jsx@@ -11,6 +11,7 @@import { useEffect, useState } from 'react';import { Loader2, AlertTriangle } from 'lucide-react';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import { getVisionModels, getSettings, patchSettingsSlice } from '../../services/api';@@ -21,12 +22,19 @@ export default function CaptionModelPicker({ onChange }) {const [models, setModels] = useState(null); // null = loading; [] = none installedconst [value, setValue] = useState(AUTO);const [saving, setSaving] = useState(false);+ const [loadError, setLoadError] = useState(null);+ const [attempt, setAttempt] = useState(0);+ // The model list and the saved choice seed the select together; if either+ // read fails the picker shows a Retry instead of a select that would read+ // "none installed" and report Auto for a saved model.useEffect(() => {let alive = true;+ setModels(null);+ setLoadError(null);Promise.all([- getVisionModels({ silent: true }).catch(() => ({ models: [] })),- getSettings({ silent: true }).catch(() => ({})),+ getVisionModels({ silent: true }),+ getSettings({ silent: true }),]).then(([vm, settings]) => {if (!alive) return;const list = vm?.models || [];@@ -43,10 +51,13 @@ export default function CaptionModelPicker({ onChange }) {setValue(AUTO);onChange?.({ providerId: null, model: null });}+ }).catch((error) => {+ if (!alive) return;+ setLoadError(error instanceof Error ? error : new Error('Request failed'));});return () => { alive = false; };- // onChange is a stable setter from the parent; intentionally run once.- }, []);+ // onChange is a stable setter from the parent; reload only on retry.+ }, [attempt]);const handleChange = async (next) => {setValue(next);@@ -68,6 +79,10 @@ export default function CaptionModelPicker({ onChange }) {}};+ if (loadError) {+ return <ListLoadError what="vision models" error={loadError} onRetry={() => setAttempt((n) => n + 1)} />;+ }+if (models === null) {return (<span className="text-xs text-gray-500 flex items-center gap-1">diff --git a/client/src/components/loraTraining/CaptionModelPicker.test.jsx b/client/src/components/loraTraining/CaptionModelPicker.test.jsxnew file mode 100644index 0000000000..42ac953dbd--- /dev/null+++ b/client/src/components/loraTraining/CaptionModelPicker.test.jsx@@ -0,0 +1,40 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+const getVisionModels = vi.fn();+const getSettings = vi.fn();+vi.mock('../../services/api', () => ({+ getVisionModels: (...a) => getVisionModels(...a),+ getSettings: (...a) => getSettings(...a),+ patchSettingsSlice: vi.fn(),+}));++import CaptionModelPicker from './CaptionModelPicker';++const renderPicker = async (onChange = vi.fn()) => {+ render(<CaptionModelPicker onChange={onChange} />);+ await act(async () => {});+ return onChange;+};++beforeEach(() => vi.clearAllMocks());++describe('CaptionModelPicker', () => {+ it('shows a load error — not "none installed" or an Auto choice — when the model list fails', async () => {+ getVisionModels.mockRejectedValueOnce(new Error('Server unavailable'));+ getSettings.mockResolvedValue({ loraTraining: { captionModel: 'vision-a', captionProviderId: 'lmstudio' } });+ const onChange = await renderPicker();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load vision models — Server unavailable');+ expect(screen.queryByText('none installed')).toBeNull();+ expect(onChange).not.toHaveBeenCalled();++ getVisionModels.mockResolvedValueOnce({ models: [{ id: 'vision-a', providerId: 'lmstudio', name: 'Vision A', backend: 'LM Studio' }] });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByLabelText('Caption model')).toHaveValue('lmstudio::vision-a');+ expect(onChange).toHaveBeenCalledWith({ providerId: 'lmstudio', model: 'vision-a' });+ });+});diff --git a/client/src/components/media/UniverseMoodBoardPicker.jsx b/client/src/components/media/UniverseMoodBoardPicker.jsxindex 1511841a4f..97abc88b1a 100644--- a/client/src/components/media/UniverseMoodBoardPicker.jsx+++ b/client/src/components/media/UniverseMoodBoardPicker.jsx@@ -1,21 +1,31 @@-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { Link } from 'react-router';import { listMoodBoardNames, listUniverseNames, listUniverseStyles } from '../../services/api';+import ListLoadError from '../ui/ListLoadError';import { BOARD_FOLLOW_UNIVERSE, BOARD_NONE } from '../../lib/styleSourceChoice.js';export { BOARD_FOLLOW_UNIVERSE, BOARD_NONE };const rowsOf = (rows) => (Array.isArray(rows) ? rows : []);-/** Load the universes, their style tokens (keyed by id), and the mood boards once. */+const EMPTY_LISTS = { universes: [], universeStyles: {}, boards: [], loaded: false, error: null };++/**+ * Load the universes, their style tokens (keyed by id), and the mood boards.+ * `loaded` is true only after all three reads succeed; a failed read sets+ * `error` (with `retry`) instead, so the picker never reports "no mood boards"+ * for a list it could not read.+ */export function useStyleSourceLists() {- const [lists, setLists] = useState({ universes: [], universeStyles: {}, boards: [], loaded: false });+ const [lists, setLists] = useState(EMPTY_LISTS);+ const [attempt, setAttempt] = useState(0);useEffect(() => {let active = true;+ setLists(EMPTY_LISTS);Promise.all([- listUniverseNames({ silent: true }).catch(() => []),- listUniverseStyles({ silent: true }).catch(() => []),- listMoodBoardNames({ silent: true }).catch(() => []),+ listUniverseNames({ silent: true }),+ listUniverseStyles({ silent: true }),+ listMoodBoardNames({ silent: true }),]).then(([universes, styles, boards]) => {if (!active) return;setLists({@@ -23,11 +33,16 @@ export function useStyleSourceLists() {universeStyles: Object.fromEntries(rowsOf(styles).map((row) => [row.id, row])),boards: rowsOf(boards),loaded: true,+ error: null,});+ }).catch((error) => {+ if (!active) return;+ setLists({ ...EMPTY_LISTS, error: error instanceof Error ? error : new Error('Request failed') });});return () => { active = false; };- }, []);- return lists;+ }, [attempt]);+ const retry = useCallback(() => setAttempt((n) => n + 1), []);+ return { ...lists, retry };}/**@@ -39,7 +54,7 @@ export default function UniverseMoodBoardPicker({lists, universeId, moodBoardChoice, onUniverseChange, onBoardChoiceChange,idPrefix, labelClass, inputClass, universeLabel = 'Universe',}) {- const { universes, universeStyles, boards, loaded } = lists;+ const { universes, universeStyles, boards, loaded, error, retry } = lists;const activeStyle = universeId ? universeStyles[universeId] : null;const embrace = activeStyle?.influences?.embrace || [];const avoid = activeStyle?.influences?.avoid || [];@@ -51,6 +66,7 @@ export default function UniverseMoodBoardPicker({return (<>+ {error && <ListLoadError what="universes and mood boards" error={error} onRetry={retry} />}<div className="grid grid-cols-1 gap-3 sm:grid-cols-2"><div><label htmlFor={`${idPrefix}-universe`} className={labelClass}>{universeLabel}</label>diff --git a/client/src/components/media/UniverseMoodBoardPicker.test.jsx b/client/src/components/media/UniverseMoodBoardPicker.test.jsxnew file mode 100644index 0000000000..7423bc5f17--- /dev/null+++ b/client/src/components/media/UniverseMoodBoardPicker.test.jsx@@ -0,0 +1,61 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const listUniverseNames = vi.fn();+const listUniverseStyles = vi.fn();+const listMoodBoardNames = vi.fn();+vi.mock('../../services/api', () => ({+ listUniverseNames: (...a) => listUniverseNames(...a),+ listUniverseStyles: (...a) => listUniverseStyles(...a),+ listMoodBoardNames: (...a) => listMoodBoardNames(...a),+}));++import UniverseMoodBoardPicker, { useStyleSourceLists, BOARD_FOLLOW_UNIVERSE } from './UniverseMoodBoardPicker';++function Harness() {+ const lists = useStyleSourceLists();+ return (+ <MemoryRouter>+ <UniverseMoodBoardPicker+ lists={lists}+ universeId=""+ moodBoardChoice={BOARD_FOLLOW_UNIVERSE}+ onUniverseChange={() => {}}+ onBoardChoiceChange={() => {}}+ idPrefix="t"+ labelClass=""+ inputClass=""+ />+ </MemoryRouter>+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);+ listUniverseStyles.mockResolvedValue([]);+ listMoodBoardNames.mockResolvedValue([]);+});++describe('UniverseMoodBoardPicker', () => {+ it('shows "No mood boards yet" only for a list that loaded empty', async () => {+ render(<Harness />);+ await act(async () => {});+ expect(screen.getByText(/No mood boards yet/)).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('shows a load error with Retry — not "No mood boards yet" — when any list read fails', async () => {+ listMoodBoardNames.mockRejectedValueOnce(new Error('Server unavailable'));+ render(<Harness />);+ await act(async () => {});+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load universes and mood boards — Server unavailable');+ expect(screen.queryByText(/No mood boards yet/)).toBeNull();++ listMoodBoardNames.mockResolvedValueOnce([{ id: 'b1', name: 'Example Board' }]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('option', { name: 'Example Board' })).toBeInTheDocument();+ });+});diff --git a/client/src/components/music/AlbumsManager.jsx b/client/src/components/music/AlbumsManager.jsxindex 195d1ef33a..d66d49c316 100644--- a/client/src/components/music/AlbumsManager.jsx+++ b/client/src/components/music/AlbumsManager.jsx@@ -17,6 +17,7 @@ import toast from '../ui/Toast';import GalleryImagePicker from '../imageGen/GalleryImagePicker';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import Field from '../ui/FormField';+import ListLoadError from '../ui/ListLoadError';import useMediaJobProgress from '../../hooks/useMediaJobProgress';import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { formatTimecode } from '../../utils/formatters';@@ -68,6 +69,8 @@ export default function AlbumsManager() {const [albums, setAlbums] = useState([]);const [allTracks, setAllTracks] = useState([]);const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState(null);+ const [loadAttempt, setLoadAttempt] = useState(0);const [form, setForm] = useState(emptyForm);const [saving, setSaving] = useState(false);const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();@@ -83,17 +86,27 @@ export default function AlbumsManager() {const setCover = (url) => setForm((f) => ({ ...f, coverImageUrl: url }));const clearGeneration = () => { genRequestRef.current += 1; setGenJobId(null); setStartingGen(false); };+ // Albums and the track pool load together; either failing is an error with+ // Retry, never an empty list (and never a "not found" for the open album).useEffect(() => {+ let active = true;+ setLoading(true);+ setLoadError(null);Promise.all([- listAlbums().catch(() => []),- listTracks({ silent: true }).catch(() => []),+ listAlbums({ silent: true }),+ listTracks({ silent: true }),]).then(([albumList, trackList]) => {+ if (!active) return;setAlbums(Array.isArray(albumList) ? albumList : []);setAllTracks(Array.isArray(trackList) ? trackList : []);})- .finally(() => setLoading(false));- }, []);+ .catch((err) => {+ if (active) setLoadError(err instanceof Error ? err : new Error('Request failed'));+ })+ .finally(() => { if (active) setLoading(false); });+ return () => { active = false; };+ }, [loadAttempt]);useEffect(() => {if (!genJobId) return;@@ -112,7 +125,7 @@ export default function AlbumsManager() {() => (isCreate || !id ? null : albums.find((a) => a.id === id) || null),[albums, id, isCreate],);- const notFound = !isCreate && !!id && !loading && !selected;+ const notFound = !isCreate && !!id && !loading && !loadError && !selected;const tracksById = useMemo(() => new Map(allTracks.map((t) => [t.id, t])), [allTracks]);const canGenerate = !!(form.title.trim() || form.genre.trim() || form.description.trim());@@ -126,7 +139,7 @@ export default function AlbumsManager() {const hydratedRef = useRef(null);const selectionKey = id ?? null;useEffect(() => {- if (loading) return;+ if (loading || loadError) return;if (hydratedRef.current === selectionKey) return;hydratedRef.current = selectionKey;cancelDelete();@@ -134,7 +147,7 @@ export default function AlbumsManager() {setTrackPickerOpen(false);if (isCreate) setForm(emptyForm());else if (selected) setForm(formFromAlbum(selected));- }, [selectionKey, isCreate, selected, loading]);+ }, [selectionKey, isCreate, selected, loading, loadError]);const handleGenerateCover = async () => {if (isGenerating) return;@@ -251,6 +264,8 @@ export default function AlbumsManager() {<div className="bg-port-card border border-port-border rounded-lg p-2">{loading ? (<div className="text-sm p-2"><BrailleSpinner text="Loading…" /></div>+ ) : loadError ? (+ <ListLoadError what="albums" error={loadError} onRetry={() => setLoadAttempt((n) => n + 1)} />) : albums.length === 0 ? (<div className="text-gray-500 text-sm p-2">No albums yet.{' '}diff --git a/client/src/components/music/AlbumsManager.test.jsx b/client/src/components/music/AlbumsManager.test.jsxnew file mode 100644index 0000000000..65e69d24e0--- /dev/null+++ b/client/src/components/music/AlbumsManager.test.jsx@@ -0,0 +1,63 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter, Route, Routes } from 'react-router';++vi.mock('./ArtistPicker', () => ({ default: () => <div data-testid="artist-picker" /> }));+vi.mock('./AlbumTrackPicker', () => ({ default: () => <div data-testid="track-picker" /> }));+vi.mock('../imageGen/GalleryImagePicker', () => ({ default: () => null }));+vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../hooks/useMediaJobProgress', () => ({ default: () => ({ status: 'idle' }) }));++const listAlbums = vi.fn();+const listTracks = vi.fn();+vi.mock('../../services/api', async (importOriginal) => ({+ ...(await importOriginal()),+ listAlbums: (...a) => listAlbums(...a),+ listTracks: (...a) => listTracks(...a),+}));++import AlbumsManager from './AlbumsManager';++const ALBUM = { id: 'album-1', title: 'Example Album', trackIds: [] };++const renderAt = async (path) => {+ render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/music/albums/:id" element={<AlbumsManager />} />+ <Route path="/music/albums" element={<AlbumsManager />} />+ </Routes>+ </MemoryRouter>,+ );+ await act(async () => {});+};++beforeEach(() => {+ vi.clearAllMocks();+ listTracks.mockResolvedValue([]);+});+afterEach(cleanup);++describe('<AlbumsManager> failed load', () => {+ it('shows a load error with Retry instead of "No albums yet" or a "not found" album, then hydrates the open album', async () => {+ listAlbums.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderAt('/music/albums/album-1');+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load albums — Server unavailable');+ expect(screen.queryByText(/No albums yet/)).toBeNull();+ expect(screen.queryByText(/could not be found/)).toBeNull();++ listAlbums.mockResolvedValue([ALBUM]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByDisplayValue('Example Album')).toBeTruthy();+ });++ it('treats a failed track-pool read as a failed load too', async () => {+ listAlbums.mockResolvedValue([ALBUM]);+ listTracks.mockRejectedValueOnce(new Error('Tracks unavailable'));+ await renderAt('/music/albums');+ expect(screen.getByRole('alert')).toHaveTextContent('Tracks unavailable');+ });+});diff --git a/client/src/components/music/ChiptunePanel.jsx b/client/src/components/music/ChiptunePanel.jsxindex 96e6cf47f9..f04bf18c51 100644--- a/client/src/components/music/ChiptunePanel.jsx+++ b/client/src/components/music/ChiptunePanel.jsx@@ -13,6 +13,7 @@import { useEffect, useMemo, useRef, useState } from 'react';import { Loader2, Wand2, Play, Square, Disc3, Gamepad2 } from 'lucide-react';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import useProviderModels from '../../hooks/useProviderModels';import useMounted from '../../hooks/useMounted';@@ -42,6 +43,7 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix, sourcePrompconst [playing, setPlaying] = useState(false);const [publishOpen, setPublishOpen] = useState(false);const [apps, setApps] = useState([]);+ const [appsError, setAppsError] = useState(null);const [publishAppId, setPublishAppId] = useState('');const [publishSubdir, setPublishSubdir] = useState(DEFAULT_SUBDIR);const [publishSlug, setPublishSlug] = useState('');@@ -227,21 +229,30 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix, sourcePromp}};+ // A failed read leaves `apps` empty and sets `appsError`, so the panel shows+ // a Retry instead of the "no managed apps" copy it reserves for a real empty list.+ const loadPublishTargets = async () => {+ setAppsError(null);+ const list = await getApps({ silent: true }).catch((err) => {+ if (mountedRef.current) setAppsError(err instanceof Error ? err : new Error('Request failed'));+ return null;+ });+ if (!mountedRef.current || !list) return;+ // Publishable targets are managed apps with a repo on disk — PortOS+ // itself is excluded (its repo is not a game asset destination); the+ // server enforces the same policy.+ const publishable = (Array.isArray(list) ? list : []).filter((a) => a.repoPath && a.id !== 'portos-default' && !a.archived);+ setApps(publishable);+ // A remembered target that is no longer publishable (deleted/archived/+ // repo-less) would leave the select showing nothing while Publish sends+ // the stale id — clear it so the user picks a live target.+ setPublishAppId((id) => (id && !publishable.some((a) => a.id === id) ? '' : id));+ };+const openPublish = async () => {setPublishedFiles(null);- if (!publishOpen && apps.length === 0) {- const list = await getApps({ silent: true }).catch(() => []);- if (!mountedRef.current) return;- // Publishable targets are managed apps with a repo on disk — PortOS- // itself is excluded (its repo is not a game asset destination); the- // server enforces the same policy.- const publishable = (Array.isArray(list) ? list : []).filter((a) => a.repoPath && a.id !== 'portos-default' && !a.archived);- setApps(publishable);- // A remembered target that is no longer publishable (deleted/archived/- // repo-less) would leave the select showing nothing while Publish sends- // the stale id — clear it so the user picks a live target.- setPublishAppId((id) => (id && !publishable.some((a) => a.id === id) ? '' : id));- }+ if (!publishOpen && apps.length === 0) await loadPublishTargets();+ if (!mountedRef.current) return;setPublishOpen((o) => !o);};@@ -375,7 +386,9 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix, sourcePromp{publishOpen ? (<div className="space-y-2 border border-port-border rounded-lg p-2 bg-port-bg">- {apps.length === 0 ? (+ {appsError ? (+ <ListLoadError what="managed apps" error={appsError} onRetry={loadPublishTargets} />+ ) : apps.length === 0 ? (<p className="text-xs text-gray-500">No managed apps with a repo path — add the game app under Apps first.</p>) : (<>diff --git a/client/src/components/music/ChiptunePanel.test.jsx b/client/src/components/music/ChiptunePanel.test.jsxindex 4145747d3b..d503a3ca0f 100644--- a/client/src/components/music/ChiptunePanel.test.jsx+++ b/client/src/components/music/ChiptunePanel.test.jsx@@ -103,6 +103,19 @@ describe('ChiptunePanel', () => {expect(screen.getByRole('button', { name: /render take/i })).toBeDisabled();});+ it('shows a load error with Retry — not the "no managed apps" copy — when the publish targets cannot be read', async () => {+ api.getApps.mockRejectedValueOnce(new Error('Server unavailable'));+ render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);++ await act(async () => { fireEvent.click(await screen.findByRole('button', { name: /publish to app/i })); });+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load managed apps — Server unavailable');+ expect(screen.queryByText(/No managed apps with a repo path/)).toBeNull();++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(await screen.findByLabelText(/target app/i)).toBeInTheDocument();+ });+describe('stale publish-target guard', () => {it('clears a saved publish target that no longer appears in the fresh apps list', async () => {// The saved prefs point at an app that has since been deleted/archived —diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsxindex b7645e7c79..b44a86d4db 100644--- a/client/src/components/music/TracksManager.jsx+++ b/client/src/components/music/TracksManager.jsx@@ -21,6 +21,7 @@ import toast from '../ui/Toast';import FilePickerButton from '../ui/FilePickerButton';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import Field from '../ui/FormField';+import ListLoadError from '../ui/ListLoadError';import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { formatBytes, formatTimecode } from '../../utils/formatters';import { withUnlistedOption } from '../../lib/withUnlistedOption';@@ -71,6 +72,8 @@ export default function TracksManager() {const { id } = useParams();const [tracks, setTracks] = useState([]);const [loading, setLoading] = useState(true);+ const [loadError, setLoadError] = useState(null);+ const [loadAttempt, setLoadAttempt] = useState(0);const [form, setForm] = useState(emptyForm);const [saving, setSaving] = useState(false);const [openingDesigner, setOpeningDesigner] = useState(false);@@ -101,26 +104,37 @@ export default function TracksManager() {// with another track's result).const selectedIdRef = useRef(null);+ // Tracks, albums and MIDI sources seed the list, the album select and the+ // read-through together; any one failing is an error with Retry, never an+ // empty list (and never a "not found" for the open track).useEffect(() => {+ let active = true;+ setLoading(true);+ setLoadError(null);Promise.all([- listTracks({ silent: true }).catch((err) => { toast.error(err.message || 'Failed to load tracks'); return []; }),- listAlbums({ silent: true }).catch(() => []),- listMusicVideoMidiSources({ silent: true }).catch(() => []),+ listTracks({ silent: true }),+ listAlbums({ silent: true }),+ listMusicVideoMidiSources({ silent: true }),]).then(([trackList, albumList, mvList]) => {+ if (!active) return;setTracks(Array.isArray(trackList) ? trackList : []);setAlbums(Array.isArray(albumList) ? albumList : []);setMvProjects(Array.isArray(mvList) ? mvList : []);})- .finally(() => setLoading(false));- }, []);+ .catch((err) => {+ if (active) setLoadError(err instanceof Error ? err : new Error('Request failed'));+ })+ .finally(() => { if (active) setLoading(false); });+ return () => { active = false; };+ }, [loadAttempt]);const isCreate = id === 'new';const selected = useMemo(() => (isCreate || !id ? null : tracks.find((t) => t.id === id) || null),[tracks, id, isCreate],);- const notFound = !isCreate && !!id && !loading && !selected;+ const notFound = !isCreate && !!id && !loading && !loadError && !selected;// The persisted track (for gen metadata + the audio player, which need a saved id).const persisted = selected;@@ -156,7 +170,7 @@ export default function TracksManager() {const justCreatedIdRef = useRef(null);const selectionKey = id ?? null;useEffect(() => {- if (loading) return;+ if (loading || loadError) return;if (hydratedRef.current === selectionKey) return;hydratedRef.current = selectionKey;selectedIdRef.current = selectionKey;@@ -174,7 +188,7 @@ export default function TracksManager() {if (justCreatedIdRef.current === selectionKey) justCreatedIdRef.current = null;else setGenMode(initialGenMode(selected));}- }, [selectionKey, isCreate, selected, loading]);+ }, [selectionKey, isCreate, selected, loading, loadError]);const upsertLocal = (track) => {setTracks((prev) => {@@ -452,6 +466,8 @@ export default function TracksManager() {<div className="bg-port-card border border-port-border rounded-lg p-2">{loading ? (<div className="text-sm p-2"><BrailleSpinner text="Loading…" /></div>+ ) : loadError ? (+ <ListLoadError what="tracks" error={loadError} onRetry={() => setLoadAttempt((n) => n + 1)} />) : tracks.length === 0 ? (<div className="text-gray-500 text-sm p-2">No tracks yet.{' '}diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsxindex 320c22c885..9b1297e397 100644--- a/client/src/components/music/TracksManager.test.jsx+++ b/client/src/components/music/TracksManager.test.jsx@@ -103,6 +103,37 @@ describe('<TracksManager> MIDI transcription read-through', () => {});});+describe('<TracksManager> failed load', () => {+ beforeEach(() => {+ listAlbums.mockResolvedValue([]);+ listMusicVideoMidiSources.mockResolvedValue([]);+ });+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it('shows a load error with Retry instead of an empty list or a "not found" track, then hydrates the open track', async () => {+ listTracks.mockRejectedValueOnce(new Error('Server unavailable'));+ renderAt('track-1');+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load tracks — Server unavailable');+ expect(screen.queryByText('No tracks yet.')).toBeNull();+ expect(screen.queryByText(/could not be found/)).toBeNull();++ listTracks.mockResolvedValue([TRACK]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByDisplayValue('Example Song')).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('fails the whole load when a secondary read (albums) fails, rather than rendering an album-less editor', async () => {+ listTracks.mockResolvedValue([TRACK]);+ listAlbums.mockRejectedValueOnce(new Error('Albums unavailable'));+ renderAt('track-1');+ expect(await screen.findByRole('alert')).toHaveTextContent('Albums unavailable');+ });+});+// #3264: the generator toggle used to live INSIDE the `persisted ?` gate, so a// brand-new track rendered nothing at all where the generators belong and there// was no way to learn the two modes existed until after the first save.diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex e30f3749d8..c2771156ca 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -30,12 +30,14 @@ import { listImageModels } from '../../../services/apiImageVideo';import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import useSlotInFlight from '../../../hooks/useSlotInFlight';+import useListResource from '../../../hooks/useListResource';import MediaJobThumb from '../MediaJobThumb';import MediaPreview from '../../media/MediaPreview';import useHydratedPreviewRoute from '../../../hooks/useHydratedPreviewRoute';import { normalizeImage } from '../../media/normalize';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';+import ListLoadError from '../../ui/ListLoadError';import ExtractCanonButton from './ExtractCanonButton';import {applyRecordRenderPin, deriveAvailableBackends, IMAGE_GEN_MODE, renderTargetPin, RENDER_TARGET,@@ -168,6 +170,8 @@ function panelsToMarkdown(panels, pageNumber) {return lines.join('\n').trim();}+const fetchImageModels = () => listImageModels({ silent: true });+export default function ComicScriptStage({ issue, series, onStageUpdate, actionsGated = false }) {const script = issue.stages?.comicScript || { status: 'empty', output: '' };const comicPages = issue.stages?.comicPages || { status: 'empty', pages: [] };@@ -193,7 +197,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions// persist their choice to settings.pipeline.imageGen so it sticks across// page reloads.const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);- const [imageModels, setImageModels] = useState([]);+ const imageModelList = useListResource(fetchImageModels);const [sysSettings, setSysSettings] = useState(null);// Shared lightbox state. PageRow reports its rendered filename up via// `onFilenameKnown` so the parent can build a navigable items list keyed by@@ -250,18 +254,14 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actionsuseEffect(() => {let cancelled = false;- Promise.all([- // `null` on failure, NOT `{}` — a `{}` stand-in derives an empty backend- // list, which `renderPinLadder` reads as "loaded, nothing enabled" and- // uses to suppress every pin. A settings fetch that failed must not look- // like an install with no backends.- getSettings().catch(() => null),- listImageModels().catch(() => []),- ]).then(([s, modelList]) => {+ // `null` on failure, NOT `{}` — a `{}` stand-in derives an empty backend+ // list, which `renderPinLadder` reads as "loaded, nothing enabled" and+ // uses to suppress every pin. A settings fetch that failed must not look+ // like an install with no backends.+ getSettings().catch(() => null).then((s) => {if (cancelled) return;setSysSettings(s);setImageCfg(readPipelineImageSettings(s));- setImageModels(Array.isArray(modelList) ? modelList : []);});return () => { cancelled = true; };}, []);@@ -778,10 +778,13 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions) : null}<Drawer open={settingsOpen} onClose={closeImageSettings} title="Comic page image gen" size="md">+ {imageModelList.state === 'error' && (+ <ListLoadError className="mb-3" what="the local model catalog" error={imageModelList.error} onRetry={imageModelList.retry} />+ )}<ImageGenSettingsFormvalue={imageCfg}onChange={persistImageCfg}- models={imageModels}+ models={imageModelList.items}availableBackends={availableBackends}grouped/>diff --git a/client/src/components/pipeline/stages/ComicScriptStage.renderPin.test.jsx b/client/src/components/pipeline/stages/ComicScriptStage.renderPin.test.jsxindex 54e749d027..3988700ed4 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.renderPin.test.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.renderPin.test.jsx@@ -116,3 +116,21 @@ describe('ComicScriptStage — series render pin (#3840)', () => {expect(body.mode).toBe('codex');});});++describe('ComicScriptStage — image model catalog', () => {+ it('shows a catalog error with Retry in the settings drawer when the model read fails', async () => {+ getSettings.mockResolvedValue({ imageGen: CLOUD_ON });+ listImageModels.mockRejectedValueOnce(new Error('Models unavailable'));+ render(+ <MemoryRouter initialEntries={['/?settings=comic-image']}>+ <ComicScriptStage issue={issue} series={series} onStageUpdate={vi.fn()} />+ </MemoryRouter>,+ );++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the local model catalog — Models unavailable');++ listImageModels.mockResolvedValueOnce([{ id: 'model-a', name: 'Model A' }]);+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());+ });+});diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex f88d09266f..38dd390a27 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -35,6 +35,7 @@ import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';import { universeStylePreset } from '../../../lib/universeStylePreset';import { buildUniverseSectionRenderTag } from '../../../lib/universeRunTag';import useMounted from '../../../hooks/useMounted';+import useListResource from '../../../hooks/useListResource';import useUniverse from '../../../hooks/useUniverse';import { useCanonPatch } from '../../../hooks/useCanonPatch';import useHydratedPreviewRoute from '../../../hooks/useHydratedPreviewRoute';@@ -44,6 +45,7 @@ import MediaPreview from '../../media/MediaPreview';import { normalizeImage } from '../../media/normalize';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';+import ListLoadError from '../../ui/ListLoadError';import {applyRecordRenderPin, deriveAvailableBackends, renderTargetPin, RENDER_TARGET,} from '../../../lib/imageGenBackends';@@ -87,13 +89,15 @@ const KINDS = [},];+const fetchImageModels = () => listImageModels({ silent: true });+export default function NounsStage({ issue, series, onStageUpdate }) {const mountedRef = useMounted();const prose = (issue.stages?.prose?.output || '').trim();const proseReady = prose.length > 0;const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);- const [imageModels, setImageModels] = useState([]);+ const imageModelList = useListResource(fetchImageModels);const [sysSettings, setSysSettings] = useState(null);// Linked universe — reference renders inherit its stylePrompt + negativePrompt// so ref images stay visually coherent with the comic-page renderer. `setUniverse`@@ -166,18 +170,14 @@ export default function NounsStage({ issue, series, onStageUpdate }) {useEffect(() => {let cancelled = false;- Promise.all([- // `null` on failure, NOT `{}` — a `{}` stand-in derives an empty backend- // list, which `renderPinLadder` reads as "loaded, nothing enabled" and- // uses to suppress every pin. A settings fetch that failed must not look- // like an install with no backends.- getSettings().catch(() => null),- listImageModels().catch(() => []),- ]).then(([s, modelList]) => {+ // `null` on failure, NOT `{}` — a `{}` stand-in derives an empty backend+ // list, which `renderPinLadder` reads as "loaded, nothing enabled" and+ // uses to suppress every pin. A settings fetch that failed must not look+ // like an install with no backends.+ getSettings().catch(() => null).then((s) => {if (cancelled || !mountedRef.current) return;setSysSettings(s);setImageCfg(readPipelineImageSettings(s));- setImageModels(Array.isArray(modelList) ? modelList : []);});return () => { cancelled = true; };}, [mountedRef]);@@ -609,10 +609,13 @@ export default function NounsStage({ issue, series, onStageUpdate }) {))}<Drawer open={settingsOpen} onClose={closeSettings} title="Reference image gen" size="md">+ {imageModelList.state === 'error' && (+ <ListLoadError className="mb-3" what="the local model catalog" error={imageModelList.error} onRetry={imageModelList.retry} />+ )}<ImageGenSettingsFormvalue={imageCfg}onChange={persistImageCfg}- models={imageModels}+ models={imageModelList.items}availableBackends={availableBackends}grouped/>diff --git a/client/src/components/pipeline/stages/NounsStage.test.jsx b/client/src/components/pipeline/stages/NounsStage.test.jsxnew file mode 100644index 0000000000..3d71888010--- /dev/null+++ b/client/src/components/pipeline/stages/NounsStage.test.jsx@@ -0,0 +1,57 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++vi.mock('../../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),+}));+vi.mock('../../../services/apiUniverseBuilder', () => ({+ refineUniverseCharacter: vi.fn(),+ getUniverseSeriesNames: vi.fn(() => Promise.resolve([])),+}));+vi.mock('../../../services/apiPipeline', () => ({+ extractPipelineCanonFromScript: vi.fn(),+ describePipelineCanonFromProse: vi.fn(),+}));+vi.mock('../../../services/apiProviders', () => ({ getProviders: vi.fn(() => Promise.resolve({ providers: [] })) }));+vi.mock('../../../services/apiSystem', () => ({+ getSettings: vi.fn(),+ patchSettingsSlice: vi.fn(),+ generateImage: vi.fn(),+}));+vi.mock('../../../services/apiImageVideo', () => ({ listImageModels: vi.fn() }));+vi.mock('../../../hooks/useUniverse', () => ({+ default: () => [{ id: 'uni-1', name: 'Example Universe', characters: [], places: [], objects: [] }, vi.fn()],+}));+vi.mock('../../../hooks/useCanonPatch', () => ({ useCanonPatch: () => vi.fn() }));+vi.mock('../../media/MediaPreview', () => ({ default: () => null }));++import NounsStage from './NounsStage';+import { getSettings } from '../../../services/apiSystem';+import { listImageModels } from '../../../services/apiImageVideo';++const issue = { id: 'iss-1', seriesId: 'ser-1', stages: { prose: { output: 'Prose text.' } } };+const series = { id: 'ser-1', name: 'Example Series', universeId: 'uni-1' };++beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue({});+});++describe('NounsStage — image model catalog', () => {+ it('shows a catalog error with Retry in the settings drawer when the model read fails', async () => {+ listImageModels.mockRejectedValueOnce(new Error('Models unavailable'));+ render(+ <MemoryRouter initialEntries={['/?settings=noun-image']}>+ <NounsStage issue={issue} series={series} onStageUpdate={vi.fn()} />+ </MemoryRouter>,+ );++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the local model catalog — Models unavailable');++ listImageModels.mockResolvedValueOnce([{ id: 'model-a', name: 'Model A' }]);+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());+ });+});diff --git a/client/src/components/sprites/ImportPanel.jsx b/client/src/components/sprites/ImportPanel.jsxindex 7e227f3068..f9cff2604b 100644--- a/client/src/components/sprites/ImportPanel.jsx+++ b/client/src/components/sprites/ImportPanel.jsx@@ -5,32 +5,31 @@* it can refresh the library (and the open detail).*/-import { useEffect, useState } from 'react';+import { useState } from 'react';import { Download, X, RefreshCw } from 'lucide-react';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import Modal from '../ui/Modal.jsx';import AppContextPicker from '../AppContextPicker.jsx';import { importSprites } from '../../services/apiSprites.js';import { getApps } from '../../services/apiApps.js';import { pluralize } from '../../lib/textUtils';+import useListResource from '../../hooks/useListResource';++// Sprite sources are managed apps (we import/sync from an app's checkout), so+// the picker is the source of truth for the path — no free-text root. Archived+// apps and apps with no repoPath can't be a source.+const fetchSourceApps = () => getApps({ silent: true })+ .then((list) => (list || []).filter((a) => a.repoPath && !a.archived));export default function ImportPanel({ onImported }) {const [open, setOpen] = useState(false);- const [apps, setApps] = useState([]);const [appId, setAppId] = useState('');const [includeProps, setIncludeProps] = useState(true);const [importing, setImporting] = useState(false);const [importErrors, setImportErrors] = useState([]);- // Sprite sources are managed apps (we import/sync from an app's checkout),- // so the picker is the source of truth for the path — no free-text root.- // Archived apps and apps with no repoPath can't be a source.- useEffect(() => {- if (!open) return;- getApps({ silent: true })- .then((list) => setApps((list || []).filter((a) => a.repoPath && !a.archived)))- .catch(() => setApps([]));- }, [open]);+ const { items: apps, state: appsState, error: appsError, retry: retryApps } = useListResource(fetchSourceApps, { enabled: open });const sourceRoot = apps.find((a) => a.id === appId)?.repoPath || '';@@ -76,6 +75,7 @@ export default function ImportPanel({ onImported }) {Pick the managed app holding the sprite pipeline (expects <code>art-pipeline/characters/</code> and/or <code>game/assets/sprites/</code>in its repo). Only approved/final assets import — reference candidates and raw run intermediates stay behind.</p>+ {appsState === 'error' && <ListLoadError what="managed apps" error={appsError} onRetry={retryApps} />}<AppContextPickerapps={apps}value={appId}diff --git a/client/src/components/sprites/ImportPanel.test.jsx b/client/src/components/sprites/ImportPanel.test.jsxnew file mode 100644index 0000000000..55c8f72b7b--- /dev/null+++ b/client/src/components/sprites/ImportPanel.test.jsx@@ -0,0 +1,35 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../services/apiSprites.js', () => ({ importSprites: vi.fn() }));+const getApps = vi.fn();+vi.mock('../../services/apiApps.js', () => ({ getApps: (...a) => getApps(...a) }));++import ImportPanel from './ImportPanel';++const openPanel = async () => {+ render(<ImportPanel onImported={() => {}} />);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Import/ })); });+};++beforeEach(() => vi.clearAllMocks());++describe('ImportPanel source apps', () => {+ it('shows a load error with Retry when the app list cannot be read, then recovers', async () => {+ getApps.mockRejectedValueOnce(new Error('Server unavailable'));+ await openPanel();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load managed apps — Server unavailable');++ getApps.mockResolvedValueOnce([+ { id: 'game', name: 'Example Game', repoPath: '/repos/example-game' },+ { id: 'archived', name: 'Old Game', repoPath: '/repos/old', archived: true },+ ]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('option', { name: /Example Game/ })).toBeInTheDocument();+ expect(screen.queryByRole('option', { name: /Old Game/ })).toBeNull();+ });+});diff --git a/client/src/components/writers-room/AnalysisHistory.jsx b/client/src/components/writers-room/AnalysisHistory.jsxindex 01bebb3534..c4fea88ca8 100644--- a/client/src/components/writers-room/AnalysisHistory.jsx+++ b/client/src/components/writers-room/AnalysisHistory.jsx@@ -1,9 +1,11 @@-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { AlertTriangle, Check, Clapperboard, FileSignature, MapPin, RotateCcw, Sparkles, Users } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import { listWritersRoomAnalyses, getWritersRoomAnalysis } from '../../services/apiWritersRoom';import { timeAgo, formatCount } from '../../utils/formatters';+import useListResource from '../../hooks/useListResource';import useMounted from '../../hooks/useMounted';// Icon + label maps must include every kind from `ANALYSIS_KINDS`. Adding a@@ -22,25 +24,18 @@ const SEVERITY_COLOR = {// `onApplyFormat` is the only mutation hook — Format-pass results call it// with the cleaned text and the caller decides what to do with it.export default function AnalysisHistory({ work, activeHash, onApplyFormat }) {- const [analyses, setAnalyses] = useState([]);- const [loading, setLoading] = useState(false);+ const fetchAnalyses = useCallback(() => listWritersRoomAnalyses(work.id, { silent: true }), [work.id]);+ const {+ items: analyses, state, error, retry: refresh,+ } = useListResource(fetchAnalyses);+ const loading = state === 'loading';const [details, setDetails] = useState({});const [expanded, setExpanded] = useState(null);const mountedRef = useMounted();- const refresh = async () => {- setLoading(true);- const list = await listWritersRoomAnalyses(work.id).catch(() => []);- if (!mountedRef.current) return;- setLoading(false);- setAnalyses(list);- };-useEffect(() => {- setAnalyses([]);setExpanded(null);setDetails({});- refresh();}, [work.id]);const expand = async (analysis) => {@@ -70,7 +65,8 @@ export default function AnalysisHistory({ work, activeHash, onApplyFormat }) {<RotateCcw size={12} className={loading ? 'animate-spin' : ''} /></button></div>- {analyses.length === 0 && !loading && (+ {state === 'error' && <ListLoadError what="analyses" error={error} onRetry={refresh} />}+ {state === 'ready' && analyses.length === 0 && (<div className="text-gray-500 italic">No analyses yet — run one from the work menu.</div>)}<ul className="space-y-1.5">diff --git a/client/src/components/writers-room/AnalysisHistory.test.jsx b/client/src/components/writers-room/AnalysisHistory.test.jsxnew file mode 100644index 0000000000..58ec95ba98--- /dev/null+++ b/client/src/components/writers-room/AnalysisHistory.test.jsx@@ -0,0 +1,44 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));++const listWritersRoomAnalyses = vi.fn();+vi.mock('../../services/apiWritersRoom', () => ({+ listWritersRoomAnalyses: (...a) => listWritersRoomAnalyses(...a),+ getWritersRoomAnalysis: vi.fn(),+}));++import AnalysisHistory from './AnalysisHistory';++const renderHistory = async () => {+ render(<AnalysisHistory work={{ id: 'work-1' }} activeHash="h1" onApplyFormat={() => {}} />);+ await act(async () => {});+};++beforeEach(() => vi.clearAllMocks());++describe('AnalysisHistory', () => {+ it('shows the empty copy only for a list that loaded empty', async () => {+ listWritersRoomAnalyses.mockResolvedValue([]);+ await renderHistory();+ expect(screen.getByText(/No analyses yet/)).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('shows a load error with Retry — not "No analyses yet" — when the read fails', async () => {+ listWritersRoomAnalyses.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderHistory();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load analyses — Server unavailable');+ expect(screen.queryByText(/No analyses yet/)).toBeNull();++ listWritersRoomAnalyses.mockResolvedValueOnce([+ { id: 'a1', kind: 'evaluate', status: 'succeeded', createdAt: '2026-01-01T00:00:00Z' },+ ]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByText('Evaluate')).toBeInTheDocument();+ });+});diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsxindex dafccde269..ac540f3cf3 100644--- a/client/src/components/writers-room/ExercisePanel.jsx+++ b/client/src/components/writers-room/ExercisePanel.jsx@@ -1,5 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Timer, Play, StopCircle, X, FilePlus } from 'lucide-react';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import {listWritersRoomExercises,@@ -11,6 +12,7 @@ import {import { formatCount, formatCountdown } from '../../utils/formatters';import { countWords } from '../../lib/textUtils';import { FormField } from '../ui/FormField';+import useListResource from '../../hooks/useListResource';import useMounted from '../../hooks/useMounted';const DURATION_PRESETS = [@@ -21,7 +23,6 @@ const DURATION_PRESETS = [];export default function ExercisePanel({ activeWork, onClose, editorDirty = false, onWorkChange, draftMutation = null, beginDraftMutation, endDraftMutation }) {- const [history, setHistory] = useState([]);const [duration, setDuration] = useState(600);const [prompt, setPrompt] = useState('');const [active, setActive] = useState(null); // { id, startedAt, durationSeconds, startingWords }@@ -36,18 +37,13 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = falseconst ownerKeyRef = useRef(ownerKey);ownerKeyRef.current = ownerKey;- const refresh = useCallback(async () => {- // Capture the workId we asked for so a slow response from the previous- // work can't overwrite the just-loaded history when the user switches- // works rapidly.- const requestedFor = activeWork?.id ?? null;- const all = await listWritersRoomExercises(requestedFor).catch(() => []);- if (!mountedRef.current) return;- if (requestedFor !== (activeWork?.id ?? null)) return; // stale response- setHistory(all);- }, [activeWork?.id]);-- useEffect(() => { refresh(); }, [refresh]);+ // `useListResource` drops a response from a superseded work, so a slow+ // answer for the previous work can't overwrite the just-loaded history.+ const workId = activeWork?.id ?? null;+ const fetchHistory = useCallback(() => listWritersRoomExercises(workId, { silent: true }), [workId]);+ const {+ items: history, state: historyState, error: historyError, retry: refresh,+ } = useListResource(fetchHistory);// 1Hz tick while a session is runninguseEffect(() => {@@ -229,7 +225,8 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = false<div className="border-t border-port-border bg-port-bg/40 px-3 py-2 max-h-40 overflow-y-auto"><h4 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Recent sessions</h4>- {history.length === 0 && <p className="text-[11px] text-gray-600">No sessions yet</p>}+ {historyState === 'error' && <ListLoadError what="sessions" error={historyError} onRetry={refresh} />}+ {historyState === 'ready' && history.length === 0 && <p className="text-[11px] text-gray-600">No sessions yet</p>}<ul className="space-y-1">{history.slice(0, 8).map((ex) => (<li key={ex.id} className="text-[11px] flex items-center gap-2">diff --git a/client/src/components/writers-room/ExercisePanel.test.jsx b/client/src/components/writers-room/ExercisePanel.test.jsxindex 461c392dd3..04157426b7 100644--- a/client/src/components/writers-room/ExercisePanel.test.jsx+++ b/client/src/components/writers-room/ExercisePanel.test.jsx@@ -104,4 +104,16 @@ describe('ExercisePanel promote-to-draft button (#5300)', () => {expect(onWorkChange).not.toHaveBeenCalled();expect(toast.error).toHaveBeenCalledWith('Could not add to draft: Exercise already promoted');});++ it('shows a load error with Retry — not "No sessions yet" — when the history read fails', async () => {+ listWritersRoomExercises.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderPanel();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load sessions — Server unavailable');+ expect(screen.queryByText('No sessions yet')).toBeNull();++ listWritersRoomExercises.mockResolvedValueOnce([exercise({ id: 'wr-ex-2', status: 'discarded' })]);+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.queryByText('No sessions yet')).toBeNull();+ });});diff --git a/client/src/components/writers-room/PolishPanel.jsx b/client/src/components/writers-room/PolishPanel.jsxindex 01ebcd52e8..a4d7d204a6 100644--- a/client/src/components/writers-room/PolishPanel.jsx+++ b/client/src/components/writers-room/PolishPanel.jsx@@ -1,6 +1,8 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { Sparkles, StopCircle, RotateCcw, Check, X, ArrowRight, Loader2 } from 'lucide-react';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';+import useListResource from '../../hooks/useListResource';import useMounted from '../../hooks/useMounted';import { useSseProgress, isTerminalSseFrame } from '../../hooks/useSseProgress';import { timeAgo, formatCount } from '../../utils/formatters';@@ -38,7 +40,6 @@ export default function PolishPanel({ work, dirty, blocked = false, onBusyChangeconst [cycles, setCycles] = useState(1);const [sseUrl, setSseUrl] = useState(null);const [starting, setStarting] = useState(false);- const [snapshots, setSnapshots] = useState([]);const [reverting, setReverting] = useState(null);const { frames, latest, closed } = useSseProgress(sseUrl, { enabled: !!sseUrl });@@ -48,23 +49,21 @@ export default function PolishPanel({ work, dirty, blocked = false, onBusyChangereturn () => onBusyChange?.(false);}, [starting, running, reverting, onBusyChange]);- const refreshSnapshots = useCallback(async () => {- const list = await listWritersRoomPolishSnapshots(work.id).catch(() => []);- if (mountedRef.current) setSnapshots(list);- }, [work.id, mountedRef]);+ const fetchSnapshots = useCallback(() => listWritersRoomPolishSnapshots(work.id, { silent: true }), [work.id]);+ const {+ items: snapshots, state: snapshotsState, error: snapshotsError, retry: refreshSnapshots,+ } = useListResource(fetchSnapshots);// On mount / work switch: reset stream state and load existing snapshots. If a// run is already active on the server (e.g. this panel was reopened), re-attach.useEffect(() => {let live = true;setSseUrl(null);- setSnapshots([]);- refreshSnapshots();getWritersRoomPolishStatus(work.id).then((s) => { if (s?.active && live && mountedRef.current) setSseUrl(`/api/writers-room/works/${encodeURIComponent(work.id)}/polish/progress`); }).catch(() => {});return () => { live = false; };- }, [work.id, refreshSnapshots, mountedRef]);+ }, [work.id, mountedRef]);// When the stream closes on a terminal frame, refresh snapshots and pull the// server-mutated body back into the editor.@@ -227,7 +226,10 @@ export default function PolishPanel({ work, dirty, blocked = false, onBusyChange<div className="text-[11px] uppercase tracking-wide text-gray-500 mb-1.5">Snapshots {snapshots.length > 0 && <span className="text-gray-600">({snapshots.length})</span>}</div>- {snapshots.length === 0 && (+ {snapshotsState === 'error' && (+ <ListLoadError what="snapshots" error={snapshotsError} onRetry={refreshSnapshots} />+ )}+ {snapshotsState === 'ready' && snapshots.length === 0 && (<div className="text-[11px] text-gray-500 italic">No snapshots yet — run a polish cycle to create revert points.</div>)}<ul className="space-y-1">diff --git a/client/src/components/writers-room/PolishPanel.test.jsx b/client/src/components/writers-room/PolishPanel.test.jsxindex a497a3d451..931121fa9c 100644--- a/client/src/components/writers-room/PolishPanel.test.jsx+++ b/client/src/components/writers-room/PolishPanel.test.jsx@@ -66,3 +66,18 @@ it('blocks server body mutations during a draft transition and reports pending rexpect(busy).toHaveBeenLastCalledWith(false);expect(revert).toBeEnabled();});++it('shows a load error with Retry — not the empty-snapshots copy — when the snapshot read fails', async () => {+ getWritersRoomPolishStatus.mockResolvedValue({ active: false });+ listWritersRoomPolishSnapshots.mockRejectedValueOnce(new Error('Server unavailable'));+ render(<PolishPanel work={{ id: 'work-1' }} dirty={false} />);+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load snapshots — Server unavailable');+ expect(screen.queryByText(/No snapshots yet/)).toBeNull();++ listWritersRoomPolishSnapshots.mockResolvedValueOnce([+ { id: 'snap-1', cycle: 1, label: 'Cycle 1', wordCount: 1200, createdAt: new Date().toISOString() },+ ]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('button', { name: /revert/i })).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+});diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex b4b0716fb4..659e187417 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -4,6 +4,7 @@ import {Clapperboard, Loader2, Users, MapPin as MapPinIcon,ListTree, SlidersHorizontal, Package,} from 'lucide-react';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';import {listWritersRoomAnalyses,@@ -12,6 +13,7 @@ import {import { getSettings, patchSettingsSlice, listImageStylePresets } from '../../services/apiSystem';import { listImageModels } from '../../services/apiImageVideo';import { deriveAvailableBackends } from '../../lib/imageGenBackends';+import useListResource from '../../hooks/useListResource';import useMounted from '../../hooks/useMounted';import Drawer from '../Drawer';import TabPills from '../ui/TabPills';@@ -43,6 +45,9 @@ const RUN_LABEL = {format: 'Format pass',};+const fetchImageModels = () => listImageModels({ silent: true });+const fetchStylePresets = () => listImageStylePresets({ silent: true });+// Memoized (#3387): this is a heavy sibling of the WorkEditor prose textarea// with no dependency on the body text, so a per-keystroke `setBody` in the// parent would otherwise re-render the whole storyboard tree. The memo boundary@@ -105,8 +110,11 @@ function StoryboardPanel({const [latestFailure, setLatestFailure] = useState(null);const [loading, setLoading] = useState(false);const [imageCfg, setImageCfg] = useState(WR_IMAGE_DEFAULTS);- const [models, setModels] = useState([]);- const [stylePresets, setStylePresets] = useState([]);+ const modelList = useListResource(fetchImageModels);+ const presetList = useListResource(fetchStylePresets);+ const models = modelList.items;+ const stylePresets = presetList.items;+ const [loadError, setLoadError] = useState(null);const [sysSettings, setSysSettings] = useState(null);const mountedRef = useMounted();// All three backends emit started/progress/completed via imageGenEvents →@@ -135,15 +143,9 @@ function StoryboardPanel({useEffect(() => {let cancelled = false;- Promise.all([- getSettings().catch(() => ({})),- listImageModels().catch(() => []),- listImageStylePresets().catch(() => []),- ]).then(([s, modelList, presets]) => {+ getSettings().catch(() => ({})).then((s) => {if (cancelled) return;applyFreshSettings(s);- setModels(Array.isArray(modelList) ? modelList : []);- setStylePresets(Array.isArray(presets) ? presets : []);});return () => { cancelled = true; };}, [applyFreshSettings]);@@ -161,8 +163,18 @@ function StoryboardPanel({const loadLatestScript = useCallback(async () => {setLoading(true);- const list = await listWritersRoomAnalyses(work.id).catch(() => []);- if (!mountedRef.current) return;+ setLoadError(null);+ // A failed read is an error with Retry — never the "no storyboard yet" an+ // empty list would render.+ const failed = (err) => {+ if (mountedRef.current) {+ setLoadError(err instanceof Error ? err : new Error('Request failed'));+ setLoading(false);+ }+ return null;+ };+ const list = await listWritersRoomAnalyses(work.id, { silent: true }).catch(failed);+ if (!list || !mountedRef.current) return;// listAnalyses is sorted createdAt desc, so the first match per status is// also the most-recent one. Track failures only when newer than the latest// success — a stale failure under a newer success is just history.@@ -178,8 +190,8 @@ function StoryboardPanel({return;}// listAnalyses returns metadata only — fetch the full snapshot for scenes + sceneImages.- const full = await getWritersRoomAnalysis(work.id, latestSucceeded.id).catch(() => null);- if (!mountedRef.current) return;+ const full = await getWritersRoomAnalysis(work.id, latestSucceeded.id, { silent: true }).catch(failed);+ if (!full || !mountedRef.current) return;setLatestScript(full);setLoading(false);}, [work.id]);@@ -299,6 +311,17 @@ function StoryboardPanel({return () => registerSceneImageMerge(null);}, [registerSceneImageMerge]);+ const catalogErrors = (+ <>+ {modelList.state === 'error' && (+ <ListLoadError className="mx-3 mt-3" what="the local model catalog" error={modelList.error} onRetry={modelList.retry} />+ )}+ {presetList.state === 'error' && (+ <ListLoadError className="mx-3 mt-3" what="style presets" error={presetList.error} onRetry={presetList.retry} />+ )}+ </>+ );+return (<div className="flex flex-col h-full"><TabPills@@ -377,7 +400,11 @@ function StoryboardPanel({{tab === TAB.SCENES && (<StoryboardScenesTab activeDraft={activeDraft} onJumpToScene={onJumpToScene} />)}- {tab === TAB.BOARDS && (+ {tab === TAB.BOARDS && catalogErrors}+ {tab === TAB.BOARDS && loadError && (+ <ListLoadError className="mx-3 mt-3" what="the storyboard" error={loadError} onRetry={loadLatestScript} />+ )}+ {tab === TAB.BOARDS && !(loadError && !latestScript) && (<StoryboardBoardsTabwork={work}scenes={scenes}@@ -411,6 +438,7 @@ function StoryboardPanel({dirty={dirty}/>)}+ {tab === TAB.CONFIG && catalogErrors}{tab === TAB.CONFIG && (<StoryboardConfigTabimageCfg={imageCfg}diff --git a/client/src/components/writers-room/StoryboardPanel.test.jsx b/client/src/components/writers-room/StoryboardPanel.test.jsxnew file mode 100644index 0000000000..e13ee24d55--- /dev/null+++ b/client/src/components/writers-room/StoryboardPanel.test.jsx@@ -0,0 +1,84 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),+}));+vi.mock('../Drawer', () => ({ default: () => null }));+vi.mock('../settings/ImageGenTab', () => ({ ImageGenTab: () => null }));+vi.mock('./StoryboardBibleTab', () => ({ default: () => null }));+vi.mock('./StoryboardScenesTab', () => ({ default: () => null }));+vi.mock('./StoryboardBoardsTab', () => ({+ default: ({ scenes }) => <div data-testid="boards-tab">{scenes.length} scenes</div>,+}));+vi.mock('./StoryboardConfigTab', () => ({+ default: ({ models }) => <div data-testid="config-tab">{models.length} models</div>,+}));++const listWritersRoomAnalyses = vi.fn();+const getWritersRoomAnalysis = vi.fn();+vi.mock('../../services/apiWritersRoom', () => ({+ listWritersRoomAnalyses: (...a) => listWritersRoomAnalyses(...a),+ getWritersRoomAnalysis: (...a) => getWritersRoomAnalysis(...a),+}));+const getSettings = vi.fn();+const listImageStylePresets = vi.fn();+vi.mock('../../services/apiSystem', () => ({+ getSettings: (...a) => getSettings(...a),+ patchSettingsSlice: vi.fn(),+ listImageStylePresets: (...a) => listImageStylePresets(...a),+}));+const listImageModels = vi.fn();+vi.mock('../../services/apiImageVideo', () => ({ listImageModels: (...a) => listImageModels(...a) }));++import StoryboardPanel, { STORYBOARD_TAB } from './StoryboardPanel';++const work = { id: 'work-1', drafts: [], activeDraftVersionId: null };++const renderPanel = async (tab) => {+ render(+ <MemoryRouter>+ <StoryboardPanel work={work} tab={tab} onTabChange={() => {}} />+ </MemoryRouter>,+ );+ await act(async () => {});+};++beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue({});+ listImageModels.mockResolvedValue([]);+ listImageStylePresets.mockResolvedValue([]);+ listWritersRoomAnalyses.mockResolvedValue([]);+});+afterEach(cleanup);++describe('StoryboardPanel failed reads', () => {+ it('shows a storyboard load error with Retry instead of the empty boards view, then loads the script', async () => {+ listWritersRoomAnalyses.mockRejectedValueOnce(new Error('Server unavailable'));+ await renderPanel(STORYBOARD_TAB.BOARDS);+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load the storyboard — Server unavailable');+ expect(screen.queryByTestId('boards-tab')).toBeNull();++ listWritersRoomAnalyses.mockResolvedValueOnce([{ id: 'a1', kind: 'script', status: 'succeeded', createdAt: '2026-01-01T00:00:00Z' }]);+ getWritersRoomAnalysis.mockResolvedValueOnce({ id: 'a1', kind: 'script', result: { scenes: [{ id: 's1' }] } });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByTestId('boards-tab')).toHaveTextContent('1 scenes');+ });++ it('shows a catalog error with Retry on the config tab when the model or preset read fails', async () => {+ listImageModels.mockRejectedValueOnce(new Error('Models unavailable'));+ listImageStylePresets.mockRejectedValueOnce(new Error('Presets unavailable'));+ await renderPanel(STORYBOARD_TAB.CONFIG);+ const alerts = screen.getAllByRole('alert');+ expect(alerts[0]).toHaveTextContent('Could not load the local model catalog — Models unavailable');+ expect(alerts[1]).toHaveTextContent('Could not load style presets — Presets unavailable');++ listImageModels.mockResolvedValueOnce([{ id: 'model-a', name: 'Model A' }]);+ await act(async () => { fireEvent.click(screen.getAllByRole('button', { name: 'Retry' })[0]); });+ expect(screen.getByTestId('config-tab')).toHaveTextContent('1 models');+ expect(screen.getAllByRole('alert')).toHaveLength(1);+ });+});diff --git a/client/src/listFetchConventions.test.js b/client/src/listFetchConventions.test.jsindex bc4de60812..29d541f55f 100644--- a/client/src/listFetchConventions.test.js+++ b/client/src/listFetchConventions.test.js@@ -76,9 +76,6 @@ const KNOWN = Object.freeze({'src/components/digital-twin/tabs/TasteTab.jsx': 2,'src/components/digital-twin/tabs/TestTab.jsx': 4,'src/components/digital-twin/tabs/TimeCapsuleTab.jsx': 1,- 'src/components/fableloom/LoomProductionPanel.jsx': 1,- 'src/components/fableloom/LoomSettingsDrawer.jsx': 1,- 'src/components/loraTraining/CaptionModelPicker.jsx': 1,'src/components/meatspace/EpigeneticTracker.jsx': 1,'src/components/meatspace/HealthCategorySection.jsx': 1,'src/components/meatspace/post/PostSessionLauncher.jsx': 2,@@ -86,22 +83,9 @@ const KNOWN = Object.freeze({'src/components/meatspace/tabs/AlcoholTab.jsx': 1,'src/components/meatspace/tabs/NicotineTab.jsx': 1,'src/components/meatspace/tabs/PostTab.jsx': 1,- 'src/components/media/UniverseMoodBoardPicker.jsx': 3,'src/components/messages/DraftsTab.jsx': 1,'src/components/messages/IMessageTab.jsx': 1,- 'src/components/music/AlbumsManager.jsx': 2,- 'src/components/music/ChiptunePanel.jsx': 1,- 'src/components/music/TracksManager.jsx': 2,- 'src/components/pipeline/stages/ComicScriptStage.jsx': 1,- 'src/components/pipeline/stages/NounsStage.jsx': 1,'src/components/privacy/PrivacyOrgsTab.jsx': 2,- 'src/components/sprites/ImportPanel.jsx': 1,- 'src/components/writers-room/AnalysisHistory.jsx': 1,- 'src/components/writers-room/ExercisePanel.jsx': 1,- 'src/components/writers-room/PolishPanel.jsx': 1,- 'src/components/writers-room/StoryboardPanel.jsx': 3,- 'src/pages/PipelineEditorialChecks.jsx': 1,- 'src/pages/PipelineManuscriptEditor.jsx': 1,'src/pages/Tribe.jsx': 2,});diff --git a/client/src/pages/PipelineEditorialChecks.catalogError.test.jsx b/client/src/pages/PipelineEditorialChecks.catalogError.test.jsxnew file mode 100644index 0000000000..f10509157a--- /dev/null+++ b/client/src/pages/PipelineEditorialChecks.catalogError.test.jsx@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import PipelineEditorialChecks from './PipelineEditorialChecks';++// A failed catalog read must surface as an error with Retry, never the+// "No editorial checks are registered" copy reserved for a real empty catalog.++const listPipelineSeries = vi.fn();+const getEditorialChecks = vi.fn();+const getPipelineManuscriptReview = vi.fn();+const getEditorialHealth = vi.fn();+const getEditorialChecksRunStatus = vi.fn();+const patchEditorialCheck = vi.fn();++vi.mock('../services/api', () => ({+ listPipelineSeries: (...a) => listPipelineSeries(...a),+ updatePipelineSeries: vi.fn(),+ getEditorialChecks: (...a) => getEditorialChecks(...a),+ patchEditorialCheck: (...a) => patchEditorialCheck(...a),+ createEditorialCustomCheck: vi.fn(),+ updateEditorialCustomCheck: vi.fn(),+ deleteEditorialCustomCheck: vi.fn(),+ previewEditorialCustomCheck: vi.fn(),+ startEditorialChecksRun: vi.fn(),+ cancelEditorialChecksRun: vi.fn(),+ getEditorialChecksRunStatus: (...a) => getEditorialChecksRunStatus(...a),+ editorialChecksRunSseUrl: () => '',+ getPipelineManuscriptReview: (...a) => getPipelineManuscriptReview(...a),+ getEditorialHealth: (...a) => getEditorialHealth(...a),+ setEditorialReadinessGate: vi.fn(),+ // Touched transitively by the triage → ManuscriptCommentCard tree.+ acceptPipelineManuscriptFix: vi.fn(),+ patchPipelineManuscriptComment: vi.fn(),+ undoPipelineManuscriptFix: vi.fn(),+ generatePipelineManuscriptFix: vi.fn(),+}));++vi.mock('../hooks/usePipelineProgress', () => ({+ usePipelineProgress: () => ({ latest: null, closed: true }),+}));+vi.mock('../hooks/useProviderModels', () => ({+ default: () => ({+ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],+ setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn(),+ }),+}));++// Keep the catalog cards + provider selector out of the way; the triage and health+// panel are the surfaces under test, so they stay REAL.+vi.mock('../components/pipeline/editorial/EditorialCheckCard', () => ({ default: () => <div>check-card</div> }));+vi.mock('../components/pipeline/editorial/EditorialCustomCheckForm', () => ({ default: () => <div>custom-form</div> }));+vi.mock('../components/ProviderModelSelector', () => ({ default: () => <div>provider-selector</div> }));++const CHECK = { id: 'naming.dissimilar-names', label: 'Character name dissimilarity', scope: 'series', kind: 'deterministic', enabled: true };++function renderPage() {+ return render(+ <MemoryRouter initialEntries={[`/pipeline/editorial-checks`]}>+ <PipelineEditorialChecks />+ </MemoryRouter>,+ );+}++describe('PipelineEditorialChecks — failed catalog read', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ listPipelineSeries.mockResolvedValue([{ id: 'ser-1', title: 'My Series' }]);+ getPipelineManuscriptReview.mockResolvedValue({ comments: [] });+ getEditorialChecksRunStatus.mockResolvedValue({ active: false });+ getEditorialHealth.mockResolvedValue(null);+ });++ it('shows a load error with Retry instead of "No editorial checks are registered", then loads the catalog', async () => {+ getEditorialChecks.mockRejectedValueOnce(new Error('Server unavailable'));+ renderPage();+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the editorial check catalog — Server unavailable');+ expect(screen.queryByText(/No editorial checks are registered/)).toBeNull();++ getEditorialChecks.mockResolvedValueOnce({ checks: [CHECK] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('check-card')).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsxindex 7647faa9a3..2e0d88423a 100644--- a/client/src/pages/PipelineEditorialChecks.jsx+++ b/client/src/pages/PipelineEditorialChecks.jsx@@ -49,6 +49,8 @@ export default function PipelineEditorialChecks() {const [searchParams, setSearchParams] = useSearchParams();const [checks, setChecks] = useState([]);const [loadingCatalog, setLoadingCatalog] = useState(true);+ const [catalogError, setCatalogError] = useState(null);+ const [catalogAttempt, setCatalogAttempt] = useState(0);const [savingIds, setSavingIds] = useState(() => new Set());const [selectedIds, setSelectedIds] = useState(() => new Set());// Checks the user muted from the triage this session (#1602, lifted here for@@ -164,13 +166,19 @@ export default function PipelineEditorialChecks() {// ---- Load the global catalog + series list once. ----useEffect(() => {let canceled = false;- getEditorialChecks().catch(() => ({ checks: [] })).then((catalog) => {- if (canceled) return;- setChecks(Array.isArray(catalog?.checks) ? catalog.checks : []);- setLoadingCatalog(false);- });+ setLoadingCatalog(true);+ setCatalogError(null);+ getEditorialChecks({ silent: true })+ .then((catalog) => {+ if (canceled) return;+ setChecks(Array.isArray(catalog?.checks) ? catalog.checks : []);+ })+ .catch((err) => {+ if (!canceled) setCatalogError(err instanceof Error ? err : new Error('Request failed'));+ })+ .finally(() => { if (!canceled) setLoadingCatalog(false); });return () => { canceled = true; };- }, []);+ }, [catalogAttempt]);// ---- Load findings + re-attach to an in-flight run when the series changes. ----// Tracks the currently-selected series so a slow findings fetch for a series@@ -729,6 +737,8 @@ export default function PipelineEditorialChecks() {{loadingCatalog ? (<p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading checks…</p>+ ) : catalogError ? (+ <ListLoadError what="the editorial check catalog" error={catalogError} onRetry={() => setCatalogAttempt((n) => n + 1)} />) : (<div className="space-y-4">{/* Below `lg` the two columns stack — this switch picks which onediff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsxindex 8fb1a2b110..31dae3dbf6 100644--- a/client/src/pages/PipelineManuscriptEditor.jsx+++ b/client/src/pages/PipelineManuscriptEditor.jsx@@ -34,6 +34,7 @@ import {} from 'lucide-react';import { formatManuscript } from '../lib/manuscriptFormat';import toast from '../components/ui/Toast';+import ListLoadError from '../components/ui/ListLoadError';import PageSkeleton from '../components/ui/PageSkeleton';import UnsavedChangesConfirm from '../components/ui/UnsavedChangesConfirm';import { useAsyncAction } from '../hooks/useAsyncAction';@@ -113,6 +114,9 @@ function SeriesManuscriptEditor() {const [pinnedPrimary, setPinnedPrimary] = useState(null);const [availableTypes, setAvailableTypes] = useState([]);const [comments, setComments] = useState([]);+ // Set when the editorial-review read failed, so the empty comment index is+ // not mistaken for "no findings"; cleared by any successful review read.+ const [reviewError, setReviewError] = useState(null);const [reviewMeta, setReviewMeta] = useState(null);const [freshReview, setFreshReview] = useState(false);// "Generate edits for every finding" — pre-builds each comment's fix during the@@ -221,7 +225,7 @@ function SeriesManuscriptEditor() {Promise.all([getPipelineSeries(seriesId, { silent: true }),getPipelineManuscript(seriesId, undefined, { silent: true }),- getPipelineManuscriptReview(seriesId).catch(() => ({ comments: [] })),+ getPipelineManuscriptReview(seriesId, { silent: true }).catch((err) => ({ loadFailed: err })),]).then(([s, manuscript, review]) => {if (canceled) return;@@ -233,6 +237,7 @@ function SeriesManuscriptEditor() {setPinnedPrimary(manuscript?.pinnedPrimary || null);setAvailableTypes(Array.isArray(manuscript?.availableTypes) ? manuscript.availableTypes : []);setComments(Array.isArray(review?.comments) ? review.comments : []);+ setReviewError(review?.loadFailed || null);}).catch((err) => {if (canceled) return;@@ -349,6 +354,7 @@ function SeriesManuscriptEditor() {if (!ownsView()) return;const next = Array.isArray(review?.comments) ? review.comments : [];setComments(next);+ setReviewError(null);if (meta) setReviewMeta({ chunked: !!meta.chunked, chunkCount: meta.chunkCount || 1 });if (recovered) {toast('Editorial review stream ended — refreshed notes from the server');@@ -361,6 +367,16 @@ function SeriesManuscriptEditor() {}).catch((err) => { if (ownsView()) toast.error(err.message || 'Failed to load review'); });+ const retryReview = () => {+ setReviewError(null);+ getPipelineManuscriptReview(seriesId, { silent: true })+ .then((review) => {+ if (!ownsView()) return;+ setComments(Array.isArray(review?.comments) ? review.comments : []);+ })+ .catch((err) => { if (ownsView()) setReviewError(err instanceof Error ? err : new Error('Request failed')); });+ };+// Terminal-frame handler for the streamed run: refresh comments + toast, then// tear the subscription down. Per-chunk frames only drive the button label.// Gate on `reviewClosed` (not just the frame type): `useSseProgress` resets@@ -965,6 +981,10 @@ function SeriesManuscriptEditor() {</div></header>+ {reviewError && (+ <ListLoadError what="editorial notes" error={reviewError} onRetry={retryReview} />+ )}+{sections.length === 0 ? (<p className="text-sm text-gray-500 italic">No drafted manuscript yet — write a comic script, prose, or teleplay on at least one issue, then run “Finish the draft” from the series arc.diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsxindex 62d15d556e..6aa6c219b9 100644--- a/client/src/pages/PipelineManuscriptEditor.test.jsx+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx@@ -71,6 +71,20 @@ beforeEach(() => {] });});+describe('PipelineManuscriptEditor — failed editorial-review read', () => {+ it('shows a load error with Retry — not an empty comment index — and still opens the manuscript', async () => {+ api.getPipelineManuscriptReview.mockRejectedValueOnce(new Error('Server unavailable'));+ renderEditor();+ expect(await screen.findByText('My Series')).toBeInTheDocument();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load editorial notes — Server unavailable');+ expect(screen.getByDisplayValue('The hero walked in. She left.')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('The ending is abrupt')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});+describe('PipelineManuscriptEditor', () => {it('renders the manuscript section and an open editorial comment in the index', async () => {renderEditor();diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 1df54fde2e..07fcea091b 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -479,9 +479,9 @@ export const generateImage = (data, options = {}) => request('/image-gen/generat// promise and reuse it for the lifetime of the page. Eliminates the repeat// fetch when the user navigates ImageGen → VideoGen → Writers Room.let stylePresetsPromise = null;-export const listImageStylePresets = () => {+export const listImageStylePresets = (options = {}) => {if (!stylePresetsPromise) {- stylePresetsPromise = request('/image-gen/style-presets').catch((err) => {+ stylePresetsPromise = request('/image-gen/style-presets', options).catch((err) => {stylePresetsPromise = null;throw err;});diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsindex 6832a8cce4..341cb128b5 100644--- a/client/src/services/apiWritersRoom.js+++ b/client/src/services/apiWritersRoom.js@@ -64,8 +64,8 @@ export const setWritersRoomActiveDraft = (id, draftId, options = {}) => request(});// Analysis (AI passes — evaluate / format / script)-export const listWritersRoomAnalyses = (workId) =>- request(`/writers-room/works/${enc(workId)}/analysis`);+export const listWritersRoomAnalyses = (workId, options = {}) =>+ request(`/writers-room/works/${enc(workId)}/analysis`, options);export const runWritersRoomAnalysis = (workId, data, options = {}) =>request(`/writers-room/works/${enc(workId)}/analysis`, {method: 'POST',@@ -89,8 +89,8 @@ export const cancelWritersRoomPolish = (workId) =>request(`/writers-room/works/${enc(workId)}/polish/cancel`, { method: 'POST' });export const getWritersRoomPolishStatus = (workId) =>request(`/writers-room/works/${enc(workId)}/polish/status`);-export const listWritersRoomPolishSnapshots = (workId) =>- request(`/writers-room/works/${enc(workId)}/polish/snapshots`);+export const listWritersRoomPolishSnapshots = (workId, options = {}) =>+ request(`/writers-room/works/${enc(workId)}/polish/snapshots`, options);export const revertWritersRoomPolishSnapshot = (workId, snapshotId, options = {}) =>request(`/writers-room/works/${enc(workId)}/polish/revert`, {method: 'POST',@@ -245,9 +245,9 @@ export const deleteWritersRoomObject = (workId, objectId, options = {}) =>});// Exercises-export const listWritersRoomExercises = (workId) => {+export const listWritersRoomExercises = (workId, options = {}) => {const qs = workId ? `?workId=${enc(workId)}` : '';- return request(`/writers-room/exercises${qs}`);+ return request(`/writers-room/exercises${qs}`, options);};export const createWritersRoomExercise = (data, options = {}) => request('/writers-room/exercises', {method: 'POST',