Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(async-boundary): migrate error-as-empty surfaces across the audit (#16640)

Arvin Xuc036a2cfd8e5
diff --git a/locales/en-US/memory.json b/locales/en-US/memory.json
index 889ed6b39d3..588a7641bf6 100644
--- a/locales/en-US/memory.json
+++ b/locales/en-US/memory.json
@@ -34,6 +34,8 @@
"context.description": "Description",
"context.empty": "No context memories available",
"context.source": "Source",
+ "detail.notFound.desc": "This memory may have been deleted or is no longer available.",
+ "detail.notFound.title": "Memory not found",
"empty.description": "Memory retrieval is a gradual process. Please engage in more conversations to enrich the content available for recall. Try having deeper interactions with the agent to better capture and store valuable information.",
"empty.search": "No matching memories found",
"empty.title": "No Memories Yet",
diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.json
index 9ee936e16c2..6d0c90048a4 100644
--- a/locales/zh-CN/memory.json
+++ b/locales/zh-CN/memory.json
@@ -34,6 +34,8 @@
"context.description": "描述",
"context.empty": "暂无情境记忆",
"context.source": "来源",
+ "detail.notFound.desc": "这条记忆可能已被删除或不再可用。",
+ "detail.notFound.title": "未找到记忆",
"empty.description": "记忆的提取是渐进式的。积累更多对话,助理会更懂你。试着聊得更深入,让助理捕捉和存储有价值的信息",
"empty.search": "未找到匹配的记忆",
"empty.title": "暂无记忆",
diff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.ts
index 4fbcc50068f..79eec814daf 100644
--- a/packages/locales/src/default/memory.ts
+++ b/packages/locales/src/default/memory.ts
@@ -38,6 +38,8 @@ export default {
'context.description': 'Description',
'context.empty': 'No context memories available',
'context.source': 'Source',
+ 'detail.notFound.desc': 'This memory may have been deleted or is no longer available.',
+ 'detail.notFound.title': 'Memory not found',
'empty.description':
'Memory retrieval is a gradual process. Please engage in more conversations to enrich the content available for recall. Try having deeper interactions with the agent to better capture and store valuable information.',
'empty.search': 'No matching memories found',
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
index 7e06b9ea569..bfc4797c733 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { Link } from 'react-router';
import NotFound from '@/components/404';
+import AsyncError from '@/components/AsyncError';
import AutoSaveHint from '@/components/Editor/AutoSaveHint';
import Loading from '@/components/Loading/BrandTextLoading';
import DocumentPreviewModal from '@/features/DocumentModal/Preview';
@@ -34,7 +35,23 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTo
s.toggleTaskAgentPanel,
]);
- const { isInitialLoading, isNotFound } = useActiveTaskDetail(taskId);
+ const { isInitialLoading, isNotFound, error, onRetry } = useActiveTaskDetail(taskId);
+
+ // A transient fetch failure (network / 500) is not a 404 — keep the URL and
+ // offer Reload instead of the terminal "task was deleted" dead-end below.
+ if (error) {
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, position: 'relative' }}>
+ <NavHeader
+ left={<Breadcrumb taskId={taskId} />}
+ styles={{ left: { paddingLeft: 4, gap: 8 } }}
+ />
+ <Flexbox flex={1} style={{ minHeight: 0, overflowY: 'auto' }}>
+ <AsyncError error={error} variant={'page'} onRetry={onRetry} />
+ </Flexbox>
+ </Flexbox>
+ );
+ }
if (isNotFound) {
return (
diff --git a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.test.ts b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.test.ts
index 6e2cd7ee1bd..cebbf374e59 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.test.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.test.ts
@@ -41,7 +41,7 @@ const buildTaskState = (
setActiveTaskId: vi.fn(),
taskDetailMap: detail ? { 'T-194': { agentId } } : {},
// `useFetchTaskDetail` is read off the store and called with the id.
- useFetchTaskDetail: () => ({ error: taskError }),
+ useFetchTaskDetail: () => ({ error: taskError, mutate: vi.fn() }),
};
};
@@ -111,12 +111,28 @@ describe('useActiveTaskDetail', () => {
expect(result.current.isNotFound).toBe(false);
});
- it('reports not-found when the task fetch errored and there is no cached detail', () => {
- mocks.taskState = buildTaskState({ detail: false, taskError: new Error('not found') });
+ it('reports not-found when the fetch threw a tagged not-found and there is no cached detail', () => {
+ const notFound = Object.assign(new Error('Task not found: T-194'), { code: 'TASK_NOT_FOUND' });
+ mocks.taskState = buildTaskState({ detail: false, taskError: notFound });
const { result } = renderHook(() => useActiveTaskDetail('T-194'));
expect(result.current.isNotFound).toBe(true);
+ expect(result.current.error).toBeUndefined();
+ expect(result.current.isInitialLoading).toBe(false);
+ });
+
+ it('reports a transient fetch error (not a 404) when a network / 500 rejection has no cached detail', () => {
+ const networkError = Object.assign(new Error('Internal Server Error'), {
+ data: { httpStatus: 500 },
+ });
+ mocks.taskState = buildTaskState({ detail: false, taskError: networkError });
+
+ const { result } = renderHook(() => useActiveTaskDetail('T-194'));
+
+ // A merely-errored task must not read as deleted — reload path, not the 404 dead-end.
+ expect(result.current.isNotFound).toBe(false);
+ expect(result.current.error).toBe(networkError);
expect(result.current.isInitialLoading).toBe(false);
});
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts
index 347850a4e29..047c8964327 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useActiveTaskDetail.ts
@@ -1,11 +1,14 @@
import { useEffect } from 'react';
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
import { useAgentStore } from '@/store/agent';
import { useTaskStore } from '@/store/task';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
interface ActiveTaskDetailState {
+ /** A transient fetch failure (network / 500) with no cached detail — distinct from a resolved not-found. Render a reload state, not a 404. */
+ error?: unknown;
/**
* Hard loading gate: the first task snapshot isn't ready yet, OR it is but the
* assignee agent's config (model / heterogeneous runtime) hasn't hydrated. The
@@ -13,8 +16,10 @@ interface ActiveTaskDetailState {
* correctly, so we hold the skeleton until it lands.
*/
isInitialLoading: boolean;
- /** The task fetch settled with an error and there is no cached detail. */
+ /** The task fetch settled with a *resolved* not-found (deleted / never existed) and there is no cached detail. */
isNotFound: boolean;
+ /** Retry the task fetch — wired to the error state's Reload. */
+ onRetry: () => void;
}
/**
@@ -49,18 +54,25 @@ export const useActiveTaskDetail = (taskId?: string): ActiveTaskDetailState => {
// `fetchTaskDetail` throws on a missing task, so `error` is the definitive
// "settled and absent" signal — using it (instead of `!isLoading`) avoids the
// first-paint flash where no fetch has run yet but the cache is still empty.
- const { error: taskError } = useFetchTaskDetail(taskId);
+ const { error: taskError, mutate } = useFetchTaskDetail(taskId);
// Hydrate-only (never touches `activeAgentId`); no-ops on an empty id, so it
// simply activates once the assignee is known from the task detail.
const { isLoading: agentConfigLoading } = useHydrateAgentConfig(isLogin, assigneeAgentId ?? '');
- if (!taskId) return { isInitialLoading: false, isNotFound: false };
+ if (!taskId) return { isInitialLoading: false, isNotFound: false, onRetry: () => {} };
- const isNotFound = !!taskError && !hasTaskDetail;
- // Anything that isn't "we have the detail" or "it's confirmed gone" is still
- // resolving — keep the skeleton up instead of flashing empty/404.
- const isTaskResolving = !hasTaskDetail && !isNotFound;
+ // Split the single `error` signal: `fetchTaskDetail` tags a *resolved*
+ // not-found with `code: 'TASK_NOT_FOUND'`, while a network / 500 rejection
+ // carries an HTTP status instead. Only the former is a real 404 (a dead-end);
+ // a transient failure must offer Reload, not tell the user the task was deleted.
+ const settledWithoutDetail = !!taskError && !hasTaskDetail;
+ const isResolvedNotFound = normalizeAsyncError(taskError).code === 'TASK_NOT_FOUND';
+ const isNotFound = settledWithoutDetail && isResolvedNotFound;
+ const fetchError = settledWithoutDetail && !isResolvedNotFound ? taskError : undefined;
+ // Anything that isn't "we have the detail", "confirmed gone", or "errored" is
+ // still resolving — keep the skeleton up instead of flashing empty/404.
+ const isTaskResolving = !hasTaskDetail && !settledWithoutDetail;
// Block on the assignee config only while its fetch is genuinely in-flight and
// we don't already have it cached. Gating on `isLoading` (not "absent from the
@@ -73,7 +85,9 @@ export const useActiveTaskDetail = (taskId?: string): ActiveTaskDetailState => {
!!assigneeAgentId && isLogin === true && !assigneeInMap && agentConfigLoading;
return {
+ error: fetchError,
isInitialLoading: isTaskResolving || (hasTaskDetail && isAssigneeResolving),
isNotFound,
+ onRetry: () => mutate(),
};
};
diff --git a/src/features/AgentUsage/index.tsx b/src/features/AgentUsage/index.tsx
index c0b5467619b..c2c77643610 100644
--- a/src/features/AgentUsage/index.tsx
+++ b/src/features/AgentUsage/index.tsx
@@ -5,6 +5,7 @@ import { Segmented } from '@lobehub/ui/base-ui';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import AgentBreadcrumb from '@/features/AgentBreadcrumb';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
@@ -43,10 +44,23 @@ const AgentUsage = memo(() => {
const [range, setRange] = useState<TimeRange>('30d');
const [granularity, setGranularity] = useState<AgentUsageGranularity>('day');
- const { data, isLoading } = useAgentUsageStats(activeAgentId ?? '', range, granularity);
+ const { data, isLoading, error, mutate } = useAgentUsageStats(
+ activeAgentId ?? '',
+ range,
+ granularity,
+ );
const rangeLabel = t('usageStats.rangeSuffix', { count: RANGE_DAYS[range] });
+ // A metrics surface's failure default is a *zero-valued object*, not an empty
+ // array — coercing `data?.summary ?? EMPTY_SUMMARY` renders a confident
+ // "$0.00 / 0 tokens" dashboard on a 500 / offline / auth failure, indistinguishable
+ // from an agent that genuinely never ran. Read `error` and, when nothing loaded,
+ // render a failed metric marker + Reload instead of any aggregate. `!error` keeps
+ // the genuine-zero (real empty) and real-data states as before. Gate on `!data`
+ // so a background revalidate error never wipes already-shown numbers.
+ const showError = !!error && !data;
+
return (
<Flexbox height={'100%'} width={'100%'}>
<NavHeader
@@ -92,18 +106,26 @@ const AgentUsage = memo(() => {
/>
</Flexbox>
</Flexbox>
- <StatCards
- isLoading={isLoading}
- rangeLabel={rangeLabel}
- summary={data?.summary ?? EMPTY_SUMMARY}
- />
- </Block>
- <Block padding={20} variant={'outlined'}>
- <UsageTrendChart buckets={data?.buckets} isLoading={isLoading} />
- </Block>
- <Block padding={20} variant={'outlined'}>
- <ModelBreakdown isLoading={isLoading} rows={data?.byModel ?? []} />
+ {showError ? (
+ <AsyncError error={error} variant={'metric'} onRetry={() => mutate()} />
+ ) : (
+ <StatCards
+ isLoading={isLoading}
+ rangeLabel={rangeLabel}
+ summary={data?.summary ?? EMPTY_SUMMARY}
+ />
+ )}
</Block>
+ {!showError && (
+ <>
+ <Block padding={20} variant={'outlined'}>
+ <UsageTrendChart buckets={data?.buckets} isLoading={isLoading} />
+ </Block>
+ <Block padding={20} variant={'outlined'}>
+ <ModelBreakdown isLoading={isLoading} rows={data?.byModel ?? []} />
+ </Block>
+ </>
+ )}
</Flexbox>
</WideScreenContainer>
</Flexbox>
diff --git a/src/features/Messenger/IntegrationDetail/Discord.tsx b/src/features/Messenger/IntegrationDetail/Discord.tsx
index f7efe53cb37..90a48ca8d5a 100644
--- a/src/features/Messenger/IntegrationDetail/Discord.tsx
+++ b/src/features/Messenger/IntegrationDetail/Discord.tsx
@@ -5,6 +5,7 @@ import { LinkIcon, ServerIcon, Trash2Icon, UserIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { usePermission } from '@/hooks/usePermission';
import { buildDiscordOpenBotUrl } from '../constants';
@@ -58,6 +59,8 @@ const DiscordDetail = memo<DiscordDetailProps>(({ appId, botUsername, name, onBa
title: t('messenger.discord.connections.disconnectTitle'),
});
+ if (data.error && data.isInitialLoading)
+ return <AsyncError error={data.error} variant={'block'} onRetry={data.mutate} />;
if (data.isInitialLoading) return <IntegrationDetailSkeleton withNestedContent />;
const { installations, links } = data;
diff --git a/src/features/Messenger/IntegrationDetail/Slack.tsx b/src/features/Messenger/IntegrationDetail/Slack.tsx
index c94734c1c39..11ab9706cd5 100644
--- a/src/features/Messenger/IntegrationDetail/Slack.tsx
+++ b/src/features/Messenger/IntegrationDetail/Slack.tsx
@@ -5,6 +5,7 @@ import { BriefcaseIcon, LinkIcon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { usePermission } from '@/hooks/usePermission';
import { createMessengerLinkModal } from '../LinkModal';
@@ -55,6 +56,8 @@ const SlackDetail = memo<SlackDetailProps>(({ appId, botUsername, name, onBack }
title: t('messenger.slack.connections.disconnectTitle'),
});
+ if (data.error && data.isInitialLoading)
+ return <AsyncError error={data.error} variant={'block'} onRetry={data.mutate} />;
if (data.isInitialLoading) return <IntegrationDetailSkeleton />;
const { installations, links, tenantNameByTenantId } = data;
diff --git a/src/features/Messenger/IntegrationDetail/Telegram.tsx b/src/features/Messenger/IntegrationDetail/Telegram.tsx
index c703483c7b5..1182d07c550 100644
--- a/src/features/Messenger/IntegrationDetail/Telegram.tsx
+++ b/src/features/Messenger/IntegrationDetail/Telegram.tsx
@@ -5,6 +5,7 @@ import { LinkIcon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { usePermission } from '@/hooks/usePermission';
import { createMessengerLinkModal } from '../LinkModal';
@@ -40,6 +41,8 @@ const TelegramDetail = memo<TelegramDetailProps>(({ appId, botUsername, name, on
platform: 'telegram',
});
+ if (data.error && data.isInitialLoading)
+ return <AsyncError error={data.error} variant={'block'} onRetry={data.mutate} />;
if (data.isInitialLoading) return <IntegrationDetailSkeleton withNestedContent />;
const { links } = data;
diff --git a/src/features/Messenger/IntegrationDetail/shared.tsx b/src/features/Messenger/IntegrationDetail/shared.tsx
index 4d9d77ce729..48f4f196719 100644
--- a/src/features/Messenger/IntegrationDetail/shared.tsx
+++ b/src/features/Messenger/IntegrationDetail/shared.tsx
@@ -393,13 +393,22 @@ export const useMessengerData = (platform: MessengerPlatform) => {
const installations = (installationsSWR.data ?? []).filter((i) => i.platform === platform);
const tenantNameByTenantId = new Map(installations.map((i) => [i.tenantId, i.tenantName]));
const isInitialLoading = linksSWR.data === undefined || installationsSWR.data === undefined;
+ // A failed links / installations fetch leaves `data === undefined`, which the
+ // callers otherwise read as a permanent skeleton — surface the error so the
+ // detail renders a failure + Retry instead (ux Read §1.1).
+ const error = linksSWR.error ?? installationsSWR.error;
return {
+ error,
installations,
installationsMutate: installationsSWR.mutate,
isInitialLoading,
links,
linksMutate: linksSWR.mutate,
+ mutate: () => {
+ void linksSWR.mutate();
+ void installationsSWR.mutate();
+ },
tenantNameByTenantId,
};
};
diff --git a/src/features/Messenger/index.tsx b/src/features/Messenger/index.tsx
index b0794d9fca5..5a5a1ed1075 100644
--- a/src/features/Messenger/index.tsx
+++ b/src/features/Messenger/index.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
import useSWR from 'swr';
+import AsyncBoundary from '@/components/AsyncBoundary';
import ImperativeModal from '@/components/ImperativeModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { messengerKeys } from '@/libs/swr/keys';
@@ -134,16 +135,23 @@ const MessengerSettings = memo(() => {
) : (
<>
<Text type="secondary">{t('messenger.subtitle')}</Text>
- {platformsSWR.isLoading ? (
- <Skeleton active paragraph={{ rows: 3 }} title={false} />
- ) : platforms.length === 0 ? (
- <div className={styles.emptyState}>{t('messenger.noPlatformsConfigured')}</div>
- ) : (
+ <AsyncBoundary
+ data={platformsSWR.data}
+ error={platformsSWR.error}
+ errorVariant={'block'}
+ isEmpty={platforms.length === 0}
+ isLoading={platformsSWR.isLoading}
+ loading={<Skeleton active paragraph={{ rows: 3 }} title={false} />}
+ empty={
+ <div className={styles.emptyState}>{t('messenger.noPlatformsConfigured')}</div>
+ }
+ onRetry={() => platformsSWR.mutate()}
+ >
<IntegrationList
platforms={platforms}
onSelect={(platform) => navigate(`/settings/messenger/${platform}`)}
/>
- )}
+ </AsyncBoundary>
</>
)}
</Flexbox>
diff --git a/src/features/Portal/TaskDetail/Body.tsx b/src/features/Portal/TaskDetail/Body.tsx
index 8fd09ef216a..938e025efe9 100644
--- a/src/features/Portal/TaskDetail/Body.tsx
+++ b/src/features/Portal/TaskDetail/Body.tsx
@@ -3,6 +3,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import NotFound from '@/components/404';
+import AsyncError from '@/components/AsyncError';
import Loading from '@/components/Loading/BrandTextLoading';
import { TaskDetailSections, TopicChatDrawer, useActiveTaskDetail } from '@/features/AgentTasks';
import DocumentPreviewModal from '@/features/DocumentModal/Preview';
@@ -14,10 +15,20 @@ const Body = memo(() => {
const taskId = useChatStore(chatPortalSelectors.taskDetailId);
// Same data wiring as the full /task/[tid] page — owns activeTaskId + polling
// fetch so the shared section components resolve to this task.
- const { isInitialLoading, isNotFound } = useActiveTaskDetail(taskId);
+ const { isInitialLoading, isNotFound, error, onRetry } = useActiveTaskDetail(taskId);
if (!taskId) return null;
+ // A transient fetch failure keeps the URL and offers Reload — distinct from a
+ // resolved not-found (deleted task), which is a terminal 404.
+ if (error) {
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflowY: 'auto' }}>
+ <AsyncError error={error} variant={'page'} onRetry={onRetry} />
+ </Flexbox>
+ );
+ }
+
if (isNotFound) {
return (
<Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflowY: 'auto' }}>
diff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
index 12b79ab762d..3c646ecd1ad 100644
--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
@@ -8,6 +8,7 @@ import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Virtuoso } from 'react-virtuoso';
+import AsyncError from '@/components/AsyncError';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useClientDataSWR } from '@/libs/swr';
import { resourceKeys } from '@/libs/swr/keys';
@@ -40,7 +41,12 @@ const SearchResultsOverlay = memo(() => {
const isActive = !!searchQuery && searchQuery.length > 0;
- const { data: rawData, isLoading } = useClientDataSWR(
+ const {
+ data: rawData,
+ isLoading,
+ error,
+ mutate,
+ } = useClientDataSWR(
isActive
? resourceKeys.search({
category: libraryId ? undefined : category,
@@ -110,6 +116,14 @@ const SearchResultsOverlay = memo(() => {
<Center height="100%">
<NeuralNetworkLoading size={48} />
</Center>
+ ) : error && (!data || data.length === 0) ? (
+ // A failed search fetch used to fall through to the "no results" state, telling
+ // the user their query matched nothing when the request actually errored
+ // (Read §1.1). Branch the failure before the no-match state; the no-match
+ // variant below is untouched and still handles a genuine zero-result search.
+ <Center height="100%">
+ <AsyncError error={error} variant={'block'} onRetry={() => mutate()} />
+ </Center>
) : !data || data.length === 0 ? (
<Center height="100%">
<Flexbox align="center" gap={8}>
diff --git a/src/features/ResourceManager/components/Explorer/index.tsx b/src/features/ResourceManager/components/Explorer/index.tsx
index 00477b1144b..493edda4794 100644
--- a/src/features/ResourceManager/components/Explorer/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/index.tsx
@@ -3,6 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { memo, useMemo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useFolderPath } from '@/routes/(main)/resource/features/hooks/useFolderPath';
import { useResourceManagerUrlSync } from '@/routes/(main)/resource/features/hooks/useResourceManagerUrlSync';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
@@ -64,8 +65,11 @@ const ResourceExplorer = memo(() => {
[category, libraryId, currentFolderSlug, sortType, sorter, listVisibility],
);
- // Use SWR for data fetching with automatic caching and revalidation
- const { isLoading, isValidating } = useFetchResources(queryParams);
+ // Use SWR for data fetching with automatic caching and revalidation.
+ // `error` / `mutate` were previously discarded, so a failed resource fetch fell
+ // through to the "create your first resource" onboarding empty (Read §1.1
+ // failure-as-empty). Capture them and branch the failure before empty.
+ const { isLoading, isValidating, error, mutate } = useFetchResources(queryParams);
// Get resource data from store (updated by SWR hook)
const { resourceList } = useResourceStore();
@@ -104,17 +108,34 @@ const ResourceExplorer = memo(() => {
<Flexbox height={'100%'}>
<Header />
<div style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
- {showEmptyStatus ? (
- <EmptyPlaceholder />
- ) : viewMode === 'list' ? (
- <ListView isLoading={isLoading} isValidating={isValidating} queryParams={queryParams} />
- ) : (
- <MasonryView
- isLoading={isLoading}
- isValidating={isValidating}
- queryParams={queryParams}
- />
- )}
+ {/*
+ AsyncBoundary gates error → empty → data. `isLoading` stays false here
+ because the list/masonry views own their own skeletons (loading is a
+ content swap inside them, not a full relayout), so the boundary only
+ arbitrates the failed-vs-empty-vs-data precedence the call site got wrong.
+ */}
+ <AsyncBoundary
+ data={data}
+ empty={<EmptyPlaceholder />}
+ error={error}
+ errorVariant={'block'}
+ isEmpty={showEmptyStatus}
+ onRetry={() => mutate()}
+ >
+ {viewMode === 'list' ? (
+ <ListView
+ isLoading={isLoading}
+ isValidating={isValidating}
+ queryParams={queryParams}
+ />
+ ) : (
+ <MasonryView
+ isLoading={isLoading}
+ isValidating={isValidating}
+ queryParams={queryParams}
+ />
+ )}
+ </AsyncBoundary>
<SearchResultsOverlay />
</div>
</Flexbox>
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
index 7da37cbaeae..52cb2ee1282 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/index.tsx
@@ -7,6 +7,7 @@ import { memo, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { VList } from 'virtua';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useFolderPath } from '@/routes/(main)/resource/features/hooks/useFolderPath';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { useFileStore } from '@/store/file';
@@ -36,9 +37,11 @@ const LibraryHierarchy = memo(() => {
const children = useTreeStore((s) => s.children);
const expanded = useTreeStore((s) => s.expanded);
const status = useTreeStore((s) => s.status);
+ const errors = useTreeStore((s) => s.errors);
const init = useTreeStore((s) => s.init);
const expandAncestors = useTreeStore((s) => s.expandAncestors);
const toggle = useTreeStore((s) => s.toggle);
+ const loadChildren = useTreeStore((s) => s.loadChildren);
// Reuse Explorer Breadcrumb's SWR cache so the sidebar doesn't double-fetch
// document.getFolderBreadcrumb when navigating into a folder.
@@ -75,52 +78,63 @@ const LibraryHierarchy = memo(() => {
return result;
}, [children, expanded]);
- if (isLoading && !children['']) {
- return <TreeSkeleton />;
- }
-
const selectedKey = currentFolderSlug ?? null;
- const isRootEmpty = !isLoading && libraryId && visibleNodes.length === 0;
-
- if (isRootEmpty) {
- return (
- <KnowledgeBaseListProvider>
- <Center gap={16} padding={24} style={{ height: '100%', textAlign: 'center' }}>
- <Icon color={cssVar.colorTextQuaternary} icon={FolderPlusIcon} size={36} />
- <Flexbox align={'center'} gap={4}>
- <Text strong>{t('library.hierarchy.empty.title')}</Text>
- <Text style={{ fontSize: 12 }} type={'secondary'}>
- {t('library.hierarchy.empty.desc')}
- </Text>
- </Flexbox>
- <AddButton />
- </Center>
- </KnowledgeBaseListProvider>
- );
- }
+
+ const hasData = visibleNodes.length > 0;
+ // The root fetch is in flight with nothing cached yet.
+ const isRootLoading = isLoading && !children[''];
+ // Only genuinely empty once a library is selected and the root resolved with no rows.
+ const isRootEmpty = !!libraryId && visibleNodes.length === 0;
+ // A *failed* root load — previously swallowed to 'idle', which fell through to the
+ // "add folder" empty (Read §1.1 failure-as-empty). Branch it before empty.
+ const rootError = status[''] === 'error' ? errors[''] : undefined;
+
+ const emptyState = (
+ <Center gap={16} padding={24} style={{ height: '100%', textAlign: 'center' }}>
+ <Icon color={cssVar.colorTextQuaternary} icon={FolderPlusIcon} size={36} />
+ <Flexbox align={'center'} gap={4}>
+ <Text strong>{t('library.hierarchy.empty.title')}</Text>
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {t('library.hierarchy.empty.desc')}
+ </Text>
+ </Flexbox>
+ <AddButton />
+ </Center>
+ );
return (
<KnowledgeBaseListProvider>
- <Flexbox paddingInline={4} style={{ height: '100%' }}>
- <VList
- bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
- style={{ height: '100%' }}
- >
- {visibleNodes.map(({ item, key, level, parentKey }) => (
- <div key={key} style={{ paddingBottom: 2 }}>
- <HierarchyNode
- isExpanded={!!expanded[item.id]}
- isLoading={status[item.id] === 'loading'}
- item={item}
- level={level}
- parentKey={parentKey}
- selectedKey={selectedKey}
- onToggle={toggle}
- />
- </div>
- ))}
- </VList>
- </Flexbox>
+ <AsyncBoundary
+ data={hasData ? (children[''] ?? true) : undefined}
+ empty={emptyState}
+ error={rootError}
+ errorVariant={'block'}
+ isEmpty={isRootEmpty}
+ isLoading={isRootLoading}
+ loading={<TreeSkeleton />}
+ onRetry={() => loadChildren('')}
+ >
+ <Flexbox paddingInline={4} style={{ height: '100%' }}>
+ <VList
+ bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
+ style={{ height: '100%' }}
+ >
+ {visibleNodes.map(({ item, key, level, parentKey }) => (
+ <div key={key} style={{ paddingBottom: 2 }}>
+ <HierarchyNode
+ isExpanded={!!expanded[item.id]}
+ isLoading={status[item.id] === 'loading'}
+ item={item}
+ level={level}
+ parentKey={parentKey}
+ selectedKey={selectedKey}
+ onToggle={toggle}
+ />
+ </div>
+ ))}
+ </VList>
+ </Flexbox>
+ </AsyncBoundary>
</KnowledgeBaseListProvider>
);
});
diff --git a/src/features/SkillsList/SkillSection.tsx b/src/features/SkillsList/SkillSection.tsx
index a2c9b4e5787..8f93f673d51 100644
--- a/src/features/SkillsList/SkillSection.tsx
+++ b/src/features/SkillsList/SkillSection.tsx
@@ -2,6 +2,7 @@ import { Accordion, AccordionItem, Center, Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo, type ReactNode, useState } from 'react';
+import AsyncError from '@/components/AsyncError';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
export interface SkillSectionHeader {
@@ -16,8 +17,16 @@ export interface SkillSectionHeader {
export interface SkillSectionProps {
children?: ReactNode;
emptyText?: string;
+ /**
+ * A failed fetch. When set (and there's no data), the body renders a failure +
+ * Retry instead of the empty placeholder — a failed scan must not read as
+ * "no skills" (ux Read §1.1).
+ */
+ error?: unknown;
isEmpty?: boolean;
isLoading?: boolean;
+ /** Retry the failed fetch (SWR `mutate`). */
+ onRetry?: () => void;
/**
* When provided, wraps content in a header + optional Accordion. Omit to
* render `children` flat (the caller controls layout entirely).
@@ -65,11 +74,21 @@ HeaderRow.displayName = 'SkillSectionHeaderRow';
interface BodyProps {
children?: ReactNode;
emptyText?: string;
+ error?: unknown;
isEmpty?: boolean;
isLoading?: boolean;
+ onRetry?: () => void;
}
-const Body = memo<BodyProps>(({ children, emptyText, isEmpty, isLoading }) => {
+const Body = memo<BodyProps>(({ children, emptyText, error, isEmpty, isLoading, onRetry }) => {
+ // Error before empty: a failed scan gets its own state, never a "no skills".
+ if (error && isEmpty) {
+ return (
+ <Flexbox paddingBlock={4} paddingInline={4}>
+ <AsyncError error={error} variant={'inline'} onRetry={onRetry} />
+ </Flexbox>
+ );
+ }
if (isLoading) {
return (
<Center paddingBlock={12}>
@@ -90,12 +109,18 @@ const Body = memo<BodyProps>(({ children, emptyText, isEmpty, isLoading }) => {
Body.displayName = 'SkillSectionBody';
const SkillSection = memo<SkillSectionProps>(
- ({ children, emptyText, isEmpty, isLoading, sectionHeader }) => {
+ ({ children, emptyText, error, isEmpty, isLoading, onRetry, sectionHeader }) => {
// Hook always runs regardless of whether sectionHeader is provided.
const [expanded, setExpanded] = useState(sectionHeader?.defaultExpanded ?? true);
const body = (
- <Body emptyText={emptyText} isEmpty={isEmpty} isLoading={isLoading}>
+ <Body
+ emptyText={emptyText}
+ error={error}
+ isEmpty={isEmpty}
+ isLoading={isLoading}
+ onRetry={onRetry}
+ >
{children}
</Body>
);
diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.ts
index 6fbebf490ea..06e8d1bb2ef 100644
--- a/src/features/SkillsList/useProjectSkills.ts
+++ b/src/features/SkillsList/useProjectSkills.ts
@@ -16,9 +16,13 @@ export interface UseProjectSkillsResult {
* rename / delete are stubbed (disabled) until the filesystem-mutation IPC
* lands.
*/
+ /** The thrown error from the SWR scan, if it failed. */
+ error: unknown;
getRowActions: (item: SkillListItem) => SkillRowAction[];
isLoading: boolean;
items: SkillListItem[];
+ /** Retry the failed scan (SWR `mutate`). */
+ mutate: () => void;
onOpenFile: (item: SkillListItem, relativePath: string) => void;
onOpenSkill: (item: SkillListItem) => void;
raw: ListProjectSkillsResult | undefined;
@@ -45,7 +49,7 @@ export const useProjectSkills = (
const openLocalFile = useChatStore((s) => s.openLocalFile);
const isRemote = !!deviceId;
- const { data, isLoading } = useFetchProjectSkills(workingDirectory, deviceId);
+ const { data, error, isLoading, mutate } = useFetchProjectSkills(workingDirectory, deviceId);
// listProjectSkills approves `data.root` for preview. Hand that exact value
// back to openLocalFile so LocalFileProtocolManager.createPreviewUrl's
@@ -122,5 +126,16 @@ export const useProjectSkills = (
];
};
- return { getRowActions, isLoading, items, onOpenFile, onOpenSkill, raw: data };
+ return {
+ error,
+ getRowActions,
+ isLoading,
+ items,
+ mutate: () => {
+ void mutate();
+ },
+ onOpenFile,
+ onOpenSkill,
+ raw: data,
+ };
};
diff --git a/src/routes/(main)/agent/channel/index.tsx b/src/routes/(main)/agent/channel/index.tsx
index 35daf518d1c..be93a86f319 100644
--- a/src/routes/(main)/agent/channel/index.tsx
+++ b/src/routes/(main)/agent/channel/index.tsx
@@ -5,6 +5,7 @@ import { createStaticStyles } from 'antd-style';
import { memo, useEffect, useMemo, useState } from 'react';
import { useParams } from 'react-router';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Loading from '@/components/Loading/BrandTextLoading';
import NavHeader from '@/features/NavHeader';
import { usePermission } from '@/hooks/usePermission';
@@ -34,12 +35,18 @@ const ChannelPage = memo(() => {
const [activeProviderId, setActiveProviderId] = useState<string>('');
const { allowed: canEdit } = usePermission('edit_own_content');
- const { data: platforms, isLoading: platformsLoading } = useAgentStore((s) =>
- s.useFetchPlatformDefinitions(),
- );
- const { data: providers, isLoading: providersLoading } = useAgentStore((s) =>
- s.useFetchBotProviders(aid),
- );
+ const {
+ data: platforms,
+ isLoading: platformsLoading,
+ error: platformsError,
+ mutate: mutatePlatforms,
+ } = useAgentStore((s) => s.useFetchPlatformDefinitions());
+ const {
+ data: providers,
+ isLoading: providersLoading,
+ error: providersError,
+ mutate: mutateProviders,
+ } = useAgentStore((s) => s.useFetchBotProviders(aid));
const triggerRefreshAllBotStatuses = useAgentStore((s) => s.triggerRefreshAllBotStatuses);
const enableImessage = useUserStore(labPreferSelectors.enableImessage);
@@ -52,6 +59,17 @@ const ChannelPage = memo(() => {
}, [aid, canEdit, triggerRefreshAllBotStatuses]);
const isLoading = platformsLoading || providersLoading;
+ const error = platformsError ?? providersError;
+
+ // Both fetches carry `fallbackData: []`, so a *failed* fetch leaves
+ // `platforms = []` and `allPlatforms` collapses to just the frontend-only
+ // `COMING_SOON_PLATFORMS` — `length > 0` stays true and the surface would
+ // render a plausible coming-soon-only catalog (every real / connected channel
+ // silently dropped). So "has data" is *not* the merged length: it's whether the
+ // real fetch actually yielded platforms. Gate on the raw fetched `platforms`
+ // (never the static merge) and require the providers fetch to have not errored,
+ // so a failed load branches to an error state before we merge the static half.
+ const hasData = (platforms?.length ?? 0) > 0 && !providersError;
// Merge server-side platforms with frontend-only coming-soon entries.
// Coming-soon entries shadow a server-registered platform of the same id, so a
@@ -100,32 +118,42 @@ const ChannelPage = memo(() => {
<Flexbox flex={1} height={'100%'}>
<NavHeader />
<Flexbox flex={1} style={{ overflowY: 'auto' }}>
- {isLoading && <Loading debugId="ChannelPage" />}
-
- {!isLoading && allPlatforms.length > 0 && activePlatformDef && (
- <div className={styles.container}>
- <PlatformList
- activeId={effectiveActiveId}
- agentId={aid}
- disabled={!canEdit}
- platforms={allPlatforms}
- providers={providers}
- runtimeStatuses={platformRuntimeStatuses}
- onSelect={setActiveProviderId}
- />
- {activePlatformDef.comingSoon ? (
- <ComingSoonDetail platformDef={activePlatformDef} />
- ) : (
- <PlatformDetail
+ <AsyncBoundary
+ data={hasData ? platforms : undefined}
+ error={error}
+ errorVariant={'block'}
+ isLoading={isLoading}
+ loading={<Loading debugId="ChannelPage" />}
+ onRetry={() => {
+ mutatePlatforms();
+ mutateProviders();
+ }}
+ >
+ {activePlatformDef && (
+ <div className={styles.container}>
+ <PlatformList
+ activeId={effectiveActiveId}
agentId={aid}
- currentConfig={currentConfig}
disabled={!canEdit}
- platformDef={activePlatformDef}
- runtimeStatus={platformRuntimeStatuses.get(activePlatformDef.id)}
+ platforms={allPlatforms}
+ providers={providers}
+ runtimeStatuses={platformRuntimeStatuses}
+ onSelect={setActiveProviderId}
/>
- )}
- </div>
- )}
+ {activePlatformDef.comingSoon ? (
+ <ComingSoonDetail platformDef={activePlatformDef} />
+ ) : (
+ <PlatformDetail
+ agentId={aid}
+ currentConfig={currentConfig}
+ disabled={!canEdit}
+ platformDef={activePlatformDef}
+ runtimeStatus={platformRuntimeStatuses.get(activePlatformDef.id)}
+ />
+ )}
+ </div>
+ )}
+ </AsyncBoundary>
</Flexbox>
</Flexbox>
);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
index 9a1f9258f72..a99be3d8704 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/ProjectLevelSkills.tsx
@@ -18,12 +18,25 @@ interface ProjectLevelSkillsProps {
const ProjectLevelSkills = memo<ProjectLevelSkillsProps>(
({ deviceId, hideHeader, workingDirectory }) => {
const { t } = useTranslation('chat');
- const { getRowActions, items, onOpenFile, onOpenSkill } = useProjectSkills(
+ const { error, getRowActions, items, mutate, onOpenFile, onOpenSkill } = useProjectSkills(
workingDirectory,
deviceId,
);
- if (items.length === 0) return null;
+ // A failed scan must surface an error + Retry, not silently vanish (ux Read
+ // §1.1). Only genuinely-empty (no error) keeps the "hide the section" behavior.
+ if (items.length === 0) {
+ if (!error) return null;
+ if (hideHeader) return <SkillSection isEmpty error={error} onRetry={mutate} />;
+ return (
+ <SkillSection
+ isEmpty
+ error={error}
+ sectionHeader={{ title: t('workingPanel.skills.section.project') }}
+ onRetry={mutate}
+ />
+ );
+ }
const list = (
<SkillsList
diff --git a/src/routes/(main)/agent/profile/index.tsx b/src/routes/(main)/agent/profile/index.tsx
index 4e63c85195b..bcc76de0fd7 100644
--- a/src/routes/(main)/agent/profile/index.tsx
+++ b/src/routes/(main)/agent/profile/index.tsx
@@ -4,6 +4,7 @@ import { Flexbox } from '@lobehub/ui';
import { type FC } from 'react';
import { memo, Suspense } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Loading from '@/components/Loading/BrandTextLoading';
import AgentBuilder from '@/features/AgentBuilder';
import WideScreenContainer from '@/features/WideScreenContainer';
@@ -34,36 +35,52 @@ const styles = StyleSheet.create({
const ProfileArea = memo(() => {
const editor = useProfileStore((s) => s.editor);
const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
+ // `isAgentConfigLoading` is data-presence ("no config in the map yet"), so a
+ // *failed* config fetch keeps the map empty and would spin forever. The store
+ // records the fetch error in `agentConfigErrorMap` — read it so failure shows a
+ // reload state (via `retryAgentConfigFetch`) instead of a permanent skeleton.
+ const configError = useAgentStore(agentSelectors.currentAgentConfigError);
+ const retryAgentConfigFetch = useAgentStore((s) => s.retryAgentConfigFetch);
const { allowed: canEdit } = usePermission('edit_own_content');
return (
<>
<Flexbox flex={1} height={'100%'} style={styles.profileArea}>
- {isAgentConfigLoading ? (
- <Loading debugId="ProfileArea" />
- ) : (
- <>
- <Header />
- <Flexbox
- horizontal
- height={'100%'}
- style={{ ...styles.contentWrapper, cursor: canEdit ? 'text' : 'default' }}
- width={'100%'}
- onClick={(e) => {
- if (!canEdit) return;
- // Only focus editor for clicks within this DOM element,
- // not from React portal (e.g. Modal) whose DOM is outside this tree
- if (e.currentTarget.contains(e.target as Node)) {
- editor?.focus();
- }
- }}
- >
- <WideScreenContainer>
- <ProfileEditor />
- </WideScreenContainer>
- </Flexbox>
- </>
- )}
+ <AsyncBoundary
+ // Config lives in the map only after a successful fetch — so "settled"
+ // is exactly "not still loading". A truthy sentinel on success lets the
+ // error branch win over the loading branch when the fetch failed (the
+ // map is empty in both, but the error should show, not the skeleton).
+ data={isAgentConfigLoading ? undefined : true}
+ error={configError}
+ errorVariant={'page'}
+ // `isAgentConfigLoading` is data-presence (empty map), true on error too;
+ // gate on `!configError` so under loading→error precedence the loading
+ // branch yields to the error state instead of spinning forever.
+ isLoading={isAgentConfigLoading && !configError}
+ loading={<Loading debugId="ProfileArea" />}
+ onRetry={() => retryAgentConfigFetch()}
+ >
+ <Header />
+ <Flexbox
+ horizontal
+ height={'100%'}
+ style={{ ...styles.contentWrapper, cursor: canEdit ? 'text' : 'default' }}
+ width={'100%'}
+ onClick={(e) => {
+ if (!canEdit) return;
+ // Only focus editor for clicks within this DOM element,
+ // not from React portal (e.g. Modal) whose DOM is outside this tree
+ if (e.currentTarget.contains(e.target as Node)) {
+ editor?.focus();
+ }
+ }}
+ >
+ <WideScreenContainer>
+ <ProfileEditor />
+ </WideScreenContainer>
+ </Flexbox>
+ </AsyncBoundary>
</Flexbox>
{/* Mounted unconditionally (not behind the config-loading gate) so the lock
is peeked on open and resolved before the editor renders. */}
diff --git a/src/routes/(main)/community/(list)/agent/index.tsx b/src/routes/(main)/community/(list)/agent/index.tsx
index c1ff7d5e584..20c6a46787f 100644
--- a/src/routes/(main)/community/(list)/agent/index.tsx
+++ b/src/routes/(main)/community/(list)/agent/index.tsx
@@ -3,11 +3,13 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
import { type AssistantQueryParams } from '@/types/discover';
import { AssistantSorts, DiscoverTab } from '@/types/discover';
+import AssistantEmpty from '../../features/AssistantEmpty';
import Pagination from '../features/Pagination';
import List from './features/List';
import Loading from './loading';
@@ -15,7 +17,7 @@ import Loading from './loading';
const AssistantPage = memo(() => {
const { q, page, category, sort, order, source } = useQuery() as AssistantQueryParams;
const useAssistantList = useDiscoverStore((s) => s.useAssistantList);
- const { data, isLoading } = useAssistantList({
+ const { data, isLoading, error, mutate } = useAssistantList({
category,
includeAgentGroup: true,
order,
@@ -26,20 +28,30 @@ const AssistantPage = memo(() => {
source,
});
- if (isLoading || !data) return <Loading />;
-
- const { items, currentPage, pageSize, totalCount } = data;
+ const items = data?.items ?? [];
return (
- <Flexbox gap={32} width={'100%'}>
- <List data={items} />
- <Pagination
- currentPage={currentPage}
- pageSize={pageSize}
- tab={DiscoverTab.Assistants}
- total={totalCount}
- />
- </Flexbox>
+ <AsyncBoundary
+ data={data}
+ empty={<AssistantEmpty />}
+ error={error}
+ isEmpty={items.length === 0}
+ isLoading={isLoading || !data}
+ loading={<Loading />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={32} width={'100%'}>
+ <List data={items} />
+ <Pagination
+ currentPage={data.currentPage}
+ pageSize={data.pageSize}
+ tab={DiscoverTab.Assistants}
+ total={data.totalCount}
+ />
+ </Flexbox>
+ )}
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/community/(list)/mcp/index.tsx b/src/routes/(main)/community/(list)/mcp/index.tsx
index 1f787677d7c..f446b580ec3 100644
--- a/src/routes/(main)/community/(list)/mcp/index.tsx
+++ b/src/routes/(main)/community/(list)/mcp/index.tsx
@@ -3,11 +3,13 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
import { type McpQueryParams } from '@/types/discover';
import { DiscoverTab, McpSorts } from '@/types/discover';
+import McpEmpty from '../../features/McpEmpty';
import Pagination from '../features/Pagination';
import List from './features/List';
import Loading from './loading';
@@ -15,7 +17,7 @@ import Loading from './loading';
const McpPage = memo(() => {
const { q, page, category, sort, order } = useQuery() as McpQueryParams;
const useMcpList = useDiscoverStore((s) => s.useFetchMcpList);
- const { data, isLoading } = useMcpList({
+ const { data, isLoading, error, mutate } = useMcpList({
category,
order,
page,
@@ -24,20 +26,30 @@ const McpPage = memo(() => {
sort: sort ?? McpSorts.Recommended,
});
- if (isLoading || !data) return <Loading />;
-
- const { items, currentPage, pageSize, totalCount } = data;
+ const items = data?.items ?? [];
return (
- <Flexbox gap={32} width={'100%'}>
- <List data={items} />
- <Pagination
- currentPage={currentPage}
- pageSize={pageSize}
- tab={DiscoverTab.Mcp}
- total={totalCount}
- />
- </Flexbox>
+ <AsyncBoundary
+ data={data}
+ empty={<McpEmpty />}
+ error={error}
+ isEmpty={items.length === 0}
+ isLoading={isLoading || !data}
+ loading={<Loading />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={32} width={'100%'}>
+ <List data={items} />
+ <Pagination
+ currentPage={data.currentPage}
+ pageSize={data.pageSize}
+ tab={DiscoverTab.Mcp}
+ total={data.totalCount}
+ />
+ </Flexbox>
+ )}
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/community/(list)/model/index.tsx b/src/routes/(main)/community/(list)/model/index.tsx
index 07d1d841934..5cb5741d636 100644
--- a/src/routes/(main)/community/(list)/model/index.tsx
+++ b/src/routes/(main)/community/(list)/model/index.tsx
@@ -3,11 +3,13 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
import { type ModelQueryParams } from '@/types/discover';
import { DiscoverTab } from '@/types/discover';
+import ModelEmpty from '../../features/ModelEmpty';
import Pagination from '../features/Pagination';
import List from './features/List';
import Loading from './loading';
@@ -15,7 +17,7 @@ import Loading from './loading';
const ModelPage = memo<{ mobile?: boolean }>(() => {
const { q, page, category, sort, order } = useQuery() as ModelQueryParams;
const useModelList = useDiscoverStore((s) => s.useModelList);
- const { data, isLoading } = useModelList({
+ const { data, isLoading, error, mutate } = useModelList({
category,
order,
page,
@@ -24,20 +26,30 @@ const ModelPage = memo<{ mobile?: boolean }>(() => {
sort,
});
- if (isLoading || !data) return <Loading />;
-
- const { items, currentPage, pageSize, totalCount } = data;
+ const items = data?.items ?? [];
return (
- <Flexbox gap={32} width={'100%'}>
- <List data={items} />
- <Pagination
- currentPage={currentPage}
- pageSize={pageSize}
- tab={DiscoverTab.Models}
- total={totalCount}
- />
- </Flexbox>
+ <AsyncBoundary
+ data={data}
+ empty={<ModelEmpty />}
+ error={error}
+ isEmpty={items.length === 0}
+ isLoading={isLoading || !data}
+ loading={<Loading />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={32} width={'100%'}>
+ <List data={items} />
+ <Pagination
+ currentPage={data.currentPage}
+ pageSize={data.pageSize}
+ tab={DiscoverTab.Models}
+ total={data.totalCount}
+ />
+ </Flexbox>
+ )}
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/community/(list)/provider/index.tsx b/src/routes/(main)/community/(list)/provider/index.tsx
index d05bc139028..3bb2cc4078e 100644
--- a/src/routes/(main)/community/(list)/provider/index.tsx
+++ b/src/routes/(main)/community/(list)/provider/index.tsx
@@ -3,11 +3,13 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
import { type ProviderQueryParams } from '@/types/discover';
import { DiscoverTab } from '@/types/discover';
+import ProviderEmpty from '../../features/ProviderEmpty';
import Pagination from '../features/Pagination';
import List from './features/List';
import Loading from './loading';
@@ -15,7 +17,7 @@ import Loading from './loading';
const ProviderPage = memo(() => {
const { q, page, sort, order } = useQuery() as ProviderQueryParams;
const useProviderList = useDiscoverStore((s) => s.useProviderList);
- const { data, isLoading } = useProviderList({
+ const { data, isLoading, error, mutate } = useProviderList({
order,
page,
pageSize: 21,
@@ -23,20 +25,30 @@ const ProviderPage = memo(() => {
sort,
});
- if (isLoading || !data) return <Loading />;
-
- const { items, currentPage, pageSize, totalCount } = data;
+ const items = data?.items ?? [];
return (
- <Flexbox gap={32} width={'100%'}>
- <List data={items} />
- <Pagination
- currentPage={currentPage}
- pageSize={pageSize}
- tab={DiscoverTab.Providers}
- total={totalCount}
- />
- </Flexbox>
+ <AsyncBoundary
+ data={data}
+ empty={<ProviderEmpty />}
+ error={error}
+ isEmpty={items.length === 0}
+ isLoading={isLoading || !data}
+ loading={<Loading />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={32} width={'100%'}>
+ <List data={items} />
+ <Pagination
+ currentPage={data.currentPage}
+ pageSize={data.pageSize}
+ tab={DiscoverTab.Providers}
+ total={data.totalCount}
+ />
+ </Flexbox>
+ )}
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/community/(list)/skill/index.tsx b/src/routes/(main)/community/(list)/skill/index.tsx
index 984f847973e..e0367c36ec8 100644
--- a/src/routes/(main)/community/(list)/skill/index.tsx
+++ b/src/routes/(main)/community/(list)/skill/index.tsx
@@ -3,11 +3,13 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useQuery } from '@/hooks/useQuery';
import { useDiscoverStore } from '@/store/discover';
import { type SkillQueryParams } from '@/types/discover';
import { DiscoverTab, SkillSorts } from '@/types/discover';
+import SkillEmpty from '../../features/SkillEmpty';
import Pagination from '../features/Pagination';
import List from './features/List';
import Loading from './loading';
@@ -15,7 +17,7 @@ import Loading from './loading';
const SkillPage = memo(() => {
const { q, page, category, sort, order } = useQuery() as SkillQueryParams;
const useSkillList = useDiscoverStore((s) => s.useFetchSkillList);
- const { data, isLoading } = useSkillList({
+ const { data, isLoading, error, mutate } = useSkillList({
category,
order,
page,
@@ -24,20 +26,30 @@ const SkillPage = memo(() => {
sort: sort ?? SkillSorts.InstallCount,
});
- if (isLoading || !data) return <Loading />;
-
- const { items, currentPage, pageSize, totalCount } = data;
+ const items = data?.items ?? [];
return (
- <Flexbox gap={32} width={'100%'}>
- <List data={items} />
- <Pagination
- currentPage={currentPage}
- pageSize={pageSize}
- tab={DiscoverTab.Skills}
- total={totalCount}
- />
- </Flexbox>
+ <AsyncBoundary
+ data={data}
+ empty={<SkillEmpty />}
+ error={error}
+ isEmpty={items.length === 0}
+ isLoading={isLoading || !data}
+ loading={<Loading />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={32} width={'100%'}>
+ <List data={items} />
+ <Pagination
+ currentPage={data.currentPage}
+ pageSize={data.pageSize}
+ tab={DiscoverTab.Skills}
+ total={data.totalCount}
+ />
+ </Flexbox>
+ )}
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
index 91cfa280c0a..4483708b661 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]/index.tsx
@@ -9,6 +9,7 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { agentEvalService } from '@/services/agentEval';
@@ -69,7 +70,6 @@ const styles = createStaticStyles(({ css }) => ({
heroBand: css`
padding: 20px;
border-radius: ${cssVar.borderRadiusLG};
-
background: ${cssVar.colorFillQuaternary};
`,
heroValue: css`
@@ -109,7 +109,7 @@ const DatasetDetail = memo(() => {
const refreshTestCases = useEvalStore((s) => s.refreshTestCases);
const refreshDatasetDetail = useEvalStore((s) => s.refreshDatasetDetail);
- const { data: dataset } = useFetchDatasetDetail(datasetId);
+ const { data: dataset, error, isLoading, mutate } = useFetchDatasetDetail(datasetId);
useFetchDatasetRuns(datasetId);
const sortedRuns = useMemo(
@@ -199,177 +199,187 @@ const DatasetDetail = memo(() => {
});
}, [benchmarkId, datasetId, message, navigate, t]);
- if (!dataset) return null;
-
+ // Skeleton → error → (resolved-null) blank, replacing a bare `return null`
+ // that flashed blank on the happy path and stayed permanently blank on a
+ // failed fetch (ux Read §1.1). A page-level failure gets a reason + Reload.
return (
- <>
- <Flexbox horizontal style={{ flex: 1, minHeight: 0 }}>
- <Flexbox
- flex={1}
- gap={24}
- style={{ minWidth: 0, overflow: 'auto', paddingBlock: 24, paddingInline: 32 }}
- >
- {/* Back link */}
- <WorkspaceLink className={styles.backLink} to={`/eval/bench/${benchmarkId}`}>
- <ArrowLeft size={16} />
- {t('dataset.detail.backToBenchmark')}
- </WorkspaceLink>
-
- {/* Header */}
- <Flexbox horizontal align="start" justify="space-between">
- <Flexbox horizontal align="start" gap={12}>
- <div className={styles.header}>
- <Database size={20} style={{ color: cssVar.colorPrimary }} />
- </div>
- <Flexbox gap={4}>
- <Text as="h4" style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>
- {dataset.name}
- </Text>
- {dataset.description && <Text type="secondary">{dataset.description}</Text>}
- </Flexbox>
- </Flexbox>
-
- <Flexbox horizontal gap={8}>
- <Button
- icon={Pencil}
- size="small"
- variant="outlined"
- onClick={() => createDatasetEditModal({ dataset, onSuccess: handleRefresh })}
- >
- {t('common.edit')}
- </Button>
- <Button danger icon={Trash2} size="small" variant="outlined" onClick={handleDelete}>
- {t('common.delete')}
- </Button>
- </Flexbox>
- </Flexbox>
-
- {/* Summary hero — headline case count + difficulty mix */}
+ <AsyncBoundary
+ data={dataset}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!dataset}
+ isLoading={isLoading}
+ onRetry={() => mutate()}
+ >
+ {dataset && (
+ <Flexbox horizontal style={{ flex: 1, minHeight: 0 }}>
<Flexbox
- horizontal
- align="center"
- className={styles.heroBand}
- gap={16}
- justify="space-between"
+ flex={1}
+ gap={24}
+ style={{ minWidth: 0, overflow: 'auto', paddingBlock: 24, paddingInline: 32 }}
>
- <Flexbox gap={6}>
- <span className={styles.heroValue}>{total}</span>
- <Text color={cssVar.colorTextTertiary} fontSize={12}>
- {t('dataset.detail.testCases')}
- </Text>
- </Flexbox>
- {difficulty.tagged > 0 && (
- <Flexbox gap={8} style={{ maxWidth: 280, minWidth: 0, width: '100%' }}>
- <SegmentBar segments={difficulty.segments} />
- <Flexbox horizontal gap={12} justify="flex-end" style={{ flexWrap: 'wrap' }}>
- {(['easy', 'medium', 'hard'] as const).map((d) => (
- <Flexbox horizontal align="center" gap={6} key={d}>
- <span
- className={styles.summaryDot}
- style={{
- background:
- d === 'easy'
- ? cssVar.colorSuccess
- : d === 'medium'
- ? cssVar.colorWarning
- : cssVar.colorError,
- }}
- />
- <Text color={cssVar.colorTextTertiary} fontSize={12}>
- {t(`difficulty.${d}`)} {difficulty.counts[d]}
- </Text>
- </Flexbox>
- ))}
+ {/* Back link */}
+ <WorkspaceLink className={styles.backLink} to={`/eval/bench/${benchmarkId}`}>
+ <ArrowLeft size={16} />
+ {t('dataset.detail.backToBenchmark')}
+ </WorkspaceLink>
+
+ {/* Header */}
+ <Flexbox horizontal align="start" justify="space-between">
+ <Flexbox horizontal align="start" gap={12}>
+ <div className={styles.header}>
+ <Database size={20} style={{ color: cssVar.colorPrimary }} />
+ </div>
+ <Flexbox gap={4}>
+ <Text as="h4" style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>
+ {dataset.name}
+ </Text>
+ {dataset.description && <Text type="secondary">{dataset.description}</Text>}
</Flexbox>
</Flexbox>
- )}
- </Flexbox>
- {/* Test Cases */}
- <Flexbox gap={12}>
- <Flexbox horizontal align="center" justify="space-between">
- <Text weight={600}>{t('dataset.detail.testCases')}</Text>
- <Text type="secondary">{t('dataset.detail.caseCount', { count: total })}</Text>
+ <Flexbox horizontal gap={8}>
+ <Button
+ icon={Pencil}
+ size="small"
+ variant="outlined"
+ onClick={() => createDatasetEditModal({ dataset, onSuccess: handleRefresh })}
+ >
+ {t('common.edit')}
+ </Button>
+ <Button danger icon={Trash2} size="small" variant="outlined" onClick={handleDelete}>
+ {t('common.delete')}
+ </Button>
+ </Flexbox>
</Flexbox>
- <div className={styles.tableWrapper}>
- <TestCaseTable
- datasetEvalMode={dataset?.evalMode}
- diffFilter={diffFilter}
- pagination={pagination}
- search={search}
- selectedId={previewCase?.id}
- testCases={filteredCases}
- total={total}
- onDelete={handleDeleteCase}
- onPageChange={(page, pageSize) => setPagination({ current: page, pageSize })}
- onPreview={setPreviewCase}
- onAddCase={() =>
- createTestCaseCreateModal({ datasetId: datasetId!, onSuccess: handleRefresh })
- }
- onDiffFilterChange={(f) => {
- setDiffFilter(f);
- setPagination((prev) => ({ ...prev, current: 1 }));
- }}
- onEdit={(testCase) =>
- createTestCaseEditModal({ onSuccess: handleRefresh, testCase })
- }
- onImport={() =>
- createDatasetImportModal({ datasetId: datasetId!, onSuccess: handleRefresh })
- }
- onSearchChange={(v) => {
- setSearch(v);
- setPagination((prev) => ({ ...prev, current: 1 }));
- }}
- />
- </div>
- </Flexbox>
+ {/* Summary hero — headline case count + difficulty mix */}
+ <Flexbox
+ horizontal
+ align="center"
+ className={styles.heroBand}
+ gap={16}
+ justify="space-between"
+ >
+ <Flexbox gap={6}>
+ <span className={styles.heroValue}>{total}</span>
+ <Text color={cssVar.colorTextTertiary} fontSize={12}>
+ {t('dataset.detail.testCases')}
+ </Text>
+ </Flexbox>
+ {difficulty.tagged > 0 && (
+ <Flexbox gap={8} style={{ maxWidth: 280, minWidth: 0, width: '100%' }}>
+ <SegmentBar segments={difficulty.segments} />
+ <Flexbox horizontal gap={12} justify="flex-end" style={{ flexWrap: 'wrap' }}>
+ {(['easy', 'medium', 'hard'] as const).map((d) => (
+ <Flexbox horizontal align="center" gap={6} key={d}>
+ <span
+ className={styles.summaryDot}
+ style={{
+ background:
+ d === 'easy'
+ ? cssVar.colorSuccess
+ : d === 'medium'
+ ? cssVar.colorWarning
+ : cssVar.colorError,
+ }}
+ />
+ <Text color={cssVar.colorTextTertiary} fontSize={12}>
+ {t(`difficulty.${d}`)} {difficulty.counts[d]}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Flexbox>
- {/* Related Runs */}
- <Flexbox gap={12}>
- <Flexbox horizontal align="center" justify="space-between">
- <Text weight={600}>
- {t('dataset.detail.relatedRuns', { count: sortedRuns.length })}
- </Text>
- <Button
- icon={Plus}
- size="small"
- onClick={() =>
- createRunCreateModal({
- benchmarkId: benchmarkId!,
- datasetId: datasetId!,
- datasetName: dataset.name,
- })
- }
- >
- {t('dataset.detail.addRun')}
- </Button>
+ {/* Test Cases */}
+ <Flexbox gap={12}>
+ <Flexbox horizontal align="center" justify="space-between">
+ <Text weight={600}>{t('dataset.detail.testCases')}</Text>
+ <Text type="secondary">{t('dataset.detail.caseCount', { count: total })}</Text>
+ </Flexbox>
+
+ <div className={styles.tableWrapper}>
+ <TestCaseTable
+ datasetEvalMode={dataset?.evalMode}
+ diffFilter={diffFilter}
+ pagination={pagination}
+ search={search}
+ selectedId={previewCase?.id}
+ testCases={filteredCases}
+ total={total}
+ onDelete={handleDeleteCase}
+ onPageChange={(page, pageSize) => setPagination({ current: page, pageSize })}
+ onPreview={setPreviewCase}
+ onAddCase={() =>
+ createTestCaseCreateModal({ datasetId: datasetId!, onSuccess: handleRefresh })
+ }
+ onDiffFilterChange={(f) => {
+ setDiffFilter(f);
+ setPagination((prev) => ({ ...prev, current: 1 }));
+ }}
+ onEdit={(testCase) =>
+ createTestCaseEditModal({ onSuccess: handleRefresh, testCase })
+ }
+ onImport={() =>
+ createDatasetImportModal({ datasetId: datasetId!, onSuccess: handleRefresh })
+ }
+ onSearchChange={(v) => {
+ setSearch(v);
+ setPagination((prev) => ({ ...prev, current: 1 }));
+ }}
+ />
+ </div>
</Flexbox>
- {sortedRuns.length > 0 ? (
- <Flexbox gap={12}>
- {sortedRuns.map((run) => (
- <RunCard benchmarkId={benchmarkId!} key={run.id} run={run} />
- ))}
+
+ {/* Related Runs */}
+ <Flexbox gap={12}>
+ <Flexbox horizontal align="center" justify="space-between">
+ <Text weight={600}>
+ {t('dataset.detail.relatedRuns', { count: sortedRuns.length })}
+ </Text>
+ <Button
+ icon={Plus}
+ size="small"
+ onClick={() =>
+ createRunCreateModal({
+ benchmarkId: benchmarkId!,
+ datasetId: datasetId!,
+ datasetName: dataset.name,
+ })
+ }
+ >
+ {t('dataset.detail.addRun')}
+ </Button>
</Flexbox>
- ) : (
- <EmptyState
- onCreate={() =>
- createRunCreateModal({
- benchmarkId: benchmarkId!,
- datasetId: datasetId!,
- datasetName: dataset.name,
- })
- }
- />
- )}
+ {sortedRuns.length > 0 ? (
+ <Flexbox gap={12}>
+ {sortedRuns.map((run) => (
+ <RunCard benchmarkId={benchmarkId!} key={run.id} run={run} />
+ ))}
+ </Flexbox>
+ ) : (
+ <EmptyState
+ onCreate={() =>
+ createRunCreateModal({
+ benchmarkId: benchmarkId!,
+ datasetId: datasetId!,
+ datasetName: dataset.name,
+ })
+ }
+ />
+ )}
+ </Flexbox>
</Flexbox>
- </Flexbox>
- {previewCase && (
- <TestCasePreviewPanel testCase={previewCase} onClose={() => setPreviewCase(null)} />
- )}
- </Flexbox>
- </>
+ {previewCase && (
+ <TestCasePreviewPanel testCase={previewCase} onClose={() => setPreviewCase(null)} />
+ )}
+ </Flexbox>
+ )}
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
index 627b9e8f7e8..c6745e6630f 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]/index.tsx
@@ -8,6 +8,7 @@ import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { runSelectors, useEvalStore } from '@/store/eval';
@@ -32,7 +33,12 @@ const CaseDetail = memo(() => {
// Ensure data is loaded even when navigating directly to this URL
const pollingConfig = { refreshInterval: isActive ? POLLING_INTERVAL : 0 };
useFetchRunDetail(runId!, pollingConfig);
- useFetchRunResults(runId!, pollingConfig);
+ const {
+ data: resultsData,
+ error: resultsError,
+ isLoading: resultsLoading,
+ mutate: mutateResults,
+ } = useFetchRunResults(runId!, pollingConfig);
const runDetail = useEvalStore(runSelectors.getRunDetailById(runId!));
const runResults = useEvalStore(runSelectors.getRunResultsById(runId!));
@@ -76,58 +82,74 @@ const CaseDetail = memo(() => {
[activeThreadId, threads],
);
- if (!caseResult) return null;
-
- const topicId = caseResult.topicId;
- const agentId = caseResult.topic?.agentId;
+ const topicId = caseResult?.topicId;
+ const agentId = caseResult?.topic?.agentId;
const basePath = `/eval/bench/${benchmarkId}/runs/${runId}/cases`;
// Resolve display data: thread-level if selected, otherwise topic-level
- const displayEvalResult = currentThread || caseResult.evalResult;
- const displayPassed = currentThread ? currentThread.passed : caseResult.passed;
- const displayScore = currentThread ? currentThread.score : caseResult.score;
+ const displayEvalResult = currentThread || caseResult?.evalResult;
+ const displayPassed = currentThread ? currentThread.passed : caseResult?.passed;
+ const displayScore = currentThread ? currentThread.score : caseResult?.score;
+ // Skeleton → error → (resolved-null) blank, replacing a bare `return null`
+ // that flashed blank while results loaded and stayed permanently blank on a
+ // failed fetch (ux Read §1.1). A page-level failure gets a reason + Reload.
return (
- <Flexbox height="100%" style={{ overflow: 'hidden' }}>
- <CaseHeader
- caseNumber={(caseResult.testCase?.sortOrder ?? 0) + 1}
- evalResult={displayEvalResult}
- passed={displayPassed}
- runName={runDetail?.name || runId!.slice(0, 8)}
- score={displayScore}
- onBack={() => navigate(`/eval/bench/${benchmarkId}/runs/${runId}`)}
- onNext={nextCaseId ? () => navigate(`${basePath}/${nextCaseId}`) : undefined}
- onPrev={prevCaseId ? () => navigate(`${basePath}/${prevCaseId}`) : undefined}
- />
- {hasMultipleThreads && (
- <Flexbox
- paddingInline={16}
- style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`, flex: 'none' }}
- >
- <Tabs
- activeKey={activeThreadId!}
- items={threads.map((thread, index) => ({
- key: thread.threadId,
- label: t('caseDetail.threads.attempt', { number: index + 1 }),
- }))}
- onChange={(key) => setActiveThreadId(key)}
+ <AsyncBoundary
+ data={resultsData}
+ error={resultsError}
+ errorVariant={'page'}
+ isEmpty={!caseResult}
+ isLoading={resultsLoading}
+ onRetry={() => mutateResults()}
+ >
+ {caseResult && (
+ <Flexbox height="100%" style={{ overflow: 'hidden' }}>
+ <CaseHeader
+ caseNumber={(caseResult.testCase?.sortOrder ?? 0) + 1}
+ evalResult={displayEvalResult}
+ passed={displayPassed}
+ runName={runDetail?.name || runId!.slice(0, 8)}
+ score={displayScore}
+ onBack={() => navigate(`/eval/bench/${benchmarkId}/runs/${runId}`)}
+ onNext={nextCaseId ? () => navigate(`${basePath}/${nextCaseId}`) : undefined}
+ onPrev={prevCaseId ? () => navigate(`${basePath}/${prevCaseId}`) : undefined}
/>
+ {hasMultipleThreads && (
+ <Flexbox
+ paddingInline={16}
+ style={{ borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`, flex: 'none' }}
+ >
+ <Tabs
+ activeKey={activeThreadId!}
+ items={threads.map((thread, index) => ({
+ key: thread.threadId,
+ label: t('caseDetail.threads.attempt', { number: index + 1 }),
+ }))}
+ onChange={(key) => setActiveThreadId(key)}
+ />
+ </Flexbox>
+ )}
+ <Flexbox horizontal flex={1} style={{ overflow: 'hidden' }}>
+ {topicId && agentId ? (
+ <ChatArea
+ agentId={agentId}
+ threadId={activeThreadId ?? undefined}
+ topicId={topicId}
+ />
+ ) : (
+ <Flexbox flex={1} />
+ )}
+ <InfoSidebar
+ evalResult={displayEvalResult}
+ passed={displayPassed}
+ score={displayScore}
+ testCase={caseResult.testCase}
+ />
+ </Flexbox>
</Flexbox>
)}
- <Flexbox horizontal flex={1} style={{ overflow: 'hidden' }}>
- {topicId && agentId ? (
- <ChatArea agentId={agentId} threadId={activeThreadId ?? undefined} topicId={topicId} />
- ) : (
- <Flexbox flex={1} />
- )}
- <InfoSidebar
- evalResult={displayEvalResult}
- passed={displayPassed}
- score={displayScore}
- testCase={caseResult.testCase}
- />
- </Flexbox>
- </Flexbox>
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
index c77f188b195..a43646171c2 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/index.tsx
@@ -9,6 +9,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { runSelectors, useEvalStore } from '@/store/eval';
import { createBatchResumeModal } from './features/BatchResumeModal';
@@ -26,10 +27,8 @@ const POLLING_INTERVAL = 3000;
const styles = createStaticStyles(({ css }) => ({
panel: css`
overflow: hidden;
-
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
-
background: ${cssVar.colorBgContainer};
`,
panelBody: css`
@@ -79,18 +78,16 @@ const RunDetail = memo(() => {
const pollingConfig = { refreshInterval: isActive ? POLLING_INTERVAL : 0 };
- useFetchRunDetail(runId!, pollingConfig);
+ const { error, isLoading, mutate } = useFetchRunDetail(runId!, pollingConfig);
useFetchRunResults(runId!, pollingConfig);
- if (!runDetail) return null;
-
const hasResults = !!runResults?.results?.length;
const isFinished =
- runDetail.status === 'completed' ||
- runDetail.status === 'failed' ||
- runDetail.status === 'aborted';
+ runDetail?.status === 'completed' ||
+ runDetail?.status === 'failed' ||
+ runDetail?.status === 'aborted';
- const metrics = runDetail.metrics;
+ const metrics = runDetail?.metrics;
const completedCases = metrics?.completedCases ?? 0;
const totalCases = metrics?.totalCases ?? 0;
const progress = totalCases > 0 ? Math.round((completedCases / totalCases) * 100) : 0;
@@ -98,131 +95,145 @@ const RunDetail = memo(() => {
const errorCount = (metrics?.errorCases ?? 0) + (metrics?.timeoutCases ?? 0);
const canRetry = isFinished && errorCount > 0;
- const k = runDetail.config?.k ?? 1;
+ const k = runDetail?.config?.k ?? 1;
const canBatchResume = (runResults?.results ?? []).some(
(result: any) => !!getResumeTarget(result, k),
);
+ // Skeleton → error → (resolved-null) blank, instead of a bare `return null`
+ // that flashed blank on the happy path and stayed permanently blank on a
+ // failed fetch (ux Read §1.1). A page-level failure gets a reason + Reload.
return (
- <Flexbox gap={24} padding={24} style={{ margin: '0 auto', maxWidth: 1440, width: '100%' }}>
- <RunHeader
- benchmarkId={benchmarkId!}
- hideStart={runDetail.status === 'idle'}
- run={runDetail}
- />
-
- {/* Report panel (when finished) or state panel (when not finished) */}
- {isFinished ? (
- <section className={styles.panel}>
- <header className={styles.panelHeader}>
- <span className={styles.panelLabel}>{t('run.detail.report')}</span>
- </header>
- <div className={styles.panelBody}>
- <StatsCards metrics={runDetail.metrics ?? undefined} />
- {hasResults && (
- <BenchmarkCharts
- benchmarkId={benchmarkId!}
- results={runResults.results}
- runId={runId!}
- />
- )}
- </div>
- </section>
- ) : (
- <section className={styles.panel}>
- <header className={styles.panelHeader}>
- <span className={styles.panelLabel}>{t('run.detail.report')}</span>
- </header>
- <div className={styles.stateBody}>
- {runDetail.status === 'running' ? (
- <RunningState />
- ) : runDetail.status === 'pending' ? (
- <PendingState hint={t('run.pending.hint')} />
- ) : runDetail.status === 'external' ? (
- <PendingState hint={t('run.external.hint')} />
- ) : (
- <IdleState run={runDetail} />
- )}
- </div>
- </section>
- )}
+ <AsyncBoundary
+ data={runDetail}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!runDetail}
+ isLoading={isLoading}
+ onRetry={() => mutate()}
+ >
+ {runDetail && (
+ <Flexbox gap={24} padding={24} style={{ margin: '0 auto', maxWidth: 1440, width: '100%' }}>
+ <RunHeader
+ benchmarkId={benchmarkId!}
+ hideStart={runDetail.status === 'idle'}
+ run={runDetail}
+ />
- {/* Case Results (always shown when results exist) */}
- {hasResults && (
- <section className={styles.panel}>
- <header className={styles.panelHeader}>
- <span className={styles.panelLabel}>{t('run.detail.caseResults')}</span>
- {(showProgress || canRetry || canBatchResume) && (
- <Flexbox horizontal align="center" gap={8}>
- {showProgress && (
- <>
- <Text fontSize={12} style={{ whiteSpace: 'nowrap' }} type={'secondary'}>
- {completedCases}/{totalCases} {t('run.detail.progressCases')}
- </Text>
- <Progress
- percent={progress}
- showInfo={false}
- size="small"
- status={isActive ? 'active' : undefined}
- style={{ margin: 0, width: 120 }}
- />
- <Text fontSize={12} type={'secondary'}>
- {progress}%
- </Text>
- </>
+ {/* Report panel (when finished) or state panel (when not finished) */}
+ {isFinished ? (
+ <section className={styles.panel}>
+ <header className={styles.panelHeader}>
+ <span className={styles.panelLabel}>{t('run.detail.report')}</span>
+ </header>
+ <div className={styles.panelBody}>
+ <StatsCards metrics={runDetail.metrics ?? undefined} />
+ {hasResults && (
+ <BenchmarkCharts
+ benchmarkId={benchmarkId!}
+ results={runResults.results}
+ runId={runId!}
+ />
)}
- {canBatchResume && (
- <Button
- icon={<Play size={14} />}
- size="small"
- onClick={() =>
- createBatchResumeModal({
- onConfirm: (targets) => batchResumeRunCases(runId!, targets),
- runId: runId!,
- })
- }
- >
- {t('run.actions.batchResume')}
- </Button>
+ </div>
+ </section>
+ ) : (
+ <section className={styles.panel}>
+ <header className={styles.panelHeader}>
+ <span className={styles.panelLabel}>{t('run.detail.report')}</span>
+ </header>
+ <div className={styles.stateBody}>
+ {runDetail.status === 'running' ? (
+ <RunningState />
+ ) : runDetail.status === 'pending' ? (
+ <PendingState hint={t('run.pending.hint')} />
+ ) : runDetail.status === 'external' ? (
+ <PendingState hint={t('run.external.hint')} />
+ ) : (
+ <IdleState run={runDetail} />
)}
- {canRetry && (
- <Button
- icon={<RotateCcw size={14} />}
- loading={retrying}
- size="small"
- onClick={() => {
- confirmModal({
- content: t('run.actions.retryErrors.confirm'),
- onOk: async () => {
- setRetrying(true);
- try {
- await retryRunErrors(runId!);
- } finally {
- setRetrying(false);
- }
- },
- title: t('run.actions.retryErrors'),
- });
- }}
- >
- {t('run.actions.retryErrors')}
- </Button>
+ </div>
+ </section>
+ )}
+
+ {/* Case Results (always shown when results exist) */}
+ {hasResults && (
+ <section className={styles.panel}>
+ <header className={styles.panelHeader}>
+ <span className={styles.panelLabel}>{t('run.detail.caseResults')}</span>
+ {(showProgress || canRetry || canBatchResume) && (
+ <Flexbox horizontal align="center" gap={8}>
+ {showProgress && (
+ <>
+ <Text fontSize={12} style={{ whiteSpace: 'nowrap' }} type={'secondary'}>
+ {completedCases}/{totalCases} {t('run.detail.progressCases')}
+ </Text>
+ <Progress
+ percent={progress}
+ showInfo={false}
+ size="small"
+ status={isActive ? 'active' : undefined}
+ style={{ margin: 0, width: 120 }}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {progress}%
+ </Text>
+ </>
+ )}
+ {canBatchResume && (
+ <Button
+ icon={<Play size={14} />}
+ size="small"
+ onClick={() =>
+ createBatchResumeModal({
+ onConfirm: (targets) => batchResumeRunCases(runId!, targets),
+ runId: runId!,
+ })
+ }
+ >
+ {t('run.actions.batchResume')}
+ </Button>
+ )}
+ {canRetry && (
+ <Button
+ icon={<RotateCcw size={14} />}
+ loading={retrying}
+ size="small"
+ onClick={() => {
+ confirmModal({
+ content: t('run.actions.retryErrors.confirm'),
+ onOk: async () => {
+ setRetrying(true);
+ try {
+ await retryRunErrors(runId!);
+ } finally {
+ setRetrying(false);
+ }
+ },
+ title: t('run.actions.retryErrors'),
+ });
+ }}
+ >
+ {t('run.actions.retryErrors')}
+ </Button>
+ )}
+ </Flexbox>
)}
- </Flexbox>
- )}
- </header>
- <CaseResultsTable
- benchmarkId={benchmarkId!}
- k={k}
- results={runResults.results}
- runId={runId!}
- runStatus={runDetail.status}
- onResumeCase={(testCaseId, threadId) => resumeRunCase(runId!, testCaseId, threadId)}
- onRetryCase={(testCaseId) => retryRunCase(runId!, testCaseId)}
- />
- </section>
+ </header>
+ <CaseResultsTable
+ benchmarkId={benchmarkId!}
+ k={k}
+ results={runResults.results}
+ runId={runId!}
+ runStatus={runDetail.status}
+ onResumeCase={(testCaseId, threadId) => resumeRunCase(runId!, testCaseId, threadId)}
+ onRetryCase={(testCaseId) => retryRunCase(runId!, testCaseId)}
+ />
+ </section>
+ )}
+ </Flexbox>
)}
- </Flexbox>
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/eval/index.tsx b/src/routes/(main)/eval/index.tsx
index dd092be3d87..6300b54956d 100644
--- a/src/routes/(main)/eval/index.tsx
+++ b/src/routes/(main)/eval/index.tsx
@@ -6,6 +6,7 @@ import { FlaskConical, Plus } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useEvalStore } from '@/store/eval';
import BenchmarkCard from './features/BenchmarkCard';
@@ -19,14 +20,13 @@ const styles = createStaticStyles(({ css }) => ({
`,
grid: css`
display: grid;
- gap: 20px;
grid-template-columns: repeat(auto-fill, minmax(480px, 1fr));
+ gap: 20px;
`,
skeletonCard: css`
padding: 20px;
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
-
background: ${cssVar.colorBgContainer};
`,
title: css`
@@ -58,14 +58,33 @@ const EvalOverview = memo(() => {
const { t } = useTranslation('eval');
const benchmarkList = useEvalStore((s) => s.benchmarkList);
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
- const { isLoading } = useFetchBenchmarks();
+ const { data, isLoading, error, mutate } = useFetchBenchmarks();
+
+ // Purpose-built onboarding empty — only reached when the fetch succeeded with
+ // zero benchmarks. A *failed* fetch is gated ahead of this by AsyncBoundary so
+ // we never invite the user to re-create benchmarks they already own (ux Read
+ // §1.1 error-as-empty trap).
+ const emptyState = (
+ <Flexbox align={'center'} flex={1} justify={'center'}>
+ <Empty description={t('benchmark.empty')} icon={FlaskConical}>
+ <Button
+ icon={Plus}
+ style={{ marginTop: 16 }}
+ type={'primary'}
+ onClick={() => createCreateBenchmarkModal()}
+ >
+ {t('overview.createBenchmark')}
+ </Button>
+ </Empty>
+ </Flexbox>
+ );
return (
<Flexbox className={styles.container} gap={32} height={'100%'} width={'100%'}>
{/* Header */}
<Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>
<Flexbox gap={4} style={{ minWidth: 0 }}>
- <Text as={'h1'} className={styles.title} ellipsis fontSize={30} weight={600}>
+ <Text ellipsis as={'h1'} className={styles.title} fontSize={30} weight={600}>
{t('overview.title')}
</Text>
<Text type={'secondary'}>{t('overview.subtitle')}</Text>
@@ -77,23 +96,17 @@ const EvalOverview = memo(() => {
)}
</Flexbox>
- {/* Body: loading / empty / grid */}
- {isLoading ? (
- <SkeletonGrid />
- ) : benchmarkList.length === 0 ? (
- <Flexbox align={'center'} flex={1} justify={'center'}>
- <Empty description={t('benchmark.empty')} icon={FlaskConical}>
- <Button
- icon={Plus}
- style={{ marginTop: 16 }}
- type={'primary'}
- onClick={() => createCreateBenchmarkModal()}
- >
- {t('overview.createBenchmark')}
- </Button>
- </Empty>
- </Flexbox>
- ) : (
+ {/* Body: error / loading / empty / grid (error gated before empty) */}
+ <AsyncBoundary
+ data={data}
+ empty={emptyState}
+ error={error}
+ errorVariant={'block'}
+ isEmpty={benchmarkList.length === 0}
+ isLoading={isLoading}
+ loading={<SkeletonGrid />}
+ onRetry={() => mutate()}
+ >
<div className={styles.grid}>
{benchmarkList.map((benchmark: any) => (
<BenchmarkCard
@@ -111,7 +124,7 @@ const EvalOverview = memo(() => {
/>
))}
</div>
- )}
+ </AsyncBoundary>
</Flexbox>
);
});
diff --git a/src/routes/(main)/memory/(home)/index.tsx b/src/routes/(main)/memory/(home)/index.tsx
index 8f63772b5f3..a8b884d8052 100644
--- a/src/routes/(main)/memory/(home)/index.tsx
+++ b/src/routes/(main)/memory/(home)/index.tsx
@@ -2,6 +2,7 @@ import { Flexbox } from '@lobehub/ui';
// import { PencilLineIcon } from 'lucide-react';
import { type FC } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Loading from '@/components/Loading/BrandTextLoading';
import NavHeader from '@/features/NavHeader';
import WideScreenContainer from '@/features/WideScreenContainer';
@@ -22,12 +23,22 @@ const Home: FC = () => {
const roles = useUserMemoryStore((s) => s.roles);
const persona = useUserMemoryStore((s) => s.persona);
- const { isLoading: isTagsLoading } = useFetchTags();
- const { isLoading: isPersonaLoading } = useFetchPersona();
+ const { isLoading: isTagsLoading, error: tagsError, mutate: mutateTags } = useFetchTags();
+ const {
+ isLoading: isPersonaLoading,
+ error: personaError,
+ mutate: mutatePersona,
+ } = useFetchPersona();
// const { EditorModalElement, openEditor } = usePersonaEditor();
if (isTagsLoading || isPersonaLoading) return <Loading debugId={'Home'} />;
+ // Persona / tags feed the store, so a failed fetch left the render falling
+ // through to the "analyze to get started" onboarding — telling the user they
+ // have no memories when the load merely errored. Branch error before empty.
+ const hasData = !!persona || roles?.length > 0;
+ const error = tagsError ?? personaError;
+
return (
<Flexbox flex={1} height={'100%'}>
<NavHeader
@@ -48,19 +59,29 @@ const Home: FC = () => {
width={'100%'}
>
<WideScreenContainer gap={32} paddingBlock={48}>
- {roles?.length > 0 && <RoleTagCloud tags={roles} />}
- {persona ? (
- <>
- <PersonaHeader />
- <Persona />
- </>
- ) : (
- !roles?.length && (
+ <AsyncBoundary
+ data={persona ?? (roles?.length ? roles : undefined)}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!hasData}
+ empty={
<MemoryEmpty>
<MemoryAnalysis />
</MemoryEmpty>
- )
- )}
+ }
+ onRetry={() => {
+ mutateTags();
+ mutatePersona();
+ }}
+ >
+ {roles?.length > 0 && <RoleTagCloud tags={roles} />}
+ {persona && (
+ <>
+ <PersonaHeader />
+ <Persona />
+ </>
+ )}
+ </AsyncBoundary>
</WideScreenContainer>
</Flexbox>
{/* {EditorModalElement} */}
diff --git a/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx b/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx
index 498c16e7888..2db6194f42d 100644
--- a/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx
+++ b/src/routes/(main)/memory/activities/features/ActivityRightPanel.tsx
@@ -5,10 +5,12 @@ import dayjs from 'dayjs';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useQueryState } from '@/hooks/useQueryParam';
import CateTag from '@/routes/(main)/memory/features/CateTag';
import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';
+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';
import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';
import HashTags from '@/routes/(main)/memory/features/HashTags';
import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';
@@ -31,7 +33,12 @@ const ActivityRightPanel = memo(() => {
const [activityId] = useQueryState('activityId', { clearOnDefault: true });
const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
- const { data: activity, isLoading } = useFetchMemoryDetail(activityId, LayersEnum.Activity);
+ const {
+ data: activity,
+ isLoading,
+ error,
+ mutate,
+ } = useFetchMemoryDetail(activityId, LayersEnum.Activity);
const schedule = useMemo(() => {
if (!activity) return null;
@@ -45,7 +52,6 @@ const ActivityRightPanel = memo(() => {
if (!activityId) return null;
let content;
- if (isLoading) content = <DetailLoading />;
if (activity) {
const capturedAt =
activity.startsAt ||
@@ -109,7 +115,18 @@ const ActivityRightPanel = memo(() => {
) : undefined,
}}
>
- {content}
+ <AsyncBoundary
+ data={activity}
+ empty={<DetailNotFound />}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!activity}
+ isLoading={isLoading}
+ loading={<DetailLoading />}
+ onRetry={() => mutate()}
+ >
+ {content}
+ </AsyncBoundary>
</DetailPanel>
);
});
diff --git a/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx b/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx
index 577b5176272..5a0abd24ec9 100644
--- a/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx
+++ b/src/routes/(main)/memory/contexts/features/ContextRightPanel.tsx
@@ -6,10 +6,12 @@ import { cssVar } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useQueryState } from '@/hooks/useQueryParam';
import CateTag from '@/routes/(main)/memory/features/CateTag';
import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';
+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';
import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';
import HashTags from '@/routes/(main)/memory/features/HashTags';
import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';
@@ -25,61 +27,61 @@ const ContextRightPanel = memo(() => {
const [contextId] = useQueryState('contextId', { clearOnDefault: true });
const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
const { t } = useTranslation('memory');
- const { data: context, isLoading } = useFetchMemoryDetail(contextId, LayersEnum.Context);
+ const {
+ data: context,
+ isLoading,
+ error,
+ mutate,
+ } = useFetchMemoryDetail(contextId, LayersEnum.Context);
if (!contextId) return null;
- let content;
- if (isLoading) content = <DetailLoading />;
- if (context)
- content = (
- <>
- <CateTag cate={context.type} />
- <Text
- as={'h1'}
- fontSize={20}
- weight={'bold'}
- style={{
- lineHeight: 1.4,
- marginBottom: 0,
- }}
- >
- {context.title}
- <Tooltip title={context.currentStatus}>
- <Center flex={'none'} height={20} style={{ display: 'inline-flex' }} width={20}>
- <Badge
- status="processing"
- style={{ marginLeft: 8 }}
- styles={{
- indicator: { alignSelf: 'center', marginBottom: 4 },
- }}
- />
- </Center>
- </Tooltip>
- </Text>
- <Flexbox horizontal align="center" gap={16}>
- <ProgressIcon
- showInfo
- format={(percent) => `${t('filter.sort.scoreImpact')}: ${percent}%`}
- percent={(context.scoreImpact ?? 0) * 100}
- />
- <ProgressIcon
- showInfo
- format={(percent) => `${t('filter.sort.scoreUrgency')}: ${percent}%`}
- percent={(context.scoreUrgency ?? 0) * 100}
- strokeColor={
- (context.scoreUrgency ?? 0) >= 0.7 ? cssVar.colorError : cssVar.colorWarning
- }
- />
- </Flexbox>
- <Flexbox horizontal align="center" gap={16} justify="space-between">
- <SourceLink source={context.source} />
- <Time capturedAt={context.capturedAt || context.updatedAt || context.createdAt} />
- </Flexbox>
- <HighlightedContent>{context.description}</HighlightedContent>
- <HashTags hashTags={context.tags} />
- </>
- );
+ const content = context && (
+ <>
+ <CateTag cate={context.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ weight={'bold'}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ >
+ {context.title}
+ <Tooltip title={context.currentStatus}>
+ <Center flex={'none'} height={20} style={{ display: 'inline-flex' }} width={20}>
+ <Badge
+ status="processing"
+ style={{ marginLeft: 8 }}
+ styles={{
+ indicator: { alignSelf: 'center', marginBottom: 4 },
+ }}
+ />
+ </Center>
+ </Tooltip>
+ </Text>
+ <Flexbox horizontal align="center" gap={16}>
+ <ProgressIcon
+ showInfo
+ format={(percent) => `${t('filter.sort.scoreImpact')}: ${percent}%`}
+ percent={(context.scoreImpact ?? 0) * 100}
+ />
+ <ProgressIcon
+ showInfo
+ format={(percent) => `${t('filter.sort.scoreUrgency')}: ${percent}%`}
+ percent={(context.scoreUrgency ?? 0) * 100}
+ strokeColor={(context.scoreUrgency ?? 0) >= 0.7 ? cssVar.colorError : cssVar.colorWarning}
+ />
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={16} justify="space-between">
+ <SourceLink source={context.source} />
+ <Time capturedAt={context.capturedAt || context.updatedAt || context.createdAt} />
+ </Flexbox>
+ <HighlightedContent>{context.description}</HighlightedContent>
+ <HashTags hashTags={context.tags} />
+ </>
+ );
return (
<DetailPanel
@@ -89,7 +91,18 @@ const ContextRightPanel = memo(() => {
) : undefined,
}}
>
- {content}
+ <AsyncBoundary
+ data={context}
+ empty={<DetailNotFound />}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!context}
+ isLoading={isLoading}
+ loading={<DetailLoading />}
+ onRetry={() => mutate()}
+ >
+ {content}
+ </AsyncBoundary>
</DetailPanel>
);
});
diff --git a/src/routes/(main)/memory/experiences/features/ExperienceRightPanel.tsx b/src/routes/(main)/memory/experiences/features/ExperienceRightPanel.tsx
index c41e14f82d1..68451cb3426 100644
--- a/src/routes/(main)/memory/experiences/features/ExperienceRightPanel.tsx
+++ b/src/routes/(main)/memory/experiences/features/ExperienceRightPanel.tsx
@@ -6,10 +6,12 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useQueryState } from '@/hooks/useQueryParam';
import CateTag from '@/routes/(main)/memory/features/CateTag';
import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';
+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';
import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';
import HashTags from '@/routes/(main)/memory/features/HashTags';
import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';
@@ -44,134 +46,131 @@ const ExperienceRightPanel = memo(() => {
const [experienceId] = useQueryState('experienceId', { clearOnDefault: true });
const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
- const { data: experience, isLoading } = useFetchMemoryDetail(experienceId, LayersEnum.Experience);
+ const {
+ data: experience,
+ isLoading,
+ error,
+ mutate,
+ } = useFetchMemoryDetail(experienceId, LayersEnum.Experience);
if (!experienceId) return null;
- let content;
- if (isLoading) content = <DetailLoading />;
- if (experience) {
- content = (
- <>
- <CateTag cate={experience.type} />
- <Text
- as={'h1'}
- fontSize={20}
- weight={'bold'}
- style={{
- lineHeight: 1.4,
- marginBottom: 0,
- }}
- >
- {experience.title}
- </Text>
- <Flexbox horizontal align="center" gap={16} justify="space-between">
- <ProgressIcon
- showInfo
- format={(percent) => `${t('filter.sort.scoreConfidence')}: ${percent}%`}
- percent={(experience.scoreConfidence ?? 0) * 100}
- />
- </Flexbox>
- <Flexbox horizontal align="center" gap={16} justify="space-between">
- <SourceLink source={experience.source} />
- <Time
- capturedAt={experience.capturedAt || experience.updatedAt || experience.createdAt}
- />
- </Flexbox>
+ const content = experience && (
+ <>
+ <CateTag cate={experience.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ weight={'bold'}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ >
+ {experience.title}
+ </Text>
+ <Flexbox horizontal align="center" gap={16} justify="space-between">
+ <ProgressIcon
+ showInfo
+ format={(percent) => `${t('filter.sort.scoreConfidence')}: ${percent}%`}
+ percent={(experience.scoreConfidence ?? 0) * 100}
+ />
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={16} justify="space-between">
+ <SourceLink source={experience.source} />
+ <Time capturedAt={experience.capturedAt || experience.updatedAt || experience.createdAt} />
+ </Flexbox>
- {experience.keyLearning && (
- <HighlightedContent>{experience.keyLearning}</HighlightedContent>
- )}
+ {experience.keyLearning && <HighlightedContent>{experience.keyLearning}</HighlightedContent>}
- <Steps
- className={styles.stepsContainer}
- current={null as any}
- direction="vertical"
- size="small"
- items={[
- {
- description: <HighlightedContent>{experience.situation}</HighlightedContent>,
- icon: (
- <Avatar
- shadow
- avatar={'S'}
- shape={'square'}
- size={24}
- style={{
- border: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
- />
- ),
- title: (
- <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
- {t('experience.steps.situation')}
- </Text>
- ),
- },
- {
- description: <HighlightedContent>{experience.reasoning}</HighlightedContent>,
- icon: (
- <Avatar
- shadow
- avatar={'T'}
- shape={'square'}
- size={24}
- style={{
- border: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
- />
- ),
- title: (
- <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
- {t('experience.steps.task')}
- </Text>
- ),
- },
- {
- description: <HighlightedContent>{experience.action}</HighlightedContent>,
- icon: (
- <Avatar
- shadow
- avatar={'A'}
- shape={'square'}
- size={24}
- style={{
- border: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
- />
- ),
- title: (
- <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
- {t('experience.steps.action')}
- </Text>
- ),
- },
- {
- description: <HighlightedContent>{experience.possibleOutcome}</HighlightedContent>,
- icon: (
- <Avatar
- shadow
- avatar={'R'}
- shape={'square'}
- size={24}
- style={{
- border: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
- />
- ),
- title: (
- <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
- {t('experience.steps.result')}
- </Text>
- ),
- },
- ]}
- />
+ <Steps
+ className={styles.stepsContainer}
+ current={null as any}
+ direction="vertical"
+ size="small"
+ items={[
+ {
+ description: <HighlightedContent>{experience.situation}</HighlightedContent>,
+ icon: (
+ <Avatar
+ shadow
+ avatar={'S'}
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.situation')}
+ </Text>
+ ),
+ },
+ {
+ description: <HighlightedContent>{experience.reasoning}</HighlightedContent>,
+ icon: (
+ <Avatar
+ shadow
+ avatar={'T'}
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.task')}
+ </Text>
+ ),
+ },
+ {
+ description: <HighlightedContent>{experience.action}</HighlightedContent>,
+ icon: (
+ <Avatar
+ shadow
+ avatar={'A'}
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.action')}
+ </Text>
+ ),
+ },
+ {
+ description: <HighlightedContent>{experience.possibleOutcome}</HighlightedContent>,
+ icon: (
+ <Avatar
+ shadow
+ avatar={'R'}
+ shape={'square'}
+ size={24}
+ style={{
+ border: `1px solid ${cssVar.colorBorderSecondary}`,
+ }}
+ />
+ ),
+ title: (
+ <Text as={'h4'} fontSize={12} type={'secondary'} weight={500}>
+ {t('experience.steps.result')}
+ </Text>
+ ),
+ },
+ ]}
+ />
- <HashTags hashTags={experience.tags} />
- </>
- );
- }
+ <HashTags hashTags={experience.tags} />
+ </>
+ );
return (
<DetailPanel
@@ -181,7 +180,18 @@ const ExperienceRightPanel = memo(() => {
) : undefined,
}}
>
- {content}
+ <AsyncBoundary
+ data={experience}
+ empty={<DetailNotFound />}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!experience}
+ isLoading={isLoading}
+ loading={<DetailLoading />}
+ onRetry={() => mutate()}
+ >
+ {content}
+ </AsyncBoundary>
</DetailPanel>
);
});
diff --git a/src/routes/(main)/memory/features/DetailNotFound.tsx b/src/routes/(main)/memory/features/DetailNotFound.tsx
new file mode 100644
index 00000000000..5ec625ab236
--- /dev/null
+++ b/src/routes/(main)/memory/features/DetailNotFound.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { Center, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { FileQuestionIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * Resolved not-found for a memory detail panel: the fetch succeeded but the item
+ * is gone (deleted elsewhere). Distinct from a fetch *error* — which
+ * `AsyncBoundary` renders via `AsyncError` with a Reload — so a deleted item
+ * never masquerades as a transient failure (and vice-versa).
+ */
+const DetailNotFound = memo(() => {
+ const { t } = useTranslation('memory');
+
+ return (
+ <Center flex={1} gap={12} padding={48} width={'100%'}>
+ <Icon icon={FileQuestionIcon} size={32} style={{ color: cssVar.colorTextTertiary }} />
+ <Flexbox align={'center'} gap={4}>
+ <Text fontSize={16} weight={600}>
+ {t('detail.notFound.title')}
+ </Text>
+ <Text
+ align={'center'}
+ color={cssVar.colorTextTertiary}
+ fontSize={13}
+ style={{ maxWidth: 320 }}
+ >
+ {t('detail.notFound.desc')}
+ </Text>
+ </Flexbox>
+ </Center>
+ );
+});
+
+export default DetailNotFound;
diff --git a/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx b/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx
index d37bc1ef37d..76f8a78d029 100644
--- a/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx
+++ b/src/routes/(main)/memory/identities/features/IdentityRightPanel.tsx
@@ -3,10 +3,12 @@
import { Text } from '@lobehub/ui';
import { memo } from 'react';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useQueryState } from '@/hooks/useQueryParam';
import CateTag from '@/routes/(main)/memory/features/CateTag';
import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';
+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';
import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';
import HashTags from '@/routes/(main)/memory/features/HashTags';
import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';
@@ -20,33 +22,34 @@ const IdentityRightPanel = memo(() => {
const [identityId] = useQueryState('identityId', { clearOnDefault: true });
const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
- const { data: identity, isLoading } = useFetchMemoryDetail(identityId, LayersEnum.Identity);
+ const {
+ data: identity,
+ isLoading,
+ error,
+ mutate,
+ } = useFetchMemoryDetail(identityId, LayersEnum.Identity);
if (!identityId) return null;
- let content;
- if (isLoading) content = <DetailLoading />;
- if (identity) {
- content = (
- <>
- <CateTag cate={identity.type} />
- <Text
- as={'h1'}
- fontSize={20}
- weight={'bold'}
- style={{
- lineHeight: 1.4,
- marginBottom: 0,
- }}
- >
- {identity.title}
- </Text>
- <Time capturedAt={identity.capturedAt || identity.updatedAt || identity.createdAt} />
- {identity.description && <HighlightedContent>{identity.description}</HighlightedContent>}
- <HashTags hashTags={identity.tags} />
- </>
- );
- }
+ const content = identity && (
+ <>
+ <CateTag cate={identity.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ weight={'bold'}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ >
+ {identity.title}
+ </Text>
+ <Time capturedAt={identity.capturedAt || identity.updatedAt || identity.createdAt} />
+ {identity.description && <HighlightedContent>{identity.description}</HighlightedContent>}
+ <HashTags hashTags={identity.tags} />
+ </>
+ );
return (
<DetailPanel
@@ -56,7 +59,18 @@ const IdentityRightPanel = memo(() => {
) : undefined,
}}
>
- {content}
+ <AsyncBoundary
+ data={identity}
+ empty={<DetailNotFound />}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!identity}
+ isLoading={isLoading}
+ loading={<DetailLoading />}
+ onRetry={() => mutate()}
+ >
+ {content}
+ </AsyncBoundary>
</DetailPanel>
);
});
diff --git a/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx b/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx
index 451fd1fc82e..d65f701d81a 100644
--- a/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx
+++ b/src/routes/(main)/memory/preferences/features/PreferenceRightPanel.tsx
@@ -6,10 +6,12 @@ import { BotIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
import { useQueryState } from '@/hooks/useQueryParam';
import CateTag from '@/routes/(main)/memory/features/CateTag';
import DetailLoading from '@/routes/(main)/memory/features/DetailLoading';
+import DetailNotFound from '@/routes/(main)/memory/features/DetailNotFound';
import DetailPanel from '@/routes/(main)/memory/features/DetailPanel';
import HashTags from '@/routes/(main)/memory/features/HashTags';
import HighlightedContent from '@/routes/(main)/memory/features/HighlightedContent';
@@ -34,59 +36,58 @@ const PreferenceRightPanel = memo(() => {
const [preferenceId] = useQueryState('preferenceId', { clearOnDefault: true });
const useFetchMemoryDetail = useUserMemoryStore((s) => s.useFetchMemoryDetail);
- const { data: preference, isLoading } = useFetchMemoryDetail(preferenceId, LayersEnum.Preference);
+ const {
+ data: preference,
+ isLoading,
+ error,
+ mutate,
+ } = useFetchMemoryDetail(preferenceId, LayersEnum.Preference);
if (!preferenceId) return null;
- let content;
- if (isLoading) content = <DetailLoading />;
- if (preference) {
- content = (
- <>
- <CateTag cate={preference.type} />
- <Text
- as={'h1'}
- fontSize={20}
- weight={'bold'}
- style={{
- lineHeight: 1.4,
- marginBottom: 0,
- }}
- >
- {preference.title || preference.type || t('preference.defaultType')}
- </Text>
- <Flexbox horizontal align="center" gap={16} justify="space-between">
- <ProgressIcon
- showInfo
- format={(percent) => `${t('filter.sort.scorePriority')}: ${percent}%`}
- percent={(preference.scorePriority ?? 0) * 100}
- />
- </Flexbox>
- <Flexbox horizontal align="center" gap={16} justify="space-between">
- <SourceLink source={preference.source} />
- <Time
- capturedAt={preference.capturedAt || preference.updatedAt || preference.createdAt}
- />
- </Flexbox>
+ const content = preference && (
+ <>
+ <CateTag cate={preference.type} />
+ <Text
+ as={'h1'}
+ fontSize={20}
+ weight={'bold'}
+ style={{
+ lineHeight: 1.4,
+ marginBottom: 0,
+ }}
+ >
+ {preference.title || preference.type || t('preference.defaultType')}
+ </Text>
+ <Flexbox horizontal align="center" gap={16} justify="space-between">
+ <ProgressIcon
+ showInfo
+ format={(percent) => `${t('filter.sort.scorePriority')}: ${percent}%`}
+ percent={(preference.scorePriority ?? 0) * 100}
+ />
+ </Flexbox>
+ <Flexbox horizontal align="center" gap={16} justify="space-between">
+ <SourceLink source={preference.source} />
+ <Time capturedAt={preference.capturedAt || preference.updatedAt || preference.createdAt} />
+ </Flexbox>
- {preference.conclusionDirectives && (
- <HighlightedContent>{preference.conclusionDirectives}</HighlightedContent>
- )}
+ {preference.conclusionDirectives && (
+ <HighlightedContent>{preference.conclusionDirectives}</HighlightedContent>
+ )}
- {preference.suggestions && (
- <Block gap={8} padding={16} variant={'filled'}>
- <Flexbox horizontal align={'center'} className={styles.suggestionsTitle} gap={6}>
- <Icon icon={BotIcon} size={16} />
- <span>{t('preference.suggestions')}</span>
- </Flexbox>
- <HighlightedContent>{preference.suggestions}</HighlightedContent>
- </Block>
- )}
+ {preference.suggestions && (
+ <Block gap={8} padding={16} variant={'filled'}>
+ <Flexbox horizontal align={'center'} className={styles.suggestionsTitle} gap={6}>
+ <Icon icon={BotIcon} size={16} />
+ <span>{t('preference.suggestions')}</span>
+ </Flexbox>
+ <HighlightedContent>{preference.suggestions}</HighlightedContent>
+ </Block>
+ )}
- <HashTags hashTags={preference.tags} />
- </>
- );
- }
+ <HashTags hashTags={preference.tags} />
+ </>
+ );
return (
<DetailPanel
@@ -96,7 +97,18 @@ const PreferenceRightPanel = memo(() => {
) : undefined,
}}
>
- {content}
+ <AsyncBoundary
+ data={preference}
+ empty={<DetailNotFound />}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!preference}
+ isLoading={isLoading}
+ loading={<DetailLoading />}
+ onRetry={() => mutate()}
+ >
+ {content}
+ </AsyncBoundary>
</DetailPanel>
);
});
diff --git a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx
index 11bc1954d97..03bb37b33cb 100644
--- a/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx
+++ b/src/routes/(main)/resource/(home)/_layout/Body/LibraryList/index.tsx
@@ -4,6 +4,7 @@ import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useCreateNewModal } from '@/features/LibraryModal';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
@@ -32,7 +33,10 @@ const LibraryList = memo(() => {
// `fallbackData: []`, `isLoading` collapses to false immediately. Without
// this, the sidebar flashes the empty state for the network round-trip
// before the real list arrives.
- const { data, isLoading, isValidating } = useFetchKnowledgeBaseList(visibility);
+ // `fallbackData: []` keeps `data` an array even on failure, so a failed KB-list
+ // fetch used to render the "create your first library" empty (Read §1.1
+ // failure-as-empty). Read `error` / `mutate` and branch the failure before empty.
+ const { data, isLoading, isValidating, error, mutate } = useFetchKnowledgeBaseList(visibility);
const navigate = useWorkspaceAwareNavigate();
@@ -48,31 +52,41 @@ const LibraryList = memo(() => {
});
};
- if (isLoading || (isValidating && (data?.length ?? 0) === 0))
- return <SkeletonList paddingInline={4} rows={3} />;
-
- if (data?.length === 0)
- return (
- <EmptyNavItem
- disabled={!canCreate}
- title={t(listVisibility === 'private' ? 'library.privateEmpty' : 'library.workspaceEmpty')}
- onClick={handleCreate}
- />
- );
+ const hasData = (data?.length ?? 0) > 0;
+ const showSkeleton = isLoading || (isValidating && !hasData);
return (
- <Flexbox gap={1} paddingInline={4}>
- {data?.map((item) => (
- <Item
- description={item.description}
- id={item.id}
- key={item.id}
- name={item.name}
- userId={item.userId}
- visibility={item.visibility}
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'inline'}
+ isEmpty={data?.length === 0}
+ isLoading={showSkeleton}
+ loading={<SkeletonList paddingInline={4} rows={3} />}
+ empty={
+ <EmptyNavItem
+ disabled={!canCreate}
+ title={t(
+ listVisibility === 'private' ? 'library.privateEmpty' : 'library.workspaceEmpty',
+ )}
+ onClick={handleCreate}
/>
- ))}
- </Flexbox>
+ }
+ onRetry={() => mutate()}
+ >
+ <Flexbox gap={1} paddingInline={4}>
+ {data?.map((item) => (
+ <Item
+ description={item.description}
+ id={item.id}
+ key={item.id}
+ name={item.name}
+ userId={item.userId}
+ visibility={item.visibility}
+ />
+ ))}
+ </Flexbox>
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/resource/library/index.tsx b/src/routes/(main)/resource/library/index.tsx
index 263a304b49f..17fb30789fa 100644
--- a/src/routes/(main)/resource/library/index.tsx
+++ b/src/routes/(main)/resource/library/index.tsx
@@ -4,6 +4,7 @@ import { memo, useLayoutEffect } from 'react';
import { useLocation, useParams } from 'react-router';
import NotFound from '@/components/404';
+import AsyncError from '@/components/AsyncError';
import NProgress from '@/components/NProgress';
import ResourceManager from '@/features/ResourceManager';
import Container from '@/routes/(main)/resource/library/features/Container';
@@ -18,7 +19,7 @@ const MainContent = memo(() => {
const setLibraryId = useResourceManagerStore((s) => s.setLibraryId);
// Load knowledge base data
- const { data, isLoading } = useKnowledgeBaseItem(knowledgeBaseId || '');
+ const { data, isLoading, error, mutate } = useKnowledgeBaseItem(knowledgeBaseId || '');
// Sync libraryId from URL params using useLayoutEffect
// useLayoutEffect runs synchronously before browser paint, ensuring state is set
@@ -34,6 +35,11 @@ const MainContent = memo(() => {
// Sync file view mode from URL
useInitFileCheck();
+ // A network / 500 on the KB fetch is NOT "this library doesn't exist" (Read §1.1):
+ // branch a transient error to a reload state that keeps the URL, and reserve the
+ // terminal 404 for a genuinely resolved-null (deleted / never-existed) record.
+ if (error && !data) return <AsyncError error={error} variant={'page'} onRetry={() => mutate()} />;
+
if (!isLoading && !data) return <NotFound />;
return <ResourceManager />;
diff --git a/src/routes/(main)/settings/creds/features/CredsList.tsx b/src/routes/(main)/settings/creds/features/CredsList.tsx
index 2113a4457bd..351165211fb 100644
--- a/src/routes/(main)/settings/creds/features/CredsList.tsx
+++ b/src/routes/(main)/settings/creds/features/CredsList.tsx
@@ -9,6 +9,7 @@ import { LogIn } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
@@ -44,7 +45,7 @@ const CredsList: FC = () => {
const { allowed: canManageCredentials } = usePermission('manage_provider_key');
const credsApi = useCredsApi();
- const { data, isLoading, refetch } = credsApi.query.list.useQuery(undefined, {
+ const { data, isLoading, error, refetch } = credsApi.query.list.useQuery(undefined, {
enabled: isAuthenticated,
});
@@ -92,13 +93,20 @@ const CredsList: FC = () => {
return (
<div className={styles.container}>
- {isLoading ? (
- <Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>
- <Spin />
- </Flexbox>
- ) : credentials.length === 0 ? (
- <Empty className={styles.empty} description={t('creds.empty')} />
- ) : (
+ <AsyncBoundary
+ data={data}
+ empty={<Empty className={styles.empty} description={t('creds.empty')} />}
+ error={error}
+ errorVariant={'block'}
+ isEmpty={credentials.length === 0}
+ isLoading={isLoading}
+ loading={
+ <Flexbox align={'center'} justify={'center'} style={{ padding: 48 }}>
+ <Spin />
+ </Flexbox>
+ }
+ onRetry={() => refetch()}
+ >
<Flexbox gap={0}>
{credentials.map((cred) => (
<CredItem
@@ -113,7 +121,7 @@ const CredsList: FC = () => {
/>
))}
</Flexbox>
- )}
+ </AsyncBoundary>
</div>
);
};
diff --git a/src/routes/(main)/settings/provider/features/ModelList/index.tsx b/src/routes/(main)/settings/provider/features/ModelList/index.tsx
index a998746af60..c0a659fb72c 100644
--- a/src/routes/(main)/settings/provider/features/ModelList/index.tsx
+++ b/src/routes/(main)/settings/provider/features/ModelList/index.tsx
@@ -16,6 +16,7 @@ import {
import { memo, Suspense, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { useIsMobile } from '@/hooks/useIsMobile';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
@@ -45,7 +46,7 @@ const Content = memo<ContentProps>(({ id }) => {
const allModels = useAiInfraStore(aiModelSelectors.filteredAiProviderModelList, isEqual);
- const { isLoading } = useFetchAiProviderModels(id);
+ const { isLoading, error, mutate } = useFetchAiProviderModels(id);
// Count models by type (for all models, not just enabled)
const modelCounts = useMemo(() => {
@@ -129,6 +130,11 @@ const Content = memo<ContentProps>(({ id }) => {
if (isLoading) return <SkeletonList />;
+ // Error before empty: a failed model-list fetch must not render as
+ // "no models yet" (EmptyModels) — surface the reason + Retry (ux Read §1.1).
+ if (error && isEmpty)
+ return <AsyncError error={error} variant={'block'} onRetry={() => mutate()} />;
+
if (isSearching) return <SearchResult />;
return isEmpty ? (
diff --git a/src/routes/(main)/settings/stats/features/overview/TotalAssistants.tsx b/src/routes/(main)/settings/stats/features/overview/TotalAssistants.tsx
index 826dcfe0a4b..01c00d11433 100644
--- a/src/routes/(main)/settings/stats/features/overview/TotalAssistants.tsx
+++ b/src/routes/(main)/settings/stats/features/overview/TotalAssistants.tsx
@@ -1,6 +1,7 @@
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Statistic from '@/components/Statistic';
import StatisticCard from '@/components/StatisticCard';
import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
@@ -14,7 +15,7 @@ import TotalCard from './ShareButton/TotalCard';
const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {
const { t } = useTranslation('auth');
- const { data, isLoading } = useClientDataSWR(statsKeys.agents(), async () => ({
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.agents(), async () => ({
count: await agentService.countAgents(),
prevCount: await agentService.countAgents({ endDate: lastMonth().format('YYYY-MM-DD') }),
}));
@@ -28,26 +29,28 @@ const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }
);
return (
- <StatisticCard
- loading={isLoading || !data}
- statistic={{
- description: (
- <Statistic
- title={t('date.prevMonth')}
- value={formatIntergerNumber(data?.prevCount) || '--'}
+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>
+ <StatisticCard
+ loading={isLoading || !data}
+ statistic={{
+ description: (
+ <Statistic
+ title={t('date.prevMonth')}
+ value={formatIntergerNumber(data?.prevCount) || '--'}
+ />
+ ),
+ precision: 0,
+ value: data?.count || '--',
+ }}
+ title={
+ <TitleWithPercentage
+ count={data?.count}
+ prvCount={data?.prevCount}
+ title={t('stats.assistants')}
/>
- ),
- precision: 0,
- value: data?.count || '--',
- }}
- title={
- <TitleWithPercentage
- count={data?.count}
- prvCount={data?.prevCount}
- title={t('stats.assistants')}
- />
- }
- />
+ }
+ />
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/settings/stats/features/overview/TotalMessages.tsx b/src/routes/(main)/settings/stats/features/overview/TotalMessages.tsx
index 40197ac364d..b3b0fcfcbe8 100644
--- a/src/routes/(main)/settings/stats/features/overview/TotalMessages.tsx
+++ b/src/routes/(main)/settings/stats/features/overview/TotalMessages.tsx
@@ -1,6 +1,7 @@
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Statistic from '@/components/Statistic';
import StatisticCard from '@/components/StatisticCard';
import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
@@ -14,7 +15,7 @@ import TotalCard from './ShareButton/TotalCard';
const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {
const { t } = useTranslation('auth');
- const { data, isLoading } = useClientDataSWR(statsKeys.messages(), async () => ({
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.messages(), async () => ({
count: await messageService.countMessages(),
prevCount: await messageService.countMessages({ endDate: lastMonth().format('YYYY-MM-DD') }),
}));
@@ -28,26 +29,28 @@ const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }
);
return (
- <StatisticCard
- loading={isLoading || !data}
- statistic={{
- description: (
- <Statistic
- title={t('date.prevMonth')}
- value={formatIntergerNumber(data?.prevCount) || '--'}
+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>
+ <StatisticCard
+ loading={isLoading || !data}
+ statistic={{
+ description: (
+ <Statistic
+ title={t('date.prevMonth')}
+ value={formatIntergerNumber(data?.prevCount) || '--'}
+ />
+ ),
+ precision: 0,
+ value: data?.count || '--',
+ }}
+ title={
+ <TitleWithPercentage
+ count={data?.count}
+ prvCount={data?.prevCount}
+ title={t('stats.messages')}
/>
- ),
- precision: 0,
- value: data?.count || '--',
- }}
- title={
- <TitleWithPercentage
- count={data?.count}
- prvCount={data?.prevCount}
- title={t('stats.messages')}
- />
- }
- />
+ }
+ />
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx b/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx
index b65d47aa231..0077ae95e1b 100644
--- a/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx
+++ b/src/routes/(main)/settings/stats/features/overview/TotalTokens.tsx
@@ -2,6 +2,7 @@ import dayjs from 'dayjs';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Statistic from '@/components/Statistic';
import StatisticCard from '@/components/StatisticCard';
import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
@@ -23,8 +24,9 @@ import TotalCard from './ShareButton/TotalCard';
const TotalTokens = memo<{ inShare?: boolean }>(({ inShare }) => {
const { t } = useTranslation('auth');
- const { data, isLoading } = useClientDataSWR(statsKeys.heatmaps(HeatmapType.Tokens), () =>
- messageService.getTokenHeatmaps(),
+ const { data, isLoading, error, mutate } = useClientDataSWR(
+ statsKeys.heatmaps(HeatmapType.Tokens),
+ () => messageService.getTokenHeatmaps(),
);
const { count, prevCount } = useMemo(() => {
@@ -48,27 +50,31 @@ const TotalTokens = memo<{ inShare?: boolean }>(({ inShare }) => {
/>
);
+ // Metric variant: a failed fetch must never fall through to a confident `$0`
+ // — show a failed marker + Retry where the number would sit (ux Read §1.1).
return (
- <StatisticCard
- loading={isLoading || !data}
- statistic={{
- description: (
- <Statistic title={t('date.prevMonth')} value={formatShortenNumber(prevCount) || '--'} />
- ),
- precision: 0,
- style: {
- fontWeight: 'bold',
- },
- value: formatShortenNumber(count) || '--',
- }}
- title={
- <TitleWithPercentage
- count={count}
- prvCount={prevCount}
- title={t('stats.heatmapStats.totalTokens')}
- />
- }
- />
+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>
+ <StatisticCard
+ loading={isLoading || !data}
+ statistic={{
+ description: (
+ <Statistic title={t('date.prevMonth')} value={formatShortenNumber(prevCount) || '--'} />
+ ),
+ precision: 0,
+ style: {
+ fontWeight: 'bold',
+ },
+ value: formatShortenNumber(count) || '--',
+ }}
+ title={
+ <TitleWithPercentage
+ count={count}
+ prvCount={prevCount}
+ title={t('stats.heatmapStats.totalTokens')}
+ />
+ }
+ />
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/settings/stats/features/overview/TotalTopics.tsx b/src/routes/(main)/settings/stats/features/overview/TotalTopics.tsx
index d0967df2013..da96cf82b1e 100644
--- a/src/routes/(main)/settings/stats/features/overview/TotalTopics.tsx
+++ b/src/routes/(main)/settings/stats/features/overview/TotalTopics.tsx
@@ -1,6 +1,7 @@
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import Statistic from '@/components/Statistic';
import StatisticCard from '@/components/StatisticCard';
import TitleWithPercentage from '@/components/StatisticCard/TitleWithPercentage';
@@ -14,7 +15,7 @@ import TotalCard from './ShareButton/TotalCard';
const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }) => {
const { t } = useTranslation('auth');
- const { data, isLoading } = useClientDataSWR(statsKeys.topics(), async () => ({
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.topics(), async () => ({
count: await topicService.countTopics(),
prevCount: await topicService.countTopics({ endDate: lastMonth().format('YYYY-MM-DD') }),
}));
@@ -25,26 +26,28 @@ const TotalMessages = memo<{ inShare?: boolean; mobile?: boolean }>(({ inShare }
);
return (
- <StatisticCard
- loading={isLoading || !data}
- statistic={{
- description: (
- <Statistic
- title={t('date.prevMonth')}
- value={formatIntergerNumber(data?.prevCount) || '--'}
+ <AsyncBoundary data={data} error={error} errorVariant={'metric'} onRetry={() => mutate()}>
+ <StatisticCard
+ loading={isLoading || !data}
+ statistic={{
+ description: (
+ <Statistic
+ title={t('date.prevMonth')}
+ value={formatIntergerNumber(data?.prevCount) || '--'}
+ />
+ ),
+ precision: 0,
+ value: data?.count || '--',
+ }}
+ title={
+ <TitleWithPercentage
+ count={data?.count}
+ prvCount={data?.prevCount}
+ title={t('stats.topics')}
/>
- ),
- precision: 0,
- value: data?.count || '--',
- }}
- title={
- <TitleWithPercentage
- count={data?.count}
- prvCount={data?.prevCount}
- title={t('stats.topics')}
- />
- }
- />
+ }
+ />
+ </AsyncBoundary>
);
});
diff --git a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
index 38c612ec3fb..8e26eea47a6 100644
--- a/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/AssistantsRank.tsx
@@ -6,6 +6,7 @@ import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import ImperativeModal from '@/components/ImperativeModal';
import { DEFAULT_AVATAR } from '@/const/meta';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -24,7 +25,7 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t } = useTranslation(['auth', 'chat']);
const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
- const { data, isLoading } = useClientDataSWR(statsKeys.rankAgents(), async () =>
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.rankAgents(), async () =>
agentService.rankAgents(),
);
@@ -69,18 +70,20 @@ export const AssistantsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
)
}
>
- <BarList
- data={data?.slice(0, 5).map((item) => mapData(item)) || []}
- height={220}
- leftLabel={t('stats.assistantsRank.left')}
- loading={isLoading || !data}
- rightLabel={t('stats.assistantsRank.right')}
- noDataText={{
- desc: t('stats.empty.desc'),
- title: t('stats.empty.title'),
- }}
- onValueChange={(item) => navigate(item.link)}
- />
+ <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>
+ <BarList
+ data={data?.slice(0, 5).map((item) => mapData(item)) || []}
+ height={220}
+ leftLabel={t('stats.assistantsRank.left')}
+ loading={isLoading || !data}
+ rightLabel={t('stats.assistantsRank.right')}
+ noDataText={{
+ desc: t('stats.empty.desc'),
+ title: t('stats.empty.title'),
+ }}
+ onValueChange={(item) => navigate(item.link)}
+ />
+ </AsyncBoundary>
</StatsFormGroup>
{showExtra && (
<ImperativeModal
diff --git a/src/routes/(main)/settings/stats/features/rankings/ModelsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/ModelsRank.tsx
index d9c7d3088e1..f1bef175ece 100644
--- a/src/routes/(main)/settings/stats/features/rankings/ModelsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/ModelsRank.tsx
@@ -6,6 +6,7 @@ import { MaximizeIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import ImperativeModal from '@/components/ImperativeModal';
import { useClientDataSWR } from '@/libs/swr';
import { statsKeys } from '@/libs/swr/keys';
@@ -16,7 +17,7 @@ import StatsFormGroup from '../components/StatsFormGroup';
export const TopicsRank = memo(() => {
const [open, setOpen] = useState(false);
const { t } = useTranslation('auth');
- const { data, isLoading } = useClientDataSWR(statsKeys.rankModels(), async () =>
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.rankModels(), async () =>
messageService.rankModels(),
);
@@ -43,17 +44,19 @@ export const TopicsRank = memo(() => {
) : undefined
}
>
- <BarList
- data={data?.slice(0, 5).map((item) => mapData(item)) || []}
- height={220}
- leftLabel={t('stats.modelsRank.left')}
- loading={isLoading || !data}
- rightLabel={t('stats.modelsRank.right')}
- noDataText={{
- desc: t('stats.empty.desc'),
- title: t('stats.empty.title'),
- }}
- />
+ <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>
+ <BarList
+ data={data?.slice(0, 5).map((item) => mapData(item)) || []}
+ height={220}
+ leftLabel={t('stats.modelsRank.left')}
+ loading={isLoading || !data}
+ rightLabel={t('stats.modelsRank.right')}
+ noDataText={{
+ desc: t('stats.empty.desc'),
+ title: t('stats.empty.title'),
+ }}
+ />
+ </AsyncBoundary>
</StatsFormGroup>
{showExtra && (
<ImperativeModal
diff --git a/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx b/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
index 536e00ab562..f25e6c84982 100644
--- a/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
+++ b/src/routes/(main)/settings/stats/features/rankings/TopicsRank.tsx
@@ -7,6 +7,7 @@ import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import ImperativeModal from '@/components/ImperativeModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import Link from '@/libs/router/Link';
@@ -24,7 +25,7 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
const { t } = useTranslation('auth');
const navigate = useWorkspaceAwareNavigate();
const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
- const { data, isLoading } = useClientDataSWR(statsKeys.rankTopics(), async () =>
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.rankTopics(), async () =>
topicService.rankTopics(),
);
@@ -62,18 +63,20 @@ export const TopicsRank = memo<{ mobile?: boolean }>(({ mobile }) => {
)
}
>
- <BarList
- data={data?.slice(0, 5).map((item) => mapData(item)) || []}
- height={220}
- leftLabel={t('stats.topicsRank.left')}
- loading={isLoading || !data}
- rightLabel={t('stats.topicsRank.right')}
- noDataText={{
- desc: t('stats.empty.desc'),
- title: t('stats.empty.title'),
- }}
- onValueChange={(item) => navigate(item.link)}
- />
+ <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>
+ <BarList
+ data={data?.slice(0, 5).map((item) => mapData(item)) || []}
+ height={220}
+ leftLabel={t('stats.topicsRank.left')}
+ loading={isLoading || !data}
+ rightLabel={t('stats.topicsRank.right')}
+ noDataText={{
+ desc: t('stats.empty.desc'),
+ title: t('stats.empty.title'),
+ }}
+ onValueChange={(item) => navigate(item.link)}
+ />
+ </AsyncBoundary>
</StatsFormGroup>
{showExtra && (
<ImperativeModal
diff --git a/src/routes/(main)/settings/stats/index.tsx b/src/routes/(main)/settings/stats/index.tsx
index 1514cb1e04a..084cf7ab5bb 100644
--- a/src/routes/(main)/settings/stats/index.tsx
+++ b/src/routes/(main)/settings/stats/index.tsx
@@ -10,6 +10,7 @@ import { Brain, UserIcon } from 'lucide-react';
import { memo, type ReactNode, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncBoundary from '@/components/AsyncBoundary';
import { useClientDataSWR } from '@/libs/swr';
import { statsKeys } from '@/libs/swr/keys';
import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';
@@ -56,7 +57,7 @@ const StatsSetting = memo<StatsSettingProps>(
const [dateRange, setDateRange] = useState<dayjs.Dayjs>(dayjs(new Date()));
const [dateStrings, setDateStrings] = useState<string>();
- const { data, isLoading, mutate } = useClientDataSWR(statsKeys.usageStat(), async () =>
+ const { data, isLoading, error, mutate } = useClientDataSWR(statsKeys.usageStat(), async () =>
usageService.findAndGroupByDay(dateStrings),
);
@@ -149,19 +150,21 @@ const StatsSetting = memo<StatsSettingProps>(
title: { lineHeight: '35px' },
}}
>
- <UsageCards
- data={data}
- groupBy={groupBy}
- isLoading={isLoading}
- resolveUser={resolveUser}
- />
- <Divider />
- <UsageTrends
- data={data}
- groupBy={groupBy}
- isLoading={isLoading}
- resolveUser={resolveUser}
- />
+ <AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>
+ <UsageCards
+ data={data}
+ groupBy={groupBy}
+ isLoading={isLoading}
+ resolveUser={resolveUser}
+ />
+ <Divider />
+ <UsageTrends
+ data={data}
+ groupBy={groupBy}
+ isLoading={isLoading}
+ resolveUser={resolveUser}
+ />
+ </AsyncBoundary>
<div style={{ height: 24 }} />
<UsageTable dateStrings={dateStrings} />
</FormGroup>
diff --git a/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx b/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx
index cef5cbe96ee..761b5df629a 100644
--- a/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx
+++ b/src/routes/(main)/settings/system-tools/features/ToolDetectorSection.tsx
@@ -7,6 +7,7 @@ import { CheckCircle2, Loader2Icon, RefreshCw, XCircle } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import { FORM_STYLE } from '@/const/layoutTokens';
import { binaryService } from '@/services/electron/binary';
@@ -127,14 +128,19 @@ const ToolDetectorSection = memo(() => {
const { t } = useTranslation('setting');
const [toolStatuses, setToolStatuses] = useState<Record<string, BinaryStatus>>({});
const [detecting, setDetecting] = useState(true);
+ // A failed `detectAll` used to be swallowed (console.error), leaving every tool
+ // rendered as "not detected" — a failure masquerading as an all-missing
+ // environment. Track it so we can render a failure + Retry instead (ux Read §1.1).
+ const [detectError, setDetectError] = useState<unknown>();
const detectTools = useCallback(async (force = false) => {
try {
setDetecting(true);
const statuses = await binaryService.detectAll(force);
setToolStatuses(statuses);
+ setDetectError(undefined);
} catch (error) {
- console.error('Failed to detect tools:', error);
+ setDetectError(error);
} finally {
setDetecting(false);
}
@@ -175,6 +181,12 @@ const ToolDetectorSection = memo(() => {
}),
);
+ // Nothing detected AND the scan errored → a real failure, not an empty
+ // environment. Show the reason + Retry rather than a wall of "not detected".
+ if (detectError && Object.keys(toolStatuses).length === 0) {
+ return <AsyncError error={detectError} variant={'block'} onRetry={handleRedetect} />;
+ }
+
return (
<Form
collapsible={false}
diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.ts
index 3f43c6897c5..2bf68cd6af0 100644
--- a/src/store/task/slices/detail/action.ts
+++ b/src/store/task/slices/detail/action.ts
@@ -125,7 +125,13 @@ export class TaskDetailSliceActionImpl {
const detail = result.data;
if (!detail) {
- throw new Error(`Task not found: ${resolvedId}`);
+ // Mark the *resolved* not-found so the read side can tell it apart from a
+ // network / 500 rejection (which propagates from `taskService.getDetail`
+ // above with an HTTP status). Without this tag both would render the same
+ // terminal 404, telling the user a merely-errored task was deleted.
+ const notFound = new Error(`Task not found: ${resolvedId}`) as Error & { code?: string };
+ notFound.code = 'TASK_NOT_FOUND';
+ throw notFound;
}
this.internal_dispatchTaskDetail({
diff --git a/src/store/tree/actions.test.ts b/src/store/tree/actions.test.ts
index fa691d98d4b..270e5d229a8 100644
--- a/src/store/tree/actions.test.ts
+++ b/src/store/tree/actions.test.ts
@@ -30,6 +30,7 @@ vi.mock('@/store/file', () => ({
const createState = (): TreeState => ({
children: {},
epoch: 0,
+ errors: {},
expanded: {},
init: vi.fn(),
knowledgeBaseId: 'kb-1',
@@ -49,9 +50,7 @@ const createState = (): TreeState => ({
const createSetter = (getState: () => TreeState) => {
return (
partial:
- | Partial<TreeState>
- | TreeState
- | ((state: TreeState) => Partial<TreeState> | TreeState),
+ Partial<TreeState> | TreeState | ((state: TreeState) => Partial<TreeState> | TreeState),
) => {
const next = typeof partial === 'function' ? partial(getState()) : partial;
Object.assign(getState(), next);
diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.ts
index 93dbb96203b..36fc0d30dd2 100644
--- a/src/store/tree/actions.ts
+++ b/src/store/tree/actions.ts
@@ -69,6 +69,7 @@ export class TreeActionImpl {
{
children: {},
epoch: this.#get().epoch + 1,
+ errors: {},
expanded: {},
knowledgeBaseId,
status: {},
@@ -84,6 +85,7 @@ export class TreeActionImpl {
{
children: {},
epoch: this.#get().epoch + 1,
+ errors: {},
expanded: {},
knowledgeBaseId: null,
status: {},
@@ -107,8 +109,11 @@ export class TreeActionImpl {
const { epoch, knowledgeBaseId, status } = this.#get();
if (status[folderId] === 'loading') return;
+ // Clear any prior error for this folder so a retry doesn't keep the failure marker.
+ const nextErrors = { ...this.#get().errors };
+ delete nextErrors[folderId];
this.#set(
- { status: { ...this.#get().status, [folderId]: 'loading' } },
+ { errors: nextErrors, status: { ...this.#get().status, [folderId]: 'loading' } },
false,
'tree/loadChildren/start',
);
@@ -136,8 +141,14 @@ export class TreeActionImpl {
} catch (error) {
if (this.#get().epoch !== epoch) return;
console.error(`Failed to load children for ${folderId}:`, error);
+ // Mark the folder as errored (was swallowed to 'idle', which read as a false
+ // "empty folder" — Read §1.1 failure-as-empty). Keep the error so the view can
+ // render a failure state with Retry instead of the "add folder" empty.
this.#set(
- { status: { ...this.#get().status, [folderId]: 'idle' } },
+ {
+ errors: { ...this.#get().errors, [folderId]: error },
+ status: { ...this.#get().status, [folderId]: 'error' },
+ },
false,
'tree/loadChildren/error',
);
diff --git a/src/store/tree/initialState.ts b/src/store/tree/initialState.ts
index a6f7c6699ad..eb494c1a954 100644
--- a/src/store/tree/initialState.ts
+++ b/src/store/tree/initialState.ts
@@ -2,6 +2,7 @@ import type { TreeDataState } from './types';
export interface TreeInitialState extends TreeDataState {
epoch: number;
+ errors: Record<string, unknown>;
expanded: Record<string, boolean>;
knowledgeBaseId: string | null;
}
@@ -9,6 +10,7 @@ export interface TreeInitialState extends TreeDataState {
export const initialTreeState: TreeInitialState = {
children: {},
epoch: 0,
+ errors: {},
expanded: {},
knowledgeBaseId: null,
status: {},
diff --git a/src/store/tree/types.ts b/src/store/tree/types.ts
index b4422d3e2f3..8a7cf9c785b 100644
--- a/src/store/tree/types.ts
+++ b/src/store/tree/types.ts
@@ -15,13 +15,15 @@ export interface TreeItem {
export interface TreeDataState {
children: Record<string, TreeItem[]>;
- status: Record<string, 'idle' | 'loading' | 'revalidating'>;
+ status: Record<string, 'idle' | 'loading' | 'revalidating' | 'error'>;
}
export type TreeStoreHandle = StoreHandle<TreeDataState>;
export interface TreeState extends TreeDataState {
epoch: number;
+ /** Last load error per folderId, so a failed fetch renders a failure state (with Retry) instead of a false "empty folder". */
+ errors: Record<string, unknown>;
expandAncestors: (folderIds: string[]) => Promise<void>;
expanded: Record<string, boolean>;