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(message): stop double-storing transcripts in SWR and evict through the replica (#21116)

Arvin Xue4ca45355336
diff --git a/src/services/message/replica.test.ts b/src/services/message/replica.test.ts
new file mode 100644
index 00000000000..d5a22704bee
--- /dev/null
+++ b/src/services/message/replica.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { cacheScope, isReplicaSyncKey } from '@/libs/replica';
+
+import { conversationMessagesKey, conversationMessagesResource } from './replica';
+
+const syncKeyOf = conversationMessagesResource.syncKey!;
+
+describe('conversationMessagesResource sync key', () => {
+ const topic = { agentId: 'agt-1', topicId: 'tpc-1' };
+
+ it('is one sync per conversation, whatever the fetch-only options', () => {
+ // ChatList mounts with `syncInterventions`, a share / portal view of the
+ // same conversation without it: both must share one read.
+ expect(syncKeyOf({ ...topic, syncInterventions: true })).toEqual(syncKeyOf(topic));
+ expect(syncKeyOf({ ...topic, scope: 'main' })).toEqual(syncKeyOf(topic));
+ });
+
+ it('keeps conversations apart', () => {
+ expect(syncKeyOf(topic)).not.toEqual(syncKeyOf({ ...topic, topicId: 'tpc-2' }));
+ expect(syncKeyOf(topic)).not.toEqual(syncKeyOf({ ...topic, threadId: 'thd-1' }));
+ });
+
+ it('is a replica sync key of the entry, outside the SWR `message:` tier', () => {
+ const key = syncKeyOf({ ...topic, syncInterventions: true });
+
+ expect(key[0]).toBe('replica:sync');
+ expect(
+ isReplicaSyncKey(key, conversationMessagesResource.name, {
+ key: conversationMessagesKey(topic),
+ scope: cacheScope.get(),
+ }),
+ ).toBe(true);
+ // The conversation stays last, for the predicate revalidation.
+ expect(key[5]).toMatchObject(topic);
+ expect(key[5]).not.toHaveProperty('syncInterventions');
+ });
+});
diff --git a/src/services/message/replica.ts b/src/services/message/replica.ts
index e9f88231922..b93caaa591d 100644
--- a/src/services/message/replica.ts
+++ b/src/services/message/replica.ts
@@ -2,18 +2,25 @@ import type { ConversationContext, UIChatMessage } from '@lobechat/types';
import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
import {
+ cacheScope,
defineReplica,
+ isReplicaSyncKey,
REPLICA_INDEX_KEY,
+ replicaKeys,
type ReplicaPagedData,
type ReplicaPageResult,
type ReplicaPagingConfig,
type ReplicaRow,
type ReplicaRowKey,
type ReplicaStorage,
+ replicaSWRDriver,
} from '@/libs/replica';
-import { normalizeMessageListQueryContext } from '@/libs/swr/keys';
+import {
+ type CanonicalMessageListContext,
+ normalizeMessageListQueryContext,
+} from '@/libs/swr/keys';
import type { MessageService } from '@/services/message';
-import { messageListKey, type MessageRoundCursor } from '@/services/message/cache';
+import type { MessageRoundCursor } from '@/services/message/cache';
import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -21,9 +28,9 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
export type ConversationMessagePage = ReplicaPagedData<UIChatMessage, MessageRoundCursor>;
/**
- * A transcript fetch: the head window is the plain row list (the same shape
- * every `message:list` consumer and cache write uses, so a fetch shared with
- * the chat store stays one shape); older pages carry their cursor.
+ * A transcript fetch: the head window is the plain row list (the shape the
+ * message list query and the chat store's head merge work with); older pages
+ * carry their cursor.
*/
export type ConversationMessageFetch =
UIChatMessage[] | ReplicaPageResult<UIChatMessage, MessageRoundCursor>;
@@ -76,6 +83,13 @@ export const conversationMessagesKey = (context: ConversationContext) =>
? `p:${JSON.stringify(normalizeMessageListQueryContext(context))}`
: `m:${JSON.stringify({ bucket: messageMapKey(context), threadId: context.threadId ?? null })}`;
+/**
+ * The canonical read context a persisted (`p:`) entry key was built from;
+ * `undefined` for memory-only (`m:`) keys, whose bucket does not name it.
+ */
+export const persistedContextOf = (key: string): CanonicalMessageListContext | undefined =>
+ key.startsWith('p:') ? JSON.parse(key.slice(2)) : undefined;
+
/**
* The chat store bucket (`messageMapKey`) an entry key renders into, and the
* thread its rows are parsed for. Every key is built by
@@ -102,22 +116,68 @@ const transcriptPaging: ReplicaPagingConfig<UIChatMessage, MessageRoundCursor> =
persist: { pages: 1 },
};
+const CONVERSATION_MESSAGES_NAME = 'conversationMessages';
+const CONVERSATION_MESSAGES_VERSION = 1;
+
+/**
+ * The conversation a transcript sync reads, without fetch-only options
+ * (`syncInterventions`): persisted entries by their canonical read context,
+ * memory-only ones by their context. Surfaces showing one conversation with
+ * different options then share one sync, as they share one entry.
+ */
+const syncContextOf = (params: ConversationMessageParams, key: string) => {
+ const { syncInterventions: _, ...context } = params;
+ return persistedContextOf(key) ?? context;
+};
+
export const conversationMessagesResource = defineReplica<
ConversationMessageParams,
ConversationMessagePage,
ConversationMessageFetch
>({
key: conversationMessagesKey,
- name: 'conversationMessages',
+ name: CONVERSATION_MESSAGES_NAME,
paging: transcriptPaging,
persistKey: (key) => key.startsWith('p:'),
storage: 'indexedDB',
- // Mutations, refreshes and evictions across the app revalidate the
- // conversation by its `message:list` key.
- syncKey: (params) => messageListKey(params),
- version: 1,
+ // A `replica:sync` key, so `slice.revalidate` and the predicate revalidation
+ // below match it; a `message:` key would hit the SWR persistence tier and
+ // store every transcript (shared and scoped ones included) a second time.
+ // Its params are the conversation, not the full sync params: one read per
+ // entry, so two responses never settle out of order into one transcript.
+ syncKey: (params) => {
+ const key = conversationMessagesKey(params);
+ return replicaKeys.sync(
+ CONVERSATION_MESSAGES_NAME,
+ CONVERSATION_MESSAGES_VERSION,
+ cacheScope.get(),
+ key,
+ syncContextOf(params, key),
+ );
+ },
+ version: CONVERSATION_MESSAGES_VERSION,
});
+/**
+ * Revalidate the transcript syncs of the active scope whose conversation
+ * matches `predicate` (every one when omitted) — the conversation-shaped
+ * matcher for code that cannot name one entry key (a whole topic across its
+ * threads, every transcript after a bulk change).
+ */
+export const revalidateConversationMessages = (
+ predicate?: (context: ConversationMessageParams) => boolean,
+) =>
+ replicaSWRDriver.revalidate((queryKey) => {
+ if (
+ !isReplicaSyncKey(queryKey, conversationMessagesResource.name, {
+ scope: conversationMessagesResource.scope.get(),
+ })
+ )
+ return false;
+ // `replicaKeys.sync` puts the sync's conversation last (see `syncContextOf`).
+ return !predicate || predicate((queryKey as unknown[])[5] as ConversationMessageParams);
+ });
+
/** Strip rows that must never be persisted (local-only placeholders with blob URLs). */
export const toPersistedTranscript = (data: ConversationMessagePage): ConversationMessagePage => {
if (!data.items.some(isLocalOnlyMessage)) return data;
diff --git a/src/services/work.test.ts b/src/services/work.test.ts
index e37bf0d55ad..1035c7d9a42 100644
--- a/src/services/work.test.ts
+++ b/src/services/work.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { isMessageListKey, workKeys } from '@/libs/swr/keys';
+import { cacheScope, replicaKeys } from '@/libs/replica';
+import { workKeys } from '@/libs/swr/keys';
const mutate = vi.fn();
@@ -18,6 +19,13 @@ vi.mock('@/libs/trpc/client', () => ({
},
}));
+/** A transcript sync key of `topicId` (the replica's default `replica:sync` shape). */
+const transcriptSync = (topicId: string) =>
+ replicaKeys.sync('conversationMessages', 1, cacheScope.get(), `p:${topicId}`, {
+ agentId: 'a1',
+ topicId,
+ });
+
// Imported after the mocks so the service binds to the stubbed `mutate`.
const { didToolMutateWorkView, workService } = await import('./work');
@@ -107,7 +115,8 @@ describe('workService.refreshConversation', () => {
const matchers = mutate.mock.calls
.map(([key]) => key)
.filter((key): key is (cacheKey: unknown) => boolean => typeof key === 'function');
- expect(matchers.some((matcher) => matcher(['message:list', { topicId: 't1' }, 1]))).toBe(true);
+ expect(matchers.some((matcher) => matcher(transcriptSync('t1')))).toBe(true);
+ expect(matchers.some((matcher) => matcher(transcriptSync('t2')))).toBe(false);
expect(matchers.some((matcher) => matcher(workKeys.versions('w1')))).toBe(true);
});
});
@@ -138,8 +147,7 @@ describe('workService.refreshConversationViews', () => {
const versionMatcher = mutate.mock.calls[1][0] as (key: unknown) => boolean;
// The version matcher must not select message-list or cross-topic gallery keys —
// Work summaries ride the message payload, and the gallery is out of scope here.
- expect(isMessageListKey(['message:list', { topicId: 't1' }, 1])).toBe(true);
- expect(versionMatcher(['message:list', { topicId: 't1' }, 1])).toBe(false);
+ expect(versionMatcher(transcriptSync('t1'))).toBe(false);
expect(versionMatcher(workKeys.workspace(null, 'all', null))).toBe(false);
});
diff --git a/src/services/work.ts b/src/services/work.ts
index 21c613b604f..e526e7a3d1f 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -15,8 +15,9 @@ import type {
} from '@lobechat/types';
import { mutate } from '@/libs/swr';
-import { isMessageListKey, matchDomain, workKeys } from '@/libs/swr/keys';
+import { matchDomain, workKeys } from '@/libs/swr/keys';
import { lambdaClient } from '@/libs/trpc/client';
+import { revalidateConversationMessages } from '@/services/message/replica';
/** One cursor page of the workspace-wide Work list (resource page 产物 gallery). */
export interface WorkSummaryPage {
@@ -127,7 +128,7 @@ class WorkService {
/**
* Invalidate everything a Work mutation can change for a conversation:
- * - the topic's `message:list` entries, since Work summaries (in-message chips
+ * - the topic's transcript syncs, since Work summaries (in-message chips
* and the sidebar summary view) ride the message payload
* - the sidebar history and expanded version views
*/
@@ -141,11 +142,11 @@ class WorkService {
/**
* Re-pull the message list for a topic so the Work summaries attached to its
- * message payload become fresh. `mutate` only refetches mounted keys, so this
- * is a no-op when the topic isn't the active conversation.
+ * message payload become fresh. Only mounted syncs refetch, so this is a
+ * no-op when the topic isn't the active conversation.
*/
refreshConversationMessages = async (topicId: string) => {
- await mutate((key) => isMessageListKey(key, (context) => context.topicId === topicId));
+ await revalidateConversationMessages((context) => context.topicId === topicId);
};
refreshAll = async () => {
@@ -176,7 +177,7 @@ class WorkService {
* Refresh only the sidebar's *lazy* Work caches for a conversation — the
* history list ({@link workKeys.conversation}) and any expanded version
* timelines ({@link workKeys.versions}). Deliberately narrower than
- * {@link refreshAll}: it never touches the `message:list` payload (Work
+ * {@link refreshAll}: it never touches the message payload (Work
* summaries ride the message list and are refreshed by the message fetch
* itself) nor the cross-topic workspace gallery (`work:workspace`).
*
@@ -200,11 +201,11 @@ class WorkService {
/**
* Broad invalidation for Work mutations without a single-topic scope (e.g.
* task deletion, which can orphan Works across topics into a "task deleted"
- * state). Refreshes every mounted `message:list` — since Work summaries ride
+ * state). Refreshes every mounted transcript sync — since Work summaries ride
* the message payload — plus the whole work domain for the sidebar caches.
*/
refreshAllConversations = async () => {
- await Promise.all([mutate((key) => isMessageListKey(key)), this.refreshAll()]);
+ await Promise.all([revalidateConversationMessages(), this.refreshAll()]);
};
refreshVersions = async (workId?: string | null) => {
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index 767e5bb7713..b8acf71b04c 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -11,7 +11,6 @@ import { messageService } from '@/services/message';
import {
clearMessageListClientCacheState,
isMessageListServerVerified,
- messageListKey,
runMessageListQuery,
} from '@/services/message/cache';
import { conversationMessagesKey, conversationMessagesResource } from '@/services/message/replica';
@@ -20,6 +19,7 @@ import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useChatStore } from '../../store';
+import { transcriptSyncKey } from './actions/testUtils';
// Mock @/libs/swr mutate
vi.mock('@lobehub/ui', async (importOriginal) => ({
@@ -777,7 +777,7 @@ describe('chatMessage actions', () => {
// 在每个测试用例开始前恢复到实际的 SWR 实现
vi.resetAllMocks();
});
- it('should refresh messages by invalidating message:list for the active agent+topic', async () => {
+ it('should refresh messages by revalidating the transcript syncs of the active agent+topic', async () => {
useChatStore.setState({ refreshMessages: realRefreshMessages });
const { result } = renderHook(() => useChatStore());
@@ -793,17 +793,15 @@ describe('chatMessage actions', () => {
expect(isMessageListServerVerified(context)).toBe(false);
- // refreshMessages now mutates with a single matcher targeting the
- // accurate `message:list` key for this agent+topic.
expect(mutate).toHaveBeenCalledTimes(1);
const matcher = (mutate as any).mock.calls[0][0];
- expect(typeof matcher).toBe('function');
- expect(matcher(messageListKey(context))).toBe(true);
- // other domains / other topics are not matched
- expect(matcher(['topic:list', 'container', {}])).toBe(false);
- expect(matcher(['message:list', { agentId: activeAgentId, topicId: 'other' }, 1])).toBe(
+ expect(matcher(transcriptSyncKey(context))).toBe(true);
+ expect(matcher(transcriptSyncKey({ ...context, threadId: 'thread-id' }))).toBe(true);
+ // other topics and the old `message:list` key are not matched
+ expect(matcher(['message:list', { ...context, groupId: null, threadId: null }, 2])).toBe(
false,
);
+ expect(matcher(transcriptSyncKey({ agentId: activeAgentId, topicId: 'other' }))).toBe(false);
});
it('should handle errors during refreshing messages', async () => {
useChatStore.setState({ refreshMessages: realRefreshMessages });
@@ -849,7 +847,9 @@ describe('chatMessage actions', () => {
});
expect(mutate).toHaveBeenCalledTimes(1);
- expect(mutate).toHaveBeenCalledWith(messageListKey(context));
+ const matcher = (mutate as any).mock.calls[0][0];
+ expect(matcher(transcriptSyncKey(context))).toBe(true);
+ expect(matcher(transcriptSyncKey({ ...context, threadId: 'other' }))).toBe(false);
});
});
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 80cc8e22cec..2cf1acf8a86 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -7,8 +7,8 @@ import { isMessageListKey } from '@/libs/swr/keys';
import {
invalidateMessageListClientState,
isMessageListServerVerified,
- messageListKey,
} from '@/services/message/cache';
+import { revalidateConversationMessages } from '@/services/message/replica';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { type ChatStore } from '@/store/chat/store';
import {
@@ -59,7 +59,8 @@ export class MessageQueryActionImpl {
// will be shared by the coordinator when the hook mounts.
if (isMessageListServerVerified({ agentId, groupId, threadId, topicId })) return;
- await mutate(messageListKey({ agentId, groupId, threadId, topicId }));
+ const transcript = getMessageTranscript(this.#set, this.#get);
+ await transcript.slice.revalidate(transcript.keyOf({ agentId, groupId, threadId, topicId }));
};
refreshMessages = async (context?: Partial<ConversationContext>): Promise<void> => {
@@ -67,17 +68,35 @@ export class MessageQueryActionImpl {
const topicId = context?.topicId !== undefined ? context.topicId : this.#get().activeTopicId;
// A force refresh owns both invalidation layers. Do this synchronously
- // before SWR mutate so an inactive key with no subscriber still loses its
- // verification window and any older in-flight generation.
+ // before the revalidation so an inactive entry with no subscriber still
+ // loses its verification window and any older in-flight generation.
invalidateMessageListClientState((ctx) => ctx.agentId === agentId && ctx.topicId === topicId);
- // Invalidate every `message:list` entry for this agent+topic (any scope /
- // thread / page-size variant).
- await mutate((key) =>
- isMessageListKey(key, (ctx) => ctx.agentId === agentId && ctx.topicId === topicId),
+ // Revalidate every transcript sync of this agent+topic (any scope / thread
+ // / share variant).
+ await revalidateConversationMessages(
+ (ctx) => ctx.agentId === agentId && ctx.topicId === topicId,
);
};
+ /**
+ * Drop the transcripts of deleted conversations from memory and storage
+ * (every one when `predicate` is omitted). Nothing is refetched: the
+ * conversation is gone.
+ *
+ * Installs upgraded from before the replica still hold `message:list` rows
+ * in the SWR IndexedDB tier, which never expires them; those are purged too
+ * until the SWR persistence layer is removed.
+ */
+ evictConversationMessages = async (
+ predicate?: (context: ConversationContext) => boolean,
+ ): Promise<void> => {
+ await Promise.all([
+ getMessageTranscript(this.#set, this.#get).evict(predicate),
+ mutate((key) => isMessageListKey(key, predicate), undefined, { revalidate: false }),
+ ]);
+ };
+
prefetchMessages = async (context: ConversationContext): Promise<void> => {
if (!context.agentId || !context.topicId) return;
// A client-minted topic with no server row yet (first-send window) would
diff --git a/src/store/chat/slices/message/actions/testUtils.ts b/src/store/chat/slices/message/actions/testUtils.ts
index 0549ab04759..1c49e44b136 100644
--- a/src/store/chat/slices/message/actions/testUtils.ts
+++ b/src/store/chat/slices/message/actions/testUtils.ts
@@ -1,7 +1,8 @@
import type { ConversationContext, UIChatMessage } from '@lobechat/types';
import { renderHook } from '@testing-library/react';
-import { createReplicaState } from '@/libs/replica';
+import { cacheScope, createReplicaState, replicaKeys } from '@/libs/replica';
+import { conversationMessagesKey, conversationMessagesResource } from '@/services/message/replica';
import { useChatStore } from '@/store/chat';
import { type ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -29,3 +30,13 @@ export const rowsOf = (context: ConversationContext) =>
/** `useFetchMessages` is a hook: run it inside a component. */
export const syncMessages = (...args: Parameters<ChatStore['useFetchMessages']>) =>
renderHook(() => useChatStore.getState().useFetchMessages(...args)).result.current;
+
+/** The `replica:sync` query key a mounted transcript sync of `context` runs under. */
+export const transcriptSyncKey = (context: ConversationContext) =>
+ replicaKeys.sync(
+ conversationMessagesResource.name,
+ conversationMessagesResource.version,
+ cacheScope.get(),
+ conversationMessagesKey(context),
+ context,
+ );
diff --git a/src/store/chat/slices/message/actions/transcript.evict.test.ts b/src/store/chat/slices/message/actions/transcript.evict.test.ts
new file mode 100644
index 00000000000..10cc41d5d78
--- /dev/null
+++ b/src/store/chat/slices/message/actions/transcript.evict.test.ts
@@ -0,0 +1,152 @@
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import { act, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, readReplicaStoredKeys } from '@/libs/replica';
+import { mutate } from '@/libs/swr';
+import { messageListKey } from '@/services/message/cache';
+import { conversationMessagesKey, conversationMessagesResource } from '@/services/message/replica';
+import { topicService } from '@/services/topic';
+import { useChatStore } from '@/store/chat';
+import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
+
+import { resetTranscripts, rowsOf } from './testUtils';
+
+vi.mock('@/libs/swr', async (importOriginal) => {
+ const actual: Record<string, any> = await importOriginal();
+ return { ...actual, mutate: vi.fn(actual.mutate) };
+});
+
+vi.mock('@/services/topic', async (importOriginal) => {
+ const actual: Record<string, any> = await importOriginal();
+ return {
+ ...actual,
+ topicService: { ...actual.topicService, removeTopic: vi.fn().mockResolvedValue(undefined) },
+ };
+});
+
+// Fresh ids per test: the replica engine keeps per-key removal state for the
+// session, which a real reload (unlike `reload` here) starts over.
+let run = 0;
+let topicA: ConversationContext;
+let topicB: ConversationContext;
+let otherAgent: ConversationContext;
+
+const row = (id: string) =>
+ ({ content: id, createdAt: 1, id, role: 'user', updatedAt: 1 }) as UIChatMessage;
+
+/** The transcript row the replica stored for a conversation (`undefined` = none). */
+const storedRow = (context: ConversationContext) =>
+ conversationMessagesResource.storage!.get({
+ queryKey: conversationMessagesKey(context),
+ scope: cacheScope.get(),
+ });
+
+/** Persist a settled transcript, as a finished conversation leaves it. */
+const persist = async (context: ConversationContext) => {
+ useChatStore.getState().replaceMessages([row(`${context.topicId}-msg`)], { context });
+ await waitFor(async () => expect(await storedRow(context)).toBeDefined());
+};
+
+/** A later session: memory starts empty, only the persisted rows remain. */
+const reload = () => resetTranscripts();
+
+describe('transcript eviction', () => {
+ beforeEach(async () => {
+ run += 1;
+ topicA = { agentId: `evict-agent-${run}`, topicId: `evict-topic-a-${run}` };
+ topicB = { agentId: `evict-agent-${run}`, topicId: `evict-topic-b-${run}` };
+ otherAgent = { agentId: `evict-other-agent-${run}`, topicId: `evict-topic-c-${run}` };
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ resetTranscripts();
+ await useChatStore.getState().evictConversationMessages();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('drops a deleted topic from memory and from the replica storage', async () => {
+ await persist(topicA);
+ await persist(topicB);
+
+ await act(() => evictMessageCache((ctx) => ctx.topicId === topicA.topicId));
+
+ expect(rowsOf(topicA)).toBeUndefined();
+ await waitFor(async () => expect(await storedRow(topicA)).toBeUndefined());
+ expect(await storedRow(topicB)).toBeDefined();
+ expect(rowsOf(topicB)).toBeDefined();
+ });
+
+ it('reaches rows only an earlier session persisted, so they never hydrate again', async () => {
+ await persist(topicA);
+ await persist(otherAgent);
+ reload();
+
+ await act(() => evictMessageCache((ctx) => ctx.agentId === topicA.agentId));
+
+ await waitFor(async () => expect(await storedRow(topicA)).toBeUndefined());
+ expect(await readReplicaStoredKeys(conversationMessagesResource)).toEqual([
+ conversationMessagesKey(otherAgent),
+ ]);
+ expect(await useChatStore.getState().preHydrateMessages(topicA)).toBe(false);
+ expect(rowsOf(topicA)).toBeUndefined();
+ expect(await useChatStore.getState().preHydrateMessages(otherAgent)).toBe(true);
+ expect(rowsOf(otherAgent)).toEqual([row(`${otherAgent.topicId}-msg`)]);
+ });
+
+ it('wipes every persisted transcript without a predicate', async () => {
+ await persist(topicA);
+ await persist(otherAgent);
+ reload();
+
+ await act(() => evictMessageCache());
+
+ expect(await storedRow(topicA)).toBeUndefined();
+ expect(await storedRow(otherAgent)).toBeUndefined();
+ expect(await readReplicaStoredKeys(conversationMessagesResource)).toEqual([]);
+ });
+
+ it('evicts the transcript of a topic removed from the chat store', async () => {
+ await persist(topicA);
+ await persist(topicB);
+ reload();
+ useChatStore.setState({
+ activeAgentId: topicA.agentId,
+ activeTopicId: undefined,
+ refreshTopic: vi.fn().mockResolvedValue(undefined),
+ });
+
+ await act(() => useChatStore.getState().removeTopic(topicA.topicId!));
+
+ expect(topicService.removeTopic).toHaveBeenCalledWith(topicA.topicId, undefined);
+ await waitFor(async () => expect(await storedRow(topicA)).toBeUndefined());
+ expect(await storedRow(topicB)).toBeDefined();
+ });
+
+ it('purges the legacy SWR `message:list` rows of deleted conversations too', async () => {
+ vi.mocked(mutate).mockClear();
+
+ await act(() => evictMessageCache((ctx) => ctx.topicId === topicA.topicId));
+
+ const [filter, data, options] = vi.mocked(mutate).mock.calls[0];
+ expect(typeof filter).toBe('function');
+ expect(data).toBeUndefined();
+ expect(options).toEqual({ revalidate: false });
+ const matches = filter as (key: unknown) => boolean;
+ expect(matches(messageListKey(topicA))).toBe(true);
+ expect(matches(messageListKey({ ...topicA, threadId: 'thd-1' }))).toBe(true);
+ expect(matches(messageListKey(topicB))).toBe(false);
+ });
+
+ it('purges every legacy SWR `message:list` row without a predicate', async () => {
+ vi.mocked(mutate).mockClear();
+
+ await act(() => evictMessageCache());
+
+ const matches = vi.mocked(mutate).mock.calls[0][0] as (key: unknown) => boolean;
+ expect(matches(messageListKey(topicA))).toBe(true);
+ expect(matches(messageListKey(otherAgent))).toBe(true);
+ expect(matches(['topic:list', 'x', {}])).toBe(false);
+ });
+});
diff --git a/src/store/chat/slices/message/actions/transcript.sync.test.ts b/src/store/chat/slices/message/actions/transcript.sync.test.ts
index a2676496eaa..c0e7af78292 100644
--- a/src/store/chat/slices/message/actions/transcript.sync.test.ts
+++ b/src/store/chat/slices/message/actions/transcript.sync.test.ts
@@ -1,14 +1,17 @@
import type { UIChatMessage } from '@lobechat/types';
import { act, waitFor } from '@testing-library/react';
+import { unstable_serialize } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useClientDataSWR } from '@/libs/swr';
+import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';
import { messageService } from '@/services/message';
import {
clearMessageListClientCacheState,
MESSAGE_LIST_VERIFICATION_INTERVAL,
runMessageListQuery,
} from '@/services/message/cache';
+import { conversationMessagesKey } from '@/services/message/replica';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
@@ -53,7 +56,7 @@ const messageSyncKeys = () =>
vi
.mocked(useClientDataSWR)
.mock.calls.map(([key]) => key as any[] | null)
- .filter((key) => key?.[0] === 'message:list');
+ .filter((key) => key?.[0] === 'replica:sync' && key[1] === 'conversationMessages');
const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };
@@ -289,23 +292,29 @@ describe('useFetchMessages', () => {
expect(messageService.getMessages).not.toHaveBeenCalled();
});
- it('keys the sync by the canonical read context', () => {
+ it('keys the sync by its entry, outside the SWR persistence tier', () => {
// The SWR mock runs the fetcher; an unmocked list read rejects after the test.
vi.mocked(messageService.getMessages).mockResolvedValue([]);
+ const shared = { ...context, topicShareId: 'share-1' };
syncMessages({ ...context, threadId: 'thread-1' });
syncMessages({ ...context, threadId: 'thread-2' });
+ syncMessages(shared);
- const [first, second] = messageSyncKeys();
+ const keys = messageSyncKeys();
+ expect(keys).toHaveLength(3);
+ const [first, second, third] = keys;
expect(first).not.toEqual(second);
- expect(first![0]).toBe('message:list');
- expect(first![1]).toEqual({
- agentId: 'test-session',
- groupId: null,
- threadId: 'thread-1',
- topicId: 'test-topic',
- });
- expect((second as any[])[1].threadId).toBe('thread-2');
+ expect(first![4]).toBe(conversationMessagesKey({ ...context, threadId: 'thread-1' }));
+ expect(second![4]).toBe(conversationMessagesKey({ ...context, threadId: 'thread-2' }));
+ expect(third![4]).toBe(conversationMessagesKey(shared));
+ // The replica persists transcripts itself; a key the SWR cache provider
+ // persists would store each one (memory-only shares too) a second time.
+ const persistedPatterns = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];
+ for (const key of keys) {
+ const serialized = unstable_serialize(key);
+ expect(persistedPatterns.filter((pattern) => serialized.includes(pattern))).toEqual([]);
+ }
});
it('skips switch-time revalidation after a successful server verification', async () => {
diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.ts
index 9b4167e8887..855593bb23a 100644
--- a/src/store/chat/slices/message/transcript/index.ts
+++ b/src/store/chat/slices/message/transcript/index.ts
@@ -2,7 +2,7 @@ import { type ChatTopic, type ConversationContext, type UIChatMessage } from '@l
import debug from 'debug';
import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';
-import { createReplicaSlice } from '@/libs/replica';
+import { createReplicaSlice, readReplicaStoredKeys } from '@/libs/replica';
import { messageService } from '@/services/message';
import {
getMessageListCacheIdentity,
@@ -15,6 +15,7 @@ import {
type ConversationMessageParams,
conversationMessagesKey,
conversationMessagesResource,
+ persistedContextOf,
toPersistedTranscript,
transcriptOf,
} from '@/services/message/replica';
@@ -240,8 +241,37 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto
if (lens.get(get(), key)) slice.persist(key);
};
+ /**
+ * Drop the transcripts of conversations that no longer exist (a deleted
+ * topic, agent or group) from memory and from storage, so their rows never
+ * hydrate again. Without `predicate` every transcript of the active scope
+ * goes. Persisted rows an earlier session wrote are reached through the
+ * replica's stored-key index. Memory-only (`m:`) entries do not survive a
+ * reload, and their keys do not name the conversation, so they are left to
+ * the session.
+ */
+ const evict = async (predicate?: (context: ConversationContext) => boolean): Promise<void> => {
+ if (!predicate) {
+ await slice.clear();
+ return;
+ }
+ const matches = (key: string) => {
+ const context = persistedContextOf(key);
+ return !!context && predicate(context as ConversationContext);
+ };
+ const scope = conversationMessagesResource.scope.get();
+ const loaded = new Set(lens.keys!(get()));
+ for (const key of loaded) if (matches(key)) slice.remove(key);
+
+ const persisted = await readReplicaStoredKeys(conversationMessagesResource);
+ // `remove` resolves against the active scope; another identity's rows are not ours.
+ if (conversationMessagesResource.scope.get() !== scope) return;
+ for (const key of persisted) if (!loaded.has(key) && matches(key)) slice.remove(key);
+ };
+
return {
commit,
+ evict,
headResolutions,
keyOf,
pendingInterventions,
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 9721ffa39ac..7fca269bd73 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -42,7 +42,6 @@ import { topicService } from '@/services/topic';
import { getAiInfraStoreState } from '@/store/aiInfra';
import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';
import { type ChatStore } from '@/store/chat';
-import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
import { snapshotAgentModel, snapshotAgentReasoning } from '@/store/chat/utils/snapshotAgentModel';
import { topicMapKey, type TopicMapScope } from '@/store/chat/utils/topicMapKey';
import {
@@ -1675,7 +1674,7 @@ export class ChatTopicActionImpl {
this.#removeTopicDetails((topic) => topic.sessionId === activeAgentId);
await refreshTopic();
// drop every deleted topic's message cache (all belong to this agent)
- void evictMessageCache((ctx) => ctx.agentId === activeAgentId);
+ void this.#get().evictConversationMessages((ctx) => ctx.agentId === activeAgentId);
// switch to default topic
switchTopic(null);
@@ -1693,7 +1692,7 @@ export class ChatTopicActionImpl {
this.#removeTopicDetails(() => true);
await refreshTopic();
// drop every deleted topic's message cache (all belong to this group)
- void evictMessageCache((ctx) => ctx.groupId === groupId);
+ void this.#get().evictConversationMessages((ctx) => ctx.groupId === groupId);
// switch to default topic
switchTopic(null);
@@ -1705,8 +1704,8 @@ export class ChatTopicActionImpl {
await topicService.removeAllTopic();
this.#removeTopicDetails(() => true);
await refreshTopic();
- // every topic is gone — wipe all cached message lists
- void evictMessageCache(() => true);
+ // every topic is gone — wipe every persisted transcript
+ void this.#get().evictConversationMessages();
};
removeTopic = async (id: string, removeFiles?: boolean): Promise<void> => {
@@ -1719,7 +1718,7 @@ export class ChatTopicActionImpl {
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);
+ void this.#get().evictConversationMessages((ctx) => ctx.topicId === id);
// switch back to default topic
if (activeTopicId === id) switchTopic(null);
@@ -1740,7 +1739,7 @@ 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));
+ void this.#get().evictConversationMessages((ctx) => !!ctx.topicId && removed.has(ctx.topicId));
// Switch to default topic
switchTopic(null);
@@ -1762,7 +1761,7 @@ export class ChatTopicActionImpl {
// 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));
+ void this.#get().evictConversationMessages((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
index e719356eb41..9f5a98efe9f 100644
--- a/src/store/chat/utils/evictMessageCache.ts
+++ b/src/store/chat/utils/evictMessageCache.ts
@@ -1,30 +1,24 @@
import { type ConversationContext } from '@lobechat/types';
-import { mutate } from '@/libs/swr';
-import { isMessageListKey } from '@/libs/swr/keys';
-
/**
- * Evict persisted `message:list` cache entries whose conversation context
- * matches `predicate`.
+ * Evict the persisted transcripts of conversations matching `predicate` (every
+ * one when omitted), for stores outside the chat store that delete them.
*
- * 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.
+ * Transcripts persist in the message replica's IndexedDB rows, which never
+ * expire, so once a topic / agent is deleted its transcript would orphan there
+ * (and hydrate again) unless it is dropped explicitly. Nothing is refetched —
+ * the conversation is gone. See `evictConversationMessages`.
*
- * 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.
+ * The chat store is loaded on demand: the session / home stores calling this
+ * must not pull the whole chat store graph in at module load.
*
* @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) => isMessageListKey(key, predicate), undefined, { revalidate: false });
+export const evictMessageCache = async (
+ predicate?: (ctx: ConversationContext) => boolean,
+): Promise<void> => {
+ const { getChatStoreState } = await import('@/store/chat/store');
+ await getChatStoreState().evictConversationMessages(predicate);
+};