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(home): serve inbox, daily brief and resource recents from replicas (#20851)

Arvin Xu78979e4d87b3
diff --git a/src/features/Home/components/GroupBlock/index.tsx b/src/features/Home/components/GroupBlock/index.tsx
index edbe1855f88..ec05f3cba73 100644
--- a/src/features/Home/components/GroupBlock/index.tsx
+++ b/src/features/Home/components/GroupBlock/index.tsx
@@ -1,5 +1,5 @@
import { type FlexboxProps, type IconProps } from '@lobehub/ui';
-import { createStaticStyles, cssVar, cx, Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx, Flexbox, Icon, Spin, Text } from '@lobehub/ui';
import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
import { type ReactNode } from 'react';
import { memo, Suspense, useState } from 'react';
@@ -17,6 +17,11 @@ interface GroupBlockProps extends Omit<FlexboxProps, 'title'> {
collapsed?: boolean;
count?: number;
icon?: IconProps['icon'];
+ /**
+ * The rows on screen are the local copy and a refresh is in flight: a small
+ * spinner beside the count, so the user knows newer data may still arrive.
+ */
+ loading?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
title?: ReactNode;
}
@@ -49,6 +54,7 @@ const GroupBlock = memo<GroupBlockProps>(
collapsed = false,
count,
icon,
+ loading,
onCollapsedChange,
...rest
}) => {
@@ -80,6 +86,7 @@ const GroupBlock = memo<GroupBlockProps>(
{title}
</Text>
{count !== undefined && <CountBadge count={count} />}
+ {loading && <Spin size="small" variant="network" />}
{onCollapsedChange && (
<Icon
color={cssVar.colorTextQuaternary}
diff --git a/src/features/Home/components/RailCard/index.tsx b/src/features/Home/components/RailCard/index.tsx
index 5d98326b680..cdc7695c148 100644
--- a/src/features/Home/components/RailCard/index.tsx
+++ b/src/features/Home/components/RailCard/index.tsx
@@ -1,4 +1,4 @@
-import { createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, Flexbox, Icon, Spin, Text } from '@lobehub/ui';
import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
import { memo, type ReactNode } from 'react';
@@ -45,18 +45,24 @@ interface RailCardProps {
*/
collapsed?: boolean;
count?: number;
+ /**
+ * The rows on screen are the local copy and a refresh is in flight: a small
+ * spinner beside the count, so the user knows newer data may still arrive.
+ */
+ loading?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
title?: ReactNode;
}
const RailCard = memo<RailCardProps>(
- ({ action, children, collapsed = false, count, onCollapsedChange, title }) => {
+ ({ action, children, collapsed = false, count, loading, onCollapsedChange, title }) => {
const heading = (
<Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>
<Text ellipsis className={homeType.sectionLabel}>
{title}
</Text>
{count !== undefined && <CountBadge count={count} />}
+ {loading && <Spin size="small" variant="network" />}
{onCollapsedChange && (
<Icon
className={'home-rail-card-chevron'}
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index d38a2793aef..a57e26250ed 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -68,6 +68,8 @@ interface InboxSection {
key: string;
/** Omitted when the section labels itself (the running card names its own count). */
label?: string;
+ /** A refresh is in flight over rows already on screen (see GroupBlock `loading`). */
+ loading?: boolean;
node: ReactNode;
onCollapsedChange?: (collapsed: boolean) => void;
/** Section carries its own card shell β€” the rail renders it verbatim. */
@@ -229,6 +231,10 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
if (!isLogin) return null;
+ // The cached feed is on screen while the server confirms it: say so on the
+ // section heading instead of hiding the rows behind a skeleton.
+ const briefsRefreshing = isBriefsInit && briefsSWR.isValidating;
+
const blockState = resolveInboxBlockState({
hasError: Boolean(briefsSWR.error),
hiddenWidgets,
@@ -337,6 +343,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
count: needsYou.length,
key: 'needsYou',
label: t('inbox.needsYou.title'),
+ loading: briefsRefreshing,
node: (
<Flexbox gap={12}>
{needsYou.map((brief) => (
@@ -362,6 +369,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
count: unreadTopics.length,
key: 'unread',
label: t('inbox.unread.title'),
+ loading: topics.isRefreshing,
node: (
<UnreadTopicList
bare={isRail}
@@ -393,6 +401,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
count: needsYou.length,
key: 'needsYou',
label: t('inbox.needsYou.title'),
+ loading: briefsRefreshing,
node: (
<Flexbox gap={12}>
{needsYou.map((brief) => (
@@ -548,6 +557,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
count,
key,
label,
+ loading,
node,
onCollapsedChange,
selfShelled,
@@ -562,6 +572,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
collapsed={collapsed}
count={count}
key={key}
+ loading={loading}
title={
label && (
<>
@@ -585,6 +596,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
collapsed={collapsed}
count={count}
key={key}
+ loading={loading}
title={
<>
{label}
diff --git a/src/features/HomeInbox/useHomeInboxTopics.test.ts b/src/features/HomeInbox/useHomeInboxTopics.test.ts
new file mode 100644
index 00000000000..1e648706c11
--- /dev/null
+++ b/src/features/HomeInbox/useHomeInboxTopics.test.ts
@@ -0,0 +1,85 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * A reload paints the persisted inbox and flags the in-flight refresh, so the
+ * section heading can show it is still confirming the rows on screen.
+ */
+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 TopicListItem, topicService } from '@/services/topic';
+import { useHomeStore } from '@/store/home';
+import { initialHomeInboxState } from '@/store/home/slices/inbox/initialState';
+import { HOME_INBOX_KEY, homeInboxTopicsResource } from '@/store/home/slices/inbox/projection';
+
+import { useHomeInboxTopics } from './useHomeInboxTopics';
+
+const topic = (id: string, status: TopicListItem['status']): TopicListItem =>
+ ({ createdAt: 0, id, status, title: id, updatedAt: 0 }) as unknown as TopicListItem;
+
+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 = '';
+
+beforeEach(() => {
+ scope = `inbox-hook-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => useHomeStore.setState({ ...initialHomeInboxState }));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('useHomeInboxTopics', () => {
+ it('reports a refresh over the persisted rows, then clears it when the server answers', async () => {
+ await homeInboxTopicsResource.storage!.set(
+ { queryKey: HOME_INBOX_KEY, scope },
+ { data: [topic('cached', 'unread')], updatedAt: 1 },
+ );
+ let answer!: (rows: TopicListItem[]) => void;
+ vi.spyOn(topicService, 'queryTopics').mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)),
+ );
+
+ const { result } = renderHook(() => useHomeInboxTopics(true), { wrapper });
+
+ await waitFor(() => expect(result.current.unread.map((t) => t.id)).toEqual(['cached']));
+ expect(result.current.isInit).toBe(true);
+ expect(result.current.isRefreshing).toBe(true);
+
+ await act(async () => answer([topic('fresh', 'unread')]));
+
+ await waitFor(() => expect(result.current.unread.map((t) => t.id)).toEqual(['fresh']));
+ expect(result.current.isRefreshing).toBe(false);
+ });
+
+ it('does not claim a refresh on a cold load with nothing to show yet', async () => {
+ vi.spyOn(topicService, 'queryTopics').mockImplementation(() => new Promise(() => {}));
+
+ const { result } = renderHook(() => useHomeInboxTopics(true), { wrapper });
+
+ await waitFor(() => expect(result.current.isInit).toBe(false));
+ expect(result.current.isRefreshing).toBe(false);
+ });
+});
diff --git a/src/features/HomeInbox/useHomeInboxTopics.ts b/src/features/HomeInbox/useHomeInboxTopics.ts
index b431d62bda4..5d9ae0e4ac9 100644
--- a/src/features/HomeInbox/useHomeInboxTopics.ts
+++ b/src/features/HomeInbox/useHomeInboxTopics.ts
@@ -1,21 +1,16 @@
import { useMemo } from 'react';
-import { useClientDataSWR } from '@/libs/swr';
-import { homeInboxKeys } from '@/libs/swr/keys';
-import { type TopicListItem, topicService } from '@/services/topic';
-import { type ChatTopicStatus } from '@/types/topic';
-
-/**
- * Everything the home inbox needs from topics, in one round trip. `queryTopics`
- * filters server-side by status, so widening this list costs nothing extra.
- */
-const INBOX_STATUSES: ChatTopicStatus[] = ['running', 'unread'];
+import { type TopicListItem } from '@/services/topic';
+import { useHomeStore } from '@/store/home';
+import { homeInboxSelectors } from '@/store/home/selectors';
export type InboxTopic = TopicListItem;
export interface HomeInboxTopics {
error: unknown;
isInit: boolean;
+ /** Rows are on screen (possibly the local copy) and a refresh is in flight. */
+ isRefreshing: boolean;
/**
* Optimistically flip a just-replied topic to `running` so it moves out of
* "unread" and into the running card the instant the user hits send β€” then
@@ -29,51 +24,39 @@ export interface HomeInboxTopics {
unread: InboxTopic[];
}
+const EMPTY: InboxTopic[] = [];
+
/**
* Account-wide topic feed for the home inbox. Deliberately NOT reusing
* `HomeRepository.getUnreadCounts()` β€” that one excludes cron/task-triggered
* topics (it powers a sidebar badge), which are exactly the ones an agent
* inbox must surface.
+ *
+ * The rows are a replica: a reload paints the last feed from the local copy
+ * and the server only confirms it.
*/
export const useHomeInboxTopics = (isLogin: boolean | undefined): HomeInboxTopics => {
- const { data, error, isLoading, mutate } = useClientDataSWR(
- isLogin ? homeInboxKeys.topics(isLogin) : null,
- // `withLastMessage` is what makes an unread row readable: the card shows what
- // the agent actually said, not just the topic title it was filed under.
- () => topicService.queryTopics({ statuses: INBOX_STATUSES, withLastMessage: true }),
- // A live overview: refetch on focus almost immediately (default throttle is
- // 5min) so a run that just finished shows up the instant the user looks.
- { focusThrottleInterval: 1000 },
+ const { error, isValidating, revalidate } = useHomeStore((s) => s.useFetchHomeInboxTopics)(
+ isLogin,
);
+ const promoteToRunning = useHomeStore((s) => s.promoteInboxTopicToRunning);
+ const data = useHomeStore(homeInboxSelectors.inboxTopics);
// Only a first-load failure is a hard error. A background poll error while we
// still hold rows keeps the stale list instead of flapping to "nothing here".
const hasHardError = Boolean(error) && data === undefined;
- const topics = useMemo(() => (data ?? []) as InboxTopic[], [data]);
+ const topics = data ?? EMPTY;
return useMemo(
() => ({
error: hasHardError ? error : undefined,
- isInit: !isLoading && !hasHardError,
- promoteToRunning: (topicId: string) => {
- // Instant: patch the cached row to `running` with no refetch, so the UI
- // responds on the same tick as the send. The server's own status write
- // lands a beat later, so reconcile after a short delay rather than
- // revalidating now and reading the row still `unread` (which would snap
- // it back to unread and look like the send did nothing).
- void mutate(
- (rows) =>
- (rows ?? []).map((row) =>
- row.id === topicId ? { ...row, status: 'running' as ChatTopicStatus } : row,
- ),
- { revalidate: false },
- );
- setTimeout(() => void mutate(), 1000);
- },
- reload: mutate,
+ isInit: (isLogin !== true || data !== undefined) && !hasHardError,
+ isRefreshing: isValidating && data !== undefined,
+ promoteToRunning,
+ reload: () => void revalidate(),
running: topics.filter((t) => t.status === 'running'),
unread: topics.filter((t) => t.status === 'unread'),
}),
- [topics, error, hasHardError, isLoading, mutate],
+ [data, topics, error, hasHardError, isLogin, isValidating, promoteToRunning, revalidate],
);
};
diff --git a/src/features/ResourceHome/Home/RecentFiles.tsx b/src/features/ResourceHome/Home/RecentFiles.tsx
index 907afc6553a..bd7db2ab245 100644
--- a/src/features/ResourceHome/Home/RecentFiles.tsx
+++ b/src/features/ResourceHome/Home/RecentFiles.tsx
@@ -15,9 +15,8 @@ import {
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useClientDataSWR } from '@/libs/swr';
-import { resourceKeys } from '@/libs/swr/keys';
-import { fileService } from '@/services/file';
+import { useHomeStore } from '@/store/home';
+import { homeRecentSelectors } from '@/store/home/selectors';
import { FilesTabs } from '@/types/files';
import SectionTitle from './SectionTitle';
@@ -93,18 +92,25 @@ const RecentFiles = memo(() => {
? getResourceQueryVisibility(undefined, listVisibility)
: undefined;
- const { data, error, isLoading, mutate } = useClientDataSWR(
- resourceKeys.recentFiles(workspaceId ?? null, visibility),
- () => fileService.getRecentFiles(8, visibility),
- );
+ // A replica partitioned by user + workspace: a reload paints the last cards
+ // from the local copy while the server confirms them.
+ const { error, isValidating, revalidate } = useHomeStore((s) => s.useFetchResourceRecentFiles)({
+ visibility,
+ });
+ const data = useHomeStore(homeRecentSelectors.resourceFiles({ visibility }));
+ const isLoading = data === undefined && !error;
if (!isLoading && !error && !data?.length) return null;
return (
<Flexbox gap={12}>
- <SectionTitle title={t('home.recentFiles')} viewAllUrl={`/resource/${FilesTabs.All}`} />
+ <SectionTitle
+ loading={isValidating && !!data?.length}
+ title={t('home.recentFiles')}
+ viewAllUrl={`/resource/${FilesTabs.All}`}
+ />
{error && !data?.length ? (
- <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} />
) : isLoading ? (
<ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.files} />
) : (
diff --git a/src/features/ResourceHome/Home/RecentPages.tsx b/src/features/ResourceHome/Home/RecentPages.tsx
index 2734d73a0d0..27731995e19 100644
--- a/src/features/ResourceHome/Home/RecentPages.tsx
+++ b/src/features/ResourceHome/Home/RecentPages.tsx
@@ -15,9 +15,8 @@ import {
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useClientDataSWR } from '@/libs/swr';
-import { resourceKeys } from '@/libs/swr/keys';
-import { fileService } from '@/services/file';
+import { useHomeStore } from '@/store/home';
+import { homeRecentSelectors } from '@/store/home/selectors';
import SectionTitle from './SectionTitle';
@@ -81,24 +80,31 @@ const RecentPages = memo(() => {
? getResourceQueryVisibility(undefined, listVisibility)
: undefined;
- const { data, error, isLoading, mutate } = useClientDataSWR(
- resourceKeys.recentPages(workspaceId ?? null, visibility),
- () => fileService.getRecentPages(6, visibility),
- );
+ // A replica partitioned by user + workspace: a reload paints the last cards
+ // from the local copy while the server confirms them.
+ const { error, isValidating, revalidate } = useHomeStore((s) => s.useFetchResourceRecentPages)({
+ visibility,
+ });
+ const data = useHomeStore(homeRecentSelectors.resourcePages({ visibility }));
+ const isLoading = data === undefined && !error;
if (!isLoading && !error && !data?.length) return null;
return (
<Flexbox gap={12}>
- <SectionTitle title={t('home.recentPages')} viewAllUrl={'/resource/page'} />
+ <SectionTitle
+ loading={isValidating && !!data?.length}
+ title={t('home.recentPages')}
+ viewAllUrl={'/resource/page'}
+ />
{error && !data?.length ? (
- <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} />
) : isLoading ? (
<ResourceSectionSkeleton {...RESOURCE_HOME_SECTIONS.pages} />
) : (
<div className={styles.grid}>
{data?.map((item) => {
- const emoji = (item.metadata as { emoji?: string } | null)?.emoji;
+ const { emoji } = item;
return (
<button
className={styles.card}
diff --git a/src/features/ResourceHome/Home/SectionTitle.tsx b/src/features/ResourceHome/Home/SectionTitle.tsx
index d236a3898b6..26242346508 100644
--- a/src/features/ResourceHome/Home/SectionTitle.tsx
+++ b/src/features/ResourceHome/Home/SectionTitle.tsx
@@ -1,6 +1,6 @@
'use client';
-import { createStaticStyles, Flexbox } from '@lobehub/ui';
+import { createStaticStyles, Flexbox, Spin } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,18 +30,23 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
interface SectionTitleProps {
+ /** The cards are the local copy and a refresh is in flight. */
+ loading?: boolean;
title: string;
/** Target path of the "view all" affordance; omitted when there is no fuller view. */
viewAllUrl?: string;
}
-const SectionTitle = memo<SectionTitleProps>(({ title, viewAllUrl }) => {
+const SectionTitle = memo<SectionTitleProps>(({ loading, title, viewAllUrl }) => {
const { t } = useTranslation('file');
const navigate = useWorkspaceAwareNavigate();
return (
<Flexbox horizontal align={'center'} justify={'space-between'}>
- <h2 className={styles.title}>{title}</h2>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <h2 className={styles.title}>{title}</h2>
+ {loading && <Spin size="small" variant="network" />}
+ </Flexbox>
{viewAllUrl && (
<button className={styles.viewAll} type={'button'} onClick={() => navigate(viewAllUrl)}>
{t('home.viewAll')}
diff --git a/src/hooks/useHomeDailyBrief.ts b/src/hooks/useHomeDailyBrief.ts
index c18e904cfbc..3ddfbc0a6b9 100644
--- a/src/hooks/useHomeDailyBrief.ts
+++ b/src/hooks/useHomeDailyBrief.ts
@@ -1,8 +1,7 @@
-import { useClientDataSWR } from '@/libs/swr';
-import { homeKeys } from '@/libs/swr/keys';
-import { homeService } from '@/services/home';
+import { useHomeStore } from '@/store/home';
+import { homeInboxSelectors } from '@/store/home/selectors';
import { useUserStore } from '@/store/user';
-import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { authSelectors } from '@/store/user/selectors';
interface HomeDailyBriefPair {
hint: string;
@@ -16,18 +15,18 @@ interface UseHomeDailyBriefResult {
pairs: HomeDailyBriefPair[];
}
+const EMPTY: HomeDailyBriefPair[] = [];
+
+/**
+ * The brief is a replica partitioned by the cache scope (user + workspace), so
+ * an account switch never serves the previous user's pairs, and a reload shows
+ * the last pairs on the first frame while the server confirms them.
+ */
export const useHomeDailyBrief = (): UseHomeDailyBriefResult => {
const isLogin = useUserStore(authSelectors.isLogin);
- const userId = useUserStore(userProfileSelectors.userId);
-
- // Scope the SWR key by userId so an account switch within the same SPA
- // session (or signing in as a different user after sign-out) refetches
- // and never serves the previous user's cached pairs from this slot.
- const { data } = useClientDataSWR(isLogin && userId ? homeKeys.dailyBrief(userId) : null, () =>
- homeService.getDailyBrief(),
- );
- const pairs = data?.pairs ?? [];
+ useHomeStore((s) => s.useFetchHomeDailyBrief)(isLogin);
+ const pairs = useHomeStore(homeInboxSelectors.dailyBrief)?.pairs ?? EMPTY;
return {
currentPair: pairs[0],
diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.ts
index c8d8d3aaf2a..cc1161f9802 100644
--- a/src/libs/swr/keys.test.ts
+++ b/src/libs/swr/keys.test.ts
@@ -8,7 +8,6 @@ import {
isAcceptanceListKey,
isDocumentCommentKeyForEvent,
recentKeys,
- resourceKeys,
taskKeys,
verifyKeys,
workKeys,
@@ -110,31 +109,6 @@ describe('workKeys', () => {
});
});
-describe('resourceKeys', () => {
- it('keeps Private and Workspace recent sections in separate cache entries', () => {
- expect(resourceKeys.recentPages('workspace-1', 'private')).not.toEqual(
- resourceKeys.recentPages('workspace-1', 'public'),
- );
- expect(resourceKeys.recentFiles('workspace-1', 'private')).not.toEqual(
- resourceKeys.recentFiles('workspace-1', 'public'),
- );
- });
-
- // Regression: without the workspace in the key, switching workspaces served
- // the previous workspace's rows out of cache before revalidation landed.
- it('keeps every Resources cache entry scoped to its workspace', () => {
- expect(resourceKeys.recentFiles('workspace-1', 'public')).not.toEqual(
- resourceKeys.recentFiles('workspace-2', 'public'),
- );
- expect(resourceKeys.recentPages('workspace-1', 'public')).not.toEqual(
- resourceKeys.recentPages('workspace-2', 'public'),
- );
- expect(resourceKeys.recentFiles(null, undefined)).not.toEqual(
- resourceKeys.recentFiles('workspace-1', undefined),
- );
- });
-});
-
describe('isDocumentCommentKeyForEvent', () => {
const event = {
documentId: 'document-1',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 594947a057a..94b642eec2c 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -380,12 +380,6 @@ export const briefKeys = {
]),
};
-// ---- home inbox ---------------------------------------------------------
-export const homeInboxKeys = {
- /** Account-wide topics powering the home inbox (running + unread + needs-input). */
- topics: def('home:inboxTopics', (isLogin: boolean) => ['home:inboxTopics', isLogin]),
-};
-
// ---- agent config / available / search ----------------------------------
export const agentConfigKeys = {
available: def('agent:available', () => ['agent:available']),
@@ -1048,10 +1042,6 @@ export const topicActionKeys = {
};
// ---- misc remaining domains ---------------------------------------------
-export const homeKeys = {
- dailyBrief: def('home:dailyBrief', (userId: string) => ['home:dailyBrief', userId]),
-};
-
/**
* Daily task-template recommendation cache schema version. Bump this when the
* persisted recommendation row shape changes incompatibly so desktop clients
@@ -1077,25 +1067,6 @@ export const resourceKeys = {
params,
workspaceId,
]),
- // Every Resources cache entry is workspace-scoped: the same visibility means
- // different rows in each workspace, so leaving `workspaceId` out of the key
- // makes a workspace switch serve the previous workspace's rows from cache.
- recentFiles: def(
- 'resource:recentFiles',
- (workspaceId: string | null, visibility?: 'private' | 'public') => [
- 'resource:recentFiles',
- workspaceId,
- visibility ?? null,
- ],
- ),
- recentPages: def(
- 'resource:recentPages',
- (workspaceId: string | null, visibility?: 'private' | 'public') => [
- 'resource:recentPages',
- workspaceId,
- visibility ?? null,
- ],
- ),
};
export const recommendationsKeys = {
heteroDetections: def('recommendations:heteroDetections', () => [
@@ -1163,7 +1134,6 @@ export const swrKeys = {
goal: goalKeys,
global: globalKeys,
group: groupKeys,
- home: homeKeys,
image: imageKeys,
imessage: imessageKeys,
inbox: inboxKeys,
diff --git a/src/store/home/initialState.ts b/src/store/home/initialState.ts
index 43e8284cf9b..f6d40f883de 100644
--- a/src/store/home/initialState.ts
+++ b/src/store/home/initialState.ts
@@ -2,6 +2,8 @@ import { type AgentListState } from './slices/agentList/initialState';
import { initialAgentListState } from './slices/agentList/initialState';
import { type HomeInputState } from './slices/homeInput/initialState';
import { initialHomeInputState } from './slices/homeInput/initialState';
+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 RecentState } from './slices/recent/initialState';
@@ -10,11 +12,12 @@ import { type SidebarUIState } from './slices/sidebarUI/initialState';
import { initialSidebarUIState } from './slices/sidebarUI/initialState';
export interface HomeStoreState
- extends AgentListState, RecentState, HomeInputState, LabelState, SidebarUIState {}
+ extends AgentListState, RecentState, HomeInboxState, HomeInputState, LabelState, SidebarUIState {}
export const initialState: HomeStoreState = {
...initialAgentListState,
...initialRecentState,
+ ...initialHomeInboxState,
...initialHomeInputState,
...initialLabelState,
...initialSidebarUIState,
diff --git a/src/store/home/selectors.ts b/src/store/home/selectors.ts
index 0e2669553ab..6fed15d3812 100644
--- a/src/store/home/selectors.ts
+++ b/src/store/home/selectors.ts
@@ -1,3 +1,4 @@
export * from './slices/agentList/selectors';
+export * from './slices/inbox/selectors';
export * from './slices/label/selectors';
export * from './slices/recent/selectors';
diff --git a/src/store/home/slices/inbox/action.test.ts b/src/store/home/slices/inbox/action.test.ts
new file mode 100644
index 00000000000..0741104aef6
--- /dev/null
+++ b/src/store/home/slices/inbox/action.test.ts
@@ -0,0 +1,161 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The home inbox feed and the daily brief are replicas: a reload paints the
+ * persisted value on the first frame and the server only confirms it.
+ */
+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 { homeService } from '@/services/home';
+import { type TopicListItem, topicService } from '@/services/topic';
+import { useHomeStore } from '@/store/home';
+import { initialHomeInboxState } from '@/store/home/slices/inbox/initialState';
+import {
+ HOME_DAILY_BRIEF_KEY,
+ HOME_INBOX_KEY,
+ homeDailyBriefResource,
+ homeInboxTopicsResource,
+} from '@/store/home/slices/inbox/projection';
+import { homeInboxSelectors } from '@/store/home/slices/inbox/selectors';
+
+const topic = (id: string, status: TopicListItem['status']): TopicListItem =>
+ ({ createdAt: 0, id, status, title: id, updatedAt: 0 }) as unknown as TopicListItem;
+
+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>(() => {});
+
+beforeEach(() => {
+ useScope(`inbox-user-${randomUUID()}:personal`);
+ act(() => useHomeStore.setState({ ...initialHomeInboxState }));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ localStorage.clear();
+});
+
+describe('home inbox replica', () => {
+ it('paints the persisted inbox rows before the network answers', async () => {
+ await homeInboxTopicsResource.storage!.set(
+ { queryKey: HOME_INBOX_KEY, scope },
+ { data: [topic('a', 'unread'), topic('b', 'running')], updatedAt: 1 },
+ );
+ vi.spyOn(topicService, 'queryTopics').mockImplementation(never);
+
+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchHomeInboxTopics)(true), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(homeInboxSelectors.inboxTopics(useHomeStore.getState())?.map((t) => t.id)).toEqual([
+ 'a',
+ 'b',
+ ]),
+ );
+ expect(result.current.isValidating).toBe(true);
+ });
+
+ it('persists a fetched feed under the active scope only', async () => {
+ vi.spyOn(topicService, 'queryTopics').mockResolvedValue([topic('a', 'unread')]);
+
+ renderHook(() => useHomeStore((s) => s.useFetchHomeInboxTopics)(true), { wrapper });
+
+ await waitFor(async () =>
+ expect(
+ (await homeInboxTopicsResource.storage!.get({ queryKey: HOME_INBOX_KEY, scope }))?.data,
+ ).toHaveLength(1),
+ );
+ expect(
+ await homeInboxTopicsResource.storage!.get({
+ queryKey: HOME_INBOX_KEY,
+ scope: 'someone-else:personal',
+ }),
+ ).toBeUndefined();
+ });
+
+ it('does not fetch while logged out', () => {
+ const queryTopics = vi.spyOn(topicService, 'queryTopics');
+ renderHook(() => useHomeStore((s) => s.useFetchHomeInboxTopics)(false), { wrapper });
+ expect(queryTopics).not.toHaveBeenCalled();
+ });
+
+ it('promotes a replied topic to running at once, then reconciles with the server', async () => {
+ const queryTopics = vi
+ .spyOn(topicService, 'queryTopics')
+ .mockResolvedValueOnce([topic('a', 'unread')])
+ .mockResolvedValue([topic('a', 'running')]);
+ renderHook(() => useHomeStore((s) => s.useFetchHomeInboxTopics)(true), { wrapper });
+ await waitFor(() =>
+ expect(homeInboxSelectors.inboxTopics(useHomeStore.getState())).toBeDefined(),
+ );
+
+ act(() => useHomeStore.getState().promoteInboxTopicToRunning('a'));
+
+ expect(homeInboxSelectors.inboxTopics(useHomeStore.getState())?.[0].status).toBe('running');
+ await waitFor(() => expect(queryTopics).toHaveBeenCalledTimes(2), { timeout: 3000 });
+ expect(homeInboxSelectors.inboxTopics(useHomeStore.getState())?.[0].status).toBe('running');
+ });
+});
+
+describe('home daily brief replica', () => {
+ it('paints the persisted brief before the network answers', async () => {
+ await homeDailyBriefResource.storage!.set(
+ { queryKey: HOME_DAILY_BRIEF_KEY, scope },
+ { data: { pairs: [{ hint: 'cached hint', welcome: 'cached welcome' }] }, updatedAt: 1 },
+ );
+ vi.spyOn(homeService, 'getDailyBrief').mockImplementation(never);
+
+ renderHook(() => useHomeStore((s) => s.useFetchHomeDailyBrief)(true), { wrapper });
+
+ await waitFor(() =>
+ expect(homeInboxSelectors.dailyBrief(useHomeStore.getState())?.pairs[0].welcome).toBe(
+ 'cached welcome',
+ ),
+ );
+ });
+
+ it("never paints another identity's brief", async () => {
+ await homeDailyBriefResource.storage!.set(
+ { queryKey: HOME_DAILY_BRIEF_KEY, scope: 'previous-user:personal' },
+ { data: { pairs: [{ hint: 'theirs', welcome: 'theirs' }] }, updatedAt: 1 },
+ );
+ vi.spyOn(homeService, 'getDailyBrief').mockResolvedValue({
+ pairs: [{ hint: 'mine', welcome: 'mine' }],
+ });
+
+ renderHook(() => useHomeStore((s) => s.useFetchHomeDailyBrief)(true), { wrapper });
+
+ await waitFor(() =>
+ expect(homeInboxSelectors.dailyBrief(useHomeStore.getState())?.pairs[0].welcome).toBe('mine'),
+ );
+ });
+});
diff --git a/src/store/home/slices/inbox/action.ts b/src/store/home/slices/inbox/action.ts
new file mode 100644
index 00000000000..7d9cefb5235
--- /dev/null
+++ b/src/store/home/slices/inbox/action.ts
@@ -0,0 +1,94 @@
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { type HomeDailyBriefResponse, homeService } from '@/services/home';
+import { type TopicListItem, topicService } from '@/services/topic';
+import type { HomeStore } from '@/store/home/store';
+import type { StoreSetter } from '@/store/types';
+import { type ChatTopicStatus } from '@/types/topic';
+import { setNamespace } from '@/utils/storeDebug';
+
+import {
+ HOME_INBOX_KEY,
+ homeDailyBriefResource,
+ type HomeFeedParams,
+ homeInboxTopicsResource,
+} from './projection';
+
+const n = setNamespace('homeInbox');
+
+/**
+ * Everything the home inbox needs from topics, in one round trip. `queryTopics`
+ * filters server-side by status, so widening this list costs nothing extra.
+ */
+const INBOX_STATUSES: ChatTopicStatus[] = ['running', 'unread'];
+
+const FEED_PARAMS: HomeFeedParams = {};
+
+/** How long the server's own status write gets before the inbox reconciles with it. */
+const PROMOTE_RECONCILE_DELAY = 1000;
+
+type Setter = StoreSetter<HomeStore>;
+export const createHomeInboxSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
+ new HomeInboxActionImpl(set, get, _api);
+
+export class HomeInboxActionImpl {
+ readonly #dailyBrief;
+ readonly #inboxTopics;
+
+ constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
+ void _api;
+ this.#inboxTopics = createReplicaSlice(homeInboxTopicsResource, {
+ actionPrefix: n('inboxTopics'),
+ // `withLastMessage` is what makes an unread row readable: the card shows what
+ // the agent actually said, not just the topic title it was filed under.
+ fetcher: () => topicService.queryTopics({ statuses: INBOX_STATUSES, withLastMessage: true }),
+ get,
+ set,
+ stateKey: 'homeInboxTopicsReplica',
+ view: recordLens<HomeStore, TopicListItem[]>('homeInboxTopicsMap'),
+ });
+ this.#dailyBrief = createReplicaSlice(homeDailyBriefResource, {
+ actionPrefix: n('dailyBrief'),
+ fetcher: () => homeService.getDailyBrief(),
+ get,
+ set,
+ stateKey: 'homeDailyBriefReplica',
+ view: recordLens<HomeStore, HomeDailyBriefResponse>('homeDailyBriefMap'),
+ });
+ }
+
+ /**
+ * Flip a just-replied topic to `running` on the same tick as the send, so it
+ * moves out of "unread" into the running card. The server's own status write
+ * lands a beat later, so reconcile after a short delay rather than now (an
+ * immediate refetch would read the row still `unread` and snap it back).
+ */
+ promoteInboxTopicToRunning = (topicId: string): void => {
+ this.#inboxTopics.update(
+ HOME_INBOX_KEY,
+ (rows) =>
+ rows?.map((row) =>
+ row.id === topicId ? { ...row, status: 'running' as ChatTopicStatus } : row,
+ ),
+ { persist: false },
+ );
+ setTimeout(() => void this.#inboxTopics.revalidate(HOME_INBOX_KEY), PROMOTE_RECONCILE_DELAY);
+ };
+
+ /** Read the pairs with `homeInboxSelectors.dailyBrief`. */
+ useFetchHomeDailyBrief = (isLogin: boolean | undefined): ReplicaSyncResult =>
+ this.#dailyBrief.useSync(FEED_PARAMS, { enabled: isLogin === true });
+
+ /**
+ * Account-wide topic feed for the home inbox. A live overview: it refetches on
+ * focus almost immediately (the default throttle is 5 min), so a run that just
+ * finished shows up the instant the user looks. Read the rows with
+ * `homeInboxSelectors.inboxTopics`.
+ */
+ useFetchHomeInboxTopics = (isLogin: boolean | undefined): ReplicaSyncResult =>
+ this.#inboxTopics.useSync(FEED_PARAMS, {
+ enabled: isLogin === true,
+ focusThrottleInterval: 1000,
+ });
+}
+
+export type HomeInboxAction = Pick<HomeInboxActionImpl, keyof HomeInboxActionImpl>;
diff --git a/src/store/home/slices/inbox/initialState.ts b/src/store/home/slices/inbox/initialState.ts
new file mode 100644
index 00000000000..cf8766a1810
--- /dev/null
+++ b/src/store/home/slices/inbox/initialState.ts
@@ -0,0 +1,19 @@
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type { HomeDailyBriefResponse } from '@/services/home';
+import type { TopicListItem } from '@/services/topic';
+
+export interface HomeInboxState {
+ /** Daily brief, the view of the `homeDailyBrief` replica. */
+ homeDailyBriefMap: Record<string, HomeDailyBriefResponse>;
+ homeDailyBriefReplica: ReplicaState<HomeDailyBriefResponse>;
+ /** Inbox topics (running + unread), the view of the `homeInboxTopics` replica. */
+ homeInboxTopicsMap: Record<string, TopicListItem[]>;
+ homeInboxTopicsReplica: ReplicaState<TopicListItem[]>;
+}
+
+export const initialHomeInboxState: HomeInboxState = {
+ homeDailyBriefMap: {},
+ homeDailyBriefReplica: createReplicaState(),
+ homeInboxTopicsMap: {},
+ homeInboxTopicsReplica: createReplicaState(),
+};
diff --git a/src/store/home/slices/inbox/projection.ts b/src/store/home/slices/inbox/projection.ts
new file mode 100644
index 00000000000..bc9c7645204
--- /dev/null
+++ b/src/store/home/slices/inbox/projection.ts
@@ -0,0 +1,29 @@
+import { defineReplica } from '@/libs/replica';
+import type { HomeDailyBriefResponse } from '@/services/home';
+import type { TopicListItem } from '@/services/topic';
+
+/** The inbox feed and the daily brief are one entry per scope (user + workspace). */
+export const HOME_INBOX_KEY = 'inbox';
+export const HOME_DAILY_BRIEF_KEY = 'today';
+
+export type HomeFeedParams = Record<string, never>;
+
+/**
+ * Running and unread topics of the home inbox, each with its last assistant
+ * reply. Up to a few hundred rows with ~2 KB previews, so IndexedDB rather than
+ * localStorage.
+ */
+export const homeInboxTopicsResource = defineReplica<HomeFeedParams, TopicListItem[]>({
+ key: () => HOME_INBOX_KEY,
+ name: 'homeInboxTopics',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Welcome line + input hint pairs from the daily generator: a few short strings. */
+export const homeDailyBriefResource = defineReplica<HomeFeedParams, HomeDailyBriefResponse>({
+ key: () => HOME_DAILY_BRIEF_KEY,
+ name: 'homeDailyBrief',
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/home/slices/inbox/selectors.ts b/src/store/home/slices/inbox/selectors.ts
new file mode 100644
index 00000000000..a2ea0968132
--- /dev/null
+++ b/src/store/home/slices/inbox/selectors.ts
@@ -0,0 +1,14 @@
+import { type HomeStore } from '@/store/home/store';
+
+import { HOME_DAILY_BRIEF_KEY, HOME_INBOX_KEY } from './projection';
+
+/** Inbox topics; `undefined` until hydrated or fetched. */
+const inboxTopics = (s: HomeStore) => s.homeInboxTopicsMap[HOME_INBOX_KEY];
+
+/** Daily brief; `undefined` until hydrated or fetched. */
+const dailyBrief = (s: HomeStore) => s.homeDailyBriefMap[HOME_DAILY_BRIEF_KEY];
+
+export const homeInboxSelectors = {
+ dailyBrief,
+ inboxTopics,
+};
diff --git a/src/store/home/slices/recent/action.test.ts b/src/store/home/slices/recent/action.test.ts
index e1ff259ffe7..af608761085 100644
--- a/src/store/home/slices/recent/action.test.ts
+++ b/src/store/home/slices/recent/action.test.ts
@@ -15,11 +15,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
+import { fileService } from '@/services/file';
import { recentService } from '@/services/recent';
import { taskService } from '@/services/task';
import { useHomeStore } from '@/store/home';
import { createRecentQueryKey, initialRecentState } from '@/store/home/slices/recent/initialState';
-import { recentListResource } from '@/store/home/slices/recent/projection';
+import {
+ recentFileListResource,
+ recentListResource,
+ recentPageListResource,
+} from '@/store/home/slices/recent/projection';
import { homeRecentSelectors } from '@/store/home/slices/recent/selectors';
const item = (id: string, title: string, type: RecentItem['type'] = 'task'): RecentItem => ({
@@ -92,6 +97,8 @@ const load = async (sidebar: RecentItem[], drawer?: RecentItem[]) => {
beforeEach(() => {
useScope(`recent-user-${randomUUID()}:personal`);
act(() => useHomeStore.setState({ ...initialRecentState }));
+ vi.spyOn(fileService, 'getRecentFiles').mockImplementation(() => new Promise(() => {}));
+ vi.spyOn(fileService, 'getRecentPages').mockImplementation(() => new Promise(() => {}));
});
afterEach(() => {
@@ -216,3 +223,149 @@ describe('recents replica', () => {
await secondRename;
});
});
+
+type RecentFileRow = Awaited<ReturnType<typeof fileService.getRecentFiles>>[number];
+type RecentPageRow = Awaited<ReturnType<typeof fileService.getRecentPages>>[number];
+
+const fileRow = (id: string, url: string): RecentFileRow =>
+ ({
+ chunkCount: 3,
+ createdAt: new Date(0),
+ fileType: 'image/png',
+ id,
+ name: `${id}.png`,
+ url,
+ }) as unknown as RecentFileRow;
+
+const pageRow = (id: string): RecentPageRow =>
+ ({
+ content: 'the whole page body',
+ editorData: { root: {} },
+ id,
+ metadata: { emoji: 'πŸ“„' },
+ name: id,
+ updatedAt: new Date(0),
+ }) as unknown as RecentPageRow;
+
+const storedRow = <T>(
+ resource: { storage?: { get: (key: { queryKey: string; scope: string }) => Promise<T> } },
+ queryKey: string,
+) => resource.storage!.get({ queryKey, scope });
+
+describe('resource home recents replica', () => {
+ it('paints the persisted file and page cards before the network answers', async () => {
+ await recentFileListResource.storage!.set(
+ { queryKey: 'private', scope },
+ {
+ data: [{ createdAt: new Date(0), fileType: 'image/png', id: 'f1', name: 'Cached file' }],
+ updatedAt: 1,
+ },
+ );
+ await recentPageListResource.storage!.set(
+ { queryKey: 'private', scope },
+ { data: [{ id: 'p1', name: 'Cached page', updatedAt: new Date(0) }], updatedAt: 1 },
+ );
+
+ const { result } = renderHook(
+ () => ({
+ files: useHomeStore((s) => s.useFetchResourceRecentFiles)({ visibility: 'private' }),
+ pages: useHomeStore((s) => s.useFetchResourceRecentPages)({ visibility: 'private' }),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => {
+ const state = useHomeStore.getState();
+ expect(homeRecentSelectors.resourceFiles({ visibility: 'private' })(state)?.[0].name).toBe(
+ 'Cached file',
+ );
+ expect(homeRecentSelectors.resourcePages({ visibility: 'private' })(state)?.[0].name).toBe(
+ 'Cached page',
+ );
+ });
+ expect(result.current.files.isValidating).toBe(true);
+ expect(result.current.pages.isValidating).toBe(true);
+ });
+
+ it('keeps each visibility in its own entry', async () => {
+ vi.mocked(fileService.getRecentPages).mockImplementation(async (_limit, visibility) => [
+ pageRow(`page-${visibility}`),
+ ]);
+
+ renderHook(
+ () => {
+ useHomeStore((s) => s.useFetchResourceRecentPages)({ visibility: 'private' });
+ useHomeStore((s) => s.useFetchResourceRecentPages)({ visibility: 'public' });
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => {
+ const state = useHomeStore.getState();
+ expect(homeRecentSelectors.resourcePages({ visibility: 'private' })(state)?.[0].id).toBe(
+ 'page-private',
+ );
+ expect(homeRecentSelectors.resourcePages({ visibility: 'public' })(state)?.[0].id).toBe(
+ 'page-public',
+ );
+ });
+ });
+
+ it('persists slim page cards, never the page body', async () => {
+ vi.mocked(fileService.getRecentPages).mockResolvedValue([pageRow('p1')]);
+
+ renderHook(() => useHomeStore((s) => s.useFetchResourceRecentPages)({}), { wrapper });
+
+ await waitFor(async () =>
+ expect((await storedRow(recentPageListResource, 'all'))?.data).toEqual([
+ { emoji: 'πŸ“„', id: 'p1', name: 'p1', updatedAt: new Date(0) },
+ ]),
+ );
+ });
+
+ it('drops credential-bearing file URLs from the persisted copy only', async () => {
+ vi.mocked(fileService.getRecentFiles).mockResolvedValue([
+ fileRow('signed', 'https://s3.example.com/a.png?X-Amz-Signature=secret'),
+ fileRow('proxy', 'https://app.example.com/f/proxy'),
+ ]);
+
+ renderHook(() => useHomeStore((s) => s.useFetchResourceRecentFiles)({}), { wrapper });
+
+ await waitFor(async () =>
+ expect((await storedRow(recentFileListResource, 'all'))?.data).toBeDefined(),
+ );
+ const persisted = (await storedRow(recentFileListResource, 'all'))!.data;
+ expect(persisted.map((card) => card.url)).toEqual([
+ undefined,
+ 'https://app.example.com/f/proxy',
+ ]);
+ expect(persisted[0]).not.toHaveProperty('chunkCount');
+ expect(JSON.stringify(localStorage)).not.toContain('X-Amz-Signature');
+ // The session still shows the thumbnail it was handed.
+ expect(
+ homeRecentSelectors
+ .resourceFiles({})(useHomeStore.getState())
+ ?.map((card) => card.url),
+ ).toEqual([
+ 'https://s3.example.com/a.png?X-Amz-Signature=secret',
+ 'https://app.example.com/f/proxy',
+ ]);
+ });
+
+ it("never paints another workspace's cards", async () => {
+ await recentFileListResource.storage!.set(
+ { queryKey: 'all', scope: `${scope}-other-workspace` },
+ {
+ data: [{ createdAt: new Date(0), fileType: 'image/png', id: 'x', name: 'Theirs' }],
+ updatedAt: 1,
+ },
+ );
+
+ const { result } = renderHook(() => useHomeStore((s) => s.useFetchResourceRecentFiles)({}), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.isHydrated).toBe(true));
+ expect(homeRecentSelectors.resourceFiles({})(useHomeStore.getState())).toBeUndefined();
+ });
+});
diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.ts
index ae81c75e43b..38611fa37a7 100644
--- a/src/store/home/slices/recent/action.ts
+++ b/src/store/home/slices/recent/action.ts
@@ -8,6 +8,7 @@ import {
type ReplicaSyncResult,
} from '@/libs/replica';
import { documentService } from '@/services/document';
+import { fileService } from '@/services/file';
import { RECENT_SIDEBAR_TYPES, recentService } from '@/services/recent';
import { taskService } from '@/services/task';
import { topicService } from '@/services/topic';
@@ -16,12 +17,26 @@ import type { StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
import { type RecentEntityRef, toRecentEntityRef } from './initialState';
-import { recentListResource } from './projection';
+import {
+ type RecentFileCard,
+ recentFileListResource,
+ recentListResource,
+ type RecentPageCard,
+ recentPageListResource,
+ type ResourceRecentParams,
+ toPersistedRecentFiles,
+ toRecentFileCard,
+ toRecentPageCard,
+} from './projection';
const n = setNamespace('recent');
/** Rows in the "all recents" drawer. */
export const ALL_RECENTS_LIMIT = 50;
+/** Cards in the resource home "Recent files" grid. */
+export const RESOURCE_RECENT_FILES_LIMIT = 8;
+/** Cards in the resource home "Recent pages" grid. */
+export const RESOURCE_RECENT_PAGES_LIMIT = 6;
interface RenameRecentParams {
id: string;
@@ -63,6 +78,8 @@ export class RecentActionImpl {
readonly #renameQueues = new Map<RecentEntityRef, Promise<unknown>>();
readonly #recentList;
readonly #recents;
+ readonly #resourceRecentFiles;
+ readonly #resourceRecentPages;
constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
void _api;
@@ -77,6 +94,29 @@ export class RecentActionImpl {
view: recordLens<HomeStore, RecentItem[]>('recentListMap'),
});
this.#recents = linkReplicaEntity<RecentItem>([this.#recentList]);
+ this.#resourceRecentFiles = createReplicaSlice(recentFileListResource, {
+ actionPrefix: n('resourceRecentFiles'),
+ fetcher: async ({ visibility }) =>
+ (await fileService.getRecentFiles(RESOURCE_RECENT_FILES_LIMIT, visibility)).map(
+ toRecentFileCard,
+ ),
+ get,
+ set,
+ stateKey: 'resourceRecentFilesReplica',
+ toPersisted: toPersistedRecentFiles,
+ view: recordLens<HomeStore, RecentFileCard[]>('resourceRecentFilesMap'),
+ });
+ this.#resourceRecentPages = createReplicaSlice(recentPageListResource, {
+ actionPrefix: n('resourceRecentPages'),
+ fetcher: async ({ visibility }) =>
+ (await fileService.getRecentPages(RESOURCE_RECENT_PAGES_LIMIT, visibility)).map(
+ toRecentPageCard,
+ ),
+ get,
+ set,
+ stateKey: 'resourceRecentPagesReplica',
+ view: recordLens<HomeStore, RecentPageCard[]>('resourceRecentPagesMap'),
+ });
}
closeAllRecentsDrawer = (): void => {
@@ -134,6 +174,14 @@ export class RecentActionImpl {
useFetchAllRecents = (open: boolean): ReplicaSyncResult =>
this.#recentList.useSync({ limit: ALL_RECENTS_LIMIT }, { enabled: open });
+ /** Resource home "Recent files". Read them with `homeRecentSelectors.resourceFiles`. */
+ useFetchResourceRecentFiles = (params: ResourceRecentParams): ReplicaSyncResult =>
+ this.#resourceRecentFiles.useSync(params);
+
+ /** Resource home "Recent pages". Read them with `homeRecentSelectors.resourcePages`. */
+ useFetchResourceRecentPages = (params: ResourceRecentParams): ReplicaSyncResult =>
+ this.#resourceRecentPages.useSync(params);
+
/**
* Sidebar recents. Asks for `limit + 1` rows to know whether "view all" is
* needed; read them with `homeRecentSelectors.query`.
diff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.ts
index 8d2dd83d0d2..4363a22fe3f 100644
--- a/src/store/home/slices/recent/initialState.ts
+++ b/src/store/home/slices/recent/initialState.ts
@@ -2,6 +2,8 @@ import type { RecentItem } from '@lobechat/types';
import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type { RecentFileCard, RecentPageCard } from './projection';
+
export { createRecentQueryKey } from './projection';
/** `${type}:${id}`: ids of different entity types can collide. */
@@ -16,10 +18,20 @@ export interface RecentState {
recentListMap: Record<string, RecentItem[]>;
/** Replica bookkeeping for `recentListMap`. */
recentListReplica: ReplicaState<RecentItem[]>;
+ /** Resource home "Recent files" per visibility, the view of the `resourceRecentFiles` replica. */
+ resourceRecentFilesMap: Record<string, RecentFileCard[]>;
+ resourceRecentFilesReplica: ReplicaState<RecentFileCard[]>;
+ /** Resource home "Recent pages" per visibility, the view of the `resourceRecentPages` replica. */
+ resourceRecentPagesMap: Record<string, RecentPageCard[]>;
+ resourceRecentPagesReplica: ReplicaState<RecentPageCard[]>;
}
export const initialRecentState: RecentState = {
allRecentsDrawerOpen: false,
recentListMap: {},
recentListReplica: createReplicaState(),
+ resourceRecentFilesMap: {},
+ resourceRecentFilesReplica: createReplicaState(),
+ resourceRecentPagesMap: {},
+ resourceRecentPagesReplica: createReplicaState(),
};
diff --git a/src/store/home/slices/recent/projection.ts b/src/store/home/slices/recent/projection.ts
index 26729c59f5b..b2f39652979 100644
--- a/src/store/home/slices/recent/projection.ts
+++ b/src/store/home/slices/recent/projection.ts
@@ -20,3 +20,87 @@ export const recentListResource = defineReplica<RecentListParams, RecentItem[]>(
storage: 'localStorage',
version: 1,
});
+
+export interface ResourceRecentParams {
+ /** Workspace visibility filter; personal mode sends none. */
+ visibility?: 'private' | 'public';
+}
+
+/** One resource-home recents query per visibility; the cache scope already carries the workspace. */
+export const resourceRecentKey = ({ visibility }: ResourceRecentParams): string =>
+ visibility ?? 'all';
+
+/** What a resource-home "Recent files" card renders. */
+export interface RecentFileCard {
+ createdAt: Date | string;
+ fileType?: string;
+ id: string;
+ name: string;
+ url?: string;
+}
+
+/** What a resource-home "Recent pages" card renders. */
+export interface RecentPageCard {
+ emoji?: string;
+ id: string;
+ name: string;
+ updatedAt: Date | string;
+}
+
+export const toRecentFileCard = ({
+ createdAt,
+ fileType,
+ id,
+ name,
+ url,
+}: RecentFileCard): RecentFileCard => ({ createdAt, fileType, id, name, url });
+
+export const toRecentPageCard = ({
+ id,
+ metadata,
+ name,
+ updatedAt,
+}: {
+ id: string;
+ metadata?: Record<string, any> | null;
+ name: string;
+ updatedAt: Date | string;
+}): RecentPageCard => {
+ const emoji = (metadata as { emoji?: unknown } | null | undefined)?.emoji;
+ return { emoji: typeof emoji === 'string' ? emoji : undefined, id, name, updatedAt };
+};
+
+/**
+ * A URL that carries a query string (a presigned storage URL in local dev) is a
+ * short-lived credential; the stable `/f/:id` proxy URL production returns has none.
+ */
+const isCredentialUrl = (url: string): boolean => {
+ try {
+ return new URL(url, 'http://localhost').search !== '';
+ } catch {
+ return true;
+ }
+};
+
+/** Persist file cards without credential-bearing URLs; the card falls back to its icon. */
+export const toPersistedRecentFiles = (cards: RecentFileCard[]): RecentFileCard[] =>
+ cards.map((card) => (card.url && isCredentialUrl(card.url) ? { ...card, url: undefined } : card));
+
+/**
+ * Resource home "Recent files". Slim cards only (no chunk / embedding status),
+ * localStorage so the section paints the last rows on the first frame.
+ */
+export const recentFileListResource = defineReplica<ResourceRecentParams, RecentFileCard[]>({
+ key: resourceRecentKey,
+ name: 'resourceRecentFiles',
+ storage: 'localStorage',
+ version: 1,
+});
+
+/** Resource home "Recent pages": slim cards, never the page body. */
+export const recentPageListResource = defineReplica<ResourceRecentParams, RecentPageCard[]>({
+ key: resourceRecentKey,
+ name: 'resourceRecentPages',
+ storage: 'localStorage',
+ version: 1,
+});
diff --git a/src/store/home/slices/recent/selectors.ts b/src/store/home/slices/recent/selectors.ts
index 558e31b3dd5..33efab78943 100644
--- a/src/store/home/slices/recent/selectors.ts
+++ b/src/store/home/slices/recent/selectors.ts
@@ -1,6 +1,7 @@
import { type HomeStore } from '@/store/home/store';
import { type RecentEntityRef, toRecentEntityRef } from './initialState';
+import { resourceRecentKey, type ResourceRecentParams } from './projection';
/** Items of one recents query; `undefined` until it is hydrated or fetched. */
const query = (queryKey: string) => (s: HomeStore) => s.recentListMap[queryKey];
@@ -8,7 +9,17 @@ const query = (queryKey: string) => (s: HomeStore) => s.recentListMap[queryKey];
const item = (queryKey: string, ref: RecentEntityRef) => (s: HomeStore) =>
s.recentListMap[queryKey]?.find((recent) => toRecentEntityRef(recent) === ref);
+/** Resource home recent files; `undefined` until hydrated or fetched. */
+const resourceFiles = (params: ResourceRecentParams) => (s: HomeStore) =>
+ s.resourceRecentFilesMap[resourceRecentKey(params)];
+
+/** Resource home recent pages; `undefined` until hydrated or fetched. */
+const resourcePages = (params: ResourceRecentParams) => (s: HomeStore) =>
+ s.resourceRecentPagesMap[resourceRecentKey(params)];
+
export const homeRecentSelectors = {
item,
query,
+ resourceFiles,
+ resourcePages,
};
diff --git a/src/store/home/store.ts b/src/store/home/store.ts
index 72050c3de90..4a552fc13ca 100644
--- a/src/store/home/store.ts
+++ b/src/store/home/store.ts
@@ -17,6 +17,8 @@ import { type GroupAction } from './slices/group/action';
import { createGroupSlice } from './slices/group/action';
import { type HomeInputAction } from './slices/homeInput/action';
import { createHomeInputSlice } from './slices/homeInput/action';
+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 RecentAction } from './slices/recent/action';
@@ -31,6 +33,7 @@ export interface HomeStore
AgentListAction,
GroupAction,
RecentAction,
+ HomeInboxAction,
HomeInputAction,
LabelAction,
SidebarUIAction,
@@ -40,6 +43,7 @@ export interface HomeStore
type HomeStoreAction = AgentListAction &
GroupAction &
RecentAction &
+ HomeInboxAction &
HomeInputAction &
LabelAction &
SidebarUIAction &
@@ -57,6 +61,7 @@ const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (
createAgentListSlice(...parameters),
createGroupSlice(...parameters),
createRecentSlice(...parameters),
+ createHomeInboxSlice(...parameters),
createHomeInputSlice(...parameters),
createLabelSlice(...parameters),
createSidebarUISlice(...parameters),