π€― 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(page): move the page list and CRUD onto @lobechat/replica (#20594)
Arvin Xubb5a79b53eb8
diff --git a/.agents/skills/data-fetching-architecture/SKILL.md b/.agents/skills/data-fetching-architecture/SKILL.mdindex 3fd57977eb8..7ab4b90a5fd 100644--- a/.agents/skills/data-fetching-architecture/SKILL.md+++ b/.agents/skills/data-fetching-architecture/SKILL.md@@ -18,12 +18,15 @@ Component β Store useFetchXxx hook β Service β lambdaClient- Store read hooks use `useClientDataSWR` and return its SWR response, including `error`and `mutate`. Sync successful results into the store through the wrapper's supportedcallback (`onSuccess`, or `onData` for the sync wrapper).+- Server lists and details that paint from a local copy go through `@/libs/replica`+ instead: the store's `useFetchXxx` returns `slice.useSync(params)` (flags only) and+ the engine writes the store. See the Replica section of [zustand](../zustand/SKILL.md).- Components call these hooks and read store data through selectors. Do not fetch in`useEffect` or duplicate server data in component `useState`.- Use `useFetchXxx` for read hooks and `refreshXxx` for cache invalidation.- For list/detail types, maps, reducers, and shared type sources, use- [Zustand data structures](../zustand/references/data-structures.md). For action classes,- internal actions, and `flattenActions`, use [zustand](../zustand/SKILL.md).+ [Zustand data structures](../zustand/references/data-structures.md). For store layout+ and action classes, use [zustand](../zustand/SKILL.md).## Home First Paint and Persistent Caches@@ -75,11 +78,12 @@ For lists cached separately under multiple parents, see- Keep pending flags in store state and clear them in `finally`. Use per-id state forrow updates/deletes so unrelated rows remain usable; create can use a separate flagbecause no persistent id exists yet.-- For optimistic create/update, use the store's reducer/dispatch convention and- restore or revalidate affected state if the service fails. Do not leave a temporary- row or a successful-looking edit after rejection.-- Delete after server success, following the `zustand` convention. Do not remove the- row optimistically or apply create/update's optimistic recipe to deletion.+- For optimistic writes on replica data, use `slice.optimistic` / `entity.optimistic`;+ a rejected call rolls back on its own, deletes included.+- For optimistic create/update on legacy stores, use the store's reducer/dispatch+ convention and restore or revalidate affected state if the service fails. Do not+ leave a temporary row or a successful-looking edit after rejection. Delete only after+ server success there: a hand-written reducer has no rollback base.- Let failures reach the caller's error UI; a `finally` block clears pending statebut does not by itself recover an optimistic write.@@ -93,6 +97,10 @@ Use `AsyncBoundary` for standard loading/error/empty/data surfaces; use `AsyncErfor custom layouts and inline failures. Pass the original SWR `data` to the boundary:`undefined` means no successful result, whereas `[]` is a settled empty result.+Replica `useSync` returns no `data`. Feed `AsyncBoundary` its `error` and a settled+signal from the store entry (`data={isListInit || undefined}`, where the selector is+`entry !== undefined`); see `src/features/Pages/PageLayout/Body/index.tsx`.+```tsxconst BenchmarkList = () => {const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.mdindex c7905ac0e84..0e49c5e8df9 100644--- a/.agents/skills/zustand/SKILL.md+++ b/.agents/skills/zustand/SKILL.md@@ -1,6 +1,6 @@---name: zustand-description: 'Use for Zustand stores: list/detail splits, state type sources, slices, actions, reducers, selectors, optimistic updates and class-action composition.'+description: 'Use for Zustand stores: state shapes and type sources, state-only stores with xActions classes, replica-backed list/detail data (@lobechat/replica), selectors, optimistic writes, and legacy slice/internal_* action composition.'user-invocable: false---@@ -10,200 +10,40 @@ user-invocable: false- Import shared store types from `@lobechat/types`, not `@lobechat/database`.- Keep lightweight list-item types separate from full detail types; list types must not extend heavy detail types.-- Use arrays for whole-list display and id-keyed maps for cached details, with per-item loading state where needed.-- Before choosing list/detail shapes, normalized maps or state type sources, read [Data structures](references/data-structures.md). Its worked examples load only when relevant.+- Key cached details by id (`xxxDetailMap: Record<string, Detail>`); never hold a single `currentDetail` object.+- Read through `xxxSelectors` aggregates (`selectors.ts`), not ad-hoc lambdas repeated across components.+- Before choosing list/detail shapes or type sources, read [Data structures](references/data-structures.md).-## Action Type Hierarchy+## State-Only Stores (default for new and migrated stores)-### 1. Public Actions+Actions stay out of the Zustand state. Reference: `src/store/page`.-Main interfaces for UI components:+| File | Owns |+| ------------------ | ------------------------------------------------------------------------------------------------------------------------ |+| `store.ts` | `useXStore = createWithEqualityFn<XState>()(devtools(() => initialState), shallow)`: state only, no methods |+| `privateAction.ts` | `XPrivateAction`: replica slices, entity links, and write helpers shared by public actions. Not exported from `index.ts` |+| `action.ts` | `XActionImpl` (the public API) and the singleton `xActions = new XActionImpl(setState, getState, new XPrivateAction(β¦))` |-- Naming: Verb form (`createTopic`, `sendMessage`)-- Responsibilities: Parameter validation, flow orchestration+- Components read state with `useXStore(selector)` and call `xActions.foo()` directly. Never select an action out of the store.+- Sync hooks live on the public class and are called as `xActions.useFetchX(params)`.+- Public actions call each other through `this.foo()`. Private helpers are reached through `this.#private`. Do not add `internal_*` methods to the store to share logic between classes.+- Label every write: `this.#set(partial, false, n('actionName'))` with `const n = setNamespace('x')`.+- Put `reset()` on the public class and register `xActions` in `resetableActions` in `src/store/utils/userDataStores.ts`.+- Tests drive `xActions` and assert on `useXStore.getState()`. To mock in component tests: `vi.mock('@/store/x', () => ({ xActions: { foo: vi.fn() }, useXStore: β¦ }))`.-### 2. Internal Actions (`internal_*`)+## Replica-Backed Server Data-Core business logic implementation:+Server lists and details the UI paints go through `@/libs/replica`, not a hand-written SWR `onSuccess` + reducer. The engine owns hydration from IndexedDB, head revalidation, paging, optimistic overlays with rollback, and scope (user + workspace) isolation. API reference: [`packages/replica/README.md`](../../../packages/replica/README.md).-- Naming: `internal_` prefix (`internal_createTopic`)-- Responsibilities: Optimistic updates, service calls, error handling-- Should not be called directly by UI+1. Define the resource (`defineReplica` / `definePagedReplica`) in the store's `projection.ts`, converting server rows at the boundary.+2. Add two state fields per replica: the view (`xxxMap: Record<key, TData>`) and its bookkeeping (`xxxReplica: createReplicaState()`).+3. Bind it in the private class: `createReplicaSlice(resource, { get, set, stateKey: 'xxxReplica', view: recordLens('xxxMap'), β¦ })`. When the same entity lives in several replicas (list row + detail), link them with `linkReplicaEntity([list, detail])`.+4. Read: `slice.useSync(params)` returns only fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`). Data comes from selectors over `xxxMap`. "Entry is `undefined`" is the loading signal β do not add `xxxInit` flags or `loadingXxxIds`.+5. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `PRE_PAINT_HYDRATE_TIMEOUT`.+6. Write: `slice.optimistic(key, apply, serverCall)` or `entity.optimistic(id, fn | 'remove', serverCall)`. A failed call rolls back to the confirmed value, so deletes are optimistic too. Rows that exist only on the client (temp ids) are declared with `isClientOnly` and seeded with `update(key, fn, { persist: false })`.-### 3. Dispatch Methods (`internal_dispatch*`)+Outside test seeding, write a replica's view only through its slice. A plain `set` bypasses the engine's bookkeeping (persistence, rollback base, entity links).-State update handlers:+## Legacy Stores-- Naming: `internal_dispatch` + entity (`internal_dispatchTopic`)-- Responsibilities: Calling reducers, updating store--## When to Use Reducer vs Simple `set`--**Use Reducer Pattern:**--- Managing object lists/maps (`messagesMap`, `topicMaps`)-- Optimistic updates-- Complex state transitions--**Use Simple `set`:**--- Toggling booleans-- Updating simple values-- Setting single state fields--## Optimistic Update Pattern--```typescript-internal_createTopic: async (params) => {- const tmpId = Date.now().toString();-- // 1. Immediately update frontend (optimistic)- get().internal_dispatchTopic(- { type: 'addTopic', value: { ...params, id: tmpId } },- 'internal_createTopic'- );-- // 2. Call backend service- const topicId = await topicService.createTopic(params);-- // 3. Refresh for consistency- await get().refreshTopic();- return topicId;-},-```--**Delete operations**: Don't use optimistic updates (destructive, complex recovery)--## Naming Conventions--**Actions:**--- Public: `createTopic`, `sendMessage`--- Internal: `internal_createTopic`, `internal_updateMessageContent`--- Dispatch: `internal_dispatchTopic`- **State:**--- ID arrays: `topicEditingIds`--- Maps: `topicMaps`, `messagesMap`--- Active: `activeTopicId`--- Init flags: `topicsInit`--## Detailed Guides--- Action patterns: `references/action-patterns.md`-- Slice organization: `references/slice-organization.md`--## Class-Based Action Implementation--We are migrating slices from plain `StateCreator` objects to **class-based actions**.--### Pattern--- Define a class that encapsulates actions and receives `(set, get, api)` in the constructor.-- Use `#private` fields (e.g., `#set`, `#get`) to avoid leaking internals.-- Prefer shared typing helpers:- - `StoreSetter<T>` from `@/store/types` for `set`.- - `Pick<ActionImpl, keyof ActionImpl>` to expose only public methods.-- Export a `create*Slice` helper that returns a class instance.--```ts-type Setter = StoreSetter<HomeStore>;-export const createRecentSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>- new RecentActionImpl(set, get, _api);--export class RecentActionImpl {- readonly #get: () => HomeStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => HomeStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- useFetchRecentTopics = () => {- // ...- };-}--export type RecentAction = Pick<RecentActionImpl, keyof RecentActionImpl>;-```--### Composition--- In store files, merge class instances with `flattenActions` (do not spread class instances).-- `flattenActions` binds methods to the original class instance and supports prototype methods and class fields.--```ts-const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (...params) => ({- ...initialState,- ...flattenActions<HomeStoreAction>([- createRecentSlice(...params),- createHomeInputSlice(...params),- ]),-});-```--### Multi-Class Slices--- For large slices that need multiple action classes, compose them in the slice entry using `flattenActions`.-- Use a local `PublicActions<T>` helper if you need to combine multiple classes and hide private fields.--```ts-type PublicActions<T> = { [K in keyof T]: T[K] };--export type ChatGroupAction = PublicActions<- ChatGroupInternalAction & ChatGroupLifecycleAction & ChatGroupMemberAction & ChatGroupCurdAction->;--export const chatGroupAction: StateCreator<- ChatGroupStore,- [['zustand/devtools', never]],- [],- ChatGroupAction-> = (...params) =>- flattenActions<ChatGroupAction>([- new ChatGroupInternalAction(...params),- new ChatGroupLifecycleAction(...params),- new ChatGroupMemberAction(...params),- new ChatGroupCurdAction(...params),- ]);-```--### Store-Access Types--- For class methods that depend on actions in other classes, define explicit store augmentations:- - `ChatGroupStoreWithSwitchTopic` for lifecycle `switchTopic`- - `ChatGroupStoreWithRefresh` for member refresh- - `ChatGroupStoreWithInternal` for curd `internal_dispatchChatGroup`--### Slices That Don't Currently Need `set`--When a slice doesn't write local state (e.g. it delegates to another store or just runs hooks), drop `#set` and mark the constructor param as `_set` with `void _set` to keep the `(set, get, api)` shape:--```ts-export class ToolActionImpl {- readonly #get: () => ConversationStore;-- constructor(_set: Setter, get: () => ConversationStore, _api?: unknown) {- void _set;- void _api;- this.#get = get;- }-- approveToolCall = async (id: string) => {- const { context, hooks } = this.#get();- await useChatStore.getState().approveToolCalling(id, '', context);- hooks.onToolCallComplete?.(id, undefined);- };-}-```--- Drop `#set` when unused; restore it when a later edit needs `set` β re-adding costs nothing.-- Don't add `setNamespace` for slices that don't write state.-- Don't keep both old slice objects and class actions active at the same time during migration.+Stores that still flatten action classes into state (`flattenActions`, `create*Slice`, `internal_*`, `internal_dispatch*` + reducers, SWR `onSuccess` syncing) follow [Legacy slices](references/legacy-slices.md). Use that layout only when editing one of those stores; migrate to the layouts above when moving its data onto a replica.diff --git a/.agents/skills/zustand/references/action-patterns.md b/.agents/skills/zustand/references/action-patterns.mddeleted file mode 100644index 1244752c2eb..00000000000--- a/.agents/skills/zustand/references/action-patterns.md+++ /dev/null@@ -1,122 +0,0 @@-# Zustand Action Patterns--## Optimistic Update Implementation--### Standard Flow--```typescript-internal_updateMessageContent: async (id, content, extra) => {- const { internal_dispatchMessage, refreshMessages } = get();-- // 1. Immediately update frontend- internal_dispatchMessage({- id,- type: 'updateMessage',- value: { content },- });-- // 2. Call backend- await messageService.updateMessage(id, { content });-- // 3. Refresh for consistency- await refreshMessages();-},-```--### Create Operations--```typescript-internal_createMessage: async (message, context) => {- let tempId = context?.tempMessageId;- if (!tempId) {- tempId = internal_createTmpMessage(message);- }-- try {- const id = await messageService.createMessage(message);- await refreshMessages();- return id;- } catch (e) {- internal_dispatchMessage({- id: tempId,- type: 'updateMessage',- value: { error: { type: ChatErrorType.CreateMessageError } },- });- }-},-```--### Delete Operations (No Optimistic Update)--```typescript-internal_removeGenerationTopic: async (id: string) => {- get().internal_updateGenerationTopicLoading(id, true);-- try {- await generationTopicService.deleteTopic(id);- await get().refreshGenerationTopics();- } finally {- get().internal_updateGenerationTopicLoading(id, false);- }-},-```--## Loading State Management--```typescript-// Define in initialState.ts-export interface ChatMessageState {- messageEditingIds: string[];-}--// Manage in action-toggleMessageEditing: (id, editing) => {- set(- { messageEditingIds: toggleBooleanList(get().messageEditingIds, id, editing) },- false,- 'toggleMessageEditing',- );-};-```--## SWR Integration--```typescript-useFetchMessages: (enable, sessionId, activeTopicId) =>- useClientDataSWR<ChatMessage[]>(- enable ? [SWR_USE_FETCH_MESSAGES, sessionId, activeTopicId] : null,- async ([, sessionId, topicId]) => messageService.getMessages(sessionId, topicId),- {- onSuccess: (messages) => {- const nextMap = { ...get().messagesMap, [messageMapKey(sessionId, activeTopicId)]: messages };- if (get().messagesInit && isEqual(nextMap, get().messagesMap)) return;- set({ messagesInit: true, messagesMap: nextMap }, false, n('useFetchMessages'));- },- }- ),--// Cache invalidation-refreshMessages: async () => {- await mutate([SWR_USE_FETCH_MESSAGES, get().activeId, get().activeTopicId]);-};-```--## Reducer Pattern--```typescript-export const messagesReducer = (state: ChatMessage[], payload: MessageDispatch): ChatMessage[] => {- switch (payload.type) {- case 'updateMessage': {- return produce(state, (draftState) => {- const index = draftState.findIndex((i) => i.id === payload.id);- if (index < 0) return;- draftState[index] = merge(draftState[index], {- ...payload.value,- updatedAt: Date.now(),- });- });- }- // ...other cases- }-};-```diff --git a/.agents/skills/zustand/references/data-structures.md b/.agents/skills/zustand/references/data-structures.mdindex 7ab99386ea2..9ef41f15e1a 100644--- a/.agents/skills/zustand/references/data-structures.md+++ b/.agents/skills/zustand/references/data-structures.md@@ -1,304 +1,60 @@# LobeHub Store Data Structures-How to structure data in Zustand stores for fast list rendering, multi-detail caching, and ergonomic optimistic updates.+How to shape list and detail data in Zustand stores. Request lifecycle, loading and error rendering belong to [data-fetching-architecture](../../data-fetching-architecture/SKILL.md).-These examples illustrate state shapes. For request lifecycle, loading, errors and retries,-follow [data-fetching-architecture](../../data-fetching-architecture/SKILL.md).+## Rules-## Core Principles+1. **Types come from `@lobechat/types`**, one entity per file. Never use `@lobechat/database` row types in store state; convert at the boundary.+2. **List item and detail are separate types.** The list item is a subset that drops heavy fields (`content`, `editorData`, `rubrics`, large arrays) and may add computed UI fields (`testCaseCount`). It never `extends` the detail type β that pulls the heavy fields back in. Worked examples: [types](data-structures/types.md).+3. **Details are cached by id** in `xxxDetailMap: Record<string, Detail>`, so switching between detail pages does not refetch and per-row updates stay local. Never hold a single `xxxDetail` object.+4. **Read through selectors** (`xxxSelectors.getXxxDetail(id)`) so components do not repeat map lookups.-### β DO+## Replica-Backed Shape-1. **Separate List and Detail** β different structures for list pages and detail pages-2. **Use Map for Details** β cache multiple detail pages with `Record<string, Detail>`-3. **Use Array for Lists** β simple arrays for list display-4. **Types from `@lobechat/types`** β never use `@lobechat/database` types in stores-5. **Distinguish List and Detail types** β List types may have computed UI fields+A replica's view is always a map keyed by the resource's `key(params)`:-### β DON'T--1. **Don't use a single detail object** β can't cache multiple pages-2. **Don't mix List and Detail types** β they have different purposes-3. **Don't use database types** β use types from `@lobechat/types`-4. **Don't use Map for lists** β simple arrays are sufficient-------## Type Definitions--Each entity gets its own file under `@lobechat/types/`. Each file exports two types:--- **Detail type** β full entity, including heavy fields (rubrics, content, editor state, β¦)-- **List item type** β a **subset** that excludes heavy fields, may add computed UI fields (counts, timestamps formatted for display)--**Important:** the List type is a **subset**, not an `extends` of Detail. Extending pulls the heavy fields right back in.--> See [`data-structures/types.md`](./data-structures/types.md) for full worked examples (Benchmark, Document) and the heavy-field exclusion checklist.-------## When to Use Map vs Array--### Use Map + Reducer β for Detail Data--β Detail page data caching β multiple detail pages cached simultaneously-β Optimistic updates β update UI before API responds-β Per-item loading states β track which items are being updated-β Multi-page navigation β user can switch between details without refetching--```typescript-benchmarkDetailMap: Record<string, AgentEvalBenchmark>;-```--Examples: benchmark detail pages, dataset detail pages, user profiles.--### Use Simple Array β for List Data--β List display β lists, tables, cards-β Refresh as a whole β entire list refreshes together-β No per-item updates β no need to mutate individual rows in place-β Simple data flow β fewer moving parts--```typescript-benchmarkList: AgentEvalBenchmarkListItem[];+```ts+export interface PageListSliceState {+ pageListMap: Record<string, ReplicaPagedData<LobeDocument, number>>; // one entry per list query+ pageListReplica: ReplicaState<ReplicaPagedData<LobeDocument, number>>;+ pageDetailMap: Record<string, LobeDocument>; // one entry per id+ pageDetailReplica: ReplicaState<LobeDocument>;+}```-Examples: benchmark list, dataset list, user list.+- A list is a map entry too (`pageListMap.all`, `topicDataMap[containerKey]`): paging bookkeeping (`hasMore`, `currentPage`, `isLoadingMore`, `total`) lives on the entry.+- No `xxxListInit` and no `loadingXxxDetailIds`: an `undefined` entry means "not settled yet", and `useSync` reports `isValidating` / `error`.+- When existing readers expect a plain row array, `splitPagedLens` (see the replica README) keeps the rows in their old field and the paging bookkeeping beside it.----+## Legacy Shape-## State Structure Pattern+Stores not on a replica keep a whole-list array plus a detail map, with explicit flags:-```typescript+```ts// src/store/eval/slices/benchmark/initialState.ts-import type { AgentEvalBenchmark, AgentEvalBenchmarkListItem } from '@lobechat/types';-export interface BenchmarkSliceState {- // List β simple array- benchmarkList: AgentEvalBenchmarkListItem[];- benchmarkListInit: boolean;-- // Detail β map for multi-entity caching- benchmarkDetailMap: Record<string, AgentEvalBenchmark>;- loadingBenchmarkDetailIds: string[]; // per-item loading-- // Mutation states (drive form-level UI)- isCreatingBenchmark: boolean;- isUpdatingBenchmark: boolean;- isDeletingBenchmark: boolean;-}--export const benchmarkInitialState: BenchmarkSliceState = {- benchmarkList: [],- benchmarkListInit: false,- benchmarkDetailMap: {},- loadingBenchmarkDetailIds: [],- isCreatingBenchmark: false,- isUpdatingBenchmark: false,- isDeletingBenchmark: false,-};-```-------## Reducer Pattern (for Detail Map)--When the Detail Map needs optimistic updates (i.e. the user edits a row and the UI should reflect it before the server confirms), wire a typed reducer instead of inlining `set` calls. This keeps mutations testable and the dispatch surface small.--> See [`data-structures/reducer.md`](./data-structures/reducer.md) for the full discriminated-union action types, the `produce`-based reducer, and the `internal_dispatch*` slice methods that connect them to Zustand.-------## Data Structure Comparison--### β WRONG β Single Detail Object--```typescript-interface BenchmarkSliceState {- benchmarkDetail: AgentEvalBenchmark | null;- isLoadingBenchmarkDetail: boolean;-}-```--Problems:--- Can only cache one detail page at a time-- Switching between details forces refetch-- No optimistic updates-- No per-item loading states--### β CORRECT β Separate List and Detail--```typescript-interface BenchmarkSliceState {- benchmarkList: AgentEvalBenchmarkListItem[];+ benchmarkList: AgentEvalBenchmarkListItem[]; // refreshed as a wholebenchmarkListInit: boolean;-benchmarkDetailMap: Record<string, AgentEvalBenchmark>;- loadingBenchmarkDetailIds: string[];-- isCreatingBenchmark: boolean;+ loadingBenchmarkDetailIds: string[]; // per-row pending+ isCreatingBenchmark: boolean; // form-level mutation flagsisUpdatingBenchmark: boolean;isDeletingBenchmark: boolean;}```-Benefits:--- Cache multiple detail pages-- Fast navigation between cached details-- Optimistic updates via reducer-- Per-item loading states-- Clear separation of concerns-------## Component Usage--### Accessing List Data--```tsx-const BenchmarkList = () => {- const benchmarks = useEvalStore((s) => s.benchmarkList);- const isInit = useEvalStore((s) => s.benchmarkListInit);-- if (!isInit) return <Loading />;- return (- <div>- {benchmarks.map((b) => (- <BenchmarkCard key={b.id} name={b.name} testCaseCount={b.testCaseCount} />- ))}- </div>- );-};-```+The detail map is written through a reducer when it takes optimistic updates β see [reducer](data-structures/reducer.md) and [Legacy slices](legacy-slices.md).-### Accessing Detail Data+## Selectors-```tsx-const BenchmarkDetail = () => {- const { benchmarkId } = useParams<{ benchmarkId: string }>();-- const benchmark = useEvalStore((s) =>- benchmarkId ? s.benchmarkDetailMap[benchmarkId] : undefined,- );- const isLoading = useEvalStore((s) =>- benchmarkId ? s.loadingBenchmarkDetailIds.includes(benchmarkId) : false,- );-- if (!benchmark) return <Loading />;- return (- <div>- <h1>{benchmark.name}</h1>- {isLoading && <Spinner />}- </div>- );-};-```--### Using Selectors (Recommended)--```typescript-// src/store/eval/slices/benchmark/selectors.ts+```tsexport const benchmarkSelectors = {getBenchmarkDetail: (id: string) => (s: EvalStore) => s.benchmarkDetailMap[id],isLoadingBenchmarkDetail: (id: string) => (s: EvalStore) =>s.loadingBenchmarkDetailIds.includes(id),};-// In component-const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId!));-const isLoading = useEvalStore(benchmarkSelectors.isLoadingBenchmarkDetail(benchmarkId!));-```-------## Decision Tree--```text-Need to store data?-β-ββ Is it a LIST for display?-β ββ β Use simple array: `xxxList: XxxListItem[]`-β - May include computed fields-β - Refreshed as a whole-β - No optimistic updates needed-β-ββ Is it DETAIL page data?- ββ β Use Map: `xxxDetailMap: Record<string, Xxx>`- - Cache multiple details- - Support optimistic updates- - Per-item loading states- - Requires reducer for mutations+const benchmark = useEvalStore(benchmarkSelectors.getBenchmarkDetail(benchmarkId));```------## Checklist--When designing store state structure:--- [ ] **Organize types by entity** in separate files (e.g. `benchmark.ts`, `agentEvalDataset.ts`)-- [ ] Create **Detail** type (full entity with all fields including heavy ones)-- [ ] Create **ListItem** type:- - [ ] Subset of Detail (exclude heavy fields)- - [ ] May include computed statistics for UI- - [ ] **NOT** `extends` Detail-- [ ] Use **array** for list data: `xxxList: XxxListItem[]`-- [ ] Use **Map** for detail data: `xxxDetailMap: Record<string, Xxx>`-- [ ] Per-item loading: `loadingXxxDetailIds: string[]`-- [ ] **Reducer** for detail map if optimistic updates needed (see [`data-structures/reducer.md`](./data-structures/reducer.md))-- [ ] **Internal dispatch** and **loading** methods-- [ ] **Selectors** for clean access (optional but recommended)-- [ ] Document in comments which fields are excluded from List and why-------## Best Practices--1. **File organization** β one entity per file, not mixed-2. **List is a subset** β ListItem excludes heavy fields, does not `extends` Detail-3. **Clear naming** β `xxxList` for arrays, `xxxDetailMap` for maps-4. **Consistent patterns** β all detail maps follow the same shape-5. **Type safety** β never use `any`, always use proper types-6. **Document exclusions** β comment which fields are excluded and why-7. **Selectors** β encapsulate access patterns-8. **Loading states** β per-item for details, global for mutations-9. **Immutability** β use Immer in reducers--### Common Mistakes to Avoid--β **DON'T extend Detail in List:**--```typescript-// Wrong β pulls heavy fields back in-export interface BenchmarkListItem extends Benchmark {- testCaseCount?: number;-}-```--β **DO create separate subset:**--```typescript-export interface BenchmarkListItem {- id: string;- name: string;- // ... only necessary fields- testCaseCount?: number; // Computed-}-```--β **DON'T mix entities in one file:**--```text-// Wrong β all entities in agentEvalEntities.ts-```--β **DO separate by entity:**--```text-// Correct β separate files-// benchmark.ts-// agentEvalDataset.ts-// agentEvalRun.ts-```+Stores are created with `shallow` equality, so a selector may return a fresh array of the same row objects (filter, sort). Returning freshly built objects per row (`.map((r) => ({ ...r }))`) defeats `shallow` and re-renders on every store change.diff --git a/.agents/skills/zustand/references/data-structures/reducer.md b/.agents/skills/zustand/references/data-structures/reducer.mdindex 868e3f52529..c86374bb2e6 100644--- a/.agents/skills/zustand/references/data-structures/reducer.md+++ b/.agents/skills/zustand/references/data-structures/reducer.md@@ -1,5 +1,7 @@# Reducer Pattern (for Detail Map)+Legacy stores only. Replica-backed data gets optimistic writes and rollback from the engine; do not add a reducer for it.+## Why Use a Reducer?- **Immutable updates** β Immer makes immutability easy@@ -66,51 +68,19 @@ export const benchmarkDetailReducer = (};```-## Internal Dispatch Methods+## Wiring It to the Store-The slice exposes two `internal_*` methods so the reducer and the loading state stay encapsulated behind a stable contract:+The action class exposes one dispatch method that runs the reducer and skips `set` when nothing changed (`src/store/eval/slices/benchmark/action.ts`):```typescript-// In action.ts-export interface BenchmarkAction {- // ... other methods ...-- // Internal β not for direct UI use- internal_dispatchBenchmarkDetail: (payload: BenchmarkDetailDispatch) => void;- internal_updateBenchmarkDetailLoading: (id: string, loading: boolean) => void;-}--export const createBenchmarkSlice: StateCreator<...> = (set, get) => ({- // ... other methods ...-- // Dispatch to reducer- internal_dispatchBenchmarkDetail: (payload) => {- const currentMap = get().benchmarkDetailMap;- const nextMap = benchmarkDetailReducer(currentMap, payload);-- // Skip set when nothing changed β avoids unnecessary re-renders- if (isEqual(nextMap, currentMap)) return;-- set(- { benchmarkDetailMap: nextMap },- false,- `dispatchBenchmarkDetail/${payload.type}`,- );- },-- // Update loading state for a specific id- internal_updateBenchmarkDetailLoading: (id, loading) => {- set(- (state) => ({- loadingBenchmarkDetailIds: loading- ? [...state.loadingBenchmarkDetailIds, id]- : state.loadingBenchmarkDetailIds.filter((i) => i !== id),- }),- false,- 'updateBenchmarkDetailLoading',- );- },-});+internal_dispatchBenchmarkDetail = (payload: BenchmarkDetailDispatch): void => {+ const currentMap = this.#get().benchmarkDetailMap;+ const nextMap = benchmarkDetailReducer(currentMap, payload);++ if (isEqual(nextMap, currentMap)) return;++ this.#set({ benchmarkDetailMap: nextMap }, false, `dispatchBenchmarkDetail/${payload.type}`);+};```-The `internal_` prefix is a convention β UI components should call the public mutation methods (e.g. `updateBenchmark`), which in turn call `internal_dispatch*`. This keeps reducer dispatch shapes out of the component layer.+Components call public mutations (`updateBenchmark`), which call `internal_dispatch*`; the dispatch payload shapes stay out of the component layer.diff --git a/.agents/skills/zustand/references/data-structures/types.md b/.agents/skills/zustand/references/data-structures/types.mdindex 8e9cc7b81d9..5397da88ed3 100644--- a/.agents/skills/zustand/references/data-structures/types.md+++ b/.agents/skills/zustand/references/data-structures/types.md@@ -1,6 +1,6 @@# Type Definitions in Detail-The [data-shape guide](../data-structures.md#type-definitions) covers the rules; this file holds the full worked examples.+The [data-shape guide](../data-structures.md#rules) covers the rules; this file holds the full worked examples.## Organizationdiff --git a/.agents/skills/zustand/references/legacy-slices.md b/.agents/skills/zustand/references/legacy-slices.mdnew file mode 100644index 00000000000..06edb516700--- /dev/null+++ b/.agents/skills/zustand/references/legacy-slices.md@@ -0,0 +1,127 @@+# Legacy Slices (actions flattened into state)++Most stores still compose action classes into the Zustand state with `flattenActions`. Follow this layout only when editing one of them. New stores, and stores moving their data onto `@lobechat/replica`, use the state-only layout in [SKILL.md](../SKILL.md). Reference store: `src/store/eval` (benchmark slice).++## Layout++```plaintext+src/store/<domain>/+βββ initialState.ts # intersects every slice state, spreads every slice initial value+βββ store.ts # XStore = XState & XAction; createStore + flattenActions+βββ selectors.ts # re-exports slice selectors+βββ slices/<slice>/+ βββ action.ts # XActionImpl class + create*Slice helper+ βββ initialState.ts+ βββ reducer.ts # optional: detail-map reducer+ βββ selectors.ts # xxxSelectors aggregate+```++Large slices split actions into an `actions/` directory (see `src/store/chat/slices/agentRun/actions/`).++## Action Classes++```ts+type Setter = StoreSetter<EvalStore>;++export const createBenchmarkSlice = (set: Setter, get: () => EvalStore, _api?: unknown) =>+ new BenchmarkActionImpl(set, get, _api);++export class BenchmarkActionImpl {+ readonly #get: () => EvalStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => EvalStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ refreshBenchmarks = async (): Promise<void> => {+ await mutate(evalKeys.benchmarks());+ };+}++export type BenchmarkAction = Pick<BenchmarkActionImpl, keyof BenchmarkActionImpl>;+```++- Keep the `(set, get, api)` constructor shape. Drop `#set` (and `setNamespace`) when the class never writes state; mark the param `_set` with `void _set`.+- Calls into another class go through `this.#get().otherAction()`. When the callee is not on the store type the class sees, widen `get` with a local augmentation type, e.g. `ChatGroupStoreWithInternal` in `src/store/agentGroup/slices/curd.ts`.++## Composition++```ts+const createStore: StateCreator<EvalStore, [['zustand/devtools', never]]> = (...parameters) => ({+ ...initialState,+ ...flattenActions<EvalStoreAction>([+ createBenchmarkSlice(...parameters),+ createDatasetSlice(...parameters),+ new EvalStoreResetAction(...parameters),+ ]),+});+```++- Merge class instances with `flattenActions`; spreading an instance drops prototype methods. On a key collision the first instance wins.+- A slice made of several classes composes them the same way in its own entry and types the result as `PublicActions<A & B & β¦>` (`src/store/agentGroup/action.ts`) so `#private` fields stay out of the store type.+- Do not keep an old `StateCreator` object slice and its class replacement active at the same time.++## Action Types++| Kind | Naming | Role |+| -------- | ------------------------------------- | ------------------------------------------------------------------- |+| Public | verb (`updateBenchmark`, `useFetchX`) | what components call; orchestration |+| Internal | `internal_` prefix | shared logic other classes call through `get()`; not called from UI |+| Dispatch | `internal_dispatch<Entity>` | runs a reducer on a map and `set`s the result only when it changed |++The `internal_*` names are a convention only: they are still public members of the store.++## Reads (SWR β store)++```ts+useFetchBenchmarkDetail = (id?: string): SWRResponse =>+ useClientDataSWR(+ id ? evalKeys.benchmarkDetail(id) : null,+ () => agentEvalService.getBenchmark(id!),+ {+ onSuccess: (data) => {+ this.#get().internal_dispatchBenchmarkDetail({+ id: id!,+ type: 'setBenchmarkDetail',+ value: data,+ });+ },+ },+ );+```++Return the SWR response so components can render `error`. Invalidate with `refreshX = () => mutate(key)`. Request lifecycle and error rendering belong to the `data-fetching-architecture` skill.++## Writes++- **Reducer vs `set`**: run maps and lists through a reducer (`reducer.ts`, Immer `produce`, discriminated-union payloads; see [reducer](data-structures/reducer.md)). Toggle booleans and set scalar fields with a plain labelled `set`.+- **Optimistic create/update**: dispatch the change, call the service, then refresh the affected keys. Track per-row pending ids (`loadingXxxDetailIds`) and clear them in `finally`. A failure must refresh or restore β never leave a successful-looking edit.+- **Delete**: call the service first and remove the row after it succeeds. Hand-written reducers have no rollback base, so an optimistic delete cannot be undone reliably. (Replica stores do delete optimistically; the engine rolls back.)++```ts+updateBenchmark = async (params: UpdateParams): Promise<void> => {+ this.#get().internal_dispatchBenchmarkDetail({+ id: params.id,+ type: 'updateBenchmarkDetail',+ value: params,+ });+ this.#get().internal_updateBenchmarkDetailLoading(params.id, true);+ try {+ await agentEvalService.updateBenchmark(params);+ await this.#get().refreshBenchmarks();+ await this.#get().refreshBenchmarkDetail(params.id);+ } finally {+ this.#get().internal_updateBenchmarkDetailLoading(params.id, false);+ }+};+```++## State Naming++- Detail maps: `xxxDetailMap`; query-keyed maps: `xxxMap` / `xxxMaps`+- Per-row pending: `loadingXxxIds`, `xxxEditingIds`+- Active selection: `activeXxxId`+- First successful load: `xxxInit`diff --git a/.agents/skills/zustand/references/slice-organization.md b/.agents/skills/zustand/references/slice-organization.mddeleted file mode 100644index d43bf765c4d..00000000000--- a/.agents/skills/zustand/references/slice-organization.md+++ /dev/null@@ -1,132 +0,0 @@-# Zustand Slice Organization--## Top-Level Store Structure--Key aggregation files:--- `src/store/chat/initialState.ts`: Aggregate all slice initial states-- `src/store/chat/store.ts`: Define top-level `ChatStore`, combine all slice actions-- `src/store/chat/selectors.ts`: Export all slice selectors-- `src/store/chat/helpers.ts`: Chat helper functions--## Store Aggregation Pattern--```typescript-// src/store/chat/initialState.ts-import { ChatTopicState, initialTopicState } from './slices/topic/initialState';-import { ChatMessageState, initialMessageState } from './slices/message/initialState';--export type ChatStoreState = ChatTopicState & ChatMessageState & ...--export const initialState: ChatStoreState = {- ...initialMessageState,- ...initialTopicState,- ...-};--// src/store/chat/store.ts-export interface ChatStoreAction- extends ChatMessageAction, ChatTopicAction, ...--const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (...params) => ({- ...initialState,- ...chatMessage(...params),- ...chatTopic(...params),-});--export const useChatStore = createWithEqualityFn<ChatStore>()(- subscribeWithSelector(devtools(createStore)),- shallow-);-```--## Single Slice Structure--```plaintext-src/store/chat/slices/-βββ [sliceName]/- βββ action.ts # Define actions (or actions/ directory)- βββ initialState.ts # State structure and initial values- βββ reducer.ts # (Optional) Reducer pattern- βββ selectors.ts # Define selectors- βββ index.ts # (Optional) Re-exports-```--### initialState.ts--```typescript-export interface ChatTopicState {- activeTopicId?: string;- topicMaps: Record<string, ChatTopic[]>;- topicsInit: boolean;- topicLoadingIds: string[];-}--export const initialTopicState: ChatTopicState = {- activeTopicId: undefined,- topicMaps: {},- topicsInit: false,- topicLoadingIds: [],-};-```--### selectors.ts--```typescript-const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => s.topicMaps[s.activeId];--const getTopicById =- (id: string) =>- (s: ChatStoreState): ChatTopic | undefined =>- currentTopics(s)?.find((topic) => topic.id === id);--// Core pattern: Use xxxSelectors aggregate-export const topicSelectors = {- currentTopics,- getTopicById,-};-```--## Complex Actions Sub-directory--```plaintext-src/store/chat/slices/agentRun/-βββ actions/-β βββ entries/ # conversation lifecycle / command bus-β βββ dispatch/ # agent dispatchers-β βββ transports/ # gateway / client / hetero executors-β βββ lifecycle/-β βββ state/-βββ initialState.ts-βββ selectors.ts-```--## State Design Patterns--### Map Structure for Associated Data--```typescript-topicMaps: Record<string, ChatTopic[]>;-messagesMap: Record<string, ChatMessage[]>;-```--### Arrays for Loading State--```typescript-messageLoadingIds: string[]-topicLoadingIds: string[]-```--### Optional Fields for Active Items--```typescript-activeId: string-activeTopicId?: string-```--## Best Practices--1. **Slice division**: By functional domain (message, topic, aiChat)-2. **File naming**: camelCase for directories, consistent patterns-3. **State structure**: Flat, avoid deep nesting-4. **Type safety**: Clear TypeScript interfaces for each slicediff --git a/packages/replica/README.md b/packages/replica/README.mdindex 79ef1b11aca..b001c173319 100644--- a/packages/replica/README.md+++ b/packages/replica/README.md@@ -47,6 +47,8 @@ slice.loadMore(key);slice.optimistic(key, apply, serverCall);```+A persisted read is asynchronous, so a list hydrated only by `useSync` paints its loading state for a few frames on a cold start. When that list must paint without a skeleton, seed it from the route loader before the route commits: `slice.ensureScope(scope)` + `slice.hydrate(params, scope)`, bounded by `settleWithin(β¦, PRE_PAINT_HYDRATE_TIMEOUT)` from `@/libs/replica/prePaint`. A later `useSync` hydrate is a no-op once the slot is filled.+Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.## Transcripts and other irregular pagesdiff --git a/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx b/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsxindex 9e915b81c71..7ed56207133 100644--- a/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx+++ b/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx@@ -89,10 +89,7 @@ vi.mock('@/store/home', () => ({}));vi.mock('@/store/page', () => ({- usePageStore: (selector: (state: Record<string, unknown>) => unknown) =>- selector({- createNewPage: createNewPageMock,- }),+ pageActions: { createNewPage: createNewPageMock },}));const isActionItem = (diff --git a/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx b/src/features/HomeSidebar/hooks/useCreateMenuItems.tsxindex 1b941552c17..4f518f009cd 100644--- a/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx+++ b/src/features/HomeSidebar/hooks/useCreateMenuItems.tsx@@ -29,7 +29,7 @@ import { chatGroupService } from '@/services/chatGroup';import { useAgentStore } from '@/store/agent';import { useAgentGroupStore } from '@/store/agentGroup';import { useHomeStore } from '@/store/home';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';type MenuItem = NonNullable<ItemType> & { sfSymbol?: SFSymbol };@@ -65,7 +65,6 @@ export const useCreateMenuItems = () => {s.switchToGroup,]);const [createGroup, loadGroups] = useAgentGroupStore((s) => [s.createGroup, s.loadGroups]);- const createNewPage = usePageStore((s) => s.createNewPage);const [isCreatingGroup, setIsCreatingGroup] = useState(false);const [isCreatingSessionGroup, setIsCreatingSessionGroup] = useState(false);@@ -419,13 +418,13 @@ export const useCreateMenuItems = () => {// rows to `'private'`; pass it explicitly so the optimistic row lands in// η§δΊΊ too, instead of flashing in ε·₯δ½εΊ and jumping when the server replies.const defaultVisibility = activeWorkspaceId ? 'private' : undefined;- const newPageId = await createNewPage(untitledTitle, defaultVisibility);+ const newPageId = await pageActions.createNewPage(untitledTitle, defaultVisibility);navigate(`/page/${newPageId}`);} catch (error) {console.error('Failed to create page:', error);toast.error('Failed to create page');}- }, [canCreate, createNewPage, tFile, navigate, activeWorkspaceId]);+ }, [canCreate, tFile, navigate, activeWorkspaceId]);/*** Create page menu itemdiff --git a/src/features/PageEditor/Header/useMenu.test.tsx b/src/features/PageEditor/Header/useMenu.test.tsxindex b4bd18c72e5..2daa6e03f98 100644--- a/src/features/PageEditor/Header/useMenu.test.tsx+++ b/src/features/PageEditor/Header/useMenu.test.tsx@@ -103,11 +103,11 @@ vi.mock('@/store/page', () => ({pageSelectors: {getDocumentById: (_id: string) => (_s: unknown) => undefined,},- usePageStore: (selector: (state: Record<string, unknown>) => unknown) =>- selector({- publishPageToWorkspace: vi.fn(),- setPageVisibility: vi.fn(),- }),+ pageActions: {+ publishPageToWorkspace: vi.fn(),+ setPageVisibility: vi.fn(),+ },+ usePageStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),}));vi.mock('@/store/user', () => ({diff --git a/src/features/PageEditor/Header/useMenu.tsx b/src/features/PageEditor/Header/useMenu.tsxindex 4df31878890..b580a505ef8 100644--- a/src/features/PageEditor/Header/useMenu.tsx+++ b/src/features/PageEditor/Header/useMenu.tsx@@ -28,7 +28,7 @@ import { editorSelectors } from '@/store/document/slices/editor';import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -85,8 +85,6 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {const openedFromLibraryId = usePageEditorStore((s) => s.knowledgeBaseId);const isInLibrary = Boolean(openedFromLibraryId || pageDocument?.metadata?.knowledgeBaseId);- const publishPageToWorkspace = usePageStore((s) => s.publishPageToWorkspace);- const setPageVisibility = usePageStore((s) => s.setPageVisibility);const canPublish = Boolean(activeWorkspaceId && isOwnPage && pageDocument?.visibility === 'private' && canEditPage,);@@ -145,7 +143,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {okText: t('continue', { ns: 'common' }),onOk: async () => {try {- await publishPageToWorkspace(documentId);+ await pageActions.publishPageToWorkspace(documentId);toast.success(t('pageList.publishSuccess'));} catch (error) {console.error('Failed to publish page:', error);@@ -154,7 +152,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {},title: t('pageList.publishConfirm.title'),});- }, [canPublish, documentId, publishPageToWorkspace, t]);+ }, [canPublish, documentId, t]);const handleMakePrivate = useCallback(() => {if (!canMakePrivate || !documentId) return;@@ -165,7 +163,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {okText: t('continue', { ns: 'common' }),onOk: async () => {try {- await setPageVisibility(documentId, 'private');+ await pageActions.setPageVisibility(documentId, 'private');toast.success(t('makePrivate.success', { ns: 'common' }));} catch (error) {console.error('Failed to make page private:', error);@@ -174,7 +172,7 @@ export const useMenu = (options: UseMenuOptions = {}): { menuItems: any[] } => {},title: t('makePrivate.confirm.title', { ns: 'common' }),});- }, [canMakePrivate, documentId, isInLibrary, setPageVisibility, t]);+ }, [canMakePrivate, documentId, isInLibrary, t]);const handleExportMarkdown = useCallback(async () => {const state = storeApi.getState();diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 4ad364de528..2ff71e13307 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -15,7 +15,7 @@ import { useRegisterFilesHotkeys } from '@/hooks/useHotkeys';import { usePermission } from '@/hooks/usePermission';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';import { StyleSheet } from '@/utils/styles';import DocumentComments from './DocumentComments';@@ -474,7 +474,6 @@ export const PageEditor: FC<PageEditorProps> = ({syncPageAgentActiveState,}) => {const { allowed: canEdit } = usePermission('edit_own_content');- const deletePage = usePageStore((s) => s.deletePage);return (<PageAgentProvider pageId={pageId} syncActiveAgent={syncPageAgentActiveState}>@@ -490,7 +489,7 @@ export const PageEditor: FC<PageEditorProps> = ({onDelete={() => {if (!canEdit) return;- deletePage(pageId || '');+ pageActions.deletePage(pageId || '');}}onEmojiChange={(emoji) => {if (!canEdit) return;diff --git a/src/features/PageExplorer/PageExplorerPlaceholder.tsx b/src/features/PageExplorer/PageExplorerPlaceholder.tsxindex b5bbaa9df93..c5f679436aa 100644--- a/src/features/PageExplorer/PageExplorerPlaceholder.tsx+++ b/src/features/PageExplorer/PageExplorerPlaceholder.tsx@@ -11,7 +11,7 @@ import NavHeader from '@/features/NavHeader';import useNotionImport from '@/features/ResourceManager/components/Header/hooks/useNotionImport';import { usePermission } from '@/hooks/usePermission';import { useFileStore } from '@/store/file';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';import { DocumentSourceType } from '@/types/document';import { standardizeIdentifier } from '@/utils/identifier';@@ -78,21 +78,6 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(const { allowed: canCreate } = usePermission('create_content');const [isUploading, setIsUploading] = useState(false);- // Page-specific operations from pageStore- const [- createNewPage,- createOptimisticPage,- replaceTempPageWithReal,- setSelectedPageId,- fetchDocuments,- ] = usePageStore((s) => [- s.createNewPage,- s.createOptimisticPage,- s.replaceTempPageWithReal,- s.setSelectedPageId,- s.fetchDocuments,- ]);-// File operations from FileStore (for uploads and notion import)const [createDocument] = useFileStore((s) => [s.createDocument]);@@ -100,7 +85,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(createDocument,currentFolderId: null,libraryId: knowledgeBaseId ?? null,- refetchResources: fetchDocuments,+ refetchResources: pageActions.refreshDocuments,t,});@@ -118,14 +103,14 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(if (!content) {// For empty pages, use createNewPage which handles optimistic updates- await createNewPage(title);+ await pageActions.createNewPage(title);return;}// For markdown uploads with content, use optimistic pattern similar to createNewPage- const tempPageId = createOptimisticPage(title);+ const tempPageId = pageActions.createOptimisticPage(title);// Set selected page to temp ID immediately (with URL update disabled for temp IDs)- setSelectedPageId(tempPageId, false);+ pageActions.setSelectedPageId(tempPageId, false);try {const newDoc = await createDocument({@@ -155,14 +140,14 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(};// Replace optimistic with real- replaceTempPageWithReal(tempPageId, realPage);+ pageActions.replaceTempPageWithReal(tempPageId, realPage);// Update selected page ID and URL to the real page- setSelectedPageId(newDoc.id);+ pageActions.setSelectedPageId(newDoc.id);} catch (error) {console.error('Failed to create page:', error);// Remove temp document on error- usePageStore.getState().removeTempPage(tempPageId);- setSelectedPageId(null);+ pageActions.removeTempPage(tempPageId);+ pageActions.setSelectedPageId(null);throw error;}};@@ -185,7 +170,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(const fileName = file.name.replace(/\.(pdf|docx)$/i, '');// Create optimistic document but don't select it yet- const tempPageId = createOptimisticPage(fileName);+ const tempPageId = pageActions.createOptimisticPage(fileName);try {// Upload file to server@@ -225,10 +210,10 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(};// Replace optimistic with real document in the store- replaceTempPageWithReal(tempPageId, realPage);+ pageActions.replaceTempPageWithReal(tempPageId, realPage);// Update selected page ID in store (with full ID including prefix)- setSelectedPageId(parsedDocument.id, false);+ pageActions.setSelectedPageId(parsedDocument.id, false);// Update URL with stripped ID (without prefix)const cleanId = standardizeIdentifier(parsedDocument.id);@@ -237,7 +222,7 @@ const PageExplorerPlaceholder = memo<PageExplorerPlaceholderProps>(} catch (error) {console.error('Failed to upload and parse file:', error);// Remove temp document on error- usePageStore.getState().removeTempPage(tempPageId);+ pageActions.removeTempPage(tempPageId);throw error;}}diff --git a/src/features/PageExplorer/index.tsx b/src/features/PageExplorer/index.tsxindex 3942947d521..3500e936f2d 100644--- a/src/features/PageExplorer/index.tsx+++ b/src/features/PageExplorer/index.tsx@@ -3,7 +3,7 @@import { memo, type ReactNode, useCallback } from 'react';import { PageEditor } from '@/features/PageEditor';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';interface PageExplorerProps {/** Forwarded to PageEditor. */@@ -24,8 +24,6 @@ interface PageExplorerProps {* Work together with a sidebar @/features/Pages/PageLayout/Body*/const PageExplorer = memo<PageExplorerProps>(({ pageId, header, fullWidthHeader, rightPanel }) => {- const updatePageOptimistically = usePageStore((s) => s.updatePageOptimistically);-// Get document title and emoji from PageStoreconst document = usePageStore(pageSelectors.getDocumentById(pageId));const title = document?.title;@@ -34,16 +32,16 @@ const PageExplorer = memo<PageExplorerProps>(({ pageId, header, fullWidthHeader,// Optimistic update handlers for title and emojiconst handleTitleChange = useCallback((newTitle: string) => {- updatePageOptimistically(pageId, { title: newTitle });+ pageActions.updatePageOptimistically(pageId, { title: newTitle });},- [pageId, updatePageOptimistically],+ [pageId],);const handleEmojiChange = useCallback((newEmoji: string | undefined) => {- updatePageOptimistically(pageId, { emoji: newEmoji });+ pageActions.updatePageOptimistically(pageId, { emoji: newEmoji });},- [pageId, updatePageOptimistically],+ [pageId],);return (diff --git a/src/features/Pages/PageLayout/Body/AllPagesDrawer/Content.tsx b/src/features/Pages/PageLayout/Body/AllPagesDrawer/Content.tsxindex a0821066567..a3f88289eff 100644--- a/src/features/Pages/PageLayout/Body/AllPagesDrawer/Content.tsx+++ b/src/features/Pages/PageLayout/Body/AllPagesDrawer/Content.tsx@@ -7,7 +7,7 @@ import { VList } from 'virtua';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import PageEmpty from '@/features/PageEmpty';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';import { type LobeDocument } from '@/types/document';import Item from '../List/Item';@@ -20,10 +20,9 @@ const Content = memo<ContentProps>(({ searchKeyword }) => {const virtuaRef = useRef<VListHandle>(null);const fetchedCountRef = useRef(-1);- const [hasMore, isLoadingMore, loadMoreDocuments] = usePageStore((s) => [+ const [hasMore, isLoadingMore] = usePageStore((s) => [pageSelectors.hasMoreDocuments(s),pageSelectors.isLoadingMoreDocuments(s),- s.loadMoreDocuments,]);const allFilteredDocuments = usePageStore(pageSelectors.getFilteredDocuments);@@ -57,9 +56,9 @@ const Content = memo<ContentProps>(({ searchKeyword }) => {// When scrolled near the end (within 5 items), load moreif (fetchedCountRef.current < count && bottomVisibleIndex + 5 > count) {fetchedCountRef.current = count;- await loadMoreDocuments();+ await pageActions.loadMoreDocuments();}- }, [hasMore, loadMoreDocuments, count, isSearching]);+ }, [hasMore, count, isSearching]);const showLoading = isLoadingMore && !isSearching;diff --git a/src/features/Pages/PageLayout/Body/List/Item/Editing.tsx b/src/features/Pages/PageLayout/Body/List/Item/Editing.tsxindex 4e40d586e06..6d5ca876bec 100644--- a/src/features/Pages/PageLayout/Body/List/Item/Editing.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/Editing.tsx@@ -7,7 +7,7 @@ import EmojiPicker from '@/components/EmojiPicker';import { useIsDark } from '@/hooks/useIsDark';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';-import { usePageStore } from '@/store/page';+import { pageActions, usePageStore } from '@/store/page';interface EditingProps {currentEmoji?: string;@@ -36,7 +36,7 @@ const Editing = memo<EditingProps>(({ documentId, title, currentEmoji, toggleEdiif (newTitle && title !== newTitle) updates.title = newTitle;if (newEmoji !== undefined && currentEmoji !== newEmoji) updates.emoji = newEmoji;- await usePageStore.getState().renamePage(documentId, updates.title || title, updates.emoji);+ await pageActions.renamePage(documentId, updates.title || title, updates.emoji);} catch (error) {console.error('Failed to update page:', error);}diff --git a/src/features/Pages/PageLayout/Body/List/Item/index.tsx b/src/features/Pages/PageLayout/Body/List/Item/index.tsxindex d69598e9927..4ff464c4afc 100644--- a/src/features/Pages/PageLayout/Body/List/Item/index.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/index.tsx@@ -10,7 +10,7 @@ import { isDesktop } from '@/const/version';import NavItem from '@/features/NavPanel/components/NavItem';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { useElectronStore } from '@/store/electron';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';import Actions from './Actions';import Editing from './Editing';@@ -28,8 +28,6 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {return [s.renamingPageId === pageId, s.selectedPageId, doc] as const;});- const selectPage = usePageStore((s) => s.selectPage);- const setRenamingPageId = usePageStore((s) => s.setRenamingPageId);const addTab = useElectronStore((s) => s.addTab);const activeWorkspaceSlug = useActiveWorkspaceSlug();@@ -39,9 +37,9 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {const toggleEditing = useCallback((visible?: boolean) => {- setRenamingPageId(visible ? pageId : null);+ pageActions.setRenamingPageId(visible ? pageId : null);},- [pageId, setRenamingPageId],+ [pageId],);const clickTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -54,14 +52,14 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {if (isDesktop) {clickTimerRef.current = setTimeout(() => {clickTimerRef.current = null;- selectPage(pageId);+ pageActions.selectPage(pageId);}, 250);} else {- selectPage(pageId);+ pageActions.selectPage(pageId);}}},- [editing, selectPage, pageId],+ [editing, pageId],);const handleDoubleClick = useCallback(() => {@@ -71,8 +69,8 @@ const PageListItem = memo<DocumentItemProps>(({ pageId, className }) => {clickTimerRef.current = null;}addTab(buildWorkspaceAwarePath(`/page/${pageId}`, activeWorkspaceSlug));- selectPage(pageId);- }, [pageId, activeWorkspaceSlug, addTab, selectPage]);+ pageActions.selectPage(pageId);+ }, [pageId, activeWorkspaceSlug, addTab]);// Icon with emoji supportconst icon = useMemo(() => {diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsxindex 72ebf48b525..7915351ed4f 100644--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx@@ -67,21 +67,13 @@ vi.mock('@/store/page', () => ({getDocumentById: (_id: string) => (_s: unknown) => storeMock.document,getFilteredDocuments: (_s: unknown) => (storeMock.document ? [storeMock.document] : []),},- usePageStore: Object.assign(- (selector: (state: Record<string, unknown>) => unknown) =>- selector({- duplicatePage: vi.fn(),- publishPageToWorkspace: vi.fn(),- removePage: vi.fn(),- }),- {- getState: () => ({- duplicatePage: vi.fn(),- publishPageToWorkspace: vi.fn(),- removePage: vi.fn(),- }),- },- ),+ pageActions: {+ duplicatePage: vi.fn(),+ publishPageToWorkspace: vi.fn(),+ removePage: vi.fn(),+ setPageVisibility: vi.fn(),+ },+ usePageStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),}));vi.mock('@/store/user', () => ({diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsxindex 8bbb4631e3f..841792b0df5 100644--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.tsx@@ -14,7 +14,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { usePermission } from '@/hooks/usePermission';import { useElectronStore } from '@/store/electron';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -35,10 +35,6 @@ export const useDropdownMenu = ({const { allowed: canCreatePage } = usePermission('create_content');const { allowed: canEditPage } = usePermission('edit_own_content');const addTab = useElectronStore((s) => s.addTab);- const removePage = usePageStore((s) => s.removePage);- const duplicatePage = usePageStore((s) => s.duplicatePage);- const publishPageToWorkspace = usePageStore((s) => s.publishPageToWorkspace);- const setPageVisibility = usePageStore((s) => s.setPageVisibility);const document = usePageStore((s) => pageSelectors.getDocumentById(pageId)(s));const transferMenuItems = useDocumentTransferMenuItem(pageId, {transferLabel: t('pageEditor.menu.move', { ns: 'file' }),@@ -63,7 +59,7 @@ export const useDropdownMenu = ({okText: t('delete'),onOk: async () => {try {- await removePage(pageId);+ await pageActions.removePage(pageId);toast.success(t('pageEditor.deleteSuccess', { ns: 'file' }));} catch (error) {console.error('Failed to delete page:', error);@@ -72,17 +68,17 @@ export const useDropdownMenu = ({},title: t('pageEditor.deleteConfirm.title', { ns: 'file' }),});- }, [canEditPage, pageId, removePage, t]);+ }, [canEditPage, pageId, t]);const handleDuplicate = useCallback(async () => {if (!canCreatePage) return;try {- await duplicatePage(pageId);+ await pageActions.duplicatePage(pageId);} catch (error) {console.error('Failed to duplicate page:', error);}- }, [canCreatePage, pageId, duplicatePage]);+ }, [canCreatePage, pageId]);const handlePublish = useCallback(() => {if (!canPublish) return;@@ -97,7 +93,7 @@ export const useDropdownMenu = ({okText: t('continue'),onOk: async () => {try {- await publishPageToWorkspace(pageId);+ await pageActions.publishPageToWorkspace(pageId);toast.success(t('pageList.publishSuccess', { ns: 'file' }));} catch (error) {console.error('Failed to publish page:', error);@@ -106,7 +102,7 @@ export const useDropdownMenu = ({},title: t('pageList.publishConfirm.title', { ns: 'file' }),});- }, [canPublish, pageId, publishPageToWorkspace, t]);+ }, [canPublish, pageId, t]);const handleMakePrivate = useCallback(() => {if (!canMakePrivate) return;@@ -117,7 +113,7 @@ export const useDropdownMenu = ({okText: t('continue'),onOk: async () => {try {- await setPageVisibility(pageId, 'private');+ await pageActions.setPageVisibility(pageId, 'private');toast.success(t('makePrivate.success'));} catch (error) {console.error('Failed to make page private:', error);@@ -126,7 +122,7 @@ export const useDropdownMenu = ({},title: t('makePrivate.confirm.title'),});- }, [canMakePrivate, pageId, setPageVisibility, t]);+ }, [canMakePrivate, pageId, t]);return useCallback(() =>diff --git a/src/features/Pages/PageLayout/Body/List/index.tsx b/src/features/Pages/PageLayout/Body/List/index.tsxindex 9b134fb7063..20de04a4043 100644--- a/src/features/Pages/PageLayout/Body/List/index.tsx+++ b/src/features/Pages/PageLayout/Body/List/index.tsx@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';import Item from './Item';@@ -27,7 +27,7 @@ interface PageListProps {const PageList = memo<PageListProps>(({ visibility }) => {const { t } = useTranslation(['file', 'common']);- const [filteredDocuments, hasMore, isLoadingMore, openAllPagesDrawer] = usePageStore((s) => {+ const [filteredDocuments, hasMore, isLoadingMore] = usePageStore((s) => {let docs;let more;if (visibility === 'private') {@@ -40,7 +40,7 @@ const PageList = memo<PageListProps>(({ visibility }) => {docs = pageSelectors.getFilteredDocumentsLimited(s);more = pageSelectors.hasMoreFilteredDocuments(s);}- return [docs, more, pageSelectors.isLoadingMoreDocuments(s), s.openAllPagesDrawer] as const;+ return [docs, more, pageSelectors.isLoadingMoreDocuments(s)] as const;});return (@@ -53,7 +53,7 @@ const PageList = memo<PageListProps>(({ visibility }) => {<NavItemicon={MoreHorizontal}title={t('more', { ns: 'common' })}- onClick={openAllPagesDrawer}+ onClick={pageActions.openAllPagesDrawer}/>)}</Flexbox>diff --git a/src/features/Pages/PageLayout/Body/index.tsx b/src/features/Pages/PageLayout/Body/index.tsxindex 90b06d692f1..f410c6625a9 100644--- a/src/features/Pages/PageLayout/Body/index.tsx+++ b/src/features/Pages/PageLayout/Body/index.tsx@@ -21,7 +21,7 @@ import AsyncBoundary from '@/components/AsyncBoundary';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import PageEmpty from '@/features/PageEmpty';import { usePermission } from '@/hooks/usePermission';-import { pageSelectors, usePageStore } from '@/store/page';+import { pageActions, pageSelectors, usePageStore } from '@/store/page';import AddButton from '../Header/AddButton';import Actions from './Actions';@@ -46,26 +46,22 @@ export enum GroupKey {const Body = memo(() => {const { t } = useTranslation('file');- // Initialize documents list via SWR; keep `isValidating` so the accordion- // header can show a subtle in-flight indicator (mirrors the Private Agent- // pattern in `home/_layout/Body/Private`).- const useFetchDocuments = usePageStore((s) => s.useFetchDocuments);- // Use the SWR result as the settled signal: `data` is `undefined` until the- // first fetch succeeds, so a failed load surfaces error + Retry instead of a- // permanent skeleton. The store's `documents` field can't be the signal β it- // initializes to `[]` (a settled-looking empty), so a failed fetch would fall- // through to the "no pages" empty rather than the error.- const { data, error, isLoading, isValidating, mutate } = useFetchDocuments();+ // Drive the list's replica sync; keep `isValidating` so the accordion header+ // can show a subtle in-flight indicator (mirrors the Private Agent pattern in+ // `home/_layout/Body/Private`).+ // The sync hook only returns flags β the rows live in the store. Use the list+ // entry itself as the settled signal: it is `undefined` until IndexedDB+ // hydration or the first server page lands, so a failed load surfaces error ++ // Retry instead of a permanent skeleton.+ const { error, isValidating, revalidate } = pageActions.useFetchDocuments();+ const isPageListInit = usePageStore(pageSelectors.isPageListInit);const filteredDocumentsCount = usePageStore(pageSelectors.filteredDocumentsCount);const privateCount = usePageStore(pageSelectors.privateFilteredDocumentsCount);const workspaceCount = usePageStore(pageSelectors.workspaceFilteredDocumentsCount);const searchKeywords = usePageStore((s) => s.searchKeywords);const dropdownMenu = useDropdownMenu();- const [allPagesDrawerOpen, closeAllPagesDrawer] = usePageStore((s) => [- s.allPagesDrawerOpen,- s.closeAllPagesDrawer,- ]);+ const allPagesDrawerOpen = usePageStore((s) => s.allPagesDrawerOpen);const activeWorkspaceId = useActiveWorkspaceId();const searchActive = Boolean(searchKeywords.trim());@@ -73,7 +69,6 @@ const Body = memo(() => {// Empty-bucket call-to-action: a single "New Page" row that creates directly// into the right visibility. Mirrors the Home sidebar's "εε»Ίε©η" affordance// β the bucket is empty but still actionable.- const createNewPage = usePageStore((s) => s.createNewPage);const { allowed: canCreate } = usePermission('create_content');const untitledLabel = t('pageList.untitled');const newPageLabel = t('addPage');@@ -88,7 +83,7 @@ const Body = memo(() => {paddingInline={4}style={canCreate ? { height: 36 } : { cursor: 'not-allowed', height: 36, opacity: 0.5 }}variant={'borderless'}- onClick={() => canCreate && createNewPage(untitledLabel, visibility)}+ onClick={() => canCreate && pageActions.createNewPage(untitledLabel, visibility)}><Center flex={'none'} height={28} width={28}><Icon icon={PlusIcon} size={'small'} />@@ -147,12 +142,12 @@ const Body = memo(() => {</ContextMenuTrigger><AccordionPanel><AsyncBoundary- data={data}+ data={isPageListInit || undefined}error={error}errorVariant={'inline'}- isLoading={isLoading}+ isLoading={!isPageListInit && !error}loading={<SkeletonList />}- onRetry={() => mutate()}+ onRetry={() => revalidate()}><Flexbox gap={1} paddingBlock={1}>{section.children}@@ -223,7 +218,7 @@ const Body = memo(() => {})}</AccordionRoot>)}- <AllPagesDrawer open={allPagesDrawerOpen} onClose={closeAllPagesDrawer} />+ <AllPagesDrawer open={allPagesDrawerOpen} onClose={pageActions.closeAllPagesDrawer} /></Flexbox>);});diff --git a/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx b/src/features/Pages/PageLayout/Body/useDropdownMenu.tsxindex 3ae492f0677..01d622ba9b7 100644--- a/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx+++ b/src/features/Pages/PageLayout/Body/useDropdownMenu.tsx@@ -13,7 +13,6 @@ import { usePageStore } from '@/store/page';export const useDropdownMenu = (): MenuProps['items'] => {const { t } = useTranslation();const showOnlyPagesNotInLibrary = usePageStore((s) => s.showOnlyPagesNotInLibrary);- const setShowOnlyPagesNotInLibrary = usePageStore((s) => s.setShowOnlyPagesNotInLibrary);const [pagePageSize, updateSystemStatus] = useGlobalStore((s) => [systemStatusSelectors.pagePageSize(s),@@ -40,11 +39,5 @@ export const useDropdownMenu = (): MenuProps['items'] => {label: t('common:navPanel.displayItems'),},];- }, [- t,- setShowOnlyPagesNotInLibrary,- showOnlyPagesNotInLibrary,- pagePageSize,- updateSystemStatus,- ]);+ }, [t, showOnlyPagesNotInLibrary, pagePageSize, updateSystemStatus]);};diff --git a/src/features/Pages/PageLayout/Header/AddButton.tsx b/src/features/Pages/PageLayout/Header/AddButton.tsxindex 9e80a4af92e..0f800c1cb0d 100644--- a/src/features/Pages/PageLayout/Header/AddButton.tsx+++ b/src/features/Pages/PageLayout/Header/AddButton.tsx@@ -6,7 +6,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { usePermission } from '@/hooks/usePermission';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';interface AddButtonProps {/**@@ -29,13 +29,11 @@ const AddButton = memo<AddButtonProps>(({ compact, visibility }) => {const { t } = useTranslation('file');const { allowed: canCreate } = usePermission('create_content');- const createNewPage = usePageStore((s) => s.createNewPage);-const handleNewDocument = () => {if (!canCreate) return;const untitledTitle = t('pageList.untitled');- createNewPage(untitledTitle, visibility);+ pageActions.createNewPage(untitledTitle, visibility);};return (diff --git a/src/hooks/usePrefetchPage.ts b/src/hooks/usePrefetchPage.tsindex 2cdd1f2d054..57a417c5e8f 100644--- a/src/hooks/usePrefetchPage.ts+++ b/src/hooks/usePrefetchPage.ts@@ -7,6 +7,10 @@ import { documentSWRKeys } from '@/services/document/swrKeys';/*** Returns a callback to prefetch page/document data into the SWR cache.* Call the returned function on mouseEnter to warm the cache before navigation.+ *+ * The Pages sidebar list is no longer an SWR cache entry β it is a+ * `@lobechat/replica` resource that hydrates from IndexedDB on mount β so only+ * the editor's document content is warmed here.*/export const usePrefetchPage = () => {return useCallback((documentId: string) => {@@ -16,10 +20,5 @@ export const usePrefetchPage = () => {mutate(documentSWRKeys.editor(documentId), documentService.getDocumentById(documentId), {revalidate: false,});-- // Prefetch page documents list (for the sidebar)- mutate(documentSWRKeys.pageDocuments(), documentService.getPageDocuments(), {- revalidate: false,- });}, []);};diff --git a/src/libs/replica/prePaint.ts b/src/libs/replica/prePaint.tsnew file mode 100644index 00000000000..05b91f96471--- /dev/null+++ b/src/libs/replica/prePaint.ts@@ -0,0 +1,21 @@+/**+ * Upper bound for a route loader's pre-paint hydrate.+ *+ * The read itself is not the risk: measured on the real storage path, a warm+ * IndexedDB read of a sidebar page (20 rows β 9 KB) is ~0.2β0.5 ms p50, the+ * first read of a cold page with an existing database ~1β10 ms, and creating+ * the database ~7β30 ms. The deadline only ever fires on a pathological storage+ * stall, so a route transition never waits longer than this for it.+ */+export const PRE_PAINT_HYDRATE_TIMEOUT = 50;++/** Resolve once `promise` settles or `ms` elapses β never rejects, never hangs. */+export const settleWithin = (promise: Promise<unknown>, ms: number): Promise<void> =>+ new Promise((resolve) => {+ const finish = () => {+ clearTimeout(timer);+ resolve();+ };+ const timer = setTimeout(finish, ms);+ void Promise.resolve(promise).then(finish, finish);+ });diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex 54e833b49f3..854c385772b 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -1,8 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { PRE_PAINT_HYDRATE_TIMEOUT } from '@/libs/replica/prePaint';+import {agentChatTopicListLoader,- PRE_PAINT_HYDRATE_TIMEOUT,preHydrateMessagesForRoute,preHydrateTopicListForRoute,} from './topicListLoader';diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 5067eec0f52..67c63a00798 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -2,6 +2,7 @@ import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import type { LoaderFunctionArgs } from 'react-router';import { getSidebarTopicListParams } from '@/hooks/chatTopicListQuery';+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';import { readPersistedTranscript } from '@/services/message/replica';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';@@ -10,28 +11,6 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));-/**- * Upper bound for the pre-paint hydrate.- *- * The read itself is not the risk: measured on the real storage path, a warm- * IndexedDB read of the sidebar page (20 rows β 9 KB) is ~0.2β0.5 ms p50, the- * first read of a cold page with an existing database ~1β10 ms, and creating- * the database ~7β30 ms. The deadline only ever fires on a pathological storage- * stall, so a route transition never waits longer than this for it.- */-export const PRE_PAINT_HYDRATE_TIMEOUT = 50;--/** Resolve once `promise` settles or `ms` elapses β never rejects, never hangs. */-const settleWithin = (promise: Promise<unknown>, ms: number): Promise<void> =>- new Promise((resolve) => {- const finish = () => {- clearTimeout(timer);- resolve();- };- const timer = setTimeout(finish, ms);- void Promise.resolve(promise).then(finish, finish);- });-/*** Builtin slugs (`inbox`, β¦) resolve from the store; an id passes through. A* user-chosen slug needs a server lookup, so it resolves only after the routediff --git a/src/routes/(main)/page/pageListLoader.ts b/src/routes/(main)/page/pageListLoader.tsnew file mode 100644index 00000000000..0e8c32c1736--- /dev/null+++ b/src/routes/(main)/page/pageListLoader.ts@@ -0,0 +1,11 @@+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { pageActions } from '@/store/page';++// Route loaders run before React commits the route: the only point where the+// persisted page list (an async read) can land before the sidebar paints its+// loading skeleton.+export const pageListLoader = async (): Promise<null> => {+ await settleWithin(pageActions.preHydrate(), PRE_PAINT_HYDRATE_TIMEOUT);++ return null;+};diff --git a/src/routes/(mobile)/page/[id]/index.tsx b/src/routes/(mobile)/page/[id]/index.tsxindex 5d8e9795062..fd73ae5fb94 100644--- a/src/routes/(mobile)/page/[id]/index.tsx+++ b/src/routes/(mobile)/page/[id]/index.tsx@@ -9,7 +9,7 @@ import { delayed } from '@/components/Skeleton/Delayed';import SurfaceSkeleton from '@/components/Skeleton/Surface';import PageExplorer from '@/features/PageExplorer';import MobilePageHeader from '@/features/Pages/MobilePageHeader';-import { usePageStore } from '@/store/page';+import { pageActions, usePageStore } from '@/store/page';import { getIdFromIdentifier } from '@/utils/identifier';const MobilePageDetail = memo(() => {@@ -20,8 +20,7 @@ const MobilePageDetail = memo(() => {// Mobile mounts no page list, so load this page into the store directly β// PageEditor reads title, emoji and workspace lock state from it.- const useFetchPageDetail = usePageStore((s) => s.useFetchPageDetail);- useFetchPageDetail(pageId);+ pageActions.useFetchPageDetail(pageId);useUnmount(() => {usePageStore.setState({ selectedPageId: undefined });diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.tsindex 52f4e0e33a6..e1bdef3964d 100644--- a/src/services/agentDocument.test.ts+++ b/src/services/agentDocument.test.ts@@ -67,8 +67,8 @@ describe('AgentDocumentService', () => {expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);// `documentsList` revalidates via a prefix matcher so the full list and the// `non-web` variant (and their workspace-scoped keys) refresh together. Pick- // the agent-documents matcher out of the list: the notebook branch also- // pushes a function matcher (its replica sync key) for `topic-1`.+ // the agent-documents matcher out of the list: the page and notebook replicas+ // also push function matchers for their own sync keys.const matchers = vi.mocked(mutate).mock.calls.map((call) => call[0])@@ -81,16 +81,25 @@ describe('AgentDocumentService', () => {expect(listMatcher!(['agent:documentsList', 'other-agent'])).toBe(false);expect(listMatcher!(['agent:documents', 'agent-1'])).toBe(false);expect(mutate).toHaveBeenCalledWith(['agent:documentEditor', 'agent-1', 'doc-1']);- expect(mutate).toHaveBeenCalledWith(['page:meta', 'page-doc-1']);- expect(mutate).toHaveBeenCalledWith(['page:detail', 'page-doc-1']);- expect(mutate).toHaveBeenCalledWith(['page:list']);- // The notebook list is a replica now, so `topicId` refreshes its sync key- // instead of the removed `notebook:documents` SWR entry.+ // The page domain is a replica, so its list and by-id copies sync through+ // `replica:sync` keys and refresh through the scoped matcher instead of the+ // removed `page:*` SWR keys.const scope = cacheScope.get();+ const matchesReplica = (key: unknown[]) => matchers.some((matcher) => matcher(key));+ expect(matchesReplica(['replica:sync', 'pageDetail', 1, scope, 'page-doc-1', {}])).toBe(true);+ // `revalidateReplica` without an entry key covers every entry of the+ // resourceβ¦+ expect(matchesReplica(['replica:sync', 'pageList', 1, scope, 'all', {}])).toBe(true);+ expect(matchesReplica(['replica:sync', 'pageList', 1, scope, 'any-entry', {}])).toBe(true);+ // β¦but only that resource, and only inside the active scope.+ expect(matchesReplica(['replica:sync', 'otherResource', 1, scope, 'all', {}])).toBe(false);+ expect(matchesReplica(['replica:sync', 'pageList', 1, 'other:personal', 'all', {}])).toBe(+ false,+ );+ // The notebook list is a replica too, so `topicId` refreshes its sync key+ // instead of the removed `notebook:documents` SWR entry.expect(- matchers.some((matcher) =>- matcher(['replica:sync', 'notebookDocuments', 1, scope, 'topic-1', 'topic-1']),- ),+ matchesReplica(['replica:sync', 'notebookDocuments', 1, scope, 'topic-1', 'topic-1']),).toBe(true);});diff --git a/src/services/document/index.ts b/src/services/document/index.tsindex 2fa4a89cbd5..a58dc1fae63 100644--- a/src/services/document/index.ts+++ b/src/services/document/index.ts@@ -1,4 +1,3 @@-import { PAGE_DOCUMENT_FILE_TYPES, PAGE_DOCUMENT_SOURCE_TYPES } from '@lobechat/const';import { type DocumentItem } from '@lobechat/database/schemas';import { lambdaClient } from '@/libs/trpc/client';@@ -207,23 +206,6 @@ export class DocumentService {return serializeHistoryComparison(result);}- async getPageDocuments(pageSize: number = 20): Promise<DocumentItem[]> {- const result = await this.queryDocuments({- current: 0,- fileTypes: PAGE_DOCUMENT_FILE_TYPES,- pageSize,- sourceTypes: PAGE_DOCUMENT_SOURCE_TYPES,- });-- return result.items- .filter(- (doc) =>- PAGE_DOCUMENT_SOURCE_TYPES.includes(doc.sourceType) &&- PAGE_DOCUMENT_FILE_TYPES.includes(doc.fileType),- )- .map((doc) => ({ ...doc, filename: doc.filename ?? doc.title ?? 'Untitled' }));- }-async getDocumentById(id: string, uniqueKey?: string): Promise<DocumentItem | undefined> {if (uniqueKey) {// Use fixed key so switching documents cancels the previous requestdiff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.tsindex 8b6e921fef9..cb08cae0fd2 100644--- a/src/services/document/invalidation.ts+++ b/src/services/document/invalidation.ts@@ -2,6 +2,7 @@ import { revalidateReplica } from '@/libs/replica';import { mutate } from '@/libs/swr';import { portalKeys } from '@/libs/swr/keys';import { notebookDocumentsResource } from '@/store/notebook/projection';+import { pageDetailResource, pageListResource } from '@/store/page/projection';import { agentDocumentSkillsResource } from '@/store/tool/slices/agentDocumentSkills/projection';import { agentDocumentSWRKeys, documentSWRKeys } from './swrKeys';@@ -36,13 +37,16 @@ export const invalidateDocumentMutation = async (if (refreshDocumentEditor !== false) {revalidations.push(mutate(documentSWRKeys.editor(documentId)));}- revalidations.push(mutate(documentSWRKeys.pageDetail(documentId)));- revalidations.push(mutate(documentSWRKeys.pageMeta(documentId)));+ // The page domain is a `@lobechat/replica` domain, so its by-id copy and+ // its list sync through `replica:sync` keys rather than the SWR cache:+ // refresh them here or a rename / move would not reach the Pages sidebar or+ // the page header until a remount.+ revalidations.push(revalidateReplica(pageDetailResource, documentId));revalidations.push(mutate(portalKeys.documentHeader(documentId)));}if (documentId || refreshPageDocuments) {- revalidations.push(mutate(documentSWRKeys.pageDocuments()));+ revalidations.push(revalidateReplica(pageListResource));}if (topicId) {diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.tsindex 53cca7f3934..831ff5c4b2e 100644--- a/src/services/document/swrKeys.ts+++ b/src/services/document/swrKeys.ts@@ -16,7 +16,4 @@ export const agentDocumentSWRKeys = {export const documentSWRKeys = {editor: (documentId: string) => ['document:editor', documentId] as const,- pageDetail: (documentId: string) => ['page:detail', documentId] as const,- pageDocuments: () => ['page:list'] as const,- pageMeta: (documentId: string) => ['page:meta', documentId] as const,};diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex c9c5b257401..2575340159e 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -77,6 +77,7 @@ import {import AppShellSkeleton, { APP_SHELL_FALLBACK_ID } from '@/spa/BootShell/AppShellSkeleton';import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';import { agentChatTopicListLoader } from '@/spa/router/agentChatTopicListLoader';+import { pageListLoader } from '@/spa/router/pageListLoader';import { NoRouteSkeleton, routeMeta, type RouteSkeletonProps } from '@/spa/router/routeMeta';import { SettingsTabs } from '@/store/global/initialState';import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';@@ -1163,6 +1164,7 @@ export const sharedMainAreaChildren: RouteObject[] = [{ preloadId: 'page' },),errorElement: <ErrorBoundary />,+ loader: pageListLoader,path: 'page',},];diff --git a/src/spa/router/pageListLoader.ts b/src/spa/router/pageListLoader.tsnew file mode 100644index 00000000000..c32e5127f9d--- /dev/null+++ b/src/spa/router/pageListLoader.ts@@ -0,0 +1,4 @@+// The route tables sit in the entry chunk's static graph; resolving the real+// loader on first use keeps the page store in the page route's lazy chunks.+export const pageListLoader = () =>+ import('@/routes/(main)/page/pageListLoader').then((module) => module.pageListLoader());diff --git a/src/spa/router/pageListLoader.wiring.test.ts b/src/spa/router/pageListLoader.wiring.test.tsnew file mode 100644index 00000000000..6a3c58cbd25--- /dev/null+++ b/src/spa/router/pageListLoader.wiring.test.ts@@ -0,0 +1,39 @@+// @vitest-environment happy-dom+import type { RouteObject } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { desktopRoutes } from './desktopRouter.config';+import { pageListLoader } from './pageListLoader';++const loaderModule = vi.hoisted(() => ({ evaluated: false }));++// Evaluating the real loader means the page store reached the entry chunk's+// first-screen graph.+vi.mock('@/routes/(main)/page/pageListLoader', () => {+ loaderModule.evaluated = true;+ return { pageListLoader: vi.fn(async () => null) };+});++const flatten = (routes: RouteObject[]): RouteObject[] =>+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);++describe('page list loader wiring', () => {+ it('does not load the store-backed loader while the route tables load', () => {+ expect(loaderModule.evaluated).toBe(false);+ });++ it('pre-hydrates the page list on the desktop page layout route', () => {+ const routes = flatten(desktopRoutes).filter((r) => r.path === 'page' && r.children?.length);++ expect(routes.length).toBeGreaterThan(0);++ expect(routes.map((r) => r.loader)).toEqual(routes.map(() => pageListLoader));+ });++ it('delegates to the real loader on first use', async () => {+ const { pageListLoader: realLoader } = await import('@/routes/(main)/page/pageListLoader');++ await expect(pageListLoader()).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalled();+ });+});diff --git a/src/store/document/slices/document/action.test.ts b/src/store/document/slices/document/action.test.tsindex dd664c2b143..1c32058783c 100644--- a/src/store/document/slices/document/action.test.ts+++ b/src/store/document/slices/document/action.test.ts@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type * as SwrModule from '@/libs/swr';import { useClientDataSWRWithSync } from '@/libs/swr';import { documentService } from '@/services/document';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';import { useDocumentStore } from '../../store';@@ -29,7 +29,7 @@ vi.mock('@/libs/swr', async (importOriginal) => {});vi.mock('@/store/page', () => ({- usePageStore: { getState: vi.fn(() => ({ upsertDocument: vi.fn() })) },+ pageActions: { upsertDocument: vi.fn() },}));const createEditor = () => ({@@ -214,8 +214,7 @@ describe('useFetchDocument onData', () => {});it('mirrors page metadata into the page store on the reconcile path', () => {- const upsertDocument = vi.fn();- vi.mocked(usePageStore.getState).mockReturnValue({ upsertDocument } as any);+ const upsertDocument = vi.mocked(pageActions.upsertDocument);const editor = createEditor();const onData = captureOnData('doc-1', editor, { sourceType: 'page' });const row = {diff --git a/src/store/document/slices/document/action.ts b/src/store/document/slices/document/action.tsindex 1605cd3fa9d..b21c24ec745 100644--- a/src/store/document/slices/document/action.ts+++ b/src/store/document/slices/document/action.ts@@ -9,7 +9,7 @@ import type { SWRResponse } from 'swr';import { useClientDataSWRWithSync } from '@/libs/swr';import { documentService } from '@/services/document';import { documentSWRKeys } from '@/services/document/swrKeys';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';import type { StoreSetter } from '@/store/types';import { isSkillMarkdownDocument, parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import { setNamespace } from '@/utils/storeDebug';@@ -259,7 +259,7 @@ export class DocumentActionImpl {this.#rememberTopicDocument(topicId, documentId);}if (sourceType === 'page') {- usePageStore.getState().upsertDocument(document);+ pageActions.upsertDocument(document);}return;}@@ -280,7 +280,7 @@ export class DocumentActionImpl {// selectors resolve correctly when the page is opened from a context// that didn't pre-load the documents list (e.g. task workspace modal).if (sourceType === 'page') {- usePageStore.getState().upsertDocument(document);+ pageActions.upsertDocument(document);}},revalidateOnFocus: true,diff --git a/src/store/page/action.list.test.ts b/src/store/page/action.list.test.tsnew file mode 100644index 00000000000..031bd18bb62--- /dev/null+++ b/src/store/page/action.list.test.ts@@ -0,0 +1,327 @@+import { PAGE_DOCUMENT_FILE_TYPES, PAGE_DOCUMENT_SOURCE_TYPES } from '@lobechat/const';+import type { DocumentItem } from '@lobechat/database/schemas';+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DocumentSourceType, type LobeDocument } from '@/types/document';++import { pageActions } from './action';+import { PAGE_LIST_KEY } from './projection';+import { usePageStore } from './store';++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++vi.mock('@/services/document', () => ({+ documentService: {+ getDocumentById: vi.fn(),+ publishDocumentToWorkspace: vi.fn(),+ queryDocuments: vi.fn(),+ setDocumentVisibility: vi.fn(),+ },+}));++const { documentService } = await import('@/services/document');++const row = (id: string, overrides: Partial<DocumentItem> = {}): DocumentItem =>+ ({+ content: null,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ editorData: null,+ fileType: 'custom/document',+ filename: `${id}.md`,+ id,+ metadata: {},+ parentId: null,+ source: 'document',+ sourceType: DocumentSourceType.API,+ title: id,+ totalCharCount: 0,+ totalLineCount: 0,+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ userId: 'user-1',+ visibility: 'public',+ workspaceId: null,+ ...overrides,+ }) as unknown as DocumentItem;++const lobeDoc = (id: string, overrides: Partial<LobeDocument> = {}): LobeDocument => ({+ content: null,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ editorData: null,+ fileType: 'custom/document',+ filename: id,+ id,+ metadata: {},+ source: 'document',+ sourceType: DocumentSourceType.API,+ title: id,+ totalCharCount: 0,+ totalLineCount: 0,+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ visibility: 'public',+ workspaceId: null,+ ...overrides,+});++/** The replica sync queries the slice registered with the SWR driver. */+const syncCalls = async (name: 'pageDetail' | 'pageList') => {+ const { useClientDataSWR } = await import('@/libs/swr');+ return vi+ .mocked(useClientDataSWR)+ .mock.calls.filter(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,+ )+ .map(([key, fetcher]) => ({+ fetcher: fetcher as () => Promise<unknown>,+ key: key as unknown[],+ }));+};++const list = () => usePageStore.getState().pageListMap[PAGE_LIST_KEY];++beforeEach(() => {+ vi.clearAllMocks();+ pageActions.reset();+});++describe('pageActions β useFetchDocuments', () => {+ it('registers the one list entry and fetches the head page with the page filters', async () => {+ renderHook(() => pageActions.useFetchDocuments());++ const [call] = await syncCalls('pageList');+ expect(call.key[0]).toBe('replica:sync');+ expect(call.key[1]).toBe('pageList');+ expect(call.key[2]).toBe(1);+ // The whole Pages list is one entry.+ expect(call.key[4]).toBe(PAGE_LIST_KEY);+ expect(call.key[5]).toEqual({ pageSize: 20 });++ vi.mocked(documentService.queryDocuments).mockResolvedValue({+ items: [row('docs_a'), row('docs_b')],+ total: 2,+ });++ const page = (await call.fetcher()) as { items: LobeDocument[]; total: number };++ expect(documentService.queryDocuments).toHaveBeenCalledWith({+ current: 0,+ fileTypes: PAGE_DOCUMENT_FILE_TYPES,+ pageSize: 20,+ sourceTypes: PAGE_DOCUMENT_SOURCE_TYPES,+ });+ expect(page.total).toBe(2);+ expect(page.items.map((item) => item.id)).toEqual(['docs_a', 'docs_b']);+ // Rows are converted at the boundary, so the whole store speaks LobeDocument.+ expect(page.items[0].createdAt).toBeInstanceOf(Date);+ // `filename` follows the display title, mirroring the old row converter.+ expect(page.items[0].filename).toBe('docs_a');+ });++ it('drops rows whose file type is not part of the pages list', async () => {+ renderHook(() => pageActions.useFetchDocuments());+ const [call] = await syncCalls('pageList');++ vi.mocked(documentService.queryDocuments).mockResolvedValue({+ items: [row('docs_page'), row('upload_1', { fileType: 'text/plain' })],+ total: 2,+ });++ const page = (await call.fetcher()) as { items: LobeDocument[] };++ expect(page.items.map((item) => item.id)).toEqual(['docs_page']);+ });+});++describe('pageActions β preHydrate', () => {+ it('seeds the list from the persisted row before anything mounts', async () => {+ const { pageListResource } = await import('./projection');+ const get = vi.spyOn(pageListResource.storage!, 'get').mockResolvedValue({+ data: {+ currentPage: 0,+ hasMore: true,+ items: [lobeDoc('docs_a'), lobeDoc('docs_b')],+ pageSize: 20,+ total: 51,+ },+ updatedAt: 1,+ });++ await expect(pageActions.preHydrate()).resolves.toBe(true);++ expect(get).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: `${PAGE_LIST_KEY}?{"pageSize":20}` }),+ );+ expect(list()?.items.map((doc) => doc.id)).toEqual(['docs_a', 'docs_b']);+ expect(usePageStore.getState().pageListReplica.entries[PAGE_LIST_KEY]?.source).toBe('storage');+ get.mockRestore();+ });++ it('leaves the list empty when nothing is persisted', async () => {+ const { pageListResource } = await import('./projection');+ const get = vi.spyOn(pageListResource.storage!, 'get').mockResolvedValue(undefined);++ await expect(pageActions.preHydrate()).resolves.toBe(false);++ expect(list()).toBeUndefined();+ get.mockRestore();+ });+});++describe('pageActions β useFetchPageDetail', () => {+ it('registers a by-id sync keyed by the page id', async () => {+ renderHook(() => pageActions.useFetchPageDetail('docs_a'));++ const [call] = await syncCalls('pageDetail');+ expect(call.key[1]).toBe('pageDetail');+ expect(call.key[4]).toBe('docs_a');+ });++ it('does not register anything without a page id', async () => {+ renderHook(() => pageActions.useFetchPageDetail(undefined));++ expect(await syncCalls('pageDetail')).toHaveLength(0);+ });+});++describe('pageActions β loadMoreDocuments', () => {+ it('pages forward with the next offset and appends the rows', async () => {+ usePageStore.setState({+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: true,+ items: [lobeDoc('docs_a')],+ pageSize: 20,+ total: 2,+ },+ },+ });+ vi.mocked(documentService.queryDocuments).mockResolvedValue({+ items: [row('docs_b')],+ total: 2,+ });++ await pageActions.loadMoreDocuments();++ expect(documentService.queryDocuments).toHaveBeenCalledWith(+ expect.objectContaining({ current: 1, pageSize: 20 }),+ );+ expect(list()?.items.map((doc) => doc.id)).toEqual(['docs_a', 'docs_b']);+ expect(list()?.currentPage).toBe(1);+ expect(list()?.hasMore).toBe(false);+ });++ it('de-duplicates a row the server repeats across pages', async () => {+ usePageStore.setState({+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: true,+ items: [lobeDoc('docs_a')],+ pageSize: 20,+ total: 3,+ },+ },+ });+ vi.mocked(documentService.queryDocuments).mockResolvedValue({+ items: [row('docs_a'), row('docs_b')],+ total: 3,+ });++ await pageActions.loadMoreDocuments();++ expect(list()?.items.map((doc) => doc.id)).toEqual(['docs_a', 'docs_b']);+ });++ it('does not page when the head page is all there is', async () => {+ usePageStore.setState({+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: [lobeDoc('docs_a')],+ pageSize: 20,+ total: 1,+ },+ },+ });++ await pageActions.loadMoreDocuments();++ expect(documentService.queryDocuments).not.toHaveBeenCalled();+ });+});++describe('pageActions β upsertDocument', () => {+ it('mirrors a page document into the by-id projection and the loaded row', () => {+ usePageStore.setState({+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: [lobeDoc('docs_a', { title: 'Old title' })],+ pageSize: 20,+ total: 1,+ },+ },+ });++ pageActions.upsertDocument(row('docs_a', { title: 'New title' }));++ expect(usePageStore.getState().pageDetailMap['docs_a'].title).toBe('New title');+ expect(list()?.items[0].title).toBe('New title');+ });++ it('mirrors a page the list does not hold into the by-id projection only', () => {+ usePageStore.setState({+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });++ pageActions.upsertDocument(row('deep_link'));++ expect(usePageStore.getState().pageDetailMap['deep_link'].id).toBe('deep_link');+ expect(list()?.items).toEqual([]);+ });+});++describe('pageActions β refresh', () => {+ it('revalidates the list entry through the scoped matcher', async () => {+ const { mutate } = await import('@/libs/swr');+ const { cacheScope } = await import('@/libs/replica');++ await pageActions.refreshDocuments();++ const matchers = vi+ .mocked(mutate)+ .mock.calls.map(([arg]) => arg)+ .filter((arg): arg is (key: unknown) => boolean => typeof arg === 'function');+ const scope = cacheScope.get();+ const matches = (key: unknown[]) => matchers.some((matcher) => matcher(key));++ expect(matches(['replica:sync', 'pageList', 1, scope, PAGE_LIST_KEY, { pageSize: 20 }])).toBe(+ true,+ );+ expect(matches(['replica:sync', 'pageList', 1, scope, 'another-entry', {}])).toBe(false);+ });++ it('refreshes the list after publishing a page to the workspace', async () => {+ const { mutate } = await import('@/libs/swr');+ vi.mocked(documentService.publishDocumentToWorkspace).mockResolvedValue({ documentIds: [] });++ const result = await pageActions.publishPageToWorkspace('docs_a');++ expect(result).toEqual({ documentIds: [] });+ expect(mutate).toHaveBeenCalled();+ });+});diff --git a/src/store/page/action.test.ts b/src/store/page/action.test.tsnew file mode 100644index 00000000000..f6481ec7a26--- /dev/null+++ b/src/store/page/action.test.ts@@ -0,0 +1,232 @@+import type { DocumentItem } from '@lobechat/database/schemas';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DocumentSourceType, type LobeDocument } from '@/types/document';++import { pageActions } from './action';+import { PAGE_LIST_KEY, TEMP_PAGE_ID_PREFIX } from './projection';+import { usePageStore } from './store';++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+}));++vi.mock('@/services/document', () => ({+ documentService: {+ createDocument: vi.fn(),+ deleteDocument: vi.fn(),+ getDocumentById: vi.fn(),+ updateDocument: vi.fn(),+ },+}));++const { documentService } = await import('@/services/document');++/** A `documents` row as the server returns it. */+const row = (id: string, overrides: Partial<DocumentItem> = {}): DocumentItem =>+ ({+ content: null,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ editorData: null,+ fileType: 'custom/document',+ filename: `${id}.md`,+ id,+ metadata: {},+ parentId: null,+ source: 'document',+ sourceType: DocumentSourceType.API,+ title: id,+ totalCharCount: 0,+ totalLineCount: 0,+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ userId: 'user-1',+ visibility: 'public',+ workspaceId: null,+ ...overrides,+ }) as unknown as DocumentItem;++const lobeDoc = (id: string, overrides: Partial<LobeDocument> = {}): LobeDocument => ({+ content: null,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ editorData: null,+ fileType: 'custom/document',+ filename: id,+ id,+ metadata: {},+ source: 'document',+ sourceType: DocumentSourceType.API,+ title: id,+ totalCharCount: 0,+ totalLineCount: 0,+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ visibility: 'public',+ workspaceId: null,+ ...overrides,+});++const items = () => usePageStore.getState().pageListMap[PAGE_LIST_KEY]?.items ?? [];++/** Seed a loaded list (no replica bookkeeping), as a fetched head page leaves it. */+const seedList = (docs: LobeDocument[]) => {+ usePageStore.setState({+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: docs,+ pageSize: 20,+ total: docs.length,+ },+ },+ });+};++beforeEach(() => {+ vi.clearAllMocks();+ pageActions.reset();+});++describe('pageActions β createNewPage', () => {+ it('shows an optimistic row, then swaps in the server row and navigates to it', async () => {+ const navigate = vi.fn();+ usePageStore.setState({ navigate });+ vi.mocked(documentService.createDocument).mockResolvedValue(+ row('docnew1', { title: 'My page', visibility: 'private' }),+ );++ const id = await pageActions.createNewPage('My page', 'private');++ expect(id).toBe('docnew1');+ // The optimistic row (client-minted id) is gone, the real row is in place.+ expect(items().map((doc) => doc.id)).toEqual(['docnew1']);+ expect(items()[0].visibility).toBe('private');+ expect(items()[0].title).toBe('My page');+ expect(usePageStore.getState().selectedPageId).toBe('docnew1');+ expect(usePageStore.getState().isCreatingNew).toBe(false);+ expect(navigate).toHaveBeenCalledWith('/page/docnew1');+ });++ it('shows the optimistic row while the request is in flight', async () => {+ let resolve!: (value: DocumentItem) => void;+ vi.mocked(documentService.createDocument).mockReturnValue(+ new Promise<DocumentItem>((r) => {+ resolve = r;+ }),+ );++ const pending = pageActions.createNewPage('Pending page');+ // Yield so the optimistic dispatch has run.+ await Promise.resolve();++ expect(items()).toHaveLength(1);+ expect(items()[0].id.startsWith(TEMP_PAGE_ID_PREFIX)).toBe(true);+ expect(items()[0].title).toBe('Pending page');+ expect(usePageStore.getState().isCreatingNew).toBe(true);++ resolve(row('docreal1'));+ await pending;++ expect(items().map((doc) => doc.id)).toEqual(['docreal1']);+ });++ it('drops the optimistic row and rethrows when creation fails', async () => {+ const navigate = vi.fn();+ usePageStore.setState({ navigate });+ vi.mocked(documentService.createDocument).mockRejectedValue(new Error('boom'));++ await expect(pageActions.createNewPage('My page')).rejects.toThrow('boom');++ expect(items()).toEqual([]);+ expect(usePageStore.getState().selectedPageId).toBeNull();+ expect(usePageStore.getState().isCreatingNew).toBe(false);+ expect(navigate).toHaveBeenCalledWith('/page');+ });+});++describe('pageActions β removePage', () => {+ it('drops the row optimistically and restores it when the delete fails', async () => {+ seedList([lobeDoc('docs_a'), lobeDoc('docs_b')]);+ vi.mocked(documentService.deleteDocument).mockRejectedValue(new Error('nope'));++ await expect(pageActions.removePage('docs_a')).rejects.toThrow('nope');++ expect(items().map((doc) => doc.id)).toEqual(['docs_a', 'docs_b']);+ });++ it('keeps the row removed once the server confirms the delete', async () => {+ seedList([lobeDoc('docs_a'), lobeDoc('docs_b')]);+ vi.mocked(documentService.deleteDocument).mockResolvedValue(undefined);++ await pageActions.removePage('docs_a');++ expect(documentService.deleteDocument).toHaveBeenCalledWith('docs_a');+ expect(items().map((doc) => doc.id)).toEqual(['docs_b']);+ });++ it('clears the selection and navigates away when the selected page is deleted', async () => {+ const navigate = vi.fn();+ seedList([lobeDoc('docs_a')]);+ usePageStore.setState({ navigate, selectedPageId: 'docs_a' });+ vi.mocked(documentService.deleteDocument).mockResolvedValue(undefined);++ await pageActions.removePage('docs_a');++ expect(usePageStore.getState().selectedPageId).toBeNull();+ expect(navigate).toHaveBeenCalledWith('/page');+ });+});++describe('pageActions β updatePageOptimistically', () => {+ it('patches the title and emoji across the list and the by-id copy', async () => {+ seedList([lobeDoc('docs_a', { title: 'Old' })]);+ usePageStore.setState({ pageDetailMap: { docs_a: lobeDoc('docs_a', { title: 'Old' }) } });+ vi.mocked(documentService.updateDocument).mockResolvedValue({} as never);++ await pageActions.updatePageOptimistically('docs_a', {+ emoji: 'π',+ title: 'Renamed',+ });++ expect(usePageStore.getState().pageListMap[PAGE_LIST_KEY]?.items[0].title).toBe('Renamed');+ expect(usePageStore.getState().pageListMap[PAGE_LIST_KEY]?.items[0].metadata.emoji).toBe('π');+ expect(usePageStore.getState().pageDetailMap['docs_a'].title).toBe('Renamed');+ expect(documentService.updateDocument).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'docs_a', title: 'Renamed' }),+ );+ });++ it('warns and leaves the store untouched for a page that is not loaded', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const before = usePageStore.getState().pageListMap;++ await pageActions.updatePageOptimistically('missing', { title: 'Renamed' });++ expect(documentService.updateDocument).not.toHaveBeenCalled();+ expect(usePageStore.getState().pageListMap).toBe(before);+ warn.mockRestore();+ });+});++describe('pageActions β duplicatePage', () => {+ it('inserts the copy at the head of the list', async () => {+ seedList([lobeDoc('docs_a')]);+ vi.mocked(documentService.getDocumentById).mockResolvedValue(row('docs_a'));+ vi.mocked(documentService.createDocument).mockResolvedValue(row('docs_copy'));++ const newPage = await pageActions.duplicatePage('docs_a');++ expect(newPage.id).toBe('docs_copy');+ expect(items().map((doc) => doc.id)).toEqual(['docs_copy', 'docs_a']);+ });+});++describe('pageActions β renamePage', () => {+ it('clears the in-place rename marker even when the title did not exist', async () => {+ usePageStore.setState({ renamingPageId: 'docs_a' });++ await pageActions.renamePage('docs_a', 'Renamed');++ expect(usePageStore.getState().renamingPageId).toBeNull();+ });+});diff --git a/src/store/page/action.ts b/src/store/page/action.tsnew file mode 100644index 00000000000..cdb32af106e--- /dev/null+++ b/src/store/page/action.ts@@ -0,0 +1,326 @@+import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import type { DocumentItem } from '@lobechat/database/schemas';++import { type ReplicaSyncResult } from '@/libs/replica';+import { documentService } from '@/services/document';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';+import type { StoreSetter } from '@/store/types';+import { DocumentSourceType, type LobeDocument } from '@/types/document';+import { standardizeIdentifier } from '@/utils/identifier';+import { setNamespace } from '@/utils/storeDebug';++import { initialState, type PageState } from './initialState';+import { currentPageSize, PagePrivateAction } from './privateAction';+import { documentItemToLobeDocument, PAGE_LIST_KEY, TEMP_PAGE_ID_PREFIX } from './projection';+import { listSelectors } from './slices/list/selectors';+import { usePageStore } from './store';++const n = setNamespace('page');++export interface PageUpdateParams {+ emoji?: string;+ title?: string;+}++type Setter = StoreSetter<PageState>;++const withEmoji = (metadata: LobeDocument['metadata'], emoji: string | undefined) =>+ Object.fromEntries(+ Object.entries({ ...metadata, ...(emoji !== undefined ? { emoji } : {}) }).filter(+ ([, v]) => v !== undefined,+ ),+ );++export class PageActionImpl {+ readonly #get: () => PageState;+ readonly #private: PagePrivateAction;+ readonly #set: Setter;++ constructor(set: Setter, get: () => PageState, privateAction: PagePrivateAction) {+ this.#set = set;+ this.#get = get;+ this.#private = privateAction;+ }++ useFetchDocuments = (): ReplicaSyncResult => {+ // Subscribed, so changing the page size re-keys the list query.+ const pageSize = useGlobalStore(systemStatusSelectors.pagePageSize);+ return this.#private.list.useSync({ pageSize });+ };++ useFetchPageDetail = (pageId?: string | null): ReplicaSyncResult =>+ this.#private.detail.useSync(pageId || null);++ preHydrate = (): Promise<boolean> => this.#private.preHydrateList();++ loadMoreDocuments = async (): Promise<void> => {+ await this.#private.list.loadMore(PAGE_LIST_KEY, { pageSize: currentPageSize() });+ };++ refreshDocuments = async (): Promise<void> => {+ await this.#private.revalidateList();+ };++ publishPageToWorkspace = async (pageId: string): Promise<{ documentIds: string[] }> => {+ const result = await documentService.publishDocumentToWorkspace(pageId);+ await this.refreshDocuments();+ return result;+ };++ setPageVisibility = async (+ pageId: string,+ visibility: 'private' | 'public',+ ): Promise<{ documentIds: string[] }> => {+ const result = await documentService.setDocumentVisibility(pageId, visibility);+ await this.refreshDocuments();+ return result;+ };++ upsertDocument = (document: DocumentItem): void => {+ const lobeDoc = documentItemToLobeDocument(document);+ this.#private.detail.update(lobeDoc.id, () => lobeDoc);+ if (this.#get().pageListMap[PAGE_LIST_KEY]?.items.some((doc) => doc.id === lobeDoc.id)) {+ this.#private.list.updateEntity(lobeDoc.id, () => lobeDoc);+ }+ };++ setSearchKeywords = (keywords: string): void => {+ this.#set({ searchKeywords: keywords }, false, n('setSearchKeywords'));+ };++ setShowOnlyPagesNotInLibrary = (show: boolean): void => {+ this.#set({ showOnlyPagesNotInLibrary: show }, false, n('setShowOnlyPagesNotInLibrary'));+ };++ closeAllPagesDrawer = (): void => {+ this.#set({ allPagesDrawerOpen: false }, false, n('closeAllPagesDrawer'));+ };++ openAllPagesDrawer = (): void => {+ this.#set({ allPagesDrawerOpen: true }, false, n('openAllPagesDrawer'));+ };++ selectPage = (pageId: string): void => {+ if (this.#get().selectedPageId === pageId) return;++ this.#set({ isCreatingNew: false, selectedPageId: pageId }, false, n('selectPage'));+ this.navigateToPage(pageId);+ };++ setRenamingPageId = (pageId: string | null): void => {+ this.#set({ renamingPageId: pageId }, false, n('setRenamingPageId'));+ };++ setSelectedPageId = (pageId: string | null, shouldNavigate: boolean = true): void => {+ this.#set({ selectedPageId: pageId }, false, n('setSelectedPageId'));+ if (shouldNavigate) this.navigateToPage(pageId);+ };++ navigateToPage = (pageId: string | null): void => {+ this.#get().navigate?.(pageId ? `/page/${standardizeIdentifier(pageId)}` : '/page');+ };++ createNewPage = async (title: string, visibility?: 'private' | 'public'): Promise<string> => {+ // The optimistic row lands in the requested bucket so it shows under the+ // accordion the user clicked "+" from before the server responds.+ const tempPageId = this.createOptimisticPage(title, visibility);+ this.#set({ isCreatingNew: true, selectedPageId: tempPageId }, false, n('createNewPage/start'));++ try {+ const realPage = documentItemToLobeDocument(+ await this.createPage({ content: '', title, visibility }),+ );++ this.#private.replaceListRow(tempPageId, realPage);+ this.#set(+ { isCreatingNew: false, selectedPageId: realPage.id },+ false,+ n('createNewPage/success'),+ );+ this.navigateToPage(realPage.id);++ return realPage.id;+ } catch (error) {+ console.error('Failed to create page:', error);+ this.removeTempPage(tempPageId);+ this.#set({ isCreatingNew: false, selectedPageId: null }, false, n('createNewPage/error'));+ this.navigateToPage(null);++ throw error;+ }+ };++ createOptimisticPage = (+ title: string = 'Untitled',+ visibility?: 'private' | 'public',+ ): string => {+ const tempId = `${TEMP_PAGE_ID_PREFIX}${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;+ const now = new Date();++ this.#private.insertListRow({+ content: null,+ createdAt: now,+ editorData: null,+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,+ filename: title,+ id: tempId,+ metadata: {},+ source: 'document',+ sourceType: DocumentSourceType.EDITOR,+ title,+ totalCharCount: 0,+ totalLineCount: 0,+ updatedAt: now,+ visibility: visibility ?? null,+ });++ return tempId;+ };++ createPage = async ({+ title,+ content = '',+ knowledgeBaseId,+ parentId,+ visibility,+ }: {+ content?: string;+ knowledgeBaseId?: string;+ parentId?: string;+ title: string;+ visibility?: 'private' | 'public';+ }): Promise<DocumentItem> =>+ documentService.createDocument({+ content,+ editorData: '{}',+ fileType: CUSTOM_DOCUMENT_FILE_TYPE,+ knowledgeBaseId,+ metadata: { createdAt: Date.now() },+ parentId,+ title,+ visibility,+ });++ deletePage = async (pageId: string): Promise<void> => {+ if (this.#get().selectedPageId !== pageId) return;++ this.#set({ isCreatingNew: false, selectedPageId: null }, false, n('deletePage'));+ this.navigateToPage(null);+ };++ duplicatePage = async (pageId: string): Promise<DocumentItem> => {+ const sourcePage = await documentService.getDocumentById(pageId);++ if (!sourcePage) {+ throw new Error(`Page with ID ${pageId} not found`);+ }++ const newPage = await documentService.createDocument({+ content: sourcePage.content || '',+ editorData: sourcePage.editorData+ ? typeof sourcePage.editorData === 'string'+ ? sourcePage.editorData+ : JSON.stringify(sourcePage.editorData)+ : '{}',+ fileType: sourcePage.fileType,+ metadata: {+ ...sourcePage.metadata,+ createdAt: Date.now(),+ duplicatedFrom: pageId,+ },+ title: `${sourcePage.title} (Copy)`,+ });++ this.#private.insertListRow(documentItemToLobeDocument(newPage));++ return newPage;+ };++ removePage = async (pageId: string): Promise<void> => {+ const { selectedPageId } = this.#get();++ // Clear the selection before the row disappears so the editor navigates+ // away from the page it is about to lose.+ if (selectedPageId === pageId) {+ this.#set({ selectedPageId: null }, false, n('removePage/clearSelection'));+ this.navigateToPage(null);+ }++ try {+ await this.#private.entity.optimistic(pageId, 'remove', () =>+ documentService.deleteDocument(pageId),+ );+ } catch (error) {+ console.error('Failed to delete page:', error);+ if (selectedPageId === pageId) {+ this.#set({ selectedPageId: pageId }, false, n('removePage/restoreSelection'));+ this.navigateToPage(pageId);+ }+ throw error;+ }+ };++ removeTempPage = (tempId: string): void => {+ this.#private.entity.remove(tempId);+ };++ replaceTempPageWithReal = (tempId: string, realPage: LobeDocument): void => {+ this.#private.replaceListRow(tempId, realPage);+ };++ renamePage = async (pageId: string, title: string, emoji?: string): Promise<void> => {+ try {+ await this.updatePageOptimistically(pageId, { emoji, title });+ } catch (error) {+ console.error('Failed to rename page:', error);+ } finally {+ this.#set({ renamingPageId: null }, false, n('renamePage'));+ }+ };++ updatePageOptimistically = async (pageId: string, updates: PageUpdateParams): Promise<void> => {+ const existingPage = listSelectors.getDocumentById(pageId)(this.#get());++ if (!existingPage) {+ console.warn('[updatePageOptimistically] Page not found:', pageId);+ return;+ }++ const apply = (doc: LobeDocument): LobeDocument => ({+ ...doc,+ metadata: withEmoji(doc.metadata, updates.emoji),+ title: updates.title ?? doc.title,+ updatedAt: new Date(),+ });+ const updatedPage = apply(existingPage);++ try {+ await this.#private.entity.optimistic(pageId, apply, () =>+ documentService.updateDocument({+ id: pageId,+ metadata: updatedPage.metadata || {},+ parentId: updatedPage.parentId || undefined,+ title: updatedPage.title || updatedPage.filename,+ }),+ );++ // Land the server's ordering and derived fields.+ await this.#private.revalidateList();+ } catch (error) {+ console.error('[updatePageOptimistically] Failed to sync to DB:', error);+ }+ };++ reset = (): void => {+ this.#set(initialState, false, n('reset'));+ };+}++const { getState, setState } = usePageStore;++export const pageActions = new PageActionImpl(+ setState,+ getState,+ new PagePrivateAction(setState, getState),+);diff --git a/src/store/page/index.ts b/src/store/page/index.tsindex 9e62bbbe3a4..858488a9bdf 100644--- a/src/store/page/index.ts+++ b/src/store/page/index.ts@@ -1,2 +1,4 @@+export { pageActions, type PageUpdateParams } from './action';+export { type PageState } from './initialState';export * from './selectors';-export { getPageStoreState, type PageStore, usePageStore } from './store';+export { usePageStore } from './store';diff --git a/src/store/page/initialState.ts b/src/store/page/initialState.tsindex 58110de5d72..7c45e123f15 100644--- a/src/store/page/initialState.ts+++ b/src/store/page/initialState.ts@@ -1,92 +1,38 @@import { type NavigateFunction } from 'react-router';-import { type LobeDocument } from '@/types/document';--export interface PageQueryFilter {- fileTypes?: string[];- sourceTypes?: string[];-}--export interface PageState {- // ===== Selection & Navigation =====- /**- * Whether all pages drawer is open- */- allPagesDrawerOpen: boolean;- // ===== List Management =====- /**- * Current page number (0-based) for pagination- */- currentPage: number;- /**- * Server documents fetched from document service- * undefined means not yet loaded (loading state)- */- documents?: LobeDocument[];- /**- * Total count of documents- */- documentsTotal: number;- /**- * Whether there are more documents to load- */- hasMoreDocuments: boolean;- // ===== UI State =====- /**- * Whether currently creating a new page- */- isCreatingNew: boolean;- /**- * Loading state for pagination (load more)- */- isLoadingMoreDocuments: boolean;-+import { initialPageCrudState, type PageCrudSliceState } from './slices/crud/initialState';+import { initialPageListState, type PageListSliceState } from './slices/list/initialState';+import {+ initialPageSelectionState,+ type PageSelectionSliceState,+} from './slices/selection/initialState';++/**+ * UI-only page state that no replica owns: the search box, the "not in a+ * library" filter and the router navigate function the actions call.+ */+export interface PageUiState {navigate?: NavigateFunction;- /**- * Filters used in the last query- */- queryFilter?: PageQueryFilter;-- /**- * ID of the page being renamed (null if none)- */- renamingPageId: string | null;- /**- * Search keywords for filtering pages- */+ /** Search keywords for filtering pages in the sidebar. */searchKeywords: string;- /**- * Currently selected page ID- */- selectedPageId: string | null;- /**- * Filter to show only pages not in any library- */+ /** Filter to show only pages not in any library. */showOnlyPagesNotInLibrary: boolean;}-export const initialState: PageState = {- // Selection & Navigation- allPagesDrawerOpen: false,-- // List Management- currentPage: 0,+/**+ * Page domain state. The list / detail rows and the selection live in their+ * slices' state so each slice owns (and the replica engine writes) its own+ * fields; this composes them into the store's single state shape.+ */+export type PageState = PageCrudSliceState &+ PageListSliceState &+ PageSelectionSliceState &+ PageUiState;- documents: undefined,-- documentsTotal: 0,-- hasMoreDocuments: false,-- // UI State- isCreatingNew: false,-- isLoadingMoreDocuments: false,-- queryFilter: undefined,-- renamingPageId: null,+export const initialState: PageState = {+ ...initialPageListState,+ ...initialPageCrudState,+ ...initialPageSelectionState,searchKeywords: '',- selectedPageId: null,showOnlyPagesNotInLibrary: false,};diff --git a/src/store/page/privateAction.ts b/src/store/page/privateAction.tsnew file mode 100644index 00000000000..35b37e213b1--- /dev/null+++ b/src/store/page/privateAction.ts@@ -0,0 +1,97 @@+import { createReplicaSlice, linkReplicaEntity, recordLens, singleEntity } from '@/libs/replica';+import { getCacheScope } from '@/libs/swr/useCacheScope';+import { documentService } from '@/services/document';+import { useGlobalStore } from '@/store/global';+import type { StoreSetter } from '@/store/types';+import { type LobeDocument } from '@/types/document';++import { type PageState } from './initialState';+import {+ documentItemToLobeDocument,+ isTempPageId,+ PAGE_LIST_KEY,+ pageDetailResource,+ pageListResource,+ type PageListValue,+} from './projection';++const DEFAULT_PAGE_SIZE = 20;++export const currentPageSize = (): number =>+ useGlobalStore.getState().status.pagePageSize || DEFAULT_PAGE_SIZE;++type Setter = StoreSetter<PageState>;++export class PagePrivateAction {+ readonly #get: () => PageState;+ readonly detail;+ readonly entity;+ readonly list;++ constructor(set: Setter, get: () => PageState) {+ this.#get = get;++ this.list = createReplicaSlice(pageListResource, {+ actionPrefix: 'pageList',+ get,+ // A page the user just created shows before its server row exists and+ // survives a head refresh until its temp id is swapped for the real one.+ isClientOnly: (doc) => isTempPageId(doc.id),+ set,+ stateKey: 'pageListReplica',+ view: recordLens<PageState, PageListValue>('pageListMap'),+ });+ this.detail = createReplicaSlice(pageDetailResource, {+ actionPrefix: 'pageDetail',+ entity: singleEntity<LobeDocument>((doc) => doc.id),+ fetcher: async (pageId) => {+ const document = await documentService.getDocumentById(pageId);+ return document ? documentItemToLobeDocument(document) : undefined;+ },+ get,+ // A miss keeps whatever is cached β the list may still hold the row.+ merge: (incoming) => incoming,+ set,+ stateKey: 'pageDetailReplica',+ view: recordLens<PageState, LobeDocument>('pageDetailMap'),+ });+ this.entity = linkReplicaEntity<LobeDocument>([this.list, this.detail]);+ }++ insertListRow = (doc: LobeDocument): void => {+ if (this.#get().pageListMap[PAGE_LIST_KEY]) {+ this.list.insertHead(PAGE_LIST_KEY, [doc]);+ return;+ }++ // No list loaded yet (mobile, or before the first page arrives): seed a+ // single-row head page so the new page renders immediately. The next sync+ // replaces the head page with the server's for every other row.+ this.list.update(+ PAGE_LIST_KEY,+ () => ({+ currentPage: 0,+ hasMore: false,+ items: [doc],+ pageSize: currentPageSize(),+ total: 1,+ }),+ { persist: false },+ );+ };++ replaceListRow = (tempId: string, doc: LobeDocument): void => {+ this.list.update(PAGE_LIST_KEY, (data) =>+ data ? { ...data, items: data.items.map((item) => (item.id === tempId ? doc : item)) } : data,+ );+ };++ revalidateList = (): Promise<unknown> => this.list.revalidate(PAGE_LIST_KEY);++ preHydrateList = (): Promise<boolean> => {+ const scope = getCacheScope();+ // The slot may still hold the previous identity's rows; drop them before seeding.+ this.list.ensureScope(scope);+ return this.list.hydrate({ pageSize: currentPageSize() }, scope);+ };+}diff --git a/src/store/page/projection.ts b/src/store/page/projection.tsnew file mode 100644index 00000000000..6294bdeeba6--- /dev/null+++ b/src/store/page/projection.ts@@ -0,0 +1,137 @@+import { PAGE_DOCUMENT_FILE_TYPES, PAGE_DOCUMENT_SOURCE_TYPES } from '@lobechat/const';+import type { DocumentItem } from '@lobechat/database/schemas';++import { definePagedReplica, defineReplica, type ReplicaPagedData } from '@/libs/replica';+import { documentService } from '@/services/document';+import { DocumentSourceType, type LobeDocument } from '@/types/document';++/**+ * The Pages sidebar renders one global list, so its paged replica keeps a single+ * entry and every selector reads `pageListMap[PAGE_LIST_KEY]`. A page opened+ * outside the loaded list (deep link, mobile, task modal) lives in+ * `pageDetailMap[id]` β both locations are read through `pageSelectors`.+ */+export const PAGE_LIST_KEY = 'all';++/** Client-minted id prefix of a page whose server row does not exist yet. */+export const TEMP_PAGE_ID_PREFIX = 'temp-page-';++/** Whether `id` is an optimistic page row that has no server row yet. */+export const isTempPageId = (id: string): boolean => id.startsWith(TEMP_PAGE_ID_PREFIX);++/**+ * The Pages list is one query. The page size is its only identity beyond the+ * entry key, so changing it resets the loaded depth instead of merging pages+ * fetched under another size.+ */+export interface PageListParams {+ pageSize: number;+}++/** `pageListMap[PAGE_LIST_KEY]` β the paged view every page selector reads. */+export type PageListValue = ReplicaPagedData<LobeDocument, number>;++// EDITOR is a client-only stamp on in-memory drafts; DB rows never carry it.+const ALLOWED_PAGE_SOURCE_TYPES: Set<string> = new Set([+ DocumentSourceType.EDITOR,+ ...PAGE_DOCUMENT_SOURCE_TYPES,+]);+const ALLOWED_PAGE_FILE_TYPES: Set<string> = new Set(PAGE_DOCUMENT_FILE_TYPES);++/**+ * Whether a document row belongs in the Pages list. Mirrors the guard the old+ * `getPageDocuments()` / `loadMoreDocuments()` pair applied before the rows+ * reached the store.+ */+export const isAllowedPageDocument = (doc: { fileType: string; sourceType: string }): boolean =>+ ALLOWED_PAGE_SOURCE_TYPES.has(doc.sourceType) && ALLOWED_PAGE_FILE_TYPES.has(doc.fileType);++/**+ * DB row β the `LobeDocument` selectors and the editor read.+ *+ * The server's own `sourceType` is kept (created pages come back as `api`,+ * uploaded PDFs as `file` β the sidebar's bucket selectors still drop the+ * latter), and `parentId` / `visibility` / `workspaceId` are carried through+ * because the rename and bucket flows read them back.+ */+export const documentItemToLobeDocument = (document: DocumentItem): LobeDocument => ({+ content: document.content || null,+ createdAt: document.createdAt ? new Date(document.createdAt) : new Date(),+ editorData:+ typeof document.editorData === 'string'+ ? JSON.parse(document.editorData)+ : document.editorData || null,+ fileType: document.fileType,+ filename: document.title || document.filename || 'Untitled',+ id: document.id,+ metadata: document.metadata || {},+ parentId: document.parentId ?? null,+ source: 'document',+ sourceType: document.sourceType as DocumentSourceType,+ title: document.title || '',+ totalCharCount: document.totalCharCount ?? document.content?.length ?? 0,+ totalLineCount: document.totalLineCount ?? 0,+ updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),+ userId: document.userId,+ visibility: document.visibility ?? null,+ workspaceId: document.workspaceId ?? null,+});++/**+ * Offset paging over `document.queryDocuments` (`current` is the page index,+ * the server orders by `updatedAt` desc and reports the real `total`). The+ * sidebar pages forward β "load more" appends older rows below the head page β+ * and only the head page survives a reload.+ */+const pagePaging = {+ direction: 'forward',+ getId: (doc: LobeDocument) => doc.id,+ mode: 'offset',+ persist: { pages: 1 },+} as const;++/**+ * The one page list of the active scope. Rows are converted at the boundary so+ * the whole store (selectors, optimistic writes, the editor) speaks+ * `LobeDocument`.+ */+export const pageListResource = definePagedReplica<+ PageListParams,+ LobeDocument,+ number,+ PageListValue+>({+ fetchPage: async (params, cursor) => {+ const result = await documentService.queryDocuments({+ current: cursor ?? 0,+ fileTypes: PAGE_DOCUMENT_FILE_TYPES,+ pageSize: params.pageSize,+ sourceTypes: PAGE_DOCUMENT_SOURCE_TYPES,+ });++ return {+ items: result.items.filter(isAllowedPageDocument).map(documentItemToLobeDocument),+ total: result.total,+ };+ },+ key: () => PAGE_LIST_KEY,+ name: 'pageList',+ paging: pagePaging,+ query: ({ pageSize }) => ({ pageSize }),+ storage: 'indexedDB',+ version: 1,+});++/**+ * One page by id, for pages that are not in the loaded list (mobile mounts no+ * sidebar, a workspace modal deeplinks a page). `pageSelectors.getDocumentById`+ * reads it as a fallback behind the list. The fetcher (owned by the store+ * slice) answers with `undefined` for a page the server no longer has, and the+ * merge then keeps whatever is cached.+ */+export const pageDetailResource = defineReplica<string, LobeDocument, LobeDocument | undefined>({+ key: (pageId) => pageId,+ name: 'pageDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/page/slices/crud/action.test.ts b/src/store/page/slices/crud/action.test.tsdeleted file mode 100644index d099a144e46..00000000000--- a/src/store/page/slices/crud/action.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import type * as SwrModule from '@/libs/swr';-import { useClientDataSWRWithSync } from '@/libs/swr';-import { DocumentSourceType, type LobeDocument } from '@/types/document';--import { usePageStore } from '../../store';--vi.mock('@/libs/swr', async (importOriginal) => {- const actual = await importOriginal<typeof SwrModule>();- return {- ...actual,- useClientDataSWRWithSync: vi.fn(() => ({ data: undefined, isValidating: false })),- };-});--const doc = (id: string, title: string): LobeDocument => ({- content: null,- createdAt: new Date('2026-01-01T00:00:00.000Z'),- editorData: null,- fileType: 'custom/document',- filename: title,- id,- metadata: {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title,- totalCharCount: 0,- totalLineCount: 0,- updatedAt: new Date('2026-01-01T00:00:00.000Z'),-});--const captureOnData = (pageId: string) => {- renderHook(() => usePageStore.getState().useFetchPageDetail(pageId));- const swrCall = vi.mocked(useClientDataSWRWithSync).mock.calls.at(-1);- return swrCall?.[2]?.onData as (data: LobeDocument | null) => void;-};--describe('useFetchPageDetail onData', () => {- beforeEach(() => {- vi.mocked(useClientDataSWRWithSync).mockClear();- usePageStore.setState({ documents: undefined });- });-- it('adds a deep-linked page that is not in the loaded list', () => {- usePageStore.setState({ documents: [doc('docs_other', 'Other')] });-- captureOnData('docs_target')(doc('docs_target', 'Target'));-- expect(usePageStore.getState().documents?.map((d) => d.id)).toEqual([- 'docs_target',- 'docs_other',- ]);- });-- it('adds the page when no list has been fetched (mobile)', () => {- captureOnData('docs_target')(doc('docs_target', 'Target'));-- expect(usePageStore.getState().documents).toEqual([doc('docs_target', 'Target')]);- });-- it('updates the page in place when it is already in the list', () => {- usePageStore.setState({ documents: [doc('docs_target', 'Old'), doc('docs_other', 'Other')] });-- captureOnData('docs_target')(doc('docs_target', 'New'));-- const { documents } = usePageStore.getState();- expect(documents).toHaveLength(2);- expect(documents?.find((d) => d.id === 'docs_target')?.title).toBe('New');- });-});diff --git a/src/store/page/slices/crud/action.ts b/src/store/page/slices/crud/action.tsdeleted file mode 100644index 0ed26ffc1a2..00000000000--- a/src/store/page/slices/crud/action.ts+++ /dev/null@@ -1,432 +0,0 @@-import { CUSTOM_DOCUMENT_FILE_TYPE } from '@lobechat/const';-import { type SWRResponse } from 'swr';--import { useClientDataSWRWithSync } from '@/libs/swr';-import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';-import { type StoreSetter } from '@/store/types';-import { type LobeDocument } from '@/types/document';-import { DocumentSourceType } from '@/types/document';-import { standardizeIdentifier } from '@/utils/identifier';-import { setNamespace } from '@/utils/storeDebug';--import { type PageStore } from '../../store';--const n = setNamespace('page/crud');--const EDITOR_PAGE_FILE_TYPE = CUSTOM_DOCUMENT_FILE_TYPE;--/**- * Page update parameters - flattened for easier use- */-export interface PageUpdateParams {- emoji?: string;- title?: string;-}--type Setter = StoreSetter<PageStore>;-export const createCrudSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>- new CrudActionImpl(set, get, _api);--export class CrudActionImpl {- readonly #get: () => PageStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => PageStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- createNewPage = async (title: string, visibility?: 'private' | 'public'): Promise<string> => {- const { createOptimisticPage, createPage, replaceTempPageWithReal } = this.#get();-- // Create optimistic page immediately in the requested bucket so the item- // shows up under the correct accordion before the server responds. The- // real row will replace it and confirm the visibility a moment later.- const tempPageId = createOptimisticPage(title, visibility);- this.#set({ isCreatingNew: true, selectedPageId: tempPageId }, false, n('createNewPage/start'));-- try {- // Create real page- const newPage = await createPage({ content: '', title, visibility });-- // Convert to LobeDocument. `visibility` and `workspaceId` MUST come from- // the server response so the sidebar bucketing selector keeps the row in- // the same accordion the user clicked "+" from β omitting them makes the- // row silently fall back to the workspace bucket.- const realPage: LobeDocument = {- content: newPage.content || '',- createdAt: newPage.createdAt ? new Date(newPage.createdAt) : new Date(),- editorData:- typeof newPage.editorData === 'string'- ? JSON.parse(newPage.editorData)- : newPage.editorData || null,- fileType: CUSTOM_DOCUMENT_FILE_TYPE,- filename: newPage.title || title,- id: newPage.id,- metadata: newPage.metadata || {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title: newPage.title || title,- totalCharCount: newPage.content?.length || 0,- totalLineCount: 0,- updatedAt: newPage.updatedAt ? new Date(newPage.updatedAt) : new Date(),- userId: newPage.userId,- visibility: newPage.visibility ?? visibility ?? null,- workspaceId: newPage.workspaceId ?? null,- };-- // Replace optimistic with real- replaceTempPageWithReal(tempPageId, realPage);- this.#set(- { isCreatingNew: false, selectedPageId: newPage.id },- false,- n('createNewPage/success'),- );-- // Navigate to the new page- this.#get().navigateToPage(newPage.id);-- return newPage.id;- } catch (error) {- console.error('Failed to create page:', error);- this.#get().removeTempPage(tempPageId);- this.#set({ isCreatingNew: false, selectedPageId: null }, false, n('createNewPage/error'));- this.#get().navigate?.('/page');-- throw error;- }- };-- createOptimisticPage = (- title: string = 'Untitled',- visibility?: 'private' | 'public',- ): string => {- // Generate temporary ID with prefix to identify optimistic pages- const tempId = `temp-page-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;- const now = new Date();-- const newPage: LobeDocument = {- content: null,- createdAt: now,- editorData: null,- fileType: EDITOR_PAGE_FILE_TYPE,- filename: title,- id: tempId,- metadata: {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title,- totalCharCount: 0,- totalLineCount: 0,- updatedAt: now,- visibility: visibility ?? null,- };-- // Add to documents array via internal dispatch- this.#get().internal_dispatchDocuments({ document: newPage, type: 'addDocument' });-- return tempId;- };-- createPage = async ({- title,- content = '',- knowledgeBaseId,- parentId,- visibility,- }: {- content?: string;- knowledgeBaseId?: string;- parentId?: string;- title: string;- visibility?: 'private' | 'public';- }): Promise<{ [key: string]: any; id: string }> => {- const now = Date.now();-- const newPage = await documentService.createDocument({- content,- editorData: '{}',- fileType: EDITOR_PAGE_FILE_TYPE,- knowledgeBaseId,- metadata: {- createdAt: now,- },- parentId,- title,- visibility,- });-- return newPage;- };-- deletePage = async (pageId: string): Promise<void> => {- const { selectedPageId } = this.#get();-- if (selectedPageId === pageId) {- this.#set({ isCreatingNew: false, selectedPageId: null }, false, n('deletePage'));- this.#get().navigateToPage(null);- }- };-- duplicatePage = async (pageId: string): Promise<{ [key: string]: any; id: string }> => {- // Fetch the source page- const sourcePage = await documentService.getDocumentById(pageId);-- if (!sourcePage) {- throw new Error(`Page with ID ${pageId} not found`);- }-- // Create a new page with copied properties- const newPage = await documentService.createDocument({- content: sourcePage.content || '',- editorData: sourcePage.editorData- ? typeof sourcePage.editorData === 'string'- ? sourcePage.editorData- : JSON.stringify(sourcePage.editorData)- : '{}',- fileType: sourcePage.fileType,- metadata: {- ...sourcePage.metadata,- createdAt: Date.now(),- duplicatedFrom: pageId,- },- title: `${sourcePage.title} (Copy)`,- });-- // Add the new page to documents array via internal dispatch- const editorPage: LobeDocument = {- content: newPage.content || null,- createdAt: newPage.createdAt ? new Date(newPage.createdAt) : new Date(),- editorData:- typeof newPage.editorData === 'string'- ? JSON.parse(newPage.editorData)- : newPage.editorData || null,- fileType: newPage.fileType,- filename: newPage.title || newPage.filename || '',- id: newPage.id,- metadata: newPage.metadata || {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title: newPage.title || '',- totalCharCount: newPage.content?.length || 0,- totalLineCount: 0,- updatedAt: newPage.updatedAt ? new Date(newPage.updatedAt) : new Date(),- userId: newPage.userId,- // Keep the sidebar bucket in sync β duplicating a private page must land- // in "Private", not silently in "Workspace".- visibility: newPage.visibility ?? null,- workspaceId: newPage.workspaceId ?? null,- };-- this.#get().internal_dispatchDocuments({ document: editorPage, type: 'addDocument' });-- return newPage;- };-- navigateToPage = (pageId: string | null): void => {- if (!pageId) {- this.#get().navigate?.('/page');- } else {- this.#get().navigate?.(`/page/${standardizeIdentifier(pageId)}`);- }- };-- removePage = async (pageId: string): Promise<void> => {- const { documents, selectedPageId } = this.#get();-- // Store original documents for rollback- const originalDocuments = documents;-- // Remove from documents array via internal dispatch (optimistic update)- this.#get().internal_dispatchDocuments({ id: pageId, type: 'removeDocument' });-- // Clear selected page ID if the deleted page is currently selected- if (selectedPageId === pageId) {- this.#set({ selectedPageId: null }, false, n('removePage/clearSelection'));- this.#get().navigateToPage(null);- }-- try {- // Delete from documents table- await documentService.deleteDocument(pageId);- } catch (error) {- console.error('Failed to delete page:', error);- // Restore documents on error- if (originalDocuments) {- this.#get().internal_dispatchDocuments({- documents: originalDocuments,- type: 'setDocuments',- });- }- if (selectedPageId === pageId) {- this.#set({ selectedPageId: pageId }, false, n('removePage/restoreSelection'));- this.#get().navigateToPage(pageId);- }- throw error;- }- };-- removeTempPage = (tempId: string): void => {- this.#get().internal_dispatchDocuments({ id: tempId, type: 'removeDocument' });- };-- renamePage = async (pageId: string, title: string, emoji?: string): Promise<void> => {- const { updatePageOptimistically } = this.#get();-- try {- await updatePageOptimistically(pageId, { emoji, title });- } catch (error) {- console.error('Failed to rename page:', error);- } finally {- this.#set({ renamingPageId: null }, false, n('renamePage'));- }- };-- replaceTempPageWithReal = (tempId: string, realPage: LobeDocument): void => {- this.#get().internal_dispatchDocuments({- document: realPage,- oldId: tempId,- type: 'replaceDocument',- });- };-- updatePage = async (id: string, updates: Partial<LobeDocument>): Promise<void> => {- await documentService.updateDocument({- content: updates.content ?? undefined,- editorData: updates.editorData- ? typeof updates.editorData === 'string'- ? updates.editorData- : JSON.stringify(updates.editorData)- : undefined,- id,- metadata: updates.metadata,- parentId: updates.parentId !== undefined ? updates.parentId : undefined,- title: updates.title,- });- await this.#get().refreshDocuments();- };-- updatePageOptimistically = async (pageId: string, updates: PageUpdateParams): Promise<void> => {- const { documents } = this.#get();-- // Find the page in documents array- const existingPage = documents?.find((doc) => doc.id === pageId);-- if (!existingPage) {- console.warn('[updatePageOptimistically] Page not found:', pageId);- return;- }-- // Build updated metadata with emoji- const updatedMetadata = {- ...existingPage.metadata,- ...(updates.emoji !== undefined ? { emoji: updates.emoji } : {}),- };-- // Clean up undefined values from metadata- const cleanedMetadata = Object.fromEntries(- Object.entries(updatedMetadata).filter(([, v]) => v !== undefined),- );-- const updatedPage: LobeDocument = {- ...existingPage,- metadata: cleanedMetadata,- title: updates.title ?? existingPage.title,- updatedAt: new Date(),- };-- // Update documents array via internal dispatch (optimistic)- this.#get().internal_dispatchDocuments({- document: updatedPage,- id: pageId,- type: 'updateDocument',- });-- // Queue background sync to DB- try {- await documentService.updateDocument({- id: pageId,- metadata: updatedPage.metadata || {},- parentId: updatedPage.parentId || undefined,- title: updatedPage.title || updatedPage.filename,- });-- // After successful sync, refresh document list to get server state- await this.#get().refreshDocuments();- } catch (error) {- console.error('[updatePageOptimistically] Failed to sync to DB:', error);- // On error, revert by restoring original page- this.#get().internal_dispatchDocuments({- document: existingPage,- id: pageId,- type: 'updateDocument',- });- }- };-- useFetchPageDetail = (pageId: string | undefined): SWRResponse<LobeDocument | null> => {- const swrKey = pageId ? documentSWRKeys.pageDetail(pageId) : null;-- return useClientDataSWRWithSync<LobeDocument | null>(- swrKey,- async () => {- if (!pageId) return null;-- const document = await documentService.getDocumentById(pageId);- if (!document) {- console.warn(`[useFetchPageDetail] Page not found: ${pageId}`);- return null;- }-- // Transform API response to LobeDocument format. `visibility` MUST be- // carried through so the sidebar's Private / Workspace bucketing stays- // stable when this hook's `onData` writes back into the shared docs- // array (see the `internal_dispatchDocuments` call below).- const fullPage: LobeDocument = {- content: document.content || null,- createdAt: document.createdAt ? new Date(document.createdAt) : new Date(),- editorData:- typeof document.editorData === 'string'- ? JSON.parse(document.editorData)- : document.editorData || null,- fileType: document.fileType,- filename: document.title || document.filename || 'Untitled',- id: document.id,- metadata: document.metadata || {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title: document.title || '',- totalCharCount: document.content?.length || 0,- totalLineCount: 0,- updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),- userId: document.userId,- visibility: document.visibility ?? null,- workspaceId: document.workspaceId ?? null,- };-- return fullPage;- },- {- focusThrottleInterval: 5000,- onData: (document) => {- if (!document || !pageId) return;-- // Auto-sync to documents array via internal dispatch. A deep-linked page- // may be outside the paginated sidebar list (or no list is mounted, as- // on mobile); add it so title, emoji and workspace lock state resolve.- const { documents } = this.#get();- this.#get().internal_dispatchDocuments(- documents?.some((doc) => doc.id === pageId)- ? { document, id: pageId, type: 'updateDocument' }- : { document, type: 'addDocument' },- );- },- revalidateOnFocus: true,- },- );- };-}--export type CrudAction = Pick<CrudActionImpl, keyof CrudActionImpl>;diff --git a/src/store/page/slices/crud/index.ts b/src/store/page/slices/crud/index.tsindex 2ae5307a29d..797eb8eb1f4 100644--- a/src/store/page/slices/crud/index.ts+++ b/src/store/page/slices/crud/index.ts@@ -1,2 +1 @@-export { createCrudSlice, type CrudAction } from './action';-export { type CrudState, initialCrudState } from './initialState';+export { initialPageCrudState, type PageCrudSliceState } from './initialState';diff --git a/src/store/page/slices/crud/initialState.ts b/src/store/page/slices/crud/initialState.tsindex a0099aaab33..383e1a6b61f 100644--- a/src/store/page/slices/crud/initialState.ts+++ b/src/store/page/slices/crud/initialState.ts@@ -1,7 +1,8 @@-export interface CrudState {+export interface PageCrudSliceState {+ /** Whether a page creation is in flight (drives the sidebar's pending row). */isCreatingNew: boolean;}-export const initialCrudState: CrudState = {+export const initialPageCrudState: PageCrudSliceState = {isCreatingNew: false,};diff --git a/src/store/page/slices/internal/action.ts b/src/store/page/slices/internal/action.tsdeleted file mode 100644index a1ee8f44b78..00000000000--- a/src/store/page/slices/internal/action.ts+++ /dev/null@@ -1,40 +0,0 @@-import isEqual from 'fast-deep-equal';--import { type StoreSetter } from '@/store/types';-import { setNamespace } from '@/utils/storeDebug';--import { type PageStore } from '../../store';-import { type DocumentsDispatch } from './reducer';-import { documentsReducer } from './reducer';--const n = setNamespace('page/internal');--type Setter = StoreSetter<PageStore>;-export const createInternalSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>- new InternalActionImpl(set, get, _api);--export class InternalActionImpl {- readonly #get: () => PageStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => PageStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- internal_dispatchDocuments = (payload: DocumentsDispatch, action?: string): void => {- const { documents } = this.#get();- const nextDocuments = documentsReducer(documents, payload);-- if (isEqual(documents, nextDocuments)) return;-- this.#set(- { documents: nextDocuments },- false,- action ?? n(`dispatchDocuments/${payload.type}`),- );- };-}--export type InternalAction = Pick<InternalActionImpl, keyof InternalActionImpl>;diff --git a/src/store/page/slices/internal/index.ts b/src/store/page/slices/internal/index.tsdeleted file mode 100644index 79221dc81ab..00000000000--- a/src/store/page/slices/internal/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './action';-export * from './reducer';diff --git a/src/store/page/slices/internal/reducer.ts b/src/store/page/slices/internal/reducer.tsdeleted file mode 100644index 88bc35e5730..00000000000--- a/src/store/page/slices/internal/reducer.ts+++ /dev/null@@ -1,105 +0,0 @@-import { produce } from 'immer';--import { type LobeDocument } from '@/types/document';--// ============ Action Types ============--type AddDocumentAction = {- document: LobeDocument;- type: 'addDocument';-};--type RemoveDocumentAction = {- id: string;- type: 'removeDocument';-};--type UpdateDocumentAction = {- document: LobeDocument;- id: string;- type: 'updateDocument';-};--type ReplaceDocumentAction = {- document: LobeDocument;- oldId: string;- type: 'replaceDocument';-};--type SetDocumentsAction = {- documents: LobeDocument[];- type: 'setDocuments';-};--type AppendDocumentsAction = {- documents: LobeDocument[];- type: 'appendDocuments';-};--export type DocumentsDispatch =- | AddDocumentAction- | RemoveDocumentAction- | UpdateDocumentAction- | ReplaceDocumentAction- | SetDocumentsAction- | AppendDocumentsAction;--// ============ Reducer ============--export const documentsReducer = (- state: LobeDocument[] | undefined,- payload: DocumentsDispatch,-): LobeDocument[] | undefined => {- switch (payload.type) {- case 'addDocument': {- return produce(state ?? [], (draft) => {- // Add to the beginning- draft.unshift(payload.document);- });- }-- case 'removeDocument': {- if (!state) return state;- return produce(state, (draft) => {- const index = draft.findIndex((doc) => doc.id === payload.id);- if (index !== -1) {- draft.splice(index, 1);- }- });- }-- case 'updateDocument': {- if (!state) return state;- return produce(state, (draft) => {- const index = draft.findIndex((doc) => doc.id === payload.id);- if (index !== -1) {- draft[index] = payload.document;- }- });- }-- case 'replaceDocument': {- if (!state) return [payload.document];- return produce(state, (draft) => {- const index = draft.findIndex((doc) => doc.id === payload.oldId);- if (index !== -1) {- draft[index] = payload.document;- }- });- }-- case 'setDocuments': {- return payload.documents;- }-- case 'appendDocuments': {- return produce(state ?? [], (draft) => {- draft.push(...payload.documents);- });- }-- default: {- return state;- }- }-};diff --git a/src/store/page/slices/list/action.ts b/src/store/page/slices/list/action.tsdeleted file mode 100644index 3be7ab9b832..00000000000--- a/src/store/page/slices/list/action.ts+++ /dev/null@@ -1,228 +0,0 @@-import { PAGE_DOCUMENT_FILE_TYPES, PAGE_DOCUMENT_SOURCE_TYPES } from '@lobechat/const';-import { type DocumentItem } from '@lobechat/database/schemas';-import { type SWRResponse } from 'swr';--import { useClientDataSWRWithSync } from '@/libs/swr';-import { documentService } from '@/services/document';-import { documentSWRKeys } from '@/services/document/swrKeys';-import { useGlobalStore } from '@/store/global';-import { type StoreSetter } from '@/store/types';-import { DocumentSourceType, type LobeDocument } from '@/types/document';-import { setNamespace } from '@/utils/storeDebug';--import { type PageStore } from '../../store';--const documentItemToLobeDocument = (document: DocumentItem): LobeDocument => ({- content: document.content || null,- createdAt: document.createdAt ? new Date(document.createdAt) : new Date(),- editorData:- typeof document.editorData === 'string'- ? JSON.parse(document.editorData)- : document.editorData || null,- fileType: document.fileType,- filename: document.title || document.filename || 'Untitled',- id: document.id,- metadata: document.metadata || {},- source: 'document',- sourceType: DocumentSourceType.EDITOR,- title: document.title || '',- totalCharCount: document.content?.length || 0,- totalLineCount: 0,- updatedAt: document.updatedAt ? new Date(document.updatedAt) : new Date(),- userId: document.userId,- visibility: document.visibility ?? null,- workspaceId: document.workspaceId ?? null,-});--const n = setNamespace('page/list');--// EDITOR is a client-only stamp on in-memory drafts; DB rows never carry it.-const ALLOWED_PAGE_SOURCE_TYPES = new Set([- DocumentSourceType.EDITOR as string,- ...PAGE_DOCUMENT_SOURCE_TYPES,-]);-const ALLOWED_PAGE_FILE_TYPES = new Set(PAGE_DOCUMENT_FILE_TYPES);--/**- * Check if a page should be displayed in the page list- */-const isAllowedPage = (page: { fileType: string; sourceType: string }) => {- return (- ALLOWED_PAGE_SOURCE_TYPES.has(page.sourceType) && ALLOWED_PAGE_FILE_TYPES.has(page.fileType)- );-};--type Setter = StoreSetter<PageStore>;-export const createListSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>- new ListActionImpl(set, get, _api);--export class ListActionImpl {- readonly #get: () => PageStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => PageStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- fetchDocuments = async (): Promise<void> => {- try {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;-- const documents = (await documentService.getPageDocuments(pageSize)) as LobeDocument[];- const hasMore = documents.length >= pageSize;-- // Use internal dispatch to set documents- this.#get().internal_dispatchDocuments({ documents, type: 'setDocuments' });-- this.#set(- {- currentPage: 0,- documentsTotal: documents.length,- hasMoreDocuments: hasMore,- queryFilter: {- fileTypes: Array.from(ALLOWED_PAGE_FILE_TYPES),- sourceTypes: Array.from(ALLOWED_PAGE_SOURCE_TYPES),- },- },- false,- n('fetchDocuments/success'),- );- } catch (error) {- console.error('Failed to fetch documents:', error);- throw error;- }- };-- loadMoreDocuments = async (): Promise<void> => {- const { currentPage, isLoadingMoreDocuments, hasMoreDocuments, queryFilter, documents } =- this.#get();-- if (isLoadingMoreDocuments || !hasMoreDocuments || !documents) return;-- const nextPage = currentPage + 1;-- this.#set({ isLoadingMoreDocuments: true }, false, n('loadMoreDocuments/start'));-- try {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- const queryParams = queryFilter- ? { current: nextPage, pageSize, ...queryFilter }- : { current: nextPage, pageSize };-- const result = await documentService.queryDocuments(queryParams);-- const newDocuments = result.items.filter(isAllowedPage).map((doc) => ({- ...doc,- filename: doc.filename ?? doc.title ?? 'Untitled',- })) as LobeDocument[];-- const hasMore = result.items.length >= pageSize;-- // Use internal dispatch to append documents- this.#get().internal_dispatchDocuments({ documents: newDocuments, type: 'appendDocuments' });-- this.#set(- {- currentPage: nextPage,- documentsTotal: result.total,- hasMoreDocuments: hasMore,- isLoadingMoreDocuments: false,- },- false,- n('loadMoreDocuments/success'),- );- } catch (error) {- console.error('Failed to load more documents:', error);- this.#set({ isLoadingMoreDocuments: false }, false, n('loadMoreDocuments/error'));- }- };-- refreshDocuments = async (): Promise<void> => {- await this.#get().fetchDocuments();- };-- /**- * Publish a private page (and its whole subtree) to the workspace, then- * refetch the sidebar so the item hops from the "Private" accordion into- * "Workspace" immediately. Errors bubble up so the caller can surface a- * localized toast without swallowing the reason.- */- publishPageToWorkspace = async (pageId: string): Promise<{ documentIds: string[] }> => {- const result = await documentService.publishDocumentToWorkspace(pageId);- await this.#get().refreshDocuments();- return result;- };-- /**- * Flip a page (and its whole subtree)'s workspace visibility. Bidirectional- * companion to `publishPageToWorkspace`. Refreshes the sidebar so the row- * hops between the "Private" and "Workspace" accordions.- */- setPageVisibility = async (- pageId: string,- visibility: 'private' | 'public',- ): Promise<{ documentIds: string[] }> => {- const result = await documentService.setDocumentVisibility(pageId, visibility);- await this.#get().refreshDocuments();- return result;- };-- setSearchKeywords = (keywords: string): void => {- this.#set({ searchKeywords: keywords }, false, n('setSearchKeywords'));- };-- setShowOnlyPagesNotInLibrary = (show: boolean): void => {- this.#set({ showOnlyPagesNotInLibrary: show }, false, n('setShowOnlyPagesNotInLibrary'));- };-- upsertDocument = (document: DocumentItem): void => {- const lobeDoc = documentItemToLobeDocument(document);- const { documents } = this.#get();- const exists = documents?.some((doc) => doc.id === document.id);- this.#get().internal_dispatchDocuments(- exists- ? { document: lobeDoc, id: document.id, type: 'updateDocument' }- : { document: lobeDoc, type: 'addDocument' },- );- };-- useFetchDocuments = (): SWRResponse<LobeDocument[]> => {- return useClientDataSWRWithSync<LobeDocument[]>(- documentSWRKeys.pageDocuments(),- async () => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- return (await documentService.getPageDocuments(pageSize)) as LobeDocument[];- },- {- onData: (documents) => {- if (!documents) return;-- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- const hasMore = documents.length >= pageSize;-- // Use internal dispatch to set documents- this.#get().internal_dispatchDocuments({ documents, type: 'setDocuments' });-- this.#set(- {- currentPage: 0,- documentsTotal: documents.length,- hasMoreDocuments: hasMore,- queryFilter: {- fileTypes: Array.from(ALLOWED_PAGE_FILE_TYPES),- sourceTypes: Array.from(ALLOWED_PAGE_SOURCE_TYPES),- },- },- false,- n('useFetchDocuments/onData'),- );- },- revalidateOnFocus: true,- },- );- };-}--export type ListAction = Pick<ListActionImpl, keyof ListActionImpl>;diff --git a/src/store/page/slices/list/index.ts b/src/store/page/slices/list/index.tsindex 3ff8cdbfb1a..573a9e857fb 100644--- a/src/store/page/slices/list/index.ts+++ b/src/store/page/slices/list/index.ts@@ -1,3 +1,2 @@-export { createListSlice, type ListAction } from './action';-export { initialListState, type ListState } from './initialState';+export { initialPageListState, type PageListSliceState } from './initialState';export { listSelectors } from './selectors';diff --git a/src/store/page/slices/list/initialState.ts b/src/store/page/slices/list/initialState.tsindex a5618558899..939f256a8e0 100644--- a/src/store/page/slices/list/initialState.ts+++ b/src/store/page/slices/list/initialState.ts@@ -1,29 +1,29 @@-import { type LobeDocument } from '@/types/document';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type { LobeDocument } from '@/types/document';-import { type PageQueryFilter } from '../../initialState';+import type { PageListValue } from '../../projection';-export interface ListState {- currentPage: number;- documents: LobeDocument[];- documentsTotal: number;- hasMoreDocuments: boolean;- isDocumentListLoading: boolean;- isLoadingMoreDocuments: boolean;- localPageMap: Map<string, LobeDocument>;- queryFilter?: PageQueryFilter;- searchKeywords: string;- showOnlyPagesNotInLibrary: boolean;+export interface PageListSliceState {+ /**+ * By-id page cache, read by `getDocumentById` as a fallback behind the list.+ * Filled for pages opened outside the loaded list (mobile, deep links) β the+ * editor's title / emoji / workspace lock state resolve from here.+ */+ pageDetailMap: Record<string, LobeDocument>;+ /** Local-first bookkeeping for `pageDetailMap`. */+ pageDetailReplica: ReplicaState<LobeDocument>;+ /**+ * The paged page list (`pageListMap.all`), what the sidebar reads. The map+ * shape keeps the door open for another list query without moving fields.+ */+ pageListMap: Record<string, PageListValue>;+ /** Local-first bookkeeping for `pageListMap`. */+ pageListReplica: ReplicaState<PageListValue>;}-export const initialListState: ListState = {- currentPage: 0,- documents: [],- documentsTotal: 0,- hasMoreDocuments: false,- isDocumentListLoading: false,- isLoadingMoreDocuments: false,- localPageMap: new Map(),- queryFilter: undefined,- searchKeywords: '',- showOnlyPagesNotInLibrary: false,+export const initialPageListState: PageListSliceState = {+ pageDetailMap: {},+ pageDetailReplica: createReplicaState(),+ pageListMap: {},+ pageListReplica: createReplicaState(),};diff --git a/src/store/page/slices/list/selectors.test.ts b/src/store/page/slices/list/selectors.test.tsindex 38b7612cec6..f21358c0998 100644--- a/src/store/page/slices/list/selectors.test.ts+++ b/src/store/page/slices/list/selectors.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { DocumentSourceType, type LobeDocument } from '@/types/document';import { initialState, type PageState } from '../../initialState';-import { initialListState } from './initialState';+import { PAGE_LIST_KEY } from '../../projection';import { listSelectors } from './selectors';vi.mock('@/store/global', () => ({@@ -37,11 +37,19 @@ const doc = (...overrides,});-const createState = (documents: LobeDocument[]): PageState => ({+const createState = (documents: LobeDocument[], overrides: Partial<PageState> = {}): PageState => ({...initialState,- ...initialListState,- documents,+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: documents,+ pageSize: 20,+ total: documents.length,+ },+ },searchKeywords: '',+ ...overrides,});describe('listSelectors β private/workspace buckets', () => {@@ -99,3 +107,59 @@ describe('listSelectors β private/workspace buckets', () => {expect(listSelectors.hasMorePrivateFilteredDocuments(state)).toBe(true);});});++describe('listSelectors β replica-backed reads', () => {+ it('reports the list as uninitialized until the entry has a value', () => {+ const empty = { ...initialState, searchKeywords: '' } as PageState;++ expect(listSelectors.isPageListInit(empty)).toBe(false);+ expect(listSelectors.isDocumentsLoading(empty)).toBe(true);+ expect(listSelectors.getFilteredDocuments(empty)).toEqual([]);+ expect(listSelectors.documentsTotal(empty)).toBe(0);++ const loaded = createState([doc('page-a', 'public')]);++ expect(listSelectors.isPageListInit(loaded)).toBe(true);+ expect(listSelectors.isDocumentsLoading(loaded)).toBe(false);+ expect(listSelectors.documentsTotal(loaded)).toBe(1);+ });++ it('reads pagination flags from the paged view', () => {+ const state = createState([doc('page-a', 'public')], {+ pageListMap: {+ [PAGE_LIST_KEY]: {+ currentPage: 1,+ hasMore: true,+ isLoadingMore: true,+ items: [doc('page-a', 'public')],+ pageSize: 20,+ total: 42,+ },+ },+ });++ expect(listSelectors.hasMoreDocuments(state)).toBe(true);+ expect(listSelectors.isLoadingMoreDocuments(state)).toBe(true);+ expect(listSelectors.documentsTotal(state)).toBe(42);+ });++ it('resolves a page from the list, falling back to the by-id projection', () => {+ const state = createState([doc('in-list', 'private')], {+ pageDetailMap: { 'deep-link': doc('deep-link', 'public', { title: 'Deep linked' }) },+ });++ expect(listSelectors.getDocumentById('in-list')(state)?.id).toBe('in-list');+ expect(listSelectors.getDocumentById('deep-link')(state)?.title).toBe('Deep linked');+ // A page that is in neither location resolves to nothing.+ expect(listSelectors.getDocumentById('missing')(state)).toBeUndefined();+ expect(listSelectors.getDocumentById(undefined)(state)).toBeUndefined();+ });++ it('prefers the list copy over the by-id projection for the same page', () => {+ const state = createState([doc('same-page', 'private', { title: 'From list' })], {+ pageDetailMap: { 'same-page': doc('same-page', 'private', { title: 'From detail' }) },+ });++ expect(listSelectors.getDocumentById('same-page')(state)?.title).toBe('From list');+ });+});diff --git a/src/store/page/slices/list/selectors.ts b/src/store/page/slices/list/selectors.tsindex 305772a5aed..448f3e52c6c 100644--- a/src/store/page/slices/list/selectors.ts+++ b/src/store/page/slices/list/selectors.ts@@ -1,15 +1,26 @@import { useGlobalStore } from '@/store/global';import { type LobeDocument } from '@/types/document';-import { type PageState } from '../../initialState';+import type { PageState } from '../../initialState';+import { PAGE_LIST_KEY } from '../../projection';++const EMPTY_DOCUMENTS: LobeDocument[] = [];++const pageList = (s: PageState) => s.pageListMap[PAGE_LIST_KEY];++const sidebarPageSize = (): number => useGlobalStore.getState().status.pagePageSize || 20;/**- * Check if documents are still loading (undefined means not yet loaded)+ * Whether the page list has a value to show (hydrated from IndexedDB or+ * confirmed by the server). Its absence is the only loading signal.*/-const isDocumentsLoading = (s: PageState): boolean => s.documents === undefined;+const isPageListInit = (s: PageState): boolean => pageList(s) !== undefined;++/** Documents are still loading (the list entry has no value yet). */+const isDocumentsLoading = (s: PageState): boolean => !isPageListInit(s);const getFilteredDocuments = (s: PageState): LobeDocument[] => {- const docs = s.documents ?? [];+ const docs = pageList(s)?.items ?? EMPTY_DOCUMENTS;const { searchKeywords, showOnlyPagesNotInLibrary } = s;@@ -46,11 +57,8 @@ const getFilteredDocuments = (s: PageState): LobeDocument[] => {};// Limited filtered documents for sidebar display-const getFilteredDocumentsLimited = (s: PageState): LobeDocument[] => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- const allDocs = getFilteredDocuments(s);- return allDocs.slice(0, pageSize);-};+const getFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>+ getFilteredDocuments(s).slice(0, sidebarPageSize());// Workspace-mode sidebar buckets: split filtered docs into "private" (creator// only) and "workspace-shared". Personal-mode `visibility` is meaningless β the@@ -63,15 +71,11 @@ const getWorkspaceFilteredDocuments = (s: PageState): LobeDocument[] =>// Bucket-scoped, sidebar-sized page slices β mirror the Limited helper for the// dual-accordion Pages sidebar so each bucket paginates independently.-const getPrivateFilteredDocumentsLimited = (s: PageState): LobeDocument[] => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- return getPrivateFilteredDocuments(s).slice(0, pageSize);-};+const getPrivateFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>+ getPrivateFilteredDocuments(s).slice(0, sidebarPageSize());-const getWorkspaceFilteredDocumentsLimited = (s: PageState): LobeDocument[] => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- return getWorkspaceFilteredDocuments(s).slice(0, pageSize);-};+const getWorkspaceFilteredDocumentsLimited = (s: PageState): LobeDocument[] =>+ getWorkspaceFilteredDocuments(s).slice(0, sidebarPageSize());const privateFilteredDocumentsCount = (s: PageState): number =>getPrivateFilteredDocuments(s).length;@@ -79,40 +83,35 @@ const privateFilteredDocumentsCount = (s: PageState): number =>const workspaceFilteredDocumentsCount = (s: PageState): number =>getWorkspaceFilteredDocuments(s).length;-const hasMorePrivateFilteredDocuments = (s: PageState): boolean => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- return getPrivateFilteredDocuments(s).length > pageSize;-};+const hasMorePrivateFilteredDocuments = (s: PageState): boolean =>+ getPrivateFilteredDocuments(s).length > sidebarPageSize();-const hasMoreWorkspaceFilteredDocuments = (s: PageState): boolean => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- return getWorkspaceFilteredDocuments(s).length > pageSize;-};+const hasMoreWorkspaceFilteredDocuments = (s: PageState): boolean =>+ getWorkspaceFilteredDocuments(s).length > sidebarPageSize();+/**+ * One page as the loaded list holds it, falling back to the by-id projection+ * for pages outside it (mobile mounts no sidebar; a deep link may land before+ * the list fetches). Returns the stored object, so a component subscribing to+ * this selector keeps a stable reference until the page actually changes.+ */const getDocumentById = (docId: string | undefined) => (s: PageState) => {if (!docId) return undefined;-- // Find in documents array- return s.documents?.find((doc) => doc.id === docId);+ return pageList(s)?.items.find((doc) => doc.id === docId) ?? s.pageDetailMap[docId];};-const hasMoreDocuments = (s: PageState): boolean => s.hasMoreDocuments;+const hasMoreDocuments = (s: PageState): boolean => Boolean(pageList(s)?.hasMore);-const isLoadingMoreDocuments = (s: PageState): boolean => s.isLoadingMoreDocuments;+const isLoadingMoreDocuments = (s: PageState): boolean => Boolean(pageList(s)?.isLoadingMore);-const documentsTotal = (s: PageState): number => s.documentsTotal;+const documentsTotal = (s: PageState): number => pageList(s)?.total ?? 0;// Check if filtered documents have more than displayed-const hasMoreFilteredDocuments = (s: PageState): boolean => {- const pageSize = useGlobalStore.getState().status.pagePageSize || 20;- const allDocs = getFilteredDocuments(s);- return allDocs.length > pageSize;-};+const hasMoreFilteredDocuments = (s: PageState): boolean =>+ getFilteredDocuments(s).length > sidebarPageSize();// Get total count of filtered documents-const filteredDocumentsCount = (s: PageState): number => {- return getFilteredDocuments(s).length;-};+const filteredDocumentsCount = (s: PageState): number => getFilteredDocuments(s).length;export const listSelectors = {documentsTotal,@@ -130,6 +129,7 @@ export const listSelectors = {hasMoreWorkspaceFilteredDocuments,isDocumentsLoading,isLoadingMoreDocuments,+ isPageListInit,privateFilteredDocumentsCount,workspaceFilteredDocumentsCount,};diff --git a/src/store/page/slices/selection/action.ts b/src/store/page/slices/selection/action.tsdeleted file mode 100644index be3ac130479..00000000000--- a/src/store/page/slices/selection/action.ts+++ /dev/null@@ -1,53 +0,0 @@-import { type StoreSetter } from '@/store/types';-import { setNamespace } from '@/utils/storeDebug';--import { type PageStore } from '../../store';--const n = setNamespace('page/selection');--type Setter = StoreSetter<PageStore>;-export const createSelectionSlice = (set: Setter, get: () => PageStore, _api?: unknown) =>- new SelectionActionImpl(set, get, _api);--export class SelectionActionImpl {- readonly #get: () => PageStore;- readonly #set: Setter;-- constructor(set: Setter, get: () => PageStore, _api?: unknown) {- void _api;- this.#set = set;- this.#get = get;- }-- closeAllPagesDrawer = (): void => {- this.#set({ allPagesDrawerOpen: false }, false, n('closeAllPagesDrawer'));- };-- openAllPagesDrawer = (): void => {- this.#set({ allPagesDrawerOpen: true }, false, n('openAllPagesDrawer'));- };-- selectPage = (pageId: string): void => {- const { selectedPageId } = this.#get();-- // Don't allow deselecting the current page- if (selectedPageId === pageId) return;-- // Select and navigate- this.#set({ isCreatingNew: false, selectedPageId: pageId }, false, n('selectPage'));- this.#get().navigateToPage(pageId);- };-- setRenamingPageId = (pageId: string | null): void => {- this.#set({ renamingPageId: pageId }, false, n('setRenamingPageId'));- };-- setSelectedPageId = (pageId: string | null, shouldNavigate: boolean = true): void => {- this.#set({ selectedPageId: pageId }, false, n('setSelectedPageId'));- if (shouldNavigate) {- this.#get().navigateToPage(pageId);- }- };-}--export type SelectionAction = Pick<SelectionActionImpl, keyof SelectionActionImpl>;diff --git a/src/store/page/slices/selection/index.ts b/src/store/page/slices/selection/index.tsindex 665c48407c2..3ce00298bcc 100644--- a/src/store/page/slices/selection/index.ts+++ b/src/store/page/slices/selection/index.ts@@ -1,2 +1 @@-export { createSelectionSlice, type SelectionAction } from './action';-export { initialSelectionState, type SelectionState } from './initialState';+export { initialPageSelectionState, type PageSelectionSliceState } from './initialState';diff --git a/src/store/page/slices/selection/initialState.ts b/src/store/page/slices/selection/initialState.tsindex 82ccd244ff8..96137d7c272 100644--- a/src/store/page/slices/selection/initialState.ts+++ b/src/store/page/slices/selection/initialState.ts@@ -1,10 +1,13 @@-export interface SelectionState {+export interface PageSelectionSliceState {+ /** Whether the all-pages drawer is open. */allPagesDrawerOpen: boolean;+ /** Id of the page being renamed in place (null if none). */renamingPageId: string | null;+ /** Currently selected page id. */selectedPageId: string | null;}-export const initialSelectionState: SelectionState = {+export const initialPageSelectionState: PageSelectionSliceState = {allPagesDrawerOpen: false,renamingPageId: null,selectedPageId: null,diff --git a/src/store/page/store.ts b/src/store/page/store.tsindex 823c235bc8a..31da4c3264d 100644--- a/src/store/page/store.ts+++ b/src/store/page/store.ts@@ -1,55 +1,15 @@import { shallow } from 'zustand/shallow';import { createWithEqualityFn } from 'zustand/traditional';-import { type StateCreator } from 'zustand/vanilla';import { createDevtools } from '../middleware/createDevtools';import { expose } from '../middleware/expose';-import { flattenActions } from '../utils/flattenActions';-import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStore';-import { type PageState } from './initialState';-import { initialState } from './initialState';-import { type CrudAction } from './slices/crud';-import { createCrudSlice } from './slices/crud';-import { type InternalAction } from './slices/internal';-import { createInternalSlice } from './slices/internal';-import { type ListAction } from './slices/list';-import { createListSlice } from './slices/list';-import { type SelectionAction } from './slices/selection';-import { createSelectionSlice } from './slices/selection';+import { initialState, type PageState } from './initialState';-// =============== Aggregate createStoreFn ============ //--export type PageStore = PageState &- InternalAction &- ListAction &- SelectionAction &- CrudAction &- ResetableStore;--type PageStoreAction = InternalAction & ListAction & SelectionAction & CrudAction & ResetableStore;--class PageStoreResetAction extends ResetableStoreAction<PageStore> {- protected readonly resetActionName = 'resetPageStore';-}--const createStore: StateCreator<PageStore, [['zustand/devtools', never]]> = (- ...parameters: Parameters<StateCreator<PageStore, [['zustand/devtools', never]]>>-) => ({- ...initialState,- ...flattenActions<PageStoreAction>([- createInternalSlice(...parameters),- createListSlice(...parameters),- createSelectionSlice(...parameters),- createCrudSlice(...parameters),- new PageStoreResetAction(...parameters),- ]),-});--// =============== Implement useStore ============ //const devtools = createDevtools('page');-export const usePageStore = createWithEqualityFn<PageStore>()(devtools(createStore), shallow);+export const usePageStore = createWithEqualityFn<PageState>()(+ devtools(() => initialState),+ shallow,+);expose('page', usePageStore);--export const getPageStoreState = () => usePageStore.getState();diff --git a/src/store/utils/userDataStores.test.ts b/src/store/utils/userDataStores.test.tsindex 236ba6b26f1..b14fa3e5346 100644--- a/src/store/utils/userDataStores.test.ts+++ b/src/store/utils/userDataStores.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const resetGatewayMuxRegistry = vi.hoisted(() => vi.fn());const storeResets = vi.hoisted(() => [] as Array<() => void>);+const pageReset = vi.hoisted(() => vi.fn());const fakeStore = vi.hoisted(() => () => ({getState: () => {const reset = vi.fn();@@ -26,7 +27,7 @@ vi.mock('@/store/image', () => ({ useImageStore: fakeStore() }));vi.mock('@/store/library', () => ({ useKnowledgeBaseStore: fakeStore() }));vi.mock('@/store/mention', () => ({ useMentionStore: fakeStore() }));vi.mock('@/store/notebook', () => ({ useNotebookStore: fakeStore() }));-vi.mock('@/store/page', () => ({ usePageStore: fakeStore() }));+vi.mock('@/store/page', () => ({ pageActions: { reset: pageReset } }));vi.mock('@/store/session', () => ({ useSessionStore: fakeStore() }));vi.mock('@/store/task', () => ({ useTaskStore: fakeStore() }));vi.mock('@/store/tool', () => ({ useToolStore: fakeStore() }));@@ -38,6 +39,7 @@ describe('stores.reset', () => {beforeEach(() => {resetGatewayMuxRegistry.mockClear();storeResets.length = 0;+ pageReset.mockClear();});it('tears down the gateway mux registry before wiping the user-data stores', async () => {@@ -48,7 +50,8 @@ describe('stores.reset', () => {stores.reset();expect(resetGatewayMuxRegistry).toHaveBeenCalledTimes(1);- expect(storeResets).toHaveLength(19);+ expect(storeResets).toHaveLength(18);+ expect(pageReset).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 65ea3f75487..dd353e7170e 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -13,7 +13,7 @@ import { useImageStore } from '@/store/image';import { useKnowledgeBaseStore } from '@/store/library';import { useMentionStore } from '@/store/mention';import { useNotebookStore } from '@/store/notebook';-import { usePageStore } from '@/store/page';+import { pageActions } from '@/store/page';import { useSessionStore } from '@/store/session';import { useTaskStore } from '@/store/task';import { useToolStore } from '@/store/tool';@@ -39,7 +39,6 @@ const resetableStores: ResetableStoreApi[] = [useKnowledgeBaseStore,useMentionStore,useNotebookStore,- usePageStore,useSessionStore,useTaskStore,useToolStore,@@ -48,9 +47,14 @@ const resetableStores: ResetableStoreApi[] = [useVideoStore,];+const resetableActions: ResetableStore[] = [pageActions];+export interface StoreActions extends ResetableStore {}-const createStoreActions = (stores: ResetableStoreApi[]): StoreActions => ({+const createStoreActions = (+ stores: ResetableStoreApi[],+ actions: ResetableStore[],+): StoreActions => ({reset: () => {// Drop the per-user gateway socket(s) before the stores they feed are// wiped β a new data context must not inherit the old identity's socket.@@ -59,8 +63,11 @@ const createStoreActions = (stores: ResetableStoreApi[]): StoreActions => ({for (const store of stores) {store.getState().reset();}+ for (const action of actions) {+ action.reset();+ }});},});-export const stores = createStoreActions(resetableStores);+export const stores = createStoreActions(resetableStores, resetableActions);