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 28 list reads fail (#12804)
[._.]/ Adam Eivy1e86ed1914ca
diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsxindex ad53689c65..5ce7f3f5e1 100644--- a/client/src/components/CmdKSearch.jsx+++ b/client/src/components/CmdKSearch.jsx@@ -82,6 +82,8 @@ export default function CmdKSearch() {const { isFeatureEnabled } = useInstanceFeatures();const [searchResults, setSearchResults] = useState([]);const [catalogResults, setCatalogResults] = useState([]);+ // A failed catalog lookup must not read as "No results" for the query.+ const [catalogFailed, setCatalogFailed] = useState(false);const [loading, setLoading] = useState(false);const [focusedIndex, setFocusedIndex] = useState(0);const [expandedSources, setExpandedSources] = useState(new Set());@@ -201,6 +203,7 @@ export default function CmdKSearch() {}, [query]);useEffect(() => {+ setCatalogFailed(false);if (query.length < 2) {setCatalogResults([]);return;@@ -209,7 +212,11 @@ export default function CmdKSearch() {const timer = setTimeout(() => {listCatalogIngredients({ q: query, limit: 5, silent: true }).then((data) => { if (!cancelled) setCatalogResults(data?.items ?? []); })- .catch(() => { if (!cancelled) setCatalogResults([]); });+ .catch(() => {+ if (cancelled) return;+ setCatalogResults([]);+ setCatalogFailed(true);+ });}, 300);return () => { cancelled = true; clearTimeout(timer); };}, [query]);@@ -607,6 +614,9 @@ export default function CmdKSearch() {No results for “{query}”</div>)}+ {catalogFailed && (+ <div role="alert" className="px-4 py-2 text-center text-xs text-port-error">Catalog search failed, so catalog matches may be missing.</div>+ )}{!loading && !query && combined.commandCount === 0 && (<div className="text-center text-sm text-gray-600 py-8">diff --git a/client/src/components/CmdKSearch.test.jsx b/client/src/components/CmdKSearch.test.jsxindex b41a59d16a..729f44346b 100644--- a/client/src/components/CmdKSearch.test.jsx+++ b/client/src/components/CmdKSearch.test.jsx@@ -10,6 +10,7 @@ const getPaletteManifest = vi.fn();const getInstanceFeatures = vi.fn();const getDashboardLayouts = vi.fn();const search = vi.fn(() => Promise.resolve({ sources: [] }));+const listCatalogIngredients = vi.fn(() => Promise.resolve({ items: [] }));const runPaletteAction = vi.fn(() => Promise.resolve({ ok: true }));const toast = vi.hoisted(() => {const mock = vi.fn();@@ -25,7 +26,7 @@ vi.mock('../services/api', () => ({runPaletteAction: (...args) => runPaletteAction(...args),getDashboardLayouts: (...args) => getDashboardLayouts(...args),setActiveDashboardLayout: vi.fn(() => Promise.resolve()),- listCatalogIngredients: vi.fn(() => Promise.resolve({ items: [] })),+ listCatalogIngredients: (...args) => listCatalogIngredients(...args),}));vi.mock('./ui/Toast', () => ({ default: toast }));@@ -61,6 +62,8 @@ beforeEach(() => {getDashboardLayouts.mockResolvedValue({ layouts: [] });search.mockReset();search.mockResolvedValue({ sources: [] });+ listCatalogIngredients.mockReset();+ listCatalogIngredients.mockResolvedValue({ items: [] });runPaletteAction.mockReset();runPaletteAction.mockResolvedValue({ ok: true });toast.mockReset();@@ -555,3 +558,29 @@ describe('CmdKSearch global search staleness', () => {vi.useRealTimers();});});++describe('CmdKSearch catalog lookup failure', () => {+ it('says catalog matches may be missing instead of a bare "No results", and clears on the next query', async () => {+ vi.useFakeTimers();+ listCatalogIngredients.mockRejectedValueOnce(new Error('catalog down'));+ render(+ <MemoryRouter initialEntries={['/current']}>+ <CmdKSearch />+ </MemoryRouter>,+ );+ await act(async () => { fireEvent.keyDown(document, { key: 'k', metaKey: true }); });+ const input = screen.getByPlaceholderText(/Go to page/);++ await act(async () => { fireEvent.change(input, { target: { value: 'zzzz' } }); });+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ expect(screen.getByRole('alert')).toHaveTextContent(/catalog search failed/i);++ await act(async () => { fireEvent.change(input, { target: { value: 'zzzzy' } }); });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByText(/No results for/)).toBeInTheDocument();++ vi.useRealTimers();+ });+});diff --git a/client/src/components/apps/LaunchVideoPanel.jsx b/client/src/components/apps/LaunchVideoPanel.jsxindex a7ec6851cd..016c085dbd 100644--- a/client/src/components/apps/LaunchVideoPanel.jsx+++ b/client/src/components/apps/LaunchVideoPanel.jsx@@ -5,8 +5,10 @@ import Drawer from '../Drawer';import ProviderModelSelector from '../ProviderModelSelector';import FilmStylePicker from '../codeAnimation/FilmStylePicker';import FilePickerButton from '../ui/FilePickerButton';+import ListLoadError from '../ui/ListLoadError';import GalleryImagePicker from '../imageGen/GalleryImagePicker';import GalleryVideoPicker from '../videoGen/GalleryVideoPicker';+import useListResource from '../../hooks/useListResource';import useRunWithPicker from '../../hooks/useRunWithPicker';import { useAsyncAction } from '../../hooks/useAsyncAction';import useUrlParams from '../../hooks/useUrlParams';@@ -19,6 +21,7 @@ import { trackAudioUrl } from '../../services/apiTracks';import { formatBytes, formatDateTime, formatDurationSec, formatLoudness } from '../../utils/formatters';import toast from '../ui/Toast';+const fetchSkillPacks = () => getMotionToolkit({ silent: true }).then(result => result.skillPacks);const inputClass = 'w-full rounded border border-port-border bg-port-bg p-2 text-port-text';const buttonClass = 'rounded bg-port-accent px-3 py-2 text-white disabled:opacity-50';const videoUrl = video => `/data/videos/${encodeURIComponent(video.filename)}`;@@ -56,7 +59,7 @@ function LaunchVideoForm({ appId, onQueued }) {const [motionBlur, setMotionBlur] = useState('');const [motionSkills, setMotionSkills] = useState(false);const [installingSkills, setInstallingSkills] = useState(false);- const [skillPacks, setSkillPacks] = useState(null);+ const { items: skillPacks, state: skillPacksState, error: skillPacksError, retry: retrySkillPacks, setItems: setSkillPacks } = useListResource(fetchSkillPacks);const [music, setMusic] = useState(false);const [generateMusic, setGenerateMusic] = useState(false);const [musicMethod, setMusicMethod] = useState('agent');@@ -79,12 +82,9 @@ function LaunchVideoForm({ appId, onQueued }) {listPipelineMusicLibrary({ silent: true }).then(result => {if (active) setTracks(result.tracks);}).catch(err => { if (active) { setTracks([]); setError(err.message); } });- getMotionToolkit({ silent: true }).then(result => {- if (active) setSkillPacks(result.skillPacks);- }).catch(() => { if (active) setSkillPacks([]); });return () => { active = false; };}, []);- const installedSkills = (skillPacks ?? []).filter(pack => pack.found.length);+ const installedSkills = skillPacks.filter(pack => pack.found.length);const consultSkills = motionSkills && installedSkills.length > 0;const handleInstallSkills = async () => {@@ -203,10 +203,12 @@ function LaunchVideoForm({ appId, onQueued }) {</div><div><label htmlFor="launch-motion-skills"><input id="launch-motion-skills" type="checkbox" disabled={!installedSkills.length} checked={consultSkills} onChange={event => setMotionSkills(event.target.checked)} /> Consult motion skills</label>- <p className="text-sm text-port-text-muted">{skillPacks === null ? 'Checking installed skills…' : installedSkills.length- ? `Technique guides from ${installedSkills.map(pack => pack.label).join(', ')}.`- : 'HyperFrames, Remotion and Claude Animation skills are not installed.'}</p>- {skillPacks !== null && skillPacks.some(pack => !pack.installed) && (+ {skillPacksState === 'error'+ ? <ListLoadError what="installed motion skills" error={skillPacksError} onRetry={retrySkillPacks} />+ : <p className="text-sm text-port-text-muted">{skillPacksState === 'loading' ? 'Checking installed skills…' : installedSkills.length+ ? `Technique guides from ${installedSkills.map(pack => pack.label).join(', ')}.`+ : 'HyperFrames, Remotion and Claude Animation skills are not installed.'}</p>}+ {skillPacksState === 'ready' && skillPacks.some(pack => !pack.installed) && (<button type="button" className="btn btn-secondary" disabled={installingSkills} onClick={handleInstallSkills}>{installingSkills ? 'Installing motion skills…' : installedSkills.length ? 'Install missing motion skills' : 'Install and enable motion skills'}</button>diff --git a/client/src/components/apps/LaunchVideoPanel.test.jsx b/client/src/components/apps/LaunchVideoPanel.test.jsxindex b407678a44..c320bfd80d 100644--- a/client/src/components/apps/LaunchVideoPanel.test.jsx+++ b/client/src/components/apps/LaunchVideoPanel.test.jsx@@ -64,6 +64,20 @@ describe('launch video drawer', () => {expect(installMotionSkills).toHaveBeenCalledWith({ silent: true });});+ it('reports a failed motion-toolkit read with Retry instead of "skills are not installed"', async () => {+ getMotionToolkit.mockRejectedValueOnce(new Error('toolkit unreachable'));+ getMotionToolkit.mockResolvedValueOnce({ ffmpeg: true, skillPacks: [{ id: 'hyperframes', label: 'HyperFrames', found: ['motion-graphics'], installed: true }] });+ renderPanel('/?launchVideo=true');++ expect(await screen.findByRole('alert')).toHaveTextContent(/could not load installed motion skills.*toolkit unreachable/i);+ expect(screen.queryByText(/skills are not installed/i)).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Technique guides from HyperFrames.')).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ expect(getMotionToolkit).toHaveBeenCalledTimes(2);+ });+it.each(['agent', 'service'])('queues %s music without requiring a library track or installed engine', async musicMethod => {createAppLaunchVideo.mockReset().mockResolvedValue({ taskId: 'task-generated' });getMotionToolkit.mockResolvedValueOnce({ ffmpeg: true, skillPacks: [{ id: 'hyperframes', label: 'HyperFrames', found: ['motion-graphics'] }] });diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsxindex ac121086e6..b2d885831a 100644--- a/client/src/components/apps/tabs/OverviewTab.jsx+++ b/client/src/components/apps/tabs/OverviewTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router';import { FolderOpen, Gamepad2, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Download, Tag, AlertTriangle, Rocket, Camera, Image, Sparkles, Trash2, Smartphone, Clapperboard, X, Loader2 } from 'lucide-react';import toast from '../../ui/Toast';@@ -8,6 +8,8 @@ import { PORTOS_APP_ID } from '../../../lib/appIdentity.js';import ActivityLog from '../ActivityLog';import SlashDoPanel from '../SlashDoPanel';import Banner from '../../ui/Banner';+import ListLoadError from '../../ui/ListLoadError';+import useListResource from '../../../hooks/useListResource';import { safeReadStorage, safeWriteStorage } from '../../../lib/safeStorage';import { useAppOperation } from '../../../hooks/useAppOperation';import * as api from '../../../services/api';@@ -27,8 +29,6 @@ export default function OverviewTab({ app, onRefresh }) {const [deleting, setDeleting] = useState(false);const [installingScripts, setInstallingScripts] = useState(false);const [detectingIcon, setDetectingIcon] = useState(false);- // Reverse lookup (#2991): sprite records that publish assets into this app.- const [spriteBindings, setSpriteBindings] = useState([]);const onComplete = useMemo(() => () => onRefresh(), [onRefresh]);// Scoped to this app: the shared hook otherwise reports whichever operation@@ -37,15 +37,15 @@ export default function OverviewTab({ app, onRefresh }) {const updating = isOperating && operationType === 'update';const standardizing = isOperating && operationType === 'standardize';- // Load the sprite records bound to this app (empty for an app with none).- useEffect(() => {- if (!app?.id) return;- let cancelled = false;- api.getAppSpriteBindings(app.id)- .then((res) => { if (!cancelled) setSpriteBindings(res?.bindings || []); })- .catch(() => { if (!cancelled) setSpriteBindings([]); });- return () => { cancelled = true; };- }, [app?.id]);+ // Reverse lookup (#2991): sprite records that publish assets into this app.+ const appId = app?.id;+ const fetchSpriteBindings = useCallback(+ () => api.getAppSpriteBindings(appId).then((res) => res?.bindings || []),+ [appId],+ );+ const {+ items: spriteBindings, state: spriteBindingsState, error: spriteBindingsError, retry: retrySpriteBindings,+ } = useListResource(fetchSpriteBindings, { enabled: Boolean(appId) });const handleUpdate = () => startUpdate(app.id, app.name);@@ -313,8 +313,11 @@ export default function OverviewTab({ app, onRefresh }) {)}{/* Sprite assets PortOS publishes into this app (reverse lookup, #2991).- Shown only when at least one sprite record is bound — makes "PortOS is+ Shown only when at least one sprite record is bound (or the read failed) — makes "PortOS isthe creative source for this app" visible from the app side. */}+ {spriteBindingsState === 'error' && (+ <ListLoadError what="published sprite assets" error={spriteBindingsError} onRetry={retrySpriteBindings} />+ )}{spriteBindings.length > 0 && (<div><div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Published Sprite Assets</div>diff --git a/client/src/components/apps/tabs/OverviewTab.test.jsx b/client/src/components/apps/tabs/OverviewTab.test.jsxindex 3774f8edfc..ff2ea3ee1c 100644--- a/client/src/components/apps/tabs/OverviewTab.test.jsx+++ b/client/src/components/apps/tabs/OverviewTab.test.jsx@@ -96,6 +96,25 @@ describe('OverviewTab PortOS registration removal', () => {});});+describe('OverviewTab sprite bindings', () => {+ beforeEach(() => vi.clearAllMocks());++ it('shows a load error with Retry when the bindings read fails, then the assets after retry', async () => {+ api.getAppSpriteBindings.mockRejectedValueOnce(new Error('bindings unavailable'));+ api.getAppSpriteBindings.mockResolvedValueOnce({ bindings: [{ recordId: 'sprite-1', name: 'Example Sprite', kind: 'character' }] });+ const user = userEvent.setup();+ renderOverview();++ expect(await screen.findByRole('alert')).toHaveTextContent(/could not load published sprite assets.*bindings unavailable/i);+ expect(screen.queryByText('Published Sprite Assets')).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('link', { name: 'Example Sprite' })).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ expect(api.getAppSpriteBindings).toHaveBeenCalledTimes(2);+ });+});+describe('OverviewTab native app actions', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/client/src/components/cos/tabs/MemoryRunsUsedBy.jsx b/client/src/components/cos/tabs/MemoryRunsUsedBy.jsxindex 2b1cbfcd33..033c128b0f 100644--- a/client/src/components/cos/tabs/MemoryRunsUsedBy.jsx+++ b/client/src/components/cos/tabs/MemoryRunsUsedBy.jsx@@ -1,25 +1,23 @@-import { useState, useEffect } from 'react';+import { useCallback } from 'react';import { Link } from 'react-router';import * as api from '../../../services/api';import { formatDateTime } from '../../../utils/formatters';+import useListResource from '../../../hooks/useListResource';+import ListLoadError from '../../ui/ListLoadError';/*** "Used by recent runs" — agent runs whose prompt included this memory, from a* bounded scan of recent run records (GET /api/memory/:id/runs, #10495).*/export default function MemoryRunsUsedBy({ memoryId }) {- const [runs, setRuns] = useState(null);-- useEffect(() => {- let active = true;- setRuns(null);- api.getMemoryRuns(memoryId, { silent: true })- .then(res => { if (active) setRuns(res?.runs || []); })- .catch(() => { if (active) setRuns([]); });- return () => { active = false; };- }, [memoryId]);+ const fetchRuns = useCallback(+ () => api.getMemoryRuns(memoryId, { silent: true }).then(res => res?.runs || []),+ [memoryId],+ );+ const { items: runs, state, error, retry } = useListResource(fetchRuns);- if (!runs || runs.length === 0) return null;+ if (state === 'error') return <ListLoadError what="recent runs that used this memory" error={error} onRetry={retry} />;+ if (runs.length === 0) return null;return (<div><span className="block text-sm text-gray-400 mb-2">Used by recent runs</span>diff --git a/client/src/components/cos/tabs/MemoryRunsUsedBy.test.jsx b/client/src/components/cos/tabs/MemoryRunsUsedBy.test.jsxnew file mode 100644index 0000000000..0249f5b846--- /dev/null+++ b/client/src/components/cos/tabs/MemoryRunsUsedBy.test.jsx@@ -0,0 +1,36 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({ getMemoryRuns: vi.fn() }));+vi.mock('../../../services/api', () => api);++import MemoryRunsUsedBy from './MemoryRunsUsedBy';++const renderPanel = () => render(<MemoryRouter><MemoryRunsUsedBy memoryId="mem-1" /></MemoryRouter>);++describe('MemoryRunsUsedBy', () => {+ beforeEach(() => vi.clearAllMocks());++ it('renders nothing for a memory no run has used', async () => {+ api.getMemoryRuns.mockResolvedValue({ runs: [] });+ const { container } = renderPanel();+ await act(async () => {});+ expect(api.getMemoryRuns).toHaveBeenCalledTimes(1);+ expect(container).toBeEmptyDOMElement();+ });++ it('shows a load error with Retry instead of hiding the section, and recovers on retry', async () => {+ api.getMemoryRuns.mockRejectedValueOnce(new Error('runs unavailable'));+ api.getMemoryRuns.mockResolvedValueOnce({ runs: [{ runId: 'run-12345678', agentId: 'agent-abcdef12' }] });+ renderPanel();++ expect(await screen.findByRole('alert')).toHaveTextContent(/could not load recent runs.*runs unavailable/i);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByText('Used by recent runs')).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'agent-ab' })).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(api.getMemoryRuns).toHaveBeenCalledTimes(2);+ });+});diff --git a/client/src/components/eidoverse/EidoverseTravel.jsx b/client/src/components/eidoverse/EidoverseTravel.jsxindex 252b07a998..ad4e50560b 100644--- a/client/src/components/eidoverse/EidoverseTravel.jsx+++ b/client/src/components/eidoverse/EidoverseTravel.jsx@@ -3,6 +3,7 @@ import { useSocketSubscription } from '../../hooks/useSocketSubscription';import { useVisibilityEvent } from '../../hooks/useVisibilityEvent';import socket from '../../services/socket';import useMounted from '../../hooks/useMounted';+import ListLoadError from '../ui/ListLoadError';import { departEidoverse, getEidoverseDestinations } from '../../services/api';export default function EidoverseTravel({ travelRef, enabled, objects = [], onDestinationsChange, beforeDeparture }) {@@ -12,6 +13,9 @@ export default function EidoverseTravel({ travelRef, enabled, objects = [], onDeconst watching = enabled && visible;const [pending, setPending] = useState(null);const [error, setError] = useState('');+ // A failed read keeps the last known destinations: it is not evidence that none exist,+ // and clearing them would also fire onDestinationsChange for a world rebuild.+ const [loadError, setLoadError] = useState(null);const generation = useRef(0);const lastDestinations = useRef(null);const busy = useRef(false);@@ -24,6 +28,7 @@ export default function EidoverseTravel({ travelRef, enabled, objects = [], onDeconst applyDestinations = useCallback((result) => {if (!Array.isArray(result?.destinations)) return;setDestinations(result.destinations);+ setLoadError(null);const fingerprint = JSON.stringify(result.destinations.map((entry) => entry.peerId).sort());if (lastDestinations.current === null) lastDestinations.current = fingerprint;}, []);@@ -43,8 +48,8 @@ export default function EidoverseTravel({ travelRef, enabled, objects = [], onDeawait getEidoverseDestinations({ silent: true }).then((result) => {if (!mounted.current || generation.current !== current || sequence !== fetchSequence.current) return;applyDestinations(result);- }).catch(() => {- if (mounted.current && generation.current === current && sequence === fetchSequence.current) setDestinations([]);+ }).catch((failure) => {+ if (mounted.current && generation.current === current && sequence === fetchSequence.current) setLoadError(failure);});}, [mounted, applyDestinations]);useEffect(() => {@@ -85,7 +90,7 @@ export default function EidoverseTravel({ travelRef, enabled, objects = [], onDetravelRef.current = depart;return () => { travelRef.current = null; };}, [depart, travelRef]);- if (!enabled || (!destinations.length && !error)) return null;+ if (!enabled || (!destinations.length && !error && !loadError)) return null;return <div className="flex flex-wrap items-center gap-2 border-b border-port-border px-4 py-2 text-sm">{Boolean(destinations.length) && (<span className="text-gray-400">Federation Terminal · Use a pod in-world or choose a destination</span>@@ -95,6 +100,7 @@ export default function EidoverseTravel({ travelRef, enabled, objects = [], onDe{pending === destination.peerId ? 'Opening guest visit…' : destination.label}<span className="ml-2 text-xs text-gray-400">{objects.find((object) => object.travelPeerId === destination.peerId)?.name}</span></button>)}+ {loadError && <ListLoadError what="travel destinations" error={loadError} onRetry={refresh} />}{error && <p role="alert" className="text-red-400">{error}</p>}</div>;}diff --git a/client/src/components/eidoverse/EidoverseTravel.test.jsx b/client/src/components/eidoverse/EidoverseTravel.test.jsxindex 4d68d9d3b0..235db5a81d 100644--- a/client/src/components/eidoverse/EidoverseTravel.test.jsx+++ b/client/src/components/eidoverse/EidoverseTravel.test.jsx@@ -138,3 +138,29 @@ it('retries a deferred world update when the parent becomes ready without anotheexpect(ready).toHaveBeenCalledTimes(1);expect(getEidoverseDestinations).toHaveBeenCalledTimes(1);});++it('reports a failed destinations read with Retry and keeps the last known destinations', async () => {+ const changed = vi.fn();+ render(<EidoverseTravel enabled travelRef={createRef()} onDestinationsChange={changed} />);+ await screen.findByRole('button', { name: 'Example world' });+ getEidoverseDestinations.mockRejectedValueOnce(new Error('destinations unavailable'));+ await act(async () => socket.receive('connect'));++ expect(await screen.findByRole('alert')).toHaveTextContent(/could not load travel destinations.*destinations unavailable/i);+ expect(screen.getByRole('button', { name: 'Example world' })).toBeInTheDocument();+ expect(changed).not.toHaveBeenCalled();++ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Example world' })).toBeInTheDocument();+ expect(getEidoverseDestinations).toHaveBeenCalledTimes(3);+});++it('shows the load error when the first destinations read fails, not an empty strip', async () => {+ getEidoverseDestinations.mockRejectedValueOnce(new Error('destinations unavailable'));+ render(<EidoverseTravel enabled travelRef={createRef()} />);+ expect(await screen.findByRole('alert')).toHaveTextContent(/destinations unavailable/);+ expect(screen.queryByRole('button', { name: 'Example world' })).not.toBeInTheDocument();+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });+ expect(screen.getByRole('button', { name: 'Example world' })).toBeInTheDocument();+});diff --git a/client/src/components/media/RigPanel.jsx b/client/src/components/media/RigPanel.jsxindex 6bf1385109..e48662237a 100644--- a/client/src/components/media/RigPanel.jsx+++ b/client/src/components/media/RigPanel.jsx@@ -6,6 +6,11 @@ import useMounted from '../../hooks/useMounted';import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';import { formatBytes, formatCount, formatPercent } from '../../utils/formatters';import toast from '../ui/Toast';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';++// Module-level so the hook's fetcher identity is stable across renders.+const fetchClips = () => listRiggingClips({ silent: true }).then((value) => value?.clips || []);/*** "Rig this character" plus the rig-status panel on `/3d/:id`.@@ -27,9 +32,6 @@ export default function RigPanel({ record, onRecordChange }) {const enabled = isFeatureEnabled('rigging');const [readiness, setReadiness] = useState(null);const [busy, setBusy] = useState(false);- // Retarget lane (#6065). `clips === null` means "not fetched yet", distinct from- // an empty roster — the empty state gets an explaining line, not a dead picker.- const [clips, setClips] = useState(null);const [selectedClip, setSelectedClip] = useState('');const [retargeting, setRetargeting] = useState(false);@@ -44,17 +46,11 @@ export default function RigPanel({ record, onRecordChange }) {return () => { active = false; };}, [enabled]);- // The clip library is only relevant once a rig exists to animate. Fetched from- // `record.rig` directly (not the `rig` const below, which is declared after the- // early return) so this hook stays unconditional per the Rules of Hooks.- useEffect(() => {- if (!enabled || record.rig?.status !== 'ready') return;- let active = true;- listRiggingClips({ silent: true })- .then((value) => { if (active) setClips(value?.clips || []); })- .catch(() => { if (active) setClips([]); });- return () => { active = false; };- }, [enabled, record.rig?.status]);+ // Retarget lane (#6065). The clip library is only relevant once a rig exists to+ // animate; a failed read must not read as "no clips yet".+ const {+ items: clips, state: clipsState, error: clipsError, retry: retryClips,+ } = useListResource(fetchClips, { enabled: enabled && record.rig?.status === 'ready' });const handleRig = useCallback(async () => {if (busy) return;@@ -107,8 +103,8 @@ export default function RigPanel({ record, onRecordChange }) {const retarget = record.retarget || null;const canRetarget = rig?.status === 'ready';- const clipsLoaded = clips !== null;- const hasClips = clipsLoaded && clips.length > 0;+ const clipsLoaded = clipsState === 'ready';+ const hasClips = clips.length > 0;const retargetBusy = retargeting || retarget?.status === 'retargeting';const diagnosticReady = retarget?.status === 'ready' && retarget.mode === 'diagnostic';const writeReady = retarget?.status === 'ready' && retarget.mode === 'write';@@ -185,7 +181,10 @@ export default function RigPanel({ record, onRecordChange }) {<h2 className="text-sm font-semibold text-white">Animate with a clip</h2></div>- {!clipsLoaded && <p className="mt-2 text-xs text-gray-500">Checking the clip library…</p>}+ {clipsState === 'loading' && <p className="mt-2 text-xs text-gray-500">Checking the clip library…</p>}+ {clipsState === 'error' && (+ <ListLoadError what="the clip library" error={clipsError} onRetry={retryClips} className="mt-2" />+ )}{clipsLoaded && !hasClips && (<p className="mt-2 text-xs text-gray-500">No animation clips yet. Drop a GLB clip into the clip library to animate this character.diff --git a/client/src/components/media/RigPanel.test.jsx b/client/src/components/media/RigPanel.test.jsxindex 32685440a9..7e25cdc48b 100644--- a/client/src/components/media/RigPanel.test.jsx+++ b/client/src/components/media/RigPanel.test.jsx@@ -117,6 +117,20 @@ describe('RigPanel retarget lane', () => {expect(screen.queryByLabelText(/animation clip/i)).not.toBeInTheDocument();});+ it('reports a failed clip-library read with Retry instead of "no clips yet"', async () => {+ mock.listRiggingClips.mockRejectedValueOnce(new Error('clip library unreadable'));+ mock.listRiggingClips.mockResolvedValueOnce({ clips: [{ filename: 'wave.glb', label: 'Wave' }] });+ render(<RigPanel record={RIGGED_RECORD} onRecordChange={() => {}} />);++ expect(await screen.findByRole('alert')).toHaveTextContent(/could not load the clip library.*clip library unreadable/i);+ expect(screen.queryByText(/no animation clips yet/i)).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByLabelText(/animation clip/i)).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(mock.listRiggingClips).toHaveBeenCalledTimes(2);+ });+it('runs a diagnostic preview and shows the proposed cleanup without offering write yet', async () => {mock.listRiggingClips.mockResolvedValue({ clips: [{ filename: 'wave.glb', label: 'Wave' }] });const diagnosed = {diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsxindex cd15ec5759..7f46e92e1a 100644--- a/client/src/components/messages/MessageDetail.jsx+++ b/client/src/components/messages/MessageDetail.jsx@@ -3,6 +3,8 @@ import { ArrowLeft, Reply, Sparkles, Send, RefreshCw, Archive, Trash2, User, Imaimport toast from '../ui/Toast';import { formatCount, formatDateTime } from '../../utils/formatters';import * as api from '../../services/api';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';// Any src/href/poster/url()/@import that points at a remote http(s) or// protocol-relative (`//host/...`) resource — the load vectors a tracking@@ -118,8 +120,6 @@ export default function MessageDetail({ message, accounts, onBack }) {const [replyBody, setReplyBody] = useState('');const [generating, setGenerating] = useState(false);const [generatedDraftId, setGeneratedDraftId] = useState(null);- const [threadMessages, setThreadMessages] = useState([]);- const [threadLoading, setThreadLoading] = useState(false);const [refreshing, setRefreshing] = useState(false);const [displayedMessage, setDisplayedMessage] = useState(message);const [actioning, setActioning] = useState(null);@@ -139,17 +139,19 @@ export default function MessageDetail({ message, accounts, onBack }) {const account = accounts.find(a => a.id === displayedMessage.accountId) || accounts[0];- // Load thread messages if this message is part of a thread- useEffect(() => {- if (!message.threadId || !message.accountId) return;- let cancelled = false;- setThreadLoading(true);- api.getMessageThread(message.accountId, message.threadId)- .then(data => { if (!cancelled) setThreadMessages(data?.messages || []); })- .catch(() => { if (!cancelled) setThreadMessages([]); })- .finally(() => { if (!cancelled) setThreadLoading(false); });- return () => { cancelled = true; };- }, [message.threadId, message.accountId]);+ // Load thread messages if this message is part of a thread. A failed read+ // falls back to the single message but says so, so a missing conversation is+ // not mistaken for a one-message thread.+ const { threadId, accountId } = message;+ const hasThreadRef = !!(threadId && accountId);+ const fetchThread = useCallback(+ () => api.getMessageThread(accountId, threadId, { silent: true }).then(data => data?.messages || []),+ [accountId, threadId],+ );+ const {+ items: threadMessages, state: threadState, error: threadError, retry: retryThread, setItems: setThreadMessages,+ } = useListResource(fetchThread, { enabled: hasThreadRef });+ const threadLoading = hasThreadRef && threadState === 'loading';const handleRefresh = async () => {setRefreshing(true);@@ -274,6 +276,9 @@ export default function MessageDetail({ message, accounts, onBack }) {)}{/* Message body / thread */}+ {hasThreadRef && threadState === 'error' && (+ <ListLoadError what="the conversation" error={threadError} onRetry={retryThread} />+ )}{threadLoading ? (<div className="text-sm text-gray-500 animate-pulse">Loading conversation...</div>) : (diff --git a/client/src/components/messages/MessageDetail.test.jsx b/client/src/components/messages/MessageDetail.test.jsxindex 65bdf265c5..641453c931 100644--- a/client/src/components/messages/MessageDetail.test.jsx+++ b/client/src/components/messages/MessageDetail.test.jsx@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';const api = vi.hoisted(() => ({createMessageDraft: vi.fn(),@@ -128,3 +129,24 @@ describe('MessageDetail SafeHtmlBody remote content blocking', () => {expect(screen.queryByText('Remote images blocked')).not.toBeInTheDocument();});});++describe('MessageDetail thread load', () => {+ const threaded = { ...baseMessage, threadId: 'thr-1', bodyText: 'Hello body' };++ it('shows a load error with Retry, still shows the message, and loads the thread on retry', async () => {+ api.getMessageThread.mockRejectedValueOnce(new Error('Thread unavailable'));+ renderMessage(threaded);+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the conversation — Thread unavailable');+ expect(screen.getByText('Hello body')).toBeTruthy();+ expect(screen.queryByText(/messages$/)).toBeNull();++ api.getMessageThread.mockResolvedValueOnce({ messages: [+ { id: 'm1', from: { name: 'Alice' }, bodyText: 'First', bodyFull: true },+ { id: 'm2', from: { name: 'Bob' }, bodyText: 'Second', bodyFull: true },+ ] });+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Second')).toBeTruthy();+ expect(screen.getByText('2 messages')).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/components/music/ArtistPicker.jsx b/client/src/components/music/ArtistPicker.jsxindex 699a0d125f..64f9692f94 100644--- a/client/src/components/music/ArtistPicker.jsx+++ b/client/src/components/music/ArtistPicker.jsx@@ -8,23 +8,17 @@* `onChange('', '')`. Self-contained: fetches the artist list on mount.*/-import { useEffect, useState } from 'react';import { Link } from 'react-router';import { listArtists } from '../../services/api';import { withUnlistedOption } from '../../lib/withUnlistedOption';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';-export default function ArtistPicker({ id = 'music-artist', value, name, onChange, disabled = false }) {- const [artists, setArtists] = useState([]);- const [loading, setLoading] = useState(true);+const fetchArtists = () => listArtists({ silent: true });- useEffect(() => {- let alive = true;- listArtists({ silent: true })- .then((list) => { if (alive) setArtists(Array.isArray(list) ? list : []); })- .catch(() => { if (alive) setArtists([]); })- .finally(() => { if (alive) setLoading(false); });- return () => { alive = false; };- }, []);+export default function ArtistPicker({ id = 'music-artist', value, name, onChange, disabled = false }) {+ const { items: artists, state, error, retry } = useListResource(fetchArtists);+ const loading = state === 'loading';const handleChange = (e) => {const artistId = e.target.value || '';@@ -54,8 +48,9 @@ export default function ArtistPicker({ id = 'music-artist', value, name, onChang<option key={a.id} value={a.id}>{a.name}</option>))}</select>+ {state === 'error' && <ListLoadError what="artist personas" error={error} onRetry={retry} className="mt-1" />}<p className="text-[11px] text-gray-500 mt-1">- {artists.length === 0 && !loading ? (+ {state === 'ready' && artists.length === 0 ? (<>No artist personas yet — <Link to="/music/artists" className="text-port-accent hover:underline">create one</Link>.</>) : !value && name ? (<>Unlinked artist: <span className="text-gray-400">{name}</span> — pick a persona to link it.</>diff --git a/client/src/components/music/ArtistPicker.test.jsx b/client/src/components/music/ArtistPicker.test.jsxindex 38de253fb7..62261f295d 100644--- a/client/src/components/music/ArtistPicker.test.jsx+++ b/client/src/components/music/ArtistPicker.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';import ArtistPicker from './ArtistPicker';@@ -50,4 +51,22 @@ describe('ArtistPicker', () => {await screen.findByRole('option', { name: 'The Kestrels' });expect(screen.getAllByRole('option', { name: 'The Kestrels' })).toHaveLength(1);});++ it('shows a load error with Retry, not the empty-personas copy, when the read fails', async () => {+ listArtists.mockRejectedValueOnce(new Error('Artists unavailable'));+ renderPicker({ value: '', name: '' });+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load artist personas — Artists unavailable');+ expect(screen.queryByText(/No artist personas yet/)).toBeNull();++ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await screen.findByRole('option', { name: 'The Kestrels' });+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('shows the empty-personas copy only once an empty list loaded', async () => {+ listArtists.mockResolvedValueOnce([]);+ renderPicker({ value: '', name: '' });+ expect(await screen.findByText(/No artist personas yet/)).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });});diff --git a/client/src/components/musicVideo/CharacterStyleSelect.jsx b/client/src/components/musicVideo/CharacterStyleSelect.jsxindex 20cfac2230..5e672c33ac 100644--- a/client/src/components/musicVideo/CharacterStyleSelect.jsx+++ b/client/src/components/musicVideo/CharacterStyleSelect.jsx@@ -1,5 +1,8 @@-import { useEffect, useState } from 'react';import { listMusicVideoCharacterStyles } from '../../services/apiMusicVideo.js';+import useListResource from '../../hooks/useListResource.js';+import ListLoadError from '../ui/ListLoadError.jsx';++const fetchStyles = () => listMusicVideoCharacterStyles({ silent: true });const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';@@ -10,25 +13,17 @@ const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded* sheet itself is chosen later on the Look step (CharacterStylePicker).*/export default function CharacterStyleSelect({ id, value, onChange }) {- // null = not loaded yet; a failed fetch shows just "No character style".- const [styles, setStyles] = useState(null);- const style = (styles || []).find((s) => s.id === value) || null;-- useEffect(() => {- let active = true;- listMusicVideoCharacterStyles({ silent: true })- .then((list) => { if (active) setStyles(list); })- .catch(() => { if (active) setStyles([]); });- return () => { active = false; };- }, []);+ const { items: styles, state, error, retry } = useListResource(fetchStyles);+ const style = styles.find((s) => s.id === value) || null;return (<div className="min-w-0"><label htmlFor={id} className="block text-xs text-port-text-muted mb-1">Character style</label><select id={id} value={value || ''} onChange={(e) => onChange(e.target.value)} className={inputClass}>- <option value="">{styles === null ? 'Loading…' : 'No character style'}</option>- {(styles || []).map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}+ <option value="">{state === 'loading' ? 'Loading…' : 'No character style'}</option>+ {styles.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}</select>+ {state === 'error' && <ListLoadError what="character styles" error={error} onRetry={retry} className="mt-1" />}{style && (<p className="mt-1 text-xs text-port-text-muted">{style.characterName} is cast as protagonist.{' '}diff --git a/client/src/components/musicVideo/CharacterStyleSelect.test.jsx b/client/src/components/musicVideo/CharacterStyleSelect.test.jsxnew file mode 100644index 0000000000..c804714f16--- /dev/null+++ b/client/src/components/musicVideo/CharacterStyleSelect.test.jsx@@ -0,0 +1,35 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/apiMusicVideo.js', () => ({+ listMusicVideoCharacterStyles: vi.fn(),+}));++import { listMusicVideoCharacterStyles } from '../../services/apiMusicVideo.js';+import CharacterStyleSelect from './CharacterStyleSelect.jsx';++const styles = [{ id: 'cs1', label: 'Noir Detective', characterName: 'Alice', referenceImageId: null }];++describe('CharacterStyleSelect', () => {+ beforeEach(() => vi.clearAllMocks());++ it('lists the fetched styles and describes the selected one', async () => {+ listMusicVideoCharacterStyles.mockResolvedValue(styles);+ render(<CharacterStyleSelect id="cs" value="cs1" onChange={vi.fn()} />);+ expect(await screen.findByRole('option', { name: 'Noir Detective' })).toBeTruthy();+ expect(screen.getByText(/Alice is cast as protagonist/)).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('shows a load error with Retry instead of silently offering only "No character style"', async () => {+ listMusicVideoCharacterStyles.mockRejectedValueOnce(new Error('Styles unavailable'));+ render(<CharacterStyleSelect id="cs" value="" onChange={vi.fn()} />);+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load character styles — Styles unavailable');++ listMusicVideoCharacterStyles.mockResolvedValueOnce(styles);+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('option', { name: 'Noir Detective' })).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/components/musicVideo/ExistingSongSelect.jsx b/client/src/components/musicVideo/ExistingSongSelect.jsxindex 6cc0d0438a..6375c5f88c 100644--- a/client/src/components/musicVideo/ExistingSongSelect.jsx+++ b/client/src/components/musicVideo/ExistingSongSelect.jsx@@ -1,5 +1,9 @@-import { useEffect, useState } from 'react';import { listMusicVideoProjectSummaries } from '../../services/apiMusicVideo.js';+import useListResource from '../../hooks/useListResource.js';+import ListLoadError from '../ui/ListLoadError.jsx';++const fetchSongProjects = () => listMusicVideoProjectSummaries({ limit: 500 }, { silent: true })+ .then((page) => (page?.items || []).filter((p) => p.trackId || p.uploadedAudioFilename));const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';@@ -9,26 +13,18 @@ const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded* projects that have a song, newest first.*/export default function ExistingSongSelect({ id, value, onChange }) {- // null = not loaded yet.- const [projects, setProjects] = useState(null);-- useEffect(() => {- let active = true;- listMusicVideoProjectSummaries({ limit: 500 }, { silent: true })- .then((page) => { if (active) setProjects((page?.items || []).filter((p) => p.trackId || p.uploadedAudioFilename)); })- .catch(() => { if (active) setProjects([]); });- return () => { active = false; };- }, []);- const missing = value && projects && !projects.some((p) => p.id === value);+ const { items: projects, state, error, retry } = useListResource(fetchSongProjects);+ const missing = value && state === 'ready' && !projects.some((p) => p.id === value);return (<div className="min-w-0"><label htmlFor={id} className="block text-xs text-port-text-muted mb-1">Song to use</label><select id={id} value={value || ''} onChange={(e) => onChange(e.target.value)} className={inputClass}>- <option value="">{projects === null ? 'Loading…' : 'Make a new song'}</option>+ <option value="">{state === 'loading' ? 'Loading…' : 'Make a new song'}</option>{missing && <option value={value}>{value} (not found)</option>}- {(projects || []).map((p) => <option key={p.id} value={p.id}>Use the song from {p.name}</option>)}+ {projects.map((p) => <option key={p.id} value={p.id}>Use the song from {p.name}</option>)}</select>+ {state === 'error' && <ListLoadError what="projects with a song" error={error} onRetry={retry} className="mt-1" />}{value && (<p className="text-[11px] text-port-text-muted mt-1">Its audio, lyrics and word timing are copied. No lyrics are written and no song is made; the look starts fresh.diff --git a/client/src/components/musicVideo/ExistingSongSelect.test.jsx b/client/src/components/musicVideo/ExistingSongSelect.test.jsxnew file mode 100644index 0000000000..e22d98afb8--- /dev/null+++ b/client/src/components/musicVideo/ExistingSongSelect.test.jsx@@ -0,0 +1,40 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../services/apiMusicVideo.js', () => ({+ listMusicVideoProjectSummaries: vi.fn(),+}));++import { listMusicVideoProjectSummaries } from '../../services/apiMusicVideo.js';+import ExistingSongSelect from './ExistingSongSelect.jsx';++const page = {+ items: [+ { id: 'p1', name: 'Example Song', trackId: 't1' },+ { id: 'p2', name: 'No Audio Yet' },+ ],+};++describe('ExistingSongSelect', () => {+ beforeEach(() => vi.clearAllMocks());++ it('lists only projects that have a song', async () => {+ listMusicVideoProjectSummaries.mockResolvedValue(page);+ render(<ExistingSongSelect id="song" value="" onChange={vi.fn()} />);+ expect(await screen.findByRole('option', { name: 'Use the song from Example Song' })).toBeTruthy();+ expect(screen.queryByRole('option', { name: /No Audio Yet/ })).toBeNull();+ });++ it('shows a load error with Retry, not a "(not found)" song, when the read fails', async () => {+ listMusicVideoProjectSummaries.mockRejectedValueOnce(new Error('Projects unavailable'));+ render(<ExistingSongSelect id="song" value="p1" onChange={vi.fn()} />);+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load projects with a song — Projects unavailable');+ expect(screen.queryByRole('option', { name: /not found/ })).toBeNull();++ listMusicVideoProjectSummaries.mockResolvedValueOnce(page);+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('option', { name: 'Use the song from Example Song' })).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/components/musicVideo/PromotionPlanPanel.jsx b/client/src/components/musicVideo/PromotionPlanPanel.jsxindex a4e951e2c1..35d2beb3fa 100644--- a/client/src/components/musicVideo/PromotionPlanPanel.jsx+++ b/client/src/components/musicVideo/PromotionPlanPanel.jsx@@ -1,10 +1,12 @@-import { useEffect, useState } from 'react';+import { useCallback, useState } from 'react';import { Link } from 'react-router';import { CalendarClock, Sparkles } from 'lucide-react';import useProviderModels from '../../hooks/useProviderModels.js';import ProviderModelSelector from '../ProviderModelSelector.jsx';import { getMusicVideoPromotionPlan, planMusicVideoPromotion } from '../../services/apiMusicVideo.js';import { formatWeekdayTime } from '../../utils/formatters.js';+import useListResource from '../../hooks/useListResource.js';+import ListLoadError from '../ui/ListLoadError.jsx';import PublishCard from './PublishCard.jsx';const inputCls = 'w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';@@ -19,7 +21,6 @@ const DAY_CHOICES = [3, 7, 14];*/export default function PromotionPlanPanel({ project }) {const projectId = project?.id;- const [steps, setSteps] = useState(null);const [goal, setGoal] = useState('');const [audience, setAudience] = useState('');const [days, setDays] = useState(7);@@ -28,15 +29,11 @@ export default function PromotionPlanPanel({ project }) {providers, selectedProviderId, selectedModel, availableModels, setSelectedProviderId, setSelectedModel,} = useProviderModels({ allowDefault: true, silent: true });- useEffect(() => {- if (!projectId) return undefined;- let active = true;- setSteps(null);- getMusicVideoPromotionPlan(projectId, { silent: true })- .then((res) => { if (active) setSteps(res?.steps || []); })- .catch(() => { if (active) setSteps([]); });- return () => { active = false; };- }, [projectId]);+ const fetchSteps = useCallback(+ () => getMusicVideoPromotionPlan(projectId, { silent: true }).then((res) => res?.steps || []),+ [projectId],+ );+ const { items: steps, state, error, retry, setItems: setSteps } = useListResource(fetchSteps, { enabled: !!projectId });const plan = () => {setPlanning(true);@@ -55,7 +52,7 @@ export default function PromotionPlanPanel({ project }) {const idFor = (name) => `mv-promo-${name}`;return (<PublishCard projectId={projectId} cardId="promotion" label="Promotion plan" icon={CalendarClock}- summary={steps?.length ? `${steps.length} step${steps.length === 1 ? '' : 's'}` : ''}>+ summary={steps.length ? `${steps.length} step${steps.length === 1 ? '' : 's'}` : ''}><p className="text-port-text-muted">Schedules the steps only you can take, with the text ready to paste. Each one shows up in <Link to="/review" className="text-port-accent underline">Actions</Link> and notifies you when it's time. Planning again replaces the open steps.</p><div className="grid gap-2 sm:grid-cols-2"><label htmlFor={idFor('goal')} className="space-y-1">@@ -82,12 +79,13 @@ export default function PromotionPlanPanel({ project }) {label="Planner" compact alwaysShowModel modelDisabled={availableModels.length === 0}emptyProviderOption="Active provider (default)" emptyModelOption="Default model" disabled={planning} />)}- <button type="button" onClick={plan} disabled={planning || !projectId}+ <button type="button" onClick={plan} disabled={planning || !projectId || state === 'error'}className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">- <Sparkles size={13} /> {planning ? 'Planning…' : (steps?.length ? 'Plan again' : 'Plan promotion')}+ <Sparkles size={13} /> {planning ? 'Planning…' : (steps.length ? 'Plan again' : 'Plan promotion')}</button></div>- {steps?.length > 0 && (+ {state === 'error' && <ListLoadError what="the scheduled steps" error={error} onRetry={retry} />}+ {steps.length > 0 && (<ol aria-label="Scheduled steps" className="space-y-1">{steps.map((step) => (<li key={step.id} className="flex flex-wrap items-baseline gap-x-2">diff --git a/client/src/components/musicVideo/PromotionPlanPanel.test.jsx b/client/src/components/musicVideo/PromotionPlanPanel.test.jsxindex 80b32bdf3d..b854371bb9 100644--- a/client/src/components/musicVideo/PromotionPlanPanel.test.jsx+++ b/client/src/components/musicVideo/PromotionPlanPanel.test.jsx@@ -39,4 +39,17 @@ describe('PromotionPlanPanel', () => {expect(await screen.findByRole('link', { name: 'Answer replies' })).toBeTruthy();expect(getMusicVideoPromotionPlan).toHaveBeenCalledWith('mv-1', { silent: true });});++ it('shows a load error with Retry and blocks re-planning when the saved plan cannot be read', async () => {+ getMusicVideoPromotionPlan.mockRejectedValueOnce(new Error('Plan unavailable'));+ renderPanel();+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the scheduled steps — Plan unavailable');+ expect(screen.getByRole('button', { name: /Plan promotion/ })).toBeDisabled();++ getMusicVideoPromotionPlan.mockResolvedValueOnce({ steps: [{ id: 't9', title: 'Answer replies', dueAt: '2026-10-07T16:30:00.000Z' }] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('link', { name: 'Answer replies' })).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ expect(screen.getByRole('button', { name: /Plan again/ })).not.toBeDisabled();+ });});diff --git a/client/src/components/pipeline/AuthorPicker.jsx b/client/src/components/pipeline/AuthorPicker.jsxindex be546f3e48..9e2db38129 100644--- a/client/src/components/pipeline/AuthorPicker.jsx+++ b/client/src/components/pipeline/AuthorPicker.jsx@@ -13,23 +13,17 @@* until the user picks a persona.*/-import { useEffect, useState } from 'react';import { Link } from 'react-router';import { listAuthors } from '../../services/api';import { withUnlistedOption } from '../../lib/withUnlistedOption';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';-export default function AuthorPicker({ id = 'series-author', value, byline, onChange, disabled = false }) {- const [authors, setAuthors] = useState([]);- const [loading, setLoading] = useState(true);+const fetchAuthors = () => listAuthors({ silent: true });- useEffect(() => {- let alive = true;- listAuthors({ silent: true })- .then((list) => { if (alive) setAuthors(Array.isArray(list) ? list : []); })- .catch(() => { if (alive) setAuthors([]); })- .finally(() => { if (alive) setLoading(false); });- return () => { alive = false; };- }, []);+export default function AuthorPicker({ id = 'series-author', value, byline, onChange, disabled = false }) {+ const { items: authors, state, error, retry } = useListResource(fetchAuthors);+ const loading = state === 'loading';const handleChange = (e) => {const authorId = e.target.value || null;@@ -59,8 +53,9 @@ export default function AuthorPicker({ id = 'series-author', value, byline, onCh<option key={a.id} value={a.id}>{a.name}</option>))}</select>+ {state === 'error' && <ListLoadError what="author personas" error={error} onRetry={retry} className="mt-1" />}<p className="text-[11px] text-gray-500 mt-1">- {authors.length === 0 && !loading ? (+ {state === 'ready' && authors.length === 0 ? (<>No author personas yet — <Link to="/authors" className="text-port-accent hover:underline">create one</Link>.</>) : !value && byline ? (<>Unlinked byline: <span className="text-gray-400">{byline}</span> — pick a persona to link it.</>diff --git a/client/src/components/pipeline/AuthorPicker.test.jsx b/client/src/components/pipeline/AuthorPicker.test.jsxindex bbd9e82893..dc5bd523f8 100644--- a/client/src/components/pipeline/AuthorPicker.test.jsx+++ b/client/src/components/pipeline/AuthorPicker.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';import AuthorPicker from './AuthorPicker';@@ -50,4 +51,22 @@ describe('AuthorPicker', () => {await screen.findByRole('option', { name: 'Alice' });expect(screen.getAllByRole('option', { name: 'Alice' })).toHaveLength(1);});++ it('shows a load error with Retry, not the empty-personas copy, when the read fails', async () => {+ listAuthors.mockRejectedValueOnce(new Error('Authors unavailable'));+ renderPicker({ value: '', byline: '' });+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load author personas — Authors unavailable');+ expect(screen.queryByText(/No author personas yet/)).toBeNull();++ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await screen.findByRole('option', { name: 'Alice' });+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('shows the empty-personas copy only once an empty list loaded', async () => {+ listAuthors.mockResolvedValueOnce([]);+ renderPicker({ value: '', byline: '' });+ expect(await screen.findByText(/No author personas yet/)).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });});diff --git a/client/src/components/pipeline/SeriesLoomsPanel.jsx b/client/src/components/pipeline/SeriesLoomsPanel.jsxindex 24952bfd14..b2f74f4115 100644--- a/client/src/components/pipeline/SeriesLoomsPanel.jsx+++ b/client/src/components/pipeline/SeriesLoomsPanel.jsx@@ -10,12 +10,14 @@* series' universe, so the AI lanes inherit its canon) and lands in the editor.*/-import { useEffect, useState } from 'react';+import { useCallback, useState } from 'react';import { Link, useNavigate } from 'react-router';import { Loader2, Plus, Waypoints } from 'lucide-react';import Pill from '../ui/Pill';import { FormField } from '../ui/FormField.jsx';import { useAsyncAction } from '../../hooks/useAsyncAction';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';import { timeAgo } from '../../utils/formatters';import { createLoom, listLooms } from '../../services/api';import { fieldClass, labelClass } from '../fableloom/fieldStyles';@@ -37,20 +39,12 @@ const countLabel = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;export default function SeriesLoomsPanel({ series }) {const navigate = useNavigate();const seriesId = series?.id;- const [looms, setLooms] = useState(null);const [showCreate, setShowCreate] = useState(false);const [participationMode, setParticipationMode] = useState('helper');const [communicationMedium, setCommunicationMedium] = useState('');- useEffect(() => {- if (!seriesId) return undefined;- let canceled = false;- setLooms(null);- listLooms({ seriesId, silent: true })- .then((rows) => { if (!canceled) setLooms(Array.isArray(rows) ? rows : []); })- .catch(() => { if (!canceled) setLooms([]); });- return () => { canceled = true; };- }, [seriesId]);+ const fetchLooms = useCallback(() => listLooms({ seriesId, silent: true }), [seriesId]);+ const { items: looms, state, error, retry } = useListResource(fetchLooms, { enabled: !!seriesId });const [runCreate, creating] = useAsyncAction(async () => {const loom = await createLoom({@@ -138,11 +132,13 @@ export default function SeriesLoomsPanel({ series }) {</div>)}- {looms === null ? (+ {state === 'loading' ? (<div className="flex items-center gap-2 text-xs text-gray-500"><Loader2 size={12} className="animate-spin" aria-hidden="true" />Loading branching narratives…</div>+ ) : state === 'error' ? (+ <ListLoadError what="branching narratives" error={error} onRetry={retry} />) : looms.length === 0 ? (<p className="text-xs text-gray-600">None yet. A branching narrative stays its own record — it just carries this series' canon and shows up here.diff --git a/client/src/components/pipeline/SeriesLoomsPanel.test.jsx b/client/src/components/pipeline/SeriesLoomsPanel.test.jsxindex fa0e33a465..fd83a91a32 100644--- a/client/src/components/pipeline/SeriesLoomsPanel.test.jsx+++ b/client/src/components/pipeline/SeriesLoomsPanel.test.jsx@@ -53,14 +53,19 @@ describe('SeriesLoomsPanel', () => {.toHaveAttribute('href', '/fableloom/loom-1');});- it('shows an empty state when nothing links to the series', async () => {- api.listLooms.mockResolvedValue([]);+ it('shows a load error with Retry, not "None yet", when the loom read fails', async () => {+ api.listLooms.mockRejectedValueOnce(new Error('Looms unavailable'));await renderPanel();- await waitFor(() => expect(screen.getByText(/None yet/)).toBeInTheDocument());+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load branching narratives — Looms unavailable');+ expect(screen.queryByText(/None yet/)).toBeNull();++ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Example Series — branching narrative')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();});- it('degrades to the empty state when the list fetch fails', async () => {- api.listLooms.mockRejectedValue(new Error('offline'));+ it('shows an empty state when nothing links to the series', async () => {+ api.listLooms.mockResolvedValue([]);await renderPanel();await waitFor(() => expect(screen.getByText(/None yet/)).toBeInTheDocument());});diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex b65f710595..3c45514257 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from 'react';+import { useMemo, useState } from 'react';import { Link } from 'react-router';import { Film, ExternalLink, Loader2, Sparkles, AlertCircle, CheckCircle2 } from 'lucide-react';import toast from '../../ui/Toast';@@ -12,8 +12,12 @@ import ModelSelect from '../../ModelSelect';import { useAsyncAction } from '../../../hooks/useAsyncAction';import { useSocketResource } from '../../../hooks/useSocketResource';import { useVideoFileSrc } from '../../../hooks/useVideoFileSrc';+import useListResource from '../../../hooks/useListResource';+import ListLoadError from '../../ui/ListLoadError';import { sceneShotWarnings } from '../../../lib/shotContinuity';+const fetchVideoModels = () => listVideoModels({ silent: true });+const PROJECT_EVENTS = ['creative-director:project:changed'];const isTerminalProjectStatus = (s) => s === 'complete' || s === 'failed';@@ -32,7 +36,7 @@ const STATUS_LABEL = {// the video-model list loaded) the video model. Rendered identically in the// initial-start and restart-confirm toolbars so the two paths can't drift.const SELECT_CLS = 'bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300';-function RenderControls({ aspectRatio, setAspectRatio, quality, setQuality, modelId, setModelId, videoModels, disabled }) {+function RenderControls({ aspectRatio, setAspectRatio, quality, setQuality, modelId, setModelId, videoModels, modelsError, onRetryModels, disabled }) {return (<><select@@ -72,6 +76,7 @@ function RenderControls({ aspectRatio, setAspectRatio, quality, setQuality, modeclassName={`${SELECT_CLS} max-w-[180px]`}/>)}+ {modelsError && <ListLoadError what="video models" error={modelsError} onRetry={onRetryModels} />}</>);}@@ -106,17 +111,9 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {// (set after a render starts) restores the user's prior choice on reload.const [modelId, setModelId] = useState(stage.modelId || '');- // Load the video-model list once for the picker. Secondary control — a fetch- // failure just hides the model select (the user still gets the server- // default), so swallow the error rather than toasting.- const [videoModels, setVideoModels] = useState([]);- useEffect(() => {- let cancelled = false;- listVideoModels({ silent: true })- .then((models) => { if (!cancelled) setVideoModels(Array.isArray(models) ? models : []); })- .catch(() => { if (!cancelled) setVideoModels([]); });- return () => { cancelled = true; };- }, []);+ // Secondary control: on a failed read the picker is replaced by an inline+ // error with Retry; rendering still works against the server default model.+ const { items: videoModels, state: modelsState, error: modelsError, retry: retryModels } = useListResource(fetchVideoModels);const { data: rawCdProject } = useSocketResource(() => cdProjectId ? getCreativeDirectorProject(cdProjectId, { slim: true }) : null,@@ -215,7 +212,8 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {aspectRatio={aspectRatio} setAspectRatio={setAspectRatio}quality={quality} setQuality={setQuality}modelId={modelId} setModelId={setModelId}- videoModels={videoModels} disabled={submitting}+ videoModels={videoModels} modelsError={modelsState === 'error' ? modelsError : null} onRetryModels={retryModels}+ disabled={submitting}/><buttontype="button"@@ -235,7 +233,8 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {aspectRatio={aspectRatio} setAspectRatio={setAspectRatio}quality={quality} setQuality={setQuality}modelId={modelId} setModelId={setModelId}- videoModels={videoModels} disabled={submitting}+ videoModels={videoModels} modelsError={modelsState === 'error' ? modelsError : null} onRetryModels={retryModels}+ disabled={submitting}/><buttontype="button"diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsxindex e78c220e96..a22b9a7138 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsx@@ -2,6 +2,7 @@ import { act, render, screen, fireEvent } from '@testing-library/react';import { MemoryRouter } from 'react-router';import { afterEach, expect, it, vi } from 'vitest';import EpisodeVideoStage from './EpisodeVideoStage';+import { listVideoModels } from '../../../services/api';import { getCreativeDirectorProject } from '../../../services/apiCreativeDirector';const handlers = vi.hoisted(() => new Map());@@ -57,3 +58,15 @@ it('drops late reads after the stage switches projects', async () => {expect(screen.queryByText('Stale failure')).not.toBeInTheDocument();expect(screen.getByText('Current project failure')).toBeInTheDocument();});++it('shows a video-model load error with Retry instead of silently hiding the model picker', async () => {+ listVideoModels.mockRejectedValueOnce(new Error('Models unavailable'));+ await act(async () => render(view(undefined)));+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load video models — Models unavailable');+ expect(screen.queryByRole('combobox', { name: 'Video model' })).toBeNull();++ listVideoModels.mockResolvedValueOnce([{ id: 'model-a', name: 'Model A' }]);+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Retry' })));+ expect(await screen.findByRole('combobox', { name: 'Video model' })).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+});diff --git a/client/src/components/privacy/OrgDrawer.jsx b/client/src/components/privacy/OrgDrawer.jsxindex 9423876aef..a0d47c95ed 100644--- a/client/src/components/privacy/OrgDrawer.jsx+++ b/client/src/components/privacy/OrgDrawer.jsx@@ -6,6 +6,7 @@ import {createPrivacyOrg, updatePrivacyOrg, getOrgHoldings, setOrgHoldings, getSocialAccounts,} from '../../services/api';import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import toast from '../ui/Toast';import { ORG_CATEGORIES, ORG_TRUST_LEVELS, ORG_STATUSES, VAULT_TYPES, INPUT_CLS, labelFor } from './constants';@@ -14,6 +15,9 @@ const EMPTY = {contactEmail: '', contactPhone: '', notes: '', socialAccountId: '',};+// Digital Twin accounts for the cross-link picker (#2147); the component owns the error UI.+const fetchSocialAccounts = () => getSocialAccounts({}, { silent: true }).then((res) => res?.accounts || []);+const HOLDINGS_READY = Object.freeze({ state: 'ready', error: null });const HOLDINGS_LOADING = Object.freeze({ state: 'loading', error: null });@@ -37,11 +41,10 @@ export default function OrgDrawer({ open, org, subjectId, vaultRecords, vaultErr// erase every holding the org has.const [holdingsLoad, setHoldingsLoad] = useState(HOLDINGS_READY);const [holdingsAttempt, setHoldingsAttempt] = useState(0);- const [socialAccounts, setSocialAccounts] = useState([]); // Digital Twin accounts for the cross-link picker+ const { items: socialAccounts, state: accountsState, error: accountsError, retry: retryAccounts } = useListResource(fetchSocialAccounts, { enabled: open });useEffect(() => {if (!open) return undefined;- let active = true;setForm(org? {name: org.name ?? '',@@ -56,12 +59,7 @@ export default function OrgDrawer({ open, org, subjectId, vaultRecords, vaultErr}: { ...EMPTY });setSelected(new Set());- // Load Digital Twin social accounts for the cross-link picker (#2147). Degrades- // to no picker options if the twin has none — never blocks org editing.- getSocialAccounts()- .then((res) => { if (active) setSocialAccounts(res?.accounts || []); })- .catch(() => { if (active) setSocialAccounts([]); });- return () => { active = false; };+ return undefined;}, [open, org]);useEffect(() => {@@ -172,14 +170,17 @@ export default function OrgDrawer({ open, org, subjectId, vaultRecords, vaultErrclassName={INPUT_CLS}><option value="">— None —</option>- {/* Preserve a stale link (account since deleted) so the select isn't blank. */}+ {/* Preserve the current link so the select isn't blank; it is only "unavailable" once the list actually loaded without it. */}{form.socialAccountId && !socialAccounts.some((a) => a.id === form.socialAccountId) && (- <option value={form.socialAccountId}>Linked account (unavailable)</option>+ <option value={form.socialAccountId}>{accountsState === 'ready' ? 'Linked account (unavailable)' : 'Linked account'}</option>)}{socialAccounts.map((a) => (<option key={a.id} value={a.id}>{accountLabel(a)}</option>))}</select>+ {accountsState === 'error' && (+ <ListLoadError what="Digital Twin social accounts" error={accountsError} onRetry={retryAccounts} className="mt-1" />+ )}<p className="text-[11px] text-gray-500 mt-1">Cross-links this org to one of your Digital Twin social accounts — the account shows an “in org registry” badge in return.</p>diff --git a/client/src/components/privacy/OrgDrawer.test.jsx b/client/src/components/privacy/OrgDrawer.test.jsxindex 9265cb07cf..0df4b4368d 100644--- a/client/src/components/privacy/OrgDrawer.test.jsx+++ b/client/src/components/privacy/OrgDrawer.test.jsx@@ -58,3 +58,19 @@ describe('OrgDrawer holdings (replace-set)', () => {expect(api.setOrgHoldings).toHaveBeenCalledWith('org-1', [{ vaultRecordId: 'v1' }], { silent: true });});});++describe('OrgDrawer linked social account picker', () => {+ it('shows a retryable error, not an unavailable link, when the account read failed', async () => {+ api.getOrgHoldings.mockResolvedValue([]);+ api.getSocialAccounts.mockRejectedValueOnce(new Error('twin down'));+ api.getSocialAccounts.mockResolvedValue({ accounts: [{ id: 'acct-1', platform: 'github', username: 'alice' }] });+ render(<OrgDrawer open org={{ ...ORG, socialAccountId: 'acct-1' }} vaultRecords={VAULT} onClose={() => {}} onSaved={() => {}} />);++ expect(await screen.findByText(/Could not load Digital Twin social accounts/)).toBeInTheDocument();+ expect(screen.queryByText('Linked account (unavailable)')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('option', { name: 'github · @alice' })).toBeInTheDocument();+ expect(screen.queryByText(/Could not load Digital Twin social accounts/)).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/providers/ProviderServiceForm.jsx b/client/src/components/providers/ProviderServiceForm.jsxindex bc0806fb62..9be8dab44a 100644--- a/client/src/components/providers/ProviderServiceForm.jsx+++ b/client/src/components/providers/ProviderServiceForm.jsx@@ -1,8 +1,10 @@-import { useEffect, useMemo, useState } from 'react';+import { useMemo, useState } from 'react';import { ExternalLink } from 'lucide-react';import toast from '../ui/Toast';import Drawer from '../Drawer';import Banner from '../ui/Banner';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import { FormField } from '../ui/FormField';import { INPUT_CLASS } from '../apps/constants';import * as api from '../../services/api';@@ -43,27 +45,22 @@ const transportsDraftFor = (definition) => Object.fromEntries(Object.entries(definition?.transports || {}).map(([protocol, transport]) => [protocol, transport.defaultBaseUrl || '']),);+const fetchDefinitions = () => api.getProviderServiceDefinitions({ silent: true })+ .then((data) => (Array.isArray(data?.definitions) ? data.definitions : []));+export default function ProviderServiceForm({ onClose, onCreated }) {- const [definitions, setDefinitions] = useState(null); // null = not fetched yet+ const { items: definitions, state: definitionsState, error: definitionsError, retry: retryDefinitions } = useListResource(fetchDefinitions);const [draft, setDraft] = useState(EMPTY_DRAFT);const [busy, setBusy] = useState(false);const set = (key) => (e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }));- useEffect(() => {- let active = true;- api.getProviderServiceDefinitions({ silent: true })- .then((data) => { if (active) setDefinitions(Array.isArray(data?.definitions) ? data.definitions : []); })- .catch(() => { if (active) setDefinitions([]); });- return () => { active = false; };- }, []);-const grouped = useMemo(() => FAMILY_ORDER- .map((family) => ({ family, rows: (definitions || []).filter((row) => row.family === family) }))+ .map((family) => ({ family, rows: definitions.filter((row) => row.family === family) })).filter((group) => group.rows.length > 0), [definitions]);- const definition = (definitions || []).find((row) => row.id === draft.definitionId) || null;+ const definition = definitions.find((row) => row.id === draft.definitionId) || null;const pickDefinition = (definitionId) => {- const next = (definitions || []).find((row) => row.id === definitionId) || null;+ const next = definitions.find((row) => row.id === definitionId) || null;setDraft({...EMPTY_DRAFT,definitionId,@@ -113,8 +110,11 @@ export default function ProviderServiceForm({ onClose, onCreated }) {return (<Drawer open onClose={onClose} title="Add service" size="md" closeLabel="Close add service" closeOnBackdrop={false}><form onSubmit={submit} className="space-y-4">- {definitions !== null && definitions.length === 0 && (- <Banner tone="error" size="sm">Could not load the service definitions from this server.</Banner>+ {definitionsState === 'error' && (+ <ListLoadError what="the service definitions" error={definitionsError} onRetry={retryDefinitions} />+ )}+ {definitionsState === 'ready' && definitions.length === 0 && (+ <Banner tone="warning" size="sm">This server declares no service definitions to add.</Banner>)}<FormField label="Service *" hint="The backend a harness can be pointed at"><select@@ -124,7 +124,7 @@ export default function ProviderServiceForm({ onClose, onCreated }) {requiredclassName={INPUT_CLASS}>- <option value="">{definitions === null ? 'Loading…' : 'Choose a service'}</option>+ <option value="">{definitionsState === 'loading' ? 'Loading…' : 'Choose a service'}</option>{grouped.map((group) => (<optgroup key={group.family} label={FAMILY_LABEL[group.family]}>{group.rows.map((row) => <option key={row.id} value={row.id}>{row.label}</option>)}diff --git a/client/src/components/providers/ProviderServiceForm.test.jsx b/client/src/components/providers/ProviderServiceForm.test.jsxnew file mode 100644index 0000000000..f98ec8475f--- /dev/null+++ b/client/src/components/providers/ProviderServiceForm.test.jsx@@ -0,0 +1,34 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';++const api = vi.hoisted(() => ({+ getProviderServiceDefinitions: vi.fn(),+ createProviderService: vi.fn(),+}));+vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import ProviderServiceForm from './ProviderServiceForm';++const DEFINITION = {+ id: 'lmstudio', label: 'LM Studio', family: 'local', plans: ['local'], envVars: [], transports: { openai: { defaultBaseUrl: null } },+};++describe('ProviderServiceForm definitions read', () => {+ beforeEach(() => vi.clearAllMocks());++ it('shows a retryable error rather than an empty service list when the read fails', async () => {+ api.getProviderServiceDefinitions.mockRejectedValueOnce(new Error('server down'));+ api.getProviderServiceDefinitions.mockResolvedValue({ definitions: [DEFINITION] });+ render(<ProviderServiceForm onClose={() => {}} onCreated={() => {}} />);++ expect(await screen.findByText(/Could not load the service definitions/)).toBeInTheDocument();+ expect(screen.queryByText(/declares no service definitions/)).not.toBeInTheDocument();+ expect(screen.queryByRole('option', { name: 'LM Studio' })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('option', { name: 'LM Studio' })).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(api.getProviderServiceDefinitions).toHaveBeenCalledWith({ silent: true });+ });+});diff --git a/client/src/components/settings/ImageGenProviderSections.jsx b/client/src/components/settings/ImageGenProviderSections.jsxindex 9d13ee65f3..f1b66e6b98 100644--- a/client/src/components/settings/ImageGenProviderSections.jsx+++ b/client/src/components/settings/ImageGenProviderSections.jsx@@ -13,6 +13,8 @@ import { useState, useEffect, useCallback, useId } from 'react';import { AlertTriangle, Check, Sparkles, Terminal } from 'lucide-react';import FormField from '../ui/FormField';import BrailleSpinner from '../BrailleSpinner';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import LocalSetupPanel from './LocalSetupPanel';import LocalRuntimeStatus from '../imageGen/LocalRuntimeStatus';import FalModelSelect from '../imageGen/FalModelSelect';@@ -36,6 +38,17 @@ export const PARALLEL_FALLBACK = { min: 1, max: Number.MAX_SAFE_INTEGER, defaultexport const clampParallel = (n, bounds = PARALLEL_FALLBACK) =>Math.max(bounds.min, Math.min(bounds.max, Math.floor(Number(n) || bounds.default)));+// The configured Codex provider's model ids (the signed-in account's catalog+// when fetched, else the shipped presets).+const fetchCodexProviderModels = () => getProviders({ silent: true }).then((data) => {+ const providers = Array.isArray(data?.providers) ? data.providers : [];+ const provider = providers.find((p) => p?.id === 'codex' && isCodexSubscriptionProvider(p))+ || providers.find(isCodexSubscriptionProvider);+ return provider ? providerModelList(provider)+ .map((m) => (typeof m === 'string' ? m : m?.id))+ .filter((id) => typeof id === 'string' && id !== '') : [];+});+const INPUT_CLASS = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';const SECTION_CLASS = 'bg-port-card border border-port-border rounded-xl p-6 space-y-4';const FIELD_LABEL_CLASS = 'block text-xs font-medium text-gray-400 mb-1';@@ -116,30 +129,12 @@ export default function ImageGenProviderSections({ mediaTab, setMediaTab, form,{ id: 'codex', command: 'codex' },codexModel.trim() || CODEX_IMAGEGEN_DEFAULT_MODEL,);- // Model picker options: the configured Codex provider's model list (the- // signed-in account's catalog when fetched, else the shipped presets), read- // only once the Codex section is enabled. `null` = not loaded yet; the- // shipped default is always offered so the picker is never empty.- const [codexProviderModels, setCodexProviderModels] = useState(null);- useEffect(() => {- if (!codexEnabled) return undefined;- let active = true;- getProviders({ silent: true })- .then((data) => {- if (!active) return;- const providers = Array.isArray(data?.providers) ? data.providers : [];- const provider = providers.find((p) => p?.id === 'codex' && isCodexSubscriptionProvider(p))- || providers.find(isCodexSubscriptionProvider);- const ids = provider ? providerModelList(provider)- .map((m) => (typeof m === 'string' ? m : m?.id))- .filter((id) => typeof id === 'string' && id !== '') : [];- setCodexProviderModels(ids);- })- .catch(() => { if (active) setCodexProviderModels([]); });- return () => { active = false; };- }, [codexEnabled]);+ // Model picker options, read only once the Codex section is enabled. The+ // shipped default is always offered so the picker is never empty, even when+ // the provider read failed (the error row below says so).+ const { items: codexProviderModels, state: codexModelsState, error: codexModelsError, retry: retryCodexModels } = useListResource(fetchCodexProviderModels, { enabled: codexEnabled });const codexModelOptions = withUnlistedOption(- [...new Set([CODEX_IMAGEGEN_DEFAULT_MODEL, ...(codexProviderModels || [])])].map((id) => ({ id })),+ [...new Set([CODEX_IMAGEGEN_DEFAULT_MODEL, ...codexProviderModels])].map((id) => ({ id })),codexModel.trim(),(id) => ({ id }),);@@ -331,6 +326,9 @@ export default function ImageGenProviderSections({ mediaTab, setMediaTab, form,<option key={id} value={id}>{id}</option>))}</select>+ {codexModelsState === 'error' && (+ <ListLoadError what="your Codex provider's models" error={codexModelsError} onRetry={retryCodexModels} className="mt-1" />+ )}<p className="text-xs text-gray-500 mt-1">Passed as <code>codex exec -m <model></code>. Leave on Default for the cheap shipped model (<code>{CODEX_IMAGEGEN_DEFAULT_MODEL}</code>). Models come from your Codex provider.</p></FormField><FormField label="Reasoning effort (optional)" labelClassName={FIELD_LABEL_CLASS}>diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsxindex 759b58212d..9b3b900c10 100644--- a/client/src/components/settings/ImageGenTab.test.jsx+++ b/client/src/components/settings/ImageGenTab.test.jsx@@ -375,6 +375,21 @@ describe('ImageGenTab grouped tabs', () => {expect(sentSlices()['imageGen.codex']).toEqual({ model: 'gpt-6-sol' });});+ it('shows a retryable error, not a bare default-only picker, when the Codex provider read fails', async () => {+ getSettings.mockResolvedValue({+ imageGen: { mode: 'codex', codex: { enabled: true }, expose: { a1111: false } },+ });+ getProviders.mockRejectedValueOnce(new Error('providers down'));+ await renderTab(['/media/image?mediaTab=codex']);++ expect(await screen.findByText(/Could not load your Codex provider's models/)).toBeTruthy();+ expect(screen.queryByRole('option', { name: 'gpt-6-sol' })).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('option', { name: 'gpt-6-sol' })).toBeTruthy();+ expect(screen.queryByText(/Could not load your Codex provider's models/)).toBeNull();+ });+it('pins the install-wide default local model and saves it under imageGen.local.modelId', async () => {await renderTab(['/media/image?mediaTab=local']);await act(async () => {});diff --git a/client/src/components/settings/SecurityTab.jsx b/client/src/components/settings/SecurityTab.jsxindex b434e3bbfb..c9ebdae269 100644--- a/client/src/components/settings/SecurityTab.jsx+++ b/client/src/components/settings/SecurityTab.jsx@@ -4,10 +4,15 @@ import toast from '../ui/Toast';import Banner from '../ui/Banner';import FormField from '../ui/FormField';import BrailleSpinner from '../BrailleSpinner';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import AgentKeyCard from './AgentKeyCard';import { getAuthStatus, setAuthPassword, clearAuthPassword, listAuthSessions, revokeAuthSession, revokeAllAgentSessions } from '../../services/api';import { formatDateShort } from '../../utils/formatters';+const fetchAgentSessions = () => listAuthSessions({ silent: true })+ .then((res) => (Array.isArray(res?.sessions) ? res.sessions : []).filter((s) => s?.label === 'agent'));+// PortOS is single-user and normally trusted because it's tailnet-only — auth// here is opt-in defense against an attacker on the same network (a sidecar// on the same tailnet, an unattended workstation). When off, every request@@ -25,11 +30,14 @@ export function SecurityTab() {const [disablePassword, setDisablePassword] = useState('');const [disabling, setDisabling] = useState(false);const statusRequestRef = useRef(0);- const [agentSessions, setAgentSessions] = useState([]);const [revokingId, setRevokingId] = useState(null);const [confirmRevokeAll, setConfirmRevokeAll] = useState(false);const [revokingAll, setRevokingAll] = useState(false);- const sessionsRequestRef = useRef(0);+ // Sessions only exist while auth is on (agentApiAuth only mints a token when+ // isAuthEnabled(), and disabling clears every session) — skip the fetch otherwise.+ const {+ items: agentSessions, state: sessionsState, error: sessionsError, retry: loadSessions, setItems: setAgentSessions,+ } = useListResource(fetchAgentSessions, { enabled: !!enabled });const loadAuthStatus = useCallback(() => {const requestId = ++statusRequestRef.current;@@ -57,32 +65,6 @@ export function SecurityTab() {loadAuthStatus();}, [loadAuthStatus]);- const loadSessions = useCallback(() => {- if (!enabled) {- setAgentSessions([]);- return;- }- const requestId = ++sessionsRequestRef.current;- listAuthSessions({ silent: true })- .then((res) => {- if (requestId !== sessionsRequestRef.current) return;- const sessions = Array.isArray(res?.sessions) ? res.sessions : [];- setAgentSessions(sessions.filter((s) => s?.label === 'agent'));- })- // Listing is a nice-to-have here — a failed fetch just hides the panel- // rather than blocking the password form above it.- .catch(() => {- if (requestId === sessionsRequestRef.current) setAgentSessions([]);- });- }, [enabled]);-- // Sessions only exist while auth is on (agentApiAuth only mints a token- // when isAuthEnabled(), and disabling clears every session) — skip the- // fetch otherwise, and drop any list left over from a prior enabled state.- useEffect(() => {- loadSessions();- }, [loadSessions]);-const handleRevokeSession = async (id) => {setRevokingId(id);const result = await revokeAuthSession(id).catch((err) => err);@@ -104,8 +86,6 @@ export function SecurityTab() {toast.error(result.message || 'Revoke failed');return;}- // Invalidate any in-flight list fetch so it can't resurrect revoked rows.- sessionsRequestRef.current += 1;setConfirmRevokeAll(false);setAgentSessions([]);toast.success(`Revoked ${result?.revoked ?? 0} agent session${result?.revoked === 1 ? '' : 's'}`);@@ -315,6 +295,10 @@ export function SecurityTab() {{enabled && <AgentKeyCard />}+ {enabled && sessionsState === 'error' && (+ <ListLoadError what="agent sessions" error={sessionsError} onRetry={loadSessions} />+ )}+{enabled && agentSessions.length > 0 && (<div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"><div className="flex flex-wrap items-center justify-between gap-2">diff --git a/client/src/components/settings/SecurityTab.test.jsx b/client/src/components/settings/SecurityTab.test.jsxindex efe2c5962a..0b037c950d 100644--- a/client/src/components/settings/SecurityTab.test.jsx+++ b/client/src/components/settings/SecurityTab.test.jsx@@ -221,6 +221,24 @@ describe('SecurityTab', () => {expect(api.listAuthSessions).toHaveBeenCalledTimes(2);});+ it('reports a failed agent-session read with Retry instead of hiding the revoke panel', async () => {+ api.getAuthStatus.mockResolvedValue({ enabled: true });+ api.listAuthSessions+ .mockRejectedValueOnce(new Error('sessions down'))+ .mockResolvedValueOnce({+ sessions: [{ id: 'agent-1', label: 'agent', expiresAt: Date.parse('2026-10-01T00:00:00Z') }],+ });++ render(<SecurityTab />);++ expect(await screen.findByText(/Could not load agent sessions/)).toBeInTheDocument();+ expect(screen.queryByText(/agent session\b/)).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('1 agent session')).toBeInTheDocument();+ expect(screen.queryByText(/Could not load agent sessions/)).not.toBeInTheDocument();+ });+it('hides the sessions panel when auth is disabled', async () => {api.getAuthStatus.mockResolvedValue({ enabled: false });diff --git a/client/src/components/songbook/SongLinks.jsx b/client/src/components/songbook/SongLinks.jsxindex 59dd9b590e..0e6c0f856b 100644--- a/client/src/components/songbook/SongLinks.jsx+++ b/client/src/components/songbook/SongLinks.jsx@@ -16,14 +16,20 @@* renamed round shouldn't read stale), and falls back to the stored label.*/-import { useState, useEffect, useMemo } from 'react';+import { useState, useMemo } from 'react';import { Link } from 'react-router';import { Link2, Plus, X } from 'lucide-react';import { listRounds, listTracks } from '../../services/api';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import {SONG_LINK_TYPES, songLinkHref, songLinkKey, songLinkTypeLabel, inputClass, labelClass,} from './constants';+// The editor owns the error UI, so the requests are silent.+const fetchRounds = () => listRounds({ silent: true }).then((res) => res?.rounds);+const fetchTracks = () => listTracks({ silent: true });+// What a chip/row shows: the target's current title when we can see it, else the// label captured when the link was made, else the raw id (never blank).const linkText = (link, freshTitle) => freshTitle || link.label || link.id;@@ -73,29 +79,14 @@ export function SongLinkChips({ links, className = '' }) {}export function SongLinksEditor({ links, onChange }) {- // null = not fetched yet (or the fetch failed) vs [] = fetched and this- // install genuinely has no records of that kind — the two must not collapse,- // or an empty install reads as "still loading" forever.- const [rounds, setRounds] = useState(null);- const [tracks, setTracks] = useState(null);+ // A rounds/tracks outage must not block editing the SONG, so a failed read+ // shows a retryable error for that kind instead of "none available".+ const rounds = useListResource(fetchRounds);+ const tracks = useListResource(fetchTracks);const [type, setType] = useState(SONG_LINK_TYPES[0].id);const [targetId, setTargetId] = useState('');- // Both lists load once when the editor mounts. `.catch` swallows the failure- // on purpose — a rounds/tracks outage must not block editing the SONG, and- // request() already toasted, so `{ silent: true }` keeps it to one toast.- useEffect(() => {- let alive = true;- listRounds({ silent: true })- .then((res) => { if (alive) setRounds(Array.isArray(res?.rounds) ? res.rounds : []); })- .catch(() => { if (alive) setRounds([]); });- listTracks({ silent: true })- .then((res) => { if (alive) setTracks(Array.isArray(res) ? res : []); })- .catch(() => { if (alive) setTracks([]); });- return () => { alive = false; };- }, []);-- const recordsByType = useMemo(() => ({ round: rounds, track: tracks }), [rounds, tracks]);+ const recordsByType = useMemo(() => ({ round: rounds.items, track: tracks.items }), [rounds.items, tracks.items]);// Options for the currently selected type, minus anything already linked.const linked = useMemo(() => new Set(links.map(songLinkKey)), [links]);@@ -128,7 +119,8 @@ export function SongLinksEditor({ links, onChange }) {// {type,id} twice, and filtering on identity would delete both at once.const remove = (index) => onChange(links.filter((_, i) => i !== index));- const loading = recordsByType[type] === null;+ const { state, error, retry } = type === 'track' ? tracks : rounds;+ const loading = state === 'loading';return (<div>@@ -177,11 +169,11 @@ export function SongLinksEditor({ links, onChange }) {id="song-link-target"value={targetId}onChange={(e) => setTargetId(e.target.value)}- disabled={loading || options.length === 0}+ disabled={state !== 'ready' || options.length === 0}className={inputClass}><option value="">- {loading ? 'Loading…' : options.length === 0 ? `No ${songLinkTypeLabel(type).toLowerCase()}s available` : 'Select…'}+ {loading ? 'Loading…' : state === 'error' ? 'Unavailable' : options.length === 0 ? `No ${songLinkTypeLabel(type).toLowerCase()}s available` : 'Select…'}</option>{options.map((o) => <option key={o.id} value={o.id}>{o.title}</option>)}</select>@@ -196,6 +188,9 @@ export function SongLinksEditor({ links, onChange }) {Add link</button></div>+ {state === 'error' && (+ <ListLoadError what={`${songLinkTypeLabel(type).toLowerCase()}s`} error={error} onRetry={retry} className="mt-2" />+ )}</div>);}diff --git a/client/src/components/songbook/SongLinks.test.jsx b/client/src/components/songbook/SongLinks.test.jsxindex f3ca0ebbbe..e13b0c9702 100644--- a/client/src/components/songbook/SongLinks.test.jsx+++ b/client/src/components/songbook/SongLinks.test.jsx@@ -132,4 +132,23 @@ describe('SongLinksEditor', () => {await waitFor(() => expect(target.textContent).toContain('No rounds available'));expect(target.disabled).toBe(true);});++ it('shows a retryable error per kind, not "none available", when a list read fails', async () => {+ api.listRounds.mockRejectedValueOnce(new Error('rounds down'));+ renderEditor([]);++ expect(await screen.findByText(/Could not load rounds/)).toBeTruthy();+ const target = screen.getByLabelText('Record to link');+ expect(target.textContent).not.toContain('No rounds available');+ expect(target.disabled).toBe(true);++ // The healthy kind is unaffected by the other kind's outage.+ fireEvent.change(screen.getByLabelText('Link type'), { target: { value: 'track' } });+ await waitFor(() => expect(screen.queryByText(/Could not load/)).toBeNull());+ expect(within(screen.getByLabelText('Record to link')).getByRole('option', { name: 'Example Track' })).toBeTruthy();++ fireEvent.change(screen.getByLabelText('Link type'), { target: { value: 'round' } });+ fireEvent.click(await screen.findByRole('button', { name: 'Retry' }));+ expect(await within(screen.getByLabelText('Record to link')).findByRole('option', { name: 'Example Round' })).toBeTruthy();+ });});diff --git a/client/src/components/sprites/SpriteReferencePicker.jsx b/client/src/components/sprites/SpriteReferencePicker.jsxindex 07982e9087..9e911bd068 100644--- a/client/src/components/sprites/SpriteReferencePicker.jsx+++ b/client/src/components/sprites/SpriteReferencePicker.jsx@@ -9,26 +9,20 @@import { useEffect, useMemo, useState } from 'react';import { Search, X, RefreshCw } from 'lucide-react';import Modal from '../ui/Modal';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import SpritePreview from './SpritePreview.jsx';import { listSpriteReferenceSources } from '../../services/apiSprites.js';+const fetchSources = () => listSpriteReferenceSources({ silent: true });+export default function SpriteReferencePicker({ open, onClose, onSelect, excludeId }) {- const [items, setItems] = useState([]);- const [loading, setLoading] = useState(false);const [query, setQuery] = useState('');+ // Refetch each open so a sprite whose main was just locked shows up.+ const { items, state, error, retry } = useListResource(fetchSources, { enabled: open });- // Refetch each open so a sprite whose main was just locked shows up; reset the- // search on close so a re-open starts clean.- useEffect(() => {- if (!open) { setQuery(''); return undefined; }- let cancelled = false;- setLoading(true);- listSpriteReferenceSources({ silent: true })- .then((list) => { if (!cancelled) setItems(Array.isArray(list) ? list : []); })- .catch(() => { if (!cancelled) setItems([]); })- .finally(() => { if (!cancelled) setLoading(false); });- return () => { cancelled = true; };- }, [open]);+ // Reset the search on close so a re-open starts clean.+ useEffect(() => { if (!open) setQuery(''); }, [open]);const filtered = useMemo(() => {const pool = items.filter((it) => it.id !== excludeId);@@ -81,10 +75,12 @@ export default function SpriteReferencePicker({ open, onClose, onSelect, exclude</div><div className="flex-1 overflow-y-auto p-3">- {loading ? (+ {state === 'loading' ? (<div className="flex items-center justify-center gap-2 text-xs text-gray-400 py-10"><RefreshCw className="w-4 h-4 animate-spin" /> Loading reference sprites…</div>+ ) : state === 'error' ? (+ <ListLoadError what="reference sprites" error={error} onRetry={retry} />) : filtered.length === 0 ? (<div className="text-xs text-gray-500 py-10 text-center">{items.length === 0diff --git a/client/src/components/sprites/SpriteReferencePicker.test.jsx b/client/src/components/sprites/SpriteReferencePicker.test.jsxindex c6488a93f7..b3a7a44d53 100644--- a/client/src/components/sprites/SpriteReferencePicker.test.jsx+++ b/client/src/components/sprites/SpriteReferencePicker.test.jsx@@ -111,10 +111,15 @@ describe('SpriteReferencePicker', () => {expect(await screen.findByText(/No sprites with a locked main reference yet/)).toBeInTheDocument();});- it('falls back to an empty list when the fetch fails', async () => {- listSpriteReferenceSources.mockRejectedValue(new Error('offline'));+ it('reports a failed fetch with Retry instead of claiming nothing is locked', async () => {+ listSpriteReferenceSources.mockRejectedValueOnce(new Error('offline'));renderPicker();- expect(await screen.findByText(/No sprites with a locked main reference yet/)).toBeInTheDocument();+ expect(await screen.findByRole('alert')).toHaveTextContent(/Could not load reference sprites/);+ expect(screen.queryByText(/No sprites with a locked main reference yet/)).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Field Medic')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();});it('refetches on each open and resets the search on close', async () => {diff --git a/client/src/components/threads/AddToThreadButton.jsx b/client/src/components/threads/AddToThreadButton.jsxindex f5aa0c9894..a5d2ef0e23 100644--- a/client/src/components/threads/AddToThreadButton.jsx+++ b/client/src/components/threads/AddToThreadButton.jsx@@ -15,12 +15,19 @@ import { ListTodo, X } from 'lucide-react';import * as api from '../../services/api';import toast from '../ui/Toast';import EntityCombobox from '../EntityCombobox';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import useClickOutside from '../../hooks/useClickOutside';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition';import useEscapeKey from '../../hooks/useEscapeKey.js';import useFocusTrap from '../../hooks/useFocusTrap.js';import { THREAD_ACTIVE_STATUSES } from '../../lib/brainThreads';+const ACTIVE_THREAD_STATUS = THREAD_ACTIVE_STATUSES.join(',');++const fetchActiveThreads = () => api.listThreads({ status: ACTIVE_THREAD_STATUS }, { silent: true })+ .then((res) => (Array.isArray(res?.threads) ? res.threads : Array.isArray(res) ? res : []));+export default function AddToThreadButton({refItem,threadRef,@@ -37,10 +44,11 @@ export default function AddToThreadButton({tooltip}) {const [open, setOpen] = useState(false);- const [threads, setThreads] = useState([]);- const [loading, setLoading] = useState(false);const [attaching, setAttaching] = useState(false);const [query, setQuery] = useState('');+ // Match-or-create needs the real thread list: a failed read must not offer "No open threads yet" and invite a duplicate.+ const { items: threads, state: threadsState, error: threadsError, retry: retryThreads } = useListResource(fetchActiveThreads, { enabled: open });+ const loading = threadsState === 'loading';const computedRef = useMemo(() => {const base = refItem || threadRef;@@ -55,25 +63,6 @@ export default function AddToThreadButton({};}, [refItem, threadRef, kind, id, label, title]);- useEffect(() => {- if (!open) return;- let active = true;- setLoading(true);- api.listThreads({ status: THREAD_ACTIVE_STATUSES.join(',') }, { silent: true })- .then((res) => {- if (!active) return;- const list = Array.isArray(res?.threads) ? res.threads : Array.isArray(res) ? res : [];- setThreads(list);- })- .catch(() => {- if (active) setThreads([]);- })- .finally(() => {- if (active) setLoading(false);- });- return () => { active = false; };- }, [open]);-const comboboxItems = useMemo(() => {return threads.map((t) => ({id: t.id,@@ -87,7 +76,7 @@ export default function AddToThreadButton({width: 320,minWidth: 260,position: 'below',- contentDeps: [comboboxItems.length, loading, attaching]+ contentDeps: [comboboxItems.length, threadsState, attaching]});const menuVisible = open && Boolean(menuStyle);@@ -194,20 +183,24 @@ export default function AddToThreadButton({)}<label htmlFor="add-to-thread-search" className="sr-only">Search threads</label>- <EntityCombobox- items={comboboxItems}- value={query}- onChange={setQuery}- onPick={handlePick}- onCreate={handleCreate}- busy={loading || attaching}- inputId="add-to-thread-search"- noun="thread"- placeholder="Search open threads or type name…"- createPrefix="New thread"- emptyNoItems="No open threads yet — type a name to create one."- className="w-full"- />+ {threadsState === 'error' ? (+ <ListLoadError what="your open threads" error={threadsError} onRetry={retryThreads} />+ ) : (+ <EntityCombobox+ items={comboboxItems}+ value={query}+ onChange={setQuery}+ onPick={handlePick}+ onCreate={handleCreate}+ busy={loading || attaching}+ inputId="add-to-thread-search"+ noun="thread"+ placeholder="Search open threads or type name…"+ createPrefix="New thread"+ emptyNoItems="No open threads yet — type a name to create one."+ className="w-full"+ />+ )}</div>,document.body)}diff --git a/client/src/components/threads/AddToThreadButton.test.jsx b/client/src/components/threads/AddToThreadButton.test.jsxindex dac4b90ae1..d18ef0fc52 100644--- a/client/src/components/threads/AddToThreadButton.test.jsx+++ b/client/src/components/threads/AddToThreadButton.test.jsx@@ -58,12 +58,11 @@ describe('AddToThreadButton', () => {const btn = screen.getByRole('button', { name: 'Add to Brain thread' });fireEvent.click(btn);- expect(api.listThreads).toHaveBeenCalledWith(- { status: 'open,waiting,someday' },- { silent: true }- );-await waitFor(() => {+ expect(api.listThreads).toHaveBeenCalledWith(+ { status: 'open,waiting,someday' },+ { silent: true }+ );expect(screen.getByText('Add to Brain thread')).toBeInTheDocument();expect(screen.getByText('Attaching:')).toBeInTheDocument();expect(screen.getByText('#100 Fix widget layout')).toBeInTheDocument();@@ -221,6 +220,22 @@ describe('AddToThreadButton', () => {});});+ it('shows a retryable error instead of the "No open threads yet" create hint when the list read fails', async () => {+ api.listThreads.mockRejectedValueOnce(new Error('brain down'));+ render(<AddToThreadButton threadRef={sampleRef} />);+ fireEvent.click(screen.getByRole('button', { name: 'Add to Brain thread' }));++ expect(await screen.findByText(/Could not load your open threads/)).toBeInTheDocument();+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();+ expect(screen.queryByText(/No open threads yet/)).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ const input = await screen.findByRole('combobox');+ fireEvent.focus(input);+ expect(await screen.findByText('Sprint planning')).toBeInTheDocument();+ expect(screen.queryByText(/Could not load your open threads/)).not.toBeInTheDocument();+ });+it('closes popover on Close button click', async () => {render(<AddToThreadButton threadRef={sampleRef} />);fireEvent.click(screen.getByRole('button', { name: 'Add to Brain thread' }));diff --git a/client/src/components/ui/ProcessLogModal.jsx b/client/src/components/ui/ProcessLogModal.jsxindex 9ab3721874..2ac5392c46 100644--- a/client/src/components/ui/ProcessLogModal.jsx+++ b/client/src/components/ui/ProcessLogModal.jsx@@ -15,6 +15,8 @@ import { useState, useEffect, useCallback, useRef } from 'react';import { RefreshCw, X } from 'lucide-react';import Modal from './Modal';import BrailleSpinner from '../BrailleSpinner';+import ListLoadError from './ListLoadError';+import useListResource from '../../hooks/useListResource';import * as api from '../../services/api';import { copyToClipboard } from '../../lib/clipboard';@@ -22,8 +24,10 @@ import { copyToClipboard } from '../../lib/clipboard';// renders a matching option on open rather than a mismatched first entry.const TAIL_OPTIONS = [100, 200, 500, 1000, 2000];+const fetchProcesses = () => api.getProcessesList({ silent: true })+ .then((list) => (Array.isArray(list) ? list : []));+export default function ProcessLogModal({ open, onClose, processName, title = 'System Logs' }) {- const [processes, setProcesses] = useState([]);const [selected, setSelected] = useState(processName || '');const [tailLines, setTailLines] = useState(200);const [logs, setLogs] = useState('');@@ -42,15 +46,8 @@ export default function ProcessLogModal({ open, onClose, processName, title = 'SsetError('');}, [open, processName]);- // Load the PM2 process picker options once per open (static across a session).- useEffect(() => {- if (!open) return;- let cancelled = false;- api.getProcessesList({ silent: true })- .then((list) => { if (!cancelled) setProcesses(Array.isArray(list) ? list : []); })- .catch(() => { if (!cancelled) setProcesses([]); });- return () => { cancelled = true; };- }, [open]);+ // PM2 process picker options, reloaded per open.+ const { items: processes, state: processesState, error: processesError, retry: retryProcesses } = useListResource(fetchProcesses, { enabled: open });const loadLogs = useCallback(async () => {if (!selected) return;@@ -142,6 +139,9 @@ export default function ProcessLogModal({ open, onClose, processName, title = 'S</button></div></div>+ {processesState === 'error' && (+ <ListLoadError what="the process list" error={processesError} onRetry={retryProcesses} className="mx-4 sm:mx-6 my-2" />+ )}<div className="flex-1 overflow-auto bg-port-bg p-3 sm:p-4 min-h-[16rem]">{loading && !logs ? (<BrailleSpinner text="Loading logs" />diff --git a/client/src/components/ui/ProcessLogModal.test.jsx b/client/src/components/ui/ProcessLogModal.test.jsxindex 0107c17a26..b6e9e074f6 100644--- a/client/src/components/ui/ProcessLogModal.test.jsx+++ b/client/src/components/ui/ProcessLogModal.test.jsx@@ -79,6 +79,18 @@ describe('ProcessLogModal', () => {expect(await screen.findByText('daemon down')).toBeInTheDocument();});+ it('reports a failed process-list read with Retry instead of silently offering only the hinted process', async () => {+ getProcessesList.mockRejectedValueOnce(new Error('pm2 unreachable'));+ render(<ProcessLogModal open onClose={() => {}} processName="portos-server" />);++ expect(await screen.findByText(/Could not load the process list/)).toBeInTheDocument();+ expect(screen.queryByRole('option', { name: 'portos-cos' })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByRole('option', { name: 'portos-cos' })).toBeInTheDocument();+ expect(screen.queryByText(/Could not load the process list/)).not.toBeInTheDocument();+ });+it('keeps the hinted process selectable even when PM2 does not report it', async () => {getProcessesList.mockResolvedValueOnce([{ name: 'portos-cos' }]);render(<ProcessLogModal open onClose={() => {}} processName="portos-server" />);diff --git a/client/src/components/videoGen/GalleryVideoPicker.jsx b/client/src/components/videoGen/GalleryVideoPicker.jsxindex b493d48673..2c06df6853 100644--- a/client/src/components/videoGen/GalleryVideoPicker.jsx+++ b/client/src/components/videoGen/GalleryVideoPicker.jsx@@ -19,10 +19,16 @@ import { normalizeVideo } from '../media/normalize';import { listVideoHistory, uploadGalleryVideo } from '../../services/apiImageVideo';import { uploadFile } from '../../services/apiMedia';import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';+import useListResource from '../../hooks/useListResource';+import ListLoadError from '../ui/ListLoadError';import toast from '../ui/Toast';const VIDEO_ACCEPT = 'video/mp4,video/webm,video/quicktime,video/x-m4v,.mp4,.webm,.mov,.m4v';+const fetchVideoItems = () => listVideoHistory({ silent: true }).then((videos) => (+ (Array.isArray(videos) ? videos : []).map(normalizeVideo).filter((it) => !it.hidden)+));+export default function GalleryVideoPicker({open,onClose,@@ -31,8 +37,7 @@ export default function GalleryVideoPicker({uploadToGallery = false,accept = VIDEO_ACCEPT,}) {- const [items, setItems] = useState([]);- const [loading, setLoading] = useState(false);+ const { items, state, error, retry } = useListResource(fetchVideoItems, { enabled: open });const [uploading, setUploading] = useState(false);const [query, setQuery] = useState('');// Invalidate on every open/close transition and on unmount. A host can@@ -49,20 +54,7 @@ export default function GalleryVideoPicker({}, [open]);useEffect(() => {- if (!open) { setQuery(''); return undefined; }- let cancelled = false;- setLoading(true);- listVideoHistory()- .then((videos) => {- if (cancelled) return;- const normalized = (Array.isArray(videos) ? videos : [])- .map(normalizeVideo)- .filter((it) => !it.hidden);- setItems(normalized);- })- .catch(() => { if (!cancelled) setItems([]); })- .finally(() => { if (!cancelled) setLoading(false); });- return () => { cancelled = true; };+ if (!open) setQuery('');}, [open]);const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);@@ -167,10 +159,12 @@ export default function GalleryVideoPicker({</div><div className="flex-1 overflow-y-auto p-3">- {loading ? (+ {state === 'loading' ? (<div className="flex items-center justify-center gap-2 text-xs text-gray-400 py-10"><RefreshCw className="w-4 h-4 animate-spin" /> Loading videos…</div>+ ) : state === 'error' ? (+ <ListLoadError what="your video gallery" error={error} onRetry={retry} />) : filtered.length === 0 ? (<div className="text-xs text-gray-500 py-10 text-center">{items.length === 0 ? 'No videos in your gallery yet.' : 'No videos match your search.'}diff --git a/client/src/components/videoGen/GalleryVideoPicker.test.jsx b/client/src/components/videoGen/GalleryVideoPicker.test.jsxindex 8fe4157c7f..34e6750136 100644--- a/client/src/components/videoGen/GalleryVideoPicker.test.jsx+++ b/client/src/components/videoGen/GalleryVideoPicker.test.jsx@@ -54,6 +54,18 @@ describe('GalleryVideoPicker', () => {expect(onClose).toHaveBeenCalled();});+ it('shows a load error with Retry instead of the empty copy when the history read fails', async () => {+ listVideoHistory.mockRejectedValueOnce(new Error('History unavailable'));+ render(<GalleryVideoPicker open onClose={vi.fn()} onSelect={vi.fn()} />);++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load your video gallery — History unavailable');+ expect(screen.queryByText('No videos in your gallery yet.')).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('a neon chase')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+ });+it('uploads into the gallery and selects the normalized entry with uploadToGallery (#4188)', async () => {uploadGalleryVideo.mockResolvedValue({id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4', thumbnail: 'upload-ab12cd34.jpg', source: 'upload',diff --git a/client/src/listFetchConventions.test.js b/client/src/listFetchConventions.test.jsindex 514a8c0e13..e9448ef00c 100644--- a/client/src/listFetchConventions.test.js+++ b/client/src/listFetchConventions.test.js@@ -73,36 +73,6 @@ const KNOWN = Object.freeze({// Named-parameter, multi-statement spelling (#12807); migrated under #12819.'src/components/loraTraining/CharacterLoraChip.jsx': 1,'src/components/meatspace/post/MemoryPractice.jsx': 1,- // Spellings the widened pattern (#12790) newly sees; migrated under #12804.- 'src/components/CmdKSearch.jsx': 1,- 'src/components/TagPicker.jsx': 1,- 'src/components/apps/LaunchVideoPanel.jsx': 1,- 'src/components/apps/tabs/OverviewTab.jsx': 1,- 'src/components/cos/tabs/MemoryRunsUsedBy.jsx': 1,- 'src/components/eidoverse/EidoverseTravel.jsx': 1,- 'src/components/media/RigPanel.jsx': 1,- 'src/components/messages/MessageDetail.jsx': 1,- 'src/components/music/ArtistPicker.jsx': 1,- 'src/components/musicVideo/CharacterStyleSelect.jsx': 1,- 'src/components/musicVideo/ExistingSongSelect.jsx': 1,- 'src/components/musicVideo/PromotionPlanPanel.jsx': 1,- 'src/components/pipeline/AuthorPicker.jsx': 1,- 'src/components/pipeline/SeriesLoomsPanel.jsx': 1,- 'src/components/pipeline/stages/EpisodeVideoStage.jsx': 1,- 'src/components/privacy/OrgDrawer.jsx': 1,- 'src/components/providers/ProviderServiceForm.jsx': 1,- 'src/components/settings/ImageGenProviderSections.jsx': 1,- 'src/components/settings/SecurityTab.jsx': 1,- 'src/components/songbook/SongLinks.jsx': 2,- 'src/components/sprites/SpriteReferencePicker.jsx': 1,- 'src/components/threads/AddToThreadButton.jsx': 1,- 'src/components/ui/ProcessLogModal.jsx': 1,- 'src/components/videoGen/GalleryVideoPicker.jsx': 1,- 'src/pages/Instances.jsx': 1,- 'src/pages/OpenClaw.jsx': 1,- 'src/pages/PipelineEditorialChecks.jsx': 2,- 'src/pages/PipelineExport.jsx': 1,- 'src/pages/Tribe.jsx': 3,});/**@@ -117,6 +87,14 @@ const EXEMPT = Object.freeze({// SYSTEM_STAGE_PROTECTED guard answer. The empty `usedBy`/`referencedBy` feed// a delete-confirm prompt, not a library listing, so no "you have none" copy.'src/pages/PromptManager.jsx': 1,+ // Canon-entity linkify lookup: a failed universe read just shows no entity chips+ // on findings (the findings themselves render, and nothing says "no canon exists");+ // nothing writes from it.+ 'src/pages/PipelineEditorialChecks.jsx': 1,+ // Tag typeahead: a failed lookup shows no suggestions, freeform tags are accepted+ // regardless (the server normalizes and creates the canonical row on save), and+ // nothing says "no tags exist" or writes from the suggestion list.+ 'src/components/TagPicker.jsx': 1,});const allowedIn = (file) => (KNOWN[file] || 0) + (EXEMPT[file] || 0);diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex e600109a32..ab0a5865ad 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -33,6 +33,7 @@ import PeerSyncSecretEditor from '../components/instances/PeerSyncSecretEditor';import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';+import ListLoadError from '../components/ui/ListLoadError';import { DEFAULT_PEER_PORT, DEFAULT_TAILCAT_LOCAL_PORT, DEFAULT_TAILCAT_REMOTE_PORT } from '../lib/ports.js';import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';import PeerAdministrationPanel from '../components/instances/PeerAdministrationPanel';@@ -1220,6 +1221,10 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReporconst [confirmRemove, setConfirmRemove] = useState(false);// Outbound subscriptions inform per-record schema compatibility.const [peerSubs, setPeerSubs] = useState([]);+ // A failed read keeps the last good subscriptions and surfaces an error row,+ // so a hidden "peer is behind" warning is never mistaken for "no mismatch".+ const [peerSubsError, setPeerSubsError] = useState(null);+ const [peerSubsAttempt, setPeerSubsAttempt] = useState(0);// Live sync activity, driven by the `sync:progress` socket event. `syncing`// is true between this peer's `start` and `complete`; while it's true every// enabled category badge shows "syncing…". On `complete` it clears and the@@ -1256,15 +1261,18 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReporuseEffect(() => {if (!peer.instanceId) {setPeerSubs([]);+ setPeerSubsError(null);return;}let cancelled = false;const refetch = () => listPeerSubscriptions({ peerId: peer.instanceId }, { silent: true }).then((r) => {- if (!cancelled) setPeerSubs(r?.subscriptions || []);+ if (cancelled) return;+ setPeerSubs(r?.subscriptions || []);+ setPeerSubsError(null);})- .catch(() => {- if (!cancelled) setPeerSubs([]);+ .catch((err) => {+ if (!cancelled) setPeerSubsError(err instanceof Error ? err : new Error('Request failed'));});refetch();// When a per-record schema block is persisted server-side, the@@ -1295,7 +1303,7 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityReporsocket.off('peerSync:subscription-unblocked', handleSchemaSubChange);socket.off('peerSync:subscription:created', handleSchemaSubChange);};- }, [peer.instanceId]);+ }, [peer.instanceId, peerSubsAttempt]);const StatusIcon = STATUS_ICONS[peer.status] || CircleDot;const isInboundOnly = peer.directions?.includes('inbound') && !peer.directions?.includes('outbound');@@ -1526,6 +1534,14 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityRepor)}<SchemaGapBadge peer={peer} peerSubs={peerSubs} />+ {peerSubsError && (+ <ListLoadError+ what="subscriptions used for schema-compatibility warnings"+ error={peerSubsError}+ onRetry={() => setPeerSubsAttempt((n) => n + 1)}+ className="mt-2"+ />+ )}<PeerMediaProviderPanel peer={peer} onRefresh={onRefresh} /><PeerAdministrationPanel peer={peer} />diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsxindex ccb3f12f27..133845a93e 100644--- a/client/src/pages/Instances.test.jsx+++ b/client/src/pages/Instances.test.jsx@@ -329,6 +329,25 @@ describe('PeerCard snapshot progress', () => {expect(badge('Pipeline').getByText('synced')).toBeInTheDocument();});+ it('flags a failed subscription read with Retry instead of hiding schema warnings, then shows the gap after Retry', async () => {+ listPeerSubscriptions.mockRejectedValueOnce(new Error('Subscriptions unavailable'));+ renderUI(<PeerCard peer={peer} syncStatus={syncStatus} onRefresh={vi.fn()} />);++ expect(await screen.findByRole('alert')).toHaveTextContent('Subscriptions unavailable');+ expect(screen.queryByText('Schema version mismatch')).not.toBeInTheDocument();++ listPeerSubscriptions.mockResolvedValueOnce({+ subscriptions: [{+ recordKind: 'universe', recordId: 'universe-1', peerId: peer.instanceId,+ blockedBySchema: { ahead: [], behind: ['universe'], peerPortosVersion: '1.0.0' },+ }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByText('Schema version mismatch')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });+// Active sync takes precedence until the user-triggered request completes.it('shows syncing ahead of checksum status and restores status on completion', async () => {let resolveSync;diff --git a/client/src/pages/OpenClaw.jsx b/client/src/pages/OpenClaw.jsxindex d58dc2d404..fd7fe1b6f1 100644--- a/client/src/pages/OpenClaw.jsx+++ b/client/src/pages/OpenClaw.jsx@@ -43,6 +43,11 @@ import { useOpenClawAttachments, OPENCLAW_ATTACHMENT_ACCEPT } from '../hooks/useimport { useOpenClawStream } from '../hooks/useOpenClawStream';import { modKey } from '../utils/platform';import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';+import useListResource from '../hooks/useListResource';+import ListLoadError from '../components/ui/ListLoadError';++const NO_APPS = Object.freeze([]);+const fetchActiveApps = () => coreApi.getApps({ silent: true }).then(data => (data || []).filter(app => !app.archived));function getRuntimeState(status, featureEnabled) {if (!featureEnabled || status?.featureEnabled === false) {@@ -131,7 +136,8 @@ export default function OpenClaw() {const featureEnabled = isFeatureEnabled('openclaw');const [status, setStatus] = useState(null);const [sessions, setSessions] = useState([]);- const [apps, setApps] = useState([]);+ const { items: loadedApps, state: appsState, error: appsError, retry: retryApps } = useListResource(fetchActiveApps, { enabled: featureEnabled });+ const apps = featureEnabled ? loadedApps : NO_APPS;const [selectedSessionId, setSelectedSessionId] = useState('');const [composer, setComposer] = useState('');const [context, setContext] = useState({@@ -274,16 +280,7 @@ export default function OpenClaw() {useEffect(() => {loadRuntime();- if (!featureEnabled) {- setApps([]);- return undefined;- }- let active = true;- coreApi.getApps()- .then(data => { if (active) setApps((data || []).filter(app => !app.archived)); })- .catch(() => { if (active) setApps([]); });- return () => { active = false; };- }, [featureEnabled, loadRuntime]);+ }, [loadRuntime]);useEffect(() => {selectedSessionIdRef.current = selectedSessionId;@@ -600,6 +597,10 @@ export default function OpenClaw() {{showContextFields ? <ChevronDown size={14} /> : <ChevronRight size={14} />}</button>+ {featureEnabled && appsState === 'error' && (+ <ListLoadError what="apps for context" error={appsError} onRetry={retryApps} className="mb-3" />+ )}+<div className={`mb-3 gap-3 md:grid-cols-2 xl:grid-cols-3 ${showContextFields ? 'grid' : 'hidden'}`}><AppContextPickerapps={apps}diff --git a/client/src/pages/OpenClaw.test.jsx b/client/src/pages/OpenClaw.test.jsxindex 417c5e885c..316109338c 100644--- a/client/src/pages/OpenClaw.test.jsx+++ b/client/src/pages/OpenClaw.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { act, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';const openClawApi = vi.hoisted(() => ({@@ -10,7 +11,8 @@ const openClawApi = vi.hoisted(() => ({}));vi.mock('../services/apiOpenClaw', () => openClawApi);-vi.mock('../services/api', () => ({ getApps: vi.fn(() => Promise.resolve([])) }));+const coreApi = vi.hoisted(() => ({ getApps: vi.fn() }));+vi.mock('../services/api', () => coreApi);vi.mock('../hooks/useInstanceFeatures.js', () => ({useInstanceFeatures: () => ({ isFeatureEnabled: () => true }),}));@@ -33,6 +35,7 @@ const renderPage = async () => {describe('OpenClaw page header', () => {beforeEach(() => {vi.clearAllMocks();+ coreApi.getApps.mockResolvedValue([]);openClawApi.getOpenClawStatus.mockResolvedValue({configured: true,enabled: true,@@ -66,3 +69,26 @@ describe('OpenClaw page header', () => {expect(bar).toContainElement(screen.getByRole('button', { name: /Refresh/ }));});});++describe('OpenClaw app context picker', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ openClawApi.getOpenClawStatus.mockResolvedValue({ configured: true, enabled: true, reachable: true, defaultSession: 'session-1' });+ openClawApi.getOpenClawSessions.mockResolvedValue({ sessions: [{ id: 'session-1', title: 'Example session' }] });+ openClawApi.getOpenClawMessages.mockResolvedValue({ messages: [] });+ });++ it('shows a load error with Retry when the app list fails, then offers the apps after Retry', async () => {+ coreApi.getApps.mockRejectedValueOnce(new Error('Apps unavailable'));+ await renderPage();++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load apps for context — Apps unavailable');+ expect(screen.queryByRole('option', { name: 'Example App' })).toBeNull();++ coreApi.getApps.mockResolvedValueOnce([{ id: 'app-1', name: 'Example App' }]);+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByRole('option', { name: 'Example App' })).toBeInTheDocument();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/pages/PipelineEditorialChecks.catalogError.test.jsx b/client/src/pages/PipelineEditorialChecks.catalogError.test.jsxindex f10509157a..a046b0aee8 100644--- a/client/src/pages/PipelineEditorialChecks.catalogError.test.jsx+++ b/client/src/pages/PipelineEditorialChecks.catalogError.test.jsx@@ -54,9 +54,9 @@ vi.mock('../components/ProviderModelSelector', () => ({ default: () => <div>provconst CHECK = { id: 'naming.dissimilar-names', label: 'Character name dissimilarity', scope: 'series', kind: 'deterministic', enabled: true };-function renderPage() {+function renderPage(search = '') {return render(- <MemoryRouter initialEntries={[`/pipeline/editorial-checks`]}>+ <MemoryRouter initialEntries={[`/pipeline/editorial-checks${search}`]}><PipelineEditorialChecks /></MemoryRouter>,);@@ -83,3 +83,27 @@ describe('PipelineEditorialChecks — failed catalog read', () => {expect(screen.queryByRole('alert')).toBeNull();});});++describe('PipelineEditorialChecks — failed findings read', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ listPipelineSeries.mockResolvedValue([{ id: 'ser-1', title: 'My Series' }]);+ getEditorialChecks.mockResolvedValue({ checks: [CHECK] });+ getEditorialChecksRunStatus.mockResolvedValue({ active: false });+ getEditorialHealth.mockResolvedValue(null);+ });++ it('shows a load error with Retry instead of the empty-findings copy, then loads the findings', async () => {+ getPipelineManuscriptReview.mockRejectedValueOnce(new Error('Review unavailable'));+ renderPage('?series=ser-1');+ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the findings for this series — Review unavailable');+ expect(screen.queryByText(/No findings/i)).toBeNull();++ getPipelineManuscriptReview.mockResolvedValueOnce({+ comments: [{ id: 'c1', checkId: CHECK.id, status: 'open', problem: 'Names too similar', location: 'Ch 1' }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText(/Names too similar/)).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsxindex 2e0d88423a..478242a424 100644--- a/client/src/pages/PipelineEditorialChecks.jsx+++ b/client/src/pages/PipelineEditorialChecks.jsx@@ -87,13 +87,21 @@ export default function PipelineEditorialChecks() {// severity saves have drained.const [severitySaveCount, setSeveritySaveCount] = useState(0);const seriesId = searchParams.get('series') || '';- const [comments, setComments] = useState([]);+ const fetchFindings = useCallback(+ () => (seriesId+ ? getPipelineManuscriptReview(seriesId, { silent: true }).then((review) => (Array.isArray(review?.comments) ? review.comments : []))+ : Promise.resolve([])),+ [seriesId],+ );+ const {+ items: comments, state: findingsState, error: findingsError, retry: reloadFindings, setItems: setComments,+ } = useListResource(fetchFindings);// Canon entities (#1631) for the selected series' linked universe, flattened to// a name→entity lookup so the triage can linkify entity references in findings.// Empty until a series with a universe is selected; load failures degrade to no// links (the findings still render).const [canonEntities, setCanonEntities] = useState([]);- const [loadingFindings, setLoadingFindings] = useState(false);+ const loadingFindings = !!seriesId && findingsState === 'loading';// Bumped whenever the findings are (re)loaded so the health panel refetches// its score/trend in lockstep — a run that seeds new findings also moves the// health score + records a trend snapshot server-side.@@ -181,35 +189,26 @@ export default function PipelineEditorialChecks() {}, [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- // the user has since navigated away from can't overwrite the new series'- // comments (which would also point the deep-links at the wrong series).+ // Tracks the currently-selected series so a queued save resolves against the+ // series it was issued for, not whichever is selected when it runs.const activeSeriesRef = useRef(seriesId);useEffect(() => { activeSeriesRef.current = seriesId; }, [seriesId]);- const loadFindings = useCallback((id) => {- // The session mute is local to the currently-shown findings: a series switch,- // a fresh load, or a run-completion reload resets it. This happened for free- // while the set lived in the triage (it unmounted during the loading state and- // remounted with empty local state); now that the parent owns it (#1697), reset- // it explicitly so a mute can't bleed across series or outlive a reload.- setHiddenCheckIds((s) => (s.size ? new Set() : s));- if (!id) { setComments([]); return; }- setLoadingFindings(true);- // Deliberately NOT silent: this caller owns no error UI of its own, so we- // let request()'s default toast be the single layer and just clear +- // swallow here. Guard every state write on the series still being current- // (stale-response race).- getPipelineManuscriptReview(id)- .then((review) => { if (activeSeriesRef.current === id) setComments(Array.isArray(review?.comments) ? review.comments : []); })- .catch(() => { if (activeSeriesRef.current === id) setComments([]); })- .finally(() => {- if (activeSeriesRef.current === id) {- setLoadingFindings(false);- setHealthRefresh((n) => n + 1); // re-pull the health score/trend in lockstep- }- });- }, []);+ // The session mute is local to the currently-shown findings: a series switch,+ // a fresh load, or a run-completion reload resets it. This happened for free+ // while the set lived in the triage (it unmounted during the loading state and+ // remounted with empty local state); now that the parent owns it (#1697), reset+ // it explicitly so a mute can't bleed across series or outlive a reload.+ const resetMutedChecks = useCallback(() => setHiddenCheckIds((s) => (s.size ? new Set() : s)), []);+ const loadFindings = useCallback(() => {+ resetMutedChecks();+ reloadFindings();+ }, [resetMutedChecks, reloadFindings]);++ // Re-pull the health score/trend in lockstep with every settled findings load.+ useEffect(() => {+ if (findingsState !== 'loading') setHealthRefresh((n) => n + 1);+ }, [findingsState]);// Inline accept/dismiss from the triage list (#1598) — replace the changed// comment in place (reactive update) and re-pull the health score/trend so the@@ -222,14 +221,14 @@ export default function PipelineEditorialChecks() {useEffect(() => {setRunActive(false);- if (!seriesId) { setComments([]); return; }- loadFindings(seriesId);+ resetMutedChecks();+ if (!seriesId) return undefined;let canceled = false;getEditorialChecksRunStatus(seriesId, { silent: true }).then((s) => { if (!canceled && s?.active) setRunActive(true); }).catch(() => {});return () => { canceled = true; };- }, [seriesId, loadFindings]);+ }, [seriesId, resetMutedChecks]);// ---- SSE progress for the active run (mirrors the manuscript editor). ----const { latest: runLatest, closed: runClosed } = usePipelineProgress(@@ -249,7 +248,7 @@ export default function PipelineEditorialChecks() {if (type !== 'complete' && type !== 'canceled' && type !== 'error') return;setRunActive(false);if (type === 'complete') {- loadFindings(seriesId);+ loadFindings();// #1573 — a check whose run() threw produced no findings; warn instead of a// silent "complete" so an always-erroring check isn't mistaken for clean.if (runLatest.errored > 0) {@@ -267,7 +266,7 @@ export default function PipelineEditorialChecks() {const t = runLatest?.type;if (t === 'complete' || t === 'canceled' || t === 'error') return; // handled abovesetRunActive(false);- loadFindings(seriesId);+ loadFindings();}, [runActive, runClosed, runLatest, seriesId]);// ---- Catalog mutations (reactive local updates; the API owns the toast).@@ -839,6 +838,8 @@ export default function PipelineEditorialChecks() {<EditorialHealthPanel seriesId={seriesId} refreshKey={healthRefresh} checksById={checksById} filterableCheckIds={triageFilterableCheckIds} filterableCategories={triageFilterableCategories} />{loadingFindings ? (<p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading findings…</p>+ ) : findingsState === 'error' ? (+ <ListLoadError what="the findings for this series" error={findingsError} onRetry={loadFindings} />) : (<EditorialFindingsTriage seriesId={seriesId} comments={comments} checksById={checksById} onCommentChange={handleCommentChange} hiddenCheckIds={hiddenCheckIds} onDisableCheck={disableCheck} onRunChecks={() => runChecks(null)} runDisabled={runDisabled || enabledCount === 0} universeId={universeId} canonEntities={canonEntities} />)}diff --git a/client/src/pages/PipelineExport.jsx b/client/src/pages/PipelineExport.jsxindex 7fbd9fccbe..72e6bf1d86 100644--- a/client/src/pages/PipelineExport.jsx+++ b/client/src/pages/PipelineExport.jsx@@ -10,7 +10,7 @@* first, mirroring the "Run Now gates on saved state" rule).*/-import { useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { Link, useParams, useNavigate } from 'react-router';import { Loader2, ArrowLeft, Download, Save, BookText, FileText, FileType } from 'lucide-react';import toast from '../components/ui/Toast';@@ -28,6 +28,8 @@ import {import { useAsyncAction } from '../hooks/useAsyncAction';import { normalizeImage, normalizeVideo } from '../components/media/normalize';import AttributionList from '../components/media/AttributionList';+import ListLoadError from '../components/ui/ListLoadError';+import useListResource from '../hooks/useListResource';import { TRIM_SIZES, DEFAULT_TRIM_SIZE, INTERIOR_FONTS, DEFAULT_INTERIOR_FONT } from '../lib/proseExportSettings.js';// Client labels for the server TRIM_SIZES and INTERIOR_FONTS (via@@ -90,7 +92,30 @@ export default function PipelineExport() {const [loading, setLoading] = useState(true);const [form, setForm] = useState(emptyForm);const [savedForm, setSavedForm] = useState(emptyForm);- const [seriesAssets, setSeriesAssets] = useState([]);+ // Roll up licenses from the series media collection so a user about to+ // publish can see the terms that applied when the pixels were made (#5638).+ const fetchSeriesAssets = useCallback(async () => {+ const [collections, videos] = await Promise.all([+ listMediaCollections({ silent: true }),+ listVideoHistory({ silent: true }),+ ]);+ const list = Array.isArray(collections) ? collections : [];+ const collection = list.find((c) => c.seriesId === seriesId || c.id === `sc-${seriesId}`);+ if (!collection) return [];+ const images = await getGalleryImages((collection.items || []).filter(item => item.kind === 'image').map(item => item.ref), { silent: true });+ const imagesByName = new Map((images || []).map((i) => [i.filename, i]));+ const videosById = new Map((videos || []).map((v) => [v.id, v]));+ const out = [];+ for (const it of collection.items || []) {+ if (it.kind === 'image' && imagesByName.has(it.ref)) {+ out.push(normalizeImage(imagesByName.get(it.ref)));+ } else if (it.kind === 'video' && videosById.has(it.ref)) {+ out.push(normalizeVideo(videosById.get(it.ref)));+ }+ }+ return out;+ }, [seriesId]);+ const { items: seriesAssets, state: assetsState, error: assetsError, retry: retryAssets } = useListResource(fetchSeriesAssets);useEffect(() => {let canceled = false;@@ -112,35 +137,6 @@ export default function PipelineExport() {return () => { canceled = true; };}, [seriesId, navigate]);- // Roll up licenses from the series media collection so a user about to- // publish can see the terms that applied when the pixels were made (#5638).- useEffect(() => {- let canceled = false;- Promise.all([- listMediaCollections({ silent: true }),- listVideoHistory({ silent: true }),- ]).then(async ([collections, videos]) => {- if (canceled) return;- const list = Array.isArray(collections) ? collections : [];- const collection = list.find((c) => c.seriesId === seriesId || c.id === `sc-${seriesId}`);- if (!collection) { setSeriesAssets([]); return; }- const images = await getGalleryImages((collection.items || []).filter(item => item.kind === 'image').map(item => item.ref), { silent: true });- if (canceled) return;- const imagesByName = new Map((images || []).map((i) => [i.filename, i]));- const videosById = new Map((videos || []).map((v) => [v.id, v]));- const out = [];- for (const it of collection.items || []) {- if (it.kind === 'image' && imagesByName.has(it.ref)) {- out.push(normalizeImage(imagesByName.get(it.ref)));- } else if (it.kind === 'video' && videosById.has(it.ref)) {- out.push(normalizeVideo(videosById.get(it.ref)));- }- }- setSeriesAssets(out);- }).catch(() => { if (!canceled) setSeriesAssets([]); });- return () => { canceled = true; };- }, [seriesId]);-const dirty = useMemo(() => JSON.stringify(form) !== JSON.stringify(savedForm),[form, savedForm],@@ -317,6 +313,9 @@ export default function PipelineExport() {</section></div>+ {assetsState === 'error' && (+ <ListLoadError what="attribution and licenses" error={assetsError} onRetry={retryAssets} className="mt-6 max-w-5xl" />+ )}<AttributionListrecords={seriesAssets}className="mt-6 max-w-5xl bg-port-card border border-port-border rounded-lg px-3 py-2"diff --git a/client/src/pages/PipelineExport.test.jsx b/client/src/pages/PipelineExport.test.jsxindex 3c04fdce8f..d8c37457f7 100644--- a/client/src/pages/PipelineExport.test.jsx+++ b/client/src/pages/PipelineExport.test.jsx@@ -1,6 +1,25 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter, Route, Routes } from 'react-router';++const api = vi.hoisted(() => ({+ getPipelineSeries: vi.fn(),+ updatePipelineSeries: vi.fn(),+ proseExportManuscriptUrl: vi.fn(() => '/m'),+ proseExportEpubUrl: vi.fn(() => '/e'),+ proseExportPdfUrl: vi.fn(() => '/p'),+ listMediaCollections: vi.fn(),+ getGalleryImages: vi.fn(),+ listVideoHistory: vi.fn(),+}));+vi.mock('../services/api', () => api);+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn() }),+}));++import PipelineExport, { TRIM_SIZE_LABELS, FONT_LABELS } from './PipelineExport.jsx';import { TRIM_SIZES, INTERIOR_FONTS } from '../lib/proseExportSettings.js';-import { TRIM_SIZE_LABELS, FONT_LABELS } from './PipelineExport.jsx';// A trim size or font added server-side without a label here would render a blank option.describe('PipelineExport labels', () => {@@ -12,3 +31,37 @@ describe('PipelineExport labels', () => {expect(Object.keys(FONT_LABELS).sort()).toEqual([...INTERIOR_FONTS].sort());});});++describe('PipelineExport attribution rollup', () => {+ const asset = {+ filename: 'img-1.png',+ provenance: { sources: [{ kind: 'model', id: 'model-a', name: 'Example Model', license: 'mit' }] },+ };++ beforeEach(() => {+ vi.clearAllMocks();+ api.getPipelineSeries.mockResolvedValue({ id: 'ser-1', name: 'Example Series' });+ api.listVideoHistory.mockResolvedValue([]);+ api.getGalleryImages.mockResolvedValue([asset]);+ });++ const renderPage = () => render(+ <MemoryRouter initialEntries={['/pipeline/ser-1/export']}>+ <Routes><Route path="/pipeline/:seriesId/export" element={<PipelineExport />} /></Routes>+ </MemoryRouter>,+ );++ it('shows a load error with Retry when the asset read fails, instead of silently hiding the licenses', async () => {+ api.listMediaCollections.mockRejectedValueOnce(new Error('Collections unavailable'));+ renderPage();++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load attribution and licenses — Collections unavailable');+ expect(screen.queryByLabelText('Attribution and licenses')).toBeNull();++ api.listMediaCollections.mockResolvedValueOnce([{ id: 'sc-ser-1', items: [{ kind: 'image', ref: 'img-1.png' }] }]);+ await userEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByLabelText('Attribution and licenses')).toHaveTextContent('Example Model');+ expect(screen.queryByRole('alert')).toBeNull();+ });+});diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 08ff4272dd..ac982c7f48 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link, useSearchParams } from 'react-router';import {AlertTriangle,@@ -31,6 +31,7 @@ import { localDateStr } from '../components/meatspace/constants';import toast from '../components/ui/Toast';import ListLoadError from '../components/ui/ListLoadError';import TabPills from '../components/ui/TabPills';+import useListResource from '../hooks/useListResource';import TribeCircleMap from '../components/tribe/TribeCircleMap.jsx';import { copyToClipboard } from '../lib/clipboard.js';import { safeReadStorage, safeRemoveStorage } from '../lib/safeStorage.js';@@ -544,16 +545,11 @@ function TouchpointSource({ source }) {}function TouchpointsPanel({ personId }) {- const [touchpoints, setTouchpoints] = useState([]);-- useEffect(() => {- if (!personId) return;- let cancelled = false;- api.getTribeTouchpoints(personId, 8)- .then((result) => { if (!cancelled) setTouchpoints(result?.touchpoints || []); })- .catch(() => { if (!cancelled) setTouchpoints([]); });- return () => { cancelled = true; };- }, [personId]);+ const fetchTouchpoints = useCallback(+ () => api.getTribeTouchpoints(personId, 8, { silent: true }).then((result) => result?.touchpoints || []),+ [personId],+ );+ const { items: touchpoints, state, error, retry } = useListResource(fetchTouchpoints, { enabled: !!personId });if (!personId) return null;@@ -561,7 +557,9 @@ function TouchpointsPanel({ personId }) {<section className="mt-4 border border-port-border bg-port-card rounded p-4"><h2 className="text-sm font-semibold text-white">Touchpoints</h2><div className="mt-3 grid gap-2">- {touchpoints.length ? touchpoints.map((touchpoint) => (+ {state === 'error' ? (+ <ListLoadError what="touchpoints" error={error} onRetry={retry} />+ ) : touchpoints.length ? touchpoints.map((touchpoint) => (<div key={touchpoint.id} className="rounded border border-port-border bg-port-bg p-3"><div className="flex items-center justify-between gap-3 text-xs text-gray-500"><span>{touchpoint.happenedAt?.slice(0, 10)}</span>@@ -569,9 +567,9 @@ function TouchpointsPanel({ personId }) {</div><p className="mt-1 text-sm text-gray-300">{touchpoint.summary || touchpoint.channel || 'Touchpoint'}</p></div>- )) : (+ )) : state === 'ready' ? (<p className="text-sm text-gray-500">No touchpoints logged yet.</p>- )}+ ) : null}</div></section>);@@ -632,16 +630,11 @@ function BeeperIdentityChip({ identity, onUnlink }) {// `TouchpointsPanel` already use. Renders nothing when the person has no// Beeper claims (no empty heading).function BeeperIdentitiesPanel({ personId }) {- const [identities, setIdentities] = useState([]);-- useEffect(() => {- if (!personId) { setIdentities([]); return; }- let cancelled = false;- api.getTribePerson(personId, { silent: true })- .then((person) => { if (!cancelled) setIdentities(person?.identities || []); })- .catch(() => { if (!cancelled) setIdentities([]); });- return () => { cancelled = true; };- }, [personId]);+ const fetchIdentities = useCallback(+ () => api.getTribePerson(personId, { silent: true }).then((person) => person?.identities || []),+ [personId],+ );+ const { items: identities, state, error, retry, setItems: setIdentities } = useListResource(fetchIdentities, { enabled: !!personId });const unlink = async (identityId) => {const result = await api.unlinkBeeperIdentity(identityId, { silent: true }).catch((err) => {@@ -652,6 +645,7 @@ function BeeperIdentitiesPanel({ personId }) {setIdentities((current) => current.filter((identity) => identity.id !== identityId));};+ if (state === 'error') return <ListLoadError what="Beeper links" error={error} onRetry={retry} className="mt-4" />;if (identities.length === 0) return null;return (@@ -702,10 +696,10 @@ const agoLabel = (days) => (days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${// replied to. Detection is server-side and LLM-free; the "Draft reply" button is// the only path that calls a provider (user action, per the AI-provider policy).// Nothing is ever auto-sent — the generated draft is filed for review.+const fetchOutreachThreads = () => api.getTribeOutreach({ silent: true }).then((result) => result?.threads || []);+function OutreachQueue() {- // null = still loading; [] = loaded-empty. Distinguishing them keeps the panel- // from flashing an empty state before the first fetch resolves.- const [threads, setThreads] = useState(null);+ const { items: threads, state: threadsState, error: threadsError, retry: retryThreads, setItems: setThreads } = useListResource(fetchOutreachThreads);// A SET of in-flight conversation keys, not a single key — with one key, starting// a second generation re-enables the first thread's button and a re-click fires a// duplicate provider call + duplicate draft.@@ -721,15 +715,7 @@ function OutreachQueue() {const outreachKey = searchParams.get('outreach');useEffect(() => {- let cancelled = false;- api.getTribeOutreach({ silent: true })- .then((result) => { if (!cancelled) setThreads(result?.threads || []); })- .catch(() => { if (!cancelled) setThreads([]); });- return () => { cancelled = true; };- }, []);-- useEffect(() => {- if (!outreachKey || !Array.isArray(threads)) return;+ if (!outreachKey) return;const target = threads.find((t) => t.conversationKey === outreachKey);if (!target) return;const el = rowRefs.current[target.conversationKey];@@ -761,7 +747,7 @@ function OutreachQueue() {// - STALE_INBOUND: they sent a newer message → it's STILL unanswered, so// refetch to pick up the latest turn rather than falsely dropping it.if (err?.code === 'ALREADY_REPLIED') {- setThreads((prev) => (prev || []).filter((t) => t.conversationKey !== key));+ setThreads((prev) => prev.filter((t) => t.conversationKey !== key));toast.success(`Looks like you already replied to ${thread.personName}`);} else if (err?.code === 'STALE_INBOUND') {api.getTribeOutreach({ silent: true })@@ -790,9 +776,11 @@ function OutreachQueue() {}};+ // A failed read must not look like "nothing is unanswered".+ if (threadsState === 'error') return <ListLoadError what="threads waiting on a reply" error={threadsError} onRetry={retryThreads} />;// Quiet when loading or when nothing is unanswered — the Care Queue below still// shows cadence nudges, so an empty outreach panel would just be noise.- if (threads === null || !threads.length) return null;+ if (!threads.length) return null;return (<section className="border border-port-border bg-port-card rounded p-4">diff --git a/client/src/pages/Tribe.test.jsx b/client/src/pages/Tribe.test.jsxindex f18c2d16b6..59ab6ebcd2 100644--- a/client/src/pages/Tribe.test.jsx+++ b/client/src/pages/Tribe.test.jsx@@ -384,3 +384,66 @@ describe('Tribe memory links panel — failed reads', () => {expect(screen.queryByText(/Could not load/)).toBeNull();});});++describe('Tribe person panels and outreach — failed reads', () => {+ beforeEach(() => {+ api.getTribePeople.mockResolvedValue({ people: PEOPLE });+ window.localStorage.clear();+ });+ afterEach(() => {+ api.getTribeTouchpoints.mockResolvedValue({ touchpoints: [] });+ api.getTribePerson.mockResolvedValue({ identities: [] });+ api.getTribeOutreach.mockResolvedValue({ threads: [] });+ });++ it('shows an error with Retry instead of "No touchpoints logged yet" when the touchpoint read fails', async () => {+ api.getTribeTouchpoints.mockRejectedValueOnce(new Error('touchpoints down'));++ renderAt('/tribe?tab=circle');+ fireEvent.click(await screen.findByText('Example Person'));++ expect(await screen.findByText(/Could not load touchpoints — touchpoints down/)).toBeTruthy();+ expect(screen.queryByText('No touchpoints logged yet.')).toBeNull();++ api.getTribeTouchpoints.mockResolvedValueOnce({ touchpoints: [{ id: 't1', happenedAt: '2026-01-02T00:00:00.000Z', source: 'user', summary: 'Coffee catch-up' }] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Coffee catch-up')).toBeTruthy();+ expect(screen.queryByText(/Could not load touchpoints/)).toBeNull();+ });++ it('shows an error with Retry instead of hiding the Beeper block when the identity read fails', async () => {+ api.getTribePerson.mockRejectedValueOnce(new Error('person down'));++ renderAt('/tribe?tab=circle');+ fireEvent.click(await screen.findByText('Example Person'));++ expect(await screen.findByText(/Could not load Beeper links — person down/)).toBeTruthy();+ expect(screen.queryByText('Linked on Beeper')).toBeNull();++ api.getTribePerson.mockResolvedValueOnce({+ identities: [{ id: 'identity-1', personId: 'p1', kind: 'handle', network: 'discord', handle: 'ada', source: 'user', conversations: [] }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Linked on Beeper')).toBeTruthy();+ expect(screen.queryByText(/Could not load Beeper links/)).toBeNull();+ });++ it('shows an error with Retry instead of hiding the reply queue when the outreach read fails', async () => {+ api.getTribeOutreach.mockRejectedValueOnce(new Error('outreach down'));++ renderAt('/tribe');++ expect(await screen.findByText(/Could not load threads waiting on a reply — outreach down/)).toBeTruthy();+ expect(screen.queryByText('Waiting on a reply')).toBeNull();++ api.getTribeOutreach.mockResolvedValueOnce({+ threads: [{+ conversationKey: 'conv-1', personId: 'p1', personName: 'Example Person', source: 'imessage',+ daysAgo: 3, snippet: 'Are we still on for Friday?',+ }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Waiting on a reply')).toBeTruthy();+ expect(screen.queryByText(/Could not load threads/)).toBeNull();+ });+});diff --git a/client/src/services/apiMessages.js b/client/src/services/apiMessages.jsindex 93e5b45381..41e3d2d17c 100644--- a/client/src/services/apiMessages.js+++ b/client/src/services/apiMessages.js@@ -20,7 +20,7 @@ export const getMessageInbox = (params = {}, options = {}) => {return request(`/messages/inbox${str ? `?${str}` : ''}`, options);};export const getMessageDetail = (accountId, messageId, options = {}) => request(`/messages/${accountId}/${messageId}`, options);-export const getMessageThread = (accountId, threadId) => request(`/messages/thread/${accountId}/${threadId}`);+export const getMessageThread = (accountId, threadId, options = {}) => request(`/messages/thread/${accountId}/${threadId}`, options);export const getMessageDrafts = (params = {}, options = {}) => {const qs = new URLSearchParams();if (params.accountId) qs.set('accountId', params.accountId);diff --git a/client/src/services/apiTribe.js b/client/src/services/apiTribe.jsindex 008bb7aca7..f7bc9e95f1 100644--- a/client/src/services/apiTribe.js+++ b/client/src/services/apiTribe.js@@ -42,8 +42,8 @@ export const updateTribePerson = (id, data, options = {}) => request(`/tribe/peoexport const deleteTribePerson = (id, options = {}) => request(`/tribe/people/${id}`, { method: 'DELETE', ...options });-export const getTribeTouchpoints = (personId, limit = 50) =>- request(`/tribe/people/${personId}/touchpoints?limit=${limit}`);+export const getTribeTouchpoints = (personId, limit = 50, options = {}) =>+ request(`/tribe/people/${personId}/touchpoints?limit=${limit}`, options);export const createTribeTouchpoint = (personId, data = {}, options = {}) => request(`/tribe/people/${personId}/touchpoints`, {method: 'POST',