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.

πŸ› fix(swr): keep IndexedDB cache across sessions and evict it on delete (#16211)

Arvin Xue02f83dd28d1
diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.ts
index a3d8985f9c0..5755dca99be 100644
--- a/src/libs/swr/localStorageProvider.test.ts
+++ b/src/libs/swr/localStorageProvider.test.ts
@@ -4,7 +4,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { taskTemplateKeys } from './keys';
-import { localDataCache } from './localDataCache';
+import { buildLocalDataKey, localDataCache } from './localDataCache';
import {
CACHE_TIERS,
clearSWRCache,
@@ -213,6 +213,51 @@ describe('createCacheProvider β€” tiering', () => {
expect(map.has('recents-v')).toBe(false);
});
+ it('hydrates idb-tier entries regardless of age (never expires)', async () => {
+ // seed an idb entry via a throwaway provider
+ const seedScope = { value: 's1' };
+ const { provider: seed } = buildProvider(seedScope);
+ seed().set('MSGS:old', { ok: true });
+ await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);
+
+ // a fresh provider with an absurdly small TTL β€” the row is well past it
+ const scope = { value: 's1' };
+ const { provider } = buildProvider(scope, { ttl: 1 });
+ const map = provider();
+
+ // idb tier ignores TTL: the stale row still hydrates (stale-while-revalidate)
+ await until(() => map.get('MSGS:old') !== undefined);
+ expect(map.get('MSGS:old')).toEqual({ ok: true });
+ });
+
+ it('drops idb-tier entries on version mismatch', async () => {
+ // seed an idb entry under a different app version
+ const seedScope = { value: 's1' };
+ const { provider: seed } = buildProvider(seedScope, { version: '9.9.9' });
+ seed().set('MSGS:stale', { ok: false });
+ await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);
+
+ const scope = { value: 's1' };
+ const { provider } = buildProvider(scope, { version: '1.0.0' });
+ const map = provider();
+
+ // give async hydration a chance, then assert it never lands
+ await new Promise((r) => setTimeout(r, 40));
+ expect(map.has('MSGS:stale')).toBe(false);
+ });
+
+ it('drops legacy idb rows that carry no cache version', async () => {
+ // seed a row directly with no version (pre-versioning / non-conforming writer)
+ await localDataCache.set(buildLocalDataKey('s1', 'MSGS:legacy'), { ok: false });
+
+ const scope = { value: 's1' };
+ const { provider } = buildProvider(scope, { version: '1.0.0' });
+ const map = provider();
+
+ await new Promise((r) => setTimeout(r, 40));
+ expect(map.has('MSGS:legacy')).toBe(false);
+ });
+
it('handles localStorage QuotaExceededError without throwing', async () => {
const scope = { value: 's1' };
const { provider } = buildProvider(scope);
diff --git a/src/libs/swr/localStorageProvider.ts b/src/libs/swr/localStorageProvider.ts
index 459e3d4100c..9aa10b0004d 100644
--- a/src/libs/swr/localStorageProvider.ts
+++ b/src/libs/swr/localStorageProvider.ts
@@ -51,7 +51,11 @@ export interface CacheProviderOptions {
onError?: (error: Error) => void;
/** Called after a scope's IndexedDB tier finishes hydrating. */
onScopeHydrated?: (scope: string) => void;
- /** Cache TTL in milliseconds, defaults to 24 hours. Applies to both tiers. */
+ /**
+ * Cache TTL in milliseconds, defaults to 7 days. Governs the localStorage
+ * tier only (small, frequently-changing shells like recents) β€” the IndexedDB
+ * tier never expires (stale-while-revalidate).
+ */
ttl?: number;
/** App version; entries from another version are ignored on load. */
version?: string;
@@ -110,7 +114,7 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
getScope = () => 'default',
idbPatterns = [],
localPatterns = [],
- ttl = 24 * 60 * 60 * 1000, // 24 hours
+ ttl = 7 * 24 * 60 * 60 * 1000, // 7 days
maxLocalEntries = 50,
version = '1.0.0',
onError = (error) => console.error('[SWR Cache]', error),
@@ -229,10 +233,15 @@ export function createCacheProvider(options: CacheProviderOptions = {}): ScopedS
const loadIdb = async (scope: string, epoch: number) => {
try {
const entries = await localDataCache.entriesByScope(scope);
- const now = Date.now();
- const valid = entries.filter(
- (e) => (e.version === undefined || e.version === version) && now - e.updatedAt <= ttl,
- );
+ // The IndexedDB tier holds read-heavy / write-light business entities
+ // (messages, topics, …): once written, a row rarely changes. We never drop
+ // these by age β€” a stale row hydrates for an instant first paint and SWR's
+ // revalidate-on-mount refreshes it in the background (stale-while-revalidate).
+ // Version is the only invalidator: a row must carry the *current* version,
+ // so legacy/unversioned rows (which the age check used to bound) are dropped
+ // and a version bump still evicts everyone. TTL governs the localStorage
+ // tier only (see `loadLocal`).
+ const valid = entries.filter((e) => e.version === version);
// Map may have changed scope while we awaited; only apply if still current.
if (cacheMapInstance && getScope() === scope && hydrationEpoch === epoch) {
cacheMapInstance.hydrate(valid.map((e) => [e.key, e.data]));
@@ -462,6 +471,8 @@ export const swrCacheProvider = (
idbPatterns: [...CACHE_TIERS.idb],
localPatterns: [...CACHE_TIERS.local],
onScopeHydrated,
- ttl: 12 * 60 * 60 * 1000, // 12 hours
+ // Governs the localStorage tier only (recents-style shells); the IndexedDB
+ // tier (messages, topics, …) never expires. 7 days is plenty for recents.
+ ttl: 7 * 24 * 60 * 60 * 1000, // 7 days
});
};
diff --git a/src/store/chat/slices/message/actions/publicApi.ts b/src/store/chat/slices/message/actions/publicApi.ts
index 9f1c18cc760..6fc2f7e5675 100644
--- a/src/store/chat/slices/message/actions/publicApi.ts
+++ b/src/store/chat/slices/message/actions/publicApi.ts
@@ -5,6 +5,7 @@ import isEqual from 'fast-deep-equal';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { type ChatStore } from '@/store/chat/store';
+import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
@@ -208,6 +209,9 @@ export class MessagePublicApiActionImpl {
await messageService.removeAllMessages();
// Clear messages directly since all messages are deleted
this.#get().replaceMessages([]);
+ // replaceMessages only clears the active topic's cache; every other topic's
+ // cached message list is now stale (and never expires) β€” wipe them all
+ void evictMessageCache(() => true);
};
copyMessage = async (id: string, content: string): Promise<void> => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 45c2098ed70..f42e9ae3c1f 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -16,6 +16,7 @@ import { chatService } from '@/services/chat';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { type ChatStore } from '@/store/chat';
+import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { useGlobalStore } from '@/store/global';
import { type StoreSetter } from '@/store/types';
@@ -850,6 +851,8 @@ export class ChatTopicActionImpl {
await topicService.removeTopicsByAgentId(activeAgentId);
await refreshTopic();
+ // drop every deleted topic's message cache (all belong to this agent)
+ void evictMessageCache((ctx) => ctx.agentId === activeAgentId);
// switch to default topic
switchTopic(null);
@@ -868,6 +871,9 @@ export class ChatTopicActionImpl {
}
await refreshTopic();
+ // drop the deleted topics' message caches
+ const removed = new Set(topicIds);
+ void evictMessageCache((ctx) => !!ctx.topicId && removed.has(ctx.topicId));
// switch to default topic
switchTopic(null);
@@ -878,6 +884,8 @@ export class ChatTopicActionImpl {
await topicService.removeAllTopic();
await refreshTopic();
+ // every topic is gone β€” wipe all cached message lists
+ void evictMessageCache(() => true);
};
removeTopic = async (id: string): Promise<void> => {
@@ -889,6 +897,8 @@ export class ChatTopicActionImpl {
await topicService.removeTopic(id);
this.#get().internal_dispatchTopic({ type: 'deleteTopic', id }, 'removeTopic');
await refreshTopic();
+ // drop the deleted topic's message cache so it doesn't orphan in IndexedDB
+ void evictMessageCache((ctx) => ctx.topicId === id);
// switch back to default topic
if (activeTopicId === id) switchTopic(null);
@@ -901,6 +911,9 @@ export class ChatTopicActionImpl {
await topicService.batchRemoveTopics(topicIds);
await refreshTopic();
+ // drop the deleted topics' message caches
+ const removed = new Set(topicIds);
+ void evictMessageCache((ctx) => !!ctx.topicId && removed.has(ctx.topicId));
// Switch to default topic
switchTopic(null);
@@ -919,6 +932,10 @@ export class ChatTopicActionImpl {
this.#get().internal_dispatchTopic({ type: 'deleteTopic', id }, 'batchMoveTopicsToAgent'),
);
await refreshTopic();
+ // the moved topics' message cache is keyed by the old agent β€” drop it so the
+ // next view under the target agent refetches instead of reading a stale key
+ const moved = new Set(topicIds);
+ void evictMessageCache((ctx) => !!ctx.topicId && moved.has(ctx.topicId));
// If the active topic was moved away, fall back to the default topic.
if (activeTopicId && topicIds.includes(activeTopicId)) switchTopic(null);
diff --git a/src/store/chat/utils/evictMessageCache.ts b/src/store/chat/utils/evictMessageCache.ts
new file mode 100644
index 00000000000..bd48dd1cf59
--- /dev/null
+++ b/src/store/chat/utils/evictMessageCache.ts
@@ -0,0 +1,38 @@
+import { type ConversationContext } from '@lobechat/types';
+
+import { mutate } from '@/libs/swr';
+import { messageKeys } from '@/libs/swr/keys';
+
+/**
+ * Evict persisted `message:list` cache entries whose conversation context
+ * matches `predicate`.
+ *
+ * The IndexedDB cache tier never expires (see `localStorageProvider`), so once a
+ * topic / agent is deleted its message cache would orphan in IndexedDB forever
+ * unless we drop it explicitly. Clears the cached value without revalidating β€”
+ * the conversation is gone, there is nothing left to refetch.
+ *
+ * Matches every `message:list` variant (any page-size / version / workspace-
+ * augmented key) sharing the same `ConversationContext`, mirroring the matcher
+ * used by `refreshMessages` / the write-through cache.
+ *
+ * @example
+ * // a single deleted topic
+ * void evictMessageCache((ctx) => ctx.topicId === topicId);
+ * // every topic under a deleted agent
+ * void evictMessageCache((ctx) => ctx.agentId === agentId);
+ * // wipe everything (delete-all)
+ * void evictMessageCache(() => true);
+ */
+export const evictMessageCache = (
+ predicate: (ctx: ConversationContext) => boolean,
+): Promise<unknown> =>
+ mutate(
+ (key) => {
+ if (!Array.isArray(key) || key[0] !== messageKeys.list.root) return false;
+ const ctx = key[1] as ConversationContext | undefined;
+ return !!ctx && predicate(ctx);
+ },
+ undefined,
+ { revalidate: false },
+ );
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index cf0e2019877..239bd629fc0 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -6,6 +6,7 @@ import { chatGroupService } from '@/services/chatGroup';
import { homeService } from '@/services/home';
import { sessionService } from '@/services/session';
import { getAgentStoreState } from '@/store/agent';
+import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { type HomeStore } from '@/store/home/store';
import { type StoreSetter } from '@/store/types';
import { type SessionGroupItemBase } from '@/types/session';
@@ -92,12 +93,17 @@ export class SidebarUIActionImpl {
removeAgent = async (agentId: string): Promise<void> => {
await agentService.removeAgent(agentId);
await this.#get().refreshAgentList();
+ // deleting an agent cascade-deletes its topics + messages on the server; drop
+ // their message cache too so it doesn't orphan in IndexedDB (never expires)
+ void evictMessageCache((ctx) => ctx.agentId === agentId);
};
removeAgentGroup = async (groupId: string): Promise<void> => {
// Delete the group
await chatGroupService.deleteGroup(groupId);
await this.#get().refreshAgentList();
+ // same cascade for a group's conversations β€” drop its cached message lists
+ void evictMessageCache((ctx) => ctx.groupId === groupId);
};
renameAgentGroup = async (
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index 3aaa35342b4..ce77c4f51e1 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -12,6 +12,7 @@ import { sessionKeys } from '@/libs/swr/keys';
import { chatGroupService } from '@/services/chatGroup';
import { sessionService } from '@/services/session';
import { getChatGroupStoreState } from '@/store/agentGroup';
+import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { type SessionStore } from '@/store/session';
import { type StoreSetter } from '@/store/types';
import { getUserStoreState, useUserStore } from '@/store/user';
@@ -139,9 +140,21 @@ export class SessionActionImpl {
await this.#get().internal_updateSession(id, { pinned });
};
+ /**
+ * @deprecated Legacy session-store delete path, kept only for the mobile
+ * session list (`(mobile)/.../SessionListContent/List/Item/Actions.tsx`).
+ * Desktop already deletes via `HomeStore.removeAgent`. New call sites must use
+ * `HomeStore.removeAgent` (agents) / `HomeStore.removeAgentGroup` (groups) β€”
+ * all three evict the message cache, so behaviour is equivalent apart from this
+ * path also switching to the inbox when the active session is removed. Remove
+ * once the mobile session list migrates to the agent store.
+ */
removeSession = async (sessionId: string): Promise<void> => {
await sessionService.removeSession(sessionId);
await this.#get().refreshSessions();
+ // deleting an agent cascade-deletes its topics + messages on the server; drop
+ // their message cache too so it doesn't orphan in IndexedDB (never expires)
+ void evictMessageCache((ctx) => ctx.agentId === sessionId);
// If the active session deleted, switch to the inbox session
if (sessionId === this.#get().activeId) {