π€― 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
β¨ feat(replica): page transcripts with irregular windows, synthetic rows and scoped buckets (#20392)
Arvin Xuf4f42d40c232
diff --git a/packages/replica/README.md b/packages/replica/README.mdindex 8f7810abb48..79ef1b11aca 100644--- a/packages/replica/README.md+++ b/packages/replica/README.md@@ -48,3 +48,18 @@ slice.optimistic(key, apply, serverCall);```Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.++## Transcripts and other irregular pages++Message-like resources page backward by cursor, with windows whose length changes on every refresh. The paging config covers them:++| Option / API | Use |+| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `paging.isCursorable(item)` | Skip synthetic rows (group / summary nodes) when pinning the join anchor or deriving a cursor. A head refresh replaces the head page's synthetic rows by id. |+| `paging.deriveCursor(item)` | Plain lists whose server reports no `nextCursor`: the next cursor comes from the oldest eligible row. Only for rows with a lossless position. |+| `paging.sort` | Stable: rows the comparator ties keep server order. Compare positions only. |+| `persistKey(key)` | Entries that stay in memory (no hydrate, no persist), e.g. scoped buckets. |+| `slice.update(key, fn, { persist: false })` + `slice.persist(key)` | Stream into memory, then persist the confirmed value once. |+| `splitPagedLens({ itemsField, metaField, derive })` | Keep raw rows where readers expect them, paging bookkeeping beside them, and derived fields (a parsed display list) in the same commit. |++`useSync(params, options)` forwards a sync schedule (`refreshInterval`, `dedupingInterval`, `revalidateIfStale`, `revalidateOnFocus`, β¦) to the driver, and runs `onSuccess` / `onError` side effects after a response is folded in.diff --git a/packages/replica/src/core/defineReplica.ts b/packages/replica/src/core/defineReplica.tsindex 78c93ece8db..7f6ef46cdd2 100644--- a/packages/replica/src/core/defineReplica.ts+++ b/packages/replica/src/core/defineReplica.ts@@ -33,13 +33,18 @@ const DEFAULT_SCOPE = staticReplicaScope();/** Builds the storage of one resource from its namespace (`replica:<name>:v<version>`). */export type ReplicaStorageFactory<TData> = (namespace: string) => ReplicaStorage<TData> | undefined;-export interface DefineReplicaOptions<TParams, TData, TFetched = TData> {+export interface DefineReplicaOptions<TParams, TData, TFetched = TData, TCursor = any> {/** Default network fetcher; a store binding may override it. */- fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;+ fetcher?: (params: TParams, cursor?: TCursor) => Promise<TFetched>;/** Entry identity inside one scope (memory bucket + persisted row). */key: (params: TParams) => string;name: string;- paging?: ReplicaPagingConfig<any>;+ paging?: ReplicaPagingConfig<any, TCursor>;+ /**+ * Entries that never touch storage (no hydrate, no persist) β e.g. scoped+ * buckets whose rows must not land under an ordinary entry. Defaults to all.+ */+ persistKey?: (key: string) => boolean;/*** Query identity beyond `key` (filters, sort, page size) β anything that* changes the rows without changing the key. Persisted rows are kept per@@ -55,9 +60,9 @@ export interface DefineReplicaOptions<TParams, TData, TFetched = TData> {version: number;}-export const defineReplica = <TParams, TData, TFetched = TData>(- options: DefineReplicaOptions<TParams, TData, TFetched>,-): ReplicaResource<TParams, TData, TFetched> => {+export const defineReplica = <TParams, TData, TFetched = TData, TCursor = any>(+ options: DefineReplicaOptions<TParams, TData, TFetched, TCursor>,+): ReplicaResource<TParams, TData, TFetched, TCursor> => {const namespace = `replica:${options.name}:v${options.version}`;const storage =typeof options.storage === 'function' ? options.storage(namespace) : options.storage;@@ -68,6 +73,7 @@ export const defineReplica = <TParams, TData, TFetched = TData>(name: options.name,namespace,paging: options.paging,+ persistKey: options.persistKey ?? (() => true),persisted: !!storage,query: (params) => (options.query ? stableQueryKey(options.query(params)) : undefined),storageKey: (params) =>@@ -94,7 +100,7 @@ export interface DefinePagedReplicaOptions<TParams, TItem, TCursor> extends Omitparams: TParams,cursor: TCursor | undefined,) => Promise<ReplicaPageResult<TItem, TCursor>>;- paging: ReplicaPagingConfig<TItem>;+ paging: ReplicaPagingConfig<TItem, TCursor>;storage?: ReplicaStorage<any> | ReplicaStorageFactory<any>;}@@ -109,8 +115,8 @@ export const definePagedReplica = <TData extends ReplicaPagedData<TItem, TCursor> = ReplicaPagedData<TItem, TCursor>,>(options: DefinePagedReplicaOptions<TParams, TItem, TCursor>,-): ReplicaResource<TParams, TData, ReplicaPageResult<TItem, TCursor>> =>- defineReplica<TParams, TData, ReplicaPageResult<TItem, TCursor>>({+): ReplicaResource<TParams, TData, ReplicaPageResult<TItem, TCursor>, TCursor> =>+ defineReplica<TParams, TData, ReplicaPageResult<TItem, TCursor>, TCursor>({...options,fetcher: options.fetchPage,storage: options.storage as ReplicaStorage<TData> | ReplicaStorageFactory<TData> | undefined,diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex 9df8a923e47..e47f4c46a4d 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -166,6 +166,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(// Until identity resolves the scope is a guess; never write into it.if (!resource.scope.canPersist()) return;for (const effect of effects) {+ if (!resource.persistKey(effect.key)) continue;const key = { ...storageKey(effect.key, effect.query), scope: effect.scope };if (effect.type === 'remove') {writeQueue.remove(key);@@ -232,6 +233,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(const hydrate = async (params: TParams, scope = resource.scope.get()) => {if (!resource.storage) return false;const key = resource.key(params);+ if (!resource.persistKey(key)) return false;const query = resource.query(params);const cached = await resource.storage.get({ ...storageKey(key, query), scope });if (!cached) return false;@@ -309,6 +311,18 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(const remove = (key: string) => dispatch({ key, scope: resource.scope.get(), type: 'remove' });+ /**+ * Persist the confirmed value of an entry as it is now β the flush after a+ * burst of in-memory `update(..., { persist: false })` writes (a stream).+ */+ const persist = (key: string) => {+ const scope = resource.scope.get();+ if (getSlot().scope !== undefined && getSlot().scope !== scope) return;+ const data = getConfirmed(key);+ if (data === undefined) return;+ runEffects([{ data, key, query: getSlot().entries[key]?.query, scope, type: 'persist' }]);+ };+const revalidate = (key?: string): Promise<unknown> =>options.revalidate ? options.revalidate(key) : Promise.resolve();@@ -530,6 +544,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(loadMore,optimistic,patchStoredEntity,+ persist,remove,replace,resource,diff --git a/packages/replica/src/core/paging.test.ts b/packages/replica/src/core/paging.test.tsindex df5f67a0126..eb201243486 100644--- a/packages/replica/src/core/paging.test.ts+++ b/packages/replica/src/core/paging.test.ts@@ -1,5 +1,6 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, expectTypeOf, it } from 'vitest';+import { definePagedReplica } from './defineReplica';import {applyHeadPage,applyNextPage,@@ -242,6 +243,182 @@ describe('cursor / backward paging (message-like transcript)', () => {expect(refreshed.nextCursor).toEqual({ createdAt: 3, id: 'm3' });});+ // Round-trimmed windows change length on every refresh; a cursor walk must+ // not read that as a query change and drop the loaded history.+ it('keeps older pages when the refreshed window has another length', () => {+ const refreshed = applyHeadPage(+ loadedTwoWindows(),+ { items: range(7, 12), nextCursor: cursorOf(msg(7)) },+ { pageSize: 6 },+ messages,+ );+ expect(mids(refreshed)).toEqual(range(3, 12).map((m) => m.id));+ expect(refreshed.currentPage).toBe(1);+ });++ it.each(['backward', 'forward'] as const)(+ 'refreshes the head cursor before trimming %s pages',+ (direction) => {+ const config = {+ ...messages,+ direction,+ sort: (a: Message, b: Message) =>+ direction === 'backward' ? a.createdAt - b.createdAt : b.createdAt - a.createdAt,+ };+ const view = (rows: Message[]) => (direction === 'backward' ? rows : [...rows].reverse());+ const head = applyHeadPage<Message, Cursor>(+ undefined,+ { items: view(range(7, 10)), nextCursor: cursorOf(msg(7)) },+ { pageSize: 4 },+ config,+ );+ const extended = applyNextPage(+ head,+ { items: view(range(3, 6)), nextCursor: cursorOf(msg(3)) },+ config,+ );+ const refreshed = applyHeadPage(+ extended,+ { items: view(range(6, 10)), nextCursor: cursorOf(msg(6)) },+ { pageSize: 5 },+ config,+ );+ expect(refreshed.nextCursor).toEqual(cursorOf(msg(3)));+ for (const trimmed of [+ collapseToHead(refreshed, config),+ toPersistedPage(refreshed, config),+ ]) {+ expect(trimmed.items).toEqual(view(range(6, 10)));+ expect(getNextPageCursor(trimmed, config)).toEqual(cursorOf(msg(6)));+ }+ },+ );++ describe('synthetic group nodes', () => {+ interface Node extends Message {+ role?: 'compressedGroup' | 'user';+ }+ const grouped: ReplicaPagingConfig<Node> = {+ ...(messages as ReplicaPagingConfig<Node>),+ isCursorable: (m) => m.role !== 'compressedGroup',+ };+ const group = (n: number): Node => ({ createdAt: n, id: `g${n}`, role: 'compressedGroup' });++ it.each(['backward', 'forward'] as const)(+ 'retains synthetic head rows sorted outside the head in %s views',+ (direction) => {+ const config = {+ ...grouped,+ direction,+ sort: (a: Node, b: Node) =>+ direction === 'backward' ? a.createdAt - b.createdAt : b.createdAt - a.createdAt,+ };+ const view = (rows: Node[]) => (direction === 'backward' ? rows : [...rows].reverse());+ const head = applyHeadPage<Node, Cursor>(+ undefined,+ { items: view([group(0), ...range(7, 10)]), nextCursor: cursorOf(msg(7)) },+ { pageSize: 5 },+ config,+ );+ const extended = applyNextPage(+ head,+ { items: view(range(3, 6)), nextCursor: cursorOf(msg(3)) },+ config,+ );+ for (const trimmed of [+ collapseToHead(extended, config),+ toPersistedPage(extended, config),+ ]) {+ expect(trimmed.items).toEqual(view([group(0), ...range(7, 10)]));+ expect(trimmed.nextCursor).toEqual(cursorOf(msg(7)));+ }+ },+ );++ it('never pins the join anchor on a synthetic node', () => {+ const head = applyHeadPage<Node, Cursor>(+ undefined,+ { items: [group(6), ...range(7, 10)], nextCursor: cursorOf(msg(7)) },+ { pageSize: 5 },+ grouped,+ );+ const extended = applyNextPage(head, { items: range(3, 5), nextCursor: null }, grouped);+ expect(extended.anchorId).toBe('m7');++ // The refreshed window still holds m7, so the older page survives even+ // though the group node in front of it was re-summarized away.+ const refreshed = applyHeadPage(+ extended,+ { items: range(7, 11), nextCursor: cursorOf(msg(7)) },+ { pageSize: 5 },+ grouped,+ );+ expect(mids(refreshed)).toEqual(['m3', 'm4', 'm5', ...range(7, 11).map((m) => m.id)]);+ });+ });++ describe('plain list without server cursors (threads)', () => {+ const plain: ReplicaPagingConfig<Message, Cursor> = {+ ...messages,+ deriveCursor: cursorOf,+ isCursorable: (m) => !m.id.startsWith('g'),+ };++ it('derives the next cursor from the oldest eligible row', () => {+ const head = applyHeadPage<Message, Cursor>(+ undefined,+ { items: [{ createdAt: 6, id: 'g6' }, ...range(7, 10)] },+ { pageSize: 5 },+ plain,+ );+ expect(head.hasMore).toBe(true);+ expect(getNextPageCursor(head, plain)).toEqual({ createdAt: 7, id: 'm7' });+ });++ it('keeps loaded pages across head refreshes and ends on an empty page', () => {+ const head = applyHeadPage<Message, Cursor>(+ undefined,+ { items: range(7, 10) },+ { pageSize: 4 },+ plain,+ );+ const extended = applyNextPage(head, { items: range(3, 6) }, plain);+ expect(getNextPageCursor(extended, plain)).toEqual({ createdAt: 3, id: 'm3' });++ const refreshed = applyHeadPage(extended, { items: range(7, 11) }, { pageSize: 5 }, plain);+ expect(mids(refreshed)).toEqual(range(3, 11).map((m) => m.id));++ const done = applyNextPage(refreshed, { items: [] }, plain);+ expect(getNextPageCursor(done, plain)).toBeNull();+ });++ it('waits for a server cursor when the resource cannot derive one', () => {+ const head = applyHeadPage<Message, Cursor>(+ undefined,+ { items: range(7, 10) },+ { pageSize: 4 },+ messages,+ );+ expect(getNextPageCursor(head, messages)).toBeUndefined();+ });+ });++ it('keeps the server order of rows the sort ties', () => {+ const sameTick = applyHeadPage<Message, Cursor>(+ undefined,+ {+ items: [+ { createdAt: 5, id: 'z-user' },+ { createdAt: 5, id: 'a-assistant' },+ ],+ nextCursor: null,+ },+ { pageSize: 2 },+ messages,+ );+ expect(mids(sameTick)).toEqual(['z-user', 'a-assistant']);+ });+it('collapses to the fresh window when it slid past the anchor (gap)', () => {const refreshed = applyHeadPage(loadedTwoWindows(),@@ -286,3 +463,36 @@ describe('cursor / backward paging (message-like transcript)', () => {expect(capped.nextCursor).toBeUndefined();});});++describe('paged resource cursor types', () => {+ it('preserves an object cursor in the configuration and resource', () => {+ interface Cursor {+ id: string;+ }+ const resource = definePagedReplica<undefined, Row, Cursor>({+ key: () => 'rows',+ name: 'rows',+ version: 1,+ paging: {+ direction: 'backward',+ getId: (row) => row.id,+ mode: 'cursor',+ deriveCursor: (row) => ({ id: row.id }),+ },+ });+ expectTypeOf(resource.paging!.deriveCursor!).returns.toEqualTypeOf<Cursor>();+ expectTypeOf(resource.fetcher!).parameter(1).toEqualTypeOf<Cursor | undefined>();+ definePagedReplica<undefined, Row, Cursor>({+ key: () => 'invalid',+ name: 'invalid',+ version: 1,+ paging: {+ direction: 'backward',+ getId: (row) => row.id,+ mode: 'cursor',+ // @ts-expect-error An object-cursor resource cannot derive a string cursor.+ deriveCursor: (row) => row.id,+ },+ });+ });+});diff --git a/packages/replica/src/core/paging.ts b/packages/replica/src/core/paging.tsindex ed59eca8e9b..cd48a04a3e9 100644--- a/packages/replica/src/core/paging.ts+++ b/packages/replica/src/core/paging.ts@@ -17,9 +17,23 @@export type ReplicaPagingMode = 'cursor' | 'offset';export type ReplicaPagingDirection = 'backward' | 'forward';-export interface ReplicaPagingConfig<TItem> {+export interface ReplicaPagingConfig<TItem, TCursor = any> {+ /**+ * Cursor mode: cursor to the page past `item`, the last cursor-eligible row+ * on the far side, for a server that pages by row but reports no+ * `nextCursor` (a plain list). Only safe when the row carries a lossless+ * position; omit it when the server owns the cursor, and paging then waits+ * for one.+ */+ deriveCursor?: (item: TItem) => TCursor;direction: ReplicaPagingDirection;getId: (item: TItem) => string;+ /**+ * Rows that may anchor a join or derive a cursor. Synthetic rows the query+ * injects (group / summary nodes) have no position of their own on the+ * server, so they are skipped. Defaults to every row.+ */+ isCursorable?: (item: TItem) => boolean;mode: ReplicaPagingMode;/** Which part survives a reload. Defaults to the head page only. */persist?: {@@ -28,7 +42,12 @@ export interface ReplicaPagingConfig<TItem> {/** Number of pages from the head side. Default 1. */pages?: number;};- /** Optional total order re-applied after every merge (e.g. messages by createdAt). */+ /**+ * Optional total order re-applied after every merge (e.g. messages by+ * createdAt). The sort is stable: rows the comparator ties keep the order+ * the server sent them in, so compare positions only β an id tie-break+ * would reorder rows created within the same tick.+ */sort?: (a: TItem, b: TItem) => number;}@@ -60,6 +79,12 @@ export interface ReplicaPagedData<TItem, TCursor = number> {/** Index of the last merged page (0 = head only). */currentPage: number;hasMore: boolean;+ /**+ * Synthetic (non-cursorable) rows of the head page. A sort can place them+ * among older pages, so a head refresh drops them by id rather than by+ * position β the fresh head brings its own.+ */+ headSyntheticIds?: string[];isLoadingMore?: boolean;items: TItem[];loadMoreError?: unknown;@@ -115,11 +140,40 @@ const offsetNext = (more: boolean, nextIndex: number) => (more ? nextIndex : nul*/export const getNextPageCursor = <TItem, TCursor>(data: ReplicaPagedData<TItem, TCursor> | undefined,- config: Pick<ReplicaPagingConfig<TItem>, 'mode'>,+ config: Pick<+ ReplicaPagingConfig<TItem, TCursor>,+ 'deriveCursor' | 'direction' | 'isCursorable' | 'mode'+ >,): TCursor | null | undefined => {if (!data) return undefined;- if (data.nextCursor !== undefined || config.mode !== 'offset') return data.nextCursor;- return (data.hasMore ? (data.currentPage ?? 0) + 1 : null) as TCursor | null;+ if (data.nextCursor !== undefined) return data.nextCursor;+ if (config.mode === 'offset')+ return (data.hasMore ? (data.currentPage ?? 0) + 1 : null) as TCursor | null;+ if (!config.deriveCursor || !data.hasMore) return undefined;+ const boundary = farBoundary(data.items, config);+ return boundary === undefined ? undefined : config.deriveCursor(boundary);+};++/**+ * The boundary row on the far side of `items` (forward: last, backward: first)+ * that may anchor a join or derive a cursor.+ */+const farBoundary = <TItem>(+ items: TItem[],+ config: Pick<ReplicaPagingConfig<TItem>, 'direction' | 'isCursorable'>,+): TItem | undefined => {+ const eligible = config.isCursorable ?? (() => true);+ if (config.direction === 'forward') return items.findLast((item) => eligible(item));+ return items.find((item) => eligible(item));+};++const syntheticIds = <TItem>(+ items: TItem[],+ config: Pick<ReplicaPagingConfig<TItem>, 'getId' | 'isCursorable'>,+): string[] | undefined => {+ if (!config.isCursorable) return undefined;+ const ids = items.filter((item) => !config.isCursorable!(item)).map(config.getId);+ return ids.length ? ids : undefined;};const splitClientOnly = <TItem>(items: TItem[], ctx: ReplicaPagingContext<TItem>) => {@@ -146,7 +200,7 @@ export const applyHeadPage = <TItem, TCursor>(current: ReplicaPagedData<TItem, TCursor> | undefined,page: ReplicaPageResult<TItem, TCursor>,options: { pageSize: number; reset?: boolean },- config: ReplicaPagingConfig<TItem>,+ config: ReplicaPagingConfig<TItem, TCursor>,ctx: ReplicaPagingContext<TItem> = {},): ReplicaPagedData<TItem, TCursor> => {const { getId, direction } = config;@@ -169,6 +223,7 @@ export const applyHeadPage = <TItem, TCursor>(const data = {anchorId: undefined,currentPage: 0,+ headSyntheticIds: syntheticIds(fresh, config),items: ordered(headItems, config),nextCursor,pageSize: options.pageSize,@@ -185,7 +240,10 @@ export const applyHeadPage = <TItem, TCursor>(};const extended = !!current && current.currentPage > 0 && !options.reset;- if (!extended || current.pageSize !== options.pageSize) return headOnly();+ // A cursor walk keys pages by position, so a head page of another length+ // (round-trimmed windows vary on every refresh) still joins by its anchor.+ if (!extended || (config.mode === 'offset' && current.pageSize !== options.pageSize))+ return headOnly();let rest: TItem[];let anchorId: string | undefined;@@ -202,23 +260,28 @@ export const applyHeadPage = <TItem, TCursor>(const anchorIndex = current.anchorId? currentServer.findIndex((item) => getId(item) === current.anchorId): -1;- if (anchorIndex === -1 || !freshIds.has(current.anchorId!) || current.nextCursor === undefined)- return headOnly();+ // Without a known next cursor the loaded pages can only be kept when the+ // cursor is derivable from the rows themselves.+ const cursorKnown = current.nextCursor !== undefined || !!config.deriveCursor;+ if (anchorIndex === -1 || !freshIds.has(current.anchorId!) || !cursorKnown) return headOnly();const farSide =direction === 'forward'? currentServer.slice(anchorIndex + 1): currentServer.slice(0, anchorIndex);- rest = farSide.filter((item) => !freshIds.has(getId(item)));- const boundary = direction === 'forward' ? fresh.at(-1) : fresh[0];+ const staleHead = new Set(current.headSyntheticIds);+ rest = farSide.filter((item) => !freshIds.has(getId(item)) && !staleHead.has(getId(item)));+ const boundary = farBoundary(fresh, config);anchorId = boundary ? getId(boundary) : current.anchorId;}+ const headNext = config.mode === 'cursor' ? page.nextCursor : current.pages?.[0]?.next;const pages = current.pages?.length- ? [{ ...current.pages[0], count: fresh.length }, ...current.pages.slice(1)]- : [{ count: fresh.length, next: current.nextCursor }];+ ? [{ count: fresh.length, next: headNext }, ...current.pages.slice(1)]+ : [{ count: fresh.length, next: headNext }];const data = {anchorId: anchorId ?? current.anchorId,currentPage: current.currentPage,+ headSyntheticIds: syntheticIds(fresh, config),items: ordered(join(headItems, rest, direction), config),nextCursor: current.nextCursor,pageSize: options.pageSize,@@ -237,7 +300,7 @@ export const applyHeadPage = <TItem, TCursor>(export const applyNextPage = <TItem, TCursor>(current: ReplicaPagedData<TItem, TCursor>,page: ReplicaPageResult<TItem, TCursor>,- config: ReplicaPagingConfig<TItem>,+ config: ReplicaPagingConfig<TItem, TCursor>,ctx: ReplicaPagingContext<TItem> = {},): ReplicaPagedData<TItem, TCursor> => {const { getId, direction } = config;@@ -258,8 +321,7 @@ export const applyNextPage = <TItem, TCursor>(// The first extension pins the join anchor at the head page's boundary.let anchorId = current.anchorId;if (current.currentPage === 0) {- const server = splitClientOnly(current.items, ctx).server;- const boundary = direction === 'forward' ? server.at(-1) : server[0];+ const boundary = farBoundary(splitClientOnly(current.items, ctx).server, config);anchorId = boundary ? getId(boundary) : undefined;}@@ -292,7 +354,7 @@ export const applyNextPage = <TItem, TCursor>(export const insertHeadItems = <TItem, TCursor>(current: ReplicaPagedData<TItem, TCursor>,items: TItem[],- config: ReplicaPagingConfig<TItem>,+ config: ReplicaPagingConfig<TItem, TCursor>,): ReplicaPagedData<TItem, TCursor> => {const seen = new Set(current.items.map(config.getId));const added = dedupe(items, config.getId, seen);@@ -342,16 +404,40 @@ export const hasPagedItem = <TItem>(config: Pick<ReplicaPagingConfig<TItem>, 'getId'>,) => !!data?.items.some((item) => config.getId(item) === id);+/** Select head-side rows without losing synthetic head rows sorted among older pages. */+const takeHeadItems = <TItem, TCursor>(+ items: TItem[],+ count: number,+ data: ReplicaPagedData<TItem, TCursor>,+ config: ReplicaPagingConfig<TItem, TCursor>,+): TItem[] => {+ if (count === 0) return [];+ const synthetic = new Set(data.headSyntheticIds);+ const syntheticCount = items.filter((item) => synthetic.has(config.getId(item))).length;+ const regular = items.filter((item) => !synthetic.has(config.getId(item)));+ const regularCount = Math.max(0, count - syntheticCount);+ const selected =+ config.direction === 'forward'+ ? regular.slice(0, regularCount)+ : regular.slice(Math.max(0, regular.length - regularCount));+ const ids = new Set(selected.map(config.getId));+ return items+ .filter((item) => synthetic.has(config.getId(item)) || ids.has(config.getId(item)))+ .slice(+ config.direction === 'forward' ? 0 : -count,+ config.direction === 'forward' ? count : undefined,+ );+};+/** Drop every loaded page but the head (e.g. after an edit inside older history). */export const collapseToHead = <TItem, TCursor>(current: ReplicaPagedData<TItem, TCursor>,- config: ReplicaPagingConfig<TItem>,+ config: ReplicaPagingConfig<TItem, TCursor>,): ReplicaPagedData<TItem, TCursor> => {if (current.currentPage === 0) return current;const head = current.pages?.[0];const count = head?.count ?? current.pageSize;- const items =- config.direction === 'forward' ? current.items.slice(0, count) : current.items.slice(-count);+ const items = takeHeadItems(current.items, count, current, config);const nextCursor = config.mode === 'offset' ? (1 as TCursor) : (head?.next ?? undefined);return {...current,@@ -373,7 +459,7 @@ export const collapseToHead = <TItem, TCursor>(*/export const toPersistedPage = <TItem, TCursor, TData extends ReplicaPagedData<TItem, TCursor>>(data: TData,- config: ReplicaPagingConfig<TItem>,+ config: ReplicaPagingConfig<TItem, TCursor>,ctx: ReplicaPagingContext<TItem> = {},): TData => {const { server } = splitClientOnly(data.items, ctx);@@ -403,8 +489,7 @@ export const toPersistedPage = <TItem, TCursor, TData extends ReplicaPagedData<Tcount = Math.min(count, server.length);}- const items =- config.direction === 'forward' ? server.slice(0, count) : server.slice(server.length - count);+ const items = takeHeadItems(server, count, data, config);const lastKept = pages[keptPages - 1];const nextCursor =config.mode === 'offset'diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.tsindex f135da9adea..e938fc13540 100644--- a/packages/replica/src/core/types.ts+++ b/packages/replica/src/core/types.ts@@ -70,17 +70,19 @@ export interface ReplicaState<T> {scope?: string;}-export interface ReplicaResource<TParams, TData, TFetched = TData> {+export interface ReplicaResource<TParams, TData, TFetched = TData, TCursor = any> {/** Paged resources receive the page cursor (`undefined` = head page). */- fetcher?: (params: TParams, cursor?: any) => Promise<TFetched>;+ fetcher?: (params: TParams, cursor?: TCursor) => Promise<TFetched>;key: (params: TParams) => string;name: string;/** Storage namespace β `name` + `version`, so a version bump orphans old rows. */namespace: string;/** Present on paged resources (`definePagedReplica`). */- paging?: ReplicaPagingConfig<any>;+ paging?: ReplicaPagingConfig<any, TCursor>;/** Whether the resource survives a reload (it has a storage). */persisted: boolean;+ /** Whether an entry key may be hydrated and persisted (see `persistKey`). */+ persistKey: (key: string) => boolean;/*** Query identity beyond `key` (filters, page size). Persisted rows are* stored per query, so a different query never hydrates; in memory a querydiff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsindex 2f13b1c2fff..1a3a9575864 100644--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ b/packages/replica/src/zustand/createReplicaSlice.ts@@ -2,6 +2,7 @@ import { useLayoutEffect } from 'react';import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';import { isReplicaSyncKey, replicaKeys } from '../core/keys';+import type { ReplicaPagedData } from '../core/paging';import type { ReplicaViewWrite } from '../core/reducer';import type { ReplicaResource, ReplicaState } from '../core/types';import type { ReplicaSyncDriver, ReplicaSyncSchedule } from './driver';@@ -124,7 +125,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(}, [active, scope]);const hydration = driver.useQuery<boolean>(- active && resource.persisted+ active && resource.persisted && resource.persistKey(key!)? replicaKeys.hydrate(resource.name, resource.version, scope, resource.storageKey(params!)): null,async () => {@@ -151,7 +152,10 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(return {error: sync.error,- isHydrated: !resource.persisted || hydration.data === true,+ isHydrated:+ !resource.persisted ||+ (key !== undefined && !resource.persistKey(key)) ||+ hydration.data === true,isValidating: sync.isValidating,revalidate: () => sync.mutate(),};@@ -178,3 +182,77 @@ export const recordLens = <TStore, TData>(return { [field]: next } as Partial<TStore>;},});++/**+ * Lens for a paged view split across store fields: the rows stay where+ * existing readers expect them (`itemsField[key]`, a plain array), the paging+ * bookkeeping lives in `metaField[key]`, and `derive` recomputes fields built+ * from the rows (e.g. a parsed display list) in the same commit β so a derived+ * field is never one frame behind its rows.+ *+ * Rows seeded without bookkeeping (by code outside the replica) read as a+ * single head page.+ */+export const splitPagedLens = <TStore, TItem, TCursor = unknown>({+ clearDerived,+ derive,+ itemsField,+ metaField,+}: {+ /** Derived fields to reset on a scope change. */+ clearDerived?: () => Partial<TStore>;+ /** Fields computed from an entry's rows (`undefined` = the entry is gone). */+ derive?: (state: TStore, key: string, items: TItem[] | undefined) => Partial<TStore>;+ itemsField: keyof TStore & string;+ metaField: keyof TStore & string;+}): ReplicaLens<TStore, ReplicaPagedData<TItem, TCursor>> => {+ type Meta = Omit<ReplicaPagedData<TItem, TCursor>, 'items'>;+ const NO_META = {} as Meta;+ // Same rows + same bookkeeping β the same view object, so the engine's+ // reference checks see "unchanged".+ const views = new WeakMap<TItem[], WeakMap<Meta, ReplicaPagedData<TItem, TCursor>>>();+ const remember = (items: TItem[], meta: Meta, view: ReplicaPagedData<TItem, TCursor>) => {+ let byMeta = views.get(items);+ if (!byMeta) views.set(items, (byMeta = new WeakMap()));+ byMeta.set(meta, view);+ return view;+ };+ const rowsOf = (state: TStore) => (state[itemsField] ?? {}) as Record<string, TItem[]>;+ const metaOf = (state: TStore) => (state[metaField] ?? {}) as Record<string, Meta>;++ return {+ clear: () => ({ [itemsField]: {}, [metaField]: {}, ...clearDerived?.() }) as Partial<TStore>,+ get: (state, key) => {+ const items = rowsOf(state)[key];+ if (!items) return undefined;+ const meta = metaOf(state)[key] ?? NO_META;+ const cached = views.get(items)?.get(meta);+ if (cached) return cached;+ const view =+ meta === NO_META+ ? { currentPage: 0, hasMore: true, items, pageSize: items.length }+ : { ...meta, items };+ return remember(items, meta, view);+ },+ keys: (state) => Object.keys(rowsOf(state)),+ set: (state, key, data) => {+ const rows = { ...rowsOf(state) };+ const metas = { ...metaOf(state) };+ if (data === undefined) {+ delete rows[key];+ delete metas[key];+ } else {+ const { items, ...meta } = data;+ rows[key] = items;+ metas[key] = meta;+ remember(items, meta, data);+ }+ const next = { ...state, [itemsField]: rows, [metaField]: metas } as TStore;+ return {+ [itemsField]: rows,+ [metaField]: metas,+ ...derive?.(next, key, data?.items),+ } as Partial<TStore>;+ },+ };+};diff --git a/packages/replica/src/zustand/splitPagedLens.test.ts b/packages/replica/src/zustand/splitPagedLens.test.tsnew file mode 100644index 00000000000..bfbee71f1cc--- /dev/null+++ b/packages/replica/src/zustand/splitPagedLens.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { testDriver as driver } from '../../tests/testDriver';+import { definePagedReplica } from '../core/defineReplica';+import type { ReplicaPagedData } from '../core/paging';+import { createReplicaState } from '../core/reducer';+import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';+import { createReplicaSlice, splitPagedLens } from './createReplicaSlice';++/**+ * A transcript-shaped host: raw rows in `rowsMap` (what existing readers use),+ * paging bookkeeping beside them, and a display list derived from the rows.+ */+interface Message {+ createdAt: number;+ id: string;+}+interface TestState {+ displayMap: Record<string, string[]>;+ pagingMap: Record<string, Omit<ReplicaPagedData<Message, number>, 'items'>>;+ replica: ReplicaState<ReplicaPagedData<Message, number>>;+ rowsMap: Record<string, Message[]>;+}++const scope: ReplicaScope = { canPersist: () => true, get: () => 'u1', use: () => 'u1' };++const memoryStorage = () => {+ const rows = new Map<string, ReplicaRow<any>>();+ const storage: ReplicaStorage<any> = {+ get: async ({ queryKey, scope }) => rows.get(`${scope}|${queryKey}`),+ remove: async ({ queryKey, scope }) => void rows.delete(`${scope}|${queryKey}`),+ set: async ({ queryKey, scope }, row) => void rows.set(`${scope}|${queryKey}`, row),+ };+ return { rows, storage };+};++const msg = (n: number): Message => ({ createdAt: n, id: `m${n}` });+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++const setup = () => {+ const { rows, storage } = memoryStorage();+ const resource = definePagedReplica<{ topic: string }, Message, number>({+ key: ({ topic }) => topic,+ name: 'transcript',+ paging: { direction: 'backward', getId: (m) => m.id, mode: 'cursor' },+ // Scoped buckets (e.g. a page copilot) stay in memory.+ persistKey: (key) => !key.startsWith('scoped:'),+ scope,+ storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ displayMap: {},+ pagingMap: {},+ replica: createReplicaState(),+ rowsMap: {},+ }));+ const slice = createReplicaSlice(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'replica',+ view: splitPagedLens<TestState, Message, number>({+ clearDerived: () => ({ displayMap: {} }),+ derive: (state, key, items) => {+ const displayMap = { ...state.displayMap };+ if (items) displayMap[key] = items.map((m) => m.id.toUpperCase());+ else delete displayMap[key];+ return { displayMap };+ },+ itemsField: 'rowsMap',+ metaField: 'pagingMap',+ }),+ });+ return { rows, slice, store };+};++describe('splitPagedLens', () => {+ it('keeps raw rows, bookkeeping and the derived list in step', () => {+ const { slice, store } = setup();++ slice.replace({ topic: 't1' }, { items: [msg(1), msg(2)], nextCursor: 1 });++ const state = store.getState();+ expect(state.rowsMap.t1.map((m) => m.id)).toEqual(['m1', 'm2']);+ expect(state.pagingMap.t1).toMatchObject({ currentPage: 0, nextCursor: 1 });+ expect(state.displayMap.t1).toEqual(['M1', 'M2']);+ });++ it('reads an unchanged entry as the same view object', () => {+ const { slice, store } = setup();+ slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });+ const before = store.getState().rowsMap;++ // Folding the identical page in again is a no-op for readers.+ slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });+ slice.update('t1', (data) => data);++ expect(store.getState().rowsMap).toBe(before);+ });++ it('treats rows seeded without bookkeeping as a head page', () => {+ const { slice, store } = setup();+ store.setState({ rowsMap: { t1: [msg(1)] } });++ slice.updateEntity<Message>('m1', (m) => ({ ...m, createdAt: 9 }), { persist: false });++ expect(store.getState().rowsMap.t1[0].createdAt).toBe(9);+ expect(store.getState().displayMap.t1).toEqual(['M1']);+ });++ it('drops derived fields with the entry', () => {+ const { slice, store } = setup();+ slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });++ slice.remove('t1');+ expect(store.getState().displayMap.t1).toBeUndefined();+ expect(store.getState().rowsMap.t1).toBeUndefined();+ });+});++describe('persistKey and persist()', () => {+ it('never persists or hydrates a key the resource keeps in memory', async () => {+ const { rows, slice } = setup();++ slice.replace({ topic: 'scoped:page-1' }, { items: [msg(1)], nextCursor: null });+ slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });+ await flush();++ expect(rows.has('u1|scoped:page-1')).toBe(false);+ expect(rows.has('u1|t1')).toBe(true);+ expect(await slice.hydrate({ topic: 'scoped:page-1' })).toBe(false);+ });++ it('flushes in-memory writes (a finished stream) in one persist', async () => {+ const { rows, slice } = setup();+ slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });+ await flush();++ for (const n of [2, 3, 4]) slice.insertHead('t1', [msg(n)]);+ await flush();+ expect(rows.get('u1|t1')?.data.items).toHaveLength(1);++ slice.persist('t1');+ await flush();+ expect(rows.get('u1|t1')?.data.items.map((m: Message) => m.id)).toEqual([+ 'm1',+ 'm2',+ 'm3',+ 'm4',+ ]);+ });+});diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex e6927ef9bab..7d3e3d94c19 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -104,4 +104,9 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>() => createCoreReplicaSlice(resource, { driver: replicaSWRDriver, ...options });export * from '@lobechat/replica';-export { recordLens, type ReplicaLens, type ReplicaSyncResult } from '@lobechat/replica/zustand';+export {+ recordLens,+ type ReplicaLens,+ type ReplicaSyncResult,+ splitPagedLens,+} from '@lobechat/replica/zustand';