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(settings): move search channels, changelog, library file picker and local file tag thumbnails onto @lobechat/replica (#22874)

Arvin Xuf2bf7560c0f9
diff --git a/src/components/ChangelogModal/ChangelogContent.tsx b/src/components/ChangelogModal/ChangelogContent.tsx
index 72d8ad54a4c..e8002b1e6ff 100644
--- a/src/components/ChangelogModal/ChangelogContent.tsx
+++ b/src/components/ChangelogModal/ChangelogContent.tsx
@@ -3,18 +3,16 @@ import { Image } from '@lobehub/ui/mdx';
import { Fragment, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import { type Components } from 'react-markdown';
-import useSWR from 'swr';
import urlJoin from 'url-join';
import { CustomMDX } from '@/components/mdx';
import CollapsibleSection from '@/components/mdx/CollapsibleSection';
import remarkCollapsibleSections from '@/components/mdx/remarkCollapsibleSections';
import { OFFICIAL_SITE } from '@/const/url';
-import { changelogKeys } from '@/libs/swr/keys';
-import { lambdaClient } from '@/libs/trpc/client';
import { type Locales } from '@/locales/resources';
import { type ChangelogIndexItem } from '@/types/changelog';
+import { useChangelogModalPost } from './useChangelog';
import VersionTag from './VersionTag';
interface ChangelogContentProps {
@@ -27,9 +25,7 @@ interface PostItemProps extends ChangelogIndexItem {
}
const PostItem = ({ id, versionRange, locale, showDivider = true }: PostItemProps) => {
- const { data } = useSWR(changelogKeys.post(id, locale), async () => {
- return await lambdaClient.changelog.getPostById.query({ id, locale });
- });
+ const data = useChangelogModalPost(id, locale);
if (!data || !data.title) return null;
diff --git a/src/components/ChangelogModal/ChangelogModalContent.tsx b/src/components/ChangelogModal/ChangelogModalContent.tsx
index 05ce761f21c..d030250c45c 100644
--- a/src/components/ChangelogModal/ChangelogModalContent.tsx
+++ b/src/components/ChangelogModal/ChangelogModalContent.tsx
@@ -3,24 +3,19 @@
import { Center, Flexbox, ScrollArea } from '@lobehub/ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
-
-import { changelogKeys } from '@/libs/swr/keys';
-import { lambdaClient } from '@/libs/trpc/client';
import ChangelogContent from './ChangelogContent';
+import { useChangelogModalIndex } from './useChangelog';
const SCROLL_HEIGHT = 'min(80vh, 760px)';
const ChangelogModalContent = memo(() => {
const { t } = useTranslation('common');
- const { data, isLoading } = useSWR(changelogKeys.modalIndex(), () =>
- lambdaClient.changelog.getIndex.query(),
- );
+ const data = useChangelogModalIndex();
return (
<ScrollArea scrollFade style={{ height: SCROLL_HEIGHT }}>
- {isLoading || !data || data.length === 0 ? (
+ {!data || data.length === 0 ? (
<Center style={{ height: SCROLL_HEIGHT }}>{t('loading')}</Center>
) : (
<Flexbox gap={16} padding={16} style={{ width: '100%' }}>
diff --git a/src/components/ChangelogModal/useChangelog.reload.test.ts b/src/components/ChangelogModal/useChangelog.reload.test.ts
new file mode 100644
index 00000000000..444d6bb9086
--- /dev/null
+++ b/src/components/ChangelogModal/useChangelog.reload.test.ts
@@ -0,0 +1,138 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The "What's new" modal paints the previous session's changelog before the
+ * network answers. Each "reload" re-imports the module graph (fresh stores,
+ * fresh SWR cache) over the same localStorage / IndexedDB.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ current: '' }));
+const changelog = vi.hoisted(() => ({ getIndex: vi.fn(), getPostById: vi.fn() }));
+
+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const swr = await import('swr');
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: swr.mutate,
+ useClientDataSWR: swr.default,
+ };
+});
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ changelog: {
+ getIndex: { query: changelog.getIndex },
+ getPostById: { query: changelog.getPostById },
+ },
+ },
+}));
+
+const INDEX = [{ date: '2026-11-01', id: 'v2-3', versionRange: ['2.3.0'] }];
+const post = (title: string) => ({
+ content: `${title} body`,
+ date: new Date('2026-11-01'),
+ description: 'summary',
+ rawTitle: title,
+ tags: ['changelog'],
+ title,
+});
+
+const pending = () => new Promise<never>(() => {});
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** A fresh module graph: what a page reload starts from (storage survives). */
+const reload = async () => {
+ cleanup();
+ vi.resetModules();
+ changelog.getIndex.mockReset();
+ changelog.getPostById.mockReset();
+ const { useChangelogModalIndex, useChangelogModalPost } = await import('./useChangelog');
+ return () =>
+ renderHook(
+ () => ({ index: useChangelogModalIndex(), post: useChangelogModalPost('v2-3', 'en-US') }),
+ { wrapper },
+ );
+};
+
+/** Let the server answer reach the persisted copy before the next reload. */
+const settle = () =>
+ act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+describe('changelog modal across a reload', { timeout: 60_000 }, () => {
+ beforeEach(() => {
+ scope.current = `changelog-user-${randomUUID()}:personal`;
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ const visitOnce = async () => {
+ const render = await reload();
+ changelog.getIndex.mockResolvedValue(INDEX);
+ changelog.getPostById.mockResolvedValue(post('Release 2.3'));
+ const { result } = render();
+ await waitFor(() => expect(result.current.post?.title).toBe('Release 2.3'));
+ await settle();
+ };
+
+ it('paints the last index and post before the network answers, then swaps in the fresh post', async () => {
+ await visitOnce();
+
+ const render = await reload();
+ changelog.getIndex.mockImplementation(pending);
+ let answer: (value: unknown) => void = () => {};
+ changelog.getPostById.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { result } = render();
+
+ await waitFor(() => expect(result.current.index).toEqual(INDEX));
+ await waitFor(() => expect(result.current.post?.title).toBe('Release 2.3'));
+ expect(result.current.post?.content).toBe('Release 2.3 body');
+ expect(changelog.getPostById).toHaveBeenCalledWith({ id: 'v2-3', locale: 'en-US' });
+
+ await act(async () => answer(post('Release 2.3 (edited)')));
+ await waitFor(() => expect(result.current.post?.title).toBe('Release 2.3 (edited)'));
+ });
+
+ it('keeps the last index and post when the refresh fails', async () => {
+ await visitOnce();
+
+ const render = await reload();
+ changelog.getIndex.mockRejectedValue(new Error('offline'));
+ changelog.getPostById.mockRejectedValue(new Error('offline'));
+ const { result } = render();
+ await settle();
+
+ expect(result.current.index).toEqual(INDEX);
+ expect(result.current.post?.title).toBe('Release 2.3');
+ });
+
+ it('does not paint another identity’s copy', async () => {
+ await visitOnce();
+
+ scope.current = `changelog-user-${randomUUID()}:personal`;
+ const render = await reload();
+ changelog.getIndex.mockImplementation(pending);
+ changelog.getPostById.mockImplementation(pending);
+ const { result } = render();
+ await settle();
+
+ expect(result.current.index).toBeUndefined();
+ expect(result.current.post).toBeUndefined();
+ });
+});
diff --git a/src/components/ChangelogModal/useChangelog.ts b/src/components/ChangelogModal/useChangelog.ts
new file mode 100644
index 00000000000..dc6c643b29b
--- /dev/null
+++ b/src/components/ChangelogModal/useChangelog.ts
@@ -0,0 +1,13 @@
+import { useChangelogIndex, useChangelogPost, useChangelogStore } from '@/store/changelog';
+
+/** The changelog index; a reload paints the persisted copy while the server confirms it. */
+export const useChangelogModalIndex = () => {
+ useChangelogStore((s) => s.useFetchChangelogIndex)();
+ return useChangelogIndex();
+};
+
+/** One changelog post in `locale`; `undefined` while loading, `null` when missing. */
+export const useChangelogModalPost = (id: string, locale: string) => {
+ useChangelogStore((s) => s.useFetchChangelogPost)({ id, locale });
+ return useChangelogPost({ id, locale });
+};
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx
index ffa2b84ca71..8e30f8109a7 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx
@@ -7,6 +7,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useChatStore } from '@/store/chat';
import { useDeviceStore } from '@/store/device';
import { DEVICE_LIST_KEY } from '@/store/device/projection';
+import {
+ initialLocalFilePreviewState,
+ localFilePreviewKey,
+ useLocalFilePreviewStore,
+} from '@/store/localFilePreview';
import { LocalFileTag } from './LocalFileTag';
@@ -62,6 +67,30 @@ describe('LocalFileTag remote device preview', () => {
getLocalFilePreview.mockReset();
useChatStore.setState(useChatStore.getInitialState());
useDeviceStore.setState(useDeviceStore.getInitialState());
+ useLocalFilePreviewStore.setState(initialLocalFilePreviewState);
+ });
+
+ it('reads the thumbnail once through the local-file preview replica, however many tags show it', async () => {
+ setTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: true }]);
+
+ render(
+ <>
+ <LocalFileTag file={imageFile} />
+ <LocalFileTag file={imageFile} />
+ </>,
+ );
+
+ const key = localFilePreviewKey({
+ accept: 'image',
+ deviceId: 'device-1',
+ filePath: '/Users/me/project/shot.png',
+ workingDirectory: '/Users/me/project',
+ });
+ await waitFor(() =>
+ expect(useLocalFilePreviewStore.getState().previewMap[key]).toMatchObject({ type: 'image' }),
+ );
+ expect(getLocalFilePreview).toHaveBeenCalledTimes(1);
});
it('reads the image thumbnail through the online topic device off desktop', async () => {
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
index a41b35ae6e7..f565449b2f9 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
@@ -11,13 +11,14 @@ import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
import { useTopicRemoteDeviceId } from '@/features/LocalFile/useTopicRemoteDeviceId';
-import { useClientDataSWR } from '@/libs/swr';
-import { localFileKeys } from '@/libs/swr/keys';
import { localFileService } from '@/services/electron/localFileService';
-import type { LocalFilePreview } from '@/services/projectFile';
-import { projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import {
+ type LocalFilePreviewTarget,
+ useLocalFilePreview,
+ useLocalFilePreviewStore,
+} from '@/store/localFilePreview';
import { parseLocalFileHref } from '../../../Conversation/Markdown/plugins/LocalFileLink/parse';
import { getFileExtension } from '../MentionMenu/localFileDisplay';
@@ -223,26 +224,24 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
(isDesktop || !!remoteDeviceId) && !file.isDirectory && !!parsed?.workingDirectory;
const canRenderImagePreview = canPreview && isPreviewableImageFile(file);
- const { data: imagePreview } = useClientDataSWR<LocalFilePreview>(
- canRenderImagePreview && parsed
- ? localFileKeys.preview({
- accept: 'image',
- allowExternalFile: allowExternalFilePreview || undefined,
- deviceId: remoteDeviceId,
- filePath: parsed.filePath,
- workingDirectory: parsed.workingDirectory,
- })
- : null,
+ // The thumbnail is read through the local-file preview replica (one request
+ // per file however many tags show it). Image previews hold a Blob, which that
+ // replica keeps in memory only.
+ const imageTarget = useMemo<LocalFilePreviewTarget | undefined>(
() =>
- projectFileService.getLocalFilePreview({
- accept: 'image',
- allowExternalFile: allowExternalFilePreview || undefined,
- deviceId: remoteDeviceId,
- path: parsed!.filePath,
- workingDirectory: parsed!.workingDirectory,
- }),
- { revalidateOnFocus: false },
+ canRenderImagePreview && parsed
+ ? {
+ accept: 'image',
+ allowExternalFile: allowExternalFilePreview || undefined,
+ deviceId: remoteDeviceId,
+ filePath: parsed.filePath,
+ workingDirectory: parsed.workingDirectory,
+ }
+ : undefined,
+ [allowExternalFilePreview, canRenderImagePreview, parsed, remoteDeviceId],
);
+ useLocalFilePreviewStore((s) => s.useFetchPreview)(imageTarget);
+ const imagePreview = useLocalFilePreview(imageTarget);
const [imageSrc, setImageSrc] = useState<string>();
useEffect(() => {
diff --git a/src/features/LibraryModal/FilePicker/index.tsx b/src/features/LibraryModal/FilePicker/index.tsx
index 0f17fa3c026..7b1096744a4 100644
--- a/src/features/LibraryModal/FilePicker/index.tsx
+++ b/src/features/LibraryModal/FilePicker/index.tsx
@@ -1,6 +1,7 @@
'use client';
import {
+ Alert,
Button,
Center,
createModal,
@@ -12,25 +13,20 @@ import {
} from '@lobehub/ui';
import { t } from 'i18next';
import { FileSearch, ServerCrash } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo } from 'react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Virtuoso } from 'react-virtuoso';
-import useSWRInfinite from 'swr/infinite';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import type { ExistingEditorAttachment } from '@/features/EditorCanvas/editorAttachments';
-import { resourceService } from '@/services/resource';
import { useGlobalStore } from '@/store/global';
import { KnowledgeType } from '@/types/knowledgeBase';
-import type { ResourceItem } from '@/types/resource';
import Item from '../AssignKnowledgeBase/Item';
import MasonryItem from '../AssignKnowledgeBase/Item/MasonryItem';
import Loading from '../AssignKnowledgeBase/Loading';
import ViewSwitcher from '../AssignKnowledgeBase/ViewSwitcher';
import { type ViewMode } from '../AssignKnowledgeBase/ViewSwitcher';
-
-const PAGE_SIZE = 50;
+import { type AttachableFile, useLibraryFiles } from './useLibraryFiles';
const styles = createStaticStyles(({ css }) => ({
grid: css`
@@ -43,65 +39,30 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-interface ResourcePage {
- hasMore: boolean;
- items: ResourceItem[];
-}
-
interface FilePickerProps {
onSelect: (attachments: ExistingEditorAttachment[]) => void;
}
-const isAttachableFile = (
- item: ResourceItem,
-): item is ResourceItem & { sourceType: 'file'; url: string } =>
- item.sourceType === 'file' && Boolean(item.url);
-
const FilePicker = memo<FilePickerProps>(({ onSelect }) => {
const { t } = useTranslation(['file', 'chat', 'common']);
const { close } = useModalContext();
- const workspaceId = useActiveWorkspaceId();
const viewMode = useGlobalStore((s) => s.status.knowledgeBaseModalViewMode || 'list') as ViewMode;
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
- const getKey = useCallback(
- (pageIndex: number, previousPage: ResourcePage | null) => {
- if (previousPage && !previousPage.hasMore) return null;
- return ['comment-library-files', workspaceId, pageIndex * PAGE_SIZE] as const;
- },
- [workspaceId],
- );
-
- const { data, error, isLoading, isValidating, mutate, setSize } = useSWRInfinite<ResourcePage>(
- getKey,
- ([, , offset]: readonly [string, string | null, number]) =>
- resourceService.queryResources({
- limit: PAGE_SIZE,
- offset,
- showFilesInKnowledgeBase: true,
- }),
- { revalidateFirstPage: false },
- );
-
- const files = useMemo(() => {
- const uniqueFiles = new Map<string, ResourceItem & { sourceType: 'file'; url: string }>();
- for (const item of data?.flatMap((page) => page?.items ?? []) ?? []) {
- if (!isAttachableFile(item)) continue;
- uniqueFiles.set(item.fileId || item.id, item);
- }
- return [...uniqueFiles.values()];
- }, [data]);
- const lastPage = data?.findLast(Boolean);
- const hasMore = Boolean(lastPage?.hasMore);
-
- useEffect(() => {
- if (!isLoading && !isValidating && files.length === 0 && hasMore) {
- void setSize((current) => current + 1);
- }
- }, [files.length, hasMore, isLoading, isValidating, setSize]);
+ const {
+ error,
+ files,
+ hasMore,
+ isAttachable,
+ isLoading,
+ isLoadingMore,
+ loadMore,
+ refreshError,
+ retry,
+ } = useLibraryFiles();
const handleSelect = useCallback(
- (file: ResourceItem & { sourceType: 'file'; url: string }) => {
+ (file: AttachableFile) => {
onSelect([
{
fileId: file.fileId || file.id,
@@ -117,16 +78,16 @@ const FilePicker = memo<FilePickerProps>(({ onSelect }) => {
);
const renderAction = useCallback(
- (file: ResourceItem & { sourceType: 'file'; url: string }) => (
- <Button type={'primary'} onClick={() => handleSelect(file)}>
+ (file: AttachableFile) => (
+ <Button disabled={!isAttachable} onClick={() => handleSelect(file)}>
{t('knowledgeBase.library.action.add', { ns: 'chat' })}
</Button>
),
- [handleSelect, t],
+ [handleSelect, isAttachable, t],
);
const renderItem = useCallback(
- (file: ResourceItem & { sourceType: 'file'; url: string }) => (
+ (file: AttachableFile) => (
<Item
action={renderAction(file)}
fileType={file.fileType}
@@ -139,10 +100,6 @@ const FilePicker = memo<FilePickerProps>(({ onSelect }) => {
[renderAction],
);
- const loadMore = useCallback(() => {
- if (hasMore && !isValidating) void setSize((current) => current + 1);
- }, [hasMore, isValidating, setSize]);
-
return (
<Flexbox height={500} width={'100%'}>
<Flexbox horizontal align={'center'} justify={'flex-end'} style={{ paddingBlockEnd: 12 }}>
@@ -151,13 +108,25 @@ const FilePicker = memo<FilePickerProps>(({ onSelect }) => {
onViewChange={(mode) => updateSystemStatus({ knowledgeBaseModalViewMode: mode })}
/>
</Flexbox>
- {isLoading && files.length === 0 ? (
+ {!!refreshError && (
+ <Alert
+ description={t('networkError', { ns: 'file' })}
+ style={{ marginBlockEnd: 12 }}
+ type={'warning'}
+ action={
+ <Button size={'small'} onClick={() => void retry()}>
+ {t('retry', { ns: 'common' })}
+ </Button>
+ }
+ />
+ )}
+ {isLoading ? (
<Loading />
- ) : error && files.length === 0 ? (
+ ) : error ? (
<Center flex={1} gap={12} padding={40}>
<Icon icon={ServerCrash} size={80} />
{t('networkError', { ns: 'file' })}
- <Button onClick={() => void mutate()}>{t('retry', { ns: 'common' })}</Button>
+ <Button onClick={() => void retry()}>{t('retry', { ns: 'common' })}</Button>
</Center>
) : files.length === 0 ? (
<Center flex={1} padding={40}>
@@ -190,7 +159,7 @@ const FilePicker = memo<FilePickerProps>(({ onSelect }) => {
/>
))}
{hasMore && (
- <Button loading={isValidating} type={'text'} onClick={loadMore}>
+ <Button loading={isLoadingMore} type={'text'} onClick={loadMore}>
{t('loadMore', { ns: 'file' })}
</Button>
)}
diff --git a/src/features/LibraryModal/FilePicker/useLibraryFiles.reload.test.ts b/src/features/LibraryModal/FilePicker/useLibraryFiles.reload.test.ts
new file mode 100644
index 00000000000..dc463591387
--- /dev/null
+++ b/src/features/LibraryModal/FilePicker/useLibraryFiles.reload.test.ts
@@ -0,0 +1,276 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The library file picker paints the previous session's head page before the
+ * network answers. Each "reload" re-imports the module graph (fresh stores,
+ * fresh SWR cache) over the same IndexedDB.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ current: '' }));
+const queryResources = vi.hoisted(() => vi.fn());
+
+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const swr = await import('swr');
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: swr.mutate,
+ useClientDataSWR: swr.default,
+ };
+});
+vi.mock('@/services/resource', () => ({ resourceService: { queryResources } }));
+
+const file = (id: string, url = `https://files.example.com/${id}?sig=1`) => ({
+ createdAt: new Date('2026-11-01'),
+ fileType: 'application/pdf',
+ id,
+ name: `${id}.pdf`,
+ size: 1,
+ sourceType: 'file',
+ url,
+});
+const folder = (id: string) => ({ ...file(id), sourceType: 'document', url: undefined });
+/** `total` counts every row of the query, not just this page's. */
+const page = (items: unknown[], hasMore = false, total = items.length) => ({
+ hasMore,
+ items,
+ total,
+});
+
+const pending = () => new Promise<never>(() => {});
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** A fresh module graph: what a page reload starts from (IndexedDB survives). */
+const reload = async () => {
+ cleanup();
+ vi.resetModules();
+ queryResources.mockReset();
+ const { useLibraryFiles } = await import('./useLibraryFiles');
+ return () => renderHook(() => useLibraryFiles(), { wrapper });
+};
+
+/** Let the server answer reach the persisted copy before the next reload. */
+const settle = () =>
+ act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+const ids = (files: { id: string }[]) => files.map((item) => item.id);
+
+describe('useLibraryFiles across a reload', { timeout: 60_000 }, () => {
+ beforeEach(() => {
+ scope.current = `file-picker-user-${randomUUID()}:personal`;
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ const visitOnce = async (items: unknown[] = [file('f1')]) => {
+ const render = await reload();
+ queryResources.mockResolvedValue(page(items));
+ const { result } = render();
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ await settle();
+ };
+
+ it('paints the last files before the network answers, attachable only once confirmed', async () => {
+ await visitOnce();
+
+ const render = await reload();
+ let answer: (value: unknown) => void = () => {};
+ queryResources.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { result } = render();
+
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f1']));
+ expect(result.current.isLoading).toBe(false);
+ // The restored row's signed URL may have expired: no attaching it yet.
+ expect(result.current.isAttachable).toBe(false);
+
+ await act(async () => answer(page([file('f1', 'https://files.example.com/f1?sig=2')])));
+
+ await waitFor(() => expect(result.current.isAttachable).toBe(true));
+ expect(result.current.files[0].url).toBe('https://files.example.com/f1?sig=2');
+ });
+
+ it('treats a restored empty page as loading until the server confirms it', async () => {
+ await visitOnce([]);
+
+ const render = await reload();
+ let answer: (value: unknown) => void = () => {};
+ queryResources.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { result } = render();
+ await settle();
+
+ expect(result.current.isLoading).toBe(true);
+
+ await act(async () => answer(page([file('f2')])));
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f2']));
+ });
+
+ it('keeps paging past pages without attachable files', async () => {
+ const render = await reload();
+ queryResources
+ .mockResolvedValueOnce(page([folder('d1')], true, 51))
+ .mockResolvedValueOnce(page([file('f3')], false, 51));
+ const { result } = render();
+
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f3']));
+ expect(queryResources).toHaveBeenLastCalledWith(
+ expect.objectContaining({ limit: 50, offset: 50, showFilesInKnowledgeBase: true }),
+ );
+ });
+
+ it('paints a file found past folder-only pages after a reload', async () => {
+ const first = await reload();
+ queryResources
+ .mockResolvedValueOnce(page([folder('d1')], true, 51))
+ .mockResolvedValueOnce(page([file('f4')], false, 51));
+ const visit = first();
+ await waitFor(() => expect(ids(visit.result.current.files)).toEqual(['f4']));
+ await settle();
+
+ const render = await reload();
+ queryResources.mockImplementation(pending);
+ const { result } = render();
+
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f4']));
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('never offers a restored file past the head before its page is re-listed', async () => {
+ const first = await reload();
+ queryResources
+ .mockResolvedValueOnce(page([folder('d1')], true, 51))
+ .mockResolvedValueOnce(page([file('f4')], false, 51));
+ const visit = first();
+ await waitFor(() => expect(ids(visit.result.current.files)).toEqual(['f4']));
+ await settle();
+
+ // f4 was deleted since: page 2 now holds f5 instead.
+ const { useLibraryFiles } = await (async () => {
+ cleanup();
+ vi.resetModules();
+ queryResources.mockReset();
+ return import('./useLibraryFiles');
+ })();
+ let answerHead: (value: unknown) => void = () => {};
+ let answerTail: (value: unknown) => void = () => {};
+ queryResources.mockImplementation(({ offset }: { offset: number }) =>
+ offset === 0
+ ? new Promise((resolve) => (answerHead = resolve))
+ : new Promise((resolve) => (answerTail = resolve)),
+ );
+ const attachableIds = new Set<string>();
+ const { result } = renderHook(
+ () => {
+ const value = useLibraryFiles();
+ if (value.isAttachable) for (const item of value.files) attachableIds.add(item.id);
+ return value;
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f4']));
+ expect(result.current.isAttachable).toBe(false);
+
+ await act(async () => answerHead(page([folder('d1')], true, 51)));
+ await settle();
+ // The head is confirmed, but f4 sits on a restored page that is not.
+ expect(ids(result.current.files)).toEqual(['f4']);
+ expect(result.current.isAttachable).toBe(false);
+
+ await act(async () => answerTail(page([file('f5')], false, 51)));
+
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f5']));
+ expect(result.current.isAttachable).toBe(true);
+ expect(attachableIds.has('f4')).toBe(false);
+ });
+
+ it('offers a retry of the later page when it fails after the head confirmed', async () => {
+ const first = await reload();
+ queryResources
+ .mockResolvedValueOnce(page([folder('d1')], true, 51))
+ .mockResolvedValueOnce(page([file('f4')], false, 51));
+ const visit = first();
+ await waitFor(() => expect(ids(visit.result.current.files)).toEqual(['f4']));
+ await settle();
+
+ const render = await reload();
+ let answerHead: (value: unknown) => void = () => {};
+ let tailCalls = 0;
+ queryResources.mockImplementation(({ offset }: { offset: number }) => {
+ if (offset === 0) return new Promise((resolve) => (answerHead = resolve));
+ tailCalls += 1;
+ return tailCalls === 1
+ ? Promise.reject(new Error('offline'))
+ : Promise.resolve(page([file('f5')], false, 51));
+ });
+ const { result } = render();
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f4']));
+
+ await act(async () => answerHead(page([folder('d1')], true, 51)));
+
+ await waitFor(() => expect(result.current.refreshError).toBeInstanceOf(Error));
+ expect(ids(result.current.files)).toEqual(['f4']);
+ expect(result.current.isAttachable).toBe(false);
+
+ await act(async () => {
+ await result.current.retry();
+ });
+
+ await waitFor(() => expect(ids(result.current.files)).toEqual(['f5']));
+ expect(result.current.isAttachable).toBe(true);
+ expect(result.current.refreshError).toBeUndefined();
+ });
+
+ it('keeps the last files, without an error, when the refresh fails', async () => {
+ await visitOnce();
+
+ const render = await reload();
+ queryResources.mockRejectedValue(new Error('offline'));
+ const { result } = render();
+ await settle();
+
+ expect(ids(result.current.files)).toEqual(['f1']);
+ expect(result.current.error).toBeUndefined();
+ // The restored files cannot be attached yet, so the failure stays retryable.
+ expect(result.current.isAttachable).toBe(false);
+ expect(result.current.refreshError).toBeInstanceOf(Error);
+
+ queryResources.mockReset();
+ queryResources.mockResolvedValue(page([file('f1', 'https://files.example.com/f1?sig=3')]));
+ await act(async () => {
+ await result.current.retry();
+ });
+
+ await waitFor(() => expect(result.current.isAttachable).toBe(true));
+ expect(result.current.refreshError).toBeUndefined();
+ });
+
+ it('does not paint another identity’s files', async () => {
+ await visitOnce();
+
+ scope.current = `file-picker-user-${randomUUID()}:personal`;
+ const render = await reload();
+ queryResources.mockImplementation(pending);
+ const { result } = render();
+ await settle();
+
+ expect(result.current.files).toEqual([]);
+ expect(result.current.isLoading).toBe(true);
+ });
+});
diff --git a/src/features/LibraryModal/FilePicker/useLibraryFiles.ts b/src/features/LibraryModal/FilePicker/useLibraryFiles.ts
new file mode 100644
index 00000000000..dd2b368be6d
--- /dev/null
+++ b/src/features/LibraryModal/FilePicker/useLibraryFiles.ts
@@ -0,0 +1,97 @@
+import { useCallback, useEffect, useMemo } from 'react';
+
+import { useLibraryFilePickerList, useLibraryFilePickerStore } from '@/store/libraryFilePicker';
+import type { ResourceItem } from '@/types/resource';
+
+export type AttachableFile = ResourceItem & { sourceType: 'file'; url: string };
+
+const isAttachableFile = (item: ResourceItem): item is AttachableFile =>
+ item.sourceType === 'file' && Boolean(item.url);
+
+const toFiles = (items: ResourceItem[] | undefined): AttachableFile[] => {
+ const uniqueFiles = new Map<string, AttachableFile>();
+ for (const item of items ?? []) {
+ if (!isAttachableFile(item)) continue;
+ uniqueFiles.set(item.fileId || item.id, item);
+ }
+ return [...uniqueFiles.values()];
+};
+
+/**
+ * Files the library picker offers, from a replica: a reopened picker paints the
+ * persisted head page while the server confirms it.
+ */
+export const useLibraryFiles = () => {
+ const {
+ error: fetchError,
+ isConfirmed,
+ revalidate,
+ snapshotItems,
+ } = useLibraryFilePickerStore((s) => s.useFetchFiles)();
+ const loadMoreFiles = useLibraryFilePickerStore((s) => s.loadMoreFiles);
+ const data = useLibraryFilePickerList();
+
+ const listedFiles = useMemo(() => toFiles(data?.items), [data]);
+ const snapshotFiles = useMemo(() => toFiles(snapshotItems), [snapshotItems]);
+ const hasMore = Boolean(data?.hasMore);
+ const isLoadingMore = Boolean(data?.isLoadingMore);
+ // Restored pages past the head were dropped on confirmation; while the
+ // re-listed pages have no file yet, keep the rows the user was looking at on
+ // screen (not attachable) rather than flashing a skeleton.
+ const showsSnapshot =
+ isConfirmed &&
+ listedFiles.length === 0 &&
+ (hasMore || isLoadingMore) &&
+ snapshotFiles.length > 0;
+ const files = showsSnapshot ? snapshotFiles : listedFiles;
+ // A failed refresh keeps the painted files; with none painted it is surfaced.
+ const error = files.length > 0 ? undefined : (fetchError ?? data?.loadMoreError);
+ const isAttachable = isConfirmed && !showsSnapshot;
+ // The painted files are a snapshot the server has not re-listed (the head
+ // refresh, or a later page after it, failed): they stay on screen but cannot
+ // be attached, so the failure (and a retry of that request) must be offered.
+ const pendingError = isConfirmed ? data?.loadMoreError : fetchError;
+ const refreshError = files.length > 0 && !isAttachable ? pendingError : undefined;
+ const retry = useCallback(
+ () => (isConfirmed && data?.loadMoreError ? loadMoreFiles() : revalidate()),
+ [data?.loadMoreError, isConfirmed, loadMoreFiles, revalidate],
+ );
+ // Nothing to show yet: no page at all, a restored page the server has not
+ // confirmed, or later pages still to look through for an attachable file.
+ const isLoading =
+ files.length === 0 && !error && (!data || !isConfirmed || hasMore || isLoadingMore);
+
+ // Pages of folders / documents only: keep paging until a file shows up.
+ useEffect(() => {
+ if (
+ isConfirmed &&
+ !isLoadingMore &&
+ !data?.loadMoreError &&
+ listedFiles.length === 0 &&
+ hasMore
+ ) {
+ void loadMoreFiles();
+ }
+ }, [data?.loadMoreError, hasMore, isConfirmed, isLoadingMore, listedFiles.length, loadMoreFiles]);
+
+ const loadMore = useCallback(() => {
+ if (hasMore && !isLoadingMore) void loadMoreFiles();
+ }, [hasMore, isLoadingMore, loadMoreFiles]);
+
+ return {
+ error,
+ files,
+ hasMore,
+ /**
+ * A restored row's `url` may be a signed link that has since expired (or
+ * the file may be gone), so a file is attachable only once the server has
+ * re-listed it.
+ */
+ isAttachable,
+ isLoading,
+ isLoadingMore,
+ loadMore,
+ refreshError,
+ retry,
+ };
+};
diff --git a/src/features/ToolSetting/index.tsx b/src/features/ToolSetting/index.tsx
index 6c06d7c401f..02bf85f102e 100644
--- a/src/features/ToolSetting/index.tsx
+++ b/src/features/ToolSetting/index.tsx
@@ -10,25 +10,20 @@ import { ToolsChannelsSkeleton } from '@/components/Skeleton/Settings/tabs/Tools
import SettingHeader from '@/features/Settings/features/SettingHeader';
import SettingsPageActions from '@/features/Settings/features/SettingsPageActions';
import { useSaveState } from '@/hooks/useSaveState';
-import { useClientDataSWR } from '@/libs/swr';
-import { searchService } from '@/services/search';
import { useUserStore } from '@/store/user';
import ChannelSection from './ChannelSection';
-
-const FETCH_AVAILABLE_CHANNELS_KEY = 'FETCH_AVAILABLE_WEB_BROWSING_CHANNELS';
+import { useAvailableChannels } from './useAvailableChannels';
const ToolSetting = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader = true }) => {
const { t } = useTranslation('setting');
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
- const { data, error, isLoading, mutate } = useClientDataSWR(FETCH_AVAILABLE_CHANNELS_KEY, () =>
- searchService.getAvailableChannels(),
- );
+ const { data, error, isLoading, retry: retryChannels } = useAvailableChannels();
// `ChannelSection` (via `useChannelRows`) seeds its local rows ONCE on mount
// from the saved channel order. So it must only mount after BOTH the available
- // channels (SWR) AND the user settings store have hydrated — otherwise on a
+ // channels (replica) AND the user settings store have hydrated — otherwise on a
// hard refresh it seeds from an unhydrated (undefined) `savedOrder`, silently
// rendering the default order and ignoring the user's saved priority (and any
// edit then overwrites the real saved order). Fold the user-state init into the
@@ -65,7 +60,7 @@ const ToolSetting = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader =
isLoading={isLoading || !isUserStateInit}
loading={<ToolsChannelsSkeleton />}
onRetry={() => {
- void mutate();
+ void retryChannels();
void refreshUserState();
}}
>
@@ -74,6 +69,8 @@ const ToolSetting = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader =
availableIds={(data?.searchProviders ?? []).map((c) => c.id)}
channelKey={'searchProviders'}
desc={t('settingTool.search.desc')}
+ // Rows are seeded once on mount: reseed when a refresh changes the set.
+ key={(data?.searchProviders ?? []).map((c) => c.id).join(',')}
save={save}
title={t('settingTool.search.title')}
/>
@@ -81,6 +78,8 @@ const ToolSetting = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader =
availableIds={(data?.crawlerImpls ?? []).map((c) => c.id)}
channelKey={'crawlerImpls'}
desc={t('settingTool.crawler.desc')}
+ // Rows are seeded once on mount: reseed when a refresh changes the set.
+ key={(data?.crawlerImpls ?? []).map((c) => c.id).join(',')}
save={save}
title={t('settingTool.crawler.title')}
/>
diff --git a/src/features/ToolSetting/useAvailableChannels.reload.test.ts b/src/features/ToolSetting/useAvailableChannels.reload.test.ts
new file mode 100644
index 00000000000..07222fd8fa1
--- /dev/null
+++ b/src/features/ToolSetting/useAvailableChannels.reload.test.ts
@@ -0,0 +1,125 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The Web Search settings page paints the previous session's channel list
+ * before the network answers. Each "reload" re-imports the module graph (fresh
+ * stores, fresh SWR cache) over the same localStorage.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const scope = vi.hoisted(() => ({ current: '' }));
+const getAvailableChannels = vi.hoisted(() => vi.fn());
+
+vi.mock('@/libs/swr/useCacheScope', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getCacheScope: () => scope.current,
+ isScopeTrusted: () => true,
+ useCacheScope: () => scope.current,
+}));
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const swr = await import('swr');
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: swr.mutate,
+ useClientDataSWR: swr.default,
+ };
+});
+vi.mock('@/services/search', () => ({ searchService: { getAvailableChannels } }));
+
+const channels = (searchProviders: string[], crawlerImpls = ['naive']) => ({
+ crawlerImpls: crawlerImpls.map((id) => ({ id })),
+ searchProviders: searchProviders.map((id) => ({ id })),
+});
+
+const pending = () => new Promise<never>(() => {});
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);
+
+/** A fresh module graph: what a page reload starts from (storage survives). */
+const reload = async () => {
+ cleanup();
+ vi.resetModules();
+ getAvailableChannels.mockReset();
+ const { useAvailableChannels } = await import('./useAvailableChannels');
+ return () => renderHook(() => useAvailableChannels(), { wrapper });
+};
+
+/** Let the server answer reach the persisted copy before the next reload. */
+const settle = () =>
+ act(async () => {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+describe('useAvailableChannels across a reload', { timeout: 60_000 }, () => {
+ beforeEach(() => {
+ scope.current = `tool-setting-user-${randomUUID()}:personal`;
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ const visitOnce = async () => {
+ const render = await reload();
+ getAvailableChannels.mockResolvedValue(channels(['tavily', 'searxng']));
+ const { result } = render();
+ await waitFor(() => expect(result.current.data).toEqual(channels(['tavily', 'searxng'])));
+ await settle();
+ };
+
+ it('paints the last channel list before the network answers, then swaps in the fresh one', async () => {
+ await visitOnce();
+
+ const render = await reload();
+ let answer: (value: unknown) => void = () => {};
+ getAvailableChannels.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+ const { result } = render();
+
+ await waitFor(() => expect(result.current.data).toEqual(channels(['tavily', 'searxng'])));
+ expect(result.current.isLoading).toBe(false);
+ expect(getAvailableChannels).toHaveBeenCalledTimes(1);
+
+ await act(async () => answer(channels(['exa'])));
+ await waitFor(() => expect(result.current.data).toEqual(channels(['exa'])));
+ });
+
+ it('keeps the last channel list, without an error, when the refresh fails', async () => {
+ await visitOnce();
+
+ const render = await reload();
+ getAvailableChannels.mockRejectedValue(new Error('offline'));
+ const { result } = render();
+ await settle();
+
+ expect(result.current.data).toEqual(channels(['tavily', 'searxng']));
+ expect(result.current.error).toBeUndefined();
+ });
+
+ it('surfaces the error of a first load with nothing to paint', async () => {
+ const render = await reload();
+ getAvailableChannels.mockRejectedValue(new Error('offline'));
+ const { result } = render();
+
+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));
+ expect(result.current.isLoading).toBe(false);
+ });
+
+ it('does not paint another identity’s copy', async () => {
+ await visitOnce();
+
+ scope.current = `tool-setting-user-${randomUUID()}:personal`;
+ const render = await reload();
+ getAvailableChannels.mockImplementation(pending);
+ const { result } = render();
+ await settle();
+
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isLoading).toBe(true);
+ });
+});
diff --git a/src/features/ToolSetting/useAvailableChannels.ts b/src/features/ToolSetting/useAvailableChannels.ts
new file mode 100644
index 00000000000..7d67dc37aae
--- /dev/null
+++ b/src/features/ToolSetting/useAvailableChannels.ts
@@ -0,0 +1,18 @@
+import { useAvailableSearchChannels, useSearchChannelStore } from '@/store/searchChannel';
+
+/**
+ * Search providers and crawlers the server enables, from a replica: a reload
+ * paints the persisted list while the server confirms it, and a failed refresh
+ * keeps it on screen (only a first load surfaces the error).
+ */
+export const useAvailableChannels = () => {
+ const { error, revalidate } = useSearchChannelStore((s) => s.useFetchAvailableChannels)();
+ const data = useAvailableSearchChannels();
+
+ return {
+ data,
+ error: data ? undefined : error,
+ isLoading: !data && !error,
+ retry: revalidate,
+ };
+};
diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.ts
index 57770099c07..08c0da40707 100644
--- a/src/libs/swr/keys.frozen.test.ts
+++ b/src/libs/swr/keys.frozen.test.ts
@@ -22,8 +22,6 @@ const LEGACY_SWR_KEYS = [
'botWakeKeys.decisions',
'botWakeKeys.summary',
'canvasKeys.storage',
- 'changelogKeys.modalIndex',
- 'changelogKeys.post',
'channelKeys.agentEnvironment',
'channelKeys.userCandidates',
'channelKeys.wakeConfig',
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 07790529e0c..edb583479f7 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -645,16 +645,11 @@ export const localFileKeys = {
]),
};
-// ---- changelog ----------------------------------------------------------
+// ---- canvas -------------------------------------------------------------
export const canvasKeys = {
storage: def('canvas:storage', () => ['canvas:storage']),
};
-export const changelogKeys = {
- modalIndex: def('changelog:modalIndex', () => ['changelog:modalIndex']),
- post: def('changelog:post', (id: string, locale: string) => ['changelog:post', id, locale]),
-};
-
// ---- agent onboarding ---------------------------------------------------
export const onboardingKeys = {
agentBootstrap: def('onboarding:agentBootstrap', () => ['onboarding:agentBootstrap']),
@@ -790,7 +785,6 @@ export const swrKeys = {
agentHome: agentHomeKeys,
auth: authKeys,
canvas: canvasKeys,
- changelog: changelogKeys,
cron: cronKeys,
device: deviceKeys,
electron: electronKeys,
diff --git a/src/store/changelog/index.ts b/src/store/changelog/index.ts
new file mode 100644
index 00000000000..301c73a2a87
--- /dev/null
+++ b/src/store/changelog/index.ts
@@ -0,0 +1,128 @@
+import type { StoreApi } from 'zustand';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn, type UseBoundStoreWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ defineReplica,
+ recordLens,
+ type ReplicaState,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { lambdaClient } from '@/libs/trpc/client';
+import { type ChangelogIndexItem } from '@/types/changelog';
+
+/** The fields of a changelog post the modal renders; the rest is never stored. */
+export interface ChangelogPost {
+ content: string;
+ image?: string;
+ rawTitle?: string;
+ title: string;
+}
+
+export interface ChangelogPostParams {
+ id: string;
+ locale: string;
+}
+
+/** The server answers one index for everyone, so the replica keeps a single entry. */
+export const CHANGELOG_INDEX_KEY = 'default';
+
+/** How many posts (per locale) survive a reload (`persist.maxEntries`). */
+export const MAX_PERSISTED_CHANGELOG_POSTS = 30;
+
+export const changelogPostKey = ({ id, locale }: ChangelogPostParams) =>
+ JSON.stringify([id, locale]);
+
+/** Changelog index of the "What's new" modal, in localStorage for a first-frame paint. */
+export const changelogIndexResource = defineReplica<string, ChangelogIndexItem[]>({
+ key: (key) => key,
+ name: 'changelogIndex',
+ storage: 'localStorage',
+ version: 1,
+});
+
+/**
+ * One changelog post per id + locale. Only the rendered fields are kept, and at
+ * most {@link MAX_PERSISTED_CHANGELOG_POSTS} rows per scope (least recently
+ * used evicted). A post the server cannot find is `null`.
+ */
+export const changelogPostResource = defineReplica<ChangelogPostParams, ChangelogPost | null>({
+ key: changelogPostKey,
+ name: 'changelogPost',
+ persist: { maxEntries: MAX_PERSISTED_CHANGELOG_POSTS },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+const fetchChangelogPost = async ({
+ id,
+ locale,
+}: ChangelogPostParams): Promise<ChangelogPost | null> => {
+ const post = await lambdaClient.changelog.getPostById.query({ id, locale });
+ if (!post) return null;
+
+ return {
+ content: post.content,
+ image: post.image,
+ rawTitle: post.rawTitle,
+ title: post.title,
+ };
+};
+
+export interface ChangelogStoreState {
+ indexMap: Record<string, ChangelogIndexItem[]>;
+ indexReplica: ReplicaState<ChangelogIndexItem[]>;
+ postMap: Record<string, ChangelogPost | null>;
+ postReplica: ReplicaState<ChangelogPost | null>;
+}
+
+interface ChangelogStore extends ChangelogStoreState {
+ /** Fetch orchestration only; read the index with `useChangelogIndex`. */
+ useFetchChangelogIndex: () => ReplicaSyncResult;
+ /** Fetch orchestration only; read the post with `useChangelogPost`. */
+ useFetchChangelogPost: (params: ChangelogPostParams) => ReplicaSyncResult;
+}
+
+export const initialChangelogState: ChangelogStoreState = {
+ indexMap: {},
+ indexReplica: createReplicaState(),
+ postMap: {},
+ postReplica: createReplicaState(),
+};
+
+export const useChangelogStore: UseBoundStoreWithEqualityFn<StoreApi<ChangelogStore>> =
+ createWithEqualityFn<ChangelogStore>()((set, get) => {
+ const index = createReplicaSlice(changelogIndexResource, {
+ actionPrefix: 'changelog/index',
+ fetcher: () => lambdaClient.changelog.getIndex.query(),
+ get,
+ set,
+ stateKey: 'indexReplica',
+ view: recordLens<ChangelogStore, ChangelogIndexItem[]>('indexMap'),
+ });
+
+ const posts = createReplicaSlice(changelogPostResource, {
+ actionPrefix: 'changelog/posts',
+ fetcher: fetchChangelogPost,
+ get,
+ set,
+ stateKey: 'postReplica',
+ view: recordLens<ChangelogStore, ChangelogPost | null>('postMap'),
+ });
+
+ return {
+ ...initialChangelogState,
+ useFetchChangelogIndex: () => index.useSync(CHANGELOG_INDEX_KEY),
+ useFetchChangelogPost: (params) => posts.useSync(params),
+ };
+ }, shallow);
+
+/** The changelog index, or `undefined` while neither persisted nor fetched. */
+export const useChangelogIndex = () =>
+ useChangelogStore((state) => state.indexMap[CHANGELOG_INDEX_KEY]);
+
+/** One post, `null` when the server has none, `undefined` while loading. */
+export const useChangelogPost = (params: ChangelogPostParams) =>
+ useChangelogStore((state) => state.postMap[changelogPostKey(params)]);
diff --git a/src/store/libraryFilePicker/index.ts b/src/store/libraryFilePicker/index.ts
new file mode 100644
index 00000000000..0075e9533ce
--- /dev/null
+++ b/src/store/libraryFilePicker/index.ts
@@ -0,0 +1,159 @@
+import type { StoreApi } from 'zustand';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn, type UseBoundStoreWithEqualityFn } from 'zustand/traditional';
+
+import {
+ cacheScope,
+ createReplicaSlice,
+ createReplicaState,
+ definePagedReplica,
+ recordLens,
+ type ReplicaPagedData,
+ type ReplicaPageResult,
+ type ReplicaState,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { resourceService } from '@/services/resource';
+import type { ResourceItem } from '@/types/resource';
+
+/** The picker lists one query (every library file), so the replica keeps a single entry. */
+export const LIBRARY_FILE_PICKER_KEY = 'default';
+
+export const LIBRARY_FILE_PICKER_PAGE_SIZE = 50;
+
+/** How many loaded pages survive a reload (`paging.persist.pages`). */
+export const LIBRARY_FILE_PICKER_PERSISTED_PAGES = 5;
+
+export type LibraryFilePickerValue = ReplicaPagedData<ResourceItem, number>;
+
+/**
+ * Files the library file picker offers (`resourceService.queryResources`, with
+ * knowledge-base files). A paged replica of its own rather than the explorer's
+ * `resourceList`: that one keeps a single entry for whatever folder the
+ * explorer shows, so the picker sharing it would repaint the explorer behind
+ * the modal with the picker's query. Up to
+ * {@link LIBRARY_FILE_PICKER_PERSISTED_PAGES} loaded pages are persisted
+ * (IndexedDB, user / workspace scope), so a reopened picker paints the last
+ * files at once.
+ */
+export const libraryFilePickerResource = definePagedReplica<string, ResourceItem, number>({
+ key: (key) => key,
+ name: 'libraryFilePicker',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // Folders and pages share the list with files, so the first attachable
+ // file can sit pages deep: keep the pages the picker paged through to
+ // reach it (no content previews, so a page stays small).
+ persist: { pages: LIBRARY_FILE_PICKER_PERSISTED_PAGES },
+ },
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One page of the picker list; `cursor` is the page index (0 = head). */
+const fetchLibraryFilePage = async (
+ _key: string,
+ cursor?: number,
+): Promise<ReplicaPageResult<ResourceItem, number>> => {
+ const page = cursor ?? 0;
+ const response = await resourceService.queryResources({
+ limit: LIBRARY_FILE_PICKER_PAGE_SIZE,
+ offset: page * LIBRARY_FILE_PICKER_PAGE_SIZE,
+ showFilesInKnowledgeBase: true,
+ });
+
+ return {
+ items: response.items,
+ // Folders and pages are dropped on the client, and the server may filter
+ // rows after paging, so only its own `hasMore` ends the list.
+ nextCursor: response.hasMore ? page + 1 : null,
+ total: response.total,
+ };
+};
+
+export interface LibraryFilePickerStoreState {
+ /**
+ * Cache scope the server last answered the list under in this session. A
+ * restored head page is a snapshot until then; another scope never vouches
+ * for the active one.
+ */
+ confirmedScope?: string;
+ /**
+ * Rows on screen when the restored pages behind the head were dropped, with
+ * the scope they belong to. The picker keeps showing them (not attachable)
+ * while it pages back through fresh pages, instead of flashing a skeleton.
+ */
+ droppedSnapshot?: { items: ResourceItem[]; scope: string };
+ pickerMap: Record<string, LibraryFilePickerValue>;
+ pickerReplica: ReplicaState<LibraryFilePickerValue>;
+}
+
+export interface LibraryFilePickerSyncResult extends ReplicaSyncResult {
+ /**
+ * The server has answered for the active identity. A restored head page is a
+ * snapshot: until then an empty one is "loading", never "no files".
+ */
+ isConfirmed: boolean;
+ /** Rows shown before the restored pages were dropped (this identity only). */
+ snapshotItems?: ResourceItem[];
+}
+
+interface LibraryFilePickerStore extends LibraryFilePickerStoreState {
+ /** Append the next page. */
+ loadMoreFiles: () => Promise<void>;
+ /** Fetch orchestration only; read the files with `useLibraryFilePickerList`. */
+ useFetchFiles: () => LibraryFilePickerSyncResult;
+}
+
+export const initialLibraryFilePickerState: LibraryFilePickerStoreState = {
+ confirmedScope: undefined,
+ droppedSnapshot: undefined,
+ pickerMap: {},
+ pickerReplica: createReplicaState(),
+};
+
+export const useLibraryFilePickerStore: UseBoundStoreWithEqualityFn<
+ StoreApi<LibraryFilePickerStore>
+> = createWithEqualityFn<LibraryFilePickerStore>()((set, get) => {
+ const files = createReplicaSlice(libraryFilePickerResource, {
+ actionPrefix: 'libraryFilePicker/files',
+ effects: {
+ onApplied: (_data, _params, { key, scope }) => {
+ // The first answer of this identity re-lists only the head: pages
+ // restored behind it are an unconfirmed snapshot (a file there may be
+ // gone), so drop them and let the picker page through fresh ones.
+ // Later head refreshes keep the pages this session loaded itself.
+ if (get().confirmedScope !== scope) {
+ const items = get().pickerMap[key]?.items ?? [];
+ if (files.collapse(key)) set({ droppedSnapshot: { items, scope } });
+ }
+ set({ confirmedScope: scope });
+ },
+ },
+ fetcher: fetchLibraryFilePage,
+ get,
+ set,
+ stateKey: 'pickerReplica',
+ view: recordLens<LibraryFilePickerStore, LibraryFilePickerValue>('pickerMap'),
+ });
+
+ return {
+ ...initialLibraryFilePickerState,
+ loadMoreFiles: () => files.loadMore(LIBRARY_FILE_PICKER_KEY, LIBRARY_FILE_PICKER_KEY),
+ useFetchFiles: () => {
+ const sync = files.useSync(LIBRARY_FILE_PICKER_KEY);
+ const scope = cacheScope.use();
+ const isConfirmed = useLibraryFilePickerStore((state) => state.confirmedScope === scope);
+ const snapshotItems = useLibraryFilePickerStore((state) =>
+ state.droppedSnapshot?.scope === scope ? state.droppedSnapshot.items : undefined,
+ );
+ return { ...sync, isConfirmed, snapshotItems };
+ },
+ };
+}, shallow);
+
+/** The picker list, or `undefined` while neither persisted nor fetched. */
+export const useLibraryFilePickerList = () =>
+ useLibraryFilePickerStore((state) => state.pickerMap[LIBRARY_FILE_PICKER_KEY]);
diff --git a/src/store/localFilePreview/index.test.ts b/src/store/localFilePreview/index.test.ts
index 39eb6463d01..6958b4436b2 100644
--- a/src/store/localFilePreview/index.test.ts
+++ b/src/store/localFilePreview/index.test.ts
@@ -151,6 +151,35 @@ describe('local file preview replica', () => {
await waitFor(async () => expect((await storedRow(NOTES))?.data).toEqual(textPreview('# v2')));
});
+ it('keeps the portal key as it was and reads an image-only target as an image', async () => {
+ // Rows the portal stored before `accept` existed must still be found.
+ expect(localFilePreviewKey(NOTES)).toBe(
+ JSON.stringify(['device', 'device-a', '/repo', '/repo/notes.md', 'workspace']),
+ );
+ const image = { ...NOTES, accept: 'image' as const, filePath: '/repo/shot.png' };
+ expect(localFilePreviewKey(image)).not.toBe(
+ localFilePreviewKey({ ...image, accept: undefined }),
+ );
+ vi.mocked(projectFileService.getLocalFilePreview).mockResolvedValue({
+ blob: new Blob(['png']),
+ contentType: 'image/png',
+ type: 'image',
+ } as never);
+
+ const { result } = renderPreview(image);
+
+ await waitFor(() => expect(result.current.preview?.type).toBe('image'));
+ expect(projectFileService.getLocalFilePreview).toHaveBeenCalledWith({
+ accept: 'image',
+ allowExternalFile: undefined,
+ deviceId: 'device-a',
+ path: '/repo/shot.png',
+ workingDirectory: '/repo',
+ });
+ // A Blob preview stays in memory: nothing to restore after a reload.
+ expect(await storedRow(image)).toBeUndefined();
+ });
+
it('keys previews by device and working directory', async () => {
const otherDevice = { ...NOTES, deviceId: 'device-b' };
await seedRow(NOTES, textPreview('device a'));
diff --git a/src/store/localFilePreview/index.ts b/src/store/localFilePreview/index.ts
index 60a07047994..e2281b4937a 100644
--- a/src/store/localFilePreview/index.ts
+++ b/src/store/localFilePreview/index.ts
@@ -60,13 +60,14 @@ const fetchSandboxFilePreview = async (
};
const fetchLocalFilePreview = (key: string): Promise<LocalFilePreview> => {
- const { allowExternalFile, deviceId, filePath, sandboxTopicId, workingDirectory } =
+ const { accept, allowExternalFile, deviceId, filePath, sandboxTopicId, workingDirectory } =
localFilePreviewTargetFromKey(key);
if (sandboxTopicId) return fetchSandboxFilePreview(filePath, sandboxTopicId);
// A local HTML file resolves its relative URLs against sibling files.
const resourceScope = !deviceId && isHtmlFile({ path: filePath }) ? 'workspace' : undefined;
return projectFileService.getLocalFilePreview({
+ ...(accept && { accept }),
allowExternalFile,
deviceId,
path: filePath,
diff --git a/src/store/localFilePreview/projection.ts b/src/store/localFilePreview/projection.ts
index 23a47af4dba..156ff79bcef 100644
--- a/src/store/localFilePreview/projection.ts
+++ b/src/store/localFilePreview/projection.ts
@@ -3,6 +3,11 @@ import type { LocalFilePreview } from '@/services/projectFile';
/** One file the local-file portal previews: where it lives and how it was opened. */
export interface LocalFilePreviewTarget {
+ /**
+ * Read the file only as an image (a chat input file tag's thumbnail): any
+ * other preview type is rejected instead of being read as text.
+ */
+ accept?: 'image';
/** A user-picked file outside the approved workspace roots. */
allowExternalFile?: boolean;
/** Remote device the file lives on; absent = this machine. */
@@ -31,8 +36,13 @@ export const MAX_PERSISTED_PREVIEWS = 30;
* The source kind and its id are separate fields: a device id is user-chosen
* (`lh connect --device-id`), so a device named `local` or `sandbox:x` must
* still decode as that device rather than this machine or a sandbox.
+ *
+ * An image-only read (`accept`) is a different request, so it is a trailing
+ * field appended only when set: the portal's keys (and their stored rows) stay
+ * as they were.
*/
export const localFilePreviewKey = ({
+ accept,
allowExternalFile,
deviceId,
filePath,
@@ -48,18 +58,21 @@ export const localFilePreviewKey = ({
workingDirectory,
filePath,
allowExternalFile ? 'external' : 'workspace',
+ ...(accept ? [accept] : []),
]);
/** The target a {@link localFilePreviewKey} was built from (fetcher side). */
export const localFilePreviewTargetFromKey = (key: string): LocalFilePreviewTarget => {
- const [kind, id, workingDirectory, filePath, access] = JSON.parse(key) as [
+ const [kind, id, workingDirectory, filePath, access, accept] = JSON.parse(key) as [
'device' | 'local' | 'sandbox',
string | null,
string,
string,
string,
+ 'image' | undefined,
];
return {
+ accept: accept === 'image' ? accept : undefined,
allowExternalFile: access === 'external' || undefined,
deviceId: kind === 'device' ? (id ?? undefined) : undefined,
filePath,
diff --git a/src/store/searchChannel/index.ts b/src/store/searchChannel/index.ts
new file mode 100644
index 00000000000..072ccfc1681
--- /dev/null
+++ b/src/store/searchChannel/index.ts
@@ -0,0 +1,70 @@
+import type { StoreApi } from 'zustand';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn, type UseBoundStoreWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ defineReplica,
+ recordLens,
+ type ReplicaState,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { searchService } from '@/services/search';
+
+/** Search providers and crawlers the server enables (`SEARCH_PROVIDERS` / `CRAWLER_IMPLS`). */
+export interface AvailableSearchChannels {
+ crawlerImpls: { id: string }[];
+ searchProviders: { id: string }[];
+}
+
+/** The server answers one list for everyone, so the replica keeps a single entry. */
+export const AVAILABLE_SEARCH_CHANNELS_KEY = 'default';
+
+/**
+ * Channels the Web Search settings page orders. Only channel ids are stored, in
+ * localStorage under the user / workspace scope, so a reload paints the last
+ * picker on the first frame while the server confirms it.
+ */
+export const availableSearchChannelsResource = defineReplica<string, AvailableSearchChannels>({
+ key: (key) => key,
+ name: 'availableSearchChannels',
+ storage: 'localStorage',
+ version: 1,
+});
+
+export interface SearchChannelStoreState {
+ channelsMap: Record<string, AvailableSearchChannels>;
+ channelsReplica: ReplicaState<AvailableSearchChannels>;
+}
+
+interface SearchChannelStore extends SearchChannelStoreState {
+ /** Fetch orchestration only; read the channels with `useAvailableSearchChannels`. */
+ useFetchAvailableChannels: () => ReplicaSyncResult;
+}
+
+export const initialSearchChannelState: SearchChannelStoreState = {
+ channelsMap: {},
+ channelsReplica: createReplicaState(),
+};
+
+export const useSearchChannelStore: UseBoundStoreWithEqualityFn<StoreApi<SearchChannelStore>> =
+ createWithEqualityFn<SearchChannelStore>()((set, get) => {
+ const channels = createReplicaSlice(availableSearchChannelsResource, {
+ actionPrefix: 'searchChannel/channels',
+ fetcher: () => searchService.getAvailableChannels(),
+ get,
+ set,
+ stateKey: 'channelsReplica',
+ view: recordLens<SearchChannelStore, AvailableSearchChannels>('channelsMap'),
+ });
+
+ return {
+ ...initialSearchChannelState,
+ useFetchAvailableChannels: () => channels.useSync(AVAILABLE_SEARCH_CHANNELS_KEY),
+ };
+ }, shallow);
+
+/** The available channels, or `undefined` while neither persisted nor fetched. */
+export const useAvailableSearchChannels = () =>
+ useSearchChannelStore((state) => state.channelsMap[AVAILABLE_SEARCH_CHANNELS_KEY]);