Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(file): move the resource explorer list onto @lobechat/replica (#20608)

Arvin Xu49f1b880e598
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index 94aca68e07b..de06f9ed3bf 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -449,7 +449,34 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return entry?.pending.length ? entry.base : port.read(key);
};
- const hydrate = async (params: TParams, scope = resource.scope.get()) => {
+ /**
+ * An overwrite hydrate repaints the entry from another query's persisted page.
+ * Client-only rows (an in-flight upload / create) have no server row yet, so
+ * that page cannot contain them β€” keep the ones still in the view, so a
+ * same-pool query change (a re-sort, a view-mode switch) never drops them.
+ * A cross-pool navigate is not "client-only" for the new params and is dropped.
+ */
+ const keepClientOnlyRows = (incoming: TData, current: TData | undefined): TData => {
+ if (!paging || !options.isClientOnly || !current) return incoming;
+ const page = incoming as unknown as ReplicaPagedData<unknown, unknown>;
+ const currentItems = (current as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];
+ const incomingIds = new Set(page.items.map((item) => paging.getId(item)));
+ const survivors = currentItems.filter(
+ (item) => options.isClientOnly!(item) && !incomingIds.has(paging.getId(item)),
+ );
+ if (survivors.length === 0) return incoming;
+ const items =
+ paging.direction === 'forward'
+ ? [...survivors, ...page.items]
+ : [...page.items, ...survivors];
+ return { ...(incoming as object), items } as TData;
+ };
+
+ const hydrate = async (
+ params: TParams,
+ scope = resource.scope.get(),
+ { overwrite = false }: { overwrite?: boolean } = {},
+ ) => {
if (!resource.storage) return false;
// An identity-less runtime reads network-only: its scope is a guess, so
// hydrating it could paint another session's private rows.
@@ -465,7 +492,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
pendingHydrates.set(scope, pending);
pending.add(start);
try {
- return await readAndHydrate(params, key, scope);
+ return await readAndHydrate(params, key, scope, overwrite);
} finally {
pending.delete(start);
if (pending.size === 0) pendingHydrates.delete(scope);
@@ -473,7 +500,12 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
}
};
- const readAndHydrate = async (params: TParams, key: string, scope: string) => {
+ const readAndHydrate = async (
+ params: TParams,
+ key: string,
+ scope: string,
+ overwrite: boolean,
+ ) => {
const storage = resource.storage!;
// A read started before a `clear()` of this scope holds a wiped row.
const generation = clearGeneration(scope);
@@ -488,11 +520,13 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
if (isRemoved(scope, key) || clearGeneration(scope) !== generation) return false;
if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;
// Entities deleted while the read was in flight may still be in the row.
- const data = withoutRemovedEntities(scope, cached.data);
- if (data === undefined) return false;
+ const stored = withoutRemovedEntities(scope, cached.data);
+ if (stored === undefined) return false;
+ const data = overwrite ? keepClientOnlyRows(stored, port.read(key)) : stored;
return dispatch({
data,
key,
+ overwrite,
params,
query,
scope,
@@ -683,14 +717,29 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const revalidate = (key?: string): Promise<unknown> =>
options.revalidate ? options.revalidate(key) : Promise.resolve();
- /** Start an optimistic overlay now and settle it later (multi-resource flows). */
+ /**
+ * Start an optimistic overlay now and settle it later (multi-resource flows).
+ * `query` tags the overlay with the query it describes; a caller that knows
+ * the requested query (e.g. before the first page painted) should pass it, so
+ * the overlay is scoped to that query rather than kept across every change.
+ */
const beginOptimistic = (
key: string,
apply: (data: TData) => TData,
+ query?: string,
): ReplicaOptimisticToken<TData> => {
const scope = resource.scope.get();
const id = ++mutationSeq;
- dispatch({ apply, id, key, scope, type: 'optimistic' });
+ // Tag the overlay with the query it describes: the entry may move on to
+ // another query (or another query may reuse the key) before it settles.
+ dispatch({
+ apply,
+ id,
+ key,
+ query: query ?? getSlot().entries[key]?.query,
+ scope,
+ type: 'optimistic',
+ });
return {
commit: (confirm) => {
dispatch({ confirm, id, key, scope, type: 'commit' });
@@ -904,6 +953,56 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
await Promise.all(patches);
};
+ /**
+ * Read-modify-write the persisted rows memory does not hold, keyed by row
+ * rather than by entity: a cached list for a folder the user is not viewing
+ * gets its projection patched in the per-key write queue, so a later visit
+ * hydrates the reconciled value instead of a stale page. `fn` returns the
+ * next data, the same reference (or `undefined`) to skip, or `null` to drop
+ * the row. Runs in the write queue, so it sees every earlier write.
+ */
+ const patchStoredRows = async (fn: (data: TData) => TData | null | undefined): Promise<void> => {
+ if (!writeQueue || !resource.scope.canPersist()) return;
+ const scope = resource.scope.get();
+ const slot = getSlot();
+ const loaded = new Set(
+ slot.scope === scope
+ ? Object.entries(slot.entries).map(([key, entry]) => storageKey(key, entry.query).queryKey)
+ : [],
+ );
+ let keys: string[];
+ try {
+ keys = await readIndex(scope);
+ } catch (error) {
+ console.error(`[replica:${resource.name}] failed to read the persisted index`, error);
+ return;
+ }
+ // Identity changed while reading the index: those rows are not ours to touch.
+ if (resource.scope.get() !== scope) return;
+ const patches: Promise<void>[] = [];
+ for (const queryKey of keys) {
+ if (loaded.has(queryKey)) continue;
+ const seq = noteWrite(scope, queryKey);
+ let dropped = false;
+ const patch = writeQueue
+ .update({ queryKey, scope }, (current) => {
+ if (!current) return undefined;
+ const next = fn(current.data);
+ if (next === current.data || next === undefined) return undefined;
+ if (next === null) {
+ dropped = true;
+ return null;
+ }
+ return { data: next, updatedAt: Date.now() };
+ })
+ .then((written) => {
+ if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);
+ });
+ patches.push(patch);
+ }
+ await Promise.all(patches);
+ };
+
/** `updateEntity`, returning the persisted-row patch (if any) to wait on. */
const applyEntity = <TItem>(
id: string,
@@ -986,6 +1085,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
loadMore,
optimistic,
patchStoredEntity,
+ patchStoredRows,
persist,
remove,
removeEntity,
diff --git a/packages/replica/src/core/paging.test.ts b/packages/replica/src/core/paging.test.ts
index 74623c2a85c..43a2f3b9e60 100644
--- a/packages/replica/src/core/paging.test.ts
+++ b/packages/replica/src/core/paging.test.ts
@@ -144,6 +144,43 @@ describe('offset / forward paging (topic-like list)', () => {
expect(getNextPageCursor({ ...legacy, hasMore: false }, offset)).toBeNull();
});
+ describe('server-reported exhaustion (rows filtered after paging)', () => {
+ it('keeps paging past a short page the server says is not the end', () => {
+ // The server consumed a full raw window of 3 but filtered one row out.
+ const head = applyHeadPage(
+ undefined,
+ { items: rows('a', 'b'), nextCursor: 1 },
+ { pageSize: 3 },
+ offset,
+ );
+ expect(head).toMatchObject({ currentPage: 0, hasMore: true, nextCursor: 1 });
+
+ const next = applyNextPage(head, { items: rows('c'), nextCursor: 2 }, offset);
+ expect(next).toMatchObject({ currentPage: 1, hasMore: true, nextCursor: 2 });
+
+ const last = applyNextPage(next, { items: rows('d', 'e', 'f'), nextCursor: null }, offset);
+ expect(last).toMatchObject({ currentPage: 2, hasMore: false, nextCursor: null });
+ });
+
+ it('persists the server verdict for a short head page', () => {
+ const head = applyHeadPage(
+ undefined,
+ { items: rows('a', 'b'), nextCursor: 1 },
+ { pageSize: 3 },
+ offset,
+ );
+ expect(toPersistedPage(head, offset)).toMatchObject({ hasMore: true, nextCursor: 1 });
+
+ const done = applyHeadPage(
+ undefined,
+ { items: rows('a', 'b'), nextCursor: null },
+ { pageSize: 3 },
+ offset,
+ );
+ expect(toPersistedPage(done, offset)).toMatchObject({ hasMore: false, nextCursor: null });
+ });
+ });
+
describe('persistence limits', () => {
it('persists the head page only by default, without flags or client-only rows', () => {
const data = { ...insertHeadItems(twoPages(), rows('tmp'), offset), isLoadingMore: true };
diff --git a/packages/replica/src/core/paging.ts b/packages/replica/src/core/paging.ts
index c6bd8a75d0d..ec3176e4a5e 100644
--- a/packages/replica/src/core/paging.ts
+++ b/packages/replica/src/core/paging.ts
@@ -53,7 +53,13 @@ export interface ReplicaPagingConfig<TItem, TCursor = any> {
export interface ReplicaPageResult<TItem, TCursor> {
items: TItem[];
- /** Cursor mode: next page cursor; `null` = exhausted, `undefined` = unknown. */
+ /**
+ * Cursor mode: next page cursor; `null` = exhausted, `undefined` = unknown.
+ * Offset mode: the server's own verdict β€” `null` = exhausted, any other
+ * value = more pages (the engine still advances by page index); `undefined`
+ * falls back to `total` / a full page. A server that filters rows after
+ * paging returns short pages that are not the end, so it must report this.
+ */
nextCursor?: TCursor | null;
total?: number;
}
@@ -133,6 +139,17 @@ const deriveHasMore = <TItem, TCursor>(
const offsetNext = (more: boolean, nextIndex: number) => (more ? nextIndex : null);
+/** Offset mode: whether a page past the loaded ones exists. */
+const offsetHasMore = <TItem, TCursor>(
+ page: ReplicaPageResult<TItem, TCursor>,
+ total: number | undefined,
+ serverCount: number,
+ pageSize: number,
+) => {
+ if (page.nextCursor !== undefined) return page.nextCursor !== null;
+ return total !== undefined ? total > serverCount : page.items.length >= pageSize;
+};
+
/**
* Cursor to request the next page with; `null` β†’ exhausted, `undefined` β†’
* cannot page yet. Offset views without bookkeeping (seeded by legacy code or
@@ -216,7 +233,7 @@ export const applyHeadPage = <TItem, TCursor>(
const nextCursor =
config.mode === 'offset'
? (offsetNext(
- total !== undefined ? total > fresh.length : fresh.length >= options.pageSize,
+ offsetHasMore(page, total, fresh.length, options.pageSize),
1,
) as TCursor | null)
: page.nextCursor;
@@ -318,7 +335,7 @@ export const applyNextPage = <TItem, TCursor>(
let next: TCursor | null | undefined;
if (config.mode === 'offset') {
- const more = total !== undefined ? total > serverCount : page.items.length >= current.pageSize;
+ const more = offsetHasMore(page, total, serverCount, current.pageSize);
next = offsetNext(more, current.currentPage + 2) as TCursor | null;
} else {
// Only an empty page marks the end when the server reports no cursor.
@@ -506,7 +523,12 @@ export const toPersistedPage = <TItem, TCursor, TData extends ReplicaPagedData<T
const lastKept = pages[keptPages - 1];
const nextCursor =
config.mode === 'offset'
- ? ((count < (data.total ?? server.length) ? keptPages : null) as TCursor | null)
+ ? ((count < (data.total ?? server.length) ||
+ // Every loaded row survives: the server's own verdict on the page past
+ // them still holds (a filtered short page is not necessarily the end).
+ (count === server.length && data.total === undefined && data.nextCursor != null)
+ ? keptPages
+ : null) as TCursor | null)
: aligned
? lastKept?.next
: undefined;
diff --git a/packages/replica/src/core/reducer.test.ts b/packages/replica/src/core/reducer.test.ts
index 3006baa719c..7ce75dccc45 100644
--- a/packages/replica/src/core/reducer.test.ts
+++ b/packages/replica/src/core/reducer.test.ts
@@ -66,6 +66,70 @@ describe('replicaReducer', () => {
expect(h.view.k).toEqual(['memory']);
});
+ it('repaints a slot answering another query when the caller asks to overwrite', () => {
+ const h = createHarness();
+ h.run({ data: ['query-1'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });
+
+ h.run({
+ data: ['query-2'],
+ key: 'k',
+ overwrite: true,
+ params: 2,
+ query: 'q2',
+ scope: S,
+ type: 'hydrate',
+ });
+
+ expect(h.view.k).toEqual(['query-2']);
+ expect(h.state.entries.k.query).toBe('q2');
+ expect(h.state.entries.k.source).toBe('storage');
+ expect(h.effects).toEqual([]);
+ });
+
+ it('keeps the slot when the overwriting hydrate asks for the query it already answers', () => {
+ const h = createHarness();
+ h.run({
+ data: () => ['server'],
+ key: 'k',
+ params: 1,
+ query: 'q1',
+ scope: S,
+ type: 'replace',
+ });
+
+ const transition = h.run({
+ data: ['stale-cache'],
+ key: 'k',
+ overwrite: true,
+ params: 1,
+ query: 'q1',
+ scope: S,
+ type: 'hydrate',
+ });
+
+ expect(h.view.k).toEqual(['server']);
+ expect(transition.writes).toEqual([]);
+ });
+
+ it('never clobbers an in-flight optimistic write, even with overwrite', () => {
+ const h = createHarness();
+ h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });
+ h.run({ apply: append('opt'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+
+ h.run({
+ data: ['b'],
+ key: 'k',
+ overwrite: true,
+ params: 2,
+ query: 'q2',
+ scope: S,
+ type: 'hydrate',
+ });
+
+ expect(h.view.k).toEqual(['a', 'opt']);
+ expect(h.state.entries.k.query).toBe('q1');
+ });
+
it('replace overwrites hydrated data and persists it', () => {
const h = createHarness();
h.run({ data: ['cached'], key: 'k', scope: S, type: 'hydrate' });
@@ -229,4 +293,107 @@ describe('replicaReducer', () => {
expect(h.effects).toEqual([{ key: 'k', scope: S, type: 'remove' }]);
});
});
+
+ describe('optimistic overlay query affinity', () => {
+ it('does not carry an overlay into another query, and its commit stays out', () => {
+ const h = createHarness();
+ h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });
+ h.run({
+ apply: append('pending-a'),
+ id: 1,
+ key: 'k',
+ query: 'q1',
+ scope: S,
+ type: 'optimistic',
+ });
+ expect(h.view.k).toEqual(['a', 'pending-a']);
+
+ // The key is reused for another query while the overlay is in flight.
+ h.run({
+ data: (basis) => [...(basis ?? []), 'b'],
+ key: 'k',
+ params: 2,
+ query: 'q2',
+ scope: S,
+ type: 'replace',
+ });
+
+ // The overlay described q1, so it must not surface under q2 ...
+ expect(h.view.k).toEqual(['a', 'b']);
+ expect(h.state.entries.k.pending).toEqual([]);
+
+ // ... and settling it later must not insert q1's row into q2.
+ h.run({ confirm: append('created-a'), id: 1, key: 'k', scope: S, type: 'commit' });
+ expect(h.view.k).toEqual(['a', 'b']);
+ });
+
+ it('still rebases a same-query overlay onto the fresh server value', () => {
+ const h = createHarness();
+ h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });
+ h.run({
+ apply: append('pending'),
+ id: 1,
+ key: 'k',
+ query: 'q1',
+ scope: S,
+ type: 'optimistic',
+ });
+
+ h.run({
+ data: (basis) => [...(basis ?? []), 'server'],
+ key: 'k',
+ params: 1,
+ query: 'q1',
+ scope: S,
+ type: 'replace',
+ });
+
+ expect(h.view.k).toEqual(['a', 'server', 'pending']);
+ expect(h.state.entries.k.pending).toHaveLength(1);
+ });
+
+ it('keeps an untagged overlay: its query cannot be proven different', () => {
+ const h = createHarness({ k: ['a'] });
+ h.run({ apply: append('untagged'), id: 1, key: 'k', scope: S, type: 'optimistic' });
+
+ h.run({
+ data: (basis) => [...(basis ?? []), 'b'],
+ key: 'k',
+ params: 2,
+ query: 'q2',
+ scope: S,
+ type: 'replace',
+ });
+
+ // Rebased onto the fresh value, exactly as before query affinity existed.
+ expect(h.view.k).toEqual(['a', 'b', 'untagged']);
+ expect(h.state.entries.k.pending).toHaveLength(1);
+ });
+
+ it('lets a navigation hydrate repaint over the query being left', () => {
+ const h = createHarness();
+ h.run({ data: ['a'], key: 'k', params: 1, query: 'q1', scope: S, type: 'hydrate' });
+ h.run({
+ apply: append('pending-a'),
+ id: 1,
+ key: 'k',
+ query: 'q1',
+ scope: S,
+ type: 'optimistic',
+ });
+
+ h.run({
+ data: ['b-cached'],
+ key: 'k',
+ overwrite: true,
+ params: 2,
+ query: 'q2',
+ scope: S,
+ type: 'hydrate',
+ });
+
+ expect(h.view.k).toEqual(['b-cached']);
+ expect(h.state.entries.k.pending).toEqual([]);
+ });
+ });
});
diff --git a/packages/replica/src/core/reducer.ts b/packages/replica/src/core/reducer.ts
index 3ab49229903..48d0215ff0e 100644
--- a/packages/replica/src/core/reducer.ts
+++ b/packages/replica/src/core/reducer.ts
@@ -13,6 +13,13 @@ export type ReplicaAction<T> =
| {
data: T;
key: string;
+ /**
+ * Repaint a slot that answers a *different* query from the persisted page
+ * (a navigation). Only the caller that knows the entry has moved on
+ * (the requested query changed) may ask for it; by default a hydrate only
+ * fills an empty slot.
+ */
+ overwrite?: boolean;
params?: unknown;
query?: string;
scope: string;
@@ -35,7 +42,15 @@ export type ReplicaAction<T> =
scope: string;
type: 'update';
}
- | { apply: (data: T) => T; id: number; key: string; scope: string; type: 'optimistic' }
+ | {
+ apply: (data: T) => T;
+ id: number;
+ key: string;
+ /** Query the overlay is started under (see `ReplicaPendingMutation`). */
+ query?: string;
+ scope: string;
+ type: 'optimistic';
+ }
| { confirm?: (data: T) => T; id: number; key: string; scope: string; type: 'commit' }
| { id: number; key: string; scope: string; type: 'rollback' }
| { key: string; scope: string; type: 'remove' }
@@ -103,8 +118,21 @@ export const replicaReducer = <T>(
switch (action.type) {
case 'hydrate': {
// Hydrate only fills an empty slot: a server-confirmed value, an
- // optimistic write or any local write always wins over storage.
- if (entry || view !== undefined) return noop(state);
+ // optimistic write or any local write always wins over storage. A caller
+ // that knows the slot answers a *different* query (a navigation) may ask
+ // to repaint it from that query's persisted page instead β€” the overlays it
+ // drops belong to the query being left. An overlay whose query is unknown
+ // still wins: we cannot prove it is not this query's.
+ if (entry) {
+ if (
+ !action.overwrite ||
+ entry.query === action.query ||
+ entry.pending.some((mutation) => mutation.query === undefined)
+ )
+ return noop(state);
+ } else if (view !== undefined) {
+ return noop(state);
+ }
return {
effects: [],
state: withEntry({
@@ -119,8 +147,16 @@ export const replicaReducer = <T>(
}
case 'replace': {
- const pending = entry?.pending ?? [];
- const next = action.data(confirmed) ?? confirmed;
+ // An overlay only describes the query it was started under, so a replace
+ // for another query drops it instead of reapplying it: its base belongs to
+ // the old query, and a later commit would insert that query's row here.
+ const pending = (entry?.pending ?? []).filter(
+ (mutation) => mutation.query === undefined || mutation.query === action.query,
+ );
+ // The merge basis under a query change is the old query's confirmed value
+ // (never the view, which may still carry a dropped overlay).
+ const basis = entry && entry.query !== action.query ? (entry.base ?? view) : confirmed;
+ const next = action.data(basis) ?? basis;
const query = 'query' in action ? action.query : entry?.query;
const nextState = withEntry({
base: pending.length ? next : undefined,
@@ -164,7 +200,10 @@ export const replicaReducer = <T>(
case 'optimistic': {
if (view === undefined) return noop(state);
- const pending = [...(entry?.pending ?? []), { apply: action.apply, id: action.id }];
+ const pending = [
+ ...(entry?.pending ?? []),
+ { apply: action.apply, id: action.id, query: action.query },
+ ];
return {
effects: [],
state: withEntry({
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
index 48feca6be14..47e8a9d5aef 100644
--- a/packages/replica/src/core/types.ts
+++ b/packages/replica/src/core/types.ts
@@ -70,6 +70,13 @@ export interface ReplicaScope {
export interface ReplicaPendingMutation<T> {
apply: (data: T) => T;
id: number;
+ /**
+ * Query the overlay was started under. An entry key can be reused for another
+ * query (a navigation), and an overlay only ever describes the query that
+ * created it β€” carrying it over would apply (and later persist) one query's
+ * row inside another.
+ */
+ query?: string;
}
export interface ReplicaEntryMeta<T> {
diff --git a/src/features/ResourceManager/components/Explorer/isQueryNavigation.ts b/src/features/ResourceManager/components/Explorer/isQueryNavigation.ts
index ec5d74efe3f..82816509163 100644
--- a/src/features/ResourceManager/components/Explorer/isQueryNavigation.ts
+++ b/src/features/ResourceManager/components/Explorer/isQueryNavigation.ts
@@ -1,29 +1,14 @@
+import { RESOURCE_POOL_KEYS } from '@/store/file/slices/resource/utils';
import type { ResourceQueryParams } from '@/types/resource';
-/**
- * Query fields that select a different *pool* of resources rather than a
- * different arrangement of the same one. Changing any of them is a navigation:
- * the rows on screen stop being an answer to the question now being asked, so
- * the views show a skeleton instead of the stale list.
- *
- * `sorter` / `sortType` are deliberately absent β€” they reorder the same pool
- * and re-sort locally, so a skeleton there would be a flash for nothing.
- */
-const POOL_KEYS = [
- 'libraryId',
- 'parentId',
- 'category',
- 'visibility',
- 'sourceFilter',
-] as const satisfies readonly (keyof ResourceQueryParams)[];
-
/**
* Whether the explorer is moving between two different resource pools.
*
* Both the list and the masonry view need this, and they used to carry their
* own copies of the comparison β€” which is exactly how `sourceFilter` came to be
- * missing from both at once. Keep it here so a new pool-selecting field is
- * added in one place.
+ * missing from both at once. The key list lives with the replica (which resets
+ * its rows on the same signal) so a new pool-selecting field is added in one
+ * place and both the skeleton and the hydration agree on it.
*/
export const isQueryNavigation = (
current: ResourceQueryParams | undefined,
@@ -31,5 +16,5 @@ export const isQueryNavigation = (
): boolean => {
if (!current || !next) return false;
- return POOL_KEYS.some((key) => current[key] !== next[key]);
+ return RESOURCE_POOL_KEYS.some((key) => current[key] !== next[key]);
};
diff --git a/src/features/ResourceManager/store/action.test.ts b/src/features/ResourceManager/store/action.test.ts
index b8aeff49ad6..44d098ff095 100644
--- a/src/features/ResourceManager/store/action.test.ts
+++ b/src/features/ResourceManager/store/action.test.ts
@@ -135,14 +135,15 @@ describe('resource manager store actions', () => {
it('should keep all-selected deletion caller-scoped when exclusions are present', async () => {
const deleteResources = vi.fn().mockResolvedValue(undefined);
+ const evictResourceLists = vi.fn().mockResolvedValue(undefined);
useResourceManagerStore.setState({
selectAllState: 'all',
selectedFileIds: ['file-2'],
});
useFileStore.setState({
- clearCurrentQueryResources: vi.fn(),
deleteResources,
+ evictResourceLists,
queryParams: { q: 'report' } as any,
});
mockDeleteResourcesByQuery.mockResolvedValue({ count: 2 });
@@ -152,6 +153,7 @@ describe('resource manager store actions', () => {
expect(mockDeleteResourcesByQuery).toHaveBeenCalledWith({ q: 'report' }, ['file-2']);
expect(mockResolveSelectionIds).not.toHaveBeenCalled();
expect(deleteResources).not.toHaveBeenCalled();
+ expect(evictResourceLists).toHaveBeenCalledTimes(1);
expect(useResourceManagerStore.getState()).toMatchObject({
selectAllState: 'none',
selectedFileIds: [],
@@ -233,8 +235,8 @@ describe('resource manager store actions', () => {
selectedFileIds: [],
});
useFileStore.setState({
- clearCurrentQueryResources: vi.fn(),
deleteResources: vi.fn(),
+ evictResourceLists: vi.fn().mockResolvedValue(undefined),
queryParams: { parentId: 'folder-a' } as any,
} as any);
mockDeleteResourcesByQuery.mockResolvedValue({ count: 1 });
@@ -249,8 +251,8 @@ describe('resource manager store actions', () => {
it('should refresh the listed folder when the deleted set is only known to the server', async () => {
useResourceManagerStore.setState({ selectAllState: 'all', selectedFileIds: [] });
useFileStore.setState({
- clearCurrentQueryResources: vi.fn(),
deleteResources: vi.fn(),
+ evictResourceLists: vi.fn().mockResolvedValue(undefined),
queryParams: { parentId: 'folder-a' } as any,
} as any);
mockDeleteResourcesByQuery.mockResolvedValue({ count: 3 });
diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.ts
index f6471caa7f1..109c2aa2eab 100644
--- a/src/features/ResourceManager/store/action.ts
+++ b/src/features/ResourceManager/store/action.ts
@@ -389,12 +389,12 @@ export class ResourceManagerStoreActionImpl {
// cannot drop those rows by id: invalidate the surfaces instead and
// let the refetch paint whatever survived.
void this.#invalidateExplorerSearch();
- fileStore.clearCurrentQueryResources();
- // The server applies the caller's workspace role: members delete
- // only their own rows, while owners may delete the full query scope.
- // Revalidate so any surviving rows immediately reappear.
- const { revalidateResources } = await import('@/store/file/slices/resource/hooks');
- await revalidateResources(fileStore.queryParams);
+ // Same for the explorer list: evict every cached variant (memory and
+ // persisted rows), so a failed refetch cannot leave deleted rows for a
+ // reload or an offline visit to repaint. The server applies the
+ // caller's workspace role β€” members delete only their own rows, owners
+ // the full query scope β€” so the revalidation repaints the survivors.
+ await fileStore.evictResourceLists();
// The deleted set is only known to the server here, and every row in
// it was a child of the listed folder, so refetch that one folder.
void useTreeStore.getState().revalidate(currentFolderKey);
diff --git a/src/store/file/slices/resource/action.test.ts b/src/store/file/slices/resource/action.test.ts
index 29bb73a6c2c..33a013b09ed 100644
--- a/src/store/file/slices/resource/action.test.ts
+++ b/src/store/file/slices/resource/action.test.ts
@@ -1,35 +1,53 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setScopedMutate } from '@/libs/swr/mutate';
import { initialState } from '@/store/file/initialState';
import { useFileStore } from '@/store/file/store';
import type { CreateDocumentParams, ResourceItem } from '@/types/resource';
-const { activeWorkspace, mockApplyMoveToCaches, mockCreateResource, mockMoveResource, treeState } =
- vi.hoisted(() => ({
- activeWorkspace: { id: null as string | null },
- mockApplyMoveToCaches: vi.fn(),
- mockCreateResource: vi.fn(),
- mockMoveResource: vi.fn(),
- treeState: { children: {} as Record<string, any[]> },
- }));
+import type { ResourceMoveCachePatch, ResourceMoveCacheScope } from './hooks';
+import type { ResourceListParams, ResourceListValue } from './projection';
+import { resourceListResource } from './projection';
+
+const {
+ mockAddFilesToKnowledgeBase,
+ mockCreateResource,
+ mockDeleteResource,
+ mockDeleteResources,
+ mockGetActiveWorkspaceId,
+ mockMoveResource,
+ mockRemoveFilesFromKnowledgeBase,
+ mockUpdateResource,
+} = vi.hoisted(() => ({
+ mockAddFilesToKnowledgeBase: vi.fn(),
+ mockCreateResource: vi.fn(),
+ mockDeleteResource: vi.fn(),
+ mockDeleteResources: vi.fn(),
+ mockGetActiveWorkspaceId: vi.fn(() => null as string | null),
+ mockMoveResource: vi.fn(),
+ mockRemoveFilesFromKnowledgeBase: vi.fn(),
+ mockUpdateResource: vi.fn(),
+}));
vi.mock('@/services/resource', () => ({
resourceService: {
createResource: mockCreateResource,
+ deleteResource: mockDeleteResource,
+ deleteResources: mockDeleteResources,
moveResource: mockMoveResource,
+ updateResource: mockUpdateResource,
},
}));
-vi.mock('./hooks', () => ({
- applyResourceMoveToListCaches: mockApplyMoveToCaches,
-}));
-
-vi.mock('@/store/tree', () => ({
- useTreeStore: { getState: () => treeState },
+vi.mock('@/services/knowledgeBase', () => ({
+ knowledgeBaseService: {
+ addFilesToKnowledgeBase: mockAddFilesToKnowledgeBase,
+ removeFilesFromKnowledgeBase: mockRemoveFilesFromKnowledgeBase,
+ },
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- getActiveWorkspaceId: () => activeWorkspace.id,
+ getActiveWorkspaceId: () => mockGetActiveWorkspaceId(),
}));
const createResource = (overrides: Partial<ResourceItem> = {}): ResourceItem => ({
@@ -45,25 +63,62 @@ const createResource = (overrides: Partial<ResourceItem> = {}): ResourceItem =>
...overrides,
});
+/**
+ * Seed the replica view exactly as the lens would after a head page landed:
+ * the flat fields and the entry stay in step, so the slice's engine reads the
+ * same rows the selectors do.
+ */
+const seedList = (
+ params: Partial<ResourceListParams>,
+ items: ResourceItem[],
+ meta: Partial<ResourceListValue> = {},
+) => {
+ const queryParams: ResourceListParams = {
+ pageSize: 50,
+ parentId: null,
+ showFilesInKnowledgeBase: false,
+ ...params,
+ };
+ const entry: ResourceListValue = {
+ currentPage: 0,
+ hasMore: false,
+ items,
+ nextCursor: null,
+ pageSize: queryParams.pageSize,
+ queryParams,
+ total: items.length,
+ ...meta,
+ };
+
+ useFileStore.setState({
+ hasMore: entry.hasMore,
+ isLoadingMore: false,
+ offset: items.length,
+ queryParams: entry.queryParams,
+ resourceList: items,
+ resourceListEntry: entry,
+ resourceMap: new Map(items.map((item) => [item.id, item])),
+ total: entry.total ?? items.length,
+ });
+};
+
+const listIds = () => useFileStore.getState().resourceList.map((item) => item.id);
+
describe('resource actions', () => {
beforeEach(() => {
vi.clearAllMocks();
- activeWorkspace.id = null;
- treeState.children = {};
+ mockGetActiveWorkspaceId.mockReturnValue(null);
useFileStore.setState(initialState);
});
- it('should keep completed background uploads out of the current resource list when they are off-screen', () => {
+ it('keeps a completed background upload out of the visible list when it is off-screen', () => {
const visibleResource = createResource({
id: 'visible-1',
name: 'Visible resource',
parentId: 'folder-b',
});
const optimisticResource = createResource({
- _optimistic: {
- isPending: true,
- retryCount: 0,
- },
+ _optimistic: { isPending: true, retryCount: 0 },
id: 'temp-a',
name: 'Background upload',
parentId: 'folder-a',
@@ -74,236 +129,135 @@ describe('resource actions', () => {
parentId: 'folder-a',
});
- useFileStore.setState({
- queryParams: { parentId: 'folder-b' },
- resourceList: [visibleResource],
- resourceMap: new Map([
- [visibleResource.id, visibleResource],
- [optimisticResource.id, optimisticResource],
- ]),
- });
+ seedList({ parentId: 'folder-b' }, [visibleResource]);
useFileStore.getState().replaceLocalResource(optimisticResource.id, completedResource);
const { resourceList, resourceMap } = useFileStore.getState();
expect(resourceList).toEqual([visibleResource]);
+ // The replica view is per query: a row for another folder never enters the
+ // open folder's list, so it is not in the derived map either.
expect(resourceMap.has(optimisticResource.id)).toBe(false);
- expect(resourceMap.get(completedResource.id)).toEqual(completedResource);
+ expect(resourceMap.has(completedResource.id)).toBe(false);
});
- it('should remove a root item from the visible list when moving it into a folder', async () => {
- const rootResource = createResource({
- id: 'root-1',
- name: 'Root resource',
- parentId: null,
- });
- const movedResource = createResource({
- id: 'root-1',
- name: 'Root resource',
- parentId: 'folder-a',
- });
+ it('replaces the temp row in place when the upload belongs to the open folder', () => {
+ const temp = createResource({ _optimistic: { isPending: true, retryCount: 0 }, id: 'temp-a' });
+ seedList({}, [temp]);
- mockMoveResource.mockResolvedValue(movedResource);
+ useFileStore.getState().replaceLocalResource('temp-a', createResource({ id: 'file-a' }));
- useFileStore.setState({
- queryParams: { parentId: null },
- resourceList: [rootResource],
- resourceMap: new Map([[rootResource.id, rootResource]]),
- });
+ expect(listIds()).toEqual(['file-a']);
+ expect(useFileStore.getState().resourceMap.has('temp-a')).toBe(false);
+ });
- await useFileStore.getState().moveResource(rootResource.id, 'folder-a');
+ it('inserts a local upload row at the head of the list', () => {
+ seedList({}, [createResource({ id: 'existing' })]);
- const { resourceList, resourceMap } = useFileStore.getState();
+ const id = useFileStore.getState().insertLocalResource(
+ {
+ fileType: 'text/plain',
+ name: 'Upload',
+ size: 3,
+ sourceType: 'file',
+ url: '',
+ },
+ 'temp-upload',
+ );
- expect(resourceList).toEqual([]);
- expect(resourceMap.has(rootResource.id)).toBe(false);
+ expect(id).toBe('temp-upload');
+ expect(listIds()).toEqual(['temp-upload', 'existing']);
});
- it('should patch the destination and source folder-list caches once a move lands', async () => {
- // Explorer is inside `2026.09` (URL slug), dragging a row onto the sibling
- // folder row `W37`: the drop target only knows the folder id.
- const targetFolder = createResource({
- fileType: 'custom/folder',
- id: 'folder-w37-id',
- name: '2026.09.W37',
- parentId: 'folder-2026-09-id',
- slug: 'w37-slug',
- });
- const doc = createResource({ id: 'doc-1', name: 'Weekly', parentId: 'folder-2026-09-id' });
- const movedDoc = { ...doc, parentId: targetFolder.id };
- mockMoveResource.mockResolvedValue(movedDoc);
- treeState.children = {
- 'folder-2026-09-id': [
- { id: targetFolder.id, isFolder: true, name: targetFolder.name, slug: 'w37-slug' },
- ],
- 'root': [{ id: 'folder-2026-09-id', isFolder: true, name: '2026.09', slug: '2026-09-slug' }],
- };
-
- useFileStore.setState({
- currentFolderId: 'folder-2026-09-id',
- queryParams: { parentId: '2026-09-slug' },
- resourceList: [doc, targetFolder],
- resourceMap: new Map([
- [doc.id, doc],
- [targetFolder.id, targetFolder],
- ]),
- });
+ it('removes a root item from the visible list when moving it into a folder', async () => {
+ const rootResource = createResource({ id: 'root-1', parentId: null });
+ mockMoveResource.mockResolvedValue(createResource({ id: 'root-1', parentId: 'folder-a' }));
+
+ seedList({ parentId: null }, [rootResource]);
- await useFileStore.getState().moveResource(doc.id, targetFolder.id);
+ await useFileStore.getState().moveResource(rootResource.id, 'folder-a');
- expect(mockApplyMoveToCaches).toHaveBeenCalledTimes(1);
- const [resource, patch] = mockApplyMoveToCaches.mock.calls[0];
- expect(resource).toEqual(movedDoc);
- expect(new Set(patch.fromParentKeys)).toEqual(new Set(['folder-2026-09-id', '2026-09-slug']));
- expect(new Set(patch.toParentKeys)).toEqual(new Set(['folder-w37-id', 'w37-slug']));
- expect(patch.scope).toEqual({ libraryId: undefined, workspaceId: null });
+ expect(listIds()).toEqual([]);
+ expect(useFileStore.getState().resourceMap.has(rootResource.id)).toBe(false);
+ // The row's own copy rides along, so the move stays one request.
+ expect(mockMoveResource).toHaveBeenCalledWith(
+ 'root-1',
+ 'folder-a',
+ expect.objectContaining({ id: 'root-1' }),
+ );
});
- it('should resolve folder aliases before the request so a scope switch cannot hide them', async () => {
- const targetFolder = createResource({
- fileType: 'custom/folder',
- id: 'folder-w37-id',
- name: 'W37',
- parentId: null,
- slug: 'w37-slug',
- });
- const doc = createResource({ id: 'doc-1', parentId: null });
- mockMoveResource.mockImplementation(async () => {
- // The user opened another library meanwhile: the old rows are gone.
- useFileStore.setState({
- queryParams: { libraryId: 'kb-2', parentId: null },
- resourceList: [],
- resourceMap: new Map(),
- });
- treeState.children = {};
- return { ...doc, parentId: targetFolder.id };
- });
- useFileStore.setState({
- queryParams: { parentId: null },
- resourceList: [doc, targetFolder],
- resourceMap: new Map([
- [doc.id, doc],
- [targetFolder.id, targetFolder],
- ]),
- });
+ it('keeps a row visible when it moves within the open folder', async () => {
+ const folderChild = createResource({ id: 'child-1', parentId: 'folder-a' });
+ mockMoveResource.mockResolvedValue(createResource({ id: 'child-1', parentId: 'folder-a' }));
- await useFileStore.getState().moveResource(doc.id, targetFolder.id);
+ seedList({ parentId: 'folder-a' }, [folderChild]);
- const [, patch] = mockApplyMoveToCaches.mock.calls[0];
- expect(new Set(patch.toParentKeys)).toEqual(new Set(['folder-w37-id', 'w37-slug']));
+ await useFileStore.getState().moveResource('child-1', 'folder-a');
+
+ expect(listIds()).toEqual(['child-1']);
});
- it('should patch the caches of the workspace and library the move started in', async () => {
- // The user switches workspace and library while the request is in flight;
- // the caches that listed the row belong to the scope captured beforehand.
- const doc = createResource({ id: 'doc-1', parentId: null });
- activeWorkspace.id = 'workspace-1';
- mockMoveResource.mockImplementation(async () => {
- activeWorkspace.id = 'workspace-2';
- useFileStore.setState({ queryParams: { libraryId: 'kb-2', parentId: null } });
- return { ...doc, parentId: 'folder-a' };
- });
+ it('rolls the moved row back when the server rejects the move', async () => {
+ const rootResource = createResource({ id: 'root-1', parentId: null });
+ mockMoveResource.mockRejectedValue(new Error('nope'));
- useFileStore.setState({
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [doc],
- resourceMap: new Map([[doc.id, doc]]),
- });
+ seedList({ parentId: null }, [rootResource]);
- await useFileStore.getState().moveResource(doc.id, 'folder-a');
+ await expect(useFileStore.getState().moveResource('root-1', 'folder-a')).rejects.toThrow();
- const [, patch] = mockApplyMoveToCaches.mock.calls[0];
- expect(patch.scope).toEqual({ libraryId: 'kb-1', workspaceId: 'workspace-1' });
+ // Rollback restores the row and its original parent.
+ expect(listIds()).toEqual(['root-1']);
+ expect(useFileStore.getState().resourceMap.get('root-1')?.parentId).toBeNull();
});
- it('should address the root with a null parent key when moving out of a folder', async () => {
- const doc = createResource({ id: 'doc-1', parentId: 'folder-a' });
- mockMoveResource.mockResolvedValue({ ...doc, parentId: null });
+ it('should not call the API when the row is already in the target folder', async () => {
+ const folderChild = createResource({ id: 'child-1', parentId: 'folder-a' });
+ seedList({ parentId: 'folder-a' }, [folderChild]);
- useFileStore.setState({
- queryParams: { parentId: 'folder-a' },
- resourceList: [doc],
- resourceMap: new Map([[doc.id, doc]]),
- });
+ await useFileStore.getState().moveResource('child-1', 'folder-a');
- await useFileStore.getState().moveResource(doc.id, null);
-
- const [, patch] = mockApplyMoveToCaches.mock.calls[0];
- expect(patch.toParentKeys).toEqual([null]);
- expect(patch.fromParentKeys).toContain('folder-a');
+ expect(mockMoveResource).not.toHaveBeenCalled();
});
- it('should treat the current folder as the source when the row omits parentId', async () => {
- // `queryResources` rows carry no `parentId`; the row is in the current list,
- // so the current query's parent (a URL slug) is the folder it leaves.
- const doc = createResource({ id: 'doc-1', parentId: undefined });
- mockMoveResource.mockResolvedValue({ ...doc, parentId: 'folder-w37-id' });
+ it('optimistically drops deleted rows and restores them on failure', async () => {
+ const rows = [createResource({ id: 'r1' }), createResource({ id: 'r2' })];
+ mockDeleteResources.mockRejectedValue(new Error('nope'));
- useFileStore.setState({
- queryParams: { parentId: '2026-09-slug' },
- resourceList: [doc],
- resourceMap: new Map([[doc.id, doc]]),
- });
+ seedList({}, rows);
- await useFileStore.getState().moveResource(doc.id, 'folder-w37-id');
+ await expect(useFileStore.getState().deleteResources(['r1'])).rejects.toThrow();
- expect(mockMoveResource).toHaveBeenCalledWith(
- doc.id,
- 'folder-w37-id',
- expect.objectContaining({ id: doc.id }),
- );
- const [, patch] = mockApplyMoveToCaches.mock.calls[0];
- expect(patch.fromParentKeys).toContain('2026-09-slug');
- expect(patch.fromParentKeys).not.toContain(null);
- expect(patch.toParentKeys).toEqual(['folder-w37-id']);
- });
+ expect(listIds()).toEqual(['r1', 'r2']);
- it('should still call the API when the row omits parentId and the target is the root', async () => {
- const doc = createResource({ id: 'doc-1', parentId: undefined });
- mockMoveResource.mockResolvedValue({ ...doc, parentId: null });
+ mockDeleteResources.mockResolvedValue(undefined);
+ await useFileStore.getState().deleteResources(['r1']);
- useFileStore.setState({
- queryParams: { parentId: 'folder-a' },
- resourceList: [doc],
- resourceMap: new Map([[doc.id, doc]]),
- });
+ expect(listIds()).toEqual(['r2']);
+ });
- await useFileStore.getState().moveResource(doc.id, null);
+ it('optimistically renames a row and confirms it with the server response', async () => {
+ const resource = createResource({ id: 'r1', name: 'Before' });
+ const renamed = createResource({ id: 'r1', name: 'After' });
+ mockUpdateResource.mockResolvedValue(renamed);
- expect(mockMoveResource).toHaveBeenCalledWith(
- doc.id,
- null,
- expect.objectContaining({ id: doc.id }),
- );
- });
+ seedList({}, [resource]);
- it('should not touch the caches when the move is rejected', async () => {
- const doc = createResource({ id: 'doc-1', parentId: null });
- mockMoveResource.mockRejectedValue(new Error('nope'));
+ const promise = useFileStore.getState().updateResource('r1', { name: 'After' });
- useFileStore.setState({
- queryParams: { parentId: null },
- resourceList: [doc],
- resourceMap: new Map([[doc.id, doc]]),
- });
+ expect(useFileStore.getState().resourceMap.get('r1')?.name).toBe('After');
- await expect(useFileStore.getState().moveResource(doc.id, 'folder-a')).rejects.toThrow();
+ await promise;
- expect(mockApplyMoveToCaches).not.toHaveBeenCalled();
+ expect(useFileStore.getState().resourceMap.get('r1')?.name).toBe('After');
+ expect(useFileStore.getState().resourceList[0]._optimistic).toBeUndefined();
});
- it('should patch a file-backed document resource with statuses returned by file id', () => {
- const resource = createResource({
- chunkCount: null,
- fileId: 'file-1',
- id: 'docs-1',
- });
+ it('patches a file-backed document resource with statuses returned by file id', () => {
+ const resource = createResource({ chunkCount: null, fileId: 'file-1', id: 'docs-1' });
- useFileStore.setState({
- resourceList: [resource],
- resourceMap: new Map([[resource.id, resource]]),
- });
+ seedList({}, [resource]);
useFileStore.getState().patchLocalResourceStatuses([
{
@@ -317,19 +271,34 @@ describe('resource actions', () => {
},
]);
- const { resourceList, resourceMap } = useFileStore.getState();
-
- expect(resourceList[0]).toMatchObject({
+ expect(useFileStore.getState().resourceMap.get('docs-1')).toMatchObject({
chunkCount: 10,
chunkingStatus: 'success',
embeddingStatus: 'success',
finishEmbedding: true,
id: 'docs-1',
});
- expect(resourceMap.get('docs-1')).toMatchObject({
- chunkCount: 10,
- embeddingStatus: 'success',
- });
+ });
+
+ it('removes rows from the list when the open view is that knowledge base', async () => {
+ const rows = [createResource({ id: 'r1', knowledgeBaseId: 'kb-1' })];
+ mockRemoveFilesFromKnowledgeBase.mockResolvedValue(undefined);
+
+ seedList({ libraryId: 'kb-1' }, rows);
+
+ await useFileStore.getState().removeResourcesFromKnowledgeBase('kb-1', ['r1']);
+
+ expect(listIds()).toEqual([]);
+ expect(mockRemoveFilesFromKnowledgeBase).toHaveBeenCalledWith('kb-1', ['r1']);
+ });
+
+ it('clears the painted rows but keeps the queried params', () => {
+ seedList({ parentId: 'folder-a' }, [createResource({ id: 'r1', parentId: 'folder-a' })]);
+
+ useFileStore.getState().clearCurrentQueryResources();
+
+ expect(listIds()).toEqual([]);
+ expect(useFileStore.getState().queryParams?.parentId).toBe('folder-a');
});
});
@@ -350,11 +319,7 @@ describe('createResourceAndSync list placement', () => {
it('keeps a root-level create out of the list while a folder is open', async () => {
const folderRow = createResource({ id: 'doc-in-folder', parentId: 'folder-a' });
- useFileStore.setState({
- queryParams: { libraryId: 'kb-1', parentId: 'folder-a-slug' },
- resourceList: [folderRow],
- resourceMap: new Map([[folderRow.id, folderRow]]),
- });
+ seedList({ libraryId: 'kb-1', parentId: 'folder-a-slug' }, [folderRow]);
mockCreateResource.mockResolvedValue(
createResource({ id: 'doc-root', knowledgeBaseId: 'kb-1', parentId: null }),
);
@@ -362,38 +327,150 @@ describe('createResourceAndSync list placement', () => {
const id = await useFileStore.getState().createResourceAndSync(createParams(null));
expect(id).toBe('doc-root');
- expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-in-folder']);
- expect(useFileStore.getState().resourceMap.has('doc-root')).toBe(true);
+ expect(listIds()).toEqual(['doc-in-folder']);
+ expect(useFileStore.getState().resourceMap.has('doc-root')).toBe(false);
});
it('keeps a create inside a folder out of the list while the root is open', async () => {
const rootRow = createResource({ id: 'doc-root', parentId: null });
- useFileStore.setState({
- queryParams: { libraryId: 'kb-1', parentId: null },
- resourceList: [rootRow],
- resourceMap: new Map([[rootRow.id, rootRow]]),
- });
+ seedList({ libraryId: 'kb-1', parentId: null }, [rootRow]);
mockCreateResource.mockResolvedValue(
createResource({ id: 'doc-nested', knowledgeBaseId: 'kb-1', parentId: 'folder-a' }),
);
await useFileStore.getState().createResourceAndSync(createParams('folder-a'));
- expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-root']);
+ expect(listIds()).toEqual(['doc-root']);
});
it('still lists a create in the open folder when that folder is addressed by slug and not cached', async () => {
- useFileStore.setState({
- queryParams: { libraryId: 'kb-1', parentId: 'folder-a-slug' },
- resourceList: [],
- resourceMap: new Map(),
- });
+ seedList({ libraryId: 'kb-1', parentId: 'folder-a-slug' }, []);
mockCreateResource.mockResolvedValue(
createResource({ id: 'doc-new', knowledgeBaseId: 'kb-1', parentId: 'folder-a' }),
);
await useFileStore.getState().createResourceAndSync(createParams('folder-a'));
- expect(useFileStore.getState().resourceList.map((item) => item.id)).toEqual(['doc-new']);
+ expect(listIds()).toEqual(['doc-new']);
+ });
+});
+
+describe('applyMovedResourceToCaches scope', () => {
+ const patchFrom = (
+ scope: Omit<ResourceMoveCacheScope, 'replicaScope'> & { replicaScope?: string },
+ ): ResourceMoveCachePatch => ({
+ fromParentKeys: [null],
+ scope: { replicaScope: resourceListResource.scope.get(), ...scope },
+ toParentKeys: ['folder-b'],
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetActiveWorkspaceId.mockReturnValue(null);
+ useFileStore.setState(initialState);
+ });
+
+ it('reconciles the completed move while the captured scope is still active', async () => {
+ seedList({ parentId: 'folder-b' }, []);
+
+ await useFileStore
+ .getState()
+ .applyMovedResourceToCaches(
+ createResource({ id: 'moved-1', parentId: 'folder-b' }),
+ patchFrom({ libraryId: undefined, workspaceId: null }),
+ );
+
+ expect(listIds()).toEqual(['moved-1']);
+ });
+
+ it('does not reconcile once the user has switched workspace', async () => {
+ seedList({ parentId: 'folder-b' }, []);
+ // The move was issued from ws-1; the replica now belongs to ws-2.
+ mockGetActiveWorkspaceId.mockReturnValue('ws-2');
+
+ await useFileStore
+ .getState()
+ .applyMovedResourceToCaches(
+ createResource({ id: 'moved-1', parentId: 'folder-b' }),
+ patchFrom({ libraryId: undefined, workspaceId: 'ws-1' }),
+ );
+
+ expect(listIds()).toEqual([]);
+ });
+
+ it('does not reconcile once another user signed in under the same workspace id', async () => {
+ seedList({ parentId: 'folder-b' }, []);
+
+ // Both users are in personal mode (workspace id `null`), so only the
+ // replica partition tells the issuing user apart from the active one.
+ await useFileStore
+ .getState()
+ .applyMovedResourceToCaches(
+ createResource({ id: 'moved-1', parentId: 'folder-b' }),
+ patchFrom({ libraryId: undefined, replicaScope: 'user-a:personal', workspaceId: null }),
+ );
+
+ expect(listIds()).toEqual([]);
+ });
+
+ it('does not reconcile once the user has switched library', async () => {
+ seedList({ libraryId: 'kb-2', parentId: 'folder-b' }, []);
+
+ await useFileStore
+ .getState()
+ .applyMovedResourceToCaches(
+ createResource({ id: 'moved-1', knowledgeBaseId: 'kb-2', parentId: 'folder-b' }),
+ patchFrom({ libraryId: 'kb-1', workspaceId: null }),
+ );
+
+ expect(listIds()).toEqual([]);
+ });
+});
+
+describe('revalidating after a committed mutation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetActiveWorkspaceId.mockReturnValue(null);
+ useFileStore.setState(initialState);
+ // Every confirmation of the mounted list rejects.
+ setScopedMutate((async () => {
+ throw new Error('revalidate failed');
+ }) as never);
+ });
+
+ afterEach(() => {
+ setScopedMutate((async () => []) as never);
+ });
+
+ it('reports a committed move as successful even when its confirmation fails', async () => {
+ mockMoveResource.mockResolvedValue(createResource({ id: 'root-1', parentId: 'folder-a' }));
+ seedList({ parentId: null }, [createResource({ id: 'root-1', parentId: null })]);
+
+ await expect(
+ useFileStore.getState().moveResource('root-1', 'folder-a'),
+ ).resolves.toBeUndefined();
+
+ // The move stands: the row left the root view instead of being restored.
+ expect(listIds()).toEqual([]);
+ });
+
+ it('keeps an API-only move completion when its confirmation fails', async () => {
+ seedList({ parentId: 'folder-b' }, []);
+
+ await expect(
+ useFileStore
+ .getState()
+ .applyMovedResourceToCaches(createResource({ id: 'moved-1', parentId: 'folder-b' }), {
+ fromParentKeys: [null],
+ scope: {
+ libraryId: undefined,
+ replicaScope: resourceListResource.scope.get(),
+ workspaceId: null,
+ },
+ toParentKeys: ['folder-b'],
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(listIds()).toEqual(['moved-1']);
});
});
diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.ts
index 2063b01effb..7fafc1900c4 100644
--- a/src/store/file/slices/resource/action.ts
+++ b/src/store/file/slices/resource/action.ts
@@ -1,210 +1,406 @@
import debug from 'debug';
+import { useLayoutEffect } from 'react';
import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import {
+ createReplicaSlice,
+ type ReplicaLens,
+ type ReplicaPageResult,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
import { knowledgeBaseService } from '@/services/knowledgeBase';
import { resourceService } from '@/services/resource';
-import type { StoreSetter } from '@/store/types';
-import { OptimisticEngine } from '@/store/utils/optimisticEngine';
-import type { CreateResourceParams, ResourceItem, UpdateResourceParams } from '@/types/resource';
-
-import type { FileStore } from '../../store';
-import type { ResourceMoveCachePatch, ResourceParentKey } from './hooks';
-import type { ResourceState } from './initialState';
-import { initialResourceState } from './initialState';
-import { getResourceQueryKey } from './utils';
+import { type StoreSetter } from '@/store/types';
+import {
+ type CreateResourceParams,
+ type ResourceItem,
+ type ResourceQueryParams,
+ type UpdateResourceParams,
+} from '@/types/resource';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type FileStore, useFileStore } from '../../store';
+import type { ResourceParentKey } from './hooks';
+import type { ResourceListParams, ResourceListValue } from './projection';
+import {
+ DEFAULT_RESOURCE_PAGE_SIZE,
+ normalizeResourceListParams,
+ RESOURCE_LIST_KEY,
+ resourceListResource,
+} from './projection';
+import {
+ getResourceQueryKey,
+ isOptimisticRowInRequestedPool,
+ listsMovedRowUnfiltered,
+ patchDestinationList,
+ patchSourceList,
+} from './utils';
const log = debug('resource-manager:action');
-interface ResourceStoreState extends Pick<
- ResourceState,
- | 'hasMore'
- | 'isLoadingMore'
- | 'isSyncing'
- | 'lastSyncTime'
- | 'offset'
- | 'queryParams'
- | 'resourceList'
- | 'resourceMap'
- | 'syncError'
- | 'syncQueue'
- | 'syncingIds'
- | 'total'
-> {}
+const n = setNamespace('resource');
type Setter = StoreSetter<FileStore>;
-export const createResourceSlice = (set: Setter, get: () => FileStore, api?: unknown) =>
- new ResourceActionImpl(set, get, api);
+/** An explorer-list overlay plus the list identity it was started on. */
+interface ListOverlay {
+ commit: (confirm?: (data: ResourceListValue) => ResourceListValue) => void;
+ rollback: () => void;
+ startedOn: string;
+}
+
+/**
+ * The explorer list keeps a single replica entry whose view lives in the flat
+ * store fields the rest of the app already reads. The engine is the only writer;
+ * `get` reconstructs the paged value from the stored entry, `set` fans it back
+ * out into `resourceList` / `resourceMap` / paging fields in one commit, so a
+ * subscriber never sees a list out of step with its bookkeeping.
+ */
+const resourceListLens: ReplicaLens<FileStore, ResourceListValue> = {
+ // A scope switch drops the whole view, query included.
+ clear: () => ({
+ hasMore: false,
+ isLoadingMore: false,
+ offset: 0,
+ queryParams: undefined,
+ resourceList: [],
+ resourceListEntry: undefined,
+ resourceMap: new Map(),
+ total: 0,
+ }),
+ get: (state) => state.resourceListEntry,
+ set: (_state, _key, data) => {
+ if (!data) {
+ // Dropping the painted rows keeps the queried params, so the views can
+ // still tell that the request on screen has moved on (skeleton instead of
+ // the previous pool's rows).
+ return {
+ hasMore: false,
+ isLoadingMore: false,
+ offset: 0,
+ resourceList: [],
+ resourceListEntry: undefined,
+ resourceMap: new Map(),
+ total: 0,
+ };
+ }
+
+ return {
+ hasMore: data.hasMore,
+ isLoadingMore: data.isLoadingMore ?? false,
+ offset: data.items.length,
+ queryParams: data.queryParams,
+ resourceList: data.items,
+ resourceListEntry: data,
+ resourceMap: new Map(data.items.map((item) => [item.id, item])),
+ total: data.total ?? data.items.length,
+ };
+ },
+};
const toError = (error: unknown) => (error instanceof Error ? error : new Error(String(error)));
+const stripOptimistic = (resource: ResourceItem): ResourceItem => {
+ const { _optimistic, ...rest } = resource;
+ void _optimistic;
+ return rest;
+};
+
+/** The `ResourceSyncResult` plus the SWR-era aliases the explorer consumes. */
+export interface ResourceListSyncResult extends ReplicaSyncResult {
+ /** Nothing painted yet and a fetch is on its way (the list/masonry skeletons). */
+ isLoading: boolean;
+ /** Alias of `revalidate`. */
+ mutate: () => Promise<unknown>;
+}
+
+export const createResourceSlice = (set: Setter, get: () => FileStore, api?: unknown) =>
+ new ResourceActionImpl(set, get, api);
+
export class ResourceActionImpl {
readonly #get: () => FileStore;
- readonly #resourceStoreHandle: {
- getState: () => ResourceStoreState;
- setState: (nextState: ResourceStoreState) => void;
- };
- readonly #set: Setter;
- #syncEngine?: OptimisticEngine<ResourceStoreState>;
+ /**
+ * The explorer list is a `@lobechat/replica` paged resource: the persisted
+ * head page paints before the network answers, and "load more" appends further
+ * pages through the engine instead of a hand-rolled `offset` accumulator.
+ */
+ readonly #resourceList;
+ /** Query the Explorer last asked for (set every render, read by the effects). */
+ #requestedListParams?: ResourceListParams;
+ /** Storage row of `#requestedListParams`; a slow hydrate of another query is dropped. */
+ #requestedListStorageKey?: string;
+ /** Storage row the painted rows answer, so the navigation effect only runs on a change. */
+ #paintedListKey?: string;
constructor(set: Setter, get: () => FileStore, _api?: unknown) {
void _api;
this.#get = get;
- this.#set = set;
- this.#resourceStoreHandle = {
- getState: () => {
- const state = this.#get();
-
- return {
- hasMore: state.hasMore,
- isLoadingMore: state.isLoadingMore,
- isSyncing: state.isSyncing,
- lastSyncTime: state.lastSyncTime,
- offset: state.offset,
- queryParams: state.queryParams,
- resourceList: state.resourceList,
- resourceMap: state.resourceMap,
- syncError: state.syncError,
- syncQueue: state.syncQueue,
- syncingIds: state.syncingIds,
- total: state.total,
- };
- },
- setState: (nextState) => {
- this.#set(nextState as Partial<FileStore>, false, 'resourceSyncEngine/setState');
- },
- };
+ this.#resourceList = createReplicaSlice(resourceListResource, {
+ actionPrefix: n('resourceList'),
+ fetcher: (params, cursor) => this.#fetchResourcePage(params, cursor),
+ get,
+ // A slow hydrate of a query the user has already left must not repaint the
+ // list: the requested row β€” not whatever the store still shows β€” decides.
+ isHydratable: (_cached, params) =>
+ resourceListResource.storageKey(params) === this.#requestedListStorageKey,
+ // Rows the explorer inserted locally (an in-flight upload / create) are
+ // the newest and have no server row yet, so a head response for their own
+ // pool β€” initial, focus or reconnect β€” must keep them instead of replacing
+ // them away. One from another pool must not: the singleton entry is reused
+ // by every query, so an unscoped predicate would paint folder A's upload
+ // in folder B.
+ isClientOnly: (item: ResourceItem) =>
+ !!item._optimistic &&
+ isOptimisticRowInRequestedPool(item._optimistic.queryKey, this.#requestedListParams),
+ set,
+ stateKey: 'resourceListReplica',
+ view: resourceListLens,
+ viewFields: (params) => ({ queryParams: params }),
+ });
}
- #clearSyncingId = (id: string) => {
- this.#set(
- (state) => {
- if (!state.syncingIds.has(id)) return {};
-
- const syncingIds = new Set(state.syncingIds);
- syncingIds.delete(id);
+ /** One page of the explorer list; `cursor` is the page index (0 = head). */
+ #fetchResourcePage = async (
+ params: ResourceListParams,
+ cursor?: number,
+ ): Promise<ReplicaPageResult<ResourceItem, number>> => {
+ const { pageSize, ...query } = params;
+ const limit = pageSize ?? DEFAULT_RESOURCE_PAGE_SIZE;
+ const page = cursor ?? 0;
+ const response = await resourceService.queryResources({
+ ...query,
+ limit,
+ offset: page * limit,
+ });
- return { syncingIds };
- },
- false,
- 'resource/clearSyncingId',
- );
+ return {
+ items: response.items,
+ // The server drops rows *after* paging (Inbox folders), so a short page is
+ // not the end: exhaustion is exactly the server's `hasMore`, never a
+ // length inferred from the visible rows.
+ nextCursor: response.hasMore ? page + 1 : null,
+ total: response.total,
+ };
};
- #clearResourceOptimisticState = (resource: ResourceItem): ResourceItem => {
- const { _optimistic, ...rest } = resource;
+ // ---- row helpers --------------------------------------------------------
- void _optimistic;
+ #insertRow = (data: ResourceListValue, resource: ResourceItem): ResourceListValue => {
+ const items = data.items.filter((item) => item.id !== resource.id);
+ const added = items.length === data.items.length ? 1 : 0;
- return rest;
+ return {
+ ...data,
+ items: [resource, ...items],
+ total: data.total === undefined ? undefined : data.total + added,
+ };
};
- #createOptimisticResource = (params: CreateResourceParams, id?: string): ResourceItem => ({
- _optimistic: {
- isPending: true,
- queryKey: getResourceQueryKey(this.#get().queryParams),
- retryCount: 0,
- },
- createdAt: new Date(),
- fileType: params.fileType,
- id: id || `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
- knowledgeBaseId: params.knowledgeBaseId,
- metadata: params.metadata,
- name: 'title' in params ? params.title : params.name,
- parentId: params.parentId,
- size: 'size' in params ? params.size : 0,
- sourceType: params.sourceType,
- updatedAt: new Date(),
- ...(params.sourceType === 'file'
- ? {
- url: params.url,
- ...(params.visibility !== undefined ? { visibility: params.visibility } : {}),
- }
- : {
- content: params.content,
- editorData: params.editorData ?? {},
- slug: params.slug,
- title: params.title,
- }),
- });
+ #removeRows = (data: ResourceListValue, ids: Set<string>): ResourceListValue => {
+ const items = data.items.filter((item) => !ids.has(item.id));
+ if (items.length === data.items.length) return data;
- #getSyncEngine = () => {
- if (this.#syncEngine) return this.#syncEngine;
-
- this.#syncEngine = new OptimisticEngine(this.#resourceStoreHandle, {
- maxRetries: 1,
- onMutationError: (_snapshot, error) => {
- this.#set(
- {
- syncError: toError(error),
- },
- false,
- 'resourceSyncEngine/error',
- );
- },
- onMutationSuccess: () => {
- this.#set(
- {
- lastSyncTime: new Date(),
- syncError: undefined,
- },
- false,
- 'resourceSyncEngine/success',
- );
- },
- onQueueChange: (snapshots) => {
- this.#set(
- {
- isSyncing: snapshots.some(
- (item) => item.status === 'pending' || item.status === 'inflight',
- ),
- syncQueue: snapshots,
- },
- false,
- 'resourceSyncEngine/queueChange',
- );
- },
+ const removed = data.items.length - items.length;
+ const total =
+ data.total === undefined ? undefined : Math.max(items.length, data.total - removed);
+
+ return {
+ ...data,
+ hasMore: total !== undefined ? total > items.length : data.hasMore,
+ items,
+ total,
+ };
+ };
+
+ #patchRow = (
+ data: ResourceListValue,
+ id: string,
+ updater: (resource: ResourceItem) => ResourceItem | undefined,
+ ): ResourceListValue => {
+ let changed = false;
+ const items = data.items.flatMap((item) => {
+ if (item.id !== id) return [item];
+ const next = updater(item);
+ changed = true;
+ return next ? [next] : [];
});
- return this.#syncEngine;
+ return changed ? { ...data, items } : data;
};
- #replaceLocalResource = (targetId: string, resource: ResourceItem) => {
- const { resourceList, resourceMap } = this.#get();
- const nextMap = new Map(resourceMap);
- nextMap.delete(targetId);
- nextMap.set(resource.id, resource);
+ #patchRows = (
+ data: ResourceListValue,
+ ids: Set<string>,
+ updater: (resource: ResourceItem) => ResourceItem,
+ ): ResourceListValue => {
+ let changed = false;
+ const items = data.items.map((item) => {
+ if (!ids.has(item.id)) return item;
+ const next = updater(item);
+ if (next !== item) changed = true;
+ return next;
+ });
- const targetIndex = resourceList.findIndex((item) => item.id === targetId);
- const nextList = resourceList.filter((item) => item.id !== targetId && item.id !== resource.id);
- // If the replaced item was already visible, keep the replacement visible too.
- // This avoids slug-vs-UUID mismatches when queryParams.parentId is a slug
- // but resource.parentId is a UUID and the parent folder isn't in resourceMap.
- const shouldInsert = targetIndex !== -1 || this.#isResourceVisibleInCurrentQuery(resource);
+ return changed ? { ...data, items } : data;
+ };
- if (shouldInsert) {
- const insertIndex = targetIndex === -1 ? 0 : Math.min(targetIndex, nextList.length);
- nextList.splice(insertIndex, 0, resource);
+ /** Replace a row in place (collapsing a duplicate when the server id already exists). */
+ #replaceRow = (
+ data: ResourceListValue,
+ fromId: string,
+ resource: ResourceItem,
+ ): ResourceListValue => {
+ const index = data.items.findIndex((item) => item.id === fromId);
+ if (index === -1) {
+ if (data.items.some((item) => item.id === resource.id)) {
+ return this.#patchRow(data, resource.id, () => resource);
+ }
+ return data;
}
- this.#set(
- {
- resourceList: nextList,
- resourceMap: nextMap,
- },
- false,
- 'resource/replaceLocalResource',
+ const items: ResourceItem[] = [];
+ data.items.forEach((item, i) => {
+ if (i === index) {
+ items.push(resource);
+ return;
+ }
+ if (item.id === resource.id) return;
+ items.push(item);
+ });
+
+ return { ...data, items };
+ };
+
+ /**
+ * Settle an optimistic create: the confirmation callback receives the value
+ * *before* the overlay, so the temp row it must swap out is not there β€” the
+ * created row is inserted instead (the overlay's own temp row is dropped).
+ */
+ #settleCreated = (
+ data: ResourceListValue,
+ tempId: string,
+ created: ResourceItem,
+ ): ResourceListValue =>
+ data.items.some((item) => item.id === tempId)
+ ? this.#replaceRow(data, tempId, created)
+ : this.#insertRow(data, created);
+
+ /**
+ * Materialize a view for the explorer list so a local insert (upload /
+ * create) has somewhere to land before the first page arrives. Rows already
+ * written straight into the flat fields are adopted rather than dropped, so
+ * a legacy caller (the upload path runs before any query is known) keeps
+ * working; with no query at all the view is seeded query-less.
+ */
+ #ensureListView = (): void => {
+ const state = this.#get();
+ if (state.resourceListEntry) return;
+
+ const params = state.queryParams;
+ const items = state.resourceList;
+ const seeded: ResourceListValue = {
+ currentPage: 0,
+ hasMore: state.hasMore,
+ items,
+ nextCursor: state.hasMore ? 1 : null,
+ pageSize: params?.pageSize ?? DEFAULT_RESOURCE_PAGE_SIZE,
+ queryParams: params,
+ total: state.total ?? items.length,
+ };
+
+ this.#resourceList.update(RESOURCE_LIST_KEY, (data) => data ?? seeded, { persist: false });
+ };
+
+ /**
+ * Replica query identity of the Explorer's current request. Tagging an
+ * overlay with it scopes the overlay even when it starts before the first
+ * page painted β€” the seeded entry has no query of its own yet, and an
+ * untagged overlay would be kept across every query change (leaking one
+ * folder's row into another).
+ */
+ #requestedListQuery = (): string | undefined =>
+ this.#requestedListParams ? resourceListResource.query(this.#requestedListParams) : undefined;
+
+ /**
+ * Optimistic overlay over the explorer list, tagged with the list it was
+ * started on (replica scope + requested storage row), so a settle can tell
+ * whether the entry has moved on to another query since.
+ */
+ #beginListOptimistic = (apply: (data: ResourceListValue) => ResourceListValue): ListOverlay => {
+ this.#ensureListView();
+ const startedOn = this.#currentListIdentity();
+ const token = this.#resourceList.beginOptimistic(
+ RESOURCE_LIST_KEY,
+ apply,
+ this.#requestedListQuery(),
);
+ return { ...token, startedOn };
+ };
+
+ /** The list on screen: replica scope + requested storage row. */
+ #currentListIdentity = (): string =>
+ `${resourceListResource.scope.get()}\u0000${this.#requestedListStorageKey ?? ''}`;
+
+ #revalidateList = async (): Promise<void> => {
+ await this.#resourceList.revalidate();
};
/**
- * The definite negative to `#isResourceVisibleInCurrentQuery`: that check
- * says "no" whenever the open folder is addressed by slug and the parent is
- * not cached, so a create must not gate on it or a fresh load inside a
- * folder would never show the row it just created. This only reports rows
- * that certainly belong elsewhere β€” another library, the root while a folder
- * is open (or the reverse), or a cached parent whose slug is not the open one.
+ * Confirm the mounted list after a mutation that the server already accepted.
+ * A failed confirmation must not undo (or fail) that mutation: the rows are
+ * committed, the next visit revalidates anyway, and the caller's own
+ * transaction would otherwise restore a row the server has moved.
*/
+ #revalidateListQuietly = async (action: string): Promise<void> => {
+ try {
+ await this.#revalidateList();
+ } catch (error) {
+ log('%s: revalidation after the mutation failed', action, error);
+ }
+ };
+
+ /**
+ * Settle an optimistic overlay and, when the list has moved on to another
+ * query since it started β€” a same-pool query change (re-sort, view-mode
+ * switch) drops the overlay, so its commit has nothing to settle β€” force a
+ * reconciliation, so the server change is not left unreflected until the
+ * next focus, reconnect or manual refresh.
+ */
+ #commitListOptimistic = (
+ token: ListOverlay | undefined,
+ action: string,
+ confirm?: (data: ResourceListValue) => ResourceListValue,
+ ): void => {
+ if (!token) return;
+ token.commit(confirm);
+ if (token.startedOn !== this.#currentListIdentity()) void this.#revalidateListQuietly(action);
+ };
+
+ /**
+ * Settle an optimistic create's temp row by id, whether or not its overlay
+ * still exists. A same-pool query change (a re-sort, a view-mode switch)
+ * repaints from that query's cached page and keeps the in-flight temp row as
+ * client-only, but drops the overlay token β€” so `rollback` / `commit` can no
+ * longer reach it. Without this a failed create would leave the temp row in
+ * the list for good (every later head response keeps it as client-only), and
+ * a successful one would show it next to the created row.
+ */
+ #settleTempRow = (tempId: string, created?: ResourceItem): void => {
+ if (!this.#get().resourceMap.has(tempId)) return;
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) => {
+ if (!data) return data;
+ return created
+ ? this.#replaceRow(data, tempId, created)
+ : this.#removeRows(data, new Set([tempId]));
+ },
+ { persist: false },
+ );
+ };
+
+ #clearSyncingOptimistic = (resource: ResourceItem): ResourceItem => stripOptimistic(resource);
+
#isResourceOutsideCurrentQuery = (resource: ResourceItem): boolean => {
const { queryParams, resourceMap } = this.#get();
@@ -255,6 +451,38 @@ export class ResourceActionImpl {
return parentResource?.slug === queryParams.parentId;
};
+ #createOptimisticResource = (params: CreateResourceParams, id?: string): ResourceItem => ({
+ _optimistic: {
+ isPending: true,
+ // The row must read as *this* pool's on the head response, including when
+ // it is inserted before the first page landed (the store's `queryParams` is
+ // only set by a paint) β€” so stamp the pool the Explorer asked for.
+ queryKey: getResourceQueryKey(this.#requestedListParams ?? this.#get().queryParams),
+ retryCount: 0,
+ },
+ createdAt: new Date(),
+ fileType: params.fileType,
+ id: id || `temp-resource-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
+ knowledgeBaseId: params.knowledgeBaseId,
+ metadata: params.metadata,
+ name: 'title' in params ? params.title : params.name,
+ parentId: params.parentId,
+ size: 'size' in params ? params.size : 0,
+ sourceType: params.sourceType,
+ updatedAt: new Date(),
+ ...(params.sourceType === 'file'
+ ? {
+ url: params.url,
+ ...(params.visibility !== undefined ? { visibility: params.visibility } : {}),
+ }
+ : {
+ content: params.content,
+ editorData: params.editorData ?? {},
+ slug: params.slug,
+ title: params.title,
+ }),
+ });
+
/**
* `queryParams.parentId` carries the folder slug from the URL while drop
* targets and the sidebar tree address folders by id. Collect both spellings
@@ -299,191 +527,180 @@ export class ResourceActionImpl {
return [...keys];
};
- #patchLocalResourceEntries = (
- ids: Set<string>,
- updater: (resource: ResourceItem) => ResourceItem | null,
- actionName: string,
- onComplete?: (draft: ResourceStoreState, meta: { visibleChangedCount: number }) => void,
- ) => {
- this.#set(
- (state) => {
- if (ids.size === 0) return {};
-
- const resourceMap = new Map(state.resourceMap);
- let changed = false;
- let visibleChangedCount = 0;
-
- const resourceList = state.resourceList.flatMap((item) => {
- if (!ids.has(item.id)) return [item];
-
- const nextItem = updater(resourceMap.get(item.id) ?? item);
-
- visibleChangedCount += 1;
- changed = true;
-
- if (!nextItem) {
- resourceMap.delete(item.id);
- return [];
- }
-
- resourceMap.set(nextItem.id, nextItem);
- return [nextItem];
- });
+ // ---- list lifecycle -----------------------------------------------------
- for (const id of ids) {
- if (state.resourceList.some((item) => item.id === id)) continue;
-
- const existing = resourceMap.get(id);
- if (!existing) continue;
-
- const nextItem = updater(existing);
- changed = true;
-
- if (!nextItem) {
- resourceMap.delete(id);
- continue;
- }
-
- resourceMap.set(nextItem.id, nextItem);
- }
-
- if (!changed) return {};
-
- const draft: ResourceStoreState = {
- ...state,
- resourceList,
- resourceMap,
- };
+ /**
+ * Repaint the explorer for a new query. The entry is a singleton reused by
+ * every query, and `hydrate` otherwise only fills an empty slot β€” so without
+ * this a query change waits for the network even when its own persisted page
+ * exists (a warm navigation, or any navigation while offline). Reading that
+ * page with `overwrite` repaints the entry in a single write, so the views
+ * never see an empty middle frame and a same-pool change (`sorter` /
+ * `sortType` / view mode) stays flash-free.
+ *
+ * The once-per-key driver read cannot cover this: it already ran for a query
+ * the session loaded before (hydrates are `once`), so the read is done here.
+ * The painted identity includes the replica scope: the same query in another
+ * workspace is another persisted row, and `useSync` clears the view when the
+ * scope switches.
+ */
+ #hydrateListQuery = (): void => {
+ const params = this.#requestedListParams;
+ const storageKey = this.#requestedListStorageKey;
+ if (!params || storageKey === undefined) return;
- onComplete?.(draft, { visibleChangedCount });
+ const paintedKey = `${resourceListResource.scope.get()}\u0000${storageKey}`;
+ if (paintedKey === this.#paintedListKey) return;
+ this.#paintedListKey = paintedKey;
- return draft;
- },
- false,
- actionName,
- );
+ void this.#resourceList.hydrate(params, undefined, { overwrite: true });
};
- #toPendingResource = (resource: ResourceItem, patch?: Partial<ResourceItem>): ResourceItem => ({
- ...resource,
- ...patch,
- _optimistic: {
- ...(resource._optimistic || {
- queryKey: getResourceQueryKey(this.#get().queryParams),
- retryCount: 0,
- }),
- isPending: true,
- },
- updatedAt: patch?.updatedAt ?? new Date(),
- });
+ /**
+ * Fetch orchestration for the explorer list. Hydrates the persisted head page,
+ * then revalidates; the rows land in the flat view β€” read them from the store,
+ * never from this hook.
+ */
+ useFetchResources = (
+ params: ResourceQueryParams | null | undefined,
+ enable: boolean = true,
+ ): ResourceListSyncResult => {
+ const normalized = normalizeResourceListParams(params);
+ const active = enable && normalized !== null;
+ // Subscribed, so the first frame after a hydrate/replace re-renders.
+ const hasValue = useFileStore((s) => s.resourceListEntry !== undefined);
+ const storageKey = normalized ? resourceListResource.storageKey(normalized) : undefined;
+ // Subscribed: a scope switch clears the replica view, so the navigation
+ // effect below has to re-run and repaint from the new scope's own row.
+ const scope = resourceListResource.scope.use();
+
+ // The latest request, read by the navigation effect below and by the
+ // stale-hydrate guard. Kept on the instance so the effect deps stay primitive.
+ this.#requestedListParams = normalized ?? undefined;
+ this.#requestedListStorageKey = storageKey;
+
+ // Declared before `useSync` so it runs before the sync's own effects: the
+ // persisted page of the new pool paints on this frame, not after the fetch.
+ useLayoutEffect(() => {
+ if (!active || storageKey === undefined) return;
+ this.#hydrateListQuery();
+ }, [active, scope, storageKey]);
+
+ const sync = this.#resourceList.useSync(active ? normalized : null, { enabled: enable });
+
+ return {
+ error: sync.error,
+ isHydrated: sync.isHydrated,
+ // Nothing painted yet and the network is still to answer: a skeleton, not
+ // the "create your first resource" onboarding.
+ isLoading: active && !hasValue && !sync.error,
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+ revalidate: sync.revalidate,
+ };
+ };
- clearResources = (): void => {
- this.#set(
- {
- ...initialResourceState,
- },
- false,
- 'resource/clearResources',
- );
+ /**
+ * Append the next page of the explorer list. The engine reads the loaded head
+ * params, dedupes by id and keeps `hasMore` honest.
+ */
+ loadMoreResources = async (): Promise<void> => {
+ await this.#resourceList.loadMore(RESOURCE_LIST_KEY);
};
+ /**
+ * Drop the painted page set (e.g. the filter chip changed) while keeping the
+ * queried params, so the views render a skeleton and the next query's fetch
+ * repaints instead of appending to the previous pool. The persisted rows the
+ * engine holds are left alone.
+ */
clearCurrentQueryResources = (): void => {
- this.#set(
- (state) => {
- const visibleIds = new Set(state.resourceList.map((item) => item.id));
- const syncingIds = new Set(
- Array.from(state.syncingIds).filter((id) => !visibleIds.has(id)),
- );
-
- // Preserve off-screen optimistic items from other queries
- const preservedMap = new Map<string, ResourceItem>();
- for (const [id, item] of state.resourceMap) {
- if (!visibleIds.has(id) && item._optimistic) {
- preservedMap.set(id, item);
- }
- }
+ // Adopt rows a legacy caller wrote straight into the flat fields first, so
+ // the drop below actually clears them.
+ this.#ensureListView();
+ this.#resourceList.update(RESOURCE_LIST_KEY, () => undefined, { persist: false });
+ };
- return {
- hasMore: false,
- offset: 0,
- resourceList: [],
- resourceMap: preservedMap,
- syncingIds,
- total: 0,
- };
- },
- false,
- 'resource/clearCurrentQueryResources',
- );
+ /**
+ * Evict every cached explorer list after a deletion only the server can
+ * enumerate (select-all "delete by query"). The deleted set is unknown here,
+ * and folder deletions reach into other folders' lists, so any persisted
+ * variant β€” another sort, view mode, filter or folder β€” may hold a deleted
+ * row. `clear()` drops memory and every persisted row of the active scope and
+ * discards reads started before it; the revalidation then repaints whatever
+ * survived. Unlike `clearCurrentQueryResources`, a failed refetch can no
+ * longer leave a pre-deletion page behind for a reload or an offline visit.
+ */
+ evictResourceLists = async (): Promise<void> => {
+ await this.#resourceList.clear();
+ await this.#revalidateListQuietly('evictResourceLists');
};
+ // ---- create / update / delete ------------------------------------------
+
createResource = async (params: CreateResourceParams): Promise<string> => {
- const optimisticResource = this.#createOptimisticResource(params);
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`createResource(${optimisticResource.id})`);
- const showInList = !this.#isResourceOutsideCurrentQuery(optimisticResource);
-
- tx.set((draft) => {
- if (showInList) draft.resourceList.unshift(optimisticResource);
- draft.resourceMap.set(optimisticResource.id, optimisticResource);
- draft.syncingIds.add(optimisticResource.id);
- });
- tx.mutation = () => resourceService.createResource(params);
- tx.onSuccess = async (result) => {
- this.#replaceLocalResource(optimisticResource.id, result as ResourceItem);
- this.#clearSyncingId(optimisticResource.id);
- };
- tx.onError = async (error) => {
- this.#clearSyncingId(optimisticResource.id);
- this.markLocalResourceError(optimisticResource.id, toError(error));
- };
+ const optimistic = this.#createOptimisticResource(params);
+ const showInList = !this.#isResourceOutsideCurrentQuery(optimistic);
+ const token = showInList
+ ? this.#beginListOptimistic((data) => this.#insertRow(data, optimistic))
+ : undefined;
- void tx.commit<ResourceItem>().catch((error) => {
+ try {
+ const created = (await resourceService.createResource(params)) as ResourceItem;
+ this.#commitListOptimistic(token, 'createResource', (data) =>
+ this.#settleCreated(data, optimistic.id, created),
+ );
+ this.#settleTempRow(optimistic.id, created);
+ } catch (error) {
+ token?.rollback();
+ this.#settleTempRow(optimistic.id);
console.error('Failed to create resource:', error);
- });
+ throw error;
+ }
- return optimisticResource.id;
+ return optimistic.id;
};
createResourceAndSync = async (params: CreateResourceParams): Promise<string> => {
- const optimisticResource = this.#createOptimisticResource(params);
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`createResourceAndSync(${optimisticResource.id})`);
+ const optimistic = this.#createOptimisticResource(params);
// A row created for another folder (sidebar "+" at the root while a folder
// is open, a folder row's "+" while the root is open) must not surface in
// the list the Explorer is currently showing.
- const showInList = !this.#isResourceOutsideCurrentQuery(optimisticResource);
+ const showInList = !this.#isResourceOutsideCurrentQuery(optimistic);
+ const token = showInList
+ ? this.#beginListOptimistic((data) => this.#insertRow(data, optimistic))
+ : undefined;
- tx.set((draft) => {
- if (showInList) draft.resourceList.unshift(optimisticResource);
- draft.resourceMap.set(optimisticResource.id, optimisticResource);
- draft.syncingIds.add(optimisticResource.id);
- });
- tx.mutation = () => resourceService.createResource(params);
- tx.onSuccess = async (result) => {
- this.#replaceLocalResource(optimisticResource.id, result as ResourceItem);
- this.#clearSyncingId(optimisticResource.id);
- };
- tx.onError = async (error) => {
- this.#clearSyncingId(optimisticResource.id);
- this.markLocalResourceError(optimisticResource.id, toError(error));
- };
-
- const created = await tx.commit<ResourceItem>();
- return created.id;
+ try {
+ const created = (await resourceService.createResource(params)) as ResourceItem;
+ this.#commitListOptimistic(token, 'createResourceAndSync', (data) =>
+ this.#settleCreated(data, optimistic.id, created),
+ );
+ this.#settleTempRow(optimistic.id, created);
+ return created.id;
+ } catch (error) {
+ token?.rollback();
+ this.#settleTempRow(optimistic.id);
+ throw error;
+ }
};
deleteResource = async (id: string): Promise<void> => {
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`deleteResource(${id})`);
+ const token = this.#beginListOptimistic((data) => this.#removeRows(data, new Set([id])));
- tx.set((draft) => {
- draft.resourceList = draft.resourceList.filter((item) => item.id !== id);
- draft.resourceMap.delete(id);
- });
- tx.mutation = () => resourceService.deleteResource(id);
+ try {
+ await resourceService.deleteResource(id);
+ this.#commitListOptimistic(token, 'deleteResource');
+ } catch (error) {
+ token?.rollback();
+ throw error;
+ }
- await tx.commit<void>();
+ // The overlay only settles the mounted query. The row may also sit in other
+ // persisted variants (another sort, view mode, filter or folder), which an
+ // offline visit or a reload would hydrate again: drop it from all of them
+ // and guard hydrates already in flight.
+ this.#resourceList.removeEntity(id);
// The file manager's by-id detail replica persists, so a confirmed deletion
// has to evict it as well: otherwise a direct visit to the deleted id
@@ -495,199 +712,68 @@ export class ResourceActionImpl {
if (ids.length === 0) return;
const idsSet = new Set(ids);
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`deleteResources(${ids.join(',')})`);
+ const token = this.#beginListOptimistic((data) => this.#removeRows(data, idsSet));
- tx.set((draft) => {
- draft.resourceList = draft.resourceList.filter((item) => !idsSet.has(item.id));
- for (const id of idsSet) {
- draft.resourceMap.delete(id);
- }
- });
- tx.mutation = () => resourceService.deleteResources(ids);
+ try {
+ await resourceService.deleteResources(ids);
+ this.#commitListOptimistic(token, 'deleteResources');
+ } catch (error) {
+ token?.rollback();
+ throw error;
+ }
- await tx.commit<void>();
+ // See `deleteResource`: evict the rows from every persisted query variant.
+ for (const id of ids) this.#resourceList.removeEntity(id);
// See `deleteResource`: the detail replica persists by id, so it must be
// evicted here too.
this.#get().forgetKnowledgeItems(ids);
};
- flushSync = async (): Promise<void> => {
- await this.#getSyncEngine().flush();
- };
-
- insertLocalResource = (params: CreateResourceParams, id?: string): string => {
- const optimisticResource = this.#createOptimisticResource(params, id);
-
- this.#set(
- (state) => {
- const resourceMap = new Map(state.resourceMap);
- resourceMap.set(optimisticResource.id, optimisticResource);
-
- return {
- resourceList: [optimisticResource, ...state.resourceList],
- resourceMap,
- };
- },
- false,
- 'resource/insertLocalResource',
- );
-
- return optimisticResource.id;
- };
-
- patchLocalResource = (
- id: string,
- updates: Partial<ResourceItem>,
- actionName: string = 'resource/patchLocalResource',
- ): void => {
- this.#patchLocalResourceEntries(
- new Set([id]),
- (resource) => ({
- ...resource,
- ...updates,
- }),
- actionName,
- );
- };
-
- patchLocalResourceStatuses = (
- items: Array<
- Pick<
- ResourceItem,
- | 'id'
- | 'chunkCount'
- | 'chunkingError'
- | 'chunkingStatus'
- | 'embeddingError'
- | 'embeddingStatus'
- | 'finishEmbedding'
- >
- >,
- ): void => {
- if (items.length === 0) return;
-
- const statusMap = new Map(items.map((item) => [item.id, item]));
- const statusByResourceId = new Map<
- string,
- Pick<
- ResourceItem,
- | 'id'
- | 'chunkCount'
- | 'chunkingError'
- | 'chunkingStatus'
- | 'embeddingError'
- | 'embeddingStatus'
- | 'finishEmbedding'
- >
- >();
+ updateResource = async (id: string, updates: UpdateResourceParams): Promise<void> => {
+ const { resourceMap } = this.#get();
+ const existing = resourceMap.get(id);
- for (const resource of this.#get().resourceList) {
- const status =
- statusMap.get(resource.id) ?? (resource.fileId && statusMap.get(resource.fileId));
- if (status) statusByResourceId.set(resource.id, status);
+ if (!existing) {
+ console.warn(`Resource ${id} not found for update`);
+ return;
}
- this.#patchLocalResourceEntries(
- new Set(statusByResourceId.keys()),
- (resource) => {
- const patch = statusByResourceId.get(resource.id);
- if (!patch) return resource;
-
- return {
- ...resource,
- chunkCount: patch.chunkCount !== undefined ? patch.chunkCount : resource.chunkCount,
- chunkingError:
- patch.chunkingError !== undefined ? patch.chunkingError : resource.chunkingError,
- chunkingStatus:
- patch.chunkingStatus !== undefined ? patch.chunkingStatus : resource.chunkingStatus,
- embeddingError:
- patch.embeddingError !== undefined ? patch.embeddingError : resource.embeddingError,
- embeddingStatus:
- patch.embeddingStatus !== undefined ? patch.embeddingStatus : resource.embeddingStatus,
- finishEmbedding:
- patch.finishEmbedding !== undefined ? patch.finishEmbedding : resource.finishEmbedding,
- };
+ const updated: ResourceItem = {
+ ...existing,
+ ...updates,
+ _optimistic: {
+ ...(existing._optimistic || {
+ queryKey: getResourceQueryKey(this.#get().queryParams),
+ retryCount: 0,
+ }),
+ isPending: true,
},
- 'resource/patchLocalResourceStatuses',
- );
- };
+ name: updates.name || updates.title || existing.name,
+ updatedAt: new Date(),
+ };
- loadMoreResources = async (): Promise<void> => {
- const { hasMore, offset, queryParams } = this.#get();
- if (!hasMore || !queryParams) return;
+ log('updateResource', id, existing, updates);
- this.#set({ isLoadingMore: true }, false, 'resource/loadMoreResources/start');
+ const token = this.#beginListOptimistic((data) => this.#patchRow(data, id, () => updated));
+ let result: ResourceItem;
try {
- const { items } = await resourceService.queryResources({
- ...queryParams,
- limit: 50,
- offset,
- });
-
- this.#set(
- (state) => {
- const existingIds = new Set(state.resourceList.map((item) => item.id));
- const resourceMap = new Map(state.resourceMap);
-
- for (const item of items) {
- resourceMap.set(item.id, item);
- }
-
- return {
- hasMore: items.length === 50,
- isLoadingMore: false,
- offset: offset + items.length,
- resourceList: [
- ...state.resourceList,
- ...items.filter((item) => !existingIds.has(item.id)),
- ],
- resourceMap,
- };
- },
- false,
- 'resource/loadMoreResources/success',
+ result = (await resourceService.updateResource(id, updates)) as ResourceItem;
+ this.#commitListOptimistic(token, 'updateResource', (data) =>
+ this.#patchRow(data, id, () => result),
);
} catch (error) {
- this.#set({ isLoadingMore: false }, false, 'resource/loadMoreResources/error');
+ token?.rollback();
throw error;
}
- };
- markLocalResourceError = (id: string, error: Error): void => {
- const { resourceMap } = this.#get();
- const resource = resourceMap.get(id);
- if (!resource) return;
-
- const nextResource: ResourceItem = {
- ...resource,
- _optimistic: {
- ...(resource._optimistic || {
- isPending: false,
- queryKey: getResourceQueryKey(this.#get().queryParams),
- retryCount: 0,
- }),
- error,
- isPending: false,
- lastSyncAttempt: new Date(),
- },
- };
-
- this.#set(
- (state) => {
- const resourceMap = new Map(state.resourceMap);
- resourceMap.set(id, nextResource);
-
- return {
- resourceList: state.resourceList.map((item) => (item.id === id ? nextResource : item)),
- resourceMap,
- };
- },
- false,
- 'resource/markLocalResourceError',
- );
+ // The overlay only settles the mounted query. The same row may be cached
+ // under another sort, view mode or filter, which a later (or offline) visit
+ // would paint with the old name: apply the confirmed row to every loaded
+ // and persisted variant.
+ const confirmed = stripOptimistic(result);
+ this.#resourceList.updateEntity<ResourceItem>(id, () => confirmed);
};
moveResource = async (id: string, parentId: string | null): Promise<void> => {
@@ -702,20 +788,22 @@ export class ResourceActionImpl {
// List rows may omit `parentId`; only a known parent can prove a no-op move.
if (existing.parentId !== undefined && (existing.parentId ?? null) === parentId) return;
- // The row lives in the current explorer list, so the current query's
- // parent names the source folder even when the row itself omits `parentId`.
+ // Capture what the completed move needs to reconcile the *other* folders'
+ // cached lists before the request goes out: the user may switch scope while
+ // it is in flight, after which neither the scope nor the old folders' slug
+ // aliases can be read from the store any more. A move of a row visible in
+ // the Explorer lands here (the tree delegates to this action), so this is
+ // the only place those caches get patched.
const cachePatch = await this.prepareResourceMoveCachePatch(
[existing.parentId, queryParams?.parentId ?? null],
parentId,
);
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`moveResource(${id})`);
- const movedResource: ResourceItem = {
+ const movedOptimistic: ResourceItem = {
...existing,
_optimistic: {
...(existing._optimistic || {
- queryKey: getResourceQueryKey(this.#get().queryParams),
+ queryKey: getResourceQueryKey(queryParams),
retryCount: 0,
}),
isPending: true,
@@ -723,39 +811,58 @@ export class ResourceActionImpl {
parentId,
updatedAt: new Date(),
};
- const shouldKeepVisible = !queryParams || this.#isResourceVisibleInCurrentQuery(movedResource);
+ const shouldKeepVisible =
+ !queryParams || this.#isResourceVisibleInCurrentQuery(movedOptimistic);
+ // The list the move starts from: the collapse below must only touch it,
+ // never a folder (or workspace) the user navigated to while in flight.
+ const originList = {
+ scope: resourceListResource.scope.get(),
+ storageKey: this.#requestedListStorageKey,
+ };
- tx.set((draft) => {
- if (shouldKeepVisible) {
- draft.resourceMap.set(id, movedResource);
- draft.resourceList = draft.resourceList.map((item) =>
- item.id === id ? movedResource : item,
- );
- return;
- }
+ const applyMove = (data: ResourceListValue, resource: ResourceItem) =>
+ shouldKeepVisible
+ ? this.#patchRow(data, id, () => resource)
+ : this.#removeRows(data, new Set([id]));
- draft.resourceList = draft.resourceList.filter((item) => item.id !== id);
- draft.resourceMap.delete(id);
- });
- tx.mutation = () => resourceService.moveResource(id, parentId, existing);
- tx.onSuccess = async (result) => {
- const moved = result as ResourceItem;
- if (shouldKeepVisible) this.#replaceLocalResource(id, moved);
+ const token = this.#beginListOptimistic((data) => applyMove(data, movedOptimistic));
- await this.applyMovedResourceToCaches(moved, cachePatch);
- };
+ let moved: ResourceItem;
+ try {
+ moved = (await resourceService.moveResource(id, parentId, existing)) as ResourceItem;
+ token?.commit((data) => applyMove(data, moved));
+ } catch (error) {
+ token?.rollback();
+ throw error;
+ }
- await tx.commit<ResourceItem>();
+ // A row that left the mounted folder shifts the loaded offsets, so the next
+ // "load more" would skip the row that moved up into the gap: drop the loaded
+ // depth to the head before confirming. Only while that folder is still the
+ // one on screen β€” the singleton entry may now hold another folder's pages,
+ // whose offsets the move did not shift.
+ if (
+ !shouldKeepVisible &&
+ originList.storageKey !== undefined &&
+ originList.storageKey === this.#requestedListStorageKey &&
+ originList.scope === resourceListResource.scope.get()
+ ) {
+ this.#resourceList.collapse(RESOURCE_LIST_KEY);
+ }
+
+ // The server accepted the move, so a reconciliation failure must not undo it
+ // or report the operation as failed (the caller β€” the tree's optimistic
+ // transaction β€” would restore a row the server already moved).
+ await this.applyMovedResourceToCaches(moved, cachePatch);
};
/**
- * Everything a completed move needs to patch the SWR folder-list caches,
- * gathered *before* the request goes out: the workspace / library the move
- * is issued from, and both folders widened to every key the explorer may
- * query them by (`queryParams.parentId` carries the URL slug while drop
- * targets and the sidebar tree address folders by id). The user may switch
- * scope while the request is in flight, after which neither the scope nor
- * the old folders' slug aliases can be read from the store any more.
+ * Everything a completed move needs to reconcile the explorer's other folder
+ * lists, gathered *before* the request goes out: the workspace / library the
+ * move is issued from, and both folders widened to every key the explorer may
+ * query them by. The user may switch scope while the request is in flight,
+ * after which neither the scope nor the old folders' slug aliases can be read
+ * from the store any more.
*
* Callers pass whatever handle they hold for each folder β€” a drop target
* id, a URL slug or an empty root.
@@ -763,9 +870,12 @@ export class ResourceActionImpl {
prepareResourceMoveCachePatch = async (
fromParent: ResourceParentKey | undefined | Array<ResourceParentKey | undefined>,
toParent: ResourceParentKey | undefined | Array<ResourceParentKey | undefined>,
- ): Promise<ResourceMoveCachePatch> => {
+ ) => {
const scope = {
libraryId: this.#get().queryParams?.libraryId,
+ // The replica partition includes the user, not just the workspace: two
+ // users in personal mode (or the same workspace) share a workspace id.
+ replicaScope: resourceListResource.scope.get(),
workspaceId: getActiveWorkspaceId(),
};
const [fromParentKeys, toParentKeys] = await Promise.all([
@@ -777,73 +887,201 @@ export class ResourceActionImpl {
};
/**
- * Mirror a completed move into the SWR folder-list caches so the destination
- * (and source) folder show the moved row on their next visit instead of the
- * cached pre-move list. `patch` comes from `prepareResourceMoveCachePatch`,
- * taken before the request.
+ * Reconcile a completed move into every cached list of the two folders the
+ * move touched β€” not only the mounted one. The patch was captured before the
+ * request (scope + both folders widened to every key the explorer may query
+ * them by), because the user may switch scope while it is in flight.
+ *
+ * The mounted list is patched through the in-memory entry; every other cached
+ * folder is patched through its persisted row, so an offline navigation
+ * hydrates the reconciled page instead of the pre-move one. The moved row is
+ * dropped from a source folder and seeded into a destination folder only when
+ * that list is an unfiltered folder listing the row certainly belongs to.
+ * Reconcile only while the issuing scope is still active: after a workspace or
+ * library switch the mounted replica answers another identity / query.
*/
applyMovedResourceToCaches = async (
resource: ResourceItem,
- patch: ResourceMoveCachePatch,
+ patch: Awaited<ReturnType<ResourceActionImpl['prepareResourceMoveCachePatch']>>,
): Promise<void> => {
- const { applyResourceMoveToListCaches } = await import('./hooks');
- await applyResourceMoveToListCaches(resource, patch);
+ // A sign-out / sign-in or a workspace switch while the move was in flight:
+ // the mounted replica and its persisted rows now belong to another
+ // identity, so the moved row must not be written into them.
+ if (resourceListResource.scope.get() !== patch.scope.replicaScope) return;
+ if (getActiveWorkspaceId() !== patch.scope.workspaceId) return;
+ if ((this.#get().queryParams?.libraryId ?? undefined) !== patch.scope.libraryId) return;
+
+ const moved = stripOptimistic(resource);
+ const toKeys = new Set(patch.toParentKeys);
+ const fromKeys = new Set(patch.fromParentKeys.filter((key) => !toKeys.has(key)));
+
+ const reconcileFolderList = (data: ResourceListValue): ResourceListValue | undefined => {
+ const params = data.queryParams;
+ if (!params || (params.libraryId ?? undefined) !== patch.scope.libraryId) return undefined;
+
+ const parentId = params.parentId ?? null;
+ if (fromKeys.has(parentId)) return patchSourceList(data, moved.id);
+ if (toKeys.has(parentId) && listsMovedRowUnfiltered(params, moved)) {
+ return patchDestinationList(data, moved, params);
+ }
+ return undefined;
+ };
+
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) => (data ? (reconcileFolderList(data) ?? data) : data),
+ { persist: true },
+ );
+ await this.#resourceList.patchStoredRows((data) => reconcileFolderList(data));
+
+ await this.#revalidateListQuietly('applyMovedResourceToCaches');
+ };
+
+ // ---- local-only row edits (upload / optimistic search paths) ------------
+
+ insertLocalResource = (params: CreateResourceParams, id?: string): string => {
+ const optimistic = this.#createOptimisticResource(params, id);
+
+ this.#ensureListView();
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) => (data ? this.#insertRow(data, optimistic) : data),
+ { persist: false },
+ );
+
+ return optimistic.id;
};
removeLocalResource = (id: string): void => {
- this.#set(
- (state) => {
- const resourceMap = new Map(state.resourceMap);
- resourceMap.delete(id);
-
- return {
- resourceList: state.resourceList.filter((item) => item.id !== id),
- resourceMap,
- };
- },
- false,
- 'resource/removeLocalResource',
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) => (data ? this.#removeRows(data, new Set([id])) : data),
+ { persist: false },
);
};
replaceLocalResource = (tempId: string, resource: ResourceItem): void => {
- this.#replaceLocalResource(tempId, resource);
+ this.#ensureListView();
+
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) => {
+ if (!data) return data;
+
+ const hasTemp = data.items.some((item) => item.id === tempId);
+ if (hasTemp) return this.#replaceRow(data, tempId, resource);
+ if (data.items.some((item) => item.id === resource.id)) {
+ return this.#patchRow(data, resource.id, () => resource);
+ }
+ // Slug-vs-UUID mismatches can hide the temp row; a resource that belongs
+ // in the open folder should still surface.
+ if (this.#isResourceVisibleInCurrentQuery(resource)) return this.#insertRow(data, resource);
+ return data;
+ },
+ { persist: false },
+ );
};
- retrySync = async (): Promise<void> => {
- await this.flushSync();
+ patchLocalResource = (
+ id: string,
+ updates: Partial<ResourceItem>,
+ _actionName: string = 'resource/patchLocalResource',
+ ): void => {
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) =>
+ data ? this.#patchRow(data, id, (resource) => ({ ...resource, ...updates })) : data,
+ { persist: false },
+ );
};
+ patchLocalResourceStatuses = (
+ items: Array<
+ Pick<
+ ResourceItem,
+ | 'id'
+ | 'chunkCount'
+ | 'chunkingError'
+ | 'chunkingStatus'
+ | 'embeddingError'
+ | 'embeddingStatus'
+ | 'finishEmbedding'
+ >
+ >,
+ ): void => {
+ if (items.length === 0) return;
+
+ const statusMap = new Map(items.map((item) => [item.id, item]));
+
+ this.#resourceList.update(
+ RESOURCE_LIST_KEY,
+ (data) => {
+ if (!data) return data;
+
+ let changed = false;
+ const rows = data.items.map((resource) => {
+ const status =
+ statusMap.get(resource.id) ?? (resource.fileId && statusMap.get(resource.fileId));
+ if (!status) return resource;
+
+ changed = true;
+ return {
+ ...resource,
+ chunkCount: status.chunkCount !== undefined ? status.chunkCount : resource.chunkCount,
+ chunkingError:
+ status.chunkingError !== undefined ? status.chunkingError : resource.chunkingError,
+ chunkingStatus:
+ status.chunkingStatus !== undefined ? status.chunkingStatus : resource.chunkingStatus,
+ embeddingError:
+ status.embeddingError !== undefined ? status.embeddingError : resource.embeddingError,
+ embeddingStatus:
+ status.embeddingStatus !== undefined
+ ? status.embeddingStatus
+ : resource.embeddingStatus,
+ finishEmbedding:
+ status.finishEmbedding !== undefined
+ ? status.finishEmbedding
+ : resource.finishEmbedding,
+ };
+ });
+
+ return changed ? { ...data, items: rows } : data;
+ },
+ { persist: true },
+ );
+ };
+
+ // ---- knowledge base membership -----------------------------------------
+
addResourcesToKnowledgeBase = async (knowledgeBaseId: string, ids: string[]): Promise<void> => {
if (ids.length === 0) return;
const idsSet = new Set(ids);
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`addResourcesToKnowledgeBase(${knowledgeBaseId})`);
-
- tx.set((draft) => {
- for (const item of draft.resourceList) {
- if (!idsSet.has(item.id)) continue;
-
- const nextItem = this.#toPendingResource(item, { knowledgeBaseId });
- draft.resourceMap.set(item.id, nextItem);
- }
+ const token = this.#beginListOptimistic((data) =>
+ this.#patchRows(data, idsSet, (resource) => ({
+ ...resource,
+ _optimistic: {
+ ...(resource._optimistic || {
+ queryKey: getResourceQueryKey(this.#get().queryParams),
+ retryCount: 0,
+ }),
+ isPending: true,
+ },
+ knowledgeBaseId,
+ })),
+ );
- draft.resourceList = draft.resourceList.map((item) => {
- if (!idsSet.has(item.id)) return item;
- return draft.resourceMap.get(item.id) ?? item;
- });
- });
- tx.mutation = () => knowledgeBaseService.addFilesToKnowledgeBase(knowledgeBaseId, ids);
- tx.onSuccess = async () => {
- this.#patchLocalResourceEntries(
- idsSet,
- (resource) => this.#clearResourceOptimisticState({ ...resource, knowledgeBaseId }),
- 'resource/addResourcesToKnowledgeBase/success',
+ try {
+ await knowledgeBaseService.addFilesToKnowledgeBase(knowledgeBaseId, ids);
+ this.#commitListOptimistic(token, 'addResourcesToKnowledgeBase', (data) =>
+ this.#patchRows(data, idsSet, (resource) =>
+ this.#clearSyncingOptimistic({ ...resource, knowledgeBaseId }),
+ ),
);
- };
-
- await tx.commit<void>();
+ } catch (error) {
+ token?.rollback();
+ throw toError(error);
+ }
};
removeResourcesFromKnowledgeBase = async (
@@ -854,98 +1092,44 @@ export class ResourceActionImpl {
const idsSet = new Set(ids);
const isKnowledgeBaseView = this.#get().queryParams?.libraryId === knowledgeBaseId;
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`removeResourcesFromKnowledgeBase(${knowledgeBaseId})`);
-
- tx.set((draft) => {
- if (isKnowledgeBaseView) {
- let visibleChangedCount = 0;
-
- draft.resourceList = draft.resourceList.filter((item) => {
- if (!idsSet.has(item.id)) return true;
-
- draft.resourceMap.delete(item.id);
- visibleChangedCount += 1;
- return false;
- });
-
- if (typeof draft.total === 'number') {
- draft.total = Math.max(0, draft.total - ids.length);
- draft.hasMore = draft.total > draft.resourceList.length;
- }
-
- draft.offset = Math.max(0, draft.offset - visibleChangedCount);
- return;
- }
-
- for (const item of draft.resourceList) {
- if (!idsSet.has(item.id)) continue;
-
- const nextItem = this.#toPendingResource(item, { knowledgeBaseId: undefined });
- draft.resourceMap.set(item.id, nextItem);
- }
-
- draft.resourceList = draft.resourceList.map((item) => {
- if (!idsSet.has(item.id)) return item;
- return draft.resourceMap.get(item.id) ?? item;
- });
- });
- tx.mutation = () => knowledgeBaseService.removeFilesFromKnowledgeBase(knowledgeBaseId, ids);
- tx.onSuccess = async () => {
- if (isKnowledgeBaseView) return;
-
- this.#patchLocalResourceEntries(
- idsSet,
- (resource) =>
- this.#clearResourceOptimisticState({
+ const token = this.#beginListOptimistic((data) =>
+ isKnowledgeBaseView
+ ? this.#removeRows(data, idsSet)
+ : this.#patchRows(data, idsSet, (resource) => ({
...resource,
+ _optimistic: {
+ ...(resource._optimistic || {
+ queryKey: getResourceQueryKey(this.#get().queryParams),
+ retryCount: 0,
+ }),
+ isPending: true,
+ },
knowledgeBaseId: undefined,
- }),
- 'resource/removeResourcesFromKnowledgeBase/success',
- );
- };
-
- await tx.commit<void>();
- };
-
- updateResource = async (id: string, updates: UpdateResourceParams): Promise<void> => {
- const { resourceMap } = this.#get();
- const existing = resourceMap.get(id);
+ })),
+ );
- if (!existing) {
- console.warn(`Resource ${id} not found for update`);
- return;
+ try {
+ await knowledgeBaseService.removeFilesFromKnowledgeBase(knowledgeBaseId, ids);
+ if (isKnowledgeBaseView) {
+ this.#commitListOptimistic(token, 'removeResourcesFromKnowledgeBase');
+ // The rows left the server's page too, so the loaded depth no longer
+ // lines up with the survivors. Drop the loaded pages to the head first:
+ // the confirmation then repaints a real head page and "load more"
+ // restarts from offset 1 instead of skipping the row that shifted up
+ // into the gap (a multi-page list kept its old cursor otherwise).
+ this.#resourceList.collapse(RESOURCE_LIST_KEY);
+ await this.#revalidateListQuietly('removeResourcesFromKnowledgeBase');
+ } else {
+ this.#commitListOptimistic(token, 'removeResourcesFromKnowledgeBase', (data) =>
+ this.#patchRows(data, idsSet, (resource) =>
+ this.#clearSyncingOptimistic({ ...resource, knowledgeBaseId: undefined }),
+ ),
+ );
+ }
+ } catch (error) {
+ token?.rollback();
+ throw toError(error);
}
-
- const updated: ResourceItem = {
- ...existing,
- ...updates,
- _optimistic: {
- ...(existing._optimistic || {
- queryKey: getResourceQueryKey(this.#get().queryParams),
- retryCount: 0,
- }),
- isPending: true,
- },
- name: updates.name || updates.title || existing.name,
- updatedAt: new Date(),
- };
-
- log('updateResource', id, existing, updates);
-
- const syncEngine = this.#getSyncEngine();
- const tx = syncEngine.createTransaction(`updateResource(${id})`);
-
- tx.set((draft) => {
- draft.resourceMap.set(id, updated);
- draft.resourceList = draft.resourceList.map((item) => (item.id === id ? updated : item));
- });
- tx.mutation = () => resourceService.updateResource(id, updates);
- tx.onSuccess = async (result) => {
- this.#replaceLocalResource(id, result as ResourceItem);
- };
-
- await tx.commit<ResourceItem>();
};
}
diff --git a/src/store/file/slices/resource/hooks.test.ts b/src/store/file/slices/resource/hooks.test.ts
deleted file mode 100644
index c0cb919fc77..00000000000
--- a/src/store/file/slices/resource/hooks.test.ts
+++ /dev/null
@@ -1,522 +0,0 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- getActiveWorkspaceId,
- useActiveWorkspaceId,
-} from '@/business/client/hooks/useActiveWorkspaceId';
-import { mutate } from '@/libs/swr';
-import type { FilesTabs } from '@/types/files';
-
-import {
- applyResourceMoveToListCaches,
- patchDestinationList,
- patchSourceList,
- revalidateResources,
- useFetchResources,
-} from './hooks';
-
-const mocks = vi.hoisted(() => ({
- mutate: vi.fn(),
- fileState: {
- hasMore: false,
- queryParams: undefined as any,
- resourceList: [] as any[],
- resourceMap: new Map<string, any>(),
- total: 0,
- },
- queryParams: {
- category: 'audios' as FilesTabs,
- parentId: null,
- showFilesInKnowledgeBase: false,
- },
- useClientDataSWR: vi.fn(() => ({ data: undefined as any })),
- activeWorkspaceId: null as string | null,
-}));
-
-vi.mock('@/libs/swr', () => ({
- mutate: mocks.mutate,
- useClientDataSWR: mocks.useClientDataSWR,
-}));
-
-vi.mock('../../store', () => ({
- useFileStore: {
- getState: () => mocks.fileState,
- setState: vi.fn((nextState) => {
- mocks.fileState = {
- ...mocks.fileState,
- ...nextState,
- };
- }),
- },
-}));
-
-vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- getActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),
- useActiveWorkspaceId: vi.fn(() => mocks.activeWorkspaceId),
-}));
-
-describe('revalidateResources', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.activeWorkspaceId = null;
- mocks.fileState = {
- hasMore: false,
- queryParams: mocks.queryParams,
- resourceList: [],
- resourceMap: new Map(),
- total: 0,
- };
- });
-
- it('matches workspace-scoped resource SWR keys', async () => {
- mocks.activeWorkspaceId = 'workspace-1';
-
- await revalidateResources();
-
- const [matcher] = vi.mocked(mutate).mock.calls[0] as [(key: unknown) => boolean];
-
- expect(matcher).toEqual(expect.any(Function));
- expect(matcher(['resource:list', mocks.queryParams, 'workspace-1'])).toBe(true);
- expect(matcher(['resource:list', mocks.queryParams, 'workspace-2'])).toBe(false);
- expect(matcher(['resource:list', mocks.queryParams])).toBe(false);
- expect(matcher(['OTHER_KEY', mocks.queryParams, 'workspace-1'])).toBe(false);
- expect(getActiveWorkspaceId).toHaveBeenCalled();
- });
-});
-
-describe('patchDestinationList', () => {
- const row = (id: string, createdAt: string, extra: Record<string, unknown> = {}) =>
- ({ createdAt: new Date(createdAt), id, name: id, size: 1, ...extra }) as any;
- const moved = row('moved', '2026-09-15T00:00:00.000Z');
-
- it('inserts newest-first when the list has no explicit sort', () => {
- const newer = row('newer', '2026-09-20T00:00:00.000Z');
- const older = row('older', '2026-09-10T00:00:00.000Z');
-
- expect(
- patchDestinationList({ hasMore: false, items: [newer, older], total: 2 }, moved, {}),
- ).toEqual({ hasMore: false, items: [newer, moved, older], total: 3 });
- });
-
- it('follows the list sort when both halves are set, like the server does', () => {
- const a = row('a', '2026-09-01T00:00:00.000Z', { name: 'Apple' });
- const z = row('z', '2026-09-02T00:00:00.000Z', { name: 'Zebra' });
- const named = { ...moved, name: 'Mango' };
-
- expect(
- patchDestinationList({ hasMore: false, items: [a, z] }, named, {
- sortType: 'asc' as any,
- sorter: 'name',
- })!.items.map((item: any) => item.id),
- ).toEqual(['a', 'moved', 'z']);
- expect(
- patchDestinationList({ hasMore: false, items: [z, a] }, named, {
- sortType: 'desc' as any,
- sorter: 'name',
- })!.items.map((item: any) => item.id),
- ).toEqual(['z', 'moved', 'a']);
- // A sorter without a sortType is newest-first on the server too.
- expect(
- patchDestinationList({ hasMore: false, items: [z, a] }, named, { sorter: 'name' })!.items.map(
- (item: any) => item.id,
- ),
- ).toEqual(['moved', 'z', 'a']);
- });
-
- it('keeps a full page at its length so "load more" resumes at the right offset', () => {
- const page = Array.from({ length: 3 }, (_, i) =>
- row(`row-${i}`, `2026-09-2${i}T00:00:00.000Z`),
- ).reverse(); // newest first: row-2, row-1, row-0
- const inside = row('inside', '2026-09-21T12:00:00.000Z');
-
- // Sorts inside the page: the last cached row falls off and is fetched
- // again at the same server offset.
- expect(patchDestinationList({ hasMore: true, items: page, total: 10 }, inside, {})).toEqual({
- hasMore: true,
- items: [page[0], inside, page[1]],
- total: 11,
- });
-
- // Sorts past the page: a later page will hold it, nothing is skipped.
- const beyond = row('beyond', '2026-09-01T00:00:00.000Z');
- expect(patchDestinationList({ hasMore: true, items: page, total: 10 }, beyond, {})).toEqual({
- hasMore: true,
- items: page,
- total: 11,
- });
- });
-
- it('lets the last loaded page grow when there is nothing more to load', () => {
- const only = row('only', '2026-09-20T00:00:00.000Z');
- const beyond = row('beyond', '2026-09-01T00:00:00.000Z');
-
- expect(patchDestinationList({ hasMore: false, items: [only], total: 1 }, beyond, {})).toEqual({
- hasMore: false,
- items: [only, beyond],
- total: 2,
- });
- });
-
- it('keeps one copy of a row the destination already lists (a retried move)', () => {
- const other = row('other', '2026-09-20T00:00:00.000Z');
-
- expect(
- patchDestinationList({ hasMore: true, items: [other, moved], total: 2 }, moved, {}),
- ).toEqual({ hasMore: true, items: [other, moved], total: 2 });
- });
-
- it('never seeds a folder that has no cache: its first visit must fetch', () => {
- expect(patchDestinationList(undefined, moved, {})).toBeUndefined();
- });
-});
-
-describe('patchSourceList', () => {
- const moved = { id: 'doc-1' } as any;
- const other = { id: 'doc-2' } as any;
-
- it('drops the moved row and returns the same object when it was not listed', () => {
- expect(patchSourceList({ hasMore: true, items: [other, moved], total: 2 }, moved)).toEqual({
- hasMore: true,
- items: [other],
- total: 1,
- });
- const untouched = { hasMore: false, items: [other], total: 1 };
- expect(patchSourceList(untouched, moved)).toBe(untouched);
- expect(patchSourceList(undefined, moved)).toBeUndefined();
- });
-});
-
-describe('applyResourceMoveToListCaches', () => {
- type Matcher = (key: unknown) => boolean;
- type Updater = (data: any) => Promise<any>;
- type MutateCall = [Matcher, Updater, { revalidate: boolean }];
-
- const moved = {
- createdAt: new Date('2026-09-15T00:00:00.000Z'),
- id: 'doc-1',
- name: 'Weekly report',
- parentId: 'folder-w37',
- };
- const scope = { libraryId: 'kb-1', workspaceId: 'workspace-1' };
- const listKey = (parentId: string | null, extra: Record<string, unknown> = {}) => [
- 'resource:list',
- { libraryId: 'kb-1', parentId, showFilesInKnowledgeBase: false, ...extra },
- 'workspace-1',
- ];
-
- /** Keys the SWR cache holds; the mocked `mutate` offers them to every matcher. */
- let cachedKeys: unknown[] = [];
-
- beforeEach(() => {
- vi.clearAllMocks();
- cachedKeys = [];
- vi.mocked(mutate).mockImplementation((async (key: unknown) => {
- if (typeof key === 'function') for (const cached of cachedKeys) (key as Matcher)(cached);
- }) as any);
- // Scope comes from the caller; the active workspace/library must not matter.
- mocks.activeWorkspaceId = 'workspace-9';
- mocks.fileState = {
- hasMore: false,
- queryParams: { libraryId: 'kb-9', parentId: 'elsewhere', showFilesInKnowledgeBase: false },
- resourceList: [],
- resourceMap: new Map(),
- total: 0,
- };
- });
-
- const runMove = async (
- patch: Partial<Parameters<typeof applyResourceMoveToListCaches>[1]> = {},
- ) => {
- await applyResourceMoveToListCaches(moved as any, {
- fromParentKeys: ['folder-2026-09', 'folder-2026-09-id'],
- scope,
- toParentKeys: ['folder-w37', 'w37-slug'],
- ...patch,
- });
-
- const calls = vi.mocked(mutate).mock.calls as unknown as MutateCall[];
- const [collect, ...rest] = calls;
- const reconcile = rest.at(-1)!;
- const writes = rest.slice(0, -1);
- return { collect, reconcile, writes };
- };
-
- it('enumerates the cached destination lists without writing to them', async () => {
- cachedKeys = [listKey('folder-w37'), listKey('w37-slug', { sorter: 'name' })];
- const { collect } = await runMove();
- const [matcher, data, options] = collect;
-
- expect(options).toEqual({ revalidate: false });
- expect(data).toBeUndefined();
- // The collecting matcher accepts nothing, so SWR mutates nothing.
- expect(matcher(listKey('folder-w37'))).toBe(false);
- });
-
- it('patches each cached destination list in its own sort, scoped to the given workspace and library', async () => {
- const byName = listKey('w37-slug', { sortType: 'asc', sorter: 'name' });
- cachedKeys = [
- listKey('folder-w37'),
- byName,
- listKey('folder-2026-09'),
- listKey(null),
- ['resource:list', { libraryId: 'kb-2', parentId: 'folder-w37' }, 'workspace-1'],
- ['resource:list', { libraryId: 'kb-1', parentId: 'folder-w37' }, 'workspace-2'],
- ['resource:list', { libraryId: 'kb-1', parentId: 'folder-w37' }, 'workspace-9'],
- ['resource:recentFiles', 'workspace-1'],
- ];
- const { writes } = await runMove();
- const destinationWrites = writes.filter(
- ([matcher]) => matcher(byName) || matcher(listKey('folder-w37')),
- );
-
- expect(destinationWrites).toHaveLength(2);
- for (const [, , options] of destinationWrites) expect(options).toEqual({ revalidate: false });
-
- const [, updateByName] = destinationWrites.find(([matcher]) => matcher(byName))!;
- const apple = { createdAt: new Date('2026-09-20T00:00:00.000Z'), id: 'a', name: 'Apple' };
- const zebra = { createdAt: new Date('2026-09-21T00:00:00.000Z'), id: 'z', name: 'Zebra' };
- await expect(
- updateByName({ hasMore: false, items: [apple, zebra], total: 2 }),
- ).resolves.toEqual({
- hasMore: false,
- items: [apple, moved, zebra],
- total: 3,
- });
-
- const [, updateDefault] = destinationWrites.find(([matcher]) =>
- matcher(listKey('folder-w37')),
- )!;
- // Newest-first: both cached rows are newer, so the row goes after them.
- await expect(
- updateDefault({ hasMore: false, items: [apple, zebra], total: 2 }),
- ).resolves.toEqual({
- hasMore: false,
- items: [apple, zebra, moved],
- total: 3,
- });
- });
-
- it('only seeds plain destination listings; filtered variants are left to revalidate', async () => {
- const plain = listKey('folder-w37');
- const plainAll = listKey('folder-w37', { category: 'all', sourceFilter: 'all' });
- const filtered = [
- listKey('folder-w37', { q: 'weekly' }),
- listKey('folder-w37', { category: 'images' }),
- listKey('folder-w37', { sourceFilter: 'ai' }),
- listKey('folder-w37', { visibility: 'private' }),
- ];
- cachedKeys = [plain, plainAll, ...filtered];
- const { writes, reconcile } = await runMove();
- const destinationWrites = writes.filter(([matcher]) => matcher(plain) || matcher(plainAll));
-
- expect(destinationWrites).toHaveLength(2);
- for (const key of filtered) {
- expect(writes.some(([matcher]) => matcher(key))).toBe(false);
- // …but a mounted filtered list is still refetched.
- expect(reconcile[0](key)).toBe(true);
- }
- });
-
- it('keeps a library row out of a personal root that hides library files', async () => {
- const root = ['resource:list', { parentId: null, showFilesInKnowledgeBase: false }, null];
- const rootShowingLibraries = [
- 'resource:list',
- { parentId: null, showFilesInKnowledgeBase: true },
- null,
- ];
- cachedKeys = [root, rootShowingLibraries];
- await applyResourceMoveToListCaches({ ...moved, knowledgeBaseId: 'kb-1' } as any, {
- fromParentKeys: ['folder-w37'],
- scope: { libraryId: undefined, workspaceId: null },
- toParentKeys: [null],
- });
-
- const calls = vi.mocked(mutate).mock.calls as unknown as MutateCall[];
- const writes = calls.slice(1, -1);
- expect(writes.some(([matcher]) => matcher(root))).toBe(false);
- expect(writes.some(([matcher]) => matcher(rootShowingLibraries))).toBe(true);
- });
-
- it('drops the moved row from every cached source list', async () => {
- const { writes } = await runMove();
- const from = writes.find(([matcher]) => matcher(listKey('folder-2026-09')))!;
- const [matcher, updater, options] = from;
-
- expect(options).toEqual({ revalidate: false });
- expect(matcher(listKey('folder-2026-09-id'))).toBe(true);
- expect(matcher(listKey('folder-w37'))).toBe(false);
- expect(
- matcher(['resource:list', { libraryId: 'kb-1', parentId: 'folder-2026-09' }, 'workspace-9']),
- ).toBe(false);
-
- const other = { id: 'doc-2', name: 'Other' };
- await expect(updater({ hasMore: true, items: [other, moved], total: 2 })).resolves.toEqual({
- hasMore: true,
- items: [other],
- total: 1,
- });
- });
-
- it('refetches mounted source/destination lists without holding the caller', async () => {
- // A resolved-without-awaiting mutate: the reconcile is the last call and
- // the helper must resolve before that refetch does.
- let releaseRefetch!: () => void;
- vi.mocked(mutate).mockImplementation(((_: unknown, __: unknown, options: any) =>
- options?.revalidate
- ? new Promise<void>((resolve) => {
- releaseRefetch = resolve;
- })
- : Promise.resolve()) as any);
-
- const settled = vi.fn();
- void applyResourceMoveToListCaches(moved as any, {
- fromParentKeys: ['folder-2026-09'],
- scope,
- toParentKeys: ['folder-w37'],
- }).then(settled);
- // Enough microtask turns for the serialising queue plus the awaited writes.
- for (let i = 0; i < 20; i++) await Promise.resolve();
-
- expect(settled).toHaveBeenCalled();
-
- const calls = vi.mocked(mutate).mock.calls as unknown as MutateCall[];
- const [matcher, updater, options] = calls.at(-1)!;
- expect(options).toEqual({ revalidate: true });
- expect(matcher(listKey('folder-w37'))).toBe(true);
- expect(matcher(listKey('folder-2026-09'))).toBe(true);
- expect(matcher(listKey(null))).toBe(false);
- const current = { hasMore: false, items: [] };
- await expect(updater(current)).resolves.toBe(current);
-
- releaseRefetch();
- vi.mocked(mutate).mockReset();
- });
-
- it('runs concurrent patches one after another so none overwrites the other', async () => {
- // Two rows moved together: the second row's patch must read the list the
- // first one wrote, so its collect/mutate calls start only after the first
- // patch finished all of its writes.
- cachedKeys = [listKey('folder-w37')];
- const order: string[] = [];
- let releaseFirstWrite: () => void = () => {};
- let armed = false;
- vi.mocked(mutate).mockImplementation((async (key: unknown, data: unknown, options: any) => {
- if (typeof key === 'function') for (const cached of cachedKeys) (key as Matcher)(cached);
- // collect: no data; write: updater + revalidate false; reconcile: revalidate true
- const kind = options?.revalidate ? 'reconcile' : data === undefined ? 'collect' : 'write';
- order.push(kind);
- if (kind === 'write' && !armed) {
- armed = true;
- await new Promise<void>((resolve) => {
- releaseFirstWrite = resolve;
- });
- }
- }) as any);
-
- const patch = { fromParentKeys: [null], scope, toParentKeys: ['folder-w37'] };
- const first = applyResourceMoveToListCaches(moved as any, patch);
- const second = applyResourceMoveToListCaches({ ...moved, id: 'doc-2' } as any, patch);
- try {
- for (let i = 0; i < 10; i++) await Promise.resolve();
-
- // First patch: keys enumerated, destination + source writes issued (the
- // destination one hangs). The second patch has not started at all.
- expect(order).toEqual(['collect', 'write', 'write']);
- } finally {
- releaseFirstWrite();
- }
- await first;
- await second;
-
- expect(order).toEqual([
- 'collect',
- 'write',
- 'write',
- 'reconcile',
- 'collect',
- 'write',
- 'write',
- 'reconcile',
- ]);
- });
-
- it('matches root lists with a null parent key', async () => {
- const { writes } = await runMove({ fromParentKeys: [null], toParentKeys: ['folder-w37'] });
- const [matcher] = writes.find(([m]) => m(listKey(null)))!;
-
- expect(matcher(['resource:list', { libraryId: 'kb-1' }, 'workspace-1'])).toBe(true);
- expect(matcher(listKey('folder-w37'))).toBe(false);
- });
-
- it('strips optimistic markers before the row lands in a cache', async () => {
- cachedKeys = [listKey('folder-w37')];
- await applyResourceMoveToListCaches(
- { ...moved, _optimistic: { isPending: true, retryCount: 0 } } as any,
- { fromParentKeys: [null], scope, toParentKeys: ['folder-w37'] },
- );
-
- const calls = vi.mocked(mutate).mock.calls as unknown as MutateCall[];
- const [, toUpdater] = calls.slice(1).find(([matcher]) => matcher(listKey('folder-w37')))!;
- const result = await toUpdater({ hasMore: false, items: [] });
- expect(result.items[0]).toEqual(moved);
- expect(result.total).toBeUndefined();
- });
-});
-
-describe('useFetchResources', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.activeWorkspaceId = null;
- mocks.fileState = {
- hasMore: false,
- queryParams: mocks.queryParams,
- resourceList: [],
- resourceMap: new Map(),
- total: 0,
- };
- mocks.useClientDataSWR.mockReturnValue({ data: undefined });
- });
-
- it('scopes the resource SWR key by active workspace', () => {
- mocks.activeWorkspaceId = 'workspace-1';
-
- renderHook(() => useFetchResources(mocks.queryParams));
-
- expect(mocks.useClientDataSWR).toHaveBeenCalledWith(
- ['resource:list', mocks.queryParams, 'workspace-1'],
- expect.any(Function),
- expect.any(Object),
- );
- expect(useActiveWorkspaceId).toHaveBeenCalled();
- });
-
- it('syncs query params when the returned list is unchanged', async () => {
- const resource = { id: 'resource-1', name: 'Report' };
- const nextQueryParams = {
- ...mocks.queryParams,
- category: 'documents' as FilesTabs,
- };
- mocks.fileState = {
- hasMore: false,
- queryParams: mocks.queryParams,
- resourceList: [resource],
- resourceMap: new Map([[resource.id, resource]]),
- total: 1,
- };
- mocks.useClientDataSWR.mockReturnValue({
- data: {
- hasMore: false,
- items: [resource],
- total: 1,
- },
- });
-
- renderHook(() => useFetchResources(nextQueryParams));
-
- await waitFor(() => {
- expect(mocks.fileState.queryParams).toBe(nextQueryParams);
- });
- expect(mocks.fileState.resourceList).toEqual([resource]);
- });
-});
diff --git a/src/store/file/slices/resource/hooks.ts b/src/store/file/slices/resource/hooks.ts
index a37ec8a50be..e2afba3f653 100644
--- a/src/store/file/slices/resource/hooks.ts
+++ b/src/store/file/slices/resource/hooks.ts
@@ -1,52 +1,10 @@
-import { isEqual } from 'es-toolkit';
-import { useEffect } from 'react';
import { shallow } from 'zustand/shallow';
-import {
- getActiveWorkspaceId,
- useActiveWorkspaceId,
-} from '@/business/client/hooks/useActiveWorkspaceId';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { resourceKeys } from '@/libs/swr/keys';
-import { resourceService } from '@/services/resource';
-import type { ResourceItem, ResourceQueryParams } from '@/types/resource';
+import { revalidateReplica } from '@/libs/replica';
+import { type ResourceQueryParams } from '@/types/resource';
import { useFileStore } from '../../store';
-import { mergeServerResourcesWithOptimistic } from './utils';
-
-type ResourceSWRKey = [string, ResourceQueryParams, string | null];
-
-const isResourceSWRKey = (
- key: unknown,
- queryParams: ResourceQueryParams,
- workspaceId: string | null,
-) => {
- if (!Array.isArray(key)) return false;
-
- return (
- key[0] === resourceKeys.list.root && isEqual(key[1], queryParams) && key[2] === workspaceId
- );
-};
-
-/**
- * Revalidate resources with current or specific query params
- * This can be called from outside React components (e.g., store actions)
- */
-export const revalidateResources = async (params?: ResourceQueryParams) => {
- const queryParams = params || useFileStore.getState().queryParams;
- const workspaceId = getActiveWorkspaceId();
- if (queryParams) {
- await mutate(
- (key) => isResourceSWRKey(key, queryParams, workspaceId),
- async (currentData) => currentData,
- {
- revalidate: true,
- },
- );
- }
-};
-
-type ResourceListData = { hasMore: boolean; items: ResourceItem[]; total?: number };
+import { resourceListResource } from './projection';
/** Parent identifiers for one folder: its id, its slug, or `null` for the root. */
export type ResourceParentKey = string | null;
@@ -54,12 +12,14 @@ export type ResourceParentKey = string | null;
/**
* The workspace and library a move was issued from. Captured *before* the
* request (`prepareResourceMoveCachePatch` on the file store): the user may
- * switch workspace or library while it is in flight, and the caches to patch
- * are the ones that listed the row, not the newly active scope.
+ * switch workspace or library while it is in flight, and the rows to reconcile
+ * belong to the scope that listed them, not the newly active one.
*/
export interface ResourceMoveCacheScope {
/** Library the explorer was showing, `undefined` outside a library. */
libraryId: string | undefined;
+ /** Replica partition (`user:workspace`) the move was issued under. */
+ replicaScope: string;
workspaceId: string | null;
}
@@ -71,297 +31,28 @@ export interface ResourceMoveCachePatch {
toParentKeys: ResourceParentKey[];
}
-const isResourceListKeyForParent = (
- key: unknown,
- { workspaceId, libraryId }: ResourceMoveCacheScope,
- parentKeys: Set<ResourceParentKey>,
-): key is ResourceSWRKey => {
- if (!Array.isArray(key)) return false;
- if (key[0] !== resourceKeys.list.root || key[2] !== workspaceId) return false;
-
- const params = key[1] as ResourceQueryParams | undefined;
- if (!params || params.libraryId !== libraryId) return false;
-
- return parentKeys.has(params.parentId ?? null);
-};
-
-/**
- * Whether a cached list is a plain folder listing the moved row certainly
- * belongs to. A list narrowed by a keyword, a category tab, a source chip or a
- * visibility mode may or may not include the row, and the server owns those
- * rules; such variants are left for revalidation rather than seeded with a row
- * that might not match. The personal root's default `showFilesInKnowledgeBase:
- * false` hides library rows, so a row that belongs to a library stays out.
- */
-const listsMovedRowUnfiltered = (params: ResourceQueryParams, resource: ResourceItem) => {
- if (params.q?.trim()) return false;
- if (params.category && params.category !== 'all') return false;
- if (params.sourceFilter && params.sourceFilter !== 'all') return false;
- if (params.visibility) return false;
- if (!params.libraryId && !params.showFilesInKnowledgeBase && resource.knowledgeBaseId) {
- return false;
- }
- return true;
-};
-
-const stripOptimistic = (resource: ResourceItem): ResourceItem => {
- const { _optimistic, ...rest } = resource;
- void _optimistic;
- return rest;
-};
-
-const toTime = (value: Date | string | number | undefined | null) =>
- value == null ? 0 : new Date(value).getTime();
-
-const SORT_ACCESSORS: Record<string, (item: ResourceItem) => number | string> = {
- createdAt: (item) => toTime(item.createdAt),
- name: (item) => item.name ?? '',
- size: (item) => item.size ?? 0,
- updatedAt: (item) => toTime(item.updatedAt),
-};
-
-/**
- * The order the server returns a list in, mirrored from the knowledge
- * repository's `orderBy`: both `sorter` and `sortType` have to be present for a
- * custom sort, anything else is newest-first.
- */
-const compareResourcesForList = ({ sorter, sortType }: ResourceQueryParams) => {
- const custom = sorter && sortType && sorter in SORT_ACCESSORS;
- const accessor = custom ? SORT_ACCESSORS[sorter] : SORT_ACCESSORS.createdAt;
- const direction = custom && String(sortType).toLowerCase() === 'asc' ? 1 : -1;
-
- return (a: ResourceItem, b: ResourceItem) => {
- const left = accessor(a);
- const right = accessor(b);
- const order =
- typeof left === 'string' && typeof right === 'string'
- ? left.localeCompare(right)
- : Number(left) - Number(right);
- return order * direction;
- };
-};
-
/**
- * Put the moved row where the server would list it. A cached page keeps its
- * length: `useFetchResources` derives the next `offset` from the cached row
- * count, so a page that grew past its limit would make "load more" skip a
- * server row. On a full page the row is either placed in order (the row that
- * falls off the end reappears at that same server offset) or, when it sorts
- * past everything cached, left for the later page that will contain it.
+ * Revalidate resources with current or specific query params.
+ * This can be called from outside React components (e.g., store actions).
*/
-export const patchDestinationList = (
- currentData: ResourceListData | undefined,
- movedResource: ResourceItem,
- params: ResourceQueryParams,
-): ResourceListData | undefined => {
- if (!currentData) return currentData;
-
- const remaining = currentData.items.filter((item) => item.id !== movedResource.id);
- const removed = currentData.items.length - remaining.length;
- const total = currentData.total === undefined ? undefined : currentData.total - removed + 1;
-
- const compare = compareResourcesForList(params);
- const position = remaining.findIndex((item) => compare(movedResource, item) < 0);
- const inserted =
- position === -1
- ? [...remaining, movedResource]
- : [...remaining.slice(0, position), movedResource, ...remaining.slice(position)];
-
- const pageLength = currentData.items.length;
- if (!currentData.hasMore || inserted.length <= pageLength) {
- return { ...currentData, items: inserted, total };
- }
-
- return {
- ...currentData,
- items: position === -1 ? remaining : inserted.slice(0, pageLength),
- total,
- };
-};
-
-export const patchSourceList = (
- currentData: ResourceListData | undefined,
- movedResource: ResourceItem,
-): ResourceListData | undefined => {
- if (!currentData) return currentData;
-
- const remaining = currentData.items.filter((item) => item.id !== movedResource.id);
- if (remaining.length === currentData.items.length) return currentData;
+export const revalidateResources = async (params?: ResourceQueryParams) => {
+ const queryParams = params || useFileStore.getState().queryParams;
+ if (!queryParams) return;
- return {
- ...currentData,
- items: remaining,
- total: currentData.total === undefined ? undefined : Math.max(0, currentData.total - 1),
- };
+ await revalidateReplica(resourceListResource);
};
/**
- * List the cached keys a matcher accepts without touching their data: the
- * collecting matcher never accepts, so SWR mutates nothing.
- */
-const collectCachedListKeys = async (matcher: (key: unknown) => key is ResourceSWRKey) => {
- const keys: ResourceSWRKey[] = [];
- await mutate(
- (key) => {
- if (matcher(key)) keys.push(key);
- return false;
- },
- undefined,
- { revalidate: false },
- );
- return keys;
-};
-
-/**
- * Keep every cached folder list in step with a move.
- *
- * `moveResource` only touches the mounted explorer state and the sidebar tree;
- * the SWR entries of the destination and source folders keep their old rows.
- * `useFetchResources` serves those entries synchronously on the next visit and
- * dedupes refetches for 30s, so the moved row was missing from the destination
- * (and could resurface in the source) until a focus revalidation. Patch the
- * cache entries themselves so the cache-hit path already shows the move.
+ * Keep the explorer list in step with a move.
*
- * Destination entries are patched one key at a time because the row's place
- * depends on that key's sort (see `patchDestinationList`); the updater SWR
- * hands us does not know which key it is running for. Filtered variants of the
- * destination (see `listsMovedRowUnfiltered`) are only revalidated.
- *
- * The patches are written with `revalidate: false` and the reconciling refetch
- * of any mounted key is fired without being awaited: SWR's `mutate` resolves
- * only after that refetch when `revalidate` is on, and this runs inside the
- * move transaction's `onSuccess`, so awaiting it would hold the caller's
- * promise (and the "moved" toast) for one extra list round-trip.
- *
- * Scoped to the workspace and library the move was issued from: other
- * libraries never list this row under these parents.
+ * The explorer list is a local-first replica now: `moveResource` already patches
+ * the in-memory view optimistically and revalidates the mounted query, and a
+ * later visit to either folder hydrates from its persisted head page and then
+ * confirms it over the network. This entry point stays for the sidebar tree's
+ * API-only move path, which does not go through the explorer's own action.
*/
-const applyMoveToListCaches = async (
- resource: ResourceItem,
- { fromParentKeys, toParentKeys, scope }: ResourceMoveCachePatch,
-) => {
- const toKeys = new Set(toParentKeys);
- const fromKeys = new Set(fromParentKeys.filter((key) => !toKeys.has(key)));
- const movedResource = stripOptimistic(resource);
-
- const isToKey = (key: unknown) => isResourceListKeyForParent(key, scope, toKeys);
- const isFromKey = (key: unknown) => isResourceListKeyForParent(key, scope, fromKeys);
- // Removing from the source is safe for every variant; inserting is not.
- const isSeedableToKey = (key: unknown): key is ResourceSWRKey =>
- isToKey(key) && listsMovedRowUnfiltered(key[1], movedResource);
-
- const destinationKeys = toKeys.size > 0 ? await collectCachedListKeys(isSeedableToKey) : [];
-
- await Promise.all([
- ...destinationKeys.map((cachedKey) =>
- mutate(
- (key) => isEqual(key, cachedKey),
- async (currentData: ResourceListData | undefined) =>
- patchDestinationList(currentData, movedResource, cachedKey[1]),
- { revalidate: false },
- ),
- ),
- fromKeys.size > 0 &&
- mutate(
- isFromKey,
- async (currentData: ResourceListData | undefined) =>
- patchSourceList(currentData, movedResource),
- { revalidate: false },
- ),
- ]);
-
- // Reconcile whichever of these keys is mounted, off the caller's critical path.
- void mutate(
- (key) => (toKeys.size > 0 && isToKey(key)) || (fromKeys.size > 0 && isFromKey(key)),
- async (currentData: ResourceListData | undefined) => currentData,
- { revalidate: true },
- );
-};
-
-let pendingMovePatches: Promise<unknown> = Promise.resolve();
-
-/**
- * Patches run one at a time. A multi-item move lands its requests together and
- * every item patches the same source / destination keys; SWR's `mutate` reads
- * the cached list before awaiting the updater and drops a write whose read was
- * overtaken by a later mutation of the same key, so concurrent patches would
- * lose all but the last row. Serialising here covers every caller β€” the
- * explorer's own moves and the tree's API-only branches alike.
- */
-export const applyResourceMoveToListCaches = (
- resource: ResourceItem,
- patch: ResourceMoveCachePatch,
-): Promise<void> => {
- const run = pendingMovePatches.then(
- () => applyMoveToListCaches(resource, patch),
- () => applyMoveToListCaches(resource, patch),
- );
- pendingMovePatches = run.catch(() => {});
- return run;
-};
-
-/**
- * Custom SWR hook for fetching resources with caching and revalidation
- */
-export const useFetchResources = (params: ResourceQueryParams | null, enable: any = true) => {
- const workspaceId = useActiveWorkspaceId();
-
- const swr = useClientDataSWR(
- enable && params ? resourceKeys.list(params, workspaceId) : null,
- async ([, queryParams]: ResourceSWRKey) => {
- const response = await resourceService.queryResources({
- ...queryParams,
- limit: queryParams.limit || 50,
- offset: 0,
- });
- return response;
- },
- {
- // Skip background revalidation when a fresh fetch for the same key
- // happened recently. Cache-hit display still works because the
- // useEffect below syncs swr.data β†’ store regardless of whether the
- // fetcher actually ran.
- dedupingInterval: 30 * 1000,
- revalidateOnFocus: true,
- revalidateOnReconnect: true,
- },
- );
-
- // Sync SWR data β†’ store on every data ref change.
- // Using useEffect (not onSuccess) covers the cache-hit path: when the key
- // changes to a previously-fetched folder, SWR returns cached data synchronously
- // without firing onSuccess. Reading the store mirror alone would surface the
- // previously-written folder's data until revalidation completes.
- const data = swr.data;
- useEffect(() => {
- if (!data || !params) return;
-
- const { hasMore, queryParams, resourceList, resourceMap, total } = useFileStore.getState();
- const merged = mergeServerResourcesWithOptimistic(data.items, resourceMap, params);
-
- if (
- !isEqual(queryParams, params) ||
- hasMore !== data.hasMore ||
- total !== data.total ||
- !isEqual(merged.resourceList, resourceList) ||
- !isEqual(merged.resourceMap, resourceMap)
- ) {
- useFileStore.setState(
- {
- hasMore: data.hasMore,
- offset: data.items.length,
- queryParams: params,
- resourceList: merged.resourceList,
- resourceMap: merged.resourceMap,
- total: data.total,
- },
- false,
- 'useFetchResources/sync',
- );
- }
- }, [data, params]);
-
- return swr;
+export const applyResourceMoveToListCaches = async (): Promise<void> => {
+ await revalidateResources();
};
/**
@@ -379,3 +70,10 @@ export const useResourceStore = () => {
shallow,
);
};
+
+/**
+ * Custom hook for fetching resources: hydrates the persisted head page and
+ * revalidates it. Read the rows from the store, not from this hook's return.
+ */
+export const useFetchResources = (params: ResourceQueryParams | null, enable: boolean = true) =>
+ useFileStore((s) => s.useFetchResources)(params, enable);
diff --git a/src/store/file/slices/resource/initialState.ts b/src/store/file/slices/resource/initialState.ts
index 5686506f477..a99129ee898 100644
--- a/src/store/file/slices/resource/initialState.ts
+++ b/src/store/file/slices/resource/initialState.ts
@@ -1,54 +1,48 @@
-import type { OptimisticMutationSnapshot } from '@/store/utils/optimisticEngine';
-import type { ResourceItem, ResourceQueryParams } from '@/types/resource';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import { type ResourceItem } from '@/types/resource';
+
+import { type ResourceListParams, type ResourceListValue } from './projection';
/**
- * Resource slice state
+ * Resource slice state.
+ *
+ * The list itself is a `@lobechat/replica` paged resource: `resourceListEntry`
+ * is the replica view, and `resourceList` / `resourceMap` / `hasMore` / `total`
+ * / `offset` / `queryParams` / `isLoadingMore` are derived from it by the
+ * slice's lens, so every existing selector keeps reading the same place.
*/
export interface ResourceState {
- /**
- * Pagination state
- */
+ /** Pagination state (derived from the replica view). */
hasMore: boolean;
- /**
- * Loading states
- */
+ /** Loading states */
isLoadingMore: boolean;
- isSyncing: boolean;
-
- /**
- * Sync status
- */
- lastSyncTime?: Date;
-
+ /** Number of rows currently painted (derived from the replica view). */
offset: number;
+ /** Current query parameters (the query the painted page set answers). */
+ queryParams?: ResourceListParams;
/**
- * Current query parameters
- */
- queryParams?: ResourceQueryParams;
- /**
- * Derived sorted/filtered list (computed from map)
+ * Derived sorted/filtered list (computed from the replica view)
* Used for rendering in UI
*/
resourceList: ResourceItem[];
/**
- * Primary store - Map for O(1) lookups
+ * The replica view of the explorer list β€” what the engine reads and writes.
+ * `undefined` until the persisted row hydrates or the first network page
+ * lands, so an un-loaded list never reads as an empty one.
*/
- resourceMap: Map<string, ResourceItem>;
+ resourceListEntry?: ResourceListValue;
- syncError?: Error;
- /**
- * Track which resources are currently syncing
- */
- syncingIds: Set<string>;
+ /** Replica bookkeeping of `resourceListEntry`. */
+ resourceListReplica: ReplicaState<ResourceListValue>;
/**
- * Sync queue (FIFO)
- * Contains pending operations to be synced to server
+ * Primary store - Map for O(1) lookups (derived from the replica view)
*/
- syncQueue: OptimisticMutationSnapshot[];
+ resourceMap: Map<string, ResourceItem>;
+
total: number;
}
@@ -58,11 +52,11 @@ export interface ResourceState {
export const initialResourceState: ResourceState = {
hasMore: false,
isLoadingMore: false,
- isSyncing: false,
offset: 0,
+ queryParams: undefined,
resourceList: [],
+ resourceListEntry: undefined,
+ resourceListReplica: createReplicaState(),
resourceMap: new Map(),
- syncQueue: [],
- syncingIds: new Set(),
total: 0,
};
diff --git a/src/store/file/slices/resource/projection.ts b/src/store/file/slices/resource/projection.ts
new file mode 100644
index 00000000000..9b58cd56c0c
--- /dev/null
+++ b/src/store/file/slices/resource/projection.ts
@@ -0,0 +1,120 @@
+import { definePagedReplica, type ReplicaPagedData } from '@/libs/replica';
+import { type FilesTabs, type ResourceSourceFilter, type SortType } from '@/types/files';
+import { type ResourceItem, type ResourceQueryParams } from '@/types/resource';
+
+/**
+ * The resource explorer shows one list at a time, so the replica keeps a single
+ * entry: a query change repaints from its own head page instead of ever sharing
+ * (or resetting) a bucket across folders, libraries or filter chips.
+ */
+export const RESOURCE_LIST_KEY = 'current';
+
+/** Page size used when the caller does not name one (the legacy `limit: 50`). */
+export const DEFAULT_RESOURCE_PAGE_SIZE = 50;
+
+/**
+ * Query identity of the explorer list. `limit` / `offset` are deliberately
+ * absent β€” the replica owns the paging cursor β€” and are replaced by `pageSize`.
+ */
+export interface ResourceListParams {
+ category?: FilesTabs;
+ includeContentPreview?: boolean;
+ libraryId?: string;
+ /**
+ * Rows per page; part of the query identity (a different page size is a
+ * different list). Optional so a legacy caller may seed the flat view fields
+ * directly; the fetch defaults it.
+ */
+ pageSize?: number;
+ parentId?: string | null;
+ q?: string;
+ showFilesInKnowledgeBase?: boolean;
+ sorter?: 'name' | 'createdAt' | 'size';
+ sortType?: SortType;
+ sourceFilter?: ResourceSourceFilter;
+ visibility?: 'private' | 'public';
+}
+
+/**
+ * The explorer list view: the generic local-first paged data plus the query it
+ * answers, so the surface can tell whether the painted page set still matches
+ * the request on screen.
+ */
+export interface ResourceListValue extends ReplicaPagedData<ResourceItem, number> {
+ /** Absent only for a view seeded by a legacy caller outside a known query. */
+ queryParams?: ResourceListParams;
+}
+
+/**
+ * Trim the caller's `ResourceQueryParams` down to the list query identity:
+ * drops the paging cursor, defaults the page size and normalizes an empty
+ * keyword to "no keyword" so it never splits one query into two entries.
+ */
+export const normalizeResourceListParams = (
+ input: ResourceQueryParams | null | undefined,
+): ResourceListParams | null => {
+ if (!input) return null;
+
+ return {
+ category: input.category,
+ includeContentPreview: input.includeContentPreview || undefined,
+ libraryId: input.libraryId,
+ pageSize: input.limit ?? DEFAULT_RESOURCE_PAGE_SIZE,
+ parentId: input.parentId ?? null,
+ q: input.q?.trim() || undefined,
+ showFilesInKnowledgeBase: input.showFilesInKnowledgeBase ?? false,
+ sorter: input.sorter,
+ sortType: input.sortType,
+ sourceFilter: input.sourceFilter,
+ visibility: input.visibility,
+ };
+};
+
+/**
+ * The resource explorer list (`resourceService.queryResources`): a local-first
+ * paged replica, so the explorer paints the persisted head page on the first
+ * frame, the network confirms it, and "load more" appends through the engine.
+ */
+export const resourceListResource = definePagedReplica<
+ ResourceListParams,
+ ResourceItem,
+ number,
+ ResourceListValue
+>({
+ key: () => RESOURCE_LIST_KEY,
+ name: 'resourceList',
+ paging: {
+ direction: 'forward',
+ getId: (item) => item.id,
+ mode: 'offset',
+ // A reload repaints what the first network page would show, never a stale tail.
+ persist: { pages: 1 },
+ },
+ query: ({
+ category,
+ includeContentPreview,
+ libraryId,
+ pageSize,
+ parentId,
+ q,
+ showFilesInKnowledgeBase,
+ sorter,
+ sortType,
+ sourceFilter,
+ visibility,
+ }) => ({
+ category,
+ includeContentPreview,
+ libraryId,
+ pageSize,
+ parentId,
+ q,
+ showFilesInKnowledgeBase,
+ sorter,
+ sortType,
+ sourceFilter,
+ visibility,
+ }),
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/file/slices/resource/replica.test.ts b/src/store/file/slices/resource/replica.test.ts
new file mode 100644
index 00000000000..71b373ebad7
--- /dev/null
+++ b/src/store/file/slices/resource/replica.test.ts
@@ -0,0 +1,1022 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The explorer list is a `@lobechat/replica` paged resource: the persisted head
+ * page paints before the network answers, the response confirms and persists it,
+ * "load more" appends through the engine, and a query change repaints from its
+ * own head page instead of appending to the previous folder's rows.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, REPLICA_INDEX_KEY } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { resourceService } from '@/services/resource';
+import { initialState } from '@/store/file/initialState';
+import { useFileStore } from '@/store/file/store';
+import type { ResourceItem } from '@/types/resource';
+
+import type { ResourceListParams } from './projection';
+import { normalizeResourceListParams, RESOURCE_LIST_KEY, resourceListResource } from './projection';
+
+vi.mock('@/services/knowledgeBase', () => ({
+ knowledgeBaseService: {
+ addFilesToKnowledgeBase: vi.fn(async () => undefined),
+ removeFilesFromKnowledgeBase: vi.fn(async () => undefined),
+ },
+}));
+
+const BASE_INPUT = { parentId: null } as const;
+const BASE_PARAMS = normalizeResourceListParams(BASE_INPUT)!;
+const BASE_KEY = resourceListResource.storageKey(BASE_PARAMS);
+
+const row = (id: string): ResourceItem => ({
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ fileType: 'text/plain',
+ id,
+ name: id,
+ parentId: null,
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),
+ url: `files/${id}.txt`,
+});
+
+const ids = () => useFileStore.getState().resourceList.map((item) => item.id);
+const page = (items: ResourceItem[], total: number, hasMore = items.length < total) => ({
+ hasMore,
+ items,
+ total,
+});
+const rows = (length: number, offset = 0) =>
+ Array.from({ length }, (_, i) => row(`resource-${i + offset}`));
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+describe('resourceList replica', () => {
+ const scopes = new Set<string>();
+ /** Storage rows written by a test, so each one is cleaned up after it. */
+ const seededQueryKeys = new Set<string>([BASE_KEY]);
+ let scope = '';
+ let querySpy: ReturnType<typeof vi.spyOn>;
+
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ /** Seed a persisted head page exactly as the engine would have written it. */
+ const seedPersisted = async (params: ResourceListParams, items: ResourceItem[]) => {
+ const queryKey = resourceListResource.storageKey(params);
+ seededQueryKeys.add(queryKey);
+ await resourceListResource.storage!.set(
+ { queryKey, scope },
+ {
+ data: {
+ currentPage: 0,
+ hasMore: false,
+ items,
+ nextCursor: null,
+ pageSize: params.pageSize ?? 50,
+ queryParams: params,
+ total: items.length,
+ },
+ updatedAt: 1,
+ },
+ );
+ // Register the row in the replica's persisted-row index, exactly as the
+ // engine does when it writes a page, so persisted patches can find it.
+ seededQueryKeys.add(REPLICA_INDEX_KEY);
+ await resourceListResource.storage!.set(
+ { queryKey: REPLICA_INDEX_KEY, scope },
+ {
+ data: [...seededQueryKeys].filter((key) => key !== REPLICA_INDEX_KEY) as never,
+ updatedAt: 1,
+ },
+ );
+ };
+
+ beforeEach(() => {
+ useScope(`resource-user-${randomUUID()}:personal`);
+ querySpy = vi.spyOn(resourceService, 'queryResources');
+ act(() => useFileStore.setState(initialState));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) =>
+ [...seededQueryKeys].map((queryKey) =>
+ resourceListResource.storage!.remove({ queryKey, scope: value }),
+ ),
+ ),
+ );
+ scopes.clear();
+ seededQueryKeys.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('reads the list from a single entry', () => {
+ expect(RESOURCE_LIST_KEY).toBe('current');
+ });
+
+ it('paints the persisted head page before the network answers', async () => {
+ await resourceListResource.storage!.set(
+ { queryKey: BASE_KEY, scope },
+ {
+ data: {
+ currentPage: 0,
+ hasMore: true,
+ items: [row('cached-1')],
+ nextCursor: 1,
+ pageSize: 50,
+ queryParams: BASE_PARAMS,
+ total: 2,
+ },
+ updatedAt: 1,
+ },
+ );
+ querySpy.mockImplementation(pending);
+
+ const hook = renderHook(
+ () => ({
+ sync: useFileStore((s) => s.useFetchResources)(BASE_INPUT),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['cached-1']));
+ expect(hook.result.current.sync.isHydrated).toBe(true);
+ expect(hook.result.current.sync.isValidating).toBe(true);
+ expect(useFileStore.getState().resourceMap.get('cached-1')).toMatchObject({ name: 'cached-1' });
+ });
+
+ it('replaces the head page with the server response and persists it', async () => {
+ querySpy.mockResolvedValue(page([row('a'), row('b')], 40));
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+
+ await waitFor(() => expect(ids()).toEqual(['a', 'b']));
+ expect(useFileStore.getState()).toMatchObject({ hasMore: true, total: 40 });
+
+ await waitFor(async () => {
+ const persisted = await resourceListResource.storage!.get({ queryKey: BASE_KEY, scope });
+ expect((persisted?.data.items as ResourceItem[] | undefined)?.map((item) => item.id)).toEqual(
+ ['a', 'b'],
+ );
+ });
+ });
+
+ it('appends the next page with the loaded query params', async () => {
+ querySpy
+ .mockResolvedValueOnce(page(rows(50), 120))
+ .mockResolvedValueOnce(page(rows(50, 50), 120));
+
+ const hook = renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(50));
+
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+
+ expect(ids()).toHaveLength(100);
+ expect(ids()[50]).toBe('resource-50');
+ expect(useFileStore.getState().hasMore).toBe(true);
+ // The replica owns the cursor: page 2 of the loaded query, offset 50.
+ expect(querySpy).toHaveBeenLastCalledWith(expect.objectContaining({ limit: 50, offset: 50 }));
+ expect(hook).toBeDefined();
+ });
+
+ it('repaints from its own head page when the query changes', async () => {
+ querySpy
+ .mockResolvedValueOnce(page(rows(50), 120))
+ .mockResolvedValueOnce(page([row('foo-1')], 1));
+
+ const hook = renderHook(
+ (props: { q?: string }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: null, q: props.q }),
+ { initialProps: {} as { q?: string }, wrapper },
+ );
+
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(50));
+
+ hook.rerender({ q: 'foo' });
+
+ await waitFor(() => expect(ids()).toEqual(['foo-1']));
+ expect(useFileStore.getState().queryParams?.q).toBe('foo');
+ expect(useFileStore.getState().total).toBe(1);
+ });
+
+ it('drops the painted rows on clear but keeps the queried params', async () => {
+ querySpy.mockResolvedValue(page([row('a')], 1));
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+
+ await waitFor(() => expect(ids()).toEqual(['a']));
+
+ act(() => useFileStore.getState().clearCurrentQueryResources());
+
+ expect(ids()).toEqual([]);
+ expect(useFileStore.getState().resourceMap.size).toBe(0);
+ // The queried params survive so the views can tell the request moved on.
+ expect(useFileStore.getState().queryParams?.parentId).toBeNull();
+ });
+
+ it('keeps paging past a short page the server reports more for', async () => {
+ // Inbox filters folder-backed rows after paging: a visible page shorter than
+ // the page size is not the end while the server still reports `hasMore`.
+ querySpy
+ .mockResolvedValueOnce({ hasMore: true, items: rows(48) })
+ .mockResolvedValueOnce({ hasMore: false, items: rows(10, 48) });
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(48));
+ expect(useFileStore.getState().hasMore).toBe(true);
+
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+
+ expect(querySpy).toHaveBeenLastCalledWith(expect.objectContaining({ limit: 50, offset: 50 }));
+ expect(ids()).toHaveLength(58);
+ expect(useFileStore.getState().hasMore).toBe(false);
+ });
+
+ it('does not fetch another page when the head page is the last one', async () => {
+ querySpy.mockResolvedValue(page([row('only')], 1));
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(1));
+ expect(useFileStore.getState().hasMore).toBe(false);
+
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+
+ expect(querySpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports isLoading only while nothing is painted', async () => {
+ querySpy.mockImplementation(pending);
+
+ const hook = renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), {
+ wrapper,
+ });
+
+ expect(hook.result.current.isLoading).toBe(true);
+ expect(useFileStore.getState().resourceList).toEqual([]);
+ });
+
+ it('keeps a pending upload row across a head revalidation and out of storage', async () => {
+ querySpy.mockResolvedValue(page([row('server-1')], 1));
+
+ const hook = renderHook(
+ () => ({ sync: useFileStore((s) => s.useFetchResources)(BASE_INPUT) }),
+ {
+ wrapper,
+ },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['server-1']));
+
+ act(() =>
+ useFileStore.getState().insertLocalResource(
+ {
+ fileType: 'text/plain',
+ name: 'Uploading',
+ size: 3,
+ sourceType: 'file',
+ url: '',
+ },
+ 'temp-upload',
+ ),
+ );
+ expect(ids()).toEqual(['temp-upload', 'server-1']);
+
+ // A focus / reconnect head response no longer carries the pending row.
+ querySpy.mockResolvedValue(page([row('server-1')], 1));
+ await act(async () => {
+ await hook.result.current.sync.mutate();
+ });
+
+ // The local row survives the refresh ...
+ expect(ids()).toContain('temp-upload');
+ // ... without ever reaching the persisted head page.
+ const persisted = await resourceListResource.storage!.get({ queryKey: BASE_KEY, scope });
+ expect((persisted?.data.items as ResourceItem[]).map((item) => item.id)).toEqual(['server-1']);
+ });
+
+ it('paints a previously visited folder from its persisted page on navigation', async () => {
+ const paramsB = normalizeResourceListParams({ parentId: 'folder-b' })!;
+ await seedPersisted(paramsB, [row('cached-b')]);
+
+ // Folder A answers; folder B never does β€” only its cache can paint it.
+ querySpy.mockImplementation((params) =>
+ params.parentId === 'folder-b' ? pending() : Promise.resolve(page([row('a-1')], 1)),
+ );
+
+ const hook = renderHook(
+ (props: { parentId: string | null }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: props.parentId }),
+ { initialProps: { parentId: null as string | null }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['a-1']));
+
+ hook.rerender({ parentId: 'folder-b' });
+
+ await waitFor(() => expect(ids()).toEqual(['cached-b']));
+ expect(useFileStore.getState().queryParams?.parentId).toBe('folder-b');
+ });
+
+ it('restores each folder from its persisted page when navigating back offline', async () => {
+ const paramsA = normalizeResourceListParams({ parentId: null })!;
+ const paramsB = normalizeResourceListParams({ parentId: 'folder-b' })!;
+ await seedPersisted(paramsA, [row('cached-a')]);
+ await seedPersisted(paramsB, [row('cached-b')]);
+ querySpy.mockImplementation(pending);
+
+ const hook = renderHook(
+ (props: { parentId: string | null }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: props.parentId }),
+ { initialProps: { parentId: null as string | null }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['cached-a']));
+
+ hook.rerender({ parentId: 'folder-b' });
+ await waitFor(() => expect(ids()).toEqual(['cached-b']));
+
+ // The once-per-key driver read of folder A already ran, so coming back must
+ // hydrate it again rather than wait for a network that is not there.
+ hook.rerender({ parentId: null });
+ await waitFor(() => expect(ids()).toEqual(['cached-a']));
+ });
+
+ it('paints a previously cached sort from its persisted page', async () => {
+ const sortedParams = normalizeResourceListParams({
+ parentId: null,
+ sorter: 'size',
+ sortType: 'asc',
+ })!;
+ await seedPersisted(sortedParams, [row('cached-sorted')]);
+
+ // Only the default (newest-first) query answers; the sorted one is offline.
+ querySpy.mockImplementation((params) =>
+ params.sorter === 'size' ? pending() : Promise.resolve(page([row('newest-1')], 1)),
+ );
+
+ const hook = renderHook(
+ (props: { sorter?: 'size' }) =>
+ useFileStore((s) => s.useFetchResources)({
+ parentId: null,
+ sorter: props.sorter,
+ sortType: props.sorter ? 'asc' : undefined,
+ }),
+ { initialProps: {} as { sorter?: 'size' }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['newest-1']));
+
+ // Same pool, different storage row: the cached page must still hydrate.
+ hook.rerender({ sorter: 'size' });
+
+ await waitFor(() => expect(ids()).toEqual(['cached-sorted']));
+ });
+
+ it('does not carry a pending create into the folder the user navigates to', async () => {
+ const paramsB = normalizeResourceListParams({ parentId: 'folder-b' })!;
+ await seedPersisted(paramsB, [row('cached-b')]);
+ querySpy.mockImplementation((params) =>
+ params.parentId === 'folder-a' ? Promise.resolve(page([row('a-1')], 1)) : pending(),
+ );
+ // The create never settles: its overlay stays in flight across the switch.
+ const createSpy = vi.spyOn(resourceService, 'createResource').mockImplementation(pending);
+
+ const hook = renderHook(
+ (props: { parentId: string | null }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: props.parentId }),
+ { initialProps: { parentId: 'folder-a' as string | null }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['a-1']));
+
+ act(() => {
+ void useFileStore.getState().createResourceAndSync({
+ fileType: 'text/plain',
+ name: 'New',
+ parentId: 'folder-a',
+ sourceType: 'file',
+ url: '',
+ });
+ });
+ expect(ids()[0].startsWith('temp-resource-')).toBe(true);
+
+ hook.rerender({ parentId: 'folder-b' });
+
+ // Folder B's cached page paints and the overlay from folder A stays out.
+ await waitFor(() => expect(ids()).toEqual(['cached-b']));
+ expect(createSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not surface an upload from another folder when the next folder answers', async () => {
+ querySpy.mockImplementation((params) =>
+ Promise.resolve(
+ params.parentId === 'folder-b' ? page([row('b-1')], 1) : page([row('a-1')], 1),
+ ),
+ );
+
+ const hook = renderHook(
+ (props: { parentId: string | null }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: props.parentId }),
+ { initialProps: { parentId: 'folder-a' as string | null }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['a-1']));
+
+ act(() =>
+ useFileStore.getState().insertLocalResource(
+ {
+ fileType: 'text/plain',
+ name: 'Uploading',
+ parentId: 'folder-a',
+ size: 3,
+ sourceType: 'file',
+ url: '',
+ },
+ 'temp-upload',
+ ),
+ );
+ expect(ids()).toEqual(['temp-upload', 'a-1']);
+
+ // Folder B has no cache, so its head response merges against A's view: the
+ // upload belongs to A's pool and must not follow the user.
+ hook.rerender({ parentId: 'folder-b' });
+
+ await waitFor(() => expect(ids()).toEqual(['b-1']));
+ });
+
+ it('keeps an upload started before the first page lands', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ querySpy.mockImplementation(async () => {
+ await gate;
+ return page([row('server-1')], 1);
+ });
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+
+ // The header is usable while the first page is still in flight.
+ act(() =>
+ useFileStore.getState().insertLocalResource(
+ {
+ fileType: 'text/plain',
+ name: 'Uploading',
+ parentId: null,
+ size: 3,
+ sourceType: 'file',
+ url: '',
+ },
+ 'temp-upload',
+ ),
+ );
+ expect(ids()).toEqual(['temp-upload']);
+
+ await act(async () => {
+ release();
+ await gate;
+ });
+
+ // The head response must keep the row it has no server counterpart for.
+ await waitFor(() => expect(ids()).toEqual(['temp-upload', 'server-1']));
+ });
+
+ it('repaints a query after the workspace scope switches away and back', async () => {
+ await seedPersisted(BASE_PARAMS, [row('cached-a')]);
+ querySpy.mockImplementation(pending);
+
+ const firstScope = scope;
+ const hook = renderHook(
+ (props: { generation: number }) => {
+ void props.generation;
+ return useFileStore((s) => s.useFetchResources)(BASE_INPUT);
+ },
+ { initialProps: { generation: 0 }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['cached-a']));
+
+ // Another workspace: an empty replica whose network never answers.
+ act(() => useScope(`resource-user-${randomUUID()}:ws-2`));
+ hook.rerender({ generation: 1 });
+ await waitFor(() => expect(ids()).toEqual([]));
+
+ // Back to the first workspace: its own persisted page must paint again.
+ act(() => useScope(firstScope));
+ hook.rerender({ generation: 2 });
+ await waitFor(() => expect(ids()).toEqual(['cached-a']));
+ });
+
+ it('confirms the page with the server after removing rows from a knowledge base view', async () => {
+ querySpy.mockResolvedValueOnce(page(rows(50), 60)).mockResolvedValueOnce(page(rows(50, 1), 59));
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)({ libraryId: 'kb-1' }), { wrapper });
+
+ await waitFor(() => expect(ids()).toHaveLength(50));
+ expect(ids()[0]).toBe('resource-0');
+
+ // Removing a row shrinks the server's page, so the loaded offset no longer
+ // lines up; the action must confirm the page instead of leaving a gap that
+ // the next "load more" would skip.
+ await act(async () => {
+ await useFileStore.getState().removeResourcesFromKnowledgeBase('kb-1', ['resource-0']);
+ });
+
+ await waitFor(() => expect(ids()[0]).toBe('resource-1'));
+ expect(ids()).not.toContain('resource-0');
+ expect(querySpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps a pending upload when a same-pool sort repaints from its cached page', async () => {
+ const sortedParams = normalizeResourceListParams({
+ parentId: null,
+ sorter: 'size',
+ sortType: 'asc',
+ })!;
+ await seedPersisted(sortedParams, [row('cached-sorted')]);
+
+ // Only the default (newest-first) query answers; the sorted one is offline.
+ querySpy.mockImplementation((params) =>
+ params.sorter === 'size' ? pending() : Promise.resolve(page([row('newest-1')], 1)),
+ );
+
+ const hook = renderHook(
+ (props: { sorter?: 'size' }) =>
+ useFileStore((s) => s.useFetchResources)({
+ parentId: null,
+ sorter: props.sorter,
+ sortType: props.sorter ? 'asc' : undefined,
+ }),
+ { initialProps: {} as { sorter?: 'size' }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['newest-1']));
+
+ act(() =>
+ useFileStore.getState().insertLocalResource(
+ {
+ fileType: 'text/plain',
+ name: 'Uploading',
+ parentId: null,
+ size: 3,
+ sourceType: 'file',
+ url: '',
+ },
+ 'temp-upload',
+ ),
+ );
+ expect(ids()).toEqual(['temp-upload', 'newest-1']);
+
+ // Same pool, different storage row: the overwrite hydrate must keep the
+ // client-only row the persisted page has no counterpart for.
+ hook.rerender({ sorter: 'size' });
+
+ await waitFor(() => expect(ids()).toContain('cached-sorted'));
+ expect(ids()).toContain('temp-upload');
+ });
+
+ it('reconciles when a same-pool query change drops the pending create token', async () => {
+ let releaseCreate!: (value: ResourceItem) => void;
+ const createGate = new Promise<ResourceItem>((resolve) => {
+ releaseCreate = resolve;
+ });
+ vi.spyOn(resourceService, 'createResource').mockImplementation(() => createGate);
+
+ querySpy.mockImplementation((params) =>
+ params.sorter === 'size'
+ ? Promise.resolve(page([row('sorted-1')], 1))
+ : Promise.resolve(page([row('newest-1')], 1)),
+ );
+
+ const hook = renderHook(
+ (props: { sorter?: 'size' }) =>
+ useFileStore((s) => s.useFetchResources)({
+ parentId: null,
+ sorter: props.sorter,
+ sortType: props.sorter ? 'asc' : undefined,
+ }),
+ { initialProps: {} as { sorter?: 'size' }, wrapper },
+ );
+
+ await waitFor(() => expect(ids()).toEqual(['newest-1']));
+
+ let creating!: Promise<string>;
+ act(() => {
+ creating = useFileStore.getState().createResource({
+ fileType: 'text/plain',
+ name: 'New',
+ parentId: null,
+ sourceType: 'file',
+ url: '',
+ });
+ });
+ expect(ids()[0].startsWith('temp-resource-')).toBe(true);
+
+ // Same-pool query change: the overlay is dropped before it settles.
+ hook.rerender({ sorter: 'size' });
+ await waitFor(() => expect(ids()).toEqual(['sorted-1']));
+
+ const callsBefore = querySpy.mock.calls.length;
+ await act(async () => {
+ releaseCreate(row('created'));
+ await creating;
+ });
+
+ // The dropped token must force a reconciliation, not leave the server
+ // change unreflected until focus / reconnect.
+ await waitFor(() => expect(querySpy.mock.calls.length).toBeGreaterThan(callsBefore));
+ });
+
+ it('restarts paging from the head after removing rows from a multi-page knowledge base view', async () => {
+ querySpy
+ .mockResolvedValueOnce(page(rows(50), 120))
+ .mockResolvedValueOnce(page(rows(50, 50), 120))
+ .mockResolvedValueOnce(page(rows(50, 1), 119));
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)({ libraryId: 'kb-1' }), { wrapper });
+
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(50));
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+ expect(useFileStore.getState().resourceList).toHaveLength(100);
+
+ await act(async () => {
+ await useFileStore.getState().removeResourcesFromKnowledgeBase('kb-1', ['resource-0']);
+ });
+
+ // The loaded depth collapsed to a fresh head page ...
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(50));
+
+ querySpy.mockResolvedValueOnce(page(rows(50, 51), 119));
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+
+ // ... so "load more" restarts at the head's next offset, not the stale 100.
+ expect(querySpy).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 50 }));
+ });
+
+ it('patches the cached source and destination folder pages after an API-only move', async () => {
+ const paramsA = normalizeResourceListParams({ parentId: 'folder-a' })!;
+ const paramsB = normalizeResourceListParams({ parentId: 'folder-b' })!;
+ await seedPersisted(paramsA, [row('moved'), row('stay-a')]);
+ await seedPersisted(paramsB, [row('stay-b')]);
+
+ const keyA = resourceListResource.storageKey(paramsA);
+ const keyB = resourceListResource.storageKey(paramsB);
+
+ // The explorer is open on an uncached folder; the move is issued elsewhere.
+ querySpy.mockResolvedValue(page([], 0));
+ renderHook(() => useFileStore((s) => s.useFetchResources)({ parentId: 'folder-c' }), {
+ wrapper,
+ });
+
+ const patch = await useFileStore
+ .getState()
+ .prepareResourceMoveCachePatch('folder-a', 'folder-b');
+ await useFileStore
+ .getState()
+ .applyMovedResourceToCaches({ ...row('moved'), parentId: 'folder-b' }, patch);
+
+ await waitFor(async () => {
+ const source = await resourceListResource.storage!.get({ queryKey: keyA, scope });
+ expect((source?.data.items as ResourceItem[]).map((item) => item.id)).toEqual(['stay-a']);
+ });
+ await waitFor(async () => {
+ const destination = await resourceListResource.storage!.get({ queryKey: keyB, scope });
+ expect((destination?.data.items as ResourceItem[]).map((item) => item.id)).toContain('moved');
+ });
+ });
+
+ it('does not carry a pre-paint create into the folder the user navigates to', async () => {
+ // Folder A never answers, so its first page never paints; folder B does.
+ querySpy.mockImplementation((params) =>
+ params.parentId === 'folder-b' ? Promise.resolve(page([row('b-1')], 1)) : pending(),
+ );
+ const createSpy = vi.spyOn(resourceService, 'createResource').mockImplementation(pending);
+
+ const hook = renderHook(
+ (props: { parentId: string | null }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: props.parentId }),
+ { initialProps: { parentId: 'folder-a' as string | null }, wrapper },
+ );
+
+ // The header is usable while the first page is still in flight, so the
+ // create starts before the entry has a query of its own.
+ act(() => {
+ void useFileStore.getState().createResourceAndSync({
+ fileType: 'text/plain',
+ name: 'New',
+ parentId: 'folder-a',
+ sourceType: 'file',
+ url: '',
+ });
+ });
+ expect(ids()[0].startsWith('temp-resource-')).toBe(true);
+
+ const paramsB = normalizeResourceListParams({ parentId: 'folder-b' })!;
+ hook.rerender({ parentId: 'folder-b' });
+
+ // Folder B's response must not be merged with folder A's in-flight row.
+ await waitFor(() => expect(ids()).toEqual(['b-1']));
+ expect(createSpy).toHaveBeenCalledTimes(1);
+
+ const persisted = await resourceListResource.storage!.get({
+ queryKey: resourceListResource.storageKey(paramsB),
+ scope,
+ });
+ expect((persisted?.data.items as ResourceItem[]).map((item) => item.id)).toEqual(['b-1']);
+ });
+
+ it('patches a cached destination folder when a move runs through the visible-row path', async () => {
+ const paramsB = normalizeResourceListParams({ parentId: 'folder-b' })!;
+ await seedPersisted(paramsB, [row('stay-b')]);
+ const keyB = resourceListResource.storageKey(paramsB);
+
+ const movedRow = { ...row('moved'), parentId: null };
+ querySpy.mockResolvedValue(page([movedRow], 1));
+ vi.spyOn(resourceService, 'moveResource').mockResolvedValue({
+ ...movedRow,
+ parentId: 'folder-b',
+ });
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)({ parentId: null }), { wrapper });
+ await waitFor(() => expect(ids()).toEqual(['moved']));
+
+ // The tree delegates to this action whenever the row is visible, so the
+ // captured destination patch has to be applied here too.
+ await act(async () => {
+ await useFileStore.getState().moveResource('moved', 'folder-b');
+ });
+
+ await waitFor(async () => {
+ const destination = await resourceListResource.storage!.get({ queryKey: keyB, scope });
+ expect((destination?.data.items as ResourceItem[]).map((item) => item.id)).toContain('moved');
+ });
+ });
+
+ it('restarts paging from the head after moving a row out of an extended folder', async () => {
+ querySpy
+ .mockResolvedValueOnce(page(rows(50), 120))
+ .mockResolvedValueOnce(page(rows(50, 50), 120))
+ .mockResolvedValueOnce(page(rows(50, 1), 119));
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)({ parentId: 'folder-a' }), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(50));
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+ expect(useFileStore.getState().resourceList).toHaveLength(100);
+
+ vi.spyOn(resourceService, 'moveResource').mockResolvedValue({
+ ...row('resource-0'),
+ parentId: 'folder-b',
+ });
+ await act(async () => {
+ await useFileStore.getState().moveResource('resource-0', 'folder-b');
+ });
+
+ // The row left the folder, so the loaded depth collapsed to a fresh head.
+ await waitFor(() => expect(useFileStore.getState().resourceList).toHaveLength(50));
+
+ querySpy.mockResolvedValueOnce(page(rows(50, 51), 119));
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+
+ expect(querySpy).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 50 }));
+ });
+
+ /** Persisted item ids of a query's row, `undefined` once the row is gone. */
+ const storedIds = async (params: ResourceListParams) => {
+ const stored = await resourceListResource.storage!.get({
+ queryKey: resourceListResource.storageKey(params),
+ scope,
+ });
+ return (stored?.data.items as ResourceItem[] | undefined)?.map((item) => item.id);
+ };
+
+ it.each([
+ ['a direct delete', () => useFileStore.getState().deleteResource('gone')],
+ ['a bulk delete', () => useFileStore.getState().deleteResources(['gone'])],
+ ])('drops %s from every persisted query variant', async (_label, runDelete) => {
+ // The same row is cached under another sort the user is not viewing.
+ const sorted = normalizeResourceListParams({ ...BASE_INPUT, sorter: 'name', sortType: 'asc' })!;
+ await seedPersisted(sorted, [row('gone'), row('keep')]);
+
+ querySpy.mockResolvedValue(page([row('gone'), row('keep')], 2));
+ vi.spyOn(resourceService, 'deleteResource').mockResolvedValue(undefined as never);
+ vi.spyOn(resourceService, 'deleteResources').mockResolvedValue(undefined as never);
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+ await waitFor(() => expect(ids()).toEqual(['gone', 'keep']));
+
+ await act(async () => {
+ await runDelete();
+ });
+
+ expect(ids()).toEqual(['keep']);
+ // A reload / offline visit of the other sort must not repaint the row.
+ await waitFor(async () => expect(await storedIds(sorted)).toEqual(['keep']));
+ });
+
+ it('evicts every persisted list variant after a select-all deletion by query', async () => {
+ const sorted = normalizeResourceListParams({ ...BASE_INPUT, sorter: 'name', sortType: 'asc' })!;
+ await seedPersisted(sorted, [row('gone')]);
+
+ // The head answers once; the revalidation after the deletion fails.
+ querySpy.mockResolvedValueOnce(page([row('gone')], 1)).mockRejectedValue(new Error('offline'));
+ vi.spyOn(resourceService, 'deleteResourcesByQuery').mockResolvedValue({ count: 1 } as never);
+ const { useTreeStore } = await import('@/store/tree');
+ vi.spyOn(useTreeStore.getState(), 'revalidate').mockResolvedValue(undefined as never);
+ const { useResourceManagerStore } = await import('@/features/ResourceManager/store');
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+ await waitFor(() => expect(ids()).toEqual(['gone']));
+ await waitFor(async () => expect(await storedIds(BASE_PARAMS)).toEqual(['gone']));
+
+ useResourceManagerStore.setState({ selectAllState: 'all', selectedFileIds: [] });
+ await act(async () => {
+ await useResourceManagerStore.getState().onActionClick('delete');
+ });
+
+ // Neither the mounted query's row nor another variant's survives to be
+ // hydrated by a reload or an offline visit.
+ expect(ids()).toEqual([]);
+ await waitFor(async () => expect(await storedIds(BASE_PARAMS)).toBeUndefined());
+ expect(await storedIds(sorted)).toBeUndefined();
+ });
+
+ it('does not collapse the folder the user navigated to while a move was in flight', async () => {
+ querySpy.mockImplementation(async (params) => {
+ if (params.parentId === 'folder-b') {
+ return params.offset === 0 ? page(rows(50, 200), 120) : page(rows(50, 250), 120);
+ }
+ return page(rows(50), 120);
+ });
+ let releaseMove!: (value: ResourceItem) => void;
+ vi.spyOn(resourceService, 'moveResource').mockImplementation(
+ () => new Promise((resolve) => (releaseMove = resolve)) as never,
+ );
+
+ const hook = renderHook(
+ (props: { parentId: string }) =>
+ useFileStore((s) => s.useFetchResources)({ parentId: props.parentId }),
+ { initialProps: { parentId: 'folder-a' }, wrapper },
+ );
+ await waitFor(() => expect(ids()[0]).toBe('resource-0'));
+
+ // Move a row out of folder A ...
+ let moving!: Promise<void>;
+ act(() => {
+ moving = useFileStore.getState().moveResource('resource-0', 'folder-c');
+ });
+ await waitFor(() => expect(releaseMove).toBeDefined());
+
+ // ... then open folder B and page it past its head while the move runs.
+ hook.rerender({ parentId: 'folder-b' });
+ await waitFor(() => expect(ids()[0]).toBe('resource-200'));
+ await act(async () => {
+ await useFileStore.getState().loadMoreResources();
+ });
+ expect(useFileStore.getState().resourceList).toHaveLength(100);
+
+ await act(async () => {
+ releaseMove({ ...row('resource-0'), parentId: 'folder-c' });
+ await moving;
+ });
+
+ // Folder B's offsets were not shifted by the move: its loaded depth stays.
+ expect(useFileStore.getState().resourceList).toHaveLength(100);
+ expect(ids()[0]).toBe('resource-200');
+ });
+
+ it('drops a failed create whose overlay a cached same-pool sort repaint dropped', async () => {
+ const sorted = normalizeResourceListParams({
+ parentId: null,
+ sorter: 'size',
+ sortType: 'asc',
+ })!;
+ await seedPersisted(sorted, [row('cached-sorted')]);
+
+ let failCreate!: (error: Error) => void;
+ vi.spyOn(resourceService, 'createResource').mockImplementation(
+ () => new Promise((_resolve, reject) => (failCreate = reject)) as never,
+ );
+ // The sorted query stays offline: only its cached page can paint it.
+ querySpy.mockImplementation((params) =>
+ params.sorter === 'size' ? pending() : Promise.resolve(page([row('newest-1')], 1)),
+ );
+
+ const hook = renderHook(
+ (props: { sorter?: 'size' }) =>
+ useFileStore((s) => s.useFetchResources)({
+ parentId: null,
+ sorter: props.sorter,
+ sortType: props.sorter ? 'asc' : undefined,
+ }),
+ { initialProps: {} as { sorter?: 'size' }, wrapper },
+ );
+ await waitFor(() => expect(ids()).toEqual(['newest-1']));
+
+ let creating!: Promise<string>;
+ act(() => {
+ creating = useFileStore.getState().createResource({
+ fileType: 'text/plain',
+ name: 'New',
+ parentId: null,
+ sourceType: 'file',
+ url: '',
+ });
+ });
+ const tempId = ids()[0];
+ expect(tempId.startsWith('temp-resource-')).toBe(true);
+
+ // The cached sort repaints and keeps the in-flight row as client-only.
+ hook.rerender({ sorter: 'size' });
+ await waitFor(() => expect(ids()).toContain('cached-sorted'));
+ expect(ids()).toContain(tempId);
+
+ await act(async () => {
+ failCreate(new Error('create failed'));
+ await creating.catch(() => undefined);
+ });
+
+ // The failed create must not linger as a phantom row.
+ expect(ids()).toEqual(['cached-sorted']);
+ });
+
+ it('applies a confirmed rename to every persisted query variant', async () => {
+ const sorted = normalizeResourceListParams({ ...BASE_INPUT, sorter: 'name', sortType: 'asc' })!;
+ await seedPersisted(sorted, [row('doc'), row('other')]);
+
+ querySpy.mockResolvedValue(page([row('doc')], 1));
+ vi.spyOn(resourceService, 'updateResource').mockResolvedValue({
+ ...row('doc'),
+ name: 'Renamed',
+ } as never);
+
+ renderHook(() => useFileStore((s) => s.useFetchResources)(BASE_INPUT), { wrapper });
+ await waitFor(() => expect(ids()).toEqual(['doc']));
+
+ await act(async () => {
+ await useFileStore.getState().updateResource('doc', { name: 'Renamed' });
+ });
+
+ expect(useFileStore.getState().resourceMap.get('doc')?.name).toBe('Renamed');
+ // The other sort's cached page must not repaint the old name.
+ await waitFor(async () => {
+ const stored = await resourceListResource.storage!.get({
+ queryKey: resourceListResource.storageKey(sorted),
+ scope,
+ });
+ const names = (stored?.data.items as ResourceItem[]).map((item) => item.name);
+ expect(names).toEqual(['Renamed', 'other']);
+ });
+ });
+});
diff --git a/src/store/file/slices/resource/utils.test.ts b/src/store/file/slices/resource/utils.test.ts
index c43c9711949..4549d3f431b 100644
--- a/src/store/file/slices/resource/utils.test.ts
+++ b/src/store/file/slices/resource/utils.test.ts
@@ -1,48 +1,47 @@
import { describe, expect, it } from 'vitest';
-import type { ResourceItem } from '@/types/resource';
+import { getResourceQueryKey, isOptimisticRowInRequestedPool } from './utils';
-import { getResourceQueryKey, mergeServerResourcesWithOptimistic } from './utils';
+describe('getResourceQueryKey', () => {
+ it('returns one stable default key when no query is given', () => {
+ expect(getResourceQueryKey()).toBe('resource-query:default');
+ expect(getResourceQueryKey(null)).toBe('resource-query:default');
+ });
-const createResource = (overrides: Partial<ResourceItem> = {}): ResourceItem => ({
- createdAt: new Date('2026-01-01T00:00:00.000Z'),
- fileType: 'text/plain',
- id: 'resource-1',
- name: 'Resource 1',
- parentId: null,
- size: 1,
- sourceType: 'file',
- updatedAt: new Date('2026-01-01T00:00:00.000Z'),
- url: 'files/resource-1.txt',
- ...overrides,
+ it('keys by the fields that select the row set', () => {
+ expect(getResourceQueryKey({ parentId: 'folder-a' })).toBe(
+ getResourceQueryKey({ parentId: 'folder-a' }),
+ );
+ expect(getResourceQueryKey({ parentId: 'folder-a' })).not.toBe(
+ getResourceQueryKey({ parentId: 'folder-b' }),
+ );
+ expect(getResourceQueryKey({ q: 'foo' })).not.toBe(getResourceQueryKey({ q: 'bar' }));
+ expect(getResourceQueryKey({ libraryId: 'kb-1' })).not.toBe(
+ getResourceQueryKey({ libraryId: 'kb-2' }),
+ );
+ });
});
-describe('mergeServerResourcesWithOptimistic', () => {
- it('should preserve optimistic resources from other queries in the global resource map', () => {
- const offscreenOptimistic = createResource({
- _optimistic: {
- isPending: true,
- queryKey: getResourceQueryKey({ parentId: 'folder-a' }),
- retryCount: 0,
- },
- id: 'temp-a',
- name: 'Offscreen upload',
- parentId: 'folder-a',
- });
- const currentServerItem = createResource({
- id: 'file-b',
- name: 'Visible item',
- parentId: 'folder-b',
- });
+describe('isOptimisticRowInRequestedPool', () => {
+ it('matches a row created in the pool on screen, including a re-sort', () => {
+ const key = getResourceQueryKey({ parentId: 'folder-a' });
- const merged = mergeServerResourcesWithOptimistic(
- [currentServerItem],
- new Map([[offscreenOptimistic.id, offscreenOptimistic]]),
- { parentId: 'folder-b' },
- );
+ expect(isOptimisticRowInRequestedPool(key, { parentId: 'folder-a' })).toBe(true);
+ expect(
+ isOptimisticRowInRequestedPool(key, {
+ parentId: 'folder-a',
+ sorter: 'size',
+ sortType: 'asc',
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects a row from another folder or library', () => {
+ const key = getResourceQueryKey({ libraryId: 'kb-1', parentId: 'folder-a' });
- expect(merged.resourceList).toEqual([currentServerItem]);
- expect(merged.resourceMap.get(offscreenOptimistic.id)).toEqual(offscreenOptimistic);
- expect(merged.resourceMap.get(currentServerItem.id)).toEqual(currentServerItem);
+ expect(isOptimisticRowInRequestedPool(key, { parentId: 'folder-b' })).toBe(false);
+ expect(isOptimisticRowInRequestedPool(key, { libraryId: 'kb-2' })).toBe(false);
+ expect(isOptimisticRowInRequestedPool(key, undefined)).toBe(false);
+ expect(isOptimisticRowInRequestedPool(undefined, { parentId: 'folder-a' })).toBe(false);
});
});
diff --git a/src/store/file/slices/resource/utils.ts b/src/store/file/slices/resource/utils.ts
index 039c0a33268..63b19d3fb64 100644
--- a/src/store/file/slices/resource/utils.ts
+++ b/src/store/file/slices/resource/utils.ts
@@ -1,7 +1,30 @@
-import { isEqual } from 'es-toolkit';
+import { type ResourceItem, type ResourceQueryParams } from '@/types/resource';
-import type { ResourceItem, ResourceQueryParams } from '@/types/resource';
+import { type ResourceListParams, type ResourceListValue } from './projection';
+/**
+ * Query fields that select a different *pool* of resources rather than a
+ * different arrangement of the same one. Changing any of them is a navigation:
+ * the rows on screen stop being an answer to the question now being asked, so
+ * the views show a skeleton instead of the stale list. `sorter` / `sortType` /
+ * `q` are deliberately absent β€” they re-ask the same pool.
+ *
+ * Lives here (not in the Explorer) so every consumer of "what counts as a
+ * navigation" reads one list.
+ */
+export const RESOURCE_POOL_KEYS = [
+ 'category',
+ 'libraryId',
+ 'parentId',
+ 'sourceFilter',
+ 'visibility',
+] as const satisfies readonly (keyof ResourceQueryParams)[];
+
+/**
+ * Stable identity of one explorer list query. The replica now owns query
+ * identity via `resourceListResource.query`; this is kept for the document
+ * slice, which stamps `ResourceItem._optimistic.queryKey` with it.
+ */
export const getResourceQueryKey = (params?: ResourceQueryParams | null) => {
if (!params) return 'resource-query:default';
@@ -16,46 +39,136 @@ export const getResourceQueryKey = (params?: ResourceQueryParams | null) => {
});
};
-export const mergeServerResourcesWithOptimistic = (
- serverItems: ResourceItem[],
- localResourceMap: Map<string, ResourceItem>,
- queryParams?: ResourceQueryParams | null,
-) => {
- const queryKey = getResourceQueryKey(queryParams);
- const serverMap = new Map(serverItems.map((item) => [item.id, item]));
+/**
+ * The pool fields an optimistic row's `_optimistic.queryKey` carries (see
+ * `getResourceQueryKey`). `sourceFilter` / `visibility` are not part of the row
+ * key, but those switches clear the painted rows outright, so a surviving
+ * client-only row only ever needs re-checking against these.
+ */
+const OPTIMISTIC_POOL_FIELDS = ['category', 'libraryId', 'parentId'] as const;
+
+/**
+ * Whether a locally inserted row (an in-flight upload / create) belongs to the
+ * pool the Explorer is showing. A head refresh for the same pool must keep it β€”
+ * even a re-sort or a view-mode change β€” while a refresh for another folder or
+ * library must not surface it there.
+ */
+export const isOptimisticRowInRequestedPool = (
+ queryKey: string | undefined,
+ params?: ResourceListParams | null,
+): boolean => {
+ if (!queryKey) return false;
+
+ try {
+ const parsed = JSON.parse(queryKey) as Record<string, unknown>;
+ return OPTIMISTIC_POOL_FIELDS.every(
+ (field) => (parsed[field] ?? null) === (params?.[field] ?? null),
+ );
+ } catch {
+ return false;
+ }
+};
+
+// ---- move reconciliation into cached folder lists ------------------------
- const optimisticItems = Array.from(localResourceMap.values()).filter(
- (item) => item._optimistic?.queryKey === queryKey,
- );
+const toTime = (value: Date | string | number | undefined | null) =>
+ value == null ? 0 : new Date(value).getTime();
+
+const SORT_ACCESSORS: Record<string, (item: ResourceItem) => number | string> = {
+ createdAt: (item) => toTime(item.createdAt),
+ name: (item) => item.name ?? '',
+ size: (item) => item.size ?? 0,
+ updatedAt: (item) => toTime(item.updatedAt),
+};
- const optimisticById = new Map<string, ResourceItem>();
- const optimisticOnlyItems: ResourceItem[] = [];
+/**
+ * The order the server returns a list in, mirrored from the knowledge
+ * repository's `orderBy`: both `sorter` and `sortType` have to be present for a
+ * custom sort, anything else is newest-first.
+ */
+const compareResourcesForList =
+ ({ sorter, sortType }: ResourceListParams) =>
+ (a: ResourceItem, b: ResourceItem) => {
+ const custom = sorter && sortType && sorter in SORT_ACCESSORS;
+ const accessor = custom ? SORT_ACCESSORS[sorter!] : SORT_ACCESSORS.createdAt;
+ const direction = custom && String(sortType).toLowerCase() === 'asc' ? 1 : -1;
- for (const item of optimisticItems) {
- if (serverMap.has(item.id)) {
- optimisticById.set(item.id, item);
- continue;
- }
+ const left = accessor(a);
+ const right = accessor(b);
+ const order =
+ typeof left === 'string' && typeof right === 'string'
+ ? left.localeCompare(right)
+ : Number(left) - Number(right);
+ return order * direction;
+ };
- optimisticOnlyItems.push(item);
+/**
+ * Whether a cached list is a plain folder listing the moved row certainly
+ * belongs to. A list narrowed by a keyword, a category tab, a source chip or a
+ * visibility mode may or may not include the row, and the server owns those
+ * rules; such variants are left for revalidation rather than seeded with a row
+ * that might not match. The personal root's default `showFilesInKnowledgeBase:
+ * false` hides library rows, so a row that belongs to a library stays out.
+ */
+export const listsMovedRowUnfiltered = (
+ params: ResourceListParams,
+ resource: ResourceItem,
+): boolean => {
+ if (params.q?.trim()) return false;
+ if (params.category && params.category !== 'all') return false;
+ if (params.sourceFilter && params.sourceFilter !== 'all') return false;
+ if (params.visibility) return false;
+ if (!params.libraryId && !params.showFilesInKnowledgeBase && resource.knowledgeBaseId) {
+ return false;
}
+ return true;
+};
+
+/** Drop the moved row from a list it no longer belongs to (a source folder). */
+export const patchSourceList = (data: ResourceListValue, movedId: string): ResourceListValue => {
+ const items = data.items.filter((item) => item.id !== movedId);
+ if (items.length === data.items.length) return data;
+
+ return {
+ ...data,
+ items,
+ hasMore: data.total === undefined ? data.hasMore : data.total - 1 > items.length,
+ total: data.total === undefined ? undefined : Math.max(items.length, data.total - 1),
+ };
+};
+
+/**
+ * Put the moved row where the server would list it. A cached page keeps its
+ * length: `loadMore` derives the next `offset` from the cached row count, so a
+ * page that grew past its limit would make "load more" skip a server row. On a
+ * full page the row is either placed in order (the row that falls off the end
+ * reappears at that same server offset) or, when it sorts past everything
+ * cached, left for the later page that will contain it.
+ */
+export const patchDestinationList = (
+ data: ResourceListValue,
+ movedResource: ResourceItem,
+ params: ResourceListParams,
+): ResourceListValue => {
+ const remaining = data.items.filter((item) => item.id !== movedResource.id);
+ const removed = data.items.length - remaining.length;
+ const total = data.total === undefined ? undefined : data.total - removed + 1;
- const mergedList = [
- ...optimisticOnlyItems,
- ...serverItems.map((item) => optimisticById.get(item.id) ?? item),
- ];
- const mergedMap = new Map(localResourceMap);
+ const compare = compareResourcesForList(params);
+ const position = remaining.findIndex((item) => compare(movedResource, item) < 0);
+ const inserted =
+ position === -1
+ ? [...remaining, movedResource]
+ : [...remaining.slice(0, position), movedResource, ...remaining.slice(position)];
- for (const item of mergedList) {
- mergedMap.set(item.id, item);
+ const pageLength = data.items.length;
+ if (!data.hasMore || inserted.length <= pageLength) {
+ return { ...data, items: inserted, total };
}
return {
- changed:
- !isEqual(mergedList, serverItems) ||
- optimisticOnlyItems.length > 0 ||
- optimisticById.size > 0,
- resourceList: mergedList,
- resourceMap: mergedMap,
+ ...data,
+ items: position === -1 ? remaining : inserted.slice(0, pageLength),
+ total,
};
};