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(replica): fold queryProjectionStorage into @/libs/replica (#21465)

Arvin Xuf81464f6b52c
diff --git a/.agents/skills/data-fetching-architecture/references/home-first-paint.md b/.agents/skills/data-fetching-architecture/references/home-first-paint.md
index 3c56c3d8d91..203da5c475d 100644
--- a/.agents/skills/data-fetching-architecture/references/home-first-paint.md
+++ b/.agents/skills/data-fetching-architecture/references/home-first-paint.md
@@ -17,7 +17,7 @@ the browser.
Restore cached results into the state consumed by the UI, then revalidate through
the existing SWR hook.
- For a small subset needed before a larger response arrives, reuse
- `LocalStorageQueryProjectionStorage` from `src/libs/queryProjectionStorage`.
+ `AppLocalStorage` from `src/libs/replica/storage.ts`.
Keep field selection and lifecycle rules in the owning domain; do not create
another storage framework or duplicate the same data across caches without a
demonstrated need.
@@ -31,7 +31,7 @@ the browser.
## User Display Snapshot Reference
`src/store/user/displaySnapshot.ts` is the domain adapter for the user's avatar URL
-and preference. It reuses `LocalStorageQueryProjectionStorage`; it is not a second
+and preference. It reuses `AppLocalStorage`; it is not a second
cache engine. `src/layout/AuthProvider/BetterAuth/UserUpdater.tsx` reads it after the
session identifies the exact user, before painting that user's initialized shell.
The authoritative user-state response still refreshes the values afterward.
diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.md
index 0426c1a31d4..14644cc89f0 100644
--- a/.agents/skills/zustand/SKILL.md
+++ b/.agents/skills/zustand/SKILL.md
@@ -40,7 +40,7 @@ Server lists and details the UI paints go through `@/libs/replica`, not a hand-w
3. Bind it in the private class: `createReplicaSlice(resource, { get, set, stateKey: 'xxxReplica', view: recordLens('xxxMap'), … })`. When the same entity lives in several replicas (list row + detail), link them with `linkReplicaEntity([list, detail])`.
4. Read: `slice.useSync(params)` returns only fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`). Data comes from selectors over `xxxMap`. "Entry is `undefined`" is the loading signal — do not add `xxxInit` flags or `loadingXxxIds`.
5. Read with no view mounted (hover prefetch, refresh after a mutation): `await slice.fetch(params)` (`{ fresh: true }` after a write). Never call the service and `slice.replace(...)` by hand, because that skips the scope, removal, clear and superseded-request guards. Side effects of every response (not-found maps, seeding another store) go in the slice `effects` (`onApplied` / `onMissing` / `onPurge` / `onError`) with `isMissing`, not in one hook's `onSuccess`.
-6. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `settleWithin(…, PRE_PAINT_HYDRATE_TIMEOUT)` from `@/libs/replica/prePaint`. `@/libs/replica` presets the cache scope, IndexedDB / localStorage storage (`@/libs/queryProjectionStorage`) and the app's SWR driver; the package README stays app-agnostic.
+6. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `settleWithin(…, PRE_PAINT_HYDRATE_TIMEOUT)` from `@/libs/replica/prePaint`. `@/libs/replica` presets the cache scope, IndexedDB / localStorage storage (`AppIndexedDBStorage` / `AppLocalStorage` in `@/libs/replica/storage`) and the app's SWR driver; the package README stays app-agnostic.
7. Write: `slice.optimistic(key, apply, serverCall)` or `entity.optimistic(id, fn | 'remove', serverCall)`. A failed call rolls back to the confirmed value, so deletes are optimistic too. Rows that exist only on the client (temp ids) are declared with `isClientOnly` and seeded with `update(key, fn, { persist: false })`.
Outside test seeding, write a replica's view only through its slice. A plain `set` bypasses the engine's bookkeeping (persistence, rollback base, entity links).
diff --git a/src/features/AgentBuilder/SuggestionChips/projection.ts b/src/features/AgentBuilder/SuggestionChips/projection.ts
index 74b08712b6e..55e44d70a41 100644
--- a/src/features/AgentBuilder/SuggestionChips/projection.ts
+++ b/src/features/AgentBuilder/SuggestionChips/projection.ts
@@ -1,6 +1,6 @@
import type { BuilderSuggestionItem, BuilderSuggestionMode } from '@lobechat/prompts';
-import type { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import type { AppLocalStorage } from '@/libs/replica';
import { cacheScope, defineReplica } from '@/libs/replica';
export interface BuilderSuggestionParams {
@@ -66,7 +66,7 @@ export const peekBuilderSuggestions = (
): BuilderSuggestionBatch | undefined => {
if (!cacheScope.canHydrate?.()) return undefined;
const storage = builderSuggestionResource.storage as
- LocalStorageQueryProjectionStorage<BuilderSuggestionBatch> | undefined;
+ AppLocalStorage<BuilderSuggestionBatch> | undefined;
const data = storage?.getSync?.({
queryKey: builderSuggestionResource.storageKey(params),
scope,
diff --git a/src/features/AgentProfileCard/useAgentProfileDetail.test.ts b/src/features/AgentProfileCard/useAgentProfileDetail.test.ts
index 1733c67cf29..4ce0cac2439 100644
--- a/src/features/AgentProfileCard/useAgentProfileDetail.test.ts
+++ b/src/features/AgentProfileCard/useAgentProfileDetail.test.ts
@@ -9,8 +9,7 @@ import { createElement, useEffect } from 'react';
import { SWRConfig, useSWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
-import { cacheScope } from '@/libs/replica';
+import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
import { agentService } from '@/services/agent';
import { useAgentStore } from '@/store/agent';
@@ -34,7 +33,7 @@ const wrapper = ({ children }: PropsWithChildren) =>
);
/** The rows the agent config replica reads (`replica:<name>:v<version>`). */
-const configStorage = new IndexedDBQueryProjectionStorage<unknown>({
+const configStorage = new AppIndexedDBStorage<unknown>({
namespace: 'replica:agentConfig:v1',
});
diff --git a/src/features/AgentRoute/useResolvedAgentRouteId.test.ts b/src/features/AgentRoute/useResolvedAgentRouteId.test.ts
index 068d8a67f2e..38a6e45eccb 100644
--- a/src/features/AgentRoute/useResolvedAgentRouteId.test.ts
+++ b/src/features/AgentRoute/useResolvedAgentRouteId.test.ts
@@ -10,8 +10,7 @@ import { createElement, useEffect } from 'react';
import { SWRConfig, useSWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
-import { cacheScope } from '@/libs/replica';
+import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
import { agentService } from '@/services/agent';
import { useAgentStore } from '@/store/agent';
@@ -44,7 +43,7 @@ const wrapper = ({ children }: PropsWithChildren) =>
);
/** The rows the slug lookup replica reads (`replica:<name>:v<version>`). */
-const slugStorage = new IndexedDBQueryProjectionStorage<string>({
+const slugStorage = new AppIndexedDBStorage<string>({
namespace: 'replica:agentSlugId:v1',
});
diff --git a/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.ts b/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.ts
index 0c49d1c192d..89c5bc46260 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.ts
+++ b/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.ts
@@ -15,8 +15,7 @@ import { createElement, useEffect } from 'react';
import { SWRConfig, useSWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
-import { cacheScope } from '@/libs/replica';
+import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
import { gitService } from '@/services/git';
import { initialGitStatusState, useGitStatusStore } from '@/store/device/gitStatus/store';
@@ -57,7 +56,7 @@ const DEVICE = 'device-1';
const PATH = '/repo';
/** The persisted row of `deviceId + path`, as the branch-list replica stores it. */
const ROW_KEY = `${DEVICE}\u0000${PATH}`;
-const storage = new IndexedDBQueryProjectionStorage<{ value?: DeviceGitBranchListItem[] }>({
+const storage = new AppIndexedDBStorage<{ value?: DeviceGitBranchListItem[] }>({
namespace: 'replica:deviceGitBranchList:v1',
});
diff --git a/src/features/RecommendTaskTemplates/projection.ts b/src/features/RecommendTaskTemplates/projection.ts
index 3c7d7b3d074..7fd103875cb 100644
--- a/src/features/RecommendTaskTemplates/projection.ts
+++ b/src/features/RecommendTaskTemplates/projection.ts
@@ -4,7 +4,7 @@ import type {
TaskTemplateConnectorSource,
} from '@lobechat/const';
-import type { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import type { AppLocalStorage } from '@/libs/replica';
import { cacheScope, defineReplica, replicaKeys } from '@/libs/replica';
import { TASK_TEMPLATE_DAILY_RECOMMEND_REPLICA } from './const';
@@ -113,8 +113,7 @@ export const peekDailyRecommendations = (
scope: string,
): unknown[] | undefined => {
if (!cacheScope.canHydrate?.()) return undefined;
- const storage = dailyRecommendResource.storage as
- LocalStorageQueryProjectionStorage<TaskTemplate[]> | undefined;
+ const storage = dailyRecommendResource.storage as AppLocalStorage<TaskTemplate[]> | undefined;
const data = storage?.getSync?.({
queryKey: dailyRecommendResource.storageKey(params),
scope,
diff --git a/src/libs/queryProjectionStorage/index.ts b/src/libs/queryProjectionStorage/index.ts
deleted file mode 100644
index b423278e44e..00000000000
--- a/src/libs/queryProjectionStorage/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from './indexedDB';
-export * from './localStorage';
-export type * from './types';
diff --git a/src/libs/queryProjectionStorage/indexedDB.ts b/src/libs/queryProjectionStorage/indexedDB.ts
deleted file mode 100644
index 47f4d4e99c1..00000000000
--- a/src/libs/queryProjectionStorage/indexedDB.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { KeyValueReplicaStorage } from '@lobechat/replica';
-
-import { localDatabase } from '@/libs/localDatabase';
-
-interface IndexedDBQueryProjectionStorageOptions {
- namespace: string;
-}
-
-const COLLECTION = 'query-projections';
-
-/** Replica rows in the app's local database (IndexedDB on the web, SQLite in Electron). */
-export class IndexedDBQueryProjectionStorage<T> extends KeyValueReplicaStorage<T> {
- constructor({ namespace }: IndexedDBQueryProjectionStorageOptions) {
- super({
- namespace,
- // Resolve `localDatabase` per call: the active adapter can be swapped at boot.
- store: {
- delete: (key) => localDatabase.delete(COLLECTION, key),
- get: (key) => localDatabase.get(COLLECTION, key),
- initialize: () => localDatabase.initialize(),
- set: (key, value) => localDatabase.set(COLLECTION, key, value),
- },
- });
- }
-}
diff --git a/src/libs/queryProjectionStorage/localStorage.ts b/src/libs/queryProjectionStorage/localStorage.ts
deleted file mode 100644
index 369298b014d..00000000000
--- a/src/libs/queryProjectionStorage/localStorage.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { LocalStorageReplicaStorage } from '@lobechat/replica';
-import superjson from 'superjson';
-
-import type { QueryProjection, QueryProjectionCodec } from './types';
-
-interface LocalStorageQueryProjectionStorageOptions<T> {
- codec?: QueryProjectionCodec<T>;
- namespace: string;
-}
-
-/** Replica rows in `localStorage`, serialized with superjson so `Date` and friends survive. */
-export class LocalStorageQueryProjectionStorage<T> extends LocalStorageReplicaStorage<T> {
- constructor({ codec, namespace }: LocalStorageQueryProjectionStorageOptions<T>) {
- super({
- codec: codec ?? {
- parse: superjson.parse<QueryProjection<T>>,
- stringify: superjson.stringify,
- },
- namespace,
- });
- }
-}
diff --git a/src/libs/queryProjectionStorage/types.ts b/src/libs/queryProjectionStorage/types.ts
deleted file mode 100644
index b13a7b2172d..00000000000
--- a/src/libs/queryProjectionStorage/types.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { ReplicaRow, ReplicaRowCodec, ReplicaRowKey, ReplicaStorage } from '@lobechat/replica';
-
-export type QueryProjectionKey = ReplicaRowKey;
-
-export type QueryProjection<T> = ReplicaRow<T>;
-
-/** A replica storage whose strict read is required: replicas refuse destructive passes without it. */
-export type QueryProjectionStorage<T> = Required<ReplicaStorage<T>>;
-
-export type QueryProjectionCodec<T> = ReplicaRowCodec<T>;
diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.ts
index d15f4654461..ca9d8c5310f 100644
--- a/src/libs/replica/index.ts
+++ b/src/libs/replica/index.ts
@@ -15,14 +15,11 @@ import {
createSWRDriver,
} from '@lobechat/replica/zustand';
-import {
- IndexedDBQueryProjectionStorage,
- LocalStorageQueryProjectionStorage,
-} from '@/libs/queryProjectionStorage';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { getCacheScope, isScopeTrusted, useCacheScope } from '@/libs/swr/useCacheScope';
import { notifyReplicaDevtools, registerReplicaDevtools } from './devtools';
+import { AppIndexedDBStorage, AppLocalStorage } from './storage';
/**
* LobeHub wiring of `@lobechat/replica`: replicas are partitioned like the SWR
@@ -96,9 +93,8 @@ const resolveStorage =
(namespace: string): ReplicaStorage<TData> | undefined => {
if (typeof storage === 'function') return storage(namespace);
if (typeof storage === 'object') return storage;
- if (storage === 'indexedDB') return new IndexedDBQueryProjectionStorage<TData>({ namespace });
- if (storage === 'localStorage')
- return new LocalStorageQueryProjectionStorage<TData>({ namespace });
+ if (storage === 'indexedDB') return new AppIndexedDBStorage<TData>({ namespace });
+ if (storage === 'localStorage') return new AppLocalStorage<TData>({ namespace });
return undefined;
};
@@ -171,6 +167,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
return slice;
};
+export { AppIndexedDBStorage, AppLocalStorage } from './storage';
export * from '@lobechat/replica';
export {
recordLens,
diff --git a/src/libs/queryProjectionStorage/indexedDB.test.ts b/src/libs/replica/storage.indexedDB.test.ts
similarity index 78%
rename from src/libs/queryProjectionStorage/indexedDB.test.ts
rename to src/libs/replica/storage.indexedDB.test.ts
index 9de758cc39a..5cbab9db4e4 100644
--- a/src/libs/queryProjectionStorage/indexedDB.test.ts
+++ b/src/libs/replica/storage.indexedDB.test.ts
@@ -2,15 +2,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { localDatabase } from '@/libs/localDatabase';
-import { IndexedDBQueryProjectionStorage } from './indexedDB';
+import { AppIndexedDBStorage } from './storage';
-describe('IndexedDBQueryProjectionStorage', () => {
+describe('AppIndexedDBStorage', () => {
beforeEach(() => vi.restoreAllMocks());
it('uses one scoped row per query projection', async () => {
vi.spyOn(localDatabase, 'initialize').mockResolvedValue();
const set = vi.spyOn(localDatabase, 'set').mockResolvedValue();
- const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+ const storage = new AppIndexedDBStorage<string[]>({ namespace: 'projects' });
const key = { queryKey: 'detail:1', scope: 'user:workspace' };
await storage.set(key, { data: ['cached'], updatedAt: 1 });
@@ -24,7 +24,7 @@ describe('IndexedDBQueryProjectionStorage', () => {
it('rejects a write that did not land, so the replica retries it', async () => {
vi.spyOn(localDatabase, 'initialize').mockResolvedValue();
vi.spyOn(localDatabase, 'set').mockRejectedValue(new Error('transaction aborted'));
- const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+ const storage = new AppIndexedDBStorage<string[]>({ namespace: 'projects' });
await expect(
storage.set({ queryKey: 'all', scope: 'personal' }, { data: ['x'], updatedAt: 1 }),
@@ -33,7 +33,7 @@ describe('IndexedDBQueryProjectionStorage', () => {
it('treats persistence failures as a cache miss', async () => {
vi.spyOn(localDatabase, 'initialize').mockRejectedValue(new Error('unavailable'));
- const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+ const storage = new AppIndexedDBStorage<string[]>({ namespace: 'projects' });
await expect(storage.get({ queryKey: 'all', scope: 'personal' })).resolves.toBeUndefined();
});
@@ -41,7 +41,7 @@ describe('IndexedDBQueryProjectionStorage', () => {
it('reports a failed delete so the caller can retry it', async () => {
vi.spyOn(localDatabase, 'initialize').mockResolvedValue();
vi.spyOn(localDatabase, 'delete').mockRejectedValue(new Error('database closed'));
- const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+ const storage = new AppIndexedDBStorage<string[]>({ namespace: 'projects' });
await expect(storage.remove({ queryKey: 'all', scope: 'personal' })).rejects.toThrow(
'database closed',
@@ -51,7 +51,7 @@ describe('IndexedDBQueryProjectionStorage', () => {
it('rejects a strict read that failed, while get stays a cache miss', async () => {
vi.spyOn(localDatabase, 'initialize').mockResolvedValue();
vi.spyOn(localDatabase, 'get').mockRejectedValue(new Error('database closed'));
- const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+ const storage = new AppIndexedDBStorage<string[]>({ namespace: 'projects' });
const key = { queryKey: '__replica:index', scope: 'personal' };
await expect(storage.getStrict(key)).rejects.toThrow('database closed');
diff --git a/src/libs/queryProjectionStorage/localStorage.test.ts b/src/libs/replica/storage.localStorage.test.ts
similarity index 77%
rename from src/libs/queryProjectionStorage/localStorage.test.ts
rename to src/libs/replica/storage.localStorage.test.ts
index 100abe3ccc6..d62da58f95f 100644
--- a/src/libs/queryProjectionStorage/localStorage.test.ts
+++ b/src/libs/replica/storage.localStorage.test.ts
@@ -1,15 +1,15 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { LocalStorageQueryProjectionStorage } from './localStorage';
+import { AppLocalStorage } from './storage';
afterEach(() => {
vi.restoreAllMocks();
localStorage.clear();
});
-describe('LocalStorageQueryProjectionStorage', () => {
+describe('AppLocalStorage', () => {
it('restores a scoped projection synchronously before the next paint', () => {
- const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const storage = new AppLocalStorage<string[]>({ namespace: 'test' });
const key = { queryKey: 'display', scope: 'user-a' };
void storage.set(key, { data: ['cached'], updatedAt: 1 });
@@ -19,7 +19,7 @@ describe('LocalStorageQueryProjectionStorage', () => {
});
it('rejects a write that did not land (quota), so the replica retries it', async () => {
- const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const storage = new AppLocalStorage<string[]>({ namespace: 'test' });
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('QuotaExceededError');
});
@@ -30,7 +30,7 @@ describe('LocalStorageQueryProjectionStorage', () => {
});
it('reads and writes one scoped query through the async interface', async () => {
- const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const storage = new AppLocalStorage<string[]>({ namespace: 'test' });
const key = { queryKey: 'limit:10', scope: 'user:workspace' };
await storage.set(key, { data: ['cached'], updatedAt: 1 });
@@ -39,7 +39,7 @@ describe('LocalStorageQueryProjectionStorage', () => {
});
it('isolates projections by scope and query key', async () => {
- const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const storage = new AppLocalStorage<string[]>({ namespace: 'test' });
await storage.set({ queryKey: 'limit:10', scope: 'scope-a' }, { data: ['a'], updatedAt: 1 });
@@ -48,7 +48,7 @@ describe('LocalStorageQueryProjectionStorage', () => {
});
it('preserves rich data types with the default codec', async () => {
- const storage = new LocalStorageQueryProjectionStorage<{ createdAt: Date }>({
+ const storage = new AppLocalStorage<{ createdAt: Date }>({
namespace: 'test',
});
const key = { queryKey: 'detail:1', scope: 'scope' };
@@ -59,7 +59,7 @@ describe('LocalStorageQueryProjectionStorage', () => {
});
it('reports a failed delete so the caller can retry it', async () => {
- const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const storage = new AppLocalStorage<string[]>({ namespace: 'test' });
vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
throw new Error('access denied');
});
@@ -70,7 +70,7 @@ describe('LocalStorageQueryProjectionStorage', () => {
});
it('rejects a strict read that failed, while get stays a cache miss', async () => {
- const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const storage = new AppLocalStorage<string[]>({ namespace: 'test' });
const key = { queryKey: '__replica:index', scope: 'user-a' };
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('access denied');
diff --git a/src/libs/replica/storage.ts b/src/libs/replica/storage.ts
new file mode 100644
index 00000000000..99e084c77e0
--- /dev/null
+++ b/src/libs/replica/storage.ts
@@ -0,0 +1,55 @@
+import {
+ KeyValueReplicaStorage,
+ LocalStorageReplicaStorage,
+ type ReplicaRow,
+ type ReplicaRowCodec,
+} from '@lobechat/replica';
+import superjson from 'superjson';
+
+import { localDatabase } from '@/libs/localDatabase';
+
+/**
+ * The app's replica storages. This module imports only the package, the local
+ * database and superjson so stores inside the `@/libs/replica` import cycle
+ * (the user store) can construct a storage without pulling in the index.
+ */
+
+interface AppIndexedDBStorageOptions {
+ namespace: string;
+}
+
+const COLLECTION = 'query-projections';
+
+/** Replica rows in the app's local database (IndexedDB on the web, SQLite in Electron). */
+export class AppIndexedDBStorage<T> extends KeyValueReplicaStorage<T> {
+ constructor({ namespace }: AppIndexedDBStorageOptions) {
+ super({
+ namespace,
+ // Resolve `localDatabase` per call: the active adapter can be swapped at boot.
+ store: {
+ delete: (key) => localDatabase.delete(COLLECTION, key),
+ get: (key) => localDatabase.get(COLLECTION, key),
+ initialize: () => localDatabase.initialize(),
+ set: (key, value) => localDatabase.set(COLLECTION, key, value),
+ },
+ });
+ }
+}
+
+interface AppLocalStorageOptions<T> {
+ codec?: ReplicaRowCodec<T>;
+ namespace: string;
+}
+
+/** Replica rows in `localStorage`, serialized with superjson so `Date` and friends survive. */
+export class AppLocalStorage<T> extends LocalStorageReplicaStorage<T> {
+ constructor({ codec, namespace }: AppLocalStorageOptions<T>) {
+ super({
+ codec: codec ?? {
+ parse: superjson.parse<ReplicaRow<T>>,
+ stringify: superjson.stringify,
+ },
+ namespace,
+ });
+ }
+}
diff --git a/src/services/message/replica.ts b/src/services/message/replica.ts
index 49dc187741f..71971cda5f2 100644
--- a/src/services/message/replica.ts
+++ b/src/services/message/replica.ts
@@ -1,6 +1,6 @@
import type { ConversationContext, UIChatMessage } from '@lobechat/types';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import { AppIndexedDBStorage } from '@/libs/replica';
import {
cacheScope,
defineReplica,
@@ -279,7 +279,7 @@ export const toolResultPayloadResource = defineReplica<string, ToolResultPayload
name: TOOL_RESULT_PAYLOAD_NAME,
persist: { maxEntries: TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES },
storage: new SizeCappedPayloadStorage(
- new IndexedDBQueryProjectionStorage<ToolResultPayloadRead>({
+ new AppIndexedDBStorage<ToolResultPayloadRead>({
namespace: `replica:${TOOL_RESULT_PAYLOAD_NAME}:v${TOOL_RESULT_PAYLOAD_VERSION}`,
}),
TOOL_RESULT_PAYLOAD_MAX_PERSISTED_CHARS,
diff --git a/src/store/agent/slices/agent/persistedReads.test.ts b/src/store/agent/slices/agent/persistedReads.test.ts
index 307efa31422..c7e6bf93dab 100644
--- a/src/store/agent/slices/agent/persistedReads.test.ts
+++ b/src/store/agent/slices/agent/persistedReads.test.ts
@@ -15,11 +15,7 @@ import { createElement, useEffect } from 'react';
import { SWRConfig, useSWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- IndexedDBQueryProjectionStorage,
- LocalStorageQueryProjectionStorage,
-} from '@/libs/queryProjectionStorage';
-import { cacheScope } from '@/libs/replica';
+import { AppIndexedDBStorage, AppLocalStorage, cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
import { agentService } from '@/services/agent';
import { aiAgentService } from '@/services/aiAgent';
@@ -53,10 +49,10 @@ const wrapper = ({ children }: PropsWithChildren) =>
/** The network never answers: whatever paints came from the device. */
const pending = () => new Promise<never>(() => {}) as Promise<any>;
-const availableAgentsStorage = new IndexedDBQueryProjectionStorage<unknown>({
+const availableAgentsStorage = new AppIndexedDBStorage<unknown>({
namespace: 'replica:availableAgents:v1',
});
-const capabilityStorage = new LocalStorageQueryProjectionStorage<unknown>({
+const capabilityStorage = new AppLocalStorage<unknown>({
namespace: 'replica:heteroServerDefaultCapability:v1',
});
diff --git a/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts b/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts
index 8a9aeeaf00b..e4f5061772f 100644
--- a/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts
+++ b/src/store/aiInfra/slices/aiProvider/__tests__/replica.test.ts
@@ -1,7 +1,7 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import { AppIndexedDBStorage } from '@/libs/replica';
import { aiProviderSelectors, useAiInfraStore as useStore } from '@/store/aiInfra';
import { initialAIModelState } from '@/store/aiInfra/slices/aiModel/initialState';
import type {
@@ -80,7 +80,7 @@ const RUNTIME_STATE_ROW = {
queryKey: aiProviderRuntimeStateResource.storageKey({ isLogin: true }),
scope: SCOPE,
};
-const rawRuntimeStateStorage = new IndexedDBQueryProjectionStorage<any>({
+const rawRuntimeStateStorage = new AppIndexedDBStorage<any>({
namespace: 'replica:aiProviderRuntimeState:v2',
});
diff --git a/src/store/aiInfra/slices/aiProvider/projection.ts b/src/store/aiInfra/slices/aiProvider/projection.ts
index 1160c8e56c7..9ba250ca384 100644
--- a/src/store/aiInfra/slices/aiProvider/projection.ts
+++ b/src/store/aiInfra/slices/aiProvider/projection.ts
@@ -1,8 +1,7 @@
import type { ReplicaStorage } from '@lobechat/replica';
import type { LobeDefaultAiModelListItem } from 'model-bank';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
-import { defineReplica, stableQueryKey } from '@/libs/replica';
+import { AppIndexedDBStorage, defineReplica, stableQueryKey } from '@/libs/replica';
import { aiProviderService } from '@/services/aiProvider';
import type {
AiProviderDetailItem,
@@ -138,7 +137,7 @@ export const toRuntimeStateDisplaySnapshot = (
};
const createRuntimeStateStorage = (): ReplicaStorage<AiProviderRuntimeStateView> => {
- const storage = new IndexedDBQueryProjectionStorage<AiProviderRuntimeStateView>({
+ const storage = new AppIndexedDBStorage<AiProviderRuntimeStateView>({
namespace: 'replica:aiProviderRuntimeState:v2',
});
const read = async (
diff --git a/src/store/device/deviceReplicaFirstPaint.test.ts b/src/store/device/deviceReplicaFirstPaint.test.ts
index b3025af090c..8f6d6b01c43 100644
--- a/src/store/device/deviceReplicaFirstPaint.test.ts
+++ b/src/store/device/deviceReplicaFirstPaint.test.ts
@@ -15,8 +15,7 @@ import { createElement, useEffect } from 'react';
import { SWRConfig, useSWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
-import { cacheScope } from '@/libs/replica';
+import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';
import { setScopedMutate } from '@/libs/swr/mutate';
import { deviceService } from '@/services/device';
import { gitService } from '@/services/git';
@@ -64,13 +63,13 @@ const pending = () => new Promise<never>(() => {});
const DEVICE = 'device-1';
const CWD = '/repo';
-const remoteBranchStorage = new IndexedDBQueryProjectionStorage<{ value?: unknown }>({
+const remoteBranchStorage = new AppIndexedDBStorage<{ value?: unknown }>({
namespace: 'replica:deviceGitRemoteBranchList:v1',
});
-const tunnelStorage = new IndexedDBQueryProjectionStorage<unknown[]>({
+const tunnelStorage = new AppIndexedDBStorage<unknown[]>({
namespace: 'replica:deviceTunnelLinks:v1',
});
-const portStorage = new IndexedDBQueryProjectionStorage<DeviceListeningPortsResult>({
+const portStorage = new AppIndexedDBStorage<DeviceListeningPortsResult>({
namespace: 'replica:deviceListeningPorts:v1',
});
diff --git a/src/store/device/projection.ts b/src/store/device/projection.ts
index 65a743a280a..149f0647d34 100644
--- a/src/store/device/projection.ts
+++ b/src/store/device/projection.ts
@@ -1,6 +1,6 @@
import type { DeviceListItem } from '@lobechat/types';
-import { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import { AppLocalStorage } from '@/libs/replica';
import { defineReplica, REPLICA_INDEX_KEY, type ReplicaStorage } from '@/libs/replica';
/** The store reads every device of the active scope, so the list has one entry. */
@@ -31,7 +31,7 @@ export const toPersistedDevice = (device: DeviceListItem): DeviceListItem => ({
* narrowed. The engine's own index row passes through untouched.
*/
const createDeviceListStorage = (namespace: string): ReplicaStorage<DeviceListItem[]> => {
- const storage = new LocalStorageQueryProjectionStorage<DeviceListItem[]>({ namespace });
+ const storage = new AppLocalStorage<DeviceListItem[]>({ namespace });
return {
get: storage.get,
diff --git a/src/store/projectFile/projection.ts b/src/store/projectFile/projection.ts
index 692ff90d664..a58fedf3403 100644
--- a/src/store/projectFile/projection.ts
+++ b/src/store/projectFile/projection.ts
@@ -1,10 +1,6 @@
import type { GitWorkingTreeFiles, ProjectFileIndexResult } from '@lobechat/electron-client-ipc';
-import {
- IndexedDBQueryProjectionStorage,
- LocalStorageQueryProjectionStorage,
-} from '@/libs/queryProjectionStorage';
-import { cacheScope, defineReplica } from '@/libs/replica';
+import { AppIndexedDBStorage, AppLocalStorage, cacheScope, defineReplica } from '@/libs/replica';
import { localFileKeys } from '@/libs/swr/keys';
import {
@@ -62,7 +58,7 @@ export const projectIndexResource = defineReplica<
name: 'projectFileIndex',
persist: { maxEntries: PROJECT_INDEX_PERSIST_MAX_ROWS },
storage: (namespace) =>
- withPersistCodec(new IndexedDBQueryProjectionStorage({ namespace }), projectIndexCodec),
+ withPersistCodec(new AppIndexedDBStorage({ namespace }), projectIndexCodec),
syncKey: (params) => localFileKeys.projectIndex(projectIndexHost(params), params.dirPath),
version: 1,
});
@@ -81,7 +77,7 @@ export const gitWorkingTreeFilesResource = defineReplica<
name: 'gitWorkingTreeFiles',
persist: { maxEntries: GIT_WORKING_TREE_PERSIST_MAX_ROWS },
storage: (namespace) =>
- withPersistCodec(new IndexedDBQueryProjectionStorage({ namespace }), gitWorkingTreeFilesCodec),
+ withPersistCodec(new AppIndexedDBStorage({ namespace }), gitWorkingTreeFilesCodec),
syncKey: ({ deviceId, dirPath }) => localFileKeys.gitWorkingTreeFiles(deviceId, dirPath),
version: 1,
});
@@ -107,7 +103,7 @@ export const filesLocationResource = defineReplica<FilesLocationParams, FilesLoc
key: ({ contextKey }) => contextKey,
name: 'filesLocation',
persist: { maxEntries: 100 },
- storage: (namespace) => new LocalStorageQueryProjectionStorage<FilesLocation>({ namespace }),
+ storage: (namespace) => new AppLocalStorage<FilesLocation>({ namespace }),
version: 1,
});
@@ -118,8 +114,7 @@ export const filesLocationResource = defineReplica<FilesLocationParams, FilesLoc
*/
export const peekFilesLocation = (contextKey: string, scope: string): FilesLocation | undefined => {
if (!cacheScope.canHydrate?.()) return undefined;
- const storage = filesLocationResource.storage as
- LocalStorageQueryProjectionStorage<FilesLocation> | undefined;
+ const storage = filesLocationResource.storage as AppLocalStorage<FilesLocation> | undefined;
return storage?.getSync({ queryKey: filesLocationResource.storageKey({ contextKey }), scope })
?.data;
};
diff --git a/src/store/user/displaySnapshot.ts b/src/store/user/displaySnapshot.ts
index 4653fd6d237..66ffb377d75 100644
--- a/src/store/user/displaySnapshot.ts
+++ b/src/store/user/displaySnapshot.ts
@@ -2,7 +2,7 @@ import { UserPreferenceSchema } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import type { PartialDeep } from 'type-fest';
-import { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';
+import { AppLocalStorage } from '@/libs/replica/storage';
import type { LobeUser, UserPreference } from '@/types/user';
import type { UserSettings } from '@/types/user/settings';
@@ -25,7 +25,7 @@ export interface UserDisplaySnapshot {
* allowlist of sections: `keyVaults` and `market` hold credentials, and the
* server passes unknown sections through.
*/
-const storage = new LocalStorageQueryProjectionStorage<UserDisplaySnapshot>({
+const storage = new AppLocalStorage<UserDisplaySnapshot>({
namespace: 'lobehub:user-display-snapshot:v1',
});
const snapshotKey = (userId: string) => ({ queryKey: 'display', scope: userId });
diff --git a/src/store/verify/projection.ts b/src/store/verify/projection.ts
index 99c2ed26922..a31ca1339ca 100644
--- a/src/store/verify/projection.ts
+++ b/src/store/verify/projection.ts
@@ -1,8 +1,7 @@
import type { AcceptanceSubjectType } from '@lobechat/types';
import type { VerifyCheckResultItem } from '@/database/schemas/verify';
-import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
-import { defineReplica } from '@/libs/replica';
+import { AppIndexedDBStorage, defineReplica } from '@/libs/replica';
import type { AcceptanceBundle, AcceptanceBySubject, VerifyStateResponse } from '@/services/verify';
/**
@@ -133,7 +132,7 @@ export const verifyRunResource = defineReplica<string, VerifyRunSnapshot>({
key: (operationId) => operationId,
name: VERIFY_RUN_NAME,
persist: { maxEntries: 100 },
- storage: new IndexedDBQueryProjectionStorage<VerifyRunSnapshot>({
+ storage: new AppIndexedDBStorage<VerifyRunSnapshot>({
namespace: `replica:${VERIFY_RUN_NAME}:v${VERIFY_RUN_VERSION}`,
}),
version: VERIFY_RUN_VERSION,