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.

♻️ refactor(notification): move the inbox modal stream, counts and transfer requests onto @lobechat/replica (#22749)

Arvin Xu7d2387a90957
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx b/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx
index 5a6cc02e8bd..3aaafb73cb1 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx
+++ b/src/features/HomeSidebar/Header/components/InboxModal/Content.tsx
@@ -13,16 +13,15 @@ import { VList } from 'virtua';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import AsyncError from '@/components/AsyncError';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import { PENDING_TRANSFERS_SWR_KEY, TransferRequestItem } from '@/features/ResourceTransferRequest';
-import { useClientDataSWR } from '@/libs/swr';
+import { TransferRequestItem } from '@/features/ResourceTransferRequest';
import type { PendingTransferRequest } from '@/services/resourceTransferRequest';
-import { resourceTransferRequestService } from '@/services/resourceTransferRequest';
+import { useHomeStore } from '@/store/home';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import NotificationItem from './NotificationItem';
-import type { NotificationListHandle } from './useNotificationList';
-import { PAGE_SIZE, useNotificationList } from './useNotificationList';
+import { useNotificationList } from './useNotificationList';
+import { usePendingTransfers } from './usePendingTransfers';
const styles = stylex.create({
item: {
@@ -45,28 +44,30 @@ interface ContentProps {
* after a transfer action that has no loaded notification row to mark read.
*/
onRefreshInbox: () => void;
- /** See {@link useNotificationList} for why the list handle is registered. */
- registerHandle: (handle: NotificationListHandle) => void;
}
const getLinkedRequestId = (item: { metadata?: NotificationMetadata | null }) =>
item.metadata?.transfer?.requestId;
const Content = memo<ContentProps>(
- ({ category, isRead, onMarkAsRead, onArchive, onRefreshInbox, registerHandle }) => {
+ ({ category, isRead, onMarkAsRead, onArchive, onRefreshInbox }) => {
const { t } = useTranslation('notification');
const virtuaRef = useRef<VListHandle>(null);
const workspaceId = useActiveWorkspaceId();
const currentUserId = useUserStore(userProfileSelectors.userId);
const {
- data: pages,
error,
- isLoading,
- isValidating,
- mutate,
- setSize,
- } = useNotificationList({ category, isRead, registerHandle });
+ hasMore,
+ headError,
+ isConfirmed: isFeedConfirmed,
+ isHeadValidating,
+ isLoadingMore,
+ loadMore,
+ loadMoreError,
+ notifications: loadedNotifications,
+ retry,
+ } = useNotificationList({ category, isRead });
// Cross-resource transfer inbox: live pending requests rendered as
// notification-style items pinned above the immutable stream. Driven by
@@ -77,20 +78,21 @@ const Content = memo<ContentProps>(
// because row suppression below must hold on all of them (a linked row
// must never show alongside, or instead of, its live item).
const showTransfers = isRead !== true && (!category || category === 'pending');
- const { data: transferRequests, mutate: mutateTransfers } = useClientDataSWR<
- PendingTransferRequest[]
- >(workspaceId ? [PENDING_TRANSFERS_SWR_KEY, workspaceId] : null, () =>
- resourceTransferRequestService.listMine(),
- );
+ const {
+ error: transfersError,
+ isConfirmed: isTransfersConfirmed,
+ isValidating: isTransfersValidating,
+ requests: transferRequests,
+ retry: retryTransfers,
+ } = usePendingTransfers(!!workspaceId);
- // Reset scroll position and pagination when filter changes
+ // Each filter is its own replica entry; only the scroll position resets.
useEffect(() => {
- setSize(1);
virtuaRef.current?.scrollTo(0);
- }, [category, isRead, setSize]);
+ }, [category, isRead]);
- const notifications = pages?.flat() ?? [];
- const hasMore = pages ? pages.at(-1)?.length === PAGE_SIZE : false;
+ const notifications = loadedNotifications ?? [];
+ const isValidating = isLoadingMore || (!loadedNotifications && isHeadValidating);
const liveRequests = (showTransfers && currentUserId && transferRequests) || [];
// While a request is live its actionable item replaces the immutable
@@ -115,7 +117,7 @@ const Content = memo<ContentProps>(
// "request no longer live" so the conservative path (refresh) runs.
let next: PendingTransferRequest[] | undefined;
try {
- next = await mutateTransfers();
+ next = await useHomeStore.getState().settleTransferRequest(request.id, succeeded);
} catch (error) {
console.error('[InboxNotificationList] transfer revalidation failed', error);
}
@@ -128,7 +130,7 @@ const Content = memo<ContentProps>(
const stillLive = !!next?.some((item) => item.id === request.id);
if (succeeded || !stillLive) onRefreshInbox();
},
- [mutateTransfers, onRefreshInbox],
+ [onRefreshInbox],
);
// The VList renders the live transfer items followed by
@@ -139,25 +141,28 @@ const Content = memo<ContentProps>(
const renderedCount = liveRequests.length + visibleCount;
const handleScroll = useCallback(() => {
const ref = virtuaRef.current;
- if (!ref || !hasMore || isValidating || error) return;
+ if (!ref || !hasMore || isLoadingMore || loadMoreError) return;
const bottomVisibleIndex = ref.findItemIndex(ref.scrollOffset + ref.viewportSize);
- if (bottomVisibleIndex + 5 > renderedCount) {
- setSize((prev) => prev + 1);
- }
- }, [error, hasMore, isValidating, renderedCount, setSize]);
+ if (bottomVisibleIndex + 5 > renderedCount) loadMore();
+ }, [hasMore, isLoadingMore, loadMore, loadMoreError, renderedCount]);
// When every loaded row is suppressed by a live request there is no VList
// to scroll, so pagination would never advance β€” fetch the next page until
// something renders or the stream ends.
const allLoadedSuppressed = visibleCount === 0 && notifications.length > 0;
useEffect(() => {
- if (allLoadedSuppressed && hasMore && !isValidating && !error) {
- setSize((prev) => prev + 1);
- }
- }, [allLoadedSuppressed, error, hasMore, isValidating, setSize]);
+ if (allLoadedSuppressed && hasMore && !isLoadingMore && !loadMoreError) loadMore();
+ }, [allLoadedSuppressed, hasMore, isLoadingMore, loadMore, loadMoreError]);
- if (isLoading) {
+ // A restored snapshot can be empty or stale: "nothing here" is only said
+ // once the server answered (for the stream, and for the live transfers
+ // that would render above it).
+ const isEmptyConfirmed =
+ isFeedConfirmed &&
+ (!workspaceId || !showTransfers || isTransfersConfirmed || !!transfersError);
+
+ if (!loadedNotifications && !headError) {
return (
<Flexbox gap={1} paddingBlock={1} paddingInline={4}>
<SkeletonList rows={5} />
@@ -165,14 +170,9 @@ const Content = memo<ContentProps>(
);
}
- if (error && notifications.length === 0) {
+ if (headError) {
return (
- <AsyncError
- error={error}
- retrying={isValidating}
- variant="page"
- onRetry={() => void mutate()}
- />
+ <AsyncError error={headError} retrying={isHeadValidating} variant="page" onRetry={retry} />
);
}
@@ -192,6 +192,25 @@ const Content = memo<ContentProps>(
: [];
if (visibleNotifications.length === 0 && transferItems.length === 0) {
+ // A failed read β€” of a restored snapshot, or a refresh after a settled
+ // empty answer β€” shows with its Retry rather than as "nothing here".
+ if (error) {
+ return (
+ <AsyncError
+ error={error}
+ retrying={isHeadValidating || isLoadingMore}
+ variant="page"
+ onRetry={retry}
+ />
+ );
+ }
+ if (!isEmptyConfirmed) {
+ return (
+ <Flexbox gap={1} paddingBlock={1} paddingInline={4}>
+ <SkeletonList rows={5} />
+ </Flexbox>
+ );
+ }
return (
<Flexbox height="100%">
<Flexbox align="center" gap={12} justify="center" paddingBlock={48}>
@@ -213,6 +232,15 @@ const Content = memo<ContentProps>(
return (
<Flexbox height="100%">
<VList ref={virtuaRef} style={{ flex: 1 }} onScroll={handleScroll}>
+ {transferItems.length > 0 && transfersError ? (
+ // The cards above stay; their actions wait for a confirmed list.
+ <AsyncError
+ error={transfersError}
+ retrying={isTransfersValidating}
+ variant="inline"
+ onRetry={() => void retryTransfers()}
+ />
+ ) : null}
{transferItems}
{visibleNotifications.map((item) => (
<Flexbox className={stylex.props(styles.item).className} key={item.id}>
@@ -232,12 +260,7 @@ const Content = memo<ContentProps>(
</Flexbox>
))}
{error ? (
- <AsyncError
- error={error}
- retrying={isValidating}
- variant="inline"
- onRetry={() => void mutate()}
- />
+ <AsyncError error={error} retrying={isValidating} variant="inline" onRetry={retry} />
) : isValidating ? (
<Flexbox padding="4px 8px">
<SkeletonList rows={2} />
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/index.tsx b/src/features/HomeSidebar/Header/components/InboxModal/index.tsx
index a9f07eee2de..f1be9084a87 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/index.tsx
+++ b/src/features/HomeSidebar/Header/components/InboxModal/index.tsx
@@ -31,7 +31,7 @@ import {
SparklesIcon,
TagIcon,
} from 'lucide-react';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
@@ -39,15 +39,14 @@ import AsyncError from '@/components/AsyncError';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import { PENDING_TRANSFERS_SWR_KEY } from '@/features/ResourceTransferRequest';
import dynamic from '@/libs/next/dynamic';
-import { mutate, useClientDataSWR } from '@/libs/swr';
+import { mutate } from '@/libs/swr';
import { inboxKeys } from '@/libs/swr/keys';
-import { notificationService } from '@/services/notification';
-import type { PendingTransferRequest } from '@/services/resourceTransferRequest';
-import { resourceTransferRequestService } from '@/services/resourceTransferRequest';
+import { useHomeStore } from '@/store/home';
+import { homeNotificationSelectors } from '@/store/home/selectors';
+import type { InboxNavigationCount } from '@/store/home/slices/notification/projection';
-import type { NotificationListHandle } from './useNotificationList';
+import { useNavigationCounts } from './useNavigationCounts';
const Content = dynamic(() => import('./Content'), {
loading: () => (
@@ -91,12 +90,7 @@ const styles = stylex.create({
},
});
-interface CategoryCount {
- category: string;
- readCount: number;
- totalCount: number;
- unreadCount: number;
-}
+type CategoryCount = InboxNavigationCount;
type ReadStatus = 'all' | 'read' | 'unread';
@@ -135,32 +129,23 @@ const InboxModalContent = memo(() => {
const [navigationFilter, setNavigationFilter] = useState(ALL_FILTER);
const [readStatus, setReadStatus] = useState<ReadStatus>('unread');
const [bulkAction, setBulkAction] = useState<'archive' | 'read'>();
- const listHandleRef = useRef<NotificationListHandle>(null);
- const registerListHandle = useCallback((handle: NotificationListHandle) => {
- listHandleRef.current = handle;
- }, []);
// `undefined` = the combined "all" view (no read-state filter).
const isRead = readStatus === 'all' ? undefined : readStatus === 'read';
const {
- data: navigationCounts,
+ counts: navigationCounts,
error: navigationCountsError,
+ isConfirmed: isNavigationCountsConfirmed,
isLoading: isNavigationCountsLoading,
isValidating: isNavigationCountsValidating,
- mutate: refreshNavigationCounts,
- } = useClientDataSWR<CategoryCount[]>(
- inboxKeys.navigationCounts(workspaceId),
- () => notificationService.getNavigationCounts(),
- { revalidateOnFocus: false },
- );
+ retry: refreshNavigationCounts,
+ } = useNavigationCounts();
- // Same key Content uses, so this reads the shared cache entry. The server
+ // The same replica Content reads (one request serves both). The server
// folds one totalCount unit per live card into `pending`, and archive-all
// cannot touch live cards β€” subtracting them yields the archivable rows.
- const { data: liveTransfers } = useClientDataSWR<PendingTransferRequest[]>(
- workspaceId ? [PENDING_TRANSFERS_SWR_KEY, workspaceId] : null,
- () => resourceTransferRequestService.listMine(),
- );
+ useHomeStore((s) => s.useFetchPendingTransferRequests)(!!workspaceId);
+ const liveTransfers = useHomeStore(homeNotificationSelectors.pendingTransferRequests);
const liveTransferCount = liveTransfers?.length ?? 0;
const categoryCounts = navigationCounts ?? [];
@@ -191,34 +176,29 @@ const InboxModalContent = memo(() => {
const category = navigationFilter === ALL_FILTER ? undefined : navigationFilter;
useEffect(() => {
+ // Only a server answer may drop a category: a restored snapshot can be stale.
if (
category &&
- !isNavigationCountsLoading &&
- !navigationCountsError &&
+ isNavigationCountsConfirmed &&
!visibleCategorySignature.split('\0').includes(category)
) {
setNavigationFilter(ALL_FILTER);
}
- }, [category, isNavigationCountsLoading, navigationCountsError, visibleCategorySignature]);
+ }, [category, isNavigationCountsConfirmed, visibleCategorySignature]);
const refreshInbox = useCallback(() => {
- // The notification list lives in a useSWRInfinite hook whose `$inf$` cache
- // key is skipped by SWR's filter-form mutate, so refresh it through the
- // bound handle Content registers instead. This is also the rollback path
- // for optimistic updates: on failure a revalidation restores server state.
- listHandleRef.current?.refresh();
+ // Re-reads every mounted inbox view and the counts; a rejected write has
+ // already rolled its optimistic change back, so this only reconciles.
+ void useHomeStore.getState().refreshInboxNotifications();
void mutate(inboxKeys.unreadCount(workspaceId));
- void mutate(inboxKeys.navigationCounts(workspaceId));
}, [workspaceId]);
const handleMarkAsRead = useCallback(
async (id: string) => {
- // A row read in the unread view leaves the list; in the All view it
- // STAYS (as combined history), so removing it there would drop it from
- // the cache until a later refresh β€” let the revalidation flip its state.
- if (readStatus !== 'all') listHandleRef.current?.optimisticRemove(id);
+ // The row flips to read: the unread view drops it, the All view keeps
+ // it (as combined history) in its read state.
try {
- await notificationService.markAsRead([id]);
+ await useHomeStore.getState().markInboxNotificationRead(id, { category, isRead });
refreshInbox();
} catch (error) {
console.error('Failed to mark notification as read:', error);
@@ -226,14 +206,13 @@ const InboxModalContent = memo(() => {
refreshInbox();
}
},
- [readStatus, refreshInbox, t],
+ [category, isRead, refreshInbox, t],
);
const handleArchive = useCallback(
async (id: string) => {
- listHandleRef.current?.optimisticRemove(id);
try {
- await notificationService.archive(id);
+ await useHomeStore.getState().archiveInboxNotification(id, { category, isRead });
refreshInbox();
} catch (error) {
console.error('Failed to archive notification:', error);
@@ -241,25 +220,16 @@ const InboxModalContent = memo(() => {
refreshInbox();
}
},
- [refreshInbox, t],
+ [category, isRead, refreshInbox, t],
);
const handleMarkAllAsRead = useCallback(async () => {
setBulkAction('read');
- // Rows only leave the unread view when read; in the all view they stay
- // (as read rows), so there the post-action refresh updates them in place.
- if (readStatus === 'unread') listHandleRef.current?.optimisticClear();
- // Pending is action-driven, not read-driven: its badge counts live
- // requests that mark-all-as-read cannot (and must not) resolve. Zeroing
- // it optimistically would flash the count away only to bounce back on the
- // refresh β€” reading as a broken button β€” so it stays untouched.
- void refreshNavigationCounts(
- (counts) =>
- counts?.map((item) => (item.category === 'pending' ? item : { ...item, unreadCount: 0 })),
- { revalidate: false },
- );
+ // Rows leave the unread view and stay (as read rows) in the all view.
+ // Pending's badge is left alone: it counts live requests that
+ // mark-all-as-read cannot (and must not) resolve.
try {
- await notificationService.markAllAsRead();
+ await useHomeStore.getState().markAllInboxNotificationsRead({ category, isRead });
refreshInbox();
} catch (error) {
console.error('Failed to mark all notifications as read:', error);
@@ -268,13 +238,12 @@ const InboxModalContent = memo(() => {
} finally {
setBulkAction(undefined);
}
- }, [readStatus, refreshInbox, refreshNavigationCounts, t]);
+ }, [category, isRead, refreshInbox, t]);
const handleArchiveAll = useCallback(async () => {
setBulkAction('archive');
- listHandleRef.current?.optimisticClear();
try {
- await notificationService.archiveAll();
+ await useHomeStore.getState().archiveAllInboxNotifications({ category, isRead });
refreshInbox();
} catch (error) {
console.error('Failed to archive all notifications:', error);
@@ -283,7 +252,7 @@ const InboxModalContent = memo(() => {
} finally {
setBulkAction(undefined);
}
- }, [refreshInbox, t]);
+ }, [category, isRead, refreshInbox, t]);
const countForStatus = (item: CategoryCount) => {
if (readStatus === 'all') return item.totalCount;
@@ -409,7 +378,7 @@ const InboxModalContent = memo(() => {
key={item.category}
title={categoryLabel(item.category)}
extra={
- !navigationCountsError && count > 0 ? (
+ count > 0 ? (
<Text style={{ marginInlineEnd: 6 }} type="secondary">
{count}
</Text>
@@ -428,7 +397,6 @@ const InboxModalContent = memo(() => {
<Content
category={category}
isRead={isRead}
- registerHandle={registerListHandle}
onArchive={handleArchive}
onMarkAsRead={handleMarkAsRead}
onRefreshInbox={refreshInbox}
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/useNavigationCounts.test.ts b/src/features/HomeSidebar/Header/components/InboxModal/useNavigationCounts.test.ts
new file mode 100644
index 00000000000..50ec2fe64e7
--- /dev/null
+++ b/src/features/HomeSidebar/Header/components/InboxModal/useNavigationCounts.test.ts
@@ -0,0 +1,76 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { notificationService } from '@/services/notification';
+import { useHomeStore } from '@/store/home';
+import { initialHomeNotificationState } from '@/store/home/slices/notification/initialState';
+import {
+ INBOX_NAVIGATION_COUNTS_KEY,
+ inboxNavigationCountsResource,
+} from '@/store/home/slices/notification/projection';
+
+import { useNavigationCounts } from './useNavigationCounts';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const counts = [{ category: 'agent', readCount: 1, totalCount: 3, unreadCount: 2 }];
+
+let scope = '';
+
+beforeEach(() => {
+ scope = `counts-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useHomeStore.setState({ ...initialHomeNotificationState }));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('useNavigationCounts', () => {
+ it('keeps cached counts and reports a failed refresh for Retry and the action guards', async () => {
+ await inboxNavigationCountsResource.storage!.set(
+ { queryKey: INBOX_NAVIGATION_COUNTS_KEY, scope },
+ { data: counts, updatedAt: 1 },
+ );
+ const getCounts = vi
+ .spyOn(notificationService, 'getNavigationCounts')
+ .mockRejectedValueOnce(new Error('offline'));
+
+ const { result } = renderHook(() => useNavigationCounts(), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.counts?.[0].unreadCount).toBe(2);
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.isConfirmed).toBe(false);
+
+ getCounts.mockResolvedValue(counts);
+ await act(() => result.current.retry());
+
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ expect(result.current.error).toBeFalsy();
+ });
+});
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/useNavigationCounts.ts b/src/features/HomeSidebar/Header/components/InboxModal/useNavigationCounts.ts
new file mode 100644
index 00000000000..c1de3502ac2
--- /dev/null
+++ b/src/features/HomeSidebar/Header/components/InboxModal/useNavigationCounts.ts
@@ -0,0 +1,28 @@
+import { useHomeStore } from '@/store/home';
+import { homeNotificationSelectors } from '@/store/home/selectors';
+
+/**
+ * The inbox sidebar counts, from the `inboxNavigationCounts` replica: a
+ * reopened modal (even after a reload) paints the last counts at once while
+ * the server confirms them. The latest fetch error is always reported β€” with
+ * cached counts on screen it still drives the inline Retry and keeps the bulk
+ * actions locked, since the counts may no longer be current.
+ */
+export const useNavigationCounts = () => {
+ const { error, isValidating, revalidate } = useHomeStore(
+ (s) => s.useFetchInboxNavigationCounts,
+ )();
+ const counts = useHomeStore(homeNotificationSelectors.navigationCounts);
+ const isConfirmed = useHomeStore(homeNotificationSelectors.isNavigationCountsConfirmed);
+
+ return {
+ /** `undefined` until hydrated or fetched. */
+ counts,
+ error,
+ /** Only a server answer may drop a category: a restored snapshot can be stale. */
+ isConfirmed,
+ isLoading: !counts && !error,
+ isValidating,
+ retry: revalidate,
+ };
+};
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.test.ts b/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.test.ts
index c7da66b65ba..998803bd400 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.test.ts
+++ b/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.test.ts
@@ -1,104 +1,146 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import { act, createElement, type ReactNode } from 'react';
-import { SWRConfig } from 'swr';
-import { describe, expect, it, vi } from 'vitest';
+/**
+ * @vitest-environment happy-dom
+ *
+ * Reopening the inbox after a reload paints the last notifications from the
+ * local replica while the server is still answering β€” no skeleton.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { notificationService } from '@/services/notification';
-import type { NotificationListHandle } from './useNotificationList';
import { useNotificationList } from './useNotificationList';
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => null,
useActiveWorkspaceId: () => null,
}));
-const listMock = vi.fn();
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
-vi.mock('@/services/notification', () => ({
- notificationService: {
- list: (...args: unknown[]) => listMock(...args),
- },
-}));
+let scope = '';
+
+const row = (id: string, isRead: boolean, title = id) => ({
+ category: 'agent',
+ createdAt: new Date(0),
+ id,
+ isRead,
+ title,
+ type: 'agent',
+});
-const wrapper = ({ children }: { children: ReactNode }) =>
- createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
-
-const setup = async (initialItems: { content: string; id: string }[]) => {
- let items = initialItems;
- listMock.mockImplementation(async () => items);
- let handle: NotificationListHandle | undefined;
-
- const { result } = renderHook(
- () =>
- useNotificationList({
- isRead: false,
- registerHandle: (h) => {
- handle = h;
- },
- }),
- { wrapper },
+/**
+ * Written in the replica's row layout (`replica:<name>:v<version>`, entry
+ * `<category>:<read state>`), so the test needs nothing of the replica module:
+ * before the migration the stream ignored the local copy and showed nothing
+ * until the request returned.
+ */
+const seedUnreadView = (items: ReturnType<typeof row>[]) =>
+ new AppIndexedDBStorage({ namespace: 'replica:inboxNotifications:v1' }).set(
+ { queryKey: '*:unread', scope },
+ {
+ data: { currentPage: 0, hasMore: false, items, nextCursor: null, pageSize: 20 },
+ updatedAt: 1,
+ },
);
- await waitFor(() => expect(result.current.data?.flat()).toEqual(initialItems));
- expect(handle).toBeDefined();
+beforeEach(() => {
+ scope = `inbox-list-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+});
- return {
- handle: handle!,
- result,
- setItems: (next: typeof items) => {
- items = next;
- },
- };
-};
+afterEach(() => {
+ vi.restoreAllMocks();
+});
describe('useNotificationList', () => {
- it('registers a refresh that revalidates the infinite list', async () => {
- // Regression: modal bulk actions (mark all as read) used a key-filter
- // mutate, which SWR skips for `$inf$` infinite keys β€” the unread list
- // never refreshed. The hook must expose its own bound revalidate instead.
- const { handle, result, setItems } = await setup([{ content: 'first', id: '1' }]);
-
- setItems([]);
- await act(async () => {
- handle.refresh();
- });
-
- await waitFor(() => expect(result.current.data?.flat()).toEqual([]));
+ it('paints the persisted unread notifications before the network answers', async () => {
+ await seedUnreadView([row('n1', false, 'Cached notification')]);
+ let answer: (rows: unknown[]) => void = () => {};
+ vi.spyOn(notificationService, 'list').mockImplementation(
+ () => new Promise((resolve) => (answer = resolve as typeof answer)) as never,
+ );
+
+ const { result } = renderHook(() => useNotificationList({ isRead: false }), { wrapper });
+
+ await waitFor(() =>
+ expect(result.current.notifications?.map((item) => item.id)).toEqual(['n1']),
+ );
+ expect(result.current.isConfirmed).toBe(false);
+
+ act(() => answer([row('n2', false)]));
+ await waitFor(() =>
+ expect(result.current.notifications?.map((item) => item.id)).toEqual(['n2']),
+ );
+ expect(result.current.isConfirmed).toBe(true);
});
- it('optimistically removes a single item without refetching', async () => {
- const first = { content: 'first', id: '1' };
- const second = { content: 'second', id: '2' };
- const { handle, result } = await setup([first, second]);
- const callsBefore = listMock.mock.calls.length;
+ it('keeps a row read from another view off the unread view', async () => {
+ await seedUnreadView([row('read-elsewhere', true), row('n1', false)]);
+ vi.spyOn(notificationService, 'list').mockImplementation(() => new Promise(() => {}));
- await act(async () => {
- handle.optimisticRemove('1');
- });
+ const { result } = renderHook(() => useNotificationList({ isRead: false }), { wrapper });
- expect(result.current.data?.flat()).toEqual([second]);
- expect(listMock.mock.calls.length).toBe(callsBefore);
+ await waitFor(() =>
+ expect(result.current.notifications?.map((item) => item.id)).toEqual(['n1']),
+ );
});
- it('optimistically clears the list without refetching', async () => {
- const { handle, result } = await setup([{ content: 'first', id: '1' }]);
- const callsBefore = listMock.mock.calls.length;
+ it('reports a failed refresh of an unconfirmed restored view, keeping its rows', async () => {
+ await seedUnreadView([]);
+ vi.spyOn(notificationService, 'list').mockRejectedValue(new Error('offline'));
- await act(async () => {
- handle.optimisticClear();
- });
+ const { result } = renderHook(() => useNotificationList({ isRead: false }), { wrapper });
- expect(result.current.data?.flat() ?? []).toEqual([]);
- expect(listMock.mock.calls.length).toBe(callsBefore);
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.isConfirmed).toBe(false);
+ expect(result.current.notifications).toEqual([]);
+ // Rows were restored, so this is not a first-load failure with nothing to show.
+ expect(result.current.headError).toBeUndefined();
});
- it('omits the isRead filter for the combined "all" view', async () => {
- // Regression: the hook always forwarded a boolean isRead, so the combined
- // chronological history (no read-state filter) was impossible to request.
- listMock.mockClear();
- listMock.mockImplementation(async () => []);
+ it('keeps the restored rows and surfaces a failed refresh for the inline retry', async () => {
+ await seedUnreadView([row('n1', false, 'Cached notification')]);
+ vi.spyOn(notificationService, 'list').mockRejectedValue(new Error('offline'));
+
+ const { result } = renderHook(() => useNotificationList({ isRead: false }), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.notifications?.map((item) => item.id)).toEqual(['n1']);
+ expect(result.current.headError).toBeUndefined();
+ });
+
+ it('surfaces a failed refresh after a confirmed empty answer', async () => {
+ const list = vi.spyOn(notificationService, 'list').mockResolvedValueOnce([]);
+
+ const { result } = renderHook(() => useNotificationList({ isRead: false }), { wrapper });
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ expect(result.current.notifications).toEqual([]);
- renderHook(() => useNotificationList({ registerHandle: () => {} }), { wrapper });
+ list.mockRejectedValue(new Error('offline'));
+ act(() => result.current.retry());
- await waitFor(() => expect(listMock).toHaveBeenCalled());
- expect((listMock.mock.calls[0][0] as { isRead?: boolean }).isRead).toBeUndefined();
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.notifications).toEqual([]);
});
});
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.ts b/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.ts
index b6007b36dc9..04770799007 100644
--- a/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.ts
+++ b/src/features/HomeSidebar/Header/components/InboxModal/useNotificationList.ts
@@ -1,73 +1,69 @@
-import { useCallback, useEffect } from 'react';
-import useSWRInfinite from 'swr/infinite';
+import { useCallback, useMemo } from 'react';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import { inboxKeys } from '@/libs/swr/keys';
-import { notificationService } from '@/services/notification';
-
-export const PAGE_SIZE = 20;
-
-export interface NotificationListHandle {
- /** Optimistically empty the list (mark all read / archive all). */
- optimisticClear: () => void;
- /** Optimistically drop one item (mark as read / archive). */
- optimisticRemove: (id: string) => void;
- refresh: () => void;
-}
+import { useHomeStore } from '@/store/home';
+import { homeNotificationSelectors } from '@/store/home/selectors';
interface UseNotificationListOptions {
category?: string;
/** Filter by read state; omit for the combined "all" view. */
isRead?: boolean;
- /**
- * Registers the list's bound mutate operations with the caller. The global
- * filter-form `mutate` cannot reach this list: SWR's key-filter mutate
- * explicitly skips `$inf$` (useSWRInfinite) cache keys, so actions in the
- * modal must go through the hook's own `mutate`. The optimistic operations
- * update the cache without revalidating; callers roll back a failed action
- * by calling `refresh` (server state is the source of truth).
- */
- registerHandle: (handle: NotificationListHandle) => void;
}
-export const useNotificationList = ({
- category,
- isRead,
- registerHandle,
-}: UseNotificationListOptions) => {
- const workspaceId = useActiveWorkspaceId();
+/**
+ * One inbox view of the notification stream, backed by the `inboxNotifications`
+ * replica: it paints its last head page at once (even after a reload) while the
+ * server confirms it in the background. Writes go through the home store's
+ * notification actions, which update the replica and its storage.
+ */
+export const useNotificationList = ({ category, isRead }: UseNotificationListOptions) => {
+ const view = useMemo(() => ({ category, isRead }), [category, isRead]);
+ const {
+ error: headError,
+ isValidating: isHeadValidating,
+ revalidate,
+ } = useHomeStore((s) => s.useFetchInboxNotifications)(view);
+ const feed = useHomeStore(homeNotificationSelectors.notificationFeed(view));
+ const isConfirmed = useHomeStore(homeNotificationSelectors.isNotificationFeedConfirmed(view));
- const getKey = useCallback(
- (_pageIndex: number, previousPageData: any[] | null) => {
- if (previousPageData && previousPageData.length < PAGE_SIZE) return null;
-
- const lastItem = previousPageData?.at(-1);
- return inboxKeys.notifications(workspaceId, lastItem?.id, category, isRead);
- },
- [category, isRead, workspaceId],
+ const loadMore = useCallback(
+ () => void useHomeStore.getState().loadMoreInboxNotifications(view),
+ [view],
);
- const swr = useSWRInfinite(getKey, async ([, , cursor, filterCategory, filterIsRead]) => {
- return notificationService.list({
- category: filterCategory as string | undefined,
- cursor: cursor as string | undefined,
- isRead: filterIsRead as boolean | undefined,
- limit: PAGE_SIZE,
- });
- });
+ // A row read from another view stays in this view's copy until the next
+ // refresh; the read-state filter keeps it on the side it now belongs to.
+ const notifications = useMemo(
+ () => feed?.items.filter((item) => isRead === undefined || item.isRead === isRead) ?? undefined,
+ [feed?.items, isRead],
+ );
+ const loadMoreError = feed?.loadMoreError;
- const { mutate } = swr;
- useEffect(() => {
- registerHandle({
- optimisticClear: () => void mutate([], { revalidate: false }),
- optimisticRemove: (id) =>
- void mutate(
- (pages?: any[][]) => pages?.map((page) => page.filter((item) => item.id !== id)),
- { revalidate: false },
- ),
- refresh: () => void mutate(),
- });
- }, [mutate, registerHandle]);
+ const retry = useCallback(() => {
+ if (feed && loadMoreError) loadMore();
+ else void revalidate();
+ }, [feed, loadMore, loadMoreError, revalidate]);
- return swr;
+ return {
+ /**
+ * Any failure to surface: with rows on screen it renders as the inline
+ * Retry row below them (a failed "load more" or a failed refresh), with
+ * none it is the first-load failure.
+ */
+ error: feed ? (loadMoreError ?? headError) : headError,
+ hasMore: !!feed?.hasMore,
+ /** A failed first load with nothing persisted to fall back on. */
+ headError: feed ? undefined : headError,
+ /**
+ * Whether the server answered this view in this session. A restored
+ * snapshot may be empty or stale, so an empty list is "loading" until then.
+ */
+ isConfirmed,
+ isHeadValidating,
+ isLoadingMore: !!feed?.isLoadingMore,
+ /** Rows on screen; `undefined` until hydrated or fetched. */
+ notifications,
+ loadMore,
+ loadMoreError,
+ retry,
+ };
};
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/usePendingTransfers.test.ts b/src/features/HomeSidebar/Header/components/InboxModal/usePendingTransfers.test.ts
new file mode 100644
index 00000000000..7a9a6ade6e5
--- /dev/null
+++ b/src/features/HomeSidebar/Header/components/InboxModal/usePendingTransfers.test.ts
@@ -0,0 +1,79 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import {
+ type PendingTransferRequest,
+ resourceTransferRequestService,
+} from '@/services/resourceTransferRequest';
+import { useHomeStore } from '@/store/home';
+import { initialHomeNotificationState } from '@/store/home/slices/notification/initialState';
+import {
+ PENDING_TRANSFER_REQUESTS_KEY,
+ pendingTransferRequestsResource,
+} from '@/store/home/slices/notification/projection';
+
+import { usePendingTransfers } from './usePendingTransfers';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false } },
+ createElement(MutateBridge),
+ children,
+ );
+
+const transfer = (id: string) =>
+ ({ createdAt: new Date(0), id, recipientId: 'me' }) as PendingTransferRequest;
+
+let scope = '';
+
+beforeEach(() => {
+ scope = `transfers-${randomUUID()}:ws-1`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useHomeStore.setState({ ...initialHomeNotificationState }));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('usePendingTransfers', () => {
+ it('keeps restored cards, surfaces a failed read and confirms them on retry', async () => {
+ await pendingTransferRequestsResource.storage!.set(
+ { queryKey: PENDING_TRANSFER_REQUESTS_KEY, scope },
+ { data: [transfer('t1')], updatedAt: 1 },
+ );
+ const listMine = vi
+ .spyOn(resourceTransferRequestService, 'listMine')
+ .mockRejectedValueOnce(new Error('offline'));
+
+ const { result } = renderHook(() => usePendingTransfers(true), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.requests?.map((r) => r.id)).toEqual(['t1']);
+ expect(result.current.isConfirmed).toBe(false);
+
+ listMine.mockResolvedValue([transfer('t1')]);
+ await act(() => result.current.retry());
+
+ await waitFor(() => expect(result.current.isConfirmed).toBe(true));
+ expect(result.current.error).toBeFalsy();
+ });
+});
diff --git a/src/features/HomeSidebar/Header/components/InboxModal/usePendingTransfers.ts b/src/features/HomeSidebar/Header/components/InboxModal/usePendingTransfers.ts
new file mode 100644
index 00000000000..155ca0c5949
--- /dev/null
+++ b/src/features/HomeSidebar/Header/components/InboxModal/usePendingTransfers.ts
@@ -0,0 +1,25 @@
+import { useHomeStore } from '@/store/home';
+import { homeNotificationSelectors } from '@/store/home/selectors';
+
+/**
+ * The caller's live transfer requests (workspace only), from the
+ * `pendingTransferRequests` replica. Restored cards render at once, but their
+ * actions stay locked until this session's read confirms them β€” so a failed
+ * read must stay visible with a Retry, or the locked buttons have no way out.
+ */
+export const usePendingTransfers = (enabled: boolean) => {
+ const { error, isValidating, revalidate } = useHomeStore(
+ (s) => s.useFetchPendingTransferRequests,
+ )(enabled);
+ const requests = useHomeStore(homeNotificationSelectors.pendingTransferRequests);
+ const isConfirmed = useHomeStore(homeNotificationSelectors.isPendingTransferRequestsConfirmed);
+
+ return {
+ error,
+ isConfirmed,
+ isValidating,
+ /** Rows on screen; `undefined` until hydrated or fetched. */
+ requests,
+ retry: revalidate,
+ };
+};
diff --git a/src/features/ResourceTransferRequest/TransferRequestItem.tsx b/src/features/ResourceTransferRequest/TransferRequestItem.tsx
index f5c9c31cac5..f8a764fa6a4 100644
--- a/src/features/ResourceTransferRequest/TransferRequestItem.tsx
+++ b/src/features/ResourceTransferRequest/TransferRequestItem.tsx
@@ -2,21 +2,22 @@
import { AGENT_CHAT_URL, GROUP_CHAT_URL } from '@lobechat/const';
import { Avatar, Block, Button, Flexbox, Tag, Text, toast } from '@lobehub/ui';
-import { memo, useState } from 'react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { formatNotificationRelativeTime } from '@/features/HomeSidebar/Header/components/InboxModal/formatNotificationRelativeTime';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useClientDataSWR } from '@/libs/swr';
import type {
PendingTransferRequest,
TransferRequestParty,
TransferRequestResourceType,
} from '@/services/resourceTransferRequest';
import { resourceTransferRequestService } from '@/services/resourceTransferRequest';
+import { useHomeStore } from '@/store/home';
+import { homeNotificationSelectors } from '@/store/home/selectors';
import { TransferErrorCode } from '@/types/transferError';
-import { isTransferManifestActionable } from './manifestState';
+import { isTransferManifestAcceptable } from './manifestState';
import { refreshCachesAfterOwnershipChange } from './refreshAfterOwnershipChange';
import TransferManifestList from './TransferManifestList';
@@ -111,22 +112,39 @@ const TransferRequestItem = memo<TransferRequestItemProps>(
// Accept is gated until the manifest loads successfully without a blocker:
// a failed/unknown impact summary must never turn into permission to act.
+ // A restored manifest paints the summary at once, but only this session's
+ // server answer may unlock Accept β€” the resource may have changed since.
+ const manifestParams = useMemo(
+ () => ({
+ recipientId: request.recipientId,
+ requestId: request.id,
+ resourceId: request.resourceId,
+ resourceType: request.resourceType as TransferRequestResourceType,
+ }),
+ [request.id, request.recipientId, request.resourceId, request.resourceType],
+ );
const {
- data: manifest,
- error: manifestError,
+ error: rawManifestError,
isValidating: isManifestValidating,
- mutate: mutateManifest,
- } = useClientDataSWR(
- isRecipient ? `transfer-manifest-${request.id}` : null,
- () =>
- resourceTransferRequestService.getManifest({
- recipientId: request.recipientId,
- resourceId: request.resourceId,
- resourceType: request.resourceType as TransferRequestResourceType,
- }),
- { revalidateOnFocus: false },
+ revalidate: revalidateManifest,
+ } = useHomeStore((s) => s.useFetchTransferManifest)(manifestParams, isRecipient);
+ const manifest = useHomeStore(homeNotificationSelectors.transferManifest(request.id));
+ const isManifestConfirmed = useHomeStore(
+ homeNotificationSelectors.isTransferManifestConfirmed(request.id),
);
- const manifestReady = isTransferManifestActionable(manifest, manifestError);
+ // The latest fetch error always shows (with Retry) and blocks Accept, even
+ // when an earlier session answer is still on screen.
+ const manifestError = rawManifestError;
+ // A restored request may have been resolved elsewhere since: its actions
+ // wait for this session's read of the live list.
+ const isRequestConfirmed = useHomeStore(
+ homeNotificationSelectors.isPendingTransferRequestsConfirmed,
+ );
+ const manifestReady = isTransferManifestAcceptable({
+ confirmed: isManifestConfirmed,
+ error: manifestError,
+ manifest,
+ });
const fallback = t('transferRequest.someone');
const counterpartLabel = partyLabel(
@@ -243,7 +261,7 @@ const TransferRequestItem = memo<TransferRequestItemProps>(
retrying={isManifestValidating}
style={{ marginInlineStart: 44 }}
onRetry={() =>
- void mutateManifest().catch((error) =>
+ void revalidateManifest().catch((error) =>
console.error('[TransferRequestItem] manifest retry failed', error),
)
}
@@ -257,7 +275,7 @@ const TransferRequestItem = memo<TransferRequestItemProps>(
{isRecipient ? (
<>
<Button
- disabled={acting}
+ disabled={acting || !isRequestConfirmed}
size="small"
onClick={() =>
run(() => resourceTransferRequestService.decline(request.id), {
@@ -269,7 +287,7 @@ const TransferRequestItem = memo<TransferRequestItemProps>(
{t('transferRequest.decline')}
</Button>
<Button
- disabled={acting || !manifestReady}
+ disabled={acting || !isRequestConfirmed || !manifestReady}
loading={acting}
size="small"
type="primary"
@@ -291,7 +309,7 @@ const TransferRequestItem = memo<TransferRequestItemProps>(
</>
) : (
<Button
- disabled={acting}
+ disabled={acting || !isRequestConfirmed}
loading={acting}
size="small"
onClick={() =>
diff --git a/src/features/ResourceTransferRequest/index.ts b/src/features/ResourceTransferRequest/index.ts
index 1514011c83e..f067ce49bc9 100644
--- a/src/features/ResourceTransferRequest/index.ts
+++ b/src/features/ResourceTransferRequest/index.ts
@@ -1,4 +1,3 @@
-export { PENDING_TRANSFERS_SWR_KEY } from './keys';
export { isTransferManifestActionable } from './manifestState';
export {
default as TransferManifestList,
diff --git a/src/features/ResourceTransferRequest/keys.ts b/src/features/ResourceTransferRequest/keys.ts
deleted file mode 100644
index 2d9e652937c..00000000000
--- a/src/features/ResourceTransferRequest/keys.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-/** SWR key prefix for the caller's live transfer requests (`listMine`). */
-export const PENDING_TRANSFERS_SWR_KEY = 'pending-transfer-requests';
diff --git a/src/features/ResourceTransferRequest/manifestState.test.ts b/src/features/ResourceTransferRequest/manifestState.test.ts
index a1393896c47..059d7ff1839 100644
--- a/src/features/ResourceTransferRequest/manifestState.test.ts
+++ b/src/features/ResourceTransferRequest/manifestState.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { TransferManifest } from '@/services/resourceTransferRequest';
-import { isTransferManifestActionable } from './manifestState';
+import { isTransferManifestAcceptable, isTransferManifestActionable } from './manifestState';
const manifest = {
botBindings: 0,
@@ -36,3 +36,24 @@ describe('isTransferManifestActionable', () => {
).toBe(false);
});
});
+
+describe('isTransferManifestAcceptable', () => {
+ it('waits for a server answer in this session before unlocking Accept', () => {
+ expect(isTransferManifestAcceptable({ confirmed: false, error: undefined, manifest })).toBe(
+ false,
+ );
+ expect(isTransferManifestAcceptable({ confirmed: true, error: undefined, manifest })).toBe(
+ true,
+ );
+ });
+
+ it('blocks Accept when a refresh fails after an earlier successful load', () => {
+ expect(
+ isTransferManifestAcceptable({
+ confirmed: true,
+ error: new Error('refresh failed'),
+ manifest,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/features/ResourceTransferRequest/manifestState.ts b/src/features/ResourceTransferRequest/manifestState.ts
index ae9137c2391..2c99609d621 100644
--- a/src/features/ResourceTransferRequest/manifestState.ts
+++ b/src/features/ResourceTransferRequest/manifestState.ts
@@ -8,3 +8,19 @@ export const isTransferManifestActionable = (
manifest: TransferManifest | undefined,
error: unknown,
): boolean => !!manifest && !error && !manifest.hiddenReferencedMember;
+
+/**
+ * Whether Accept may be pressed. A restored manifest only paints the summary:
+ * it must have been answered by the server in this session, and the LATEST
+ * fetch error still blocks β€” a failed refresh after an earlier success leaves
+ * the impact unknown again.
+ */
+export const isTransferManifestAcceptable = ({
+ confirmed,
+ error,
+ manifest,
+}: {
+ confirmed: boolean;
+ error: unknown;
+ manifest: TransferManifest | undefined;
+}): boolean => confirmed && isTransferManifestActionable(manifest, error);
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
index 2d2cb411a34..e82dee525d1 100644
--- a/src/libs/swr/keys.frozen.test.ts
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -86,8 +86,6 @@ const LEGACY_SWR_KEYS = [
'groupKeys.queryAgentsForCreate',
'imageKeys.generationStatus',
'imessageKeys.bridgeStatus',
- 'inboxKeys.navigationCounts',
- 'inboxKeys.notifications',
'inboxKeys.unreadCount',
'inboxKeys.unreadMentions',
'localFileKeys.claudeCodeMemory',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 148454defeb..d3916d6e791 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -692,21 +692,6 @@ export const verifyKeys = {
// ---- inbox / notifications ----------------------------------------------
export const inboxKeys = {
- navigationCounts: def('inbox:navigationCounts', (workspaceId: string | null) => [
- 'inbox:navigationCounts',
- workspaceId,
- ]),
- notifications: def(
- 'inbox:notifications',
- // Keyed by context: the server scopes the inbox to the active workspace
- // (null = personal), so cached pages must never be reused across contexts.
- (
- workspaceId: string | null,
- cursor: string | undefined,
- category: string | undefined,
- isRead: boolean | undefined,
- ) => ['inbox:notifications', workspaceId, cursor, category, isRead],
- ),
unreadCount: def('inbox:unreadCount', (workspaceId: string | null) => [
'inbox:unreadCount',
workspaceId,
diff --git a/src/store/home/initialState.ts b/src/store/home/initialState.ts
index 01dac89aca6..779200b89d8 100644
--- a/src/store/home/initialState.ts
+++ b/src/store/home/initialState.ts
@@ -8,6 +8,8 @@ import { type HomeInboxState } from './slices/inbox/initialState';
import { initialHomeInboxState } from './slices/inbox/initialState';
import { type LabelState } from './slices/label/initialState';
import { initialLabelState } from './slices/label/initialState';
+import { type HomeNotificationState } from './slices/notification/initialState';
+import { initialHomeNotificationState } from './slices/notification/initialState';
import { type RecentState } from './slices/recent/initialState';
import { initialRecentState } from './slices/recent/initialState';
import { type SidebarUIState } from './slices/sidebarUI/initialState';
@@ -20,6 +22,7 @@ export interface HomeStoreState
RecentState,
HomeInboxState,
HomeInputState,
+ HomeNotificationState,
LabelState,
SidebarUIState {}
@@ -29,6 +32,7 @@ export const initialState: HomeStoreState = {
...initialRecentState,
...initialHomeInboxState,
...initialHomeInputState,
+ ...initialHomeNotificationState,
...initialLabelState,
...initialSidebarUIState,
};
diff --git a/src/store/home/selectors.ts b/src/store/home/selectors.ts
index 1213af18370..71df571fda7 100644
--- a/src/store/home/selectors.ts
+++ b/src/store/home/selectors.ts
@@ -2,4 +2,5 @@ export * from './slices/agentList/selectors';
export * from './slices/favorite/selectors';
export * from './slices/inbox/selectors';
export * from './slices/label/selectors';
+export * from './slices/notification/selectors';
export * from './slices/recent/selectors';
diff --git a/src/store/home/slices/notification/action.test.ts b/src/store/home/slices/notification/action.test.ts
new file mode 100644
index 00000000000..e0aca9ec180
--- /dev/null
+++ b/src/store/home/slices/notification/action.test.ts
@@ -0,0 +1,407 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The header inbox modal reads four replicas: the notification stream (per
+ * view), its sidebar counts, the live transfer requests and their manifests.
+ * A reload paints the persisted copy before the network answers; writes land
+ * on the replica (and its storage) instead of relying on a best-effort refetch.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { notificationService } from '@/services/notification';
+import {
+ type PendingTransferRequest,
+ resourceTransferRequestService,
+ type TransferManifest,
+} from '@/services/resourceTransferRequest';
+import { useHomeStore } from '@/store/home';
+import { initialHomeNotificationState } from '@/store/home/slices/notification/initialState';
+import {
+ INBOX_NAVIGATION_COUNTS_KEY,
+ inboxNavigationCountsResource,
+ type InboxNotificationFeed,
+ type InboxNotificationItem,
+ inboxNotificationResource,
+ inboxNotificationsKey,
+ PENDING_TRANSFER_REQUESTS_KEY,
+ pendingTransferRequestsResource,
+ transferManifestResource,
+} from '@/store/home/slices/notification/projection';
+import { homeNotificationSelectors } from '@/store/home/slices/notification/selectors';
+
+const item = (id: string, isRead = false): InboxNotificationItem =>
+ ({ category: 'agent', createdAt: new Date(0), id, isRead, title: id }) as InboxNotificationItem;
+
+const feed = (items: InboxNotificationItem[]): InboxNotificationFeed => ({
+ currentPage: 0,
+ hasMore: false,
+ items,
+ nextCursor: null,
+ pageSize: 20,
+});
+
+const transfer = (id: string): PendingTransferRequest =>
+ ({
+ createdAt: new Date(0),
+ id,
+ recipientId: 'me',
+ resourceId: `r-${id}`,
+ }) as PendingTransferRequest;
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+let scope = '';
+const useScope = (next: string) => {
+ scope = next;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+};
+
+const never = <T>() => new Promise<T>(() => {});
+
+const UNREAD = { isRead: false };
+const ALL = {};
+
+const storedFeed = async (params: object) =>
+ (
+ await inboxNotificationResource.storage!.get({
+ queryKey: inboxNotificationsKey(params),
+ scope,
+ })
+ )?.data as InboxNotificationFeed | undefined;
+
+const seedFeed = (params: object, items: InboxNotificationItem[], at = scope) =>
+ inboxNotificationResource.storage!.set(
+ { queryKey: inboxNotificationsKey(params), scope: at },
+ { data: feed(items), updatedAt: 1 },
+ );
+
+const useFeed = (params: object) =>
+ renderHook(() => useHomeStore((s) => s.useFetchInboxNotifications)(params), { wrapper });
+
+/**
+ * Persist a view through the engine (so it is in the scope's row index), then
+ * drop it from memory: the row is what a view not opened this session holds.
+ */
+const persistUnloadedView = async (params: object, items: InboxNotificationItem[]) => {
+ const list = vi.spyOn(notificationService, 'list').mockResolvedValue(items);
+ const { unmount } = useFeed(params);
+ await waitFor(async () => expect((await storedFeed(params))?.items).toHaveLength(items.length));
+ unmount();
+ list.mockReset();
+ act(() => useHomeStore.setState({ ...initialHomeNotificationState }));
+};
+
+const viewIds = (params: object) =>
+ homeNotificationSelectors
+ .notificationFeed(params)(useHomeStore.getState())
+ ?.items.map((i) => i.id);
+
+beforeEach(() => {
+ useScope(`notification-user-${randomUUID()}:ws-1`);
+ act(() => useHomeStore.setState({ ...initialHomeNotificationState }));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ localStorage.clear();
+});
+
+describe('inbox notification stream replica', () => {
+ it('paints the persisted head page before the network answers, then takes the server page', async () => {
+ await seedFeed(UNREAD, [item('cached')]);
+ let answer: (rows: InboxNotificationItem[]) => void = () => {};
+ vi.spyOn(notificationService, 'list').mockImplementation(
+ () => new Promise((resolve) => (answer = resolve as typeof answer)),
+ );
+
+ const { result } = useFeed(UNREAD);
+
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['cached']));
+ expect(result.current.isValidating).toBe(true);
+ expect(
+ homeNotificationSelectors.isNotificationFeedConfirmed(UNREAD)(useHomeStore.getState()),
+ ).toBe(false);
+
+ act(() => answer([item('fresh')]));
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['fresh']));
+ expect(
+ homeNotificationSelectors.isNotificationFeedConfirmed(UNREAD)(useHomeStore.getState()),
+ ).toBe(true);
+ });
+
+ it('treats a restored empty snapshot as unconfirmed until the server answers', async () => {
+ await seedFeed(UNREAD, []);
+ vi.spyOn(notificationService, 'list').mockImplementation(never);
+
+ useFeed(UNREAD);
+
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual([]));
+ expect(
+ homeNotificationSelectors.isNotificationFeedConfirmed(UNREAD)(useHomeStore.getState()),
+ ).toBe(false);
+ });
+
+ it("never paints another identity's stream", async () => {
+ await seedFeed(UNREAD, [item('theirs')], 'previous-user:ws-1');
+ vi.spyOn(notificationService, 'list').mockResolvedValue([item('mine')]);
+
+ useFeed(UNREAD);
+
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['mine']));
+ });
+
+ it('keeps the last rows when a background refresh fails', async () => {
+ await seedFeed(UNREAD, [item('cached')]);
+ vi.spyOn(notificationService, 'list').mockRejectedValue(new Error('offline'));
+
+ const { result } = useFeed(UNREAD);
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(viewIds(UNREAD)).toEqual(['cached']);
+ });
+
+ it('pages with the id of the last row and stops on a short page', async () => {
+ const page = Array.from({ length: 20 }, (_, index) => item(`n${index}`));
+ const list = vi
+ .spyOn(notificationService, 'list')
+ .mockResolvedValueOnce(page)
+ .mockResolvedValueOnce([item('tail')]);
+ useFeed(UNREAD);
+ await waitFor(() => expect(viewIds(UNREAD)).toHaveLength(20));
+
+ await act(() => useHomeStore.getState().loadMoreInboxNotifications(UNREAD));
+
+ expect(list).toHaveBeenLastCalledWith(
+ expect.objectContaining({ cursor: 'n19', isRead: false, limit: 20 }),
+ );
+ expect(viewIds(UNREAD)).toHaveLength(21);
+ expect(
+ homeNotificationSelectors.notificationFeed(UNREAD)(useHomeStore.getState())?.hasMore,
+ ).toBe(false);
+ });
+
+ it('drops an archived row from every view and from storage, so a reload cannot restore it', async () => {
+ await persistUnloadedView(ALL, [item('a'), item('b')]);
+ vi.spyOn(notificationService, 'list').mockResolvedValue([item('a'), item('b')]);
+ vi.spyOn(notificationService, 'archive').mockResolvedValue(undefined as never);
+ useFeed(UNREAD);
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['a', 'b']));
+
+ await act(() => useHomeStore.getState().archiveInboxNotification('a', UNREAD));
+
+ expect(viewIds(UNREAD)).toEqual(['b']);
+ await waitFor(async () =>
+ expect((await storedFeed(UNREAD))?.items.map((i) => i.id)).toEqual(['b']),
+ );
+ // The all view was never opened in this session: its persisted copy is patched too.
+ await waitFor(async () =>
+ expect((await storedFeed(ALL))?.items.map((i) => i.id)).toEqual(['b']),
+ );
+ });
+
+ it('rolls an archive back when the server rejects it', async () => {
+ vi.spyOn(notificationService, 'list').mockResolvedValue([item('a')]);
+ vi.spyOn(notificationService, 'archive').mockRejectedValue(new Error('denied'));
+ useFeed(UNREAD);
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['a']));
+
+ await act(async () => {
+ await expect(useHomeStore.getState().archiveInboxNotification('a', UNREAD)).rejects.toThrow(
+ 'denied',
+ );
+ });
+
+ expect(viewIds(UNREAD)).toEqual(['a']);
+ });
+
+ it('persists a read row as read in the other views', async () => {
+ await persistUnloadedView(ALL, [item('a')]);
+ vi.spyOn(notificationService, 'list').mockResolvedValue([item('a')]);
+ vi.spyOn(notificationService, 'markAsRead').mockResolvedValue(undefined as never);
+ useFeed(UNREAD);
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['a']));
+
+ await act(() => useHomeStore.getState().markInboxNotificationRead('a', UNREAD));
+
+ expect(
+ homeNotificationSelectors.notificationFeed(UNREAD)(useHomeStore.getState())?.items[0].isRead,
+ ).toBe(true);
+ await waitFor(async () => expect((await storedFeed(ALL))?.items[0].isRead).toBe(true));
+ });
+
+ it('empties every persisted view after archive-all', async () => {
+ await persistUnloadedView(ALL, [item('a')]);
+ vi.spyOn(notificationService, 'list').mockResolvedValue([item('a'), item('b')]);
+ vi.spyOn(notificationService, 'archiveAll').mockResolvedValue(undefined as never);
+ useFeed(UNREAD);
+ await waitFor(() => expect(viewIds(UNREAD)).toEqual(['a', 'b']));
+
+ await act(() => useHomeStore.getState().archiveAllInboxNotifications(UNREAD));
+
+ expect(viewIds(UNREAD)).toEqual([]);
+ await waitFor(async () => expect((await storedFeed(UNREAD))?.items).toEqual([]));
+ await waitFor(async () => expect((await storedFeed(ALL))?.items).toEqual([]));
+ });
+});
+
+describe('inbox navigation counts replica', () => {
+ it('paints the persisted counts before the network answers', async () => {
+ await inboxNavigationCountsResource.storage!.set(
+ { queryKey: INBOX_NAVIGATION_COUNTS_KEY, scope },
+ {
+ data: [{ category: 'agent', readCount: 1, totalCount: 3, unreadCount: 2 }],
+ updatedAt: 1,
+ },
+ );
+ vi.spyOn(notificationService, 'getNavigationCounts').mockImplementation(never);
+
+ renderHook(() => useHomeStore((s) => s.useFetchInboxNavigationCounts)(), { wrapper });
+
+ await waitFor(() =>
+ expect(
+ homeNotificationSelectors.navigationCounts(useHomeStore.getState())?.[0].unreadCount,
+ ).toBe(2),
+ );
+ expect(homeNotificationSelectors.isNavigationCountsConfirmed(useHomeStore.getState())).toBe(
+ false,
+ );
+ });
+});
+
+describe('pending transfer requests replica', () => {
+ it('serves the modal header and the stream with one request', async () => {
+ const listMine = vi.spyOn(resourceTransferRequestService, 'listMine').mockResolvedValue([]);
+
+ renderHook(
+ () => {
+ useHomeStore((s) => s.useFetchPendingTransferRequests)(true);
+ useHomeStore((s) => s.useFetchPendingTransferRequests)(true);
+ },
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(homeNotificationSelectors.pendingTransferRequests(useHomeStore.getState())).toEqual(
+ [],
+ ),
+ );
+ expect(listMine).toHaveBeenCalledTimes(1);
+ });
+
+ it('paints persisted requests, but only a server answer confirms they are live', async () => {
+ await pendingTransferRequestsResource.storage!.set(
+ { queryKey: PENDING_TRANSFER_REQUESTS_KEY, scope },
+ { data: [transfer('t1')], updatedAt: 1 },
+ );
+ vi.spyOn(resourceTransferRequestService, 'listMine').mockImplementation(never);
+
+ renderHook(() => useHomeStore((s) => s.useFetchPendingTransferRequests)(true), { wrapper });
+
+ await waitFor(() =>
+ expect(
+ homeNotificationSelectors
+ .pendingTransferRequests(useHomeStore.getState())
+ ?.map((r) => r.id),
+ ).toEqual(['t1']),
+ );
+ expect(
+ homeNotificationSelectors.isPendingTransferRequestsConfirmed(useHomeStore.getState()),
+ ).toBe(false);
+ });
+
+ it('drops a settled request from the list and storage even when the re-read fails', async () => {
+ vi.spyOn(resourceTransferRequestService, 'listMine')
+ .mockResolvedValueOnce([transfer('t1'), transfer('t2')])
+ .mockRejectedValue(new Error('offline'));
+ renderHook(() => useHomeStore((s) => s.useFetchPendingTransferRequests)(true), { wrapper });
+ await waitFor(() =>
+ expect(
+ homeNotificationSelectors.pendingTransferRequests(useHomeStore.getState()),
+ ).toHaveLength(2),
+ );
+
+ await act(async () => {
+ await expect(useHomeStore.getState().settleTransferRequest('t1', true)).rejects.toThrow(
+ 'offline',
+ );
+ });
+
+ expect(
+ homeNotificationSelectors.pendingTransferRequests(useHomeStore.getState())?.map((r) => r.id),
+ ).toEqual(['t2']);
+ await waitFor(async () =>
+ expect(
+ (
+ await pendingTransferRequestsResource.storage!.get({
+ queryKey: PENDING_TRANSFER_REQUESTS_KEY,
+ scope,
+ })
+ )?.data.map((r) => r.id),
+ ).toEqual(['t2']),
+ );
+ });
+});
+
+describe('transfer manifest replica', () => {
+ const params = {
+ recipientId: 'me',
+ requestId: 't1',
+ resourceId: 'agent-1',
+ resourceType: 'agent' as const,
+ };
+ const manifest = { hiddenReferencedMember: false, tasksToDetach: 2 } as TransferManifest;
+
+ it('paints a persisted manifest without treating it as confirmed', async () => {
+ await transferManifestResource.storage!.set(
+ { queryKey: 't1', scope },
+ { data: manifest, updatedAt: 1 },
+ );
+ let answer: (value: TransferManifest) => void = () => {};
+ vi.spyOn(resourceTransferRequestService, 'getManifest').mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)),
+ );
+
+ renderHook(() => useHomeStore((s) => s.useFetchTransferManifest)(params), { wrapper });
+
+ await waitFor(() =>
+ expect(
+ homeNotificationSelectors.transferManifest('t1')(useHomeStore.getState())?.tasksToDetach,
+ ).toBe(2),
+ );
+ expect(
+ homeNotificationSelectors.isTransferManifestConfirmed('t1')(useHomeStore.getState()),
+ ).toBe(false);
+
+ act(() => answer({ ...manifest, tasksToDetach: 3 }));
+ await waitFor(() =>
+ expect(
+ homeNotificationSelectors.isTransferManifestConfirmed('t1')(useHomeStore.getState()),
+ ).toBe(true),
+ );
+ expect(
+ homeNotificationSelectors.transferManifest('t1')(useHomeStore.getState())?.tasksToDetach,
+ ).toBe(3);
+ });
+});
diff --git a/src/store/home/slices/notification/action.ts b/src/store/home/slices/notification/action.ts
new file mode 100644
index 00000000000..07e4c56f90c
--- /dev/null
+++ b/src/store/home/slices/notification/action.ts
@@ -0,0 +1,235 @@
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { notificationService } from '@/services/notification';
+import {
+ type PendingTransferRequest,
+ resourceTransferRequestService,
+ type TransferManifest,
+} from '@/services/resourceTransferRequest';
+import type { HomeStore } from '@/store/home/store';
+import type { StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ INBOX_NAVIGATION_COUNTS_KEY,
+ INBOX_NOTIFICATION_PAGE_SIZE,
+ type InboxNavigationCount,
+ inboxNavigationCountsResource,
+ type InboxNotificationFeed,
+ type InboxNotificationItem,
+ type InboxNotificationParams,
+ inboxNotificationResource,
+ inboxNotificationsKey,
+ PENDING_TRANSFER_REQUESTS_KEY,
+ pendingTransferRequestsResource,
+ type TransferManifestParams,
+ transferManifestResource,
+} from './projection';
+
+const n = setNamespace('homeNotification');
+
+const SINGLETON_PARAMS: Record<string, never> = {};
+
+/**
+ * The modal header and the stream both read the live transfer list on open;
+ * one request serves both. Writes refresh with `fetch({ fresh: true })`.
+ */
+const PENDING_TRANSFERS_DEDUPE_INTERVAL = 10_000;
+
+const markRead = (item: InboxNotificationItem): InboxNotificationItem =>
+ item.isRead ? item : { ...item, isRead: true };
+
+/** What every view holds once the server archived the whole stream. */
+const emptyFeed = (feed: InboxNotificationFeed): InboxNotificationFeed => ({
+ ...feed,
+ anchorId: undefined,
+ currentPage: 0,
+ hasMore: false,
+ items: [],
+ loadMoreError: undefined,
+ nextCursor: null,
+ pages: undefined,
+});
+
+type Setter = StoreSetter<HomeStore>;
+export const createHomeNotificationSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new HomeNotificationActionImpl(set, get, _api);
+
+/**
+ * The header inbox modal: the notification stream, its sidebar counts and the
+ * live transfer requests pinned above the stream. Each is a replica, so
+ * reopening the modal after a reload paints the last answer while the server
+ * confirms it. The unread badge (`inbox:unreadCount`) is a poll and stays on
+ * SWR.
+ */
+export class HomeNotificationActionImpl {
+ readonly #counts;
+ readonly #get: () => HomeStore;
+ readonly #manifest;
+ readonly #notifications;
+ readonly #transfers;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#get = get;
+ this.#notifications = createReplicaSlice(inboxNotificationResource, {
+ actionPrefix: n('notifications'),
+ fetcher: async ({ category, isRead }: InboxNotificationParams, cursor?: string) => {
+ const items = await notificationService.list({
+ category,
+ cursor,
+ isRead,
+ limit: INBOX_NOTIFICATION_PAGE_SIZE,
+ });
+ // The server pages by row id and reports no cursor: a short page ends the stream.
+ return {
+ items,
+ nextCursor: items.length < INBOX_NOTIFICATION_PAGE_SIZE ? null : items.at(-1)!.id,
+ };
+ },
+ get,
+ set,
+ stateKey: 'inboxNotificationsReplica',
+ view: recordLens<HomeStore, InboxNotificationFeed>('inboxNotificationsMap'),
+ });
+ this.#counts = createReplicaSlice(inboxNavigationCountsResource, {
+ actionPrefix: n('navigationCounts'),
+ fetcher: () => notificationService.getNavigationCounts(),
+ get,
+ set,
+ stateKey: 'inboxNavigationCountsReplica',
+ view: recordLens<HomeStore, InboxNavigationCount[]>('inboxNavigationCountsMap'),
+ });
+ this.#transfers = createReplicaSlice(pendingTransferRequestsResource, {
+ actionPrefix: n('pendingTransfers'),
+ fetcher: () => resourceTransferRequestService.listMine(),
+ get,
+ set,
+ stateKey: 'pendingTransferRequestsReplica',
+ view: recordLens<HomeStore, PendingTransferRequest[]>('pendingTransferRequestsMap'),
+ });
+ this.#manifest = createReplicaSlice(transferManifestResource, {
+ actionPrefix: n('transferManifest'),
+ fetcher: ({ recipientId, resourceId, resourceType }: TransferManifestParams) =>
+ resourceTransferRequestService.getManifest({ recipientId, resourceId, resourceType }),
+ get,
+ set,
+ stateKey: 'transferManifestReplica',
+ view: recordLens<HomeStore, TransferManifest>('transferManifestMap'),
+ });
+ }
+
+ /** Apply a confirmed change to every inbox view, loaded or only persisted. */
+ #patchAllFeeds = async (fn: (feed: InboxNotificationFeed) => InboxNotificationFeed) => {
+ const keys = Object.keys(this.#get().inboxNotificationsMap);
+ this.#notifications.updateMany(keys.map((key) => ({ apply: (feed) => feed && fn(feed), key })));
+ await this.#notifications.patchStoredRows((feed) => feed && fn(feed));
+ };
+
+ /** Read one view with `homeNotificationSelectors.notificationFeed`. */
+ useFetchInboxNotifications = (
+ params: InboxNotificationParams,
+ enabled = true,
+ ): ReplicaSyncResult => this.#notifications.useSync(params, { enabled });
+
+ /** Read with `homeNotificationSelectors.navigationCounts`. */
+ useFetchInboxNavigationCounts = (enabled = true): ReplicaSyncResult =>
+ this.#counts.useSync(SINGLETON_PARAMS, { enabled, revalidateOnFocus: false });
+
+ /** Workspace-only. Read with `homeNotificationSelectors.pendingTransferRequests`. */
+ useFetchPendingTransferRequests = (enabled = true): ReplicaSyncResult =>
+ this.#transfers.useSync(SINGLETON_PARAMS, {
+ dedupingInterval: PENDING_TRANSFERS_DEDUPE_INTERVAL,
+ enabled,
+ });
+
+ /** Read with `homeNotificationSelectors.transferManifest(params.requestId)`. */
+ useFetchTransferManifest = (params: TransferManifestParams, enabled = true): ReplicaSyncResult =>
+ this.#manifest.useSync(params, { enabled, revalidateOnFocus: false });
+
+ loadMoreInboxNotifications = (params: InboxNotificationParams) =>
+ this.#notifications.loadMore(inboxNotificationsKey(params), params);
+
+ /** Re-read every mounted inbox view and the sidebar counts. */
+ refreshInboxNotifications = async () => {
+ await Promise.all([this.#notifications.revalidate(), this.#counts.revalidate()]);
+ };
+
+ /**
+ * Mark one row read. The view on screen flips it at once (the unread view
+ * drops read rows); once the server confirms, every other view and its
+ * persisted copy carries the change too, so a reload cannot resurface it as
+ * unread. A rejected call rolls the view back and rethrows.
+ */
+ markInboxNotificationRead = async (id: string, view: InboxNotificationParams) => {
+ const apply = (feed: InboxNotificationFeed) => ({
+ ...feed,
+ items: feed.items.map((item) => (item.id === id ? markRead(item) : item)),
+ });
+ await this.#notifications.optimistic(inboxNotificationsKey(view), apply, () =>
+ notificationService.markAsRead([id]),
+ );
+ this.#notifications.updateEntity<InboxNotificationItem>(id, markRead);
+ };
+
+ /** Archive one row: optimistic on the view, then dropped from every view and from storage. */
+ archiveInboxNotification = async (id: string, view: InboxNotificationParams) => {
+ await this.#notifications.optimistic(
+ inboxNotificationsKey(view),
+ (feed) => ({ ...feed, items: feed.items.filter((item) => item.id !== id) }),
+ () => notificationService.archive(id),
+ );
+ this.#notifications.removeEntity(id);
+ };
+
+ /**
+ * Mark everything read. Pending's count is left alone: it counts live
+ * requests that mark-all-as-read cannot resolve, so zeroing it would only
+ * bounce back on the refresh.
+ */
+ markAllInboxNotificationsRead = async (view: InboxNotificationParams) => {
+ this.#counts.update(
+ INBOX_NAVIGATION_COUNTS_KEY,
+ (counts) =>
+ counts?.map((item) => (item.category === 'pending' ? item : { ...item, unreadCount: 0 })),
+ { persist: false },
+ );
+ await this.#notifications.optimistic(
+ inboxNotificationsKey(view),
+ (feed) => ({ ...feed, items: feed.items.map(markRead) }),
+ () => notificationService.markAllAsRead(),
+ );
+ await this.#patchAllFeeds((feed) => ({ ...feed, items: feed.items.map(markRead) }));
+ };
+
+ /** Archive everything: the view empties at once, every other view once the server confirms. */
+ archiveAllInboxNotifications = async (view: InboxNotificationParams) => {
+ await this.#notifications.optimistic(inboxNotificationsKey(view), emptyFeed, () =>
+ notificationService.archiveAll(),
+ );
+ await this.#patchAllFeeds(emptyFeed);
+ };
+
+ /**
+ * After a transfer action: a resolved request leaves the list (and storage)
+ * before the re-read, so a failed re-read cannot keep its action buttons
+ * alive or restore it on the next launch. Resolves the server's live list.
+ */
+ settleTransferRequest = async (
+ requestId: string,
+ succeeded: boolean,
+ ): Promise<PendingTransferRequest[]> => {
+ if (succeeded) {
+ this.#transfers.update(PENDING_TRANSFER_REQUESTS_KEY, (list) =>
+ list?.filter((request) => request.id !== requestId),
+ );
+ this.#manifest.remove(requestId);
+ }
+ const { data } = await this.#transfers.fetch(SINGLETON_PARAMS, { fresh: true });
+ return data;
+ };
+}
+
+export type HomeNotificationAction = Pick<
+ HomeNotificationActionImpl,
+ keyof HomeNotificationActionImpl
+>;
diff --git a/src/store/home/slices/notification/initialState.ts b/src/store/home/slices/notification/initialState.ts
new file mode 100644
index 00000000000..bd8eac7ff8f
--- /dev/null
+++ b/src/store/home/slices/notification/initialState.ts
@@ -0,0 +1,30 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type { PendingTransferRequest, TransferManifest } from '@/services/resourceTransferRequest';
+
+import type { InboxNavigationCount, InboxNotificationFeed } from './projection';
+
+export interface HomeNotificationState {
+ /** Inbox sidebar counts, the view of the `inboxNavigationCounts` replica. */
+ inboxNavigationCountsMap: Record<string, InboxNavigationCount[]>;
+ inboxNavigationCountsReplica: ReplicaState<InboxNavigationCount[]>;
+ /** Inbox stream per view (`inboxNotificationsKey`), the `inboxNotifications` replica. */
+ inboxNotificationsMap: Record<string, InboxNotificationFeed>;
+ inboxNotificationsReplica: ReplicaState<InboxNotificationFeed>;
+ /** Live transfer requests, the view of the `pendingTransferRequests` replica. */
+ pendingTransferRequestsMap: Record<string, PendingTransferRequest[]>;
+ pendingTransferRequestsReplica: ReplicaState<PendingTransferRequest[]>;
+ /** Impact summary per transfer request id, the `transferManifest` replica. */
+ transferManifestMap: Record<string, TransferManifest>;
+ transferManifestReplica: ReplicaState<TransferManifest>;
+}
+
+export const initialHomeNotificationState: HomeNotificationState = {
+ inboxNavigationCountsMap: {},
+ inboxNavigationCountsReplica: createReplicaState(),
+ inboxNotificationsMap: {},
+ inboxNotificationsReplica: createReplicaState(),
+ pendingTransferRequestsMap: {},
+ pendingTransferRequestsReplica: createReplicaState(),
+ transferManifestMap: {},
+ transferManifestReplica: createReplicaState(),
+};
diff --git a/src/store/home/slices/notification/projection.ts b/src/store/home/slices/notification/projection.ts
new file mode 100644
index 00000000000..f64fce7f378
--- /dev/null
+++ b/src/store/home/slices/notification/projection.ts
@@ -0,0 +1,106 @@
+import { definePagedReplica, defineReplica, type ReplicaPagedData } from '@/libs/replica';
+import type { notificationService } from '@/services/notification';
+import type {
+ PendingTransferRequest,
+ TransferManifest,
+ TransferRequestResourceType,
+} from '@/services/resourceTransferRequest';
+
+/** Server page size of the inbox stream (`notification.list` caps `limit` at 50). */
+export const INBOX_NOTIFICATION_PAGE_SIZE = 20;
+
+export type InboxNotificationItem = Awaited<ReturnType<typeof notificationService.list>>[number];
+
+export interface InboxNavigationCount {
+ category: string;
+ readCount: number;
+ totalCount: number;
+ unreadCount: number;
+}
+
+/**
+ * One inbox view: a category (or every category) under a read-state filter
+ * (`undefined` = the combined "all" view). The active workspace is part of the
+ * replica scope β€” the server scopes the inbox to the request context β€” so it is
+ * not repeated here.
+ */
+export interface InboxNotificationParams {
+ category?: string;
+ isRead?: boolean;
+}
+
+export type InboxNotificationFeed = ReplicaPagedData<InboxNotificationItem, string>;
+
+export const inboxNotificationsKey = ({ category, isRead }: InboxNotificationParams) =>
+ `${category ?? '*'}:${isRead === undefined ? 'all' : isRead ? 'read' : 'unread'}`;
+
+/**
+ * The inbox stream, one entry per view. Only the head page survives a reload,
+ * and the views are bounded (categories Γ— read states), with a cap for the
+ * extra categories the server may report.
+ */
+export const inboxNotificationResource = definePagedReplica<
+ InboxNotificationParams,
+ InboxNotificationItem,
+ string
+>({
+ key: inboxNotificationsKey,
+ name: 'inboxNotifications',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'cursor',
+ persist: { pages: 1 },
+ },
+ persist: { maxEntries: 30 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** The inbox sidebar counts are one entry per scope. */
+export const INBOX_NAVIGATION_COUNTS_KEY = 'counts';
+
+/** Per-category read / unread / total counts: a handful of numbers. */
+export const inboxNavigationCountsResource = defineReplica<
+ Record<string, never>,
+ InboxNavigationCount[]
+>({
+ key: () => INBOX_NAVIGATION_COUNTS_KEY,
+ name: 'inboxNavigationCounts',
+ storage: 'localStorage',
+ version: 1,
+});
+
+/** The caller's live transfer requests are one entry per scope (workspace only). */
+export const PENDING_TRANSFER_REQUESTS_KEY = 'mine';
+
+/** Live transfer requests where the caller is recipient or initiator (server-capped list). */
+export const pendingTransferRequestsResource = defineReplica<
+ Record<string, never>,
+ PendingTransferRequest[]
+>({
+ key: () => PENDING_TRANSFER_REQUESTS_KEY,
+ name: 'pendingTransferRequests',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export interface TransferManifestParams {
+ recipientId: string;
+ /** Entry identity only: a request's manifest never moves to another request. */
+ requestId: string;
+ resourceId: string;
+ resourceType: TransferRequestResourceType;
+}
+
+/**
+ * Impact summary of one live transfer request, keyed by request. A few numbers
+ * per request; the cap keeps resolved requests from accumulating.
+ */
+export const transferManifestResource = defineReplica<TransferManifestParams, TransferManifest>({
+ key: ({ requestId }) => requestId,
+ name: 'transferManifest',
+ persist: { maxEntries: 20 },
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/home/slices/notification/selectors.ts b/src/store/home/slices/notification/selectors.ts
new file mode 100644
index 00000000000..fa6f2700185
--- /dev/null
+++ b/src/store/home/slices/notification/selectors.ts
@@ -0,0 +1,54 @@
+import { type HomeStore } from '@/store/home/store';
+
+import {
+ INBOX_NAVIGATION_COUNTS_KEY,
+ type InboxNotificationParams,
+ inboxNotificationsKey,
+ PENDING_TRANSFER_REQUESTS_KEY,
+} from './projection';
+
+/**
+ * Whether an entry was answered by the server in this session. A value
+ * restored from storage can be an empty, truncated or stale snapshot, so an
+ * empty list (or a missing row) only means "nothing there" once this holds.
+ * Later local writes keep the flag; an identity switch empties the entries.
+ */
+const isServerConfirmed = (entry: { source: string } | undefined) => entry?.source === 'server';
+
+/** One inbox view; `undefined` until hydrated or fetched. */
+const notificationFeed = (params: InboxNotificationParams) => (s: HomeStore) =>
+ s.inboxNotificationsMap[inboxNotificationsKey(params)];
+
+const isNotificationFeedConfirmed = (params: InboxNotificationParams) => (s: HomeStore) =>
+ isServerConfirmed(s.inboxNotificationsReplica.entries[inboxNotificationsKey(params)]);
+
+/** Sidebar counts; `undefined` until hydrated or fetched. */
+const navigationCounts = (s: HomeStore) => s.inboxNavigationCountsMap[INBOX_NAVIGATION_COUNTS_KEY];
+
+const isNavigationCountsConfirmed = (s: HomeStore) =>
+ isServerConfirmed(s.inboxNavigationCountsReplica.entries[INBOX_NAVIGATION_COUNTS_KEY]);
+
+/** Live transfer requests; `undefined` until hydrated or fetched. */
+const pendingTransferRequests = (s: HomeStore) =>
+ s.pendingTransferRequestsMap[PENDING_TRANSFER_REQUESTS_KEY];
+
+/** A restored request may have been resolved since: act on it only once confirmed. */
+const isPendingTransferRequestsConfirmed = (s: HomeStore) =>
+ isServerConfirmed(s.pendingTransferRequestsReplica.entries[PENDING_TRANSFER_REQUESTS_KEY]);
+
+const transferManifest = (requestId: string) => (s: HomeStore) => s.transferManifestMap[requestId];
+
+/** A restored manifest paints the summary, but only a fresh one may unlock Accept. */
+const isTransferManifestConfirmed = (requestId: string) => (s: HomeStore) =>
+ isServerConfirmed(s.transferManifestReplica.entries[requestId]);
+
+export const homeNotificationSelectors = {
+ isNavigationCountsConfirmed,
+ isNotificationFeedConfirmed,
+ isPendingTransferRequestsConfirmed,
+ isTransferManifestConfirmed,
+ navigationCounts,
+ notificationFeed,
+ pendingTransferRequests,
+ transferManifest,
+};
diff --git a/src/store/home/store.ts b/src/store/home/store.ts
index 99350bcb2b8..e05e68e3afa 100644
--- a/src/store/home/store.ts
+++ b/src/store/home/store.ts
@@ -23,6 +23,8 @@ import { type HomeInboxAction } from './slices/inbox/action';
import { createHomeInboxSlice } from './slices/inbox/action';
import { type LabelAction } from './slices/label/action';
import { createLabelSlice } from './slices/label/action';
+import { type HomeNotificationAction } from './slices/notification/action';
+import { createHomeNotificationSlice } from './slices/notification/action';
import { type RecentAction } from './slices/recent/action';
import { createRecentSlice } from './slices/recent/action';
import { type SidebarUIAction } from './slices/sidebarUI/action';
@@ -38,6 +40,7 @@ export interface HomeStore
RecentAction,
HomeInboxAction,
HomeInputAction,
+ HomeNotificationAction,
LabelAction,
SidebarUIAction,
ResetableStore,
@@ -49,6 +52,7 @@ type HomeStoreAction = AgentListAction &
RecentAction &
HomeInboxAction &
HomeInputAction &
+ HomeNotificationAction &
LabelAction &
SidebarUIAction &
ResetableStore;
@@ -68,6 +72,7 @@ const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (
createRecentSlice(...parameters),
createHomeInboxSlice(...parameters),
createHomeInputSlice(...parameters),
+ createHomeNotificationSlice(...parameters),
createLabelSlice(...parameters),
createSidebarUISlice(...parameters),
new HomeStoreResetAction(...parameters),