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.

πŸ› fix(async): surface retryable fetch failure states (#16647)

Arvin Xu60e26ec6e2a5
diff --git a/.agents/skills/data-fetching-architecture/SKILL.md b/.agents/skills/data-fetching-architecture/SKILL.md
index afca4208c87..22c410ae535 100644
--- a/.agents/skills/data-fetching-architecture/SKILL.md
+++ b/.agents/skills/data-fetching-architecture/SKILL.md
@@ -269,13 +269,59 @@ export const createBenchmarkSlice: StateCreator<EvalStore, any, [], BenchmarkAct
1. **SWR keys as constants** at top of file
2. **useClientDataSWR** for all data fetching (never useEffect)
-3. **onSuccess callback** updates store state
+3. **onSuccess/onData callback** updates store state
4. **Refresh methods** use `mutate()` to invalidate cache
-5. **Loading states** in initialState, updated in onSuccess
+5. **Loading states** in initialState, updated in onSuccess/onData
6. **Mutations** call service, then refresh relevant cache
---
+## Async Failure Boundary Contract
+
+Every read hook returns an SWR response that includes `error` and `mutate`; the surface must
+consume them. A success-only init flag (`!isInit`, `!map[id]`, `data ?? []`) is not enough:
+when the request fails, that flag often never flips, so the UI paints a permanent skeleton,
+a fake empty state, a false `NotFound`, or a confident zero-value metric.
+
+Use the shared UI primitives:
+
+- `AsyncBoundary` for normal loading / error / empty / data surfaces.
+- `AsyncError` for custom layouts, detail pages, inline load-more failures, or metrics.
+
+Core precedence for first-load failures:
+
+```tsx
+const { data, error, isLoading, mutate } = useFetchXxx();
+
+return (
+ <AsyncBoundary
+ data={data}
+ empty={<EmptyState />}
+ error={error}
+ isEmpty={!error && data?.length === 0}
+ isLoading={isLoading}
+ onRetry={() => {
+ void mutate();
+ }}
+ >
+ <List items={data ?? []} />
+ </AsyncBoundary>
+);
+```
+
+Rules:
+
+- Check `error` before empty / `NotFound` / zero defaults. Error is not a kind of empty.
+- Keep already-loaded content on background revalidation failures; only replace the surface
+ when there is no settled data to preserve.
+- For detail maps, don't put the error branch after `if (!map[id]) return <Skeleton/>`.
+ First-load failures never populate the map, making that error branch unreachable.
+- For infinite scroll / load-more, persist a per-bucket `loadMoreError` and render an
+ inline Retry row. Do not let an `IntersectionObserver` silently retry while the error is
+ still unresolved.
+- For merged fetched + static lists, branch on the fetched slice's `error` before merging.
+ Static fallback rows can make a failed fetch look like a plausible partial catalog.
+
## Layer 3: Component Usage
### Fetching List Data
@@ -600,9 +646,12 @@ See `store-data-structures` for details.
### Step 4: Component Usage
- [ ] Use store hooks (NOT useEffect)
+- [ ] Destructure and consume `error` / `mutate`; wrap first-load surfaces in `AsyncBoundary`
+ or render `AsyncError` before empty / `NotFound` / zero defaults
- [ ] List pages: access `xxxList` array
- [ ] Detail pages: access `xxxDetailMap[id]`
- [ ] Use loading states for UI feedback
+- [ ] Infinite-scroll failures persist as a visible tail Retry row, not a silent `catch`
**Mental model:** Types β†’ Service β†’ Reducer β†’ Slice β†’ Component 🎯
diff --git a/src/features/AgentDocumentPage/Header/index.tsx b/src/features/AgentDocumentPage/Header/index.tsx
index 7e34f1976f5..296dae40444 100644
--- a/src/features/AgentDocumentPage/Header/index.tsx
+++ b/src/features/AgentDocumentPage/Header/index.tsx
@@ -22,6 +22,7 @@ interface HeaderProps {
agentDocumentId?: string;
agentId: string;
documentId: string;
+ itemError?: unknown;
onBack: () => void;
onDeleted: () => void;
title?: string;
@@ -29,9 +30,13 @@ interface HeaderProps {
}
const Header = memo<HeaderProps>(
- ({ agentId, agentDocumentId, documentId, onBack, onDeleted, title, updatedAt }) => {
+ ({ agentId, agentDocumentId, documentId, itemError, onBack, onDeleted, title, updatedAt }) => {
const { t } = useTranslation(['file', 'chat']);
const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));
+ const showTitleError = !!itemError && !title;
+ const resolvedTitle = showTitleError
+ ? t('workingPanel.resources.error', { ns: 'chat' })
+ : title || t('pageEditor.titlePlaceholder');
const { menuItems } = useMenu({
agentDocumentId,
agentId,
@@ -57,8 +62,12 @@ const Header = memo<HeaderProps>(
</Text>
</Flexbox>
<Text style={{ color: cssVar.colorTextQuaternary, flexShrink: 0 }}>/</Text>
- <Text className={cx(oneLineEllipsis)} style={{ minWidth: 0 }} weight={500}>
- {title || t('pageEditor.titlePlaceholder')}
+ <Text
+ className={cx(oneLineEllipsis)}
+ style={{ color: showTitleError ? cssVar.colorError : undefined, minWidth: 0 }}
+ weight={500}
+ >
+ {resolvedTitle}
</Text>
</Flexbox>
}
diff --git a/src/features/AgentDocumentPage/RightPanel/index.tsx b/src/features/AgentDocumentPage/RightPanel/index.tsx
index 2bef03fb24f..55733b71d30 100644
--- a/src/features/AgentDocumentPage/RightPanel/index.tsx
+++ b/src/features/AgentDocumentPage/RightPanel/index.tsx
@@ -93,7 +93,11 @@ const AgentDocumentRightPanel = memo(() => {
// Deduped against AgentDocumentsGroup's own fetch (same SWR key). When the
// agent has no plain documents (e.g. only skills) we default to the Skills
// tab so the panel doesn't open on an empty Documents view.
- const { data: documentList = [], isLoading: isDocumentListLoading } = useClientDataSWR(
+ const {
+ data: documentList = [],
+ error: documentListError,
+ isLoading: isDocumentListLoading,
+ } = useClientDataSWR(
activeAgentId ? agentDocumentSWRKeys.documentsList(activeAgentId) : null,
() => agentDocumentService.listDocuments({ agentId: activeAgentId! }),
);
@@ -117,7 +121,9 @@ const AgentDocumentRightPanel = memo(() => {
);
const activeTab: AgentDocumentPanelTab =
pickedTab ??
- (isSkillEntry || (!isDocumentListLoading && !hasDocuments) ? 'skills' : 'documents');
+ (isSkillEntry || (!documentListError && !isDocumentListLoading && !hasDocuments)
+ ? 'skills'
+ : 'documents');
return (
<RightPanel stableLayout defaultWidth={360} maxWidth={720} minWidth={300}>
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsx
index c8fb8adb083..6eb466b3f51 100644
--- a/src/features/AgentDocumentPage/index.test.tsx
+++ b/src/features/AgentDocumentPage/index.test.tsx
@@ -31,17 +31,28 @@ vi.mock('@/features/WideScreenContainer', () => ({
),
}));
+const headerProps = vi.hoisted(() => ({
+ current: undefined as undefined | Record<string, unknown>,
+}));
+
vi.mock('./Header', () => ({
- default: ({ documentId }: { documentId?: string }) => (
- <div data-document-id={documentId} data-testid="header" />
- ),
+ default: (props: Record<string, unknown>) => {
+ headerProps.current = props;
+ return <div data-document-id={props.documentId as string | undefined} data-testid="header" />;
+ },
}));
-vi.mock('./useAgentDocumentItem', () => ({
- useAgentDocumentItem: () => ({
+const agentDocumentItemState = vi.hoisted(() => ({
+ current: {
+ error: undefined as unknown,
item: { filename: 'spec.md', id: 'agent-document-1', title: 'Spec' },
mutate: vi.fn(),
- }),
+ skillBundle: undefined as unknown,
+ },
+}));
+
+vi.mock('./useAgentDocumentItem', () => ({
+ useAgentDocumentItem: () => agentDocumentItemState.current,
}));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
@@ -89,15 +100,23 @@ vi.mock('@/store/user/selectors', () => ({
describe('AgentDocumentPage', () => {
beforeEach(() => {
mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = false;
+ agentDocumentItemState.current = {
+ error: undefined,
+ item: { filename: 'spec.md', id: 'agent-document-1', title: 'Spec' },
+ mutate: vi.fn(),
+ skillBundle: undefined,
+ };
docChatTopicState.current = {
error: undefined,
isLoading: false,
topicId: 'doc-topic-1',
};
+ headerProps.current = undefined;
panelProps.current = undefined;
});
afterEach(() => {
+ headerProps.current = undefined;
panelProps.current = undefined;
});
@@ -107,6 +126,15 @@ describe('AgentDocumentPage', () => {
expect(screen.getByTestId('header').dataset.documentId).toBe('docs_abc');
});
+ it('passes document list fetch errors to the header', () => {
+ const itemError = new Error('metadata failed');
+ agentDocumentItemState.current = { ...agentDocumentItemState.current, error: itemError };
+
+ render(<AgentDocumentPage documentId="docs_abc" />);
+
+ expect(headerProps.current).toMatchObject({ itemError });
+ });
+
it('does not render FloatingChatPanel when the lab feature is disabled', () => {
render(<AgentDocumentPage documentId="docs_abc" />);
expect(screen.queryByTestId('floating-chat-panel')).toBeNull();
diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsx
index 34224cb3364..093f30643e6 100644
--- a/src/features/AgentDocumentPage/index.tsx
+++ b/src/features/AgentDocumentPage/index.tsx
@@ -31,7 +31,7 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
const { aid } = useParams<{ aid: string }>();
const agentId = aid ?? '';
const navigate = useWorkspaceAwareNavigate();
- const { item, mutate, skillBundle } = useAgentDocumentItem(agentId, documentId);
+ const { error: itemError, item, mutate, skillBundle } = useAgentDocumentItem(agentId, documentId);
const enableFloatingChatPanel = useUserStore(
labPreferSelectors.enableAgentDocumentFloatingChatPanel,
@@ -62,13 +62,14 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
agentDocumentId={item?.id}
agentId={agentId}
documentId={documentId}
+ itemError={itemError}
title={title}
updatedAt={item?.updatedAt}
onBack={backToChat}
onDeleted={backToChat}
/>
),
- [agentId, backToChat, documentId, item?.id, item?.updatedAt, title],
+ [agentId, backToChat, documentId, item?.id, item?.updatedAt, itemError, title],
);
return (
diff --git a/src/features/AgentDocumentPage/useAgentDocumentItem.ts b/src/features/AgentDocumentPage/useAgentDocumentItem.ts
index 206497fdac9..2dae3503197 100644
--- a/src/features/AgentDocumentPage/useAgentDocumentItem.ts
+++ b/src/features/AgentDocumentPage/useAgentDocumentItem.ts
@@ -17,7 +17,7 @@ import {
* bundle rename.
*/
export const useAgentDocumentItem = (agentId: string | undefined, documentId: string) => {
- const { data, mutate } = useClientDataSWR(
+ const { data, error, mutate } = useClientDataSWR(
agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,
() => agentDocumentService.listDocuments({ agentId: agentId! }),
);
@@ -29,5 +29,5 @@ export const useAgentDocumentItem = (agentId: string | undefined, documentId: st
? data?.find((d) => d.documentId === item.parentId)
: undefined;
- return { item, mutate, skillBundle };
+ return { error, item, mutate, skillBundle };
};
diff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsx
index e0e9584c67d..e5f305d0d5c 100644
--- a/src/features/AgentTopicManager/index.tsx
+++ b/src/features/AgentTopicManager/index.tsx
@@ -5,6 +5,7 @@ import { Flexbox, Skeleton } from '@lobehub/ui';
import { memo, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import Loading from '@/components/Loading/BrandTextLoading';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -47,6 +48,7 @@ const AgentTopicManager = memo(() => {
const allTopics = useChatStore(topicSelectors.agentTopicsViewTopics);
const hasMore = useChatStore(topicSelectors.agentTopicsViewHasMore);
const isLoadingMore = useChatStore(topicSelectors.agentTopicsViewIsLoadingMore);
+ const loadMoreError = useChatStore(topicSelectors.agentTopicsViewLoadMoreError);
const reset = useTopicsViewStore((s) => s.reset);
const search = useTopicsViewStore((s) => s.search);
@@ -73,7 +75,7 @@ const AgentTopicManager = memo(() => {
reset();
}, [activeAgentId, reset]);
- const { isLoading } = useFetchAgentTopicsView(true, {
+ const { error, isLoading, mutate } = useFetchAgentTopicsView(true, {
agentId: activeAgentId,
pageSize: PAGE_SIZE,
// Opt into the heavier card-detail columns (firstUserMessage,
@@ -184,7 +186,7 @@ const AgentTopicManager = memo(() => {
if (!root || !sentinel) return;
const observer = new IntersectionObserver(
([entry]) => {
- if (entry.isIntersecting && hasMore && !isLoadingMore) {
+ if (entry.isIntersecting && hasMore && !isLoadingMore && !loadMoreError) {
void loadMoreAgentTopicsView();
}
},
@@ -192,7 +194,7 @@ const AgentTopicManager = memo(() => {
);
observer.observe(sentinel);
return () => observer.disconnect();
- }, [hasMore, isLoadingMore, isSearchMode, loadMoreAgentTopicsView]);
+ }, [hasMore, isLoadingMore, isSearchMode, loadMoreAgentTopicsView, loadMoreError]);
if (!activeAgentId) return <Loading debugId="AgentTopicManager" />;
@@ -220,7 +222,15 @@ const AgentTopicManager = memo(() => {
>
<Toolbar projects={projects} statusCounts={statusCounts} />
<BulkActionBar />
- {isLoading && baseTopics.length === 0 ? (
+ {!isSearchMode && error && !isLoading && baseTopics.length === 0 ? (
+ <AsyncError
+ error={error}
+ variant={'block'}
+ onRetry={() => {
+ void mutate();
+ }}
+ />
+ ) : isLoading && baseTopics.length === 0 ? (
<Skeleton active paragraph={{ rows: 6 }} title={false} />
) : totalAfterFilter === 0 ? (
<EmptyState
@@ -255,6 +265,17 @@ const AgentTopicManager = memo(() => {
</span>
</Flexbox>
)}
+ {!isSearchMode && loadMoreError && !isLoadingMore && (
+ <Flexbox align={'center'} paddingBlock={12}>
+ <AsyncError
+ error={loadMoreError}
+ variant={'inline'}
+ onRetry={() => {
+ void loadMoreAgentTopicsView();
+ }}
+ />
+ </Flexbox>
+ )}
</>
)}
</Flexbox>
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 8b46d98f732..4a22611a06f 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -3,6 +3,7 @@
import type { ReactNode } from 'react';
import { memo, useCallback, useMemo } from 'react';
+import AsyncError from '@/components/AsyncError';
import { useFetchAgentDocuments } from '@/hooks/useFetchAgentDocuments';
import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';
@@ -171,6 +172,18 @@ const ChatList = memo<ChatListProps>(
// because there's no server data to fetch - only local optimistic updates exist
const isNewConversation = !context.topicId;
+ if (!messagesInit && !isNewConversation && messagesSWR.error && !messagesSWR.isLoading) {
+ return (
+ <AsyncError
+ error={messagesSWR.error}
+ variant={'page'}
+ onRetry={() => {
+ void messagesSWR.mutate();
+ }}
+ />
+ );
+ }
+
if (!messagesInit && !isNewConversation) {
return <SkeletonList />;
}
diff --git a/src/features/DailyBrief/__tests__/index.test.tsx b/src/features/DailyBrief/__tests__/index.test.tsx
index 4e4b48af8b5..5604c779524 100644
--- a/src/features/DailyBrief/__tests__/index.test.tsx
+++ b/src/features/DailyBrief/__tests__/index.test.tsx
@@ -55,6 +55,10 @@ vi.mock('@/features/Recommendations', () => ({
useRecommendationsVisible: () => mocks.state.recommendationsVisible,
}));
+vi.mock('@/components/AsyncError', () => ({
+ default: () => <div data-testid="async-error" />,
+}));
+
vi.mock('@/routes/(main)/home/features/components/GroupBlock', () => ({
default: ({
action,
@@ -122,6 +126,7 @@ beforeEach(() => {
mocks.state.isLogin = true;
mocks.state.recommendationsVisible = true;
mocks.useFetchBriefs.mockClear();
+ mocks.useFetchBriefs.mockReturnValue({ error: undefined, isLoading: false, mutate: vi.fn() });
});
describe('DailyBrief', () => {
@@ -144,4 +149,20 @@ describe('DailyBrief', () => {
expect(screen.getByText('Brief item')).toBeInTheDocument();
expect(screen.getByText('View all tasks')).toBeInTheDocument();
});
+
+ it('renders a retryable error state when the first brief fetch fails', () => {
+ mocks.state.isBriefsInit = false;
+ mocks.useFetchBriefs.mockReturnValue({
+ error: new Error('brief fetch failed'),
+ isLoading: false,
+ mutate: vi.fn(),
+ });
+
+ render(<DailyBrief />);
+
+ expect(screen.getByTestId('group-block')).toBeInTheDocument();
+ expect(screen.getByText('Brief')).toBeInTheDocument();
+ expect(screen.getByTestId('async-error')).toBeInTheDocument();
+ expect(screen.queryByText('Brief skeleton')).not.toBeInTheDocument();
+ });
});
diff --git a/src/features/DailyBrief/index.tsx b/src/features/DailyBrief/index.tsx
index 18ff1a251ab..de4d5baf357 100644
--- a/src/features/DailyBrief/index.tsx
+++ b/src/features/DailyBrief/index.tsx
@@ -3,6 +3,7 @@ import { Newspaper } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import TopicChatDrawer from '@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer';
import DocumentPreviewModal from '@/features/DocumentModal/Preview';
import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';
@@ -21,7 +22,7 @@ const DailyBrief = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const isLogin = useUserStore(authSelectors.isLogin);
const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
- useFetchBriefs(isLogin);
+ const briefsSWR = useFetchBriefs(isLogin);
const briefs = useBriefStore(briefListSelectors.briefs);
const isInit = useBriefStore(briefListSelectors.isBriefsInit);
@@ -29,6 +30,20 @@ const DailyBrief = memo(() => {
if (!isLogin) return null;
+ if (briefsSWR.error && !isInit && !briefsSWR.isLoading) {
+ return (
+ <GroupBlock icon={Newspaper} title={t('brief.title')}>
+ <AsyncError
+ error={briefsSWR.error}
+ variant={'block'}
+ onRetry={() => {
+ void briefsSWR.mutate();
+ }}
+ />
+ </GroupBlock>
+ );
+ }
+
if (!isInit) {
return (
<GroupBlock icon={Newspaper} title={t('brief.title')}>
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsx
index 5560602b699..013c33143d8 100644
--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx
@@ -4,13 +4,23 @@
import { act, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { editorSelectors } from '@/store/document/slices/editor';
+
import DocumentIdMode from './DocumentIdMode';
const handleContentChangeStore = vi.fn();
const performSave = vi.fn();
const flushSave = vi.fn();
const onEditorInit = vi.fn().mockResolvedValue(undefined);
-const useFetchDocument = vi.fn(() => ({ error: undefined }));
+const createFetchDocumentResult = (
+ overrides: Partial<{
+ data: unknown;
+ error: unknown;
+ isLoading: boolean;
+ mutate: ReturnType<typeof vi.fn>;
+ }> = {},
+) => ({ data: undefined, error: undefined, isLoading: false, mutate: vi.fn(), ...overrides });
+const useFetchDocument = vi.fn(() => createFetchDocumentResult());
let saveHotkeyHandler: (() => void | Promise<void>) | undefined;
@@ -38,6 +48,14 @@ vi.mock('@/hooks/useHotkeys', () => ({
}),
}));
+vi.mock('@/components/404', () => ({
+ default: vi.fn(() => <div data-testid="not-found" />),
+}));
+
+vi.mock('@/components/AsyncError', () => ({
+ default: vi.fn(() => <div data-testid="async-error" />),
+}));
+
vi.mock('@/store/document', () => ({
useDocumentStore: Object.assign(
vi.fn((selector: (state: typeof mockDocumentStore) => unknown) => selector(mockDocumentStore)),
@@ -69,6 +87,7 @@ describe('DocumentIdMode', () => {
flushSave.mockClear();
onEditorInit.mockClear();
useFetchDocument.mockClear();
+ vi.mocked(editorSelectors.isDocumentLoading).mockReturnValue(() => false);
saveHotkeyHandler = undefined;
});
@@ -126,4 +145,36 @@ describe('DocumentIdMode', () => {
topicId: 'topic-1',
});
});
+
+ it('should render a fetch error before the document loading gate', () => {
+ const editor = {
+ getLexicalEditor: vi.fn(() => ({})),
+ } as any;
+ useFetchDocument.mockReturnValueOnce({
+ ...createFetchDocumentResult(),
+ error: new Error('load failed'),
+ });
+ vi.mocked(editorSelectors.isDocumentLoading).mockReturnValueOnce(() => true);
+
+ render(<DocumentIdMode documentId="doc-1" editor={editor} />);
+
+ expect(screen.getByTestId('async-error')).toBeInTheDocument();
+ expect(screen.queryByTestId('internal-editor')).not.toBeInTheDocument();
+ });
+
+ it('should render not found when the document fetch resolves to null', () => {
+ const editor = {
+ getLexicalEditor: vi.fn(() => ({})),
+ } as any;
+ useFetchDocument.mockReturnValueOnce({
+ ...createFetchDocumentResult(),
+ data: null,
+ });
+ vi.mocked(editorSelectors.isDocumentLoading).mockReturnValueOnce(() => true);
+
+ render(<DocumentIdMode documentId="doc-1" editor={editor} />);
+
+ expect(screen.getByTestId('not-found')).toBeInTheDocument();
+ expect(screen.queryByTestId('internal-editor')).not.toBeInTheDocument();
+ });
});
diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsx
index c9b18b9a9db..8a4ba36689d 100644
--- a/src/features/EditorCanvas/DocumentIdMode.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.tsx
@@ -1,11 +1,13 @@
'use client';
import { type IEditor } from '@lobehub/editor';
-import { Alert, Skeleton } from '@lobehub/ui';
+import { Skeleton } from '@lobehub/ui';
import { memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { createStoreUpdater } from 'zustand-utils';
+import NotFound from '@/components/404';
+import AsyncError from '@/components/AsyncError';
import { useSaveDocumentHotkey } from '@/hooks/useHotkeys';
import { useDocumentStore } from '@/store/document';
import { editorSelectors } from '@/store/document/slices/editor';
@@ -23,23 +25,6 @@ const EditorSkeleton = memo(() => (
</div>
));
-/**
- * Error display for fetch failures
- */
-const EditorError = memo<{ error: Error }>(({ error }) => {
- const { t } = useTranslation('file');
-
- return (
- <Alert
- showIcon
- description={error.message || t('pageEditor.loadError', 'Failed to load document')}
- style={{ margin: 16 }}
- title={t('pageEditor.error', 'Error')}
- type="error"
- />
- );
-});
-
export interface DocumentIdModeProps extends EditorCanvasProps {
documentId: string;
editor: IEditor | undefined;
@@ -93,7 +78,12 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
);
// Use SWR hook for document fetching (auto-initializes via onSuccess in DocumentStore)
- const { data: remoteDocument, error } = useFetchDocument(documentId, {
+ const {
+ data: remoteDocument,
+ error,
+ isLoading: isFetchingDocument,
+ mutate,
+ } = useFetchDocument(documentId, {
autoSave,
editor,
sourceType,
@@ -205,6 +195,30 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
remoteDocumentVersion,
]);
+ if (error && isLoading && !isFetchingDocument) {
+ return (
+ <>
+ {unsavedGuardNode}
+ <AsyncError
+ error={error}
+ variant={'page'}
+ onRetry={() => {
+ void mutate();
+ }}
+ />
+ </>
+ );
+ }
+
+ if (remoteDocument === null) {
+ return (
+ <>
+ {unsavedGuardNode}
+ <NotFound />
+ </>
+ );
+ }
+
// Show loading state
if (isLoading) {
return (
@@ -220,7 +234,15 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
return (
<>
{unsavedGuardNode}
- {error && <EditorError error={error as Error} />}
+ {error && (
+ <AsyncError
+ error={error}
+ variant={'inline'}
+ onRetry={() => {
+ void mutate();
+ }}
+ />
+ )}
<InternalEditor
contentChangeLockRef={contentChangeLockRef}
editor={editor}
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
index eb6c0172831..b8cbf1ded21 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
@@ -6,6 +6,7 @@ import { memo, useCallback, useEffect, useRef } from 'react';
import { type VListHandle } from 'virtua';
import { VList } from 'virtua';
+import AsyncError from '@/components/AsyncError';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import TopicEmpty from '@/features/TopicEmpty';
import { useChatStore } from '@/store/chat';
@@ -30,6 +31,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
activeThreadId,
hasMore,
isLoadingMore,
+ loadMoreError,
isExpandingPageSize,
loadMoreTopics,
activeAgentId,
@@ -39,6 +41,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
s.activeThreadId,
topicSelectors.hasMoreTopics(s),
topicSelectors.isLoadingMoreTopics(s),
+ topicSelectors.loadMoreTopicsError(s),
topicSelectors.isExpandingPageSize(s),
s.loadMoreTopics,
s.activeAgentId,
@@ -81,7 +84,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
// Initial load: calculate how many items needed to fill viewport
useEffect(() => {
- if (!open || initializedRef.current || isLoadingMore || isSearching) return;
+ if (!open || initializedRef.current || isLoadingMore || isSearching || loadMoreError) return;
const timer = setTimeout(() => {
const ref = virtuaRef.current;
@@ -112,7 +115,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
}, 100);
return () => clearTimeout(timer);
- }, [open, count, hasMore, loadMoreTopics, isLoadingMore]);
+ }, [open, count, hasMore, loadMoreTopics, isLoadingMore, loadMoreError, isSearching]);
// Reset initialized flag when drawer closes
useEffect(() => {
@@ -127,7 +130,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
if (isSearching) return;
const ref = virtuaRef.current;
- if (!ref || !hasMore) return;
+ if (!ref || !hasMore || loadMoreError) return;
// Use findItemIndex to detect scroll position
const bottomVisibleIndex = ref.findItemIndex(ref.scrollOffset + ref.viewportSize);
@@ -137,12 +140,27 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
fetchedCountRef.current = count;
await loadMoreTopics();
}
- }, [hasMore, loadMoreTopics, count, isSearching]);
+ }, [hasMore, loadMoreTopics, count, isSearching, loadMoreError]);
const showLoading = (isLoadingMore || isExpandingPageSize) && !isSearching;
const showSearchLoading = isSearching && isSearchingTopic;
+ const showLoadMoreError = !isSearching && !!loadMoreError && !isLoadingMore;
// Show empty state when no topics
+ if (count === 0 && showLoadMoreError) {
+ return (
+ <Flexbox padding={12}>
+ <AsyncError
+ error={loadMoreError}
+ variant={'block'}
+ onRetry={() => {
+ void loadMoreTopics();
+ }}
+ />
+ </Flexbox>
+ );
+ }
+
if (count === 0 && !showLoading && !showSearchLoading) {
return <TopicEmpty search={Boolean(searchKeyword)} />;
}
@@ -181,6 +199,17 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {
<SkeletonList rows={3} />
</Flexbox>
)}
+ {showLoadMoreError && (
+ <Flexbox padding={'4px 8px'}>
+ <AsyncError
+ error={loadMoreError}
+ variant={'inline'}
+ onRetry={() => {
+ void loadMoreTopics();
+ }}
+ />
+ </Flexbox>
+ )}
</VList>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index a8640b6bfd5..e9ae2846f0a 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -67,6 +67,14 @@ vi.mock('@/components/NeuralNetworkLoading', () => ({
default: () => <div data-testid="neural-network-loading" />,
}));
+vi.mock('@/components/AsyncError', () => ({
+ default: ({ onRetry }: { onRetry?: () => void }) => (
+ <button data-testid="async-error" onClick={onRetry}>
+ async-error
+ </button>
+ ),
+}));
+
vi.mock('@/libs/swr', () => ({
useClientDataSWR: (...args: unknown[]) => useClientDataSWR(...args),
}));
@@ -580,16 +588,18 @@ describe('AgentDocumentsGroup', () => {
});
it('renders error state when SWR returns an error', () => {
+ const mutate = vi.fn();
useClientDataSWR.mockReturnValue({
data: [],
error: new Error('oops'),
isLoading: false,
- mutate: vi.fn(),
+ mutate,
});
render(<AgentDocumentsGroup />);
- expect(screen.getByText('Failed to load resources')).toBeInTheDocument();
+ fireEvent.click(screen.getByTestId('async-error'));
+ expect(mutate).toHaveBeenCalled();
});
it('renders the loading spinner while data is being fetched', () => {
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index da2148de1b6..ca277a26770 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -17,6 +17,7 @@ import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
+import AsyncError from '@/components/AsyncError';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';
@@ -377,7 +378,13 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
if (error) {
return (
<Center flex={1} paddingBlock={24}>
- <Text type={'danger'}>{t('workingPanel.resources.error')}</Text>
+ <AsyncError
+ error={error}
+ variant={'block'}
+ onRetry={() => {
+ void mutate();
+ }}
+ />
</Center>
);
}
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index c4b22a4324c..db0d10aaf0f 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -74,6 +74,7 @@ beforeEach(() => {
activeAgentId: undefined,
activeGroupId: undefined,
activeTopicId: undefined,
+ agentTopicsViewMap: {},
searchTopics: [],
topicDataMap: {},
topicLoadingIdCounts: {},
@@ -1285,6 +1286,93 @@ describe('topic action', () => {
expect(topicData.hasMore).toBe(false);
});
});
+ describe('loadMoreAgentTopicsView', () => {
+ it('records a pagination error without clearing existing topics or hasMore', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'agent-1';
+ const key = topicMapKey({ agentId });
+ const topics = [
+ { id: 'topic-1', title: 'Topic 1' },
+ { id: 'topic-2', title: 'Topic 2' },
+ ] as ChatTopic[];
+ const error = new Error('load more failed');
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ agentTopicsViewMap: {
+ [key]: {
+ currentPage: 0,
+ hasMore: true,
+ isLoadingMore: false,
+ items: topics,
+ pageSize: 2,
+ total: 4,
+ withDetails: true,
+ },
+ },
+ });
+ });
+
+ (topicService.getTopics as Mock).mockRejectedValueOnce(error);
+
+ await act(async () => {
+ await result.current.loadMoreAgentTopicsView();
+ });
+
+ const topicData = useChatStore.getState().agentTopicsViewMap[key];
+ expect(topicService.getTopics).toHaveBeenCalledWith({
+ agentId,
+ current: 1,
+ pageSize: 2,
+ withDetails: true,
+ });
+ expect(topicData.items).toEqual(topics);
+ expect(topicData.hasMore).toBe(true);
+ expect(topicData.isLoadingMore).toBe(false);
+ expect(topicData.loadMoreError).toBe(error);
+ });
+
+ it('clears a stale pagination error after retry succeeds', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = 'agent-1';
+ const key = topicMapKey({ agentId });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ agentTopicsViewMap: {
+ [key]: {
+ currentPage: 0,
+ hasMore: true,
+ isLoadingMore: false,
+ items: [{ id: 'topic-1', title: 'Topic 1' } as ChatTopic],
+ loadMoreError: new Error('previous failure'),
+ pageSize: 1,
+ total: 2,
+ },
+ },
+ });
+ });
+
+ (topicService.getTopics as Mock).mockResolvedValueOnce({
+ items: [{ id: 'topic-2', title: 'Topic 2' }],
+ total: 2,
+ });
+
+ await act(async () => {
+ await result.current.loadMoreAgentTopicsView();
+ });
+
+ const topicData = useChatStore.getState().agentTopicsViewMap[key];
+ expect(topicData.items.map((item) => item.id)).toEqual(['topic-1', 'topic-2']);
+ expect(topicData.currentPage).toBe(1);
+ expect(topicData.hasMore).toBe(false);
+ expect(topicData.isLoadingMore).toBe(false);
+ expect(topicData.loadMoreError).toBeUndefined();
+ });
+ });
+
describe('removeUnstarredTopic', () => {
it('should remove unstarred topics and refresh the topic list', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 65b0a054b91..3ade42f3f9c 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -512,6 +512,7 @@ export class ChatTopicActionImpl {
isInbox: Boolean(isInbox),
isExpandingPageSize: false,
isLoadingMore: false,
+ loadMoreError: undefined,
items: nextItems,
pageSize,
total: totalCount,
@@ -609,6 +610,7 @@ export class ChatTopicActionImpl {
hasMore,
isExpandingPageSize: false,
isLoadingMore: false,
+ loadMoreError: undefined,
items: nextItems,
pageSize,
total: totalCount,
@@ -640,7 +642,7 @@ export class ChatTopicActionImpl {
{
agentTopicsViewMap: {
...agentTopicsViewMap,
- [key]: { ...currentData, isLoadingMore: true },
+ [key]: { ...currentData, isLoadingMore: true, loadMoreError: undefined },
},
},
false,
@@ -667,6 +669,7 @@ export class ChatTopicActionImpl {
currentPage: nextPage,
hasMore,
isLoadingMore: false,
+ loadMoreError: undefined,
items: nextItems,
total: result.total,
},
@@ -675,12 +678,16 @@ export class ChatTopicActionImpl {
false,
n('loadMoreAgentTopicsView(success)'),
);
- } catch {
+ } catch (error) {
this.#set(
{
agentTopicsViewMap: {
...this.#get().agentTopicsViewMap,
- [key]: { ...this.#get().agentTopicsViewMap[key]!, isLoadingMore: false },
+ [key]: {
+ ...this.#get().agentTopicsViewMap[key]!,
+ isLoadingMore: false,
+ loadMoreError: error,
+ },
},
},
false,
@@ -712,7 +719,7 @@ export class ChatTopicActionImpl {
{
topicDataMap: {
...topicDataMap,
- [key]: { ...currentData!, isLoadingMore: true },
+ [key]: { ...currentData!, isLoadingMore: true, loadMoreError: undefined },
},
},
false,
@@ -752,6 +759,7 @@ export class ChatTopicActionImpl {
hasMore,
isInbox: currentData?.isInbox,
isLoadingMore: false,
+ loadMoreError: undefined,
items: nextItems,
pageSize,
total: result.total,
@@ -762,12 +770,16 @@ export class ChatTopicActionImpl {
false,
n('loadMoreTopics(success)'),
);
- } catch {
+ } catch (error) {
this.#set(
{
topicDataMap: {
...this.#get().topicDataMap,
- [key]: { ...this.#get().topicDataMap[key]!, isLoadingMore: false },
+ [key]: {
+ ...this.#get().topicDataMap[key]!,
+ isLoadingMore: false,
+ loadMoreError: error,
+ },
},
},
false,
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index d690a722da4..d571c51d3c9 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -12,6 +12,12 @@ export interface TopicData {
isInbox?: boolean;
isLoadingMore?: boolean;
items: ChatTopic[];
+ /**
+ * Last page-fetch failure. Kept separate from the first-page SWR `error` so
+ * infinite-scroll surfaces can render an inline Retry row instead of silently
+ * dropping the loading-more row while `hasMore` remains true.
+ */
+ loadMoreError?: unknown;
/**
* Last fetched/used page size for this topic container.
* Used to detect "pageSize expansion" (user increases pageSize) without being affected by SWR revalidation
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index cb51e37feaf..5e87bc989c8 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -205,6 +205,8 @@ const hasMoreTopicsForSidebar = (s: ChatStoreState): boolean => {
const isLoadingMoreTopics = (s: ChatStoreState): boolean =>
currentTopicData(s)?.isLoadingMore ?? false;
+const loadMoreTopicsError = (s: ChatStoreState): unknown => currentTopicData(s)?.loadMoreError;
+
const isExpandingPageSize = (s: ChatStoreState): boolean =>
currentTopicData(s)?.isExpandingPageSize ?? false;
@@ -224,9 +226,13 @@ const agentTopicsViewHasMore = (s: ChatStoreState): boolean =>
const agentTopicsViewIsLoadingMore = (s: ChatStoreState): boolean =>
agentTopicsViewData(s)?.isLoadingMore ?? false;
+const agentTopicsViewLoadMoreError = (s: ChatStoreState): unknown =>
+ agentTopicsViewData(s)?.loadMoreError;
+
export const topicSelectors = {
agentTopicsViewHasMore,
agentTopicsViewIsLoadingMore,
+ agentTopicsViewLoadMoreError,
agentTopicsViewTopics,
currentActiveTopic,
currentActiveTopicSummary,
@@ -252,5 +258,6 @@ export const topicSelectors = {
isLoadingMoreTopics,
isSearchingTopic,
isUndefinedTopics,
+ loadMoreTopicsError,
searchTopics,
};