🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(work): move Works gallery, project works, sidebar history and versions onto a work replica (#21118)
Arvin Xu45b4a150b5c3
diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsxindex 55f6c15da81..74c42eb165f 100644--- a/src/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx+++ b/src/features/Conversation/WorkingSidebar/WorksSection/VersionList.tsx@@ -1,12 +1,10 @@import type { WorkVersionItem } from '@lobechat/types';import { Center, createStaticStyles, Flexbox, Spin, Text } from '@lobehub/ui';-import { memo } from 'react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { formatTaskItemDate } from '@/features/AgentTasks/features/formatTaskItemDate';-import { useClientDataSWR } from '@/libs/swr';-import { workKeys } from '@/libs/swr/keys';-import { workService } from '@/services/work';+import { useWorkStore, workActions, workSelectors } from '@/store/work';import { computeWorkVersionCostDeltas, formatWorkVersionCost } from '@/utils/workVersionCost';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -36,22 +34,22 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));+const EMPTY_VERSIONS: WorkVersionItem[] = [];+const VersionList = memo<{ workId: string }>(({ workId }) => {const { i18n, t } = useTranslation(['chat', 'common']);- const {- data = [],- error,- isLoading,- } = useClientDataSWR<WorkVersionItem[]>(- workKeys.versions(workId),- () => workService.listVersions(workId),- {- fallbackData: [],- revalidateOnFocus: false,- },- );+ const params = useMemo(() => ({ workId }), [workId]);+ const { error, isHydrated } = workActions.useFetchWorkVersions(params, {+ revalidateOnFocus: false,+ });+ // `undefined` while nothing is painted yet; the stored timeline paints first.+ const stored = useWorkStore(workSelectors.workVersions(workId));+ const data = stored ?? EMPTY_VERSIONS;++ // Before the stored copy is read, paint nothing rather than a spinner.+ if (stored === undefined && !error && !isHydrated) return null;- if (isLoading) {+ if (stored === undefined && !error) {return (<Center height={56}><Spin size="small" />@@ -59,7 +57,8 @@ const VersionList = memo<{ workId: string }>(({ workId }) => {);}- if (error) {+ // A failed refresh keeps the settled timeline on screen.+ if (stored === undefined && error) {return <Text className={styles.error}>{t('workingPanel.works.versionError')}</Text>;}diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/index.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/index.tsxindex d04c96dd08b..a4b86b99542 100644--- a/src/features/Conversation/WorkingSidebar/WorksSection/index.tsx+++ b/src/features/Conversation/WorkingSidebar/WorksSection/index.tsx@@ -2,17 +2,16 @@ import type { WorkListItem } from '@lobechat/types';import { ActionIcon, Center, createStaticStyles, Empty, Flexbox, Spin } from '@lobehub/ui';import isEqual from 'fast-deep-equal';import { ClipboardListIcon, HistoryIcon, ListIcon } from 'lucide-react';-import { memo, useEffect, useRef } from 'react';+import { memo, useEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { getAllWorkSummaries } from '@/features/Conversation/store/slices/data/workSummaries';import WorkSummaryCard from '@/features/Work/WorkSummaryCard';import { useLocalStorageState } from '@/hooks/useLocalStorageState';-import { useClientDataSWR } from '@/libs/swr';-import { workKeys } from '@/libs/swr/keys';import { workService } from '@/services/work';import { useChatStore } from '@/store/chat';import { dbMessageSelectors, operationSelectors } from '@/store/chat/selectors';+import { useWorkStore, workActions, workSelectors } from '@/store/work';import WorkVersionHistoryCard from './WorkVersionHistoryCard';@@ -20,6 +19,8 @@ type WorksViewMode = 'history' | 'summary';const WORKS_VIEW_MODE_STORAGE_KEY = 'lobechat-working-panel-works-view-mode';+const EMPTY_HISTORY: WorkListItem[] = [];+const styles = createStaticStyles(({ css, cssVar }) => ({container: css`min-height: 0;@@ -133,27 +134,30 @@ const WorksSection = memo<WorksSectionProps>(({ active = true }) => {}, [summaryData, isRunning, topicId, threadId]);// History (version timeline) is heavier and genuinely on-demand — keep it on- // its own lazy fetch, gated so a collapsed / inactive sidebar never pulls it.- const {- data: historyData = [],- error: historyError,- isLoading: isHistoryLoading,- } = useClientDataSWR<WorkListItem[]>(- mode === 'history' && topicId && active- ? workKeys.conversation(topicId, threadId ?? null)- : null,- () => workService.listByConversation({ threadId, topicId }),- {- fallbackData: [],- revalidateOnFocus: false,- },+ // its own lazy sync, gated so a collapsed / inactive sidebar never pulls it.+ // It is a replica: a revisit or reload paints the last history first.+ const historyParams = useMemo(+ () => (mode === 'history' && topicId && active ? { threadId, topicId } : null),+ [active, mode, threadId, topicId],);-- const isLoading = mode === 'history' ? isHistoryLoading : false;- const error = mode === 'history' ? historyError : undefined;+ const historySync = workActions.useFetchConversationWorks(historyParams, {+ revalidateOnFocus: false,+ });+ const storedHistory = useWorkStore(workSelectors.conversationWorks(historyParams));+ const historyData = storedHistory ?? EMPTY_HISTORY;+ const historyPending = !!historyParams && storedHistory === undefined;++ // Settled history stays on screen when a background refresh fails.+ const error = historyPending ? historySync.error : undefined;+ // Before the stored copy is read, paint nothing rather than a spinner the+ // cached history replaces a frame later.+ const isHydrating = historyPending && !historySync.isHydrated;+ const isLoading = historyPending && !error && !isHydrating;const data = mode === 'summary' ? summaryData : historyData;const content = (() => {+ if (isHydrating) return null;+if (isLoading) {return (<Center flex={1}>diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsxindex 1799b0d35e2..9d1d3b63e4c 100644--- a/src/features/Projects/Workspace/ProjectDashboard.tsx+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx@@ -39,11 +39,9 @@ import {import WorkSummaryCard from '@/features/Work/WorkSummaryCard';import { useOpenWork } from '@/features/WorkGallery/useOpenWork';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useClientDataSWR } from '@/libs/swr';-import { workKeys } from '@/libs/swr/keys';-import { workService } from '@/services/work';import { goalSelectors, useGoalStore } from '@/store/goal';import type { ProjectDetail } from '@/store/project';+import { useWorkStore, workActions, workSelectors } from '@/store/work';const styles = createStaticStyles(({ css }) => ({attention: css`@@ -117,6 +115,7 @@ const styles = createStaticStyles(({ css }) => ({}));const TERMINAL_STATUSES = new Set<TaskStatus | string>(['canceled', 'completed']);+const EMPTY_WORKS: WorkSummaryItem[] = [];const ATTENTION_STATUSES = new Set<TaskStatus | string>(['failed', 'paused']);interface ProjectDashboardProps {detail: ProjectDetail;@@ -155,23 +154,21 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =>const goalSWR = useGoalStore((s) => s.useFetchGoals)(undefined, projectId);const coordinatorAgentId = detail.project.coordinatorAgentId;const projectReference = detail.project.slug ?? projectId;- const workSWR = useClientDataSWR(- coordinatorAgentId- ? workKeys.workspace(workspaceId, `project:${projectId}:${coordinatorAgentId}`)- : null,- () =>- workService.listByWorkspace({- limit: 4,- originAgentId: coordinatorAgentId,- }),+ const agentWorksParams = useMemo(+ () => (coordinatorAgentId ? { originAgentId: coordinatorAgentId, workspaceId } : null),+ [coordinatorAgentId, workspaceId],);+ const workSync = workActions.useFetchAgentWorks(agentWorksParams);+ // `undefined` while nothing is painted yet; the stored copy paints first.+ const storedWorks = useWorkStore(workSelectors.agentWorks(coordinatorAgentId));const tasks = detail.tasks ?? [];const activeTasks = tasks.filter((task) => !TERMINAL_STATUSES.has(task.status)).slice(0, 5);const attentionTasks = tasks.filter((task) => ATTENTION_STATUSES.has(task.status)).slice(0, 3);const completedGoals = goals.filter(({ goal }) => goal.status === 'achieved').length;const progress = goals.length ? Math.round((completedGoals / goals.length) * 100) : 0;- const works = workSWR.data?.items ?? [];+ const works = storedWorks ?? EMPTY_WORKS;+ const worksPending = !!coordinatorAgentId && storedWorks === undefined;const goalPreview = useMemo(() => goals.slice(0, 3), [goals]);return (@@ -265,14 +262,16 @@ const ProjectDashboard = memo<ProjectDashboardProps>(({ detail, projectId }) =><Flexbox className={styles.section} gap={12}><SectionTitle count={works.length} title={t('overview.latestWorks')} />- {workSWR.error ? (+ {workSync.error && worksPending ? (<AsyncError- error={workSWR.error}+ error={workSync.error}variant={'inline'}- onRetry={() => void workSWR.mutate()}+ onRetry={() => void workSync.revalidate()}/>- ) : workSWR.isLoading ? (- <ArticleSkeleton rows={4} />+ ) : worksPending ? (+ // Before the stored copy is read, paint nothing rather than a+ // skeleton that the cached cards replace a frame later.+ workSync.isHydrated && <ArticleSkeleton rows={4} />) : works.length === 0 ? (<Emptydescription={t('overview.worksEmptyDescription')}diff --git a/src/features/Work/useRemoveWork.ts b/src/features/Work/useRemoveWork.tsindex f77d4747d6c..98c18b97162 100644--- a/src/features/Work/useRemoveWork.ts+++ b/src/features/Work/useRemoveWork.ts@@ -4,6 +4,7 @@ import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { workService } from '@/services/work';+import { workActions } from '@/store/work';/*** User-initiated removal of a Work card. Intended for orphaned Works (the@@ -12,13 +13,7 @@ import { workService } from '@/services/work';* delete cascades the Work's version history and any project pins.*/export interface UseRemoveWorkOptions {- /**- * Called after the Work is deleted and the global Work caches are refreshed.- * Lists backed by `useSWRInfinite` (e.g. the resource-page gallery) need- * this: SWR's filter-form `mutate` skips their `$inf$` cache keys, so the- * global refresh below never reaches them and the card would linger until a- * reload — the owner passes its bound `mutate` here instead.- */+ /** Called after the Work is deleted and the Work caches are refreshed. */onRemoved?: () => void | Promise<void>;}@@ -45,6 +40,9 @@ export const useRemoveWork = ({ onRemoved }: UseRemoveWorkOptions = {}) => {onOk: async () => {try {await workService.deleteWork(item.id);+ // Drop the card from every Work replica (and their persisted rows)+ // right away, so neither a list on screen nor a reload paints it.+ workActions.removeWork(item.id);// The orphan may be surfaced in the gallery, the sidebar and any// message it was registered from, so refresh every Work view.await workService.refreshAllConversations();diff --git a/src/features/WorkGallery/hooks.test.ts b/src/features/WorkGallery/hooks.test.tsindex 3335fd0e0f0..d632a5198c8 100644--- a/src/features/WorkGallery/hooks.test.ts+++ b/src/features/WorkGallery/hooks.test.ts@@ -1,34 +1,32 @@/*** @vitest-environment happy-dom*/-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { randomUUID } from 'node:crypto';+import type { WorkSummaryItem } from '@lobechat/types';+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 { documentService } from '@/services/document';+import { workService } from '@/services/work';+import { initialWorkState, useWorkStore } from '@/store/work';+import { workspaceWorksResource } from '@/store/work/projection';import { useWorkspaceWorksInfinite } from './hooks';const mocks = vi.hoisted(() => ({deleteDocument: vi.fn(),deleteDocuments: vi.fn(),- globalMutate: vi.fn(),- infiniteMutate: vi.fn(),- setSize: vi.fn(),-}));--vi.mock('swr/infinite', () => ({- default: vi.fn(() => ({- data: [{ items: [], nextCursor: null }],- error: undefined,- isLoading: false,- isValidating: false,- mutate: mocks.infiniteMutate,- setSize: mocks.setSize,- size: 1,- })),+ listByWorkspace: vi.fn(),}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => null,useActiveWorkspaceId: () => null,}));@@ -37,94 +35,126 @@ vi.mock('@/features/ResourceManager/store', () => ({selector({ listVisibility: 'private' }),}));-vi.mock('@/libs/swr', () => ({- mutate: (...args: unknown[]) => mocks.globalMutate(...args),-}));-vi.mock('@/libs/trpc/client', () => ({lambdaClient: {document: {deleteDocument: { mutate: (...args: unknown[]) => mocks.deleteDocument(...args) },deleteDocuments: { mutate: (...args: unknown[]) => mocks.deleteDocuments(...args) },},- work: {},+ work: {+ listByWorkspace: { query: (...args: unknown[]) => mocks.listByWorkspace(...args) },+ },},}));+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,+ );++const summary = (id: string, title = id) =>+ ({ id, resourceType: 'document', title, type: 'document' }) as unknown as WorkSummaryItem;++const ALL = { workspaceId: null };++let scope = '';+beforeEach(() => {- vi.clearAllMocks();+ scope = `gallery-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useWorkStore.setState({ ...initialWorkState }));mocks.deleteDocument.mockResolvedValue(undefined);mocks.deleteDocuments.mockResolvedValue(undefined);- mocks.globalMutate.mockResolvedValue([]);- mocks.infiniteMutate.mockResolvedValue([]);+ mocks.listByWorkspace.mockResolvedValue({ items: [summary('wk_1')], nextCursor: null });+});++afterEach(async () => {+ await workspaceWorksResource.storage!.remove({+ queryKey: workspaceWorksResource.storageKey(ALL),+ scope,+ });+ vi.restoreAllMocks();+ vi.clearAllMocks();});describe('useWorkspaceWorksInfinite', () => {- it.each([- ['one document', () => documentService.deleteDocument('doc-1')],- ['multiple documents', () => documentService.deleteDocuments(['doc-1', 'doc-2'])],- ])('refreshes the mounted gallery after deleting %s', async (_label, removeDocuments) => {- const { unmount } = renderHook(() => useWorkspaceWorksInfinite('all'));+ it('paints the last stored works on a revisit without an initial loading state', async () => {+ await workspaceWorksResource.storage!.set(+ { queryKey: workspaceWorksResource.storageKey(ALL), scope },+ {+ data: {+ currentPage: 0,+ hasMore: false,+ items: [summary('wk_1', 'Cached')],+ nextCursor: null,+ pageSize: 1,+ pages: [{ count: 1, next: null }],+ },+ updatedAt: 1,+ },+ );+ mocks.listByWorkspace.mockImplementation(() => new Promise(() => {}));- await act(removeDocuments);+ const { result } = renderHook(() => useWorkspaceWorksInfinite('all'), { wrapper });- expect(mocks.infiniteMutate).toHaveBeenCalledTimes(1);- unmount();+ await waitFor(() => expect(result.current.items.map((i) => i.title)).toEqual(['Cached']));+ expect(result.current.isLoadingInitial).toBe(false);+ expect(result.current.isValidating).toBe(true);});- it('stops refreshing a gallery after it unmounts', async () => {- const { unmount } = renderHook(() => useWorkspaceWorksInfinite('all'));- unmount();+ it('pages forward with the cursor of the loaded head page', async () => {+ mocks.listByWorkspace+ .mockResolvedValueOnce({ items: [summary('wk_1')], nextCursor: 'c1' })+ .mockResolvedValueOnce({ items: [summary('wk_2')], nextCursor: null });+ const { result } = renderHook(() => useWorkspaceWorksInfinite('all'), { wrapper });+ await waitFor(() => expect(result.current.hasMore).toBe(true));- await documentService.deleteDocument('doc-1');+ act(() => result.current.loadMore());- expect(mocks.infiniteMutate).not.toHaveBeenCalled();+ await waitFor(() => expect(result.current.items.map((i) => i.id)).toEqual(['wk_1', 'wk_2']));+ expect(mocks.listByWorkspace).toHaveBeenLastCalledWith(+ expect.objectContaining({ cursor: 'c1', includeFileWorks: true, limit: 30 }),+ );+ expect(result.current.hasMore).toBe(false);});- it('keeps a completed document deletion successful when gallery refresh fails', async () => {- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});- const { unmount } = renderHook(() => useWorkspaceWorksInfinite('all'));- mocks.infiniteMutate.mockRejectedValueOnce(new Error('refresh failed'));+ it.each([+ ['one document', () => documentService.deleteDocument('doc-1')],+ ['multiple documents', () => documentService.deleteDocuments(['doc-1', 'doc-2'])],+ ])('refreshes the mounted gallery after deleting %s', async (_label, removeDocuments) => {+ const { result, unmount } = renderHook(() => useWorkspaceWorksInfinite('all'), { wrapper });+ await waitFor(() => expect(result.current.items.map((i) => i.id)).toEqual(['wk_1']));+ mocks.listByWorkspace.mockResolvedValue({ items: [summary('wk_2')], nextCursor: null });- await expect(documentService.deleteDocument('doc-1')).resolves.toBeUndefined();+ await act(removeDocuments);- expect(mocks.deleteDocument).toHaveBeenCalledWith({ id: 'doc-1' });- expect(consoleError).toHaveBeenCalledWith(- '[DocumentService] Failed to refresh Works after document deletion:',- expect.any(Error),- );+ await waitFor(() => expect(result.current.items.map((i) => i.id)).toEqual(['wk_2']));unmount();- consoleError.mockRestore();});- it('waits for the gallery refresh when another cache refresh fails', async () => {+ it('keeps a completed document deletion successful when gallery refresh fails', async () => {const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});- const { unmount } = renderHook(() => useWorkspaceWorksInfinite('all'));- let resolveGalleryRefresh!: () => void;- mocks.infiniteMutate.mockImplementationOnce(- () =>- new Promise<void>((resolve) => {- resolveGalleryRefresh = resolve;- }),+ vi.spyOn(workService, 'refreshWorkspaceLists').mockRejectedValueOnce(+ new Error('refresh failed'),);- mocks.globalMutate.mockRejectedValueOnce(new Error('refresh failed'));-- let deletionSettled = false;- const deletion = documentService.deleteDocument('doc-1').finally(() => {- deletionSettled = true;- });- await vi.waitFor(() => expect(mocks.infiniteMutate).toHaveBeenCalledTimes(1));- expect(deletionSettled).toBe(false);- resolveGalleryRefresh();- await expect(deletion).resolves.toBeUndefined();+ await expect(documentService.deleteDocument('doc-1')).resolves.toBeUndefined();- expect(deletionSettled).toBe(true);+ expect(mocks.deleteDocument).toHaveBeenCalledWith({ id: 'doc-1' });expect(consoleError).toHaveBeenCalledWith('[DocumentService] Failed to refresh Works after document deletion:',expect.any(Error),);- unmount();- consoleError.mockRestore();});});diff --git a/src/features/WorkGallery/hooks.ts b/src/features/WorkGallery/hooks.tsindex 43e6f3bd7f0..36ef9961f6b 100644--- a/src/features/WorkGallery/hooks.ts+++ b/src/features/WorkGallery/hooks.ts@@ -1,104 +1,89 @@-import { useCallback, useEffect } from 'react';-import useSWRInfinite from 'swr/infinite';+import { useCallback, useEffect, useMemo } from 'react';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useResourceManagerStore } from '@/features/ResourceManager/store';+import type { ResourceListVisibilityFilter } from '@/features/ResourceManager/store/initialState';import { getResourceQueryVisibility } from '@/features/ResourceManager/store/selectors';-import { workKeys } from '@/libs/swr/keys';-import type { WorkSummaryPage } from '@/services/work';-import { workService } from '@/services/work';+import { useWorkStore, workActions, workSelectors, type WorkspaceWorksParams } from '@/store/work';import { workFilterFromKey, type WorkGalleryKey } from './const';-const WORK_GALLERY_PAGE_SIZE = 30;+const EMPTY_ITEMS: never[] = [];++/**+ * Replica params of one gallery filter. Personal Works have no workspace mode+ * switch, so keep the historical unfiltered query there. Inside a workspace,+ * mirror every other Resources surface: Private means caller-owned private+ * rows; Workspace means public rows shared with the team.+ */+export const workspaceWorksParams = (+ galleryKey: WorkGalleryKey,+ workspaceId: string | null,+ listVisibility: ResourceListVisibilityFilter,+): WorkspaceWorksParams => {+ const { provider, type } = workFilterFromKey(galleryKey);+ return {+ provider,+ type,+ visibility: workspaceId ? getResourceQueryVisibility(undefined, listVisibility) : undefined,+ workspaceId,+ };+};/*** Cursor-paginated, infinite-scrolling Work summaries scoped to the active* workspace (or personal space). `galleryKey` selects the filter (a Work type,- * a skill provider, or the combined `all` view). Changing it collapses back to- * the first page. Mirrors `useVerifyReportSummariesInfinite`.+ * a skill provider, or the combined `all` view). Each filter is its own+ * local-first replica entry: a revisit or reload paints the last head page+ * while the network confirms; switching back to a filter collapses it to that+ * head page.*/export const useWorkspaceWorksInfinite = (galleryKey: WorkGalleryKey) => {const workspaceId = useActiveWorkspaceId();const listVisibility = useResourceManagerStore((s) => s.listVisibility);- const filter = workFilterFromKey(galleryKey);- // Personal Works have no workspace mode switch, so keep the historical- // unfiltered query there. Inside a workspace, mirror every other Resources- // surface: Private means caller-owned private rows; Workspace means public- // rows shared with the team.- const visibility = workspaceId- ? getResourceQueryVisibility(undefined, listVisibility)- : undefined;-- const getKey = useCallback(- (_index: number, previous: WorkSummaryPage | null) => {- // Stop paging once the previous page reported no further cursor.- if (previous && previous.nextCursor === null) return null;- return workKeys.workspace(- workspaceId,- galleryKey,- previous?.nextCursor ?? undefined,- visibility,- );- },- [galleryKey, visibility, workspaceId],+ const { provider, type, visibility } = workspaceWorksParams(+ galleryKey,+ workspaceId,+ listVisibility,);-- const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(- getKey,- ([, , , cursor, keyVisibility]: readonly [- string,- string | null,- string,- string | null,- 'private' | 'public' | null,- ]) =>- workService.listByWorkspace({- cursor: cursor || undefined,- limit: WORK_GALLERY_PAGE_SIZE,- provider: filter.provider,- type: filter.type ?? null,- visibility: keyVisibility ?? undefined,- }),- { revalidateFirstPage: false },+ const params = useMemo<WorkspaceWorksParams>(+ () => ({ provider, type, visibility, workspaceId }),+ [provider, type, visibility, workspaceId],);- // A new filter starts a fresh key series; collapse size back to 1 so we- // don't cascade-fetch as many pages as the previous filter had loaded.- useEffect(() => {- setSize(1);- }, [galleryKey, setSize, visibility]);+ const list = useWorkStore(workSelectors.workspaceWorks(params));+ const { error: headError, isValidating, revalidate } = workActions.useFetchWorkspaceWorks(params);- useEffect(() => workService.registerWorkspaceListRefresh(() => mutate()), [mutate]);+ // A filter switched to starts again from its head page, not the pages an+ // earlier visit loaded.+ useEffect(() => {+ workActions.collapseWorkspaceWorks(params);+ }, [params]);+ const loadMoreError = list?.loadMoreError;const loadMore = useCallback(() => {- void setSize((s) => s + 1);- }, [setSize]);+ void workActions.loadMoreWorkspaceWorks(params);+ }, [params]);+ // The inline retry re-asks for the page that failed; a head failure+ // revalidates the head.const reload = useCallback(() => {- void mutate();- }, [mutate]);-- // SWR leaves a failed/pending page's slot `undefined`, so guard the holes.- const items = data?.flatMap((page) => page?.items ?? []) ?? [];- const lastLoadedPage = data?.findLast(Boolean);- const reachedEnd = lastLoadedPage ? lastLoadedPage.nextCursor === null : false;-- // A subsequent page is genuinely in flight only when it hasn't errored — an- // errored page also leaves its slot undefined, but must not read as loading.- const isLoadingMore =- !error && (isLoading || (size > 0 && !!data && typeof data[size - 1] === 'undefined'));+ if (loadMoreError) loadMore();+ else void revalidate();+ }, [loadMore, loadMoreError, revalidate]);- // Pause the sentinel while an error is showing so it can't hot-loop the failed- // page; the gallery offers a manual retry (`reload`) instead.- const hasMore = !reachedEnd && !error;+ const error = headError ?? loadMoreError;+ // `undefined` = nothing painted yet (no stored copy, no response).+ const isLoadingInitial = list === undefined && !headError;return {error,- hasMore,- isLoadingInitial: isLoading,- isLoadingMore,+ // Pause the sentinel while an error is showing so it can't hot-loop the+ // failed page; the gallery offers a manual retry (`reload`) instead.+ hasMore: !!list?.hasMore && !error,+ isLoadingInitial,+ isLoadingMore: !!list?.isLoadingMore,isValidating,- items,+ items: list?.items ?? EMPTY_ITEMS,loadMore,reload,};diff --git a/src/routes/(main)/resource/(home)/worksLoader.test.ts b/src/routes/(main)/resource/(home)/worksLoader.test.tsnew file mode 100644index 00000000000..7c7bc1a44db--- /dev/null+++ b/src/routes/(main)/resource/(home)/worksLoader.test.ts@@ -0,0 +1,128 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { initialState } from '@/features/ResourceManager/store/initialState';++import { galleryKeyOfUrl, worksLoader } from './worksLoader';++const mocks = vi.hoisted(() => ({+ preHydrateWorkspaceWorks: vi.fn(),+ workspaceId: null as string | null,+ workspaceSlug: null as string | null,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ getActiveWorkspaceSlug: () => mocks.workspaceSlug,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => mocks.workspaceId,+}));++vi.mock('@/features/ResourceManager/store/modePersistence', () => ({+ readPersistedResourceMode: (workspaceId?: string) =>+ workspaceId === 'ws_private' ? 'private' : undefined,+}));++vi.mock('@/store/work', () => ({+ workActions: { preHydrateWorkspaceWorks: mocks.preHydrateWorkspaceWorks },+}));++const load = (url: string, params: Record<string, string> = {}) =>+ worksLoader({ context: undefined, params, request: new Request(url) } as any);++beforeEach(() => {+ mocks.preHydrateWorkspaceWorks.mockReset().mockResolvedValue(true);+ mocks.workspaceId = null;+ mocks.workspaceSlug = null;+ useResourceManagerStore.setState({ listVisibility: initialState.listVisibility });+});++describe('galleryKeyOfUrl', () => {+ it.each([+ ['https://app.test/resource', 'all'],+ ['https://app.test/acme/resource/', 'all'],+ ['https://app.test/resource/works', 'all'],+ ['https://app.test/resource/works?works=task', 'task'],+ ['https://app.test/resource/works?works=bogus', 'all'],+ ['https://app.test/resource/documents', null],+ ['https://app.test/page', null],+ ])('%s → %s', (url, key) => {+ expect(galleryKeyOfUrl(new URL(url))).toBe(key);+ });+});++describe('worksLoader', () => {+ it('seeds the personal gallery filter the URL encodes', async () => {+ await load('https://app.test/resource/works?works=document');++ expect(mocks.preHydrateWorkspaceWorks).toHaveBeenCalledWith({+ provider: undefined,+ type: 'document',+ visibility: undefined,+ workspaceId: null,+ });+ });++ it('uses the persisted Private / Workspace mode of the active workspace', async () => {+ mocks.workspaceId = 'ws_private';+ await load('https://app.test/resource');+ expect(mocks.preHydrateWorkspaceWorks).toHaveBeenLastCalledWith(+ expect.objectContaining({ visibility: 'private', workspaceId: 'ws_private' }),+ );++ mocks.workspaceId = 'ws_other';+ await load('https://app.test/resource');+ expect(mocks.preHydrateWorkspaceWorks).toHaveBeenLastCalledWith(+ expect.objectContaining({ visibility: 'public', workspaceId: 'ws_other' }),+ );+ });++ it('restores the persisted mode into the ResourceManager store before the page renders', async () => {+ mocks.workspaceId = 'ws_private';+ await load('https://app.test/resource/works');++ // The gallery hook reads `listVisibility` from this store on its first+ // render; it must select the same (prehydrated) private entry.+ expect(useResourceManagerStore.getState().listVisibility).toBe('private');+ });++ it('skips resource categories that show no Works', async () => {+ await load('https://app.test/resource/images');+ expect(mocks.preHydrateWorkspaceWorks).not.toHaveBeenCalled();+ });++ it('seeds when the destination route is the active workspace', async () => {+ mocks.workspaceId = 'ws_other';+ mocks.workspaceSlug = 'acme';++ await load('https://app.test/acme/resource', { workspaceSlug: 'acme' });++ expect(mocks.preHydrateWorkspaceWorks).toHaveBeenCalledWith(+ expect.objectContaining({ workspaceId: 'ws_other' }),+ );+ });++ it.each([+ ['another workspace', 'https://app.test/beta/resource', { workspaceSlug: 'beta' }, 'acme'],+ ['the personal space', 'https://app.test/resource', {}, 'acme'],+ [+ 'a workspace from the personal space',+ 'https://app.test/acme/resource',+ { workspaceSlug: 'acme' },+ null,+ ],+ ])(+ 'skips a navigation into %s while the previous scope is still active',+ async (_label, url, params, activeSlug) => {+ mocks.workspaceId = activeSlug ? 'ws_private' : null;+ mocks.workspaceSlug = activeSlug;++ await load(url, params);++ expect(mocks.preHydrateWorkspaceWorks).not.toHaveBeenCalled();+ // Nor does it restore the left space's mode into the store.+ expect(useResourceManagerStore.getState().listVisibility).toBe(initialState.listVisibility);+ },+ );+});diff --git a/src/routes/(main)/resource/(home)/worksLoader.ts b/src/routes/(main)/resource/(home)/worksLoader.tsnew file mode 100644index 00000000000..e66c19f2116--- /dev/null+++ b/src/routes/(main)/resource/(home)/worksLoader.ts@@ -0,0 +1,57 @@+import type { LoaderFunctionArgs } from 'react-router';++import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { parseWorkGalleryKey, type WorkGalleryKey } from '@/features/WorkGallery/const';+import { workspaceWorksParams } from '@/features/WorkGallery/hooks';+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { workActions } from '@/store/work';++/**+ * The Work gallery filter a resource URL paints: the dashboard's recent works+ * (`/resource`) and the gallery (`/resource/works?works=<key>`). Other+ * categories show no Works.+ */+export const galleryKeyOfUrl = (url: URL): WorkGalleryKey | null => {+ const segment = url.pathname.match(/\/resource(?:\/([^/]+))?\/?$/);+ if (!segment) return null;+ if (!segment[1]) return 'all';+ if (segment[1] !== 'works') return null;+ return parseWorkGalleryKey(url.searchParams.get('works')) ?? 'all';+};++/**+ * Seed the persisted Work gallery head page for the filter the URL encodes.+ *+ * Route loaders run before React commits the route: the only point where the+ * persisted list (an async read) can land before the page paints its loading+ * skeleton. The visibility is the persisted Private / Workspace mode the+ * resource sidebar restores for this workspace; the loader restores it into+ * the ResourceManager store first, so the page's first render reads the same+ * mode (and the same replica entry) instead of the store default.+ */+export const worksLoader = async ({ params, request }: LoaderFunctionArgs): Promise<null> => {+ const galleryKey = galleryKeyOfUrl(new URL(request.url));+ if (!galleryKey) return null;++ // A navigation into another workspace (or back to the personal space) runs+ // this loader before the destination commits and switches the scope, so the+ // active workspace and replica scope still describe the space being left.+ // Seeding them would read the wrong space; the page hydrates on mount once+ // the scope has switched.+ if ((params.workspaceSlug ?? null) !== getActiveWorkspaceSlug()) return null;++ const workspaceId = getActiveWorkspaceId();+ useResourceManagerStore.getState().hydrateListVisibility(workspaceId ?? undefined);+ const { listVisibility } = useResourceManagerStore.getState();++ await settleWithin(+ workActions.preHydrateWorkspaceWorks(+ workspaceWorksParams(galleryKey, workspaceId, listVisibility),+ ),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/services/work.ts b/src/services/work.tsindex e526e7a3d1f..20baa8a4aa3 100644--- a/src/services/work.ts+++ b/src/services/work.ts@@ -58,8 +58,6 @@ export const didToolMutateWorkView = ({};class WorkService {- private readonly workspaceListRefreshers = new Set<() => Promise<unknown>>();-// This client ships the descriptor fallback for every registered Work type, so// it always opts into the `file` type (and any future gated type). The flag is// set here at the service boundary rather than per call site — an@@ -150,27 +148,27 @@ class WorkService {};refreshAll = async () => {+ await this.#collapseWorkspaceTails();await mutate(matchDomain('work:'));};/**- * Register a mounted workspace gallery's bound SWR Infinite revalidator.- *- * SWR intentionally skips `$inf$` keys for filter-form global mutations, so- * mutations outside the gallery cannot otherwise refresh its aggregate page- * cache. The returned cleanup keeps this registry scoped to mounted lists.+ * Revalidate every mounted workspace Work list (the gallery filters and the+ * project dashboards). Their replicas sync through `work:workspace` keys.*/- registerWorkspaceListRefresh = (refresh: () => Promise<unknown>) => {- this.workspaceListRefreshers.add(refresh);-- return () => {- this.workspaceListRefreshers.delete(refresh);- };+ refreshWorkspaceLists = async () => {+ await this.#collapseWorkspaceTails();+ await mutate((key) => Array.isArray(key) && key[0] === workKeys.workspace.root);};- /** Refresh every mounted workspace Work list through its bound SWR mutation. */- refreshWorkspaceLists = async () => {- await Promise.all([...this.workspaceListRefreshers].map((refresh) => refresh()));+ /**+ * The gallery replica only re-requests its head page, so loaded tail pages+ * are dropped first rather than left stale. Imported on demand: the work+ * store depends on this service.+ */+ #collapseWorkspaceTails = async () => {+ const { workActions } = await import('@/store/work');+ workActions.collapseWorkspaceWorksTails();};/**diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 324f5c51a56..c8a613b78aa 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -89,6 +89,7 @@ import { preferenceListLoader } from '@/spa/router/preferenceListLoader';import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';import { withSegmentFallback } from '@/spa/router/withSegmentFallback';+import { worksLoader } from '@/spa/router/worksLoader';import { SettingsTabs } from '@/store/global/initialState';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';@@ -672,6 +673,7 @@ export const sharedMainAreaChildren: RouteObject[] = [}),},index: true,+ loader: worksLoader,},...BusinessResourceRoutes,...resourceCategoryRoutes,@@ -699,6 +701,7 @@ export const sharedMainAreaChildren: RouteObject[] = [handle: {meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),},+ loader: worksLoader,path: ':category',},],diff --git a/src/spa/router/worksLoader.ts b/src/spa/router/worksLoader.tsnew file mode 100644index 00000000000..3c557e27069--- /dev/null+++ b/src/spa/router/worksLoader.ts@@ -0,0 +1,7 @@+import type { LoaderFunctionArgs } from 'react-router';++// The route tables sit in the entry chunk's static graph; resolving the real+// loader on first use keeps the work store in the resource route's lazy+// chunks. The request carries the gallery filter (`?works=`).+export const worksLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/resource/(home)/worksLoader').then((module) => module.worksLoader(args));diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.tsindex f7f4e94cfa8..cacd9dd4c9b 100644--- a/src/store/utils/userDataStores.test.ts+++ b/src/store/utils/userDataStores.test.ts@@ -5,6 +5,7 @@ const storeResets = vi.hoisted(() => [] as Array<() => void>);const pageReset = vi.hoisted(() => vi.fn());const resourcePermissionReset = vi.hoisted(() => vi.fn());const sandboxReset = vi.hoisted(() => vi.fn());+const workReset = vi.hoisted(() => vi.fn());const fakeStore = vi.hoisted(() => () => ({getState: () => {const reset = vi.fn();@@ -40,6 +41,7 @@ vi.mock('@/store/tool', () => ({ useToolStore: fakeStore() }));vi.mock('@/store/user', () => ({ useUserStore: fakeStore() }));vi.mock('@/store/userMemory', () => ({ useUserMemoryStore: fakeStore() }));vi.mock('@/store/video', () => ({ useVideoStore: fakeStore() }));+vi.mock('@/store/work', () => ({ workActions: { reset: workReset } }));describe('stores.reset', () => {beforeEach(() => {@@ -48,6 +50,7 @@ describe('stores.reset', () => {pageReset.mockClear();resourcePermissionReset.mockClear();sandboxReset.mockClear();+ workReset.mockClear();});it('tears down the gateway mux registry before wiping the user-data stores', async () => {@@ -64,6 +67,7 @@ describe('stores.reset', () => {// outlive the data context, even when the next one reuses the scope string.expect(resourcePermissionReset).toHaveBeenCalledTimes(1);expect(sandboxReset).toHaveBeenCalledTimes(1);+ expect(workReset).toHaveBeenCalledTimes(1);for (const reset of storeResets) expect(reset).toHaveBeenCalledTimes(1);expect(order[0]).toBe('mux');});diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.tsindex 512c596cab0..5bd7689d445 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -25,6 +25,7 @@ import { useUserStore } from '@/store/user';import { useUserMemoryStore } from '@/store/userMemory';import type { ResetableStore } from '@/store/utils/resetableStore';import { useVideoStore } from '@/store/video';+import { workActions } from '@/store/work';interface ResetableStoreApi {getState: () => ResetableStore;@@ -57,6 +58,7 @@ const resetableActions: ResetableStore[] = [projectFileActions,resourcePermissionActions,sandboxActions,+ workActions,];export interface StoreActions extends ResetableStore {}diff --git a/src/store/work/action.ts b/src/store/work/action.tsnew file mode 100644index 00000000000..7ca16cbedf3--- /dev/null+++ b/src/store/work/action.ts@@ -0,0 +1,102 @@+import type { ReplicaSyncOptions } from '@lobechat/replica/zustand';+import type { WorkListItem, WorkVersionItem } from '@lobechat/types';++import type { ReplicaSyncResult } from '@/libs/replica';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { initialWorkState, type WorkState } from './initialState';+import { WorkPrivateAction } from './privateAction';+import {+ type AgentWorksParams,+ type ConversationWorksParams,+ workspaceWorksKey,+ type WorkspaceWorksParams,+ type WorkVersionsParams,+} from './projection';+import { useWorkStore } from './store';++const n = setNamespace('work');++type Setter = StoreSetter<WorkState>;++/**+ * Work lists the UI paints from a local copy: the workspace gallery, the+ * project dashboard's latest works, and the working sidebar's history and+ * version timelines. Each is a replica (first frame from storage, the network+ * confirms); Work mutations keep revalidating them through the `work:` sync+ * keys (`workService.refresh*`).+ */+export class WorkActionImpl {+ readonly #get: () => WorkState;+ readonly #private: WorkPrivateAction;+ readonly #set: Setter;++ constructor(set: Setter, get: () => WorkState, privateAction: WorkPrivateAction) {+ this.#get = get;+ this.#set = set;+ this.#private = privateAction;+ }++ /** Back to a filter's head page, e.g. when the gallery switches to it again. */+ collapseWorkspaceWorks = (params: WorkspaceWorksParams): void => {+ this.#private.workspaceWorks.collapse(workspaceWorksKey(params));+ };++ /**+ * Before a Work change refreshes the `work:` sync keys: drop every gallery+ * filter's loaded tail pages. Only the head page is re-requested, and a tail+ * kept behind an unchanged head would go on showing a Work as it was (e.g. a+ * card whose document was just deleted). The tail loads again on scroll.+ */+ collapseWorkspaceWorksTails = (): void => {+ for (const [key, data] of Object.entries(this.#get().workspaceWorksMap)) {+ if (data.currentPage > 0) this.#private.workspaceWorks.collapse(key);+ }+ };++ loadMoreWorkspaceWorks = async (params: WorkspaceWorksParams): Promise<void> => {+ await this.#private.workspaceWorks.loadMore(workspaceWorksKey(params), params);+ };++ /** Seed a gallery filter from storage before its route paints (route loaders). */+ preHydrateWorkspaceWorks = (params: WorkspaceWorksParams): Promise<boolean> =>+ this.#private.preHydrateWorkspaceWorks(params);++ /**+ * A deleted Work card leaves every list that showed it — including the+ * persisted rows of lists not on screen, so a reload cannot paint it again.+ */+ removeWork = (id: string): void => {+ this.#private.works.remove(id);+ this.#private.versions.remove(id);+ };++ reset = (): void => {+ this.#set(initialWorkState, false, n('reset'));+ };++ useFetchAgentWorks = (params: AgentWorksParams | null): ReplicaSyncResult =>+ this.#private.agentWorks.useSync(params);++ useFetchConversationWorks = (+ params: ConversationWorksParams | null,+ options?: ReplicaSyncOptions<WorkListItem[], WorkListItem[]>,+ ): ReplicaSyncResult => this.#private.conversationWorks.useSync(params, options);++ useFetchWorkVersions = (+ params: WorkVersionsParams | null,+ options?: ReplicaSyncOptions<WorkVersionItem[], WorkVersionItem[]>,+ ): ReplicaSyncResult => this.#private.versions.useSync(params, options);++ useFetchWorkspaceWorks = (params: WorkspaceWorksParams | null): ReplicaSyncResult =>+ this.#private.workspaceWorks.useSync(params);+}++const { getState, setState } = useWorkStore;++export const workActions = new WorkActionImpl(+ setState,+ getState,+ new WorkPrivateAction(setState, getState),+);diff --git a/src/store/work/index.ts b/src/store/work/index.tsnew file mode 100644index 00000000000..8e0eecb7f83--- /dev/null+++ b/src/store/work/index.ts@@ -0,0 +1,10 @@+export { workActions } from './action';+export { type WorkspaceWorksData, type WorkState } from './initialState';+export {+ type AgentWorksParams,+ type ConversationWorksParams,+ type WorkspaceWorksParams,+ type WorkVersionsParams,+} from './projection';+export { workSelectors } from './selectors';+export { useWorkStore } from './store';diff --git a/src/store/work/initialState.ts b/src/store/work/initialState.tsnew file mode 100644index 00000000000..da8417af986--- /dev/null+++ b/src/store/work/initialState.ts@@ -0,0 +1,32 @@+import type { WorkListItem, WorkSummaryItem, WorkVersionItem } from '@lobechat/types';++import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';++/** One gallery filter's loaded pages. */+export type WorkspaceWorksData = ReplicaPagedData<WorkSummaryItem, string>;++export interface WorkState {+ /** Latest Works by origin agent (`agentWorksResource` key). */+ agentWorksMap: Record<string, WorkSummaryItem[]>;+ agentWorksReplica: ReplicaState<WorkSummaryItem[]>;+ /** Sidebar Work history by conversation (`conversationWorksKey`). */+ conversationWorksMap: Record<string, WorkListItem[]>;+ conversationWorksReplica: ReplicaState<WorkListItem[]>;+ /** Workspace gallery pages by filter (`workspaceWorksKey`). */+ workspaceWorksMap: Record<string, WorkspaceWorksData>;+ workspaceWorksReplica: ReplicaState<WorkspaceWorksData>;+ /** Version timelines by Work id. */+ workVersionsMap: Record<string, WorkVersionItem[]>;+ workVersionsReplica: ReplicaState<WorkVersionItem[]>;+}++export const initialWorkState: WorkState = {+ agentWorksMap: {},+ agentWorksReplica: createReplicaState(),+ conversationWorksMap: {},+ conversationWorksReplica: createReplicaState(),+ workVersionsMap: {},+ workVersionsReplica: createReplicaState(),+ workspaceWorksMap: {},+ workspaceWorksReplica: createReplicaState(),+};diff --git a/src/store/work/privateAction.ts b/src/store/work/privateAction.tsnew file mode 100644index 00000000000..ce3308d5b40--- /dev/null+++ b/src/store/work/privateAction.ts@@ -0,0 +1,112 @@+import type { WorkListItem, WorkSummaryItem, WorkVersionItem } from '@lobechat/types';++import {+ arrayEntity,+ cacheScope,+ createReplicaSlice,+ linkReplicaEntity,+ recordLens,+ type ReplicaPageResult,+} from '@/libs/replica';+import { workService } from '@/services/work';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import type { WorkspaceWorksData, WorkState } from './initialState';+import {+ AGENT_WORKS_LIMIT,+ agentWorksResource,+ conversationWorksResource,+ toPersistedVersions,+ WORKSPACE_WORKS_PAGE_SIZE,+ type WorkspaceWorksParams,+ workspaceWorksResource,+ workVersionsResource,+} from './projection';++const n = setNamespace('work');++type Setter = StoreSetter<WorkState>;++const workId = (item: { id: string }) => item.id;++export class WorkPrivateAction {+ readonly agentWorks;+ readonly conversationWorks;+ readonly versions;+ readonly workspaceWorks;+ /** One Work card everywhere it is listed: gallery, project dashboard, sidebar history. */+ readonly works;++ constructor(set: Setter, get: () => WorkState) {+ this.workspaceWorks = createReplicaSlice(workspaceWorksResource, {+ actionPrefix: n('workspaceWorks'),+ fetcher: this.#fetchWorkspacePage,+ get,+ set,+ stateKey: 'workspaceWorksReplica',+ view: recordLens<WorkState, WorkspaceWorksData>('workspaceWorksMap'),+ });+ this.agentWorks = createReplicaSlice(agentWorksResource, {+ actionPrefix: n('agentWorks'),+ entity: arrayEntity<WorkSummaryItem>(workId),+ fetcher: async ({ originAgentId }) => {+ const { items } = await workService.listByWorkspace({+ limit: AGENT_WORKS_LIMIT,+ originAgentId,+ });+ return items;+ },+ get,+ set,+ stateKey: 'agentWorksReplica',+ view: recordLens<WorkState, WorkSummaryItem[]>('agentWorksMap'),+ });+ this.conversationWorks = createReplicaSlice(conversationWorksResource, {+ actionPrefix: n('conversationWorks'),+ entity: arrayEntity<WorkListItem>(workId),+ fetcher: ({ threadId, topicId }) => workService.listByConversation({ threadId, topicId }),+ get,+ set,+ stateKey: 'conversationWorksReplica',+ view: recordLens<WorkState, WorkListItem[]>('conversationWorksMap'),+ });+ this.versions = createReplicaSlice(workVersionsResource, {+ actionPrefix: n('versions'),+ fetcher: ({ workId }) => workService.listVersions(workId),+ get,+ set,+ stateKey: 'workVersionsReplica',+ toPersisted: toPersistedVersions,+ view: recordLens<WorkState, WorkVersionItem[]>('workVersionsMap'),+ });+ this.works = linkReplicaEntity<WorkSummaryItem | WorkListItem>([+ this.workspaceWorks,+ this.agentWorks,+ this.conversationWorks,+ ]);+ }++ /** One gallery page: `cursor` undefined = the head (newest first). */+ #fetchWorkspacePage = async (+ { provider, type, visibility }: WorkspaceWorksParams,+ cursor?: string,+ ): Promise<ReplicaPageResult<WorkSummaryItem, string>> => {+ const { items, nextCursor } = await workService.listByWorkspace({+ cursor,+ limit: WORKSPACE_WORKS_PAGE_SIZE,+ provider,+ type: type ?? null,+ visibility,+ });+ return { items, nextCursor };+ };++ /** Seed a gallery filter from storage before its route paints. */+ preHydrateWorkspaceWorks = (params: WorkspaceWorksParams): Promise<boolean> => {+ const scope = cacheScope.get();+ // The slot may still hold the previous identity's rows; drop them before seeding.+ this.workspaceWorks.ensureScope(scope);+ return this.workspaceWorks.hydrate(params, scope);+ };+}diff --git a/src/store/work/projection.ts b/src/store/work/projection.tsnew file mode 100644index 00000000000..406c054e55c--- /dev/null+++ b/src/store/work/projection.ts@@ -0,0 +1,128 @@+import type {+ ListedWorkType,+ WorkListItem,+ WorkSkillProvider,+ WorkSummaryItem,+ WorkVersionItem,+ WorkVisibility,+} from '@lobechat/types';++import { definePagedReplica, defineReplica } from '@/libs/replica';+import { workKeys } from '@/libs/swr/keys';++import type { WorkspaceWorksData } from './initialState';++/** Head page size of the workspace Work gallery. */+export const WORKSPACE_WORKS_PAGE_SIZE = 30;++/** Cards the project dashboard shows for its coordinator agent. */+export const AGENT_WORKS_LIMIT = 4;++export interface WorkspaceWorksParams {+ provider?: WorkSkillProvider;+ type?: ListedWorkType;+ visibility?: WorkVisibility;+ /** Only shapes the SWR sync key; the replica scope already partitions by workspace. */+ workspaceId: string | null;+}++/** Entry key of one gallery filter (`workspaceWorksMap[key]`). */+export const workspaceWorksKey = ({ provider, type, visibility }: WorkspaceWorksParams): string =>+ `${type ?? '*'}|${provider ?? '*'}|${visibility ?? '*'}`;++/**+ * The cross-topic Work gallery (resource home recent works, /resource/works),+ * one local-first entry per filter. The server pages by an opaque cursor,+ * newest first; a reload repaints the head page while the network confirms.+ *+ * The sync adopts the `work:workspace` key so Work mutations that refresh the+ * `work:` domain (`workService.refreshAll` / `refreshWorkspaceLists`) reach it.+ */+export const workspaceWorksResource = definePagedReplica<+ WorkspaceWorksParams,+ WorkSummaryItem,+ string,+ WorkspaceWorksData+>({+ key: workspaceWorksKey,+ name: 'workspaceWorks',+ paging: {+ direction: 'forward',+ getId: (item) => item.id,+ mode: 'cursor',+ persist: { pages: 1 },+ },+ // Types × providers × visibility are a handful of filters; the cap only+ // guards against filter keys a later release adds.+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ syncKey: (params) =>+ workKeys.workspace(params.workspaceId, workspaceWorksKey(params), undefined, params.visibility),+ version: 1,+});++export interface AgentWorksParams {+ originAgentId: string;+ workspaceId: string | null;+}++/**+ * The latest Works one agent produced — the project dashboard's "latest works"+ * for its coordinator agent. A short fixed-size list per agent.+ */+export const agentWorksResource = defineReplica<AgentWorksParams, WorkSummaryItem[]>({+ key: ({ originAgentId }) => originAgentId,+ name: 'agentWorks',+ persist: { maxEntries: 50 },+ storage: 'indexedDB',+ syncKey: ({ originAgentId, workspaceId }) =>+ workKeys.workspace(workspaceId, `agent:${originAgentId}:${AGENT_WORKS_LIMIT}`),+ version: 1,+});++export interface ConversationWorksParams {+ threadId?: string | null;+ topicId: string;+}++/** Entry key of one conversation's Work history (`conversationWorksMap[key]`). */+export const conversationWorksKey = ({ threadId, topicId }: ConversationWorksParams): string =>+ `${topicId}|${threadId ?? ''}`;++/**+ * The working sidebar's Work history of one conversation (topic + thread).+ * Persisted for the most recent conversations only.+ *+ * The sync adopts `work:conversation`, which the runtime transports revalidate+ * once per operation end (`workService.refreshConversationViews`).+ */+export const conversationWorksResource = defineReplica<ConversationWorksParams, WorkListItem[]>({+ key: conversationWorksKey,+ name: 'conversationWorks',+ persist: { maxEntries: 100 },+ storage: 'indexedDB',+ syncKey: ({ threadId, topicId }) => workKeys.conversation(topicId, threadId ?? null),+ version: 1,+});++export interface WorkVersionsParams {+ workId: string;+}++/**+ * The version timeline of one Work (expanded history card). The sync adopts+ * `work:versions`, revalidated with the conversation views. Persisted slim+ * (no captured `content`) for the most recently expanded Works.+ */+export const workVersionsResource = defineReplica<WorkVersionsParams, WorkVersionItem[]>({+ key: ({ workId }) => workId,+ name: 'workVersions',+ persist: { maxEntries: 200 },+ storage: 'indexedDB',+ syncKey: ({ workId }) => workKeys.versions(workId),+ version: 1,+});++/** The timeline never renders a version's captured text, so it is not persisted. */+export const toPersistedVersions = (versions: WorkVersionItem[]): WorkVersionItem[] =>+ versions.map((version) => (version.content === null ? version : { ...version, content: null }));diff --git a/src/store/work/replica.test.ts b/src/store/work/replica.test.tsnew file mode 100644index 00000000000..9107b4d66d7--- /dev/null+++ b/src/store/work/replica.test.ts@@ -0,0 +1,350 @@+/**+ * @vitest-environment happy-dom+ *+ * Work lists are replicas: the gallery, the project dashboard's latest works,+ * the sidebar history and the version timelines paint from their persisted+ * copy on the first frame, the network only confirms, and the `work:` sync+ * keys keep the existing Work refresh paths reaching them.+ */+import { randomUUID } from 'node:crypto';++import type { WorkListItem, WorkSummaryItem, WorkVersionItem } from '@lobechat/types';+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 { workService } from '@/services/work';++import { workActions } from './action';+import { initialWorkState, type WorkspaceWorksData } from './initialState';+import {+ agentWorksResource,+ conversationWorksKey,+ conversationWorksResource,+ workspaceWorksKey,+ type WorkspaceWorksParams,+ workspaceWorksResource,+ workVersionsResource,+} from './projection';+import { workSelectors } from './selectors';+import { useWorkStore } from './store';++vi.mock('@/services/work', async (importOriginal) => {+ const actual = await importOriginal<{ workService: typeof workService }>();+ const service = actual.workService;+ service.listByConversation = vi.fn();+ service.listByWorkspace = vi.fn();+ service.listVersions = vi.fn();+ return { ...actual, workService: service };+});++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,+ );++const summary = (id: string, title = id): WorkSummaryItem =>+ ({ id, resourceType: 'document', title, type: 'document' }) as unknown as WorkSummaryItem;++const listItem = (id: string, title = id): WorkListItem =>+ ({ id, resourceType: 'document', title, type: 'document' }) as unknown as WorkListItem;++const version = (id: string, content: string | null = null): WorkVersionItem =>+ ({ changeType: 'created', content, id, version: 1, workId: 'wk_1' }) as WorkVersionItem;++/** A persisted head page as the paged engine writes it. */+const paged = (items: WorkSummaryItem[], nextCursor: string | null = null): WorkspaceWorksData => ({+ currentPage: 0,+ hasMore: nextCursor !== null,+ items,+ nextCursor,+ pageSize: items.length,+ pages: [{ count: items.length, next: nextCursor }],+});++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const ALL: WorkspaceWorksParams = { workspaceId: null };++const galleryIds = (params = ALL) =>+ useWorkStore.getState().workspaceWorksMap[workspaceWorksKey(params)]?.items.map((i) => i.id);++describe('work replicas', () => {+ const scopes = new Set<string>();+ let scope = '';+ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`work-user-${randomUUID()}:personal`);+ act(() => useWorkStore.setState({ ...initialWorkState }));+ vi.clearAllMocks();+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) => [+ workspaceWorksResource.storage!.remove({+ queryKey: workspaceWorksKey(ALL),+ scope: value,+ }),+ agentWorksResource.storage!.remove({ queryKey: 'agt_1', scope: value }),+ conversationWorksResource.storage!.remove({+ queryKey: conversationWorksKey({ topicId: 'tpc_1' }),+ scope: value,+ }),+ workVersionsResource.storage!.remove({ queryKey: 'wk_1', scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ });++ it('paints the persisted gallery head page before the network answers', async () => {+ await workspaceWorksResource.storage!.set(+ { queryKey: workspaceWorksResource.storageKey(ALL), scope },+ { data: paged([summary('wk_1', 'Cached')]), updatedAt: 1 },+ );+ vi.mocked(workService.listByWorkspace).mockImplementation(pending);++ const sync = renderHook(() => workActions.useFetchWorkspaceWorks(ALL), { wrapper });+ const list = renderHook(() => useWorkStore(workSelectors.workspaceWorks(ALL)));++ await waitFor(() => expect(list.result.current?.items.map((i) => i.title)).toEqual(['Cached']));+ expect(sync.result.current.isValidating).toBe(true);+ });++ it('pre-hydrates the gallery from storage without a mounted view', async () => {+ await workspaceWorksResource.storage!.set(+ { queryKey: workspaceWorksResource.storageKey(ALL), scope },+ { data: paged([summary('wk_1', 'Cached')]), updatedAt: 1 },+ );++ await workActions.preHydrateWorkspaceWorks(ALL);++ expect(galleryIds()).toEqual(['wk_1']);+ expect(workService.listByWorkspace).not.toHaveBeenCalled();+ });++ it('replaces the gallery with the server head page, persists it and pages by cursor', async () => {+ vi.mocked(workService.listByWorkspace)+ .mockResolvedValueOnce({ items: [summary('wk_1'), summary('wk_2')], nextCursor: 'c1' })+ .mockResolvedValueOnce({ items: [summary('wk_3')], nextCursor: null });++ renderHook(() => workActions.useFetchWorkspaceWorks(ALL), { wrapper });+ await waitFor(() => expect(galleryIds()).toEqual(['wk_1', 'wk_2']));+ expect(workService.listByWorkspace).toHaveBeenCalledWith({+ cursor: undefined,+ limit: 30,+ provider: undefined,+ type: null,+ visibility: undefined,+ });+ await waitFor(async () =>+ expect(+ (+ await workspaceWorksResource.storage!.get({+ queryKey: workspaceWorksResource.storageKey(ALL),+ scope,+ })+ )?.data.items.map((i) => i.id),+ ).toEqual(['wk_1', 'wk_2']),+ );++ await act(() => workActions.loadMoreWorkspaceWorks(ALL));++ expect(workService.listByWorkspace).toHaveBeenLastCalledWith(+ expect.objectContaining({ cursor: 'c1' }),+ );+ expect(galleryIds()).toEqual(['wk_1', 'wk_2', 'wk_3']);+ expect(useWorkStore.getState().workspaceWorksMap[workspaceWorksKey(ALL)]?.hasMore).toBe(false);+ });++ it('keys each gallery filter and visibility as its own entry', async () => {+ vi.mocked(workService.listByWorkspace).mockImplementation(async ({ type, visibility }) => ({+ items: [summary(`${type ?? 'all'}_${visibility ?? 'any'}`)],+ nextCursor: null,+ }));+ const tasks: WorkspaceWorksParams = { type: 'task', visibility: 'private', workspaceId: 'ws' };++ renderHook(+ () => {+ workActions.useFetchWorkspaceWorks(ALL);+ workActions.useFetchWorkspaceWorks(tasks);+ },+ { wrapper },+ );++ await waitFor(() => expect(galleryIds()).toEqual(['all_any']));+ await waitFor(() => expect(galleryIds(tasks)).toEqual(['task_private']));+ });++ it('refreshWorkspaceLists revalidates a mounted gallery through its work:workspace key', async () => {+ vi.mocked(workService.listByWorkspace)+ .mockResolvedValueOnce({ items: [summary('wk_1')], nextCursor: null })+ .mockResolvedValueOnce({ items: [summary('wk_2')], nextCursor: null });+ renderHook(() => workActions.useFetchWorkspaceWorks(ALL), { wrapper });+ await waitFor(() => expect(galleryIds()).toEqual(['wk_1']));++ await act(() => workService.refreshWorkspaceLists());++ await waitFor(() => expect(galleryIds()).toEqual(['wk_2']));+ });++ it('a Work refresh drops loaded tail pages instead of keeping them stale', async () => {+ vi.mocked(workService.listByWorkspace)+ .mockResolvedValueOnce({ items: [summary('wk_1'), summary('wk_2')], nextCursor: 'c1' })+ .mockResolvedValueOnce({ items: [summary('wk_3', 'Before')], nextCursor: null })+ // The head is unchanged after the change, so it still holds the join anchor.+ .mockResolvedValueOnce({ items: [summary('wk_1'), summary('wk_2')], nextCursor: 'c1' })+ .mockResolvedValueOnce({ items: [summary('wk_3', 'Orphaned')], nextCursor: null });+ renderHook(() => workActions.useFetchWorkspaceWorks(ALL), { wrapper });+ await waitFor(() => expect(galleryIds()).toEqual(['wk_1', 'wk_2']));+ await act(() => workActions.loadMoreWorkspaceWorks(ALL));+ expect(galleryIds()).toEqual(['wk_1', 'wk_2', 'wk_3']);++ await act(() => workService.refreshWorkspaceLists());++ // The tail card is not left showing its pre-change value…+ await waitFor(() => expect(galleryIds()).toEqual(['wk_1', 'wk_2']));+ // …and comes back current when it is paged in again.+ await act(() => workActions.loadMoreWorkspaceWorks(ALL));+ const tail = useWorkStore.getState().workspaceWorksMap[workspaceWorksKey(ALL)]?.items[2];+ expect(tail?.title).toBe('Orphaned');+ });++ it('syncs the project dashboard works of one agent', async () => {+ vi.mocked(workService.listByWorkspace).mockResolvedValue({+ items: [summary('wk_a')],+ nextCursor: null,+ });++ renderHook(+ () => workActions.useFetchAgentWorks({ originAgentId: 'agt_1', workspaceId: null }),+ {+ wrapper,+ },+ );++ await waitFor(() =>+ expect(+ workSelectors+ .agentWorks('agt_1')(useWorkStore.getState())+ ?.map((i) => i.id),+ ).toEqual(['wk_a']),+ );+ expect(workService.listByWorkspace).toHaveBeenCalledWith({ limit: 4, originAgentId: 'agt_1' });+ });++ it('paints the persisted sidebar history and refreshes it through work:conversation', async () => {+ const params = { threadId: null, topicId: 'tpc_1' };+ await conversationWorksResource.storage!.set(+ { queryKey: conversationWorksResource.storageKey(params), scope },+ { data: [listItem('wk_1', 'Cached')], updatedAt: 1 },+ );+ let resolveFirst!: (items: WorkListItem[]) => void;+ vi.mocked(workService.listByConversation)+ .mockImplementationOnce(() => new Promise((resolve) => (resolveFirst = resolve)))+ .mockResolvedValueOnce([listItem('wk_2', 'Refreshed')]);++ renderHook(() => workActions.useFetchConversationWorks(params), { wrapper });+ const history = renderHook(() => useWorkStore(workSelectors.conversationWorks(params)));++ await waitFor(() => expect(history.result.current?.map((i) => i.title)).toEqual(['Cached']));++ resolveFirst([listItem('wk_1', 'Server')]);+ await waitFor(() => expect(history.result.current?.map((i) => i.title)).toEqual(['Server']));++ await act(() => workService.refreshConversationViews('tpc_1', null));+ await waitFor(() => expect(history.result.current?.map((i) => i.title)).toEqual(['Refreshed']));+ });++ it('persists version timelines without their captured content', async () => {+ vi.mocked(workService.listVersions).mockResolvedValue([version('v1', 'a very long body')]);++ renderHook(() => workActions.useFetchWorkVersions({ workId: 'wk_1' }), { wrapper });++ await waitFor(() =>+ expect(useWorkStore.getState().workVersionsMap.wk_1?.[0]?.content).toBe('a very long body'),+ );+ await waitFor(async () => {+ const row = await workVersionsResource.storage!.get({ queryKey: 'wk_1', scope });+ expect(row?.data.map((v) => [v.id, v.content])).toEqual([['v1', null]]);+ });+ });++ it('removeWork drops the card from every list and its persisted rows', async () => {+ vi.mocked(workService.listByWorkspace).mockResolvedValue({+ items: [summary('wk_1'), summary('wk_2')],+ nextCursor: null,+ });+ vi.mocked(workService.listByConversation).mockResolvedValue([+ listItem('wk_1'),+ listItem('wk_3'),+ ]);+ const history = { topicId: 'tpc_1' };++ const { unmount } = renderHook(+ () => {+ workActions.useFetchWorkspaceWorks(ALL);+ workActions.useFetchConversationWorks(history);+ },+ { wrapper },+ );+ await waitFor(() => expect(galleryIds()).toEqual(['wk_1', 'wk_2']));+ await waitFor(() =>+ expect(workSelectors.conversationWorks(history)(useWorkStore.getState())).toHaveLength(2),+ );+ unmount();++ act(() => workActions.removeWork('wk_1'));++ expect(galleryIds()).toEqual(['wk_2']);+ expect(+ workSelectors+ .conversationWorks(history)(useWorkStore.getState())+ ?.map((i) => i.id),+ ).toEqual(['wk_3']);+ await waitFor(async () => {+ const row = await workspaceWorksResource.storage!.get({+ queryKey: workspaceWorksResource.storageKey(ALL),+ scope,+ });+ expect(row?.data.items.map((i) => i.id)).toEqual(['wk_2']);+ });+ });++ it('never hydrates another identity’s persisted gallery', async () => {+ const other = `work-user-${randomUUID()}:personal`;+ scopes.add(other);+ await workspaceWorksResource.storage!.set(+ { queryKey: workspaceWorksResource.storageKey(ALL), scope: other },+ { data: paged([summary('wk_other')]), updatedAt: 1 },+ );+ vi.mocked(workService.listByWorkspace).mockImplementation(pending);++ const sync = renderHook(() => workActions.useFetchWorkspaceWorks(ALL), { wrapper });++ await waitFor(() => expect(sync.result.current.isHydrated).toBe(true));+ expect(galleryIds()).toBeUndefined();+ });+});diff --git a/src/store/work/selectors.ts b/src/store/work/selectors.tsnew file mode 100644index 00000000000..885c1172129--- /dev/null+++ b/src/store/work/selectors.ts@@ -0,0 +1,26 @@+import type { WorkState } from './initialState';+import {+ conversationWorksKey,+ type ConversationWorksParams,+ workspaceWorksKey,+ type WorkspaceWorksParams,+} from './projection';++/** Every getter returns `undefined` until the entry first paints (storage or network). */+const workspaceWorks = (params: WorkspaceWorksParams) => (s: WorkState) =>+ s.workspaceWorksMap[workspaceWorksKey(params)];++const agentWorks = (originAgentId: string | null | undefined) => (s: WorkState) =>+ originAgentId ? s.agentWorksMap[originAgentId] : undefined;++const conversationWorks = (params: ConversationWorksParams | null) => (s: WorkState) =>+ params ? s.conversationWorksMap[conversationWorksKey(params)] : undefined;++const workVersions = (workId: string) => (s: WorkState) => s.workVersionsMap[workId];++export const workSelectors = {+ agentWorks,+ conversationWorks,+ workspaceWorks,+ workVersions,+};diff --git a/src/store/work/store.ts b/src/store/work/store.tsnew file mode 100644index 00000000000..24a26adb48e--- /dev/null+++ b/src/store/work/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { initialWorkState, type WorkState } from './initialState';++const devtools = createDevtools('work');++export const useWorkStore = createWithEqualityFn<WorkState>()(+ devtools(() => initialWorkState),+ shallow,+);++expose('work', useWorkStore);