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(brief): move the day news digest onto @lobechat/replica (#22746)

Arvin Xu4da776e21bbd
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index 335ffe45258..aedf26f71cd 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -18,7 +18,7 @@ import Recommendations, { useRecommendationsVisible } from '@/features/Recommend
// acceptance workspace into its chunk for one hook.
import { useCacheScope } from '@/libs/swr/useCacheScope';
import { useBriefStore } from '@/store/brief';
-import { briefListSelectors } from '@/store/brief/selectors';
+import { briefListSelectors, briefNewsSelectors } from '@/store/brief/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useGoalStore } from '@/store/goal';
@@ -162,16 +162,27 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
// of serving yesterday under a "Daily brief" label until remount.
const newsDay = dayjs().subtract(newsDayOffset, 'day').format('YYYY-MM-DD');
const useFetchNewsByDay = useBriefStore((s) => s.useFetchNewsByDay);
- const newsSWR = useFetchNewsByDay(isLogin === true && showRailSections, cacheScope, newsDay);
- const dayNews = newsSWR.data?.news;
- const hasEarlierNews = newsSWR.data?.hasEarlier ?? false;
- // `keepPreviousData` shows the previous day's payload while a page flip is in
- // flight, so everything the user SEES (title, empty copy, arrow gating) must
- // derive from the payload's own day — not from `newsDayOffset`, which has
- // already moved on. Otherwise a slow flip renders "Yesterday's brief" over
- // today's items. Clicks navigate relative to the shown day for the same
- // reason: WYSIWYG paging self-heals any offset/data divergence.
- const shownNewsOffset = newsSWR.data ? resolveShownNewsOffset(newsSWR.data.day) : 0;
+ const newsSync = useFetchNewsByDay(isLogin === true && showRailSections, newsDay);
+ // While a page flip is in flight the previous day stays on screen. Only the
+ // day *key* is remembered here — the row itself is read from the replica,
+ // which clears on a scope switch, so another identity's digest never shows.
+ // A restored empty day is not the server's answer (it may just be stale), so
+ // it is not paintable — no "nothing today" copy — until confirmed.
+ const requestedNews = useBriefStore(briefNewsSelectors.paintableNewsDay(newsDay));
+ const [settledNewsDay, setSettledNewsDay] = useState(newsDay);
+ if (requestedNews && settledNewsDay !== newsDay) setSettledNewsDay(newsDay);
+ const newsData = useBriefStore(
+ briefNewsSelectors.paintableNewsDay(requestedNews ? newsDay : settledNewsDay),
+ );
+ const dayNews = newsData?.news;
+ const hasEarlierNews = newsData?.hasEarlier ?? false;
+ // The previous day's payload shows while a page flip is in flight, so
+ // everything the user SEES (title, empty copy, arrow gating) must derive
+ // from the payload's own day — not from `newsDayOffset`, which has already
+ // moved on. Otherwise a slow flip renders "Yesterday's brief" over today's
+ // items. Clicks navigate relative to the shown day for the same reason:
+ // WYSIWYG paging self-heals any offset/data divergence.
+ const shownNewsOffset = newsData ? resolveShownNewsOffset(newsData.day) : 0;
// Goals are the one home feed that is not about today: they run for days, so
// the dashboard is where you check on them. Behind the same lab toggle as the
@@ -386,15 +397,15 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
// A first-load failure of the day feed must not make the whole section
// vanish — an absent "Daily brief" is indistinguishable from having no
// briefs, so surface the error with a retry like the topic feed does.
- if (showRailSections && newsSWR.error && !dayNews)
+ if (showRailSections && newsSync.error && !dayNews)
sections.push({
key: 'news-error',
label: t('inbox.news.title'),
node: (
<AsyncError
- error={newsSWR.error}
+ error={newsSync.error}
variant={'inline'}
- onRetry={() => void newsSWR.mutate()}
+ onRetry={() => void newsSync.revalidate()}
/>
),
});
@@ -409,7 +420,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
const showNewsSection =
showRailSections && !!dayNews && (news.length > 0 || shownNewsOffset > 0 || hasEarlierNews);
if (showNewsSection) {
- const newsDate = dayjs(newsSWR.data!.day);
+ const newsDate = dayjs(newsData!.day);
const newsLabel =
shownNewsOffset === 0
? t('inbox.news.title')
@@ -426,9 +437,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
sections.push({
action: (
<Flexbox horizontal align={'center'} gap={4}>
- {unresolvedNews.length > 0 && (
- <MarkAllReadButton news={unresolvedNews} onResolved={() => void newsSWR.mutate()} />
- )}
+ {unresolvedNews.length > 0 && <MarkAllReadButton news={unresolvedNews} />}
<ActionIcon
disabled={!hasEarlierNews}
icon={ChevronLeftIcon}
@@ -493,7 +502,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
// back when the cards land.
const railFeedsSettled =
(!showGoals || goals !== undefined || Boolean(goalsSWR.error)) &&
- (!showRailSections || Boolean(newsSWR.data) || Boolean(newsSWR.error));
+ (!showRailSections || Boolean(dayNews) || Boolean(newsSync.error));
if (!railFeedsSettled)
return (
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
index dd744ed678f..3f617849a6f 100644
--- a/src/libs/swr/keys.frozen.test.ts
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -22,7 +22,6 @@ const LEGACY_SWR_KEYS = [
'authKeys.oidcInteraction',
'botWakeKeys.decisions',
'botWakeKeys.summary',
- 'briefKeys.news',
'canvasKeys.storage',
'changelogKeys.modalIndex',
'changelogKeys.post',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 3c9817cd9b8..723b70fb107 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -285,23 +285,6 @@ export const workKeys = {
),
};
-// ---- brief --------------------------------------------------------------
-// The unresolved brief feed no longer has an SWR key: it moved onto
-// `local-replica` (`briefList`, partitioned by identity scope). Only the
-// day-scoped news digest still reads through SWR.
-export const briefKeys = {
- /**
- * Day-scoped news digest (`insight` + `result`, resolved included), keyed by
- * the viewer's local day (`YYYY-MM-DD`) on top of the identity scope.
- */
- news: def('brief:news', (isLogin: boolean, scope: string, day: string) => [
- 'brief:news',
- isLogin,
- scope,
- day,
- ]),
-};
-
// ---- agent config / available / search ----------------------------------
export const agentConfigKeys = {
search: def('agent:search', (keyword?: string) => ['agent:search', keyword]),
@@ -865,7 +848,6 @@ export const swrKeys = {
agentHome: agentHomeKeys,
agentSignal: agentSignalKeys,
auth: authKeys,
- brief: briefKeys,
canvas: canvasKeys,
changelog: changelogKeys,
cron: cronKeys,
diff --git a/src/routes/(main)/home/homeInboxLoader.test.ts b/src/routes/(main)/home/homeInboxLoader.test.ts
new file mode 100644
index 00000000000..94dcd703fef
--- /dev/null
+++ b/src/routes/(main)/home/homeInboxLoader.test.ts
@@ -0,0 +1,53 @@
+import dayjs from 'dayjs';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { homeInboxLoader } from './homeInboxLoader';
+
+const preHydrateInbox = vi.fn(async () => [true, true]);
+const activeWorkspace = vi.hoisted(() => ({ slug: null as string | null }));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: () => activeWorkspace.slug,
+}));
+
+vi.mock('@/store/brief', () => ({
+ getBriefStoreState: () => ({ preHydrateInbox }),
+}));
+
+beforeEach(() => {
+ preHydrateInbox.mockClear();
+ activeWorkspace.slug = null;
+});
+
+describe('homeInboxLoader', () => {
+ it('seeds the inbox and today’s digest of the active scope', async () => {
+ await expect(homeInboxLoader({ params: {} })).resolves.toBeNull();
+
+ expect(preHydrateInbox).toHaveBeenCalledWith(dayjs().format('YYYY-MM-DD'));
+ });
+
+ it('seeds the inbox when the URL opens the workspace already active', async () => {
+ activeWorkspace.slug = 'acme';
+
+ await homeInboxLoader({ params: { workspaceSlug: 'acme' } });
+
+ expect(preHydrateInbox).toHaveBeenCalledTimes(1);
+ });
+
+ // The scope still belongs to the workspace being left: seeding it would paint
+ // another workspace's briefs.
+ it('reads nothing while the URL enters another workspace', async () => {
+ activeWorkspace.slug = 'acme';
+
+ await homeInboxLoader({ params: { workspaceSlug: 'other' } });
+ await homeInboxLoader({ params: {} });
+
+ expect(preHydrateInbox).not.toHaveBeenCalled();
+ });
+
+ it('does not hold the route on a storage stall', async () => {
+ preHydrateInbox.mockImplementationOnce(() => new Promise(() => {}));
+
+ await expect(homeInboxLoader({ params: {} })).resolves.toBeNull();
+ });
+});
diff --git a/src/routes/(main)/home/homeInboxLoader.ts b/src/routes/(main)/home/homeInboxLoader.ts
new file mode 100644
index 00000000000..c15bdddace7
--- /dev/null
+++ b/src/routes/(main)/home/homeInboxLoader.ts
@@ -0,0 +1,25 @@
+import dayjs from 'dayjs';
+import type { LoaderFunctionArgs } from 'react-router';
+
+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';
+import { getBriefStoreState } from '@/store/brief';
+
+// Route loaders run before React commits the route: the only point where the
+// persisted inbox (an async IndexedDB read) can land before Home paints its
+// brief skeleton. A reload always opens the digest on today.
+export const homeInboxLoader = async ({
+ params,
+}: Pick<LoaderFunctionArgs, 'params'>): Promise<null> => {
+ // The URL → workspace switch runs after the route commits, so while the URL
+ // enters another workspace the active scope is still the one being left;
+ // reading it would seed the wrong partition. Leave that to the inbox's sync.
+ if ((params.workspaceSlug ?? null) !== getActiveWorkspaceSlug()) return null;
+
+ await settleWithin(
+ getBriefStoreState().preHydrateInbox(dayjs().format('YYYY-MM-DD')),
+ PRE_PAINT_HYDRATE_TIMEOUT,
+ );
+
+ return null;
+};
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 3e5102f7fb1..b649ee59f08 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -42,6 +42,7 @@ import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces'
import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';
import { agentPageChildren } from '@/spa/router/agentPageRoutes';
import { evalRoute } from '@/spa/router/evalRoutes';
+import { homeInboxLoader } from '@/spa/router/homeInboxLoader';
import { memoryChildren } from '@/spa/router/memoryRoutes';
import { onboardingRoute } from '@/spa/router/onboardingRoute';
import { pageListLoader } from '@/spa/router/pageListLoader';
@@ -647,6 +648,7 @@ const createMainAreaChildrenDefinition = (options: MainAreaRouteOptions = {}): R
element: deferPlatformElement(options.createHomeElement),
handle: { meta: workspaceHomeRouteMeta },
index: true,
+ loader: homeInboxLoader,
},
...sharedMainAreaChildren,
// Workspace settings — `/:slug/settings/*`. Dedicated layout with its
@@ -755,6 +757,7 @@ const createMainAreaChildrenDefinition = (options: MainAreaRouteOptions = {}): R
}),
},
index: true,
+ loader: homeInboxLoader,
},
// Catch-all route
{
diff --git a/src/spa/router/homeInboxLoader.ts b/src/spa/router/homeInboxLoader.ts
new file mode 100644
index 00000000000..b3a11698e0b
--- /dev/null
+++ b/src/spa/router/homeInboxLoader.ts
@@ -0,0 +1,6 @@
+import type { LoaderFunctionArgs } from 'react-router';
+
+// The route tables sit in the entry chunk's static graph; resolving the real
+// loader on first use keeps the brief store out of it.
+export const homeInboxLoader = (args: LoaderFunctionArgs) =>
+ import('@/routes/(main)/home/homeInboxLoader').then((module) => module.homeInboxLoader(args));
diff --git a/src/store/brief/slices/list/action.test.ts b/src/store/brief/slices/list/action.test.ts
index df461705d67..655f736abd6 100644
--- a/src/store/brief/slices/list/action.test.ts
+++ b/src/store/brief/slices/list/action.test.ts
@@ -20,12 +20,15 @@ import { useBriefStore } from '@/store/brief';
import type { BriefItem } from '@/store/brief/types';
import { initialBriefListState } from './initialState';
-import { briefListResource } from './projection';
-import { briefListSelectors } from './selectors';
+import { briefListResource, briefNewsResource, type NewsDay } from './projection';
+import { briefListSelectors, briefNewsSelectors } from './selectors';
const LIST_PARAMS = {} as Record<string, never>;
/** The persisted row of the feed under test (one entry, keyed `unresolved`). */
const STORAGE_KEY = { queryKey: briefListResource.storageKey(LIST_PARAMS) };
+const DAY = '2026-07-31';
+/** The persisted row of the digest of `DAY`. */
+const NEWS_STORAGE_KEY = { queryKey: briefNewsResource.storageKey({ day: DAY }) };
const createBrief = (id: string): BriefItem => ({
actions: null,
@@ -79,6 +82,15 @@ const useScope = (next: string) => {
vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
};
+/** The digest of `DAY` as the inbox reads it. */
+const newsDay = () => briefNewsSelectors.newsDay(DAY)(useBriefStore.getState());
+const newsDayOf = (news: BriefItem[], hasEarlier = false): NewsDay => ({
+ day: DAY,
+ hasEarlier,
+ news,
+});
+const useNewsDay = () => useBriefStore((s) => s.useFetchNewsByDay)(true, DAY);
+
/** The feed as the inbox reads it. */
const feed = () => briefListSelectors.briefs(useBriefStore.getState());
@@ -154,15 +166,15 @@ describe('brief list replica', () => {
const listNewsByDay = vi
.spyOn(briefService, 'listNewsByDay')
.mockResolvedValue({ data: [createBrief('b1')], hasEarlier: false } as never);
- const { result } = renderHook(
- () => useBriefStore((s) => s.useFetchNewsByDay)(true, scope, '2026-07-31'),
- { wrapper },
- );
- await waitFor(() => expect(result.current.data).toBeDefined());
+ renderHook(() => useBriefStore((s) => s.useFetchNewsByDay)(true, DAY), { wrapper });
+ await waitFor(() => expect(newsDay()).toBeDefined());
expect(listNewsByDay).toHaveBeenCalledTimes(1);
+ listNewsByDay.mockImplementation(() => new Promise(() => {}));
await act(() => useBriefStore.getState().resolveBrief('b1', 'approve'));
+ // The answer lands on the digest at once, then the day re-reads.
+ expect(newsDay()?.news[0]).toMatchObject({ resolvedAction: 'approve' });
await waitFor(() => expect(listNewsByDay).toHaveBeenCalledTimes(2));
});
@@ -207,3 +219,208 @@ describe('brief list replica', () => {
await waitFor(() => expect(briefListSelectors.hasBriefs(useBriefStore.getState())).toBe(false));
});
});
+
+describe('brief news replica', () => {
+ it('paints the persisted digest before the network answers, then adopts the server', async () => {
+ await briefNewsResource.storage!.set(
+ { ...NEWS_STORAGE_KEY, scope },
+ { data: newsDayOf([createBrief('cached')]), updatedAt: 1 },
+ );
+ const request = deferred<{ data: BriefItem[]; hasEarlier: boolean }>();
+ vi.spyOn(briefService, 'listNewsByDay').mockReturnValue(request.promise as never);
+
+ const { result } = renderHook(useNewsDay, { wrapper });
+
+ await waitFor(() => expect(newsDay()?.news.map((brief) => brief.id)).toEqual(['cached']));
+ expect(result.current.isValidating).toBe(true);
+ // Restored, not confirmed: an empty restored day must not read as "nothing today".
+ expect(briefNewsSelectors.isNewsDayConfirmed(DAY)(useBriefStore.getState())).toBe(false);
+
+ await act(async () => request.resolve({ data: [createBrief('fresh')], hasEarlier: true }));
+
+ await waitFor(() => expect(newsDay()?.news.map((brief) => brief.id)).toEqual(['fresh']));
+ expect(newsDay()?.hasEarlier).toBe(true);
+ expect(briefNewsSelectors.isNewsDayConfirmed(DAY)(useBriefStore.getState())).toBe(true);
+ });
+
+ it('queries the viewer’s local day as a [start, end) range', async () => {
+ const listNewsByDay = vi
+ .spyOn(briefService, 'listNewsByDay')
+ .mockResolvedValue({ data: [], hasEarlier: false } as never);
+
+ renderHook(useNewsDay, { wrapper });
+
+ await waitFor(() => expect(newsDay()).toBeDefined());
+ const [range] = listNewsByDay.mock.calls[0];
+ expect(range.startAt.getTime()).toBe(new Date(2026, 6, 31).getTime());
+ expect(range.endAt.getTime()).toBe(new Date(2026, 7, 1).getTime());
+ });
+
+ it('keeps an empty restored day unconfirmed until the server answers', async () => {
+ await briefNewsResource.storage!.set(
+ { ...NEWS_STORAGE_KEY, scope },
+ { data: newsDayOf([]), updatedAt: 1 },
+ );
+ vi.spyOn(briefService, 'listNewsByDay').mockImplementation(() => new Promise(() => {}));
+
+ renderHook(useNewsDay, { wrapper });
+
+ await waitFor(() => expect(newsDay()?.news).toEqual([]));
+ expect(briefNewsSelectors.isNewsDayConfirmed(DAY)(useBriefStore.getState())).toBe(false);
+ });
+
+ it('collapses several readers of the same day into one request', async () => {
+ const listNewsByDay = vi
+ .spyOn(briefService, 'listNewsByDay')
+ .mockResolvedValue({ data: [createBrief('b1')], hasEarlier: false } as never);
+
+ // One app-wide SWR cache, as in the product.
+ const cache = new Map();
+ const sharedWrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => cache } },
+ createElement(MutateBridge),
+ children,
+ );
+
+ // Rail + main inbox mounted together, then one more Home surface right after.
+ renderHook(
+ () => {
+ useNewsDay();
+ useNewsDay();
+ },
+ { wrapper: sharedWrapper },
+ );
+ await waitFor(() => expect(newsDay()).toBeDefined());
+ renderHook(useNewsDay, { wrapper: sharedWrapper });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+
+ await waitFor(() => expect(newsDay()).toBeDefined());
+ expect(listNewsByDay).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the last digest when a background refresh fails', async () => {
+ const listNewsByDay = vi
+ .spyOn(briefService, 'listNewsByDay')
+ .mockResolvedValue({ data: [createBrief('b1')], hasEarlier: false } as never);
+ const { result } = renderHook(useNewsDay, { wrapper });
+ await waitFor(() => expect(newsDay()).toBeDefined());
+
+ listNewsByDay.mockRejectedValue(new Error('offline'));
+ await act(async () => {
+ await result.current.revalidate().catch(() => {});
+ });
+
+ expect(newsDay()?.news.map((brief) => brief.id)).toEqual(['b1']);
+ });
+
+ it('marks resolved-as-read briefs on the digest and its persisted row', async () => {
+ await load([createBrief('b1'), createBrief('b2')]);
+ vi.spyOn(briefService, 'listNewsByDay').mockResolvedValue({
+ data: [createBrief('b1'), createBrief('b2')],
+ hasEarlier: false,
+ } as never);
+ renderHook(useNewsDay, { wrapper });
+ await waitFor(() => expect(newsDay()).toBeDefined());
+ vi.spyOn(briefService, 'listNewsByDay').mockImplementation(() => new Promise(() => {}));
+ vi.spyOn(briefService, 'resolveManyAsRead').mockResolvedValue({ data: ['b1'] } as never);
+
+ await act(() => useBriefStore.getState().resolveBriefsAsRead(['b1']));
+
+ // Without waiting for the re-read: the digest is a day's record, so the
+ // brief stays there, resolved.
+ expect(newsDay()?.news.map((brief) => [brief.id, Boolean(brief.resolvedAt)])).toEqual([
+ ['b1', true],
+ ['b2', false],
+ ]);
+ await waitFor(async () => {
+ const row = await briefNewsResource.storage!.get({ ...NEWS_STORAGE_KEY, scope });
+ expect(row?.data.news[0].resolvedAt).toBeTruthy();
+ });
+ });
+
+ it('does not restore a deleted brief from the persisted digest', async () => {
+ vi.spyOn(briefService, 'listNewsByDay').mockResolvedValue({
+ data: [createBrief('b1'), createBrief('b2')],
+ hasEarlier: false,
+ } as never);
+ const { unmount } = renderHook(useNewsDay, { wrapper });
+ await waitFor(() => expect(newsDay()).toBeDefined());
+ vi.spyOn(briefService, 'delete').mockResolvedValue(undefined as never);
+
+ await act(() => useBriefStore.getState().deleteBrief('b1'));
+ expect(newsDay()?.news.map((brief) => brief.id)).toEqual(['b2']);
+
+ await waitFor(async () => {
+ const row = await briefNewsResource.storage!.get({ ...NEWS_STORAGE_KEY, scope });
+ expect(row?.data.news.map((brief) => brief.id)).toEqual(['b2']);
+ });
+
+ // A reload: a fresh store hydrates the persisted day before the network answers.
+ unmount();
+ act(() => useBriefStore.setState({ ...initialBriefListState }));
+ vi.spyOn(briefService, 'listNewsByDay').mockImplementation(() => new Promise(() => {}));
+ renderHook(useNewsDay, { wrapper });
+ await waitFor(() => expect(newsDay()?.news.map((brief) => brief.id)).toEqual(['b2']));
+ });
+
+ it('never shows the previous scope’s digest after a scope switch', async () => {
+ vi.spyOn(briefService, 'listNewsByDay').mockResolvedValue({
+ data: [createBrief('b1')],
+ hasEarlier: false,
+ } as never);
+ const { rerender } = renderHook(useNewsDay, { wrapper });
+ await waitFor(() => expect(newsDay()).toBeDefined());
+
+ useScope(`brief-user-${randomUUID()}:personal`);
+ vi.spyOn(briefService, 'listNewsByDay').mockImplementation(() => new Promise(() => {}));
+ rerender();
+
+ await waitFor(() => expect(newsDay()).toBeUndefined());
+ });
+
+ it('seeds the persisted feed and digest before Home mounts', async () => {
+ await briefListResource.storage!.set(
+ { ...STORAGE_KEY, scope },
+ { data: [createBrief('cached-feed')], updatedAt: 1 },
+ );
+ await briefNewsResource.storage!.set(
+ { ...NEWS_STORAGE_KEY, scope },
+ { data: newsDayOf([createBrief('cached-news')]), updatedAt: 1 },
+ );
+ const listUnresolved = vi.spyOn(briefService, 'listUnresolved');
+ const listNewsByDay = vi.spyOn(briefService, 'listNewsByDay');
+
+ // No hook is mounted: this is the route loader before the first frame.
+ await useBriefStore.getState().preHydrateInbox(DAY);
+
+ expect(feed().map((brief) => brief.id)).toEqual(['cached-feed']);
+ expect(newsDay()?.news.map((brief) => brief.id)).toEqual(['cached-news']);
+ expect(listUnresolved).not.toHaveBeenCalled();
+ expect(listNewsByDay).not.toHaveBeenCalled();
+ });
+
+ it('does not seed another scope’s rows', async () => {
+ await briefNewsResource.storage!.set(
+ { ...NEWS_STORAGE_KEY, scope },
+ { data: newsDayOf([createBrief('mine')]), updatedAt: 1 },
+ );
+ await useBriefStore.getState().preHydrateInbox(DAY);
+ expect(newsDay()).toBeDefined();
+
+ useScope(`brief-user-${randomUUID()}:personal`);
+ await useBriefStore.getState().preHydrateInbox(DAY);
+
+ expect(newsDay()).toBeUndefined();
+ expect(briefListSelectors.isBriefsInit(useBriefStore.getState())).toBe(false);
+ });
+
+ it('does not fetch while disabled', () => {
+ const listNewsByDay = vi.spyOn(briefService, 'listNewsByDay');
+ renderHook(() => useBriefStore((s) => s.useFetchNewsByDay)(false, DAY), { wrapper });
+ expect(listNewsByDay).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.ts
index c0623a8d3d8..e44b9f7559a 100644
--- a/src/store/brief/slices/list/action.ts
+++ b/src/store/brief/slices/list/action.ts
@@ -1,6 +1,5 @@
import { NEWS_BRIEF_TYPES } from '@lobechat/types';
import dayjs from 'dayjs';
-import { type SWRResponse } from 'swr';
import {
createReplicaSlice,
@@ -9,8 +8,8 @@ import {
type ReplicaSyncResult,
revalidateReplica,
} from '@/libs/replica';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { briefKeys, goalKeys } from '@/libs/swr/keys';
+import { mutate } from '@/libs/swr';
+import { goalKeys } from '@/libs/swr/keys';
import { briefService } from '@/services/brief';
import { taskService } from '@/services/task';
import { type BriefStore } from '@/store/brief/store';
@@ -19,22 +18,19 @@ import { goalGraphResource, homeGoalListResource } from '@/store/goal/projection
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
-import { BRIEF_LIST_KEY, briefEntity, briefListResource } from './projection';
+import {
+ BRIEF_LIST_KEY,
+ briefEntity,
+ briefListResource,
+ briefNewsResource,
+ type NewsDay,
+ newsDayEntity,
+ type NewsDayParams,
+} from './projection';
const n = setNamespace('briefList');
-export interface NewsDay {
- /**
- * The local day (`YYYY-MM-DD`) this payload belongs to. Carried in the data so
- * consumers rendering with `keepPreviousData` can label/gate from the day
- * actually shown instead of the day being fetched — otherwise a slow page
- * flip shows the new day's title over the old day's briefs.
- */
- day: string;
- /** Any news brief older than this day exists — the day pager's "older" arrow. */
- hasEarlier: boolean;
- news: BriefItem[];
-}
+export type { NewsDay } from './projection';
/** Sync flags of the unresolved feed, plus the aliases the inbox reads. */
export interface BriefListSyncResult extends ReplicaSyncResult {
@@ -47,6 +43,13 @@ export interface BriefListSyncResult extends ReplicaSyncResult {
/** The feed has one entry per scope (the replica partitions by identity), so its params are constant. */
const LIST_PARAMS = {} as Record<string, never>;
+/**
+ * The digest is read by every Home surface that owns the rail sections; collapse
+ * their mounts into one request. Writes, focus and explicit revalidation still
+ * refresh as usual.
+ */
+const NEWS_DEDUPING_INTERVAL = 10_000;
+
type Setter = StoreSetter<BriefStore>;
export const createBriefListSlice = (set: Setter, get: () => BriefStore, _api?: unknown) =>
@@ -55,7 +58,10 @@ export const createBriefListSlice = (set: Setter, get: () => BriefStore, _api?:
export class BriefListActionImpl {
readonly #get: () => BriefStore;
readonly #briefList;
+ readonly #briefNews;
readonly #briefs;
+ readonly #listBriefs;
+ readonly #newsBriefs;
constructor(set: Setter, get: () => BriefStore, _api?: unknown) {
void _api;
@@ -76,7 +82,30 @@ export class BriefListActionImpl {
// applies right away, a failed write rolls back to the confirmed base, and a
// confirmed write reaches the persisted row too — so a reload never hydrates
// a value the server has already moved past.
- this.#briefs = linkReplicaEntity<BriefItem>([this.#briefList]);
+ this.#briefNews = createReplicaSlice(briefNewsResource, {
+ actionPrefix: n('news'),
+ entity: newsDayEntity,
+ // `day` is the viewer's local `YYYY-MM-DD`; the [start, end) instants are
+ // computed here so the server stays timezone-agnostic.
+ fetcher: async ({ day }: NewsDayParams): Promise<NewsDay> => {
+ const startAt = dayjs(day).startOf('day');
+ const result = await briefService.listNewsByDay({
+ endAt: startAt.add(1, 'day').toDate(),
+ startAt: startAt.toDate(),
+ });
+ return { day, hasEarlier: result.hasEarlier, news: result.data as BriefItem[] };
+ },
+ get,
+ set,
+ stateKey: 'briefNewsReplica',
+ view: recordLens<BriefStore, NewsDay>('briefNewsMap'),
+ });
+ // A news brief is in both the unresolved feed and its day's digest, so a
+ // read / resolve / delete lands on both — persisted rows of days not on
+ // screen included.
+ this.#briefs = linkReplicaEntity<BriefItem>([this.#briefList, this.#briefNews]);
+ this.#listBriefs = linkReplicaEntity<BriefItem>([this.#briefList]);
+ this.#newsBriefs = linkReplicaEntity<BriefItem>([this.#briefNews]);
}
#syncResult = (sync: ReplicaSyncResult): BriefListSyncResult => ({
@@ -108,7 +137,13 @@ export class BriefListActionImpl {
if (ids.length === 0) return;
const result = await briefService.resolveManyAsRead(ids);
- for (const id of result.data) this.#briefs.remove(id);
+ const resolvedAt = new Date().toISOString();
+ for (const id of result.data) {
+ this.#listBriefs.remove(id);
+ // The digest keeps resolved briefs (it is a day's record, not a to-do list).
+ this.#newsBriefs.update(id, (brief) => ({ ...brief, resolvedAction: 'read', resolvedAt }));
+ }
+ void this.#briefNews.revalidate();
};
resolveBrief = async (id: string, action?: string, comment?: string) => {
@@ -126,8 +161,7 @@ export class BriefListActionImpl {
// An urgent news brief is answered from "Needs you", and the day digest it
// returns to holds its own unresolved copy — refresh it so the handled brief
// does not come back there as unread once it leaves the unresolved feed.
- if (target && NEWS_BRIEF_TYPES.includes(target.type))
- void mutate((key) => Array.isArray(key) && key[0] === briefKeys.news.root);
+ if (target && NEWS_BRIEF_TYPES.includes(target.type)) void this.#briefNews.revalidate();
// A goal brief answered the goal itself: the island and the goal views
// asking the same question have to drop it too.
if (goal)
@@ -159,27 +193,30 @@ export class BriefListActionImpl {
};
/**
- * Day-scoped news digest (`insight` + `result`, resolved included). Lives in
- * SWR only — no zustand bucket: the key already partitions by identity scope
- * and day, the list is read-mostly, and the one mutation that touches it
- * (mark-all-read) revalidates through the returned SWR handle. `day` is the
- * viewer's local `YYYY-MM-DD`; the [start, end) instants are computed here so
- * the server stays timezone-agnostic. `keepPreviousData` keeps the section
- * stable while the user pages between days.
+ * Day-scoped news digest (`insight` + `result`, resolved included) of the
+ * active identity scope. Read it with `briefNewsSelectors.newsDay(day)`: the
+ * replica hydrates the persisted day on the first frame and converges on the
+ * server in the background.
*/
- useFetchNewsByDay = (enabled: boolean, scope: string, day: string): SWRResponse<NewsDay> =>
- useClientDataSWR<NewsDay>(
- enabled ? briefKeys.news(true, scope, day) : null,
- async () => {
- const startAt = dayjs(day).startOf('day');
- const result = await briefService.listNewsByDay({
- endAt: startAt.add(1, 'day').toDate(),
- startAt: startAt.toDate(),
- });
- return { day, hasEarlier: result.hasEarlier, news: result.data as BriefItem[] };
- },
- { keepPreviousData: true },
- );
+ useFetchNewsByDay = (enabled: boolean, day: string): ReplicaSyncResult =>
+ this.#briefNews.useSync({ day }, { dedupingInterval: NEWS_DEDUPING_INTERVAL, enabled });
+
+ /**
+ * Seed the persisted unresolved feed and `day`'s digest before Home commits,
+ * so the inbox paints the last confirmed briefs on the first frame instead of
+ * a skeleton until the mount-time hydrate lands. Call from a route loader,
+ * bounded by a timeout.
+ */
+ preHydrateInbox = async (day: string): Promise<boolean[]> => {
+ const scope = briefListResource.scope.get();
+ // The slots may still hold the previous identity's rows; drop them first.
+ this.#briefList.ensureScope(scope);
+ this.#briefNews.ensureScope(scope);
+ return Promise.all([
+ this.#briefList.hydrate(LIST_PARAMS, scope),
+ this.#briefNews.hydrate({ day }, scope),
+ ]);
+ };
/**
* The unresolved feed of the active scope. Read the rows with
diff --git a/src/store/brief/slices/list/initialState.ts b/src/store/brief/slices/list/initialState.ts
index 3f681a54d1b..932309cd0ce 100644
--- a/src/store/brief/slices/list/initialState.ts
+++ b/src/store/brief/slices/list/initialState.ts
@@ -1,14 +1,22 @@
import { createReplicaState, type ReplicaState } from '@/libs/replica';
import { type BriefItem } from '@/store/brief/types';
+import { type NewsDay } from './projection';
+
export interface BriefListState {
/** The unresolved feed — the view of the `briefList` replica (`briefListMap[BRIEF_LIST_KEY]`). */
briefListMap: Record<string, BriefItem[]>;
/** Replica bookkeeping for `briefListMap`. */
briefListReplica: ReplicaState<BriefItem[]>;
+ /** The day-scoped news digest — the view of the `briefNews` replica, keyed by local day. */
+ briefNewsMap: Record<string, NewsDay>;
+ /** Replica bookkeeping for `briefNewsMap`. */
+ briefNewsReplica: ReplicaState<NewsDay>;
}
export const initialBriefListState: BriefListState = {
briefListMap: {},
briefListReplica: createReplicaState(),
+ briefNewsMap: {},
+ briefNewsReplica: createReplicaState(),
};
diff --git a/src/store/brief/slices/list/projection.ts b/src/store/brief/slices/list/projection.ts
index 97c85efe192..b57737f838e 100644
--- a/src/store/brief/slices/list/projection.ts
+++ b/src/store/brief/slices/list/projection.ts
@@ -36,3 +36,43 @@ export const briefListResource = defineReplica<
export const briefEntity: ReplicaEntityAdapter<BriefItem[], BriefItem> = arrayEntity<BriefItem>(
(brief) => brief.id,
);
+
+export interface NewsDay {
+ /**
+ * The local day (`YYYY-MM-DD`) this payload belongs to. Carried in the data so
+ * a consumer still showing the previous day while the next one loads can
+ * label/gate from the day actually shown instead of the day being fetched.
+ */
+ day: string;
+ /** Any news brief older than this day exists — the day pager's "older" arrow. */
+ hasEarlier: boolean;
+ news: BriefItem[];
+}
+
+export interface NewsDayParams {
+ /** The viewer's local day, `YYYY-MM-DD`. */
+ day: string;
+}
+
+/**
+ * The day-scoped news digest (`insight` + `result`, resolved included), one
+ * entry per local day of the active identity scope. Persisted so a reload
+ * paints the last confirmed digest on the first frame; only the most recently
+ * viewed days are kept — paging further back is rare and refetches.
+ */
+export const briefNewsResource = defineReplica<NewsDayParams, NewsDay>({
+ key: ({ day }) => day,
+ name: 'briefNews',
+ persist: { maxEntries: 7 },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** A news brief lives in `NewsDay.news`, addressed by `briefs.id`. */
+export const newsDayEntity: ReplicaEntityAdapter<NewsDay, BriefItem> = {
+ has: (data, id) => briefEntity.has(data.news, id),
+ map: (data, id, fn) => {
+ const news = briefEntity.map(data.news, id, fn);
+ return news === data.news || news === undefined ? data : { ...data, news };
+ },
+};
diff --git a/src/store/brief/slices/list/selectors.test.ts b/src/store/brief/slices/list/selectors.test.ts
index d7b99eb92fd..71292b9e849 100644
--- a/src/store/brief/slices/list/selectors.test.ts
+++ b/src/store/brief/slices/list/selectors.test.ts
@@ -5,7 +5,7 @@ import { type BriefItem } from '@/store/brief/types';
import { initialBriefListState } from './initialState';
import { BRIEF_LIST_KEY } from './projection';
-import { briefListSelectors } from './selectors';
+import { briefListSelectors, briefNewsSelectors } from './selectors';
const createState = (overrides: Partial<BriefStore> = {}) =>
({
@@ -56,3 +56,29 @@ describe('briefListSelectors', () => {
});
});
});
+
+describe('briefNewsSelectors.paintableNewsDay', () => {
+ const DAY = '2026-07-31';
+ const newsState = (news: BriefItem[], source?: 'server' | 'storage') =>
+ createState({
+ briefNewsMap: { [DAY]: { day: DAY, hasEarlier: false, news } },
+ briefNewsReplica: {
+ entries: source ? { [DAY]: { pending: [], source, updatedAt: 1 } } : {},
+ },
+ });
+
+ it('is undefined before the day is hydrated or fetched', () => {
+ expect(briefNewsSelectors.paintableNewsDay(DAY)(createState())).toBeUndefined();
+ });
+
+ it('paints restored rows before the server answers', () => {
+ const state = newsState([{ id: 'b1' }] as unknown as BriefItem[], 'storage');
+ expect(briefNewsSelectors.paintableNewsDay(DAY)(state)?.news).toHaveLength(1);
+ });
+
+ // A stale empty snapshot must not claim "nothing happened today".
+ it('keeps a restored empty day loading until the server confirms it', () => {
+ expect(briefNewsSelectors.paintableNewsDay(DAY)(newsState([], 'storage'))).toBeUndefined();
+ expect(briefNewsSelectors.paintableNewsDay(DAY)(newsState([], 'server'))?.news).toEqual([]);
+ });
+});
diff --git a/src/store/brief/slices/list/selectors.ts b/src/store/brief/slices/list/selectors.ts
index 4c1b1a563e6..7e46ec943ff 100644
--- a/src/store/brief/slices/list/selectors.ts
+++ b/src/store/brief/slices/list/selectors.ts
@@ -1,7 +1,7 @@
import { type BriefStore } from '@/store/brief/store';
import { type BriefItem } from '@/store/brief/types';
-import { BRIEF_LIST_KEY } from './projection';
+import { BRIEF_LIST_KEY, type NewsDay } from './projection';
/** Stable identity so an unloaded feed never churns `shallow`-compared subscribers. */
const EMPTY_BRIEFS: BriefItem[] = [];
@@ -25,3 +25,39 @@ export const briefListSelectors = {
hasBriefs,
isBriefsInit,
};
+
+/** The digest of one local day, `undefined` until it is hydrated or fetched in the active scope. */
+const newsDay =
+ (day: string) =>
+ (s: BriefStore): NewsDay | undefined =>
+ s.briefNewsMap[day];
+
+/**
+ * Whether the server has answered for this day in the active scope. A digest
+ * restored from storage may be a stale snapshot, so an empty restored day is
+ * still "loading" — not "nothing happened today" — until this is true.
+ */
+const isNewsDayConfirmed =
+ (day: string) =>
+ (s: BriefStore): boolean => {
+ const source = s.briefNewsReplica.entries[day]?.source;
+ return source === 'server' || source === 'local';
+ };
+
+/**
+ * The digest of a day once it can be painted: any restored rows, or an empty
+ * day only after the server confirmed it. `undefined` reads as loading.
+ */
+const paintableNewsDay =
+ (day: string) =>
+ (s: BriefStore): NewsDay | undefined => {
+ const data = s.briefNewsMap[day];
+ if (!data) return undefined;
+ return data.news.length > 0 || isNewsDayConfirmed(day)(s) ? data : undefined;
+ };
+
+export const briefNewsSelectors = {
+ isNewsDayConfirmed,
+ newsDay,
+ paintableNewsDay,
+};
diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.ts
index a8b063ac2cc..fb71cb8ff3b 100644
--- a/src/store/goal/action.test.ts
+++ b/src/store/goal/action.test.ts
@@ -7,6 +7,7 @@ import { revalidateReplica } from '@/libs/replica';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { aiChatService } from '@/services/aiChat';
import { goalService } from '@/services/goal';
+import { briefListResource } from '@/store/brief/slices/list/projection';
import { taskGroupListResource, taskListResource } from '@/store/task/slices/list/projection';
import { useGoalStore } from './index';
@@ -33,6 +34,7 @@ vi.mock('@/services/goal', () => ({
advance: vi.fn(),
archive: vi.fn(),
close: vi.fn(),
+ decide: vi.fn(),
delete: vi.fn(),
getGraph: vi.fn(),
list: vi.fn(),
@@ -432,6 +434,21 @@ describe('GoalAction', () => {
expect(revalidateReplica).toHaveBeenCalledWith(taskGroupListResource);
});
+ it('refreshes the inbox brief feed after a decision gate is answered', async () => {
+ await useGoalStore
+ .getState()
+ .decideGoal('goal-1', { decisionId: 'decision-1', optionId: 'option-1' });
+
+ expect(goalService.decide).toHaveBeenCalledWith({
+ decisionId: 'decision-1',
+ id: 'goal-1',
+ optionId: 'option-1',
+ });
+ // The inbox brief asking the same gate is the `briefList` replica — the old
+ // `brief:list` SWR prefix mutate matched nothing, so the brief stayed put.
+ expect(revalidateReplica).toHaveBeenCalledWith(briefListResource);
+ });
+
it('reports an archive that landed as done even when the refresh after it fails', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(revalidateReplica).mockRejectedValueOnce(new Error('offline'));
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index b436b0c81f0..e99ec5ca151 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -27,6 +27,7 @@ import { goalKeys } from '@/libs/swr/keys';
import { aiChatService } from '@/services/aiChat';
import { type GoalListItem, goalService } from '@/services/goal';
import { type MetricSeriesWithPoints, metricService } from '@/services/metric';
+import { briefListResource } from '@/store/brief/slices/list/projection';
import { taskGroupListResource, taskListResource } from '@/store/task/slices/list/projection';
import type { StoreSetter } from '@/store/types';
import { useUserStore } from '@/store/user';
@@ -328,7 +329,9 @@ export class GoalActionImpl {
this.refreshGoalGraph(goalId),
mutate(goalKeys.pendingForIsland()),
revalidateReplica(homeGoalListResource),
- mutate((key) => Array.isArray(key) && key[0] === 'brief:list'),
+ // The inbox brief carrying the same gate is a replica: an SWR key prefix
+ // (the old `brief:list`) no longer reaches it.
+ revalidateReplica(briefListResource),
]);
};