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 retry row, not an empty list, when settings, sharing, CoS and provider panels fail to load (#12786)
Adam Eivy0c137f71c2da
diff --git a/client/src/components/FeatureProviderPicker.jsx b/client/src/components/FeatureProviderPicker.jsxindex c71e688ad7..853c4209e1 100644--- a/client/src/components/FeatureProviderPicker.jsx+++ b/client/src/components/FeatureProviderPicker.jsx@@ -1,6 +1,7 @@import { useEffect, useMemo, useState } from 'react';import toast from './ui/Toast';import ProviderModelSelector from './ProviderModelSelector';+import ListLoadError from './ui/ListLoadError';import { getProviders, getSettings, updateSettings } from '../services/api';import { filterSelectableModels } from '../utils/providers';@@ -21,13 +22,19 @@ export default function FeatureProviderPicker({ featureKey, fallbackId = 'claudeconst [providerId, setProviderId] = useState('');const [model, setModel] = useState('');const [loaded, setLoaded] = useState(false);+ // A failed read must not resolve to "no providers" (and a fallback selection)+ // — the picker fails into an error row with Retry instead.+ const [loadError, setLoadError] = useState(null);+ const [attempt, setAttempt] = useState(0);const [saving, setSaving] = useState(false);useEffect(() => {let cancelled = false;+ setLoaded(false);+ setLoadError(null);Promise.all([- getProviders().catch(() => ({ providers: [] })),- getSettings({ silent: true }).catch(() => ({})),+ getProviders({ silent: true }),+ getSettings({ silent: true }),]).then(([p, settings]) => {if (cancelled) return;// Match the server resolver's default-true semantics (pickCliProvider@@ -48,9 +55,11 @@ export default function FeatureProviderPicker({ featureKey, fallbackId = 'claudesetProviderId(resolved?.id || '');setModel(cfg.model && offered.includes(cfg.model) ? cfg.model : (resolved?.defaultModel || ''));setLoaded(true);+ }).catch((err) => {+ if (!cancelled) setLoadError(err instanceof Error ? err : new Error('Request failed'));});return () => { cancelled = true; };- }, [featureKey, fallbackId]);+ }, [featureKey, fallbackId, attempt]);const availableModels = useMemo(() => {const p = providers.find((pr) => pr.id === providerId);@@ -74,6 +83,9 @@ export default function FeatureProviderPicker({ featureKey, fallbackId = 'claudetoast.success('Saved');};+ if (loadError) {+ return <ListLoadError what="AI providers" error={loadError} onRetry={() => setAttempt((n) => n + 1)} />;+ }if (!loaded) return null;if (providers.length === 0) {return (diff --git a/client/src/components/FeatureProviderPicker.test.jsx b/client/src/components/FeatureProviderPicker.test.jsxnew file mode 100644index 0000000000..6e40d28f72--- /dev/null+++ b/client/src/components/FeatureProviderPicker.test.jsx@@ -0,0 +1,39 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import FeatureProviderPicker from './FeatureProviderPicker';++const api = vi.hoisted(() => ({+ getProviders: vi.fn(),+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+}));++vi.mock('../services/api', () => api);+vi.mock('./ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++describe('FeatureProviderPicker', () => {+ beforeEach(() => vi.clearAllMocks());++ it('fails into an error row with Retry instead of "No enabled CLI providers"', async () => {+ api.getProviders.mockRejectedValueOnce(new Error('providers 503'));+ api.getSettings.mockResolvedValue({});+ render(<FeatureProviderPicker featureKey="autofixer" />);++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load AI providers — providers 503');+ expect(screen.queryByText(/No enabled CLI providers/)).not.toBeInTheDocument();++ api.getProviders.mockResolvedValue({ providers: [] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.getByText(/No enabled CLI providers/)).toBeInTheDocument());+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });++ it('does not seed the picker from defaults when only the settings read fails', async () => {+ api.getProviders.mockResolvedValue({ providers: [{ id: 'claude-code', type: 'cli', models: ['m1'], defaultModel: 'm1' }] });+ api.getSettings.mockRejectedValueOnce(new Error('settings 500'));+ render(<FeatureProviderPicker featureKey="autofixer" />);++ expect(await screen.findByRole('alert')).toHaveTextContent('settings 500');+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/QuickTaskWidget.jsx b/client/src/components/QuickTaskWidget.jsxindex 8c32d97eb7..d79be6b6f4 100644--- a/client/src/components/QuickTaskWidget.jsx+++ b/client/src/components/QuickTaskWidget.jsx@@ -1,16 +1,15 @@-import { useState, useEffect } from 'react';import { Link } from 'react-router';import * as api from '../services/api';import TaskAddForm from './cos/TaskAddForm';+import ListLoadError from './ui/ListLoadError';+import useListResource from '../hooks/useListResource';-export default function QuickTaskWidget() {- const [providers, setProviders] = useState([]);- const [apps, setApps] = useState([]);+const fetchProviders = () => api.getProviders({ silent: true }).then(data => data?.providers || []);+const fetchApps = () => api.getApps({ silent: true }).then(data => (Array.isArray(data) ? data : data?.apps || []));- useEffect(() => {- api.getProviders().then(data => setProviders(data.providers || [])).catch(() => setProviders([]));- api.getApps().then(setApps).catch(() => setApps([]));- }, []);+export default function QuickTaskWidget() {+ const providersList = useListResource(fetchProviders);+ const appsList = useListResource(fetchApps);// Tiles render with overflow-hidden + a fixed pixel height (h * ROW_HEIGHT)// — fill the cell and let the form area scroll if the user shrank the@@ -24,7 +23,15 @@ export default function QuickTaskWidget() {</Link></div><div className="flex-1 min-h-0 overflow-y-auto">- <TaskAddForm providers={providers} apps={apps} onTaskAdded={() => {}} compact defaultExpanded />+ {providersList.state === 'error' && (+ <ListLoadError what="AI providers" error={providersList.error} onRetry={providersList.retry} />+ )}+ {appsList.state === 'error' && (+ <ListLoadError what="apps" error={appsList.error} onRetry={appsList.retry} className={providersList.state === 'error' ? 'mt-2' : ''} />+ )}+ {providersList.state !== 'error' && appsList.state !== 'error' && (+ <TaskAddForm providers={providersList.items} apps={appsList.items} onTaskAdded={() => {}} compact defaultExpanded />+ )}</div></div>);diff --git a/client/src/components/QuickTaskWidget.test.jsx b/client/src/components/QuickTaskWidget.test.jsxnew file mode 100644index 0000000000..1d4816b404--- /dev/null+++ b/client/src/components/QuickTaskWidget.test.jsx@@ -0,0 +1,30 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import QuickTaskWidget from './QuickTaskWidget';++const api = vi.hoisted(() => ({ getProviders: vi.fn(), getApps: vi.fn() }));++vi.mock('../services/api', () => api);+vi.mock('./cos/TaskAddForm', () => ({+ default: ({ providers, apps }) => <div data-testid="task-form">{providers.length} providers, {apps.length} apps</div>,+}));++const renderWidget = () => render(<MemoryRouter><QuickTaskWidget /></MemoryRouter>);++describe('QuickTaskWidget', () => {+ beforeEach(() => vi.clearAllMocks());++ it('shows an error row with Retry, not a form with no providers, when a read fails', async () => {+ api.getProviders.mockResolvedValue({ providers: [{ id: 'p1' }] });+ api.getApps.mockRejectedValueOnce(new Error('apps 502'));+ renderWidget();++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load apps — apps 502');+ expect(screen.queryByTestId('task-form')).not.toBeInTheDocument();++ api.getApps.mockResolvedValue([{ id: 'a1' }, { id: 'a2' }]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.getByTestId('task-form')).toHaveTextContent('1 providers, 2 apps'));+ });+});diff --git a/client/src/components/apps/JiraConfigPanel.jsx b/client/src/components/apps/JiraConfigPanel.jsxindex 0c421f3f6d..6b2ca71a43 100644--- a/client/src/components/apps/JiraConfigPanel.jsx+++ b/client/src/components/apps/JiraConfigPanel.jsx@@ -4,12 +4,17 @@ import { Save, Loader2 } from 'lucide-react';import * as api from '../../services/api';import toast from '../ui/Toast';import Banner from '../ui/Banner';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import { INPUT_CLASS } from './constants';// A JIRA issue key like PROJ-1553 — used to tell "user typed a key to validate"// from "user is searching an epic by name" in the epic field.const EPIC_KEY_RE = /^[A-Za-z][A-Za-z0-9]*-\d+$/;+const fetchJiraInstances = () => api.getJiraInstances({ silent: true })+ .then(data => (data?.instances ? Object.values(data.instances) : []));+/** Flatten the app record's stored `jira` object into flat form fields. */const toForm = (jira) => ({enabled: jira?.enabled || false,@@ -37,7 +42,7 @@ export default function JiraConfigPanel({ app, onSaved }) {const [form, setForm] = useState(() => toForm(app.jira));const [saving, setSaving] = useState(false);const [error, setError] = useState(null);- const [instances, setInstances] = useState([]);+ const { items: instances, state: instancesState, error: instancesError, retry: retryInstances } = useListResource(fetchJiraInstances);const [projects, setProjects] = useState([]);const [loadingProjects, setLoadingProjects] = useState(false);const [projectSearch, setProjectSearch] = useState('');@@ -49,12 +54,6 @@ export default function JiraConfigPanel({ app, onSaved }) {const [epicDropdownOpen, setEpicDropdownOpen] = useState(false);const [epicValidation, setEpicValidation] = useState({ state: 'idle' });- useEffect(() => {- api.getJiraInstances()- .then(data => setInstances(data?.instances ? Object.values(data.instances) : []))- .catch(() => setInstances([]));- }, []);-useEffect(() => {if (!form.instanceId) {setProjects([]);@@ -224,7 +223,11 @@ export default function JiraConfigPanel({ app, onSaved }) {</label>{form.enabled && (- instances.length === 0 ? (+ instancesState === 'loading' ? (+ <p className="text-sm text-gray-500">Loading JIRA instances…</p>+ ) : instancesState === 'error' ? (+ <ListLoadError what="JIRA instances" error={instancesError} onRetry={retryInstances} />+ ) : instances.length === 0 ? (<Banner tone="warning" size="md">No JIRA instances configured. <Link to="/devtools/jira" className="underline hover:text-white">Configure JIRA</Link> first.</Banner>diff --git a/client/src/components/apps/JiraConfigPanel.test.jsx b/client/src/components/apps/JiraConfigPanel.test.jsxnew file mode 100644index 0000000000..6b904e36e4--- /dev/null+++ b/client/src/components/apps/JiraConfigPanel.test.jsx@@ -0,0 +1,46 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import JiraConfigPanel from './JiraConfigPanel';++const api = vi.hoisted(() => ({+ getJiraInstances: vi.fn(),+ getJiraProjects: vi.fn(),+ getJiraBoards: vi.fn(),+ getJiraBoardSprints: vi.fn(),+ getJiraIssue: vi.fn(),+ searchJiraEpics: vi.fn(),+ updateApp: vi.fn(),+}));++vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++const app = { id: 'app-1', jira: { enabled: true } };+const renderPanel = () => render(<MemoryRouter><JiraConfigPanel app={app} onSaved={() => {}} /></MemoryRouter>);++describe('JiraConfigPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getJiraProjects.mockResolvedValue([]);+ });++ it('reports a failed instance read with Retry, not "No JIRA instances configured"', async () => {+ api.getJiraInstances.mockRejectedValueOnce(new Error('jira 500'));+ renderPanel();++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load JIRA instances — jira 500');+ expect(screen.queryByText(/No JIRA instances configured/)).not.toBeInTheDocument();++ api.getJiraInstances.mockResolvedValue({ instances: { i1: { id: 'i1', name: 'Example', baseUrl: 'https://jira.example.com' } } });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.getByLabelText('JIRA Instance')).toBeInTheDocument());+ });++ it('keeps the empty copy for a genuinely empty instance list', async () => {+ api.getJiraInstances.mockResolvedValue({ instances: {} });+ renderPanel();+ expect(await screen.findByText(/No JIRA instances configured/)).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsxindex 8802946d68..f39608777d 100644--- a/client/src/components/cos/tabs/JobsTab.jsx+++ b/client/src/components/cos/tabs/JobsTab.jsx@@ -16,6 +16,10 @@ import JobCard, {} from '../JobCard';import useUserTimezone from '../../../hooks/useUserTimezone.js';import TaskDataInputs from '../TaskDataInputs';+import ListLoadError from '../../ui/ListLoadError';+import useListResource from '../../../hooks/useListResource';++const fetchApps = () => api.getApps({ silent: true }).then(data => data?.apps || data || []);// Blank create-form state — shared by the initial useState and the post-create// reset so the two can't drift (a field added to one but not the other would@@ -48,7 +52,7 @@ export default function JobsTab() {const [jobs, setJobs] = useState([]);// The job whose trigger is in flight, so its card can disable Run now.const [triggering, setTriggering] = useState(null);- const [apps, setApps] = useState([]);+ const { items: apps, state: appsState, error: appsError, retry: retryApps } = useListResource(fetchApps);const [rawProviders, setRawProviders] = useState([]);const [activeProviderId, setActiveProviderId] = useState('');const [stats, setStats] = useState(null);@@ -72,10 +76,6 @@ export default function JobsTab() {useEffect(() => { fetchJobs(); }, [fetchJobs]);- useEffect(() => {- api.getApps().then(data => setApps(data?.apps || data || [])).catch(() => setApps([]));- }, []);-useEffect(() => {api.getProviders({ silent: true }).then(data => {setRawProviders(data?.providers || []);@@ -223,6 +223,10 @@ export default function JobsTab() {</div>)}+ {appsState === 'error' && (+ <ListLoadError what="apps for the job scope pickers" error={appsError} onRetry={retryApps} />+ )}+{showCreate && (<div className="bg-port-card border border-port-accent/50 rounded-lg p-4"><div className="space-y-3">@@ -274,6 +278,7 @@ export default function JobsTab() {aria-label="App scope"value={newJob.appId || ''}onChange={e => setNewJob(j => ({ ...j, appId: e.target.value }))}+ disabled={appsState === 'error'}className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"><option value="">Global (PortOS)</option>diff --git a/client/src/components/cos/tabs/JobsTab.test.jsx b/client/src/components/cos/tabs/JobsTab.test.jsxindex 52dddf44d5..acb123f908 100644--- a/client/src/components/cos/tabs/JobsTab.test.jsx+++ b/client/src/components/cos/tabs/JobsTab.test.jsx@@ -131,4 +131,16 @@ describe('JobsTab / JobCard Run Now disable behavior (#4036)', () => {await waitFor(() => expect(screen.getByText('Test Job')).toBeInTheDocument());expect(screen.queryByText('Due')).not.toBeInTheDocument();});++ it('shows an error row with Retry when the apps read fails, and recovers on retry', async () => {+ api.getApps.mockRejectedValueOnce(new Error('apps 500'));+ render(<JobsTab apps={[]} providers={[]} />);++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load apps for the job scope pickers — apps 500');++ api.getApps.mockResolvedValue([{ id: 'app-1', name: 'Example App' }]);+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());+ expect(api.getApps).toHaveBeenCalledTimes(2);+ });});diff --git a/client/src/components/cos/tabs/ProviderStatusCard.jsx b/client/src/components/cos/tabs/ProviderStatusCard.jsxindex ceafce4ffe..fa4c56ab86 100644--- a/client/src/components/cos/tabs/ProviderStatusCard.jsx+++ b/client/src/components/cos/tabs/ProviderStatusCard.jsx@@ -63,10 +63,12 @@ export default function ProviderStatusCard() {setLoading(true);const [statusData, providerData] = await Promise.all([api.getProviderStatuses().catch(() => null),- api.getProviders().catch(() => ({ providers: [] }))+ api.getProviders({ silent: true }).catch(() => null)]);- setStatuses(statusData);- setProviders(providerData.providers || []);+ // Without the provider list "All Available" would be vacuous, so a failed+ // provider read fails the whole card into its Retry state.+ setStatuses(providerData ? statusData : null);+ setProviders(providerData?.providers || []);setLoading(false);};diff --git a/client/src/components/cos/tabs/ProviderStatusCard.test.jsx b/client/src/components/cos/tabs/ProviderStatusCard.test.jsxindex e9e87ec2c1..cc955bdec8 100644--- a/client/src/components/cos/tabs/ProviderStatusCard.test.jsx+++ b/client/src/components/cos/tabs/ProviderStatusCard.test.jsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import * as api from '../../../services/api';import socket from '../../../services/socket';@@ -60,4 +60,21 @@ describe('ProviderStatusCard', () => {await waitFor(() => expect(screen.getByTestId('rate-limit-window-example')).toHaveTextContent('API window: limit 100'));});++ it('fails into Retry instead of "All Available" when the provider list read fails', async () => {+ api.getProviderStatuses.mockResolvedValue({+ providers: { example: { available: false, reason: 'rate-limit', message: 'Rate limit exceeded' } },+ });+ api.getProviders.mockRejectedValueOnce(new Error('providers 500'));++ render(<ProviderStatusCard />);++ expect(await screen.findByText('Unable to load status')).toBeInTheDocument();+ expect(screen.queryByText('All Available')).not.toBeInTheDocument();++ api.getProviders.mockResolvedValue({ providers: [{ id: 'example', name: 'Example Provider' }] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry loading status' }));+ await waitFor(() => expect(screen.queryByText('Unable to load status')).not.toBeInTheDocument());+ expect(screen.getByText('Example Provider')).toBeInTheDocument();+ });});diff --git a/client/src/components/cos/tabs/RunsTab.deepLink.test.jsx b/client/src/components/cos/tabs/RunsTab.deepLink.test.jsxindex d282121de6..13a3fe32fc 100644--- a/client/src/components/cos/tabs/RunsTab.deepLink.test.jsx+++ b/client/src/components/cos/tabs/RunsTab.deepLink.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({@@ -59,4 +59,24 @@ describe('RunsTab ?run= deep link', () => {expect(await screen.findByText('first prompt')).toBeInTheDocument();expect(api.getRunPrompt).not.toHaveBeenCalled();});++ it('renders a failed runs read as an error row with Retry, not "No AI runs yet"', async () => {+ api.getRuns.mockRejectedValueOnce(new Error('runs 500'));+ renderTab('/cos/runs');++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load runs — runs 500');+ expect(screen.queryByText('No AI runs yet')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('first prompt')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });++ it('keeps the empty copy for a genuinely empty run history', async () => {+ api.getRuns.mockResolvedValue({ runs: [] });+ renderTab('/cos/runs');++ expect(await screen.findByText('No AI runs yet')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });});diff --git a/client/src/components/cos/tabs/RunsTab.jsx b/client/src/components/cos/tabs/RunsTab.jsxindex 29b46c4bfb..eaad5b5e88 100644--- a/client/src/components/cos/tabs/RunsTab.jsx+++ b/client/src/components/cos/tabs/RunsTab.jsx@@ -5,6 +5,8 @@ import * as api from '../../../services/api';import { formatTime, formatRuntime, formatBytes, formatDateTime } from '../../../utils/formatters';import BrailleSpinner from '../../BrailleSpinner';import Banner from '../../ui/Banner';+import ListLoadError from '../../ui/ListLoadError';+import useListResource from '../../../hooks/useListResource';import ProcessLogModal from '../../ui/ProcessLogModal';import { writeClipboardSilently } from '../../../lib/clipboard';import { clickableProps, onActivateKeyDown } from '../../../lib/a11yKeyboard.js';@@ -20,8 +22,6 @@ export default function RunsTab() {const navigate = useNavigate();const [searchParams] = useSearchParams();const deepLinkRunId = searchParams.get('run');- const [runs, setRuns] = useState([]);- const [loading, setLoading] = useState(true);const [expandedId, setExpandedId] = useState(null);const [expandedDetails, setExpandedDetails] = useState({});const [sourceFilter, setSourceFilter] = useState('all');@@ -30,16 +30,12 @@ export default function RunsTab() {// The failed run whose system logs are open in the log modal, or null.const [logModalRun, setLogModalRun] = useState(null);- const loadRuns = useCallback(async () => {- setLoading(true);- const data = await api.getRuns(100, 0, sourceFilter).catch(() => ({ runs: [] }));- setRuns(data.runs || []);- setLoading(false);- }, [sourceFilter]);-- useEffect(() => {- loadRuns();- }, [loadRuns]);+ const fetchRuns = useCallback(+ () => api.getRuns(100, 0, sourceFilter, { silent: true }).then(data => data?.runs || []),+ [sourceFilter]+ );+ const { items: runs, state: runsState, error: runsError, retry: loadRuns, setItems: setRuns } = useListResource(fetchRuns);+ const loading = runsState === 'loading';// Filter runs by source and statusconst filteredRuns = runs.filter(run => {@@ -261,7 +257,9 @@ export default function RunsTab() {{/* Runs List */}<div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl overflow-hidden">- {filteredRuns.length === 0 ? (+ {runsState === 'error' ? (+ <ListLoadError what="runs" error={runsError} onRetry={loadRuns} className="m-3" />+ ) : filteredRuns.length === 0 ? (<div className="text-center py-12 text-gray-500">{runs.length === 0 ? 'No AI runs yet' : 'No runs match the selected filters'}</div>diff --git a/client/src/components/settings/SharingTab.jsx b/client/src/components/settings/SharingTab.jsxindex a0895ad866..425129b427 100644--- a/client/src/components/settings/SharingTab.jsx+++ b/client/src/components/settings/SharingTab.jsx@@ -2,8 +2,15 @@ import { useEffect, useState } from 'react';import { Save, Loader2, Users, ShieldCheck, Network } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import { getAuthStatus, getMediaShareCandidates, getSettings, listMusicEngines, updateSettings } from '../../services/api';+// Engine health probes may spawn local Python checks on a cold cache, so this+// loads independently of the sharing controls.+const fetchMusicEngines = () => listMusicEngines({ silent: true })+ .then((music) => (Array.isArray(music?.engines) ? music.engines : []));+const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);const modelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;@@ -62,7 +69,7 @@ export function SharingTab() {// only `mediaProvider` and `strictPullAuthorization`, and patches those// sub-keys alone (the server merges the slice per sub-key, #4703).const [authEnabled, setAuthEnabled] = useState(false);- const [musicEngines, setMusicEngines] = useState([]);+ const { items: musicEngines, state: musicEnginesState, error: musicEnginesError, retry: retryMusicEngines } = useListResource(fetchMusicEngines);const [providerSettings, setProviderSettings] = useState({});const [providerEnabled, setProviderEnabled] = useState(false);const [providerMaxQueuedJobs, setProviderMaxQueuedJobs] = useState(2);@@ -80,12 +87,6 @@ export function SharingTab() {const [providerSaving, setProviderSaving] = useState(false);useEffect(() => {- // Engine health probes may spawn local Python checks on a cold cache. Load- // them independently so the existing sharing controls do not wait on that- // optional provider catalog.- listMusicEngines({ silent: true })- .then((music) => setMusicEngines(Array.isArray(music?.engines) ? music.engines : []))- .catch(() => setMusicEngines([]));// Same rationale as the engine probe above: readiness inspection can touch// the model cache, so keep it off the critical path for the other controls.getMediaShareCandidates({ silent: true })@@ -402,7 +403,11 @@ export function SharingTab() {<fieldset><legend className="block text-xs uppercase tracking-wider text-gray-500 mb-2">Allowed audio models</legend>- {musicEngines.length === 0 ? (+ {musicEnginesState === 'error' ? (+ <ListLoadError what="the local music engine catalog" error={musicEnginesError} onRetry={retryMusicEngines} />+ ) : musicEnginesState === 'loading' ? (+ <p className="text-sm text-gray-500">Loading the local music engine catalog…</p>+ ) : musicEngines.length === 0 ? (<p className="text-sm text-gray-500">The local music engine catalog is not available to configure.</p>) : (<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">diff --git a/client/src/components/settings/SharingTab.test.jsx b/client/src/components/settings/SharingTab.test.jsxindex eaf7af7a61..b04623cc59 100644--- a/client/src/components/settings/SharingTab.test.jsx+++ b/client/src/components/settings/SharingTab.test.jsx@@ -335,4 +335,17 @@ describe('SharingTab — an absent federation slice is not a failed read', () =>.toHaveBeenCalledWith('Could not read current settings — provider not saved'));expect(updateSettings).not.toHaveBeenCalled();});++ it('shows an error row with Retry when the music engine catalog fails, not the "not available" copy', async () => {+ listMusicEngines.mockRejectedValueOnce(new Error('engines 500'));+ render(<SharingTab />);++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load the local music engine catalog — engines 500');+ expect(screen.queryByText(/music engine catalog is not available/)).not.toBeInTheDocument();++ listMusicEngines.mockResolvedValue({ engines: [{ id: 'e1', name: 'Example Engine', models: [{ id: 'm1', name: 'Example Model' }] }] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Example Engine')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });});diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsxindex 64bd4a98f4..e8fd290650 100644--- a/client/src/components/settings/VoiceTab.jsx+++ b/client/src/components/settings/VoiceTab.jsx@@ -14,6 +14,8 @@ import { formatVoiceLabel } from '../../lib/voiceLabel';import { withUnlistedOption } from '../../lib/withUnlistedOption';import ProviderModelSelector from '../ProviderModelSelector';import FormField from '../ui/FormField';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource';import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';const SERVICE_LABELS = {@@ -70,7 +72,6 @@ export function VoiceTab() {const [saving, setSaving] = useState(false);const [cfg, setCfg] = useState(null);const [status, setStatus] = useState(null);- const [voiceList, setVoiceList] = useState({ engine: null, voices: [] });const [ttsEngines, setTtsEngines] = useState([]);const [ttsEngineError, setTtsEngineError] = useState(null);const [testing, setTesting] = useState(false);@@ -95,6 +96,14 @@ export function VoiceTab() {const currentEngine = cfg?.tts?.engine;+ // The selected engine's voice catalog. A failed read renders an error row with+ // Retry rather than an empty picker that offers only the saved voice.+ const fetchVoices = useCallback(+ () => listVoices(currentEngine, { silent: true }).then((v) => (Array.isArray(v?.voices) ? v.voices : [])),+ [currentEngine],+ );+ const { items: voices, state: voicesState, error: voicesError, retry: retryVoices, setItems: setVoices } = useListResource(fetchVoices, { enabled: Boolean(currentEngine) });+useEffect(() => {if (!currentEngine || ttsEngines.length === 0) return;const registered = ttsEngines.find((item) => (@@ -105,13 +114,11 @@ export function VoiceTab() {}, [currentEngine, ttsEngines]);const refreshStatus = useCallback(() => {- return Promise.all([- getVoiceStatus(),- listVoices(currentEngine).catch(() => ({ engine: null, voices: [] })),- ])- .then(([s, v]) => { setStatus(s); setVoiceList(v); })+ retryVoices();+ return getVoiceStatus()+ .then(setStatus).catch(() => setStatus(null));- }, [currentEngine]);+ }, [retryVoices]);useEffect(() => {Promise.all([getVoiceConfig({ silent: true }), getVoiceStatus({ silent: true })])@@ -142,17 +149,6 @@ export function VoiceTab() {});}, []);- // Refetch the voice catalog whenever the user flips TTS engine so the picker- // reflects the selected engine's voices (without requiring a save first).- useEffect(() => {- if (!currentEngine) return undefined;- let active = true;- listVoices(currentEngine)- .then((v) => { if (active) setVoiceList(v); })- .catch(() => { if (active) setVoiceList({ engine: currentEngine, voices: [] }); });- return () => { active = false; };- }, [currentEngine]);-// Functional setState form so sequential patch() calls in one event handler// compose correctly — each one sees the prior's result instead of cloning// the pre-event `cfg` and silently overwriting earlier changes.@@ -285,7 +281,6 @@ export function VoiceTab() {item.id === configuredEngine || item.aliases?.includes(configuredEngine)));const engine = engineMeta?.id || configuredEngine;- const voices = voiceList.voices || [];const engineConfigKey = typeof engineMeta?.configKey === 'string' ? engineMeta.configKey : null;const fallbackConfigKey = [configuredEngine, configuredEngine.replace(/-tts$/, '')].find((key) => cfg.tts[key] && typeof cfg.tts[key] === 'object');@@ -537,7 +532,7 @@ export function VoiceTab() {setDownloadingVoice(val);fetchPiperVoice(val, { silent: true }).then(() => listVoices('piper', { silent: true }))- .then((fresh) => setVoiceList(fresh))+ .then((fresh) => setVoices(Array.isArray(fresh?.voices) ? fresh.voices : [])).catch((err) => toast.error(`Voice download failed: ${err.message}`)).finally(() => setDownloadingVoice(null));}@@ -560,6 +555,9 @@ export function VoiceTab() {: <Play size={14} />}</button></div>+ {voicesState === 'error' && (+ <ListLoadError what="voices" error={voicesError} onRetry={retryVoices} className="mt-2" />+ )}</FormField>{cfg.tts.retiredEngine === 'kokoro' && (diff --git a/client/src/components/settings/VoiceTab.test.jsx b/client/src/components/settings/VoiceTab.test.jsxindex 2e585a8e61..0b3010b657 100644--- a/client/src/components/settings/VoiceTab.test.jsx+++ b/client/src/components/settings/VoiceTab.test.jsx@@ -161,6 +161,17 @@ describe('VoiceTab TTS engine registry', () => {expect(voiceSelect).toHaveValue('retired-voice');expect(screen.getByRole('option', { name: 'retired-voice (current)' })).toBeTruthy();});++ it('shows an error row with Retry when the voice catalog fails, not a picker offering only the saved voice', async () => {+ voiceApi.listVoices.mockRejectedValueOnce(new Error('voices 500'));+ render(<MemoryRouter><VoiceTab /></MemoryRouter>);++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load voices — voices 500');++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await screen.findByRole('option', { name: /Expressive Alto/ });+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });});describe('VoiceTab LLM / code-agent pickers', () => {diff --git a/client/src/components/sharing/ShareToButton.jsx b/client/src/components/sharing/ShareToButton.jsxindex 89ef6052a7..3cc6bf2881 100644--- a/client/src/components/sharing/ShareToButton.jsx+++ b/client/src/components/sharing/ShareToButton.jsx@@ -22,10 +22,12 @@* compact?: boolean*/-import { useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { Share2, Check, Circle, CheckCircle2, Loader2 } from 'lucide-react';import toast from '../ui/Toast';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource.js';import useClickOutside from '../../hooks/useClickOutside.js';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';import {@@ -39,6 +41,8 @@ import {const SUBSCRIBABLE_KINDS = new Set(['series', 'universe']);const MENU_WIDTH = 288; // w-72+const fetchBuckets = () => listShareBuckets({ silent: true }).then((r) => r?.buckets || []);+function renderRowIcon({ busy, subscribable, subscribed }) {if (busy) return <Loader2 size={14} className="animate-spin text-port-accent" />;if (!subscribable) return <Check size={14} className="text-gray-600" />;@@ -49,11 +53,32 @@ function renderRowIcon({ busy, subscribable, subscribed }) {export default function ShareToButton({ kind, ids, items, label = 'Share', compact = false, className = '' }) {const [open, setOpen] = useState(false);- const [buckets, setBuckets] = useState([]);- const [subscriptions, setSubscriptions] = useState([]); // [{id, bucketId, ...}]- const [loading, setLoading] = useState(false);const [busyBucketId, setBusyBucketId] = useState(null);const wrapperRef = useRef(null);+ const isSubscribable = SUBSCRIBABLE_KINDS.has(kind);+ const recordId = isSubscribable && Array.isArray(ids) && ids.length > 0 ? ids[0] : null;+ // Buckets + subscriptions reload on every open. Subscriptions are scoped to+ // the (kind, recordId) being viewed so the "checked" indicator reflects this+ // record specifically, not the bucket's universe of subscriptions. A failed+ // read of either is an error row, never "no buckets" / "not subscribed" —+ // an unchecked row would let a click create a duplicate subscription.+ const fetchSubscriptions = useCallback(+ () => (isSubscribable && recordId+ ? listShareSubscriptions({ recordKind: kind, recordId }, { silent: true }).then((r) => r?.subscriptions || [])+ : Promise.resolve([])),+ [isSubscribable, kind, recordId],+ );+ const bucketsList = useListResource(fetchBuckets, { enabled: open });+ const subscriptionsList = useListResource(fetchSubscriptions, { enabled: open });+ const buckets = bucketsList.items;+ const subscriptions = subscriptionsList.items;+ const setSubscriptions = subscriptionsList.setItems;+ const loading = bucketsList.state === 'loading' || subscriptionsList.state === 'loading';+ const loadFailed = bucketsList.state === 'error' ? bucketsList : subscriptionsList.state === 'error' ? subscriptionsList : null;+ const retryLoad = () => {+ if (bucketsList.state === 'error') bucketsList.retry();+ if (subscriptionsList.state === 'error') subscriptionsList.retry();+ };// Portal the dropdown to <body> so it escapes each card's stacking context// (an in-card `absolute z-30` popover is otherwise painted under the next// card). `usePopoverPosition` owns the fixed placement: it anchors to the@@ -67,39 +92,9 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compaminWidth: 220,gap: 4,position: 'below',- contentDeps: [loading, buckets.length, subscriptions.length]+ contentDeps: [loading, loadFailed, buckets.length, subscriptions.length]});- const isSubscribable = SUBSCRIBABLE_KINDS.has(kind);- const recordId = isSubscribable && Array.isArray(ids) && ids.length > 0 ? ids[0] : null;-- // Refresh buckets + subscriptions on open. Subscriptions are scoped to the- // (kind, recordId) being viewed so the "checked" indicator reflects this- // record specifically, not the bucket's universe of subscriptions.- const refresh = async () => {- setLoading(true);- const tasks = [- listShareBuckets({ silent: true }).then((r) => r?.buckets || []).catch(() => []),- ];- if (isSubscribable && recordId) {- tasks.push(- listShareSubscriptions({ recordKind: kind, recordId }, { silent: true })- .then((r) => r?.subscriptions || [])- .catch(() => []),- );- } else {- tasks.push(Promise.resolve([]));- }- const [b, s] = await Promise.all(tasks);- setBuckets(b);- setSubscriptions(s);- setLoading(false);- };-- useEffect(() => {- if (open) refresh();- }, [open]);-// Close on Escape and return focus to the trigger so keyboard users don't// have to Tab back through the popover content.useEffect(() => {@@ -208,6 +203,8 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa<div className="px-3 py-3 text-xs text-gray-500 flex items-center gap-2"><Loader2 size={12} className="animate-spin" /> Loading buckets…</div>+ ) : loadFailed ? (+ <ListLoadError what={loadFailed === bucketsList ? 'buckets' : 'subscriptions'} error={loadFailed.error} onRetry={retryLoad} className="m-2" />) : buckets.length === 0 ? (<div className="px-3 py-3 text-xs text-gray-500">No buckets yet. <a href="/sharing" className="text-port-accent hover:underline">Add one</a>.diff --git a/client/src/components/sharing/ShareToButton.test.jsx b/client/src/components/sharing/ShareToButton.test.jsxindex 6d20344cb5..252a00933a 100644--- a/client/src/components/sharing/ShareToButton.test.jsx+++ b/client/src/components/sharing/ShareToButton.test.jsx@@ -95,4 +95,27 @@ describe('ShareToButton', () => {{ silent: true },));});++ it('shows an error row with Retry when the bucket read fails, not "No buckets yet"', async () => {+ const user = userEvent.setup();+ api.listShareBuckets.mockRejectedValueOnce(new Error('buckets 500'));+ render(<ShareToButton kind="series" ids={['s1']} />);+ await user.click(screen.getByRole('button', { name: /Share/i }));++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load buckets — buckets 500');+ expect(screen.queryByText(/No buckets yet/)).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Bucket A')).toBeTruthy();+ });++ it('does not render unchecked rows when the subscription read fails', async () => {+ const user = userEvent.setup();+ api.listShareSubscriptions.mockRejectedValueOnce(new Error('subs 500'));+ render(<ShareToButton kind="series" ids={['s1']} />);+ await user.click(screen.getByRole('button', { name: /Share/i }));++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load subscriptions — subs 500');+ expect(screen.queryByText('Bucket A')).toBeNull();+ });});diff --git a/client/src/components/sharing/SyncToPeerButton.jsx b/client/src/components/sharing/SyncToPeerButton.jsxindex 4cee1f1051..f880b456ed 100644--- a/client/src/components/sharing/SyncToPeerButton.jsx+++ b/client/src/components/sharing/SyncToPeerButton.jsx@@ -22,10 +22,12 @@* compact?: boolean*/-import { useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { Cloud, Circle, CheckCircle2, Loader2 } from 'lucide-react';import toast from '../ui/Toast';+import ListLoadError from '../ui/ListLoadError';+import useListResource from '../../hooks/useListResource.js';import useClickOutside from '../../hooks/useClickOutside.js';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';import {@@ -37,6 +39,12 @@ import {const MENU_WIDTH = 288; // w-72+// Only show enabled, online-or-connectable peers — Tailnet peers that are+// marked enabled but currently offline are still listed so the user can+// create the subscription now and let the push pipeline retry on reconnect.+const fetchPeers = () => getInstances({ silent: true })+ .then((instances) => (instances?.peers || []).filter((p) => p.enabled && p.instanceId));+export default function SyncToPeerButton({recordKind,recordId,@@ -45,11 +53,26 @@ export default function SyncToPeerButton({className = '',}) {const [open, setOpen] = useState(false);- const [peers, setPeers] = useState([]);- const [subscriptions, setSubscriptions] = useState([]); // [{id, peerId, ...}]- const [loading, setLoading] = useState(false);const [busyPeerId, setBusyPeerId] = useState(null);const wrapperRef = useRef(null);+ // Peers + subscriptions reload on every open. A failed read of either is an+ // error row, never "no peers" / "not subscribed" — an unchecked row would let+ // a click create a duplicate subscription.+ const fetchSubscriptions = useCallback(+ () => listPeerSubscriptions({ recordKind, recordId }, { silent: true }).then((r) => r?.subscriptions || []),+ [recordKind, recordId],+ );+ const peersList = useListResource(fetchPeers, { enabled: open });+ const subscriptionsList = useListResource(fetchSubscriptions, { enabled: open });+ const peers = peersList.items;+ const subscriptions = subscriptionsList.items; // [{id, peerId, ...}]+ const setSubscriptions = subscriptionsList.setItems;+ const loading = peersList.state === 'loading' || subscriptionsList.state === 'loading';+ const loadFailed = peersList.state === 'error' ? peersList : subscriptionsList.state === 'error' ? subscriptionsList : null;+ const retryLoad = () => {+ if (peersList.state === 'error') peersList.retry();+ if (subscriptionsList.state === 'error') subscriptionsList.retry();+ };// The dropdown is portaled to <body> so it escapes each series/universe// card's stacking context (the cards have their own compositing layer, so an// in-card `absolute z-30` popover is painted UNDER the next card).@@ -63,26 +86,9 @@ export default function SyncToPeerButton({minWidth: 220,gap: 4,position: 'below',- contentDeps: [loading, peers.length, subscriptions.length]+ contentDeps: [loading, loadFailed, peers.length, subscriptions.length]});- const refresh = async () => {- setLoading(true);- const [instances, subs] = await Promise.all([- getInstances({ silent: true }).catch(() => null),- listPeerSubscriptions({ recordKind, recordId }, { silent: true })- .then((r) => r?.subscriptions || [])- .catch(() => []),- ]);- // Only show enabled, online-or-connectable peers — Tailnet peers that are- // marked enabled but currently offline are still listed so the user can- // create the subscription now and let the push pipeline retry on reconnect.- const visiblePeers = (instances?.peers || []).filter((p) => p.enabled && p.instanceId);- setPeers(visiblePeers);- setSubscriptions(subs);- setLoading(false);- };-// Per-record subscribability — mirrors server-side guards in peerSync.js// (peerAllowsOutbound + peerHasCategory). Without this triple gate the// UI would let the user subscribe to a peer that silently rejects every@@ -107,10 +113,6 @@ export default function SyncToPeerButton({return !!cats && typeof cats === 'object' && cats[requiredCategory] === true;};- useEffect(() => {- if (open) refresh();- }, [open]);-// Close on Escape and return focus to the trigger so keyboard users don't// have to Tab back through the popover content.useEffect(() => {@@ -202,6 +204,8 @@ export default function SyncToPeerButton({<div className="px-3 py-3 text-xs text-gray-500 flex items-center gap-2"><Loader2 size={12} className="animate-spin" /> Loading peers…</div>+ ) : loadFailed ? (+ <ListLoadError what={loadFailed === peersList ? 'peers' : 'subscriptions'} error={loadFailed.error} onRetry={retryLoad} className="m-2" />) : peers.length === 0 ? (<div className="px-3 py-3 text-xs text-gray-500">No peers configured. <a href="/instances" className="text-port-accent hover:underline">Add one</a>.diff --git a/client/src/components/sharing/SyncToPeerButton.test.jsx b/client/src/components/sharing/SyncToPeerButton.test.jsxindex 36ad8959ec..27db81086f 100644--- a/client/src/components/sharing/SyncToPeerButton.test.jsx+++ b/client/src/components/sharing/SyncToPeerButton.test.jsx@@ -198,4 +198,27 @@ describe('SyncToPeerButton', () => {// Focus returns to the trigger after Escape.expect(document.activeElement).toBe(trigger);});++ it('shows an error row with Retry when the peer read fails, not "No peers configured"', async () => {+ const user = userEvent.setup();+ api.getInstances.mockRejectedValueOnce(new Error('instances 500'));+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load peers — instances 500');+ expect(screen.queryByText(/No peers configured/)).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Retry' }));+ expect(await screen.findByText('Peer A')).toBeTruthy();+ });++ it('does not render unchecked rows when the subscription read fails', async () => {+ const user = userEvent.setup();+ api.listPeerSubscriptions.mockRejectedValueOnce(new Error('subs 500'));+ render(<SyncToPeerButton recordKind="universe" recordId="u1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load subscriptions — subs 500');+ expect(screen.queryByText('Peer A')).toBeNull();+ });});diff --git a/client/src/listFetchConventions.test.js b/client/src/listFetchConventions.test.jsindex ab3cb2651f..bc4de60812 100644--- a/client/src/listFetchConventions.test.js+++ b/client/src/listFetchConventions.test.js@@ -56,18 +56,12 @@ export const LIST_COLLAPSE = /\.catch\(\s*\(\s*\)\s*=>\s*(?:\[\]|\{?\s*set[A-Z]\* site is migrated to `useListResource`; never raise one.*/const KNOWN = Object.freeze({- 'src/components/FeatureProviderPicker.jsx': 1,- 'src/components/QuickTaskWidget.jsx': 2,- 'src/components/apps/JiraConfigPanel.jsx': 1,'src/components/brain/IdeaLoomLists.jsx': 1,'src/components/brain/YoutubeIngestSettings.jsx': 1,'src/components/brain/tabs/ConfigTab.jsx': 1,'src/components/brain/tabs/DailyLogTab.jsx': 1,'src/components/brain/tabs/FeedsTab.jsx': 1,'src/components/brain/tabs/TrustTab.jsx': 1,- 'src/components/cos/tabs/JobsTab.jsx': 1,- 'src/components/cos/tabs/ProviderStatusCard.jsx': 1,- 'src/components/cos/tabs/RunsTab.jsx': 1,'src/components/digital-twin/ObservedTasteEvidence.jsx': 1,'src/components/digital-twin/tabs/AccountsTab.jsx': 3,'src/components/digital-twin/tabs/AutobiographyTab.jsx': 3,@@ -101,23 +95,29 @@ const KNOWN = Object.freeze({'src/components/pipeline/stages/ComicScriptStage.jsx': 1,'src/components/pipeline/stages/NounsStage.jsx': 1,'src/components/privacy/PrivacyOrgsTab.jsx': 2,- 'src/components/settings/SharingTab.jsx': 1,- 'src/components/settings/VoiceTab.jsx': 1,- 'src/components/sharing/ShareToButton.jsx': 2,- 'src/components/sharing/SyncToPeerButton.jsx': 1,'src/components/sprites/ImportPanel.jsx': 1,'src/components/writers-room/AnalysisHistory.jsx': 1,'src/components/writers-room/ExercisePanel.jsx': 1,'src/components/writers-room/PolishPanel.jsx': 1,'src/components/writers-room/StoryboardPanel.jsx': 3,- 'src/pages/AIProviders.jsx': 2,'src/pages/PipelineEditorialChecks.jsx': 1,'src/pages/PipelineManuscriptEditor.jsx': 1,- 'src/pages/PromptManager.jsx': 1,- 'src/pages/Sharing.jsx': 1,'src/pages/Tribe.jsx': 2,});+/**+ * Sites that match on purpose, each with the reason it is not a list collapse.+ * They are not ratcheted down: the count is the number of intentional matches.+ */+const EXEMPT = Object.freeze({+ // `canDelete: true` on a failed usage read lets the server's own+ // 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,+});++const allowedIn = (file) => (KNOWN[file] || 0) + (EXEMPT[file] || 0);+const countIn = (source) => (source.match(LIST_COLLAPSE) || []).length;describe('page list fetches keep a failed read distinct from an empty list', () => {@@ -152,16 +152,16 @@ describe('page list fetches keep a failed read distinct from an empty list', ()if (count > 0) found[file] = count;}const added = Object.entries(found)- .filter(([file, count]) => count > (KNOWN[file] || 0))- .map(([file, count]) => `${file}: ${count} (known ${KNOWN[file] || 0})`);+ .filter(([file, count]) => count > allowedIn(file))+ .map(([file, count]) => `${file}: ${count} (known ${allowedIn(file)})`);expect(added, ['These list fetches render a failed read as an empty list. Read the list through','`useListResource(fetcher)` and render `<ListLoadError onRetry={retry}>` on `state === "error"`,','keeping the empty copy for `state === "ready"`; never `.catch(() => [])` / `setX([])`.',].join('\n')).toEqual([]);- const stale = Object.entries(KNOWN)- .filter(([file, count]) => (found[file] || 0) < count)- .map(([file, count]) => `${file}: now ${found[file] || 0} (known ${count})`);+ const stale = Object.keys({ ...KNOWN, ...EXEMPT })+ .filter((file) => (found[file] || 0) < allowedIn(file))+ .map((file) => `${file}: now ${found[file] || 0} (known ${allowedIn(file)})`);expect(stale, 'A migrated site: lower or remove its KNOWN row so the ratchet holds.').toEqual([]);});});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 1d714a695e..777c75f979 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -105,7 +105,16 @@ export default function AIProviders() {const [showRunPanel, setShowRunPanel] = useState(false);const [runPrompt, setRunPrompt] = useState('');const [selectedWorkspace, setSelectedWorkspace] = useState('');- const [orchestrationProfiles, setOrchestrationProfiles] = useState([]);+ const loadOrchestrationProfiles = useCallback(async () => {+ const result = await api.getOrchestrationProfiles?.({ silent: true });+ return Array.isArray(result) ? result : result?.profiles || [];+ }, []);+ const {+ items: orchestrationProfiles,+ state: orchestrationProfilesState,+ error: orchestrationProfilesError,+ retry: retryOrchestrationProfiles,+ } = useListResource(loadOrchestrationProfiles);const [selectedProfileId, setSelectedProfileId] = useState('');const loadApps = useCallback(async () => {const list = await api.getApps({ silent: true });@@ -116,8 +125,19 @@ export default function AIProviders() {const [activeRun, setActiveRun] = useState(null);const [runOutput, setRunOutput] = useState('');const [showSamples, setShowSamples] = useState(false);- const [sampleProviders, setSampleProviders] = useState([]);- const [loadingSamples, setLoadingSamples] = useState(false);+ // Samples are fetched only once the user asks for them (`showSamples`).+ const loadSamples = useCallback(async () => {+ const result = await api.getSampleProviders({ silent: true });+ return result?.providers || [];+ }, []);+ const {+ items: sampleProviders,+ state: samplesState,+ error: samplesError,+ retry: retrySamples,+ setItems: setSampleProviders,+ } = useListResource(loadSamples, { enabled: showSamples });+ const loadingSamples = showSamples && samplesState === 'loading';const [addingSample, setAddingSample] = useState({});// Samples this machine could actually run. One the server marked// hardware-`unavailable` has no path to becoming usable here, so it is not@@ -288,13 +308,12 @@ export default function AIProviders() {setLoadError(false);let providersFailed = false;const statusRevision = ++observationRevision.current.status;- const [providersData, statusData, orchestrationProfilesData] = await Promise.all([+ const [providersData, statusData] = await Promise.all([api.getProviders({ fresh: true }).catch(() => {providersFailed = true;return null;}),api.getProviderStatuses().catch(() => ({ providers: {} })),- api.getOrchestrationProfiles?.({ silent: true }).catch(() => ({ profiles: [] })),]);if (providersFailed || !providersData) {setLoadError(true);@@ -311,10 +330,6 @@ export default function AIProviders() {: null);}if (statusRevision === observationRevision.current.status) setStatuses(statusData.providers || {});- const profList = Array.isArray(orchestrationProfilesData)- ? orchestrationProfilesData- : orchestrationProfilesData?.profiles || [];- setOrchestrationProfiles(profList);setLoading(false);};@@ -586,12 +601,11 @@ export default function AIProviders() {}};- const handleLoadSamples = async () => {- setLoadingSamples(true);- setShowSamples(true);- const result = await api.getSampleProviders().catch(() => ({ providers: [] }));- setSampleProviders(result.providers || []);- setLoadingSamples(false);+ // First open fetches via `enabled`; re-selecting "Load Samples" while the+ // panel is already open re-fetches.+ const handleLoadSamples = () => {+ if (showSamples) retrySamples();+ else setShowSamples(true);};const handleAddSample = async (provider) => {@@ -922,6 +936,8 @@ export default function AIProviders() {{loadingSamples ? (<div className="text-center py-6 text-gray-400">Loading sample providers...</div>+ ) : samplesState === 'error' ? (+ <ListLoadError what="sample providers" error={samplesError} onRetry={retrySamples} />) : addableSamples.length === 0 ? (<div className="text-center py-6 text-gray-500">{sampleProviders.length === 0@@ -1032,17 +1048,21 @@ export default function AIProviders() {/></div>- <select- aria-label="Orchestration profile"- value={selectedProfileId}- onChange={(e) => setSelectedProfileId(e.target.value)}- className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white w-full sm:w-auto"- >- <option value="">No profile (direct)</option>- {orchestrationProfiles.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>+ {orchestrationProfilesState === 'error' ? (+ <ListLoadError what="orchestration profiles" error={orchestrationProfilesError} onRetry={retryOrchestrationProfiles} />+ ) : (+ <select+ aria-label="Orchestration profile"+ value={selectedProfileId}+ onChange={(e) => setSelectedProfileId(e.target.value)}+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white w-full sm:w-auto"+ >+ <option value="">No profile (direct)</option>+ {orchestrationProfiles.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ )}{appsState === 'error' && (<ListLoadError what="workspaces" error={appsError} onRetry={retryApps} />diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex e0e046c802..2e846d1fd2 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -2473,4 +2473,50 @@ describe('AIProviders list resources (#12171)', () => {});expect(await screen.findByLabelText('Known PortOS peer')).toBeInTheDocument();});++ it('shows error row with Retry when orchestration profiles fail to load, not an empty profile select', async () => {+ vi.clearAllMocks();+ api.getProviders.mockResolvedValue({ providers: [{ id: 'p1', name: 'P1', type: 'api', enabled: true }], activeProvider: 'p1' });+ api.getApps.mockResolvedValue([]);+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getOrchestrationProfiles.mockRejectedValueOnce(new Error('profiles offline'));++ await renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Run Prompt' }));++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load orchestration profiles — profiles offline');+ expect(screen.queryByLabelText('Orchestration profile')).not.toBeInTheDocument();++ api.getOrchestrationProfiles.mockResolvedValueOnce({ profiles: [{ id: 'deep-research', name: 'Deep Research' }] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ const profileSelect = await screen.findByLabelText('Orchestration profile');+ expect(within(profileSelect).getByRole('option', { name: 'Deep Research' })).toBeInTheDocument();+ });++ it('shows error row with Retry when sample providers fail to load, not "all samples already added"', async () => {+ vi.clearAllMocks();+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });+ api.getApps.mockResolvedValue([]);+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getSampleProviders.mockRejectedValueOnce(new Error('samples offline'));++ await renderPage();+ await clickLoadSamples();++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load sample providers — samples offline');+ expect(screen.queryByText(/All sample providers are already in your configuration/)).not.toBeInTheDocument();++ api.getSampleProviders.mockResolvedValueOnce({+ providers: [{ id: 'sample-1', name: 'Sample AI', type: 'api', enabled: true, endpoint: 'https://api.example.com', models: ['m1'] }],+ });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByText('Sample AI')).toBeInTheDocument();+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ });});diff --git a/client/src/pages/Sharing.jsx b/client/src/pages/Sharing.jsxindex 3fccf8ba18..976303cff2 100644--- a/client/src/pages/Sharing.jsx+++ b/client/src/pages/Sharing.jsx@@ -7,13 +7,15 @@* that get stamped as the source on every outgoing share.*/-import { useEffect, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { useParams, useNavigate } from 'react-router';import {Share2, Plus, Trash2, Folder, Inbox, History, Save, Loader2, Check, X, Users, AlertCircle, RefreshCw, Copy, GitMerge,} from 'lucide-react';import PageHeader from '../components/PageHeader';import PageSkeleton from '../components/ui/PageSkeleton';+import ListLoadError from '../components/ui/ListLoadError';+import useListResource from '../hooks/useListResource';import toast from '../components/ui/Toast';import InlineConfirmRow from '../components/ui/InlineConfirmRow';import { FormField } from '../components/ui/FormField';@@ -111,9 +113,13 @@ export default function Sharing() {// deep-linkable and reload-safe. `selectedId` is the route param.function SharingBuckets({ selectedId }) {const navigate = useNavigate();- const [buckets, setBuckets] = useState([]);- const [, setLocalSchemaVersion] = useState(null);- const [loading, setLoading] = useState(true);+ const fetchBuckets = useCallback(() => listShareBuckets({ silent: true }).then((resp) => resp?.buckets || []), []);+ const { items: buckets, state: bucketsState, error: bucketsError, retry: retryBuckets, setItems: setBuckets } = useListResource(fetchBuckets);+ const loading = bucketsState === 'loading';+ // 'loading' | 'ready' | 'error'. The display-name editor is seeded from these+ // settings and its Save replaces them, so it stays locked until the read succeeds.+ const [settingsState, setSettingsState] = useState('loading');+ const [settingsError, setSettingsError] = useState(null);const [showAdd, setShowAdd] = useState(false);const [form, setForm] = useState(emptyForm);const [creating, setCreating] = useState(false);@@ -133,27 +139,32 @@ function SharingBuckets({ selectedId }) {const { isConfirming: isRemoveArmed, requestDelete: armRemove, cancelDelete: cancelRemove, confirmDelete: confirmRemove } = useConfirmDelete();- // Load buckets + settings on mount.+ // Auto-select the first bucket when the URL doesn't already name one, so a+ // bare /sharing lands on a populated detail panel (replace: no history spam).useEffect(() => {- Promise.all([- listShareBuckets({ silent: true }).catch(() => ({ buckets: [] })),- getSettings().catch(() => ({})),- ]).then(([bResp, settings]) => {- const list = bResp?.buckets || [];- setBuckets(list);- setLocalSchemaVersion(bResp?.localSchemaVersion ?? null);- // Auto-select the first bucket when the URL doesn't already name one, so a- // bare /sharing lands on a populated detail panel (replace: no history spam).- if (!selectedId && list.length > 0) navigate(`/sharing/buckets/${encodeURIComponent(list[0].id)}`, { replace: true });- const display = settings?.sharingDisplayName || '';- const bio = settings?.sharingBio || '';- setSharingDisplayName(display);- setSharingBio(bio);- setSavedDisplayName(display);- setSavedBio(bio);- setLoading(false);- });+ if (bucketsState === 'ready' && !selectedId && buckets.length > 0) {+ navigate(`/sharing/buckets/${encodeURIComponent(buckets[0].id)}`, { replace: true });+ }+ }, [bucketsState]);++ const loadSettings = useCallback(() => {+ setSettingsState('loading');+ return getSettings({ silent: true })+ .then((settings) => {+ const display = settings?.sharingDisplayName || '';+ const bio = settings?.sharingBio || '';+ setSharingDisplayName(display);+ setSharingBio(bio);+ setSavedDisplayName(display);+ setSavedBio(bio);+ setSettingsState('ready');+ })+ .catch((err) => {+ setSettingsError(err instanceof Error ? err : new Error('Request failed'));+ setSettingsState('error');+ });}, []);+ useEffect(() => { loadSettings(); }, [loadSettings]);// Lazy-load inbox + activity when a bucket is selected.const loadInbox = (bucketId) => {@@ -288,7 +299,7 @@ function SharingBuckets({ selectedId }) {const selected = buckets.find((b) => b.id === selectedId) || null;// A bucketId in the URL that isn't in the loaded list (removed / bad deep link).- const bucketNotFound = !!selectedId && !loading && !selected;+ const bucketNotFound = !!selectedId && bucketsState === 'ready' && !selected;const displayNameDirty = sharingDisplayName !== savedDisplayName || sharingBio !== savedBio;return (@@ -327,12 +338,16 @@ function SharingBuckets({ selectedId }) {<p className="text-xs text-gray-500 mb-3">This name is stamped as the <em>source</em> on every share you send. Recipients see it as attribution. Each bucket can override this with its own name.</p>+ {settingsState === 'error' && (+ <ListLoadError what="your display name" error={settingsError} onRetry={loadSettings} className="mb-3" />+ )}<div className="grid grid-cols-1 md:grid-cols-[1fr_2fr_auto] gap-3 items-start"><inputtype="text"aria-label="Your display name"value={sharingDisplayName}onChange={(e) => setSharingDisplayName(e.target.value)}+ disabled={settingsState !== 'ready'}placeholder="Display name (e.g. atomantic)"maxLength={120}className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"@@ -342,6 +357,7 @@ function SharingBuckets({ selectedId }) {aria-label="Your bio / contact note"value={sharingBio}onChange={(e) => setSharingBio(e.target.value)}+ disabled={settingsState !== 'ready'}placeholder="Optional bio / contact note (visible to recipients)"maxLength={2000}className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"@@ -349,7 +365,7 @@ function SharingBuckets({ selectedId }) {<buttontype="button"onClick={handleSaveDisplayName}- disabled={!displayNameDirty || savingDisplayName}+ disabled={!displayNameDirty || savingDisplayName || settingsState !== 'ready'}className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-40 disabled:cursor-not-allowed">{savingDisplayName ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}@@ -452,6 +468,8 @@ function SharingBuckets({ selectedId }) {<aside>{loading ? (<PageSkeleton header="none" label="Loading buckets" cards={3} sidebar={false} />+ ) : bucketsState === 'error' ? (+ <ListLoadError what="buckets" error={bucketsError} onRetry={retryBuckets} />) : buckets.length === 0 ? (<div className="p-4 bg-port-card border border-port-border rounded-lg text-sm text-gray-500">No buckets yet. Click <span className="text-port-accent">Add bucket</span> to register a synced folder.diff --git a/client/src/pages/Sharing.test.jsx b/client/src/pages/Sharing.test.jsxindex 7232595df0..3f67b3cb67 100644--- a/client/src/pages/Sharing.test.jsx+++ b/client/src/pages/Sharing.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor, act } from '@testing-library/react';+import { render, screen, waitFor, act, fireEvent } from '@testing-library/react';import { createMemoryRouter } from 'react-router';import { RouterProvider } from 'react-router/dom';@@ -125,6 +125,49 @@ describe('Sharing bucket detail tab (URL-derived)', () => {});});+describe('Sharing list and settings reads', () => {+ const routes = [+ { path: '/sharing', element: <Sharing /> },+ { path: '/sharing/:section', element: <Sharing /> },+ { path: '/sharing/:section/:bucketId', element: <Sharing /> },+ ];+ const renderAt = (path) => render(<RouterProvider router={createMemoryRouter(routes, { initialEntries: [path] })} />);++ beforeEach(() => {+ vi.clearAllMocks();+ api.getSettings.mockResolvedValue({ sharingDisplayName: 'Alice', sharingBio: '' });+ api.listShareInbox.mockResolvedValue({ items: [] });+ api.listShareActivity.mockResolvedValue({ manifests: [] });+ });++ it('shows an error row with Retry when the bucket read fails, not "No buckets yet"', async () => {+ api.listShareBuckets.mockRejectedValueOnce(new Error('buckets 500'));+ renderAt('/sharing');++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load buckets — buckets 500');+ expect(screen.queryByText(/No buckets yet/)).not.toBeInTheDocument();++ api.listShareBuckets.mockResolvedValue({ buckets: [{ id: 'b1', name: 'Bucket One', path: '/tmp/b1', mode: 'inbox' }] });+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect((await screen.findAllByText('Bucket One')).length).toBeGreaterThan(0);+ });++ it('locks the display-name editor when the settings read fails so a save cannot replace stored values', async () => {+ api.listShareBuckets.mockResolvedValue({ buckets: [] });+ api.getSettings.mockRejectedValueOnce(new Error('settings 500'));+ renderAt('/sharing');++ expect(await screen.findByRole('alert')).toHaveTextContent('Could not load your display name — settings 500');+ const nameInput = screen.getByLabelText('Your display name');+ expect(nameInput).toBeDisabled();+ expect(screen.getByRole('button', { name: /Save/ })).toBeDisabled();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(nameInput).toHaveValue('Alice'));+ expect(nameInput).not.toBeDisabled();+ });+});+// Sharing derives its top section strip from the nav manifest's// `tabGroup: 'sharing'` (#6383) — this pins the id/label/order the page means to// render, and that every manifest section has a presentation entry (icon) indiff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex 8981996f67..9f146abb27 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -87,7 +87,7 @@ export const addProviderTuiMode = (id, options = {}) => request(`/providers/${idmethod: 'POST',...options,}).then(invalidateAfter);-export const getSampleProviders = () => request('/providers/samples');+export const getSampleProviders = (options) => request('/providers/samples', options);// The composition catalog (#7564/#7566): harnesses with enablement, service// instances, bootstrap apps, per-harness (and per-model) effort ladders, the// harness/service compatibility map, and the sanitized presets — everythingdiff --git a/client/src/services/apiRuns.js b/client/src/services/apiRuns.jsindex 5099692deb..3c0a0dfeca 100644--- a/client/src/services/apiRuns.js+++ b/client/src/services/apiRuns.js@@ -1,8 +1,8 @@import { request } from './apiCore.js';// Runs-export const getRuns = (limit = 50, offset = 0, source = 'all') =>- request(`/runs?limit=${limit}&offset=${offset}&source=${source}`);+export const getRuns = (limit = 50, offset = 0, source = 'all', options) =>+ request(`/runs?limit=${limit}&offset=${offset}&source=${source}`, options);export const createRun = (data, options) => request('/runs', {method: 'POST',body: JSON.stringify(data),diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex ed24a91ac7..1df54fde2e 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -525,7 +525,7 @@ export const searchDatadogErrors = (instanceId, serviceName, environment, fromTi});// JIRA-export const getJiraInstances = () => request('/jira/instances');+export const getJiraInstances = (options) => request('/jira/instances', options);export const getJiraProjects = (instanceId, options) => request(`/jira/instances/${instanceId}/projects`, options);export const getJiraBoards = (instanceId, projectKey, options) =>request(`/jira/instances/${instanceId}/projects/${encodeURIComponent(projectKey)}/boards`, options);