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.

✨ feat(conversation): open topics local-first from a persisted transcript replica (#20449)

Arvin Xu62f7d4cec4a9
diff --git a/packages/replica/src/core/defineReplica.ts b/packages/replica/src/core/defineReplica.ts
index 7f6ef46cdd2..16069c06ec5 100644
--- a/packages/replica/src/core/defineReplica.ts
+++ b/packages/replica/src/core/defineReplica.ts
@@ -56,6 +56,13 @@ export interface DefineReplicaOptions<TParams, TData, TFetched = TData, TCursor
scope?: ReplicaScope;
/** Persisted copy of the replica. Omit for a memory-only replica (no first-frame paint). */
storage?: ReplicaStorage<TData> | ReplicaStorageFactory<TData>;
+ /**
+ * Query-cache key of the network sync, for a resource adopting an existing
+ * key that other code already revalidates by. Defaults to `replicaKeys.sync`.
+ * With a custom key, revalidate through that key β€” `slice.revalidate` only
+ * matches default keys.
+ */
+ syncKey?: (params: TParams) => readonly unknown[];
/** Bump to invalidate every persisted row written by older shapes. */
version: number;
}
@@ -82,6 +89,7 @@ export const defineReplica = <TParams, TData, TFetched = TData, TCursor = any>(
options.query ? stableQueryKey(options.query(params)) : undefined,
),
scope: options.scope ?? DEFAULT_SCOPE,
+ syncKey: options.syncKey,
storage,
version: options.version,
};
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index e47f4c46a4d..f56c9e64178 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -76,6 +76,17 @@ export interface ReplicaEngineOptions<TParams, TData, TFetched> {
merge?: (incoming: TFetched, confirmed: TData | undefined, params: TParams) => TData | undefined;
/** Where the engine reads and commits the view. */
port: ReplicaStorePort<TData>;
+ /**
+ * Reconcile a server response with the value currently shown before it is
+ * folded in β€” e.g. keep a row the client knows is newer, or ignore a
+ * response that raced a newer local state. Return `undefined` to drop the
+ * response entirely.
+ */
+ prepareHead?: (
+ incoming: TFetched,
+ current: TData | undefined,
+ params: TParams,
+ ) => TFetched | undefined;
/** Re-run the network sync of one entry (or all); wired by the fetch adapter. */
revalidate?: (key?: string) => Promise<unknown>;
/** Strip transient / client-only parts before persisting; `undefined` skips. */
@@ -278,8 +289,12 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return confirmed !== undefined && isEqual(next, confirmed) ? undefined : next;
};
- const replace = (params: TParams, incoming: TFetched, scope = resource.scope.get()) => {
+ const replace = (params: TParams, fetched: TFetched, scope = resource.scope.get()) => {
const key = resource.key(params);
+ const incoming = options.prepareHead
+ ? options.prepareHead(fetched, port.read(key), params)
+ : fetched;
+ if (incoming === undefined) return false;
const query = resource.query(params);
const entry = getSlot().entries[key];
// A different query (filters, sort) must not merge with loaded pages. A
diff --git a/packages/replica/src/core/paging.test.ts b/packages/replica/src/core/paging.test.ts
index eb201243486..74623c2a85c 100644
--- a/packages/replica/src/core/paging.test.ts
+++ b/packages/replica/src/core/paging.test.ts
@@ -453,6 +453,23 @@ describe('cursor / backward paging (message-like transcript)', () => {
expect(collapsed.nextCursor).toEqual({ createdAt: 7, id: 'm7' });
});
+ it('persists rows appended to the head after it was fetched', () => {
+ const head = applyHeadPage<Message, Cursor>(
+ undefined,
+ { items: range(1, 4), nextCursor: null },
+ { pageSize: 4 },
+ messages,
+ );
+ // A sent message and its reply land through a plain write, not a page.
+ const grown = { ...head, items: [...head.items, msg(5), msg(6)] };
+
+ expect(mids(toPersistedPage(grown, messages))).toEqual(['m1', 'm2', 'm3', 'm4', 'm5', 'm6']);
+ // With older pages loaded, only the head (and its growth) is kept.
+ const loaded = loadedTwoWindows();
+ const loadedGrown = { ...loaded, items: [...loaded.items, msg(11)] };
+ expect(mids(toPersistedPage(loadedGrown, messages))).toEqual(['m7', 'm8', 'm9', 'm10', 'm11']);
+ });
+
it('persists the newest window, capped by maxItems; a cut forgets the cursor', () => {
const persisted = toPersistedPage(loadedTwoWindows(), messages);
expect(mids(persisted)).toEqual(['m7', 'm8', 'm9', 'm10']);
diff --git a/packages/replica/src/core/paging.ts b/packages/replica/src/core/paging.ts
index cd48a04a3e9..5e0bd3e4103 100644
--- a/packages/replica/src/core/paging.ts
+++ b/packages/replica/src/core/paging.ts
@@ -465,7 +465,13 @@ export const toPersistedPage = <TItem, TCursor, TData extends ReplicaPagedData<T
const { server } = splitClientOnly(data.items, ctx);
const pageLimit = Math.max(1, config.persist?.pages ?? 1);
const maxItems = config.persist?.maxItems ?? Number.POSITIVE_INFINITY;
- const pages = data.pages?.length ? data.pages : [{ count: server.length, next: data.nextCursor }];
+ // The head page absorbs every row written since it was fetched (a sent
+ // message, a streamed reply): older pages keep their fetched size, so the
+ // head is whatever they do not account for.
+ const olderCount = (data.pages ?? []).slice(1).reduce((sum, page) => sum + page.count, 0);
+ const pages = data.pages?.length
+ ? [{ ...data.pages[0], count: Math.max(0, server.length - olderCount) }, ...data.pages.slice(1)]
+ : [{ count: server.length, next: data.nextCursor }];
let count = 0;
let keptPages = 0;
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
index e938fc13540..ef28ba8509d 100644
--- a/packages/replica/src/core/types.ts
+++ b/packages/replica/src/core/types.ts
@@ -93,5 +93,7 @@ export interface ReplicaResource<TParams, TData, TFetched = TData, TCursor = any
storage?: ReplicaStorage<TData>;
/** Row key in `storage` for these params (`key`, plus `?query` when set). */
storageKey: (params: TParams) => string;
+ /** Custom query-cache key of the network sync (see `DefineReplicaOptions.syncKey`). */
+ syncKey?: (params: TParams) => readonly unknown[];
version: number;
}
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
index 5284701ee40..b9ade6acc73 100644
--- a/packages/replica/src/zustand/createReplicaSlice.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -221,6 +221,37 @@ describe('createReplicaSlice', () => {
expect(store.getState().lists.all).toEqual(['b-1']);
});
+ it('syncs under a custom key when the resource adopts one', () => {
+ const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));
+ const resource = defineReplica<{ id: string }, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'customKeyed',
+ scope,
+ syncKey: ({ id }) => ['legacy:list', id],
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {
+ driver: { revalidate: vi.fn(), useQuery },
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+
+ renderHook(() => slice.useSync({ id: 'a' }));
+
+ expect(useQuery).toHaveBeenCalledWith(
+ ['legacy:list', 'a'],
+ expect.any(Function),
+ expect.any(Object),
+ );
+ });
+
it('does not let a slow hydration overwrite a faster server response', async () => {
const storage = createMemoryStorage();
storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index 32e3b193852..0f492194827 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -153,7 +153,8 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
const sync = driver.useQuery<TFetched>(
active && fetcher
- ? replicaKeys.sync(resource.name, resource.version, scope, key!, params)
+ ? (resource.syncKey?.(params!) ??
+ replicaKeys.sync(resource.name, resource.version, scope, key!, params))
: null,
() => fetcher!(params!, undefined),
{
diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.ts
index 4f78a244676..74b31998b82 100644
--- a/packages/replica/src/zustand/driver.ts
+++ b/packages/replica/src/zustand/driver.ts
@@ -5,10 +5,12 @@
export interface ReplicaSyncSchedule {
/** Collapse identical requests within this window (ms). */
dedupingInterval?: number;
- /** Poll every N ms while mounted (0 = off). */
- refreshInterval?: number;
+ /** Poll every N ms while mounted (0 = off); a function decides per tick from the latest data. */
+ refreshInterval?: number | ((latest: any) => number);
/** Keep polling while the page is hidden. */
refreshWhenHidden?: boolean;
+ /** Keep polling while the browser is offline. */
+ refreshWhenOffline?: boolean;
revalidateIfStale?: boolean;
revalidateOnFocus?: boolean;
revalidateOnReconnect?: boolean;
diff --git a/packages/replica/src/zustand/splitPagedLens.test.ts b/packages/replica/src/zustand/splitPagedLens.test.ts
index bfbee71f1cc..2653db4a1b9 100644
--- a/packages/replica/src/zustand/splitPagedLens.test.ts
+++ b/packages/replica/src/zustand/splitPagedLens.test.ts
@@ -120,6 +120,56 @@ describe('splitPagedLens', () => {
});
});
+describe('prepareHead', () => {
+ it('reconciles a head page with the shown rows, or drops it', () => {
+ const resource = definePagedReplica<{ topic: string }, Message, number>({
+ key: ({ topic }) => topic,
+ name: 'preparedTranscript',
+ paging: { direction: 'backward', getId: (m) => m.id, mode: 'cursor' },
+ scope,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ displayMap: {},
+ pagingMap: {},
+ replica: createReplicaState(),
+ rowsMap: {},
+ }));
+ let dropNext = false;
+ const slice = createReplicaSlice(resource, {
+ driver,
+ get: store.getState,
+ // Keep a locally newer row (higher createdAt) over the server's copy.
+ prepareHead: (page, current) => {
+ if (dropNext) return undefined;
+ const local = new Map(current?.items.map((m) => [m.id, m]));
+ return {
+ ...page,
+ items: page.items.map((m) => {
+ const mine = local.get(m.id);
+ return mine && mine.createdAt > m.createdAt ? mine : m;
+ }),
+ };
+ },
+ set: (partial) => store.setState(partial),
+ stateKey: 'replica',
+ view: splitPagedLens<TestState, Message, number>({
+ itemsField: 'rowsMap',
+ metaField: 'pagingMap',
+ }),
+ });
+
+ slice.replace({ topic: 't1' }, { items: [msg(1)], nextCursor: null });
+ slice.update('t1', (data) => data && { ...data, items: [{ createdAt: 9, id: 'm1' }] });
+ slice.replace({ topic: 't1' }, { items: [msg(1), msg(2)], nextCursor: null });
+ expect(store.getState().rowsMap.t1).toEqual([{ createdAt: 9, id: 'm1' }, msg(2)]);
+
+ dropNext = true;
+ expect(slice.replace({ topic: 't1' }, { items: [], nextCursor: null })).toBe(false);
+ expect(store.getState().rowsMap.t1).toHaveLength(2);
+ });
+});
+
describe('persistKey and persist()', () => {
it('never persists or hydrates a key the resource keeps in memory', async () => {
const { rows, slice } = setup();
diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsx
index ce63a02ddc4..bf4a93e1ce7 100644
--- a/src/features/Conversation/ConversationProvider.test.tsx
+++ b/src/features/Conversation/ConversationProvider.test.tsx
@@ -66,7 +66,8 @@ vi.mock('@/hooks/useFetchMemoryForTopic', () => ({ useFetchTopicMemories: vi.fn(
vi.mock('@/hooks/useFetchNotebookDocuments', () => ({ useFetchNotebookDocuments: vi.fn() }));
vi.mock('@/libs/swr', () => ({
- useClientDataSWRWithSync: () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: () => ({
data: undefined,
error: undefined,
isLoading: false,
@@ -92,9 +93,11 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/chat', () => ({
getChatStoreState: () => ({}),
- useChatStore: (
- selector: (state: { activeAgentId: string; creatingTopicIds: string[] }) => unknown,
- ) => selector({ activeAgentId: 'agt_old', creatingTopicIds: [] }),
+ useChatStore: Object.assign(
+ (selector: (state: { activeAgentId: string; creatingTopicIds: string[] }) => unknown) =>
+ selector({ activeAgentId: 'agt_old', creatingTopicIds: [] }),
+ { getState: () => ({}) },
+ ),
}));
vi.mock('@/store/chat/selectors', () => ({
diff --git a/src/features/Conversation/StoreUpdater.tsx b/src/features/Conversation/StoreUpdater.tsx
index 51d5f6fece3..595caf462b9 100644
--- a/src/features/Conversation/StoreUpdater.tsx
+++ b/src/features/Conversation/StoreUpdater.tsx
@@ -100,6 +100,9 @@ const StoreUpdater = memo<StoreUpdaterProps>(
// when calling onMessagesChange (otherwise writes to the old topic key)
storeApi.setState({
...createEphemeralResetState(),
+ // The store shows one conversation: the previous one's replica
+ // bookkeeping must not describe the next one's rows.
+ messageReplica: { entries: {}, scope: storeApi.getState().messageReplica.scope },
context,
dbMessages: messages ?? [],
displayMessages: [],
diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.ts
index 94691f617b0..d29634ce15e 100644
--- a/src/features/Conversation/store/initialState.ts
+++ b/src/features/Conversation/store/initialState.ts
@@ -92,6 +92,9 @@ export const createEphemeralResetState = (): Partial<State> => ({
heteroOverloadWaitOpIds: {},
inputMessage: '',
isLoadingEarlierMessages: false,
+ // The paging of the previous conversation's transcript must not describe
+ // the next one's rows.
+ messagePaging: undefined,
refreshingRowId: undefined,
isScrolling: false,
messageEditingIds: [],
diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.ts
index 0555b5a4635..4e398f20f40 100644
--- a/src/features/Conversation/store/selectors.test.ts
+++ b/src/features/Conversation/store/selectors.test.ts
@@ -38,6 +38,7 @@ const createMockState = (overrides: Partial<State> = {}): State => ({
displayMessages: [],
hooks: {},
isLoadingEarlierMessages: false,
+ messageReplica: { entries: {} } as State['messageReplica'],
messagesInit: false,
operationState: DEFAULT_OPERATION_STATE,
skipFetch: false,
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index a86a51587d3..7509143880e 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -1,14 +1,16 @@
import type { UIChatMessage } from '@lobechat/types';
-import { act, waitFor } from '@testing-library/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useClientDataSWRWithSync } from '@/libs/swr';
+import { cacheScope } from '@/libs/replica';
+import { useClientDataSWR } from '@/libs/swr';
import { messageService } from '@/services/message';
import {
clearMessageListClientCacheState,
MESSAGE_LIST_VERIFICATION_INTERVAL,
runMessageListQuery,
} from '@/services/message/cache';
+import { conversationMessagesResource } from '@/services/message/replica';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
@@ -44,20 +46,41 @@ vi.mock('@/services/message', () => {
};
});
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => undefined,
+ useActiveWorkspaceId: () => undefined,
+}));
+
// Mock SWR
vi.mock('@/libs/swr', () => ({
- useClientDataSWRWithSync: vi.fn((key, fetcher, options) => {
- // Simulate SWR behavior for testing
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn((key, fetcher, options) => {
+ // Simulate SWR behavior for testing: fetch once, report success
if (key) {
- fetcher?.().then((data: UIChatMessage[]) => {
- options?.onData?.(data);
+ fetcher?.().then((data: unknown) => {
+ options?.onSuccess?.(data);
});
}
- return { data: undefined, isLoading: true };
+ return { data: undefined, isValidating: true, mutate: vi.fn() };
}),
}));
+/** The transcript sync's SWR keys (the replica's hydration read is a separate query). */
+const messageSyncKeys = () =>
+ vi
+ .mocked(useClientDataSWR)
+ .mock.calls.map(([key]) => key as any[] | null)
+ .filter((key) => key?.[0] === 'message:list');
+
+/** `useFetchMessages` is a hook: run it inside a component. */
+const fetchMessagesOf =
+ (store: ReturnType<typeof createStore>) =>
+ (
+ ...args: Parameters<ReturnType<ReturnType<typeof createStore>['getState']>['useFetchMessages']>
+ ) =>
+ renderHook(() => store.getState().useFetchMessages(...args)).result.current;
+
// Create a test store
const createTestStore = () =>
createStore({
@@ -290,6 +313,30 @@ describe('DataSlice', () => {
expect(store.getState().isLoadingEarlierMessages).toBe(false);
});
+ it('hands the extended transcript to the host, so its next sync keeps the older rows', async () => {
+ const onMessagesChange = vi.fn();
+ const context = {
+ agentId: 'agent-earlier',
+ threadId: 'thread-earlier',
+ topicId: 'topic-earlier-host',
+ };
+ const store = createStore({ context });
+ store.setState({ onMessagesChange });
+ store.getState().replaceMessages(windowMessages, { skipOnMessagesChange: true });
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({ messages: earlierPage });
+
+ await store.getState().loadEarlierMessages();
+
+ expect(onMessagesChange).toHaveBeenCalledTimes(1);
+ expect(onMessagesChange.mock.calls[0][0].map((m: UIChatMessage) => m.id)).toEqual([
+ 'u1',
+ 'a1',
+ 'u2',
+ 'a2',
+ ]);
+ expect(onMessagesChange.mock.calls[0][1]).toEqual(context);
+ });
+
it('stops fetching once a page comes back empty (beginning reached)', async () => {
const store = createStore({
context: {
@@ -455,6 +502,154 @@ describe('DataSlice', () => {
});
});
+ describe('loadEarlierMessages on a round-cursor topic', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ clearMessageListClientCacheState();
+ });
+
+ const context = { agentId: 'agent-round', threadId: null, topicId: 'topic-round' };
+ const windowMessages: UIChatMessage[] = [
+ { id: 'u2', content: 'q2', role: 'user', createdAt: 1000, updatedAt: 1000 } as any,
+ ];
+ const windowCursor = { createdAt: '1970-01-01T00:00:01.000123Z', id: 'u2' };
+
+ it('waits for the window cursor instead of deriving a lossy one', async () => {
+ const store = createStore({ context });
+ store.getState().replaceMessages(windowMessages);
+
+ await store.getState().loadEarlierMessages();
+
+ expect(messageService.getEarlierMessages).not.toHaveBeenCalled();
+ });
+
+ it("pages from the window's lossless cursor and stops at the topic start", async () => {
+ await runMessageListQuery(context, async () => ({
+ messages: windowMessages,
+ olderCursor: windowCursor,
+ }));
+ const store = createStore({ context });
+ store.getState().replaceMessages(windowMessages);
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({
+ messages: [{ id: 'u1', content: 'q1', role: 'user', createdAt: 1, updatedAt: 1 } as any],
+ olderCursor: null,
+ });
+
+ await store.getState().loadEarlierMessages();
+ await store.getState().loadEarlierMessages();
+
+ expect(messageService.getEarlierMessages).toHaveBeenCalledTimes(1);
+ expect(messageService.getEarlierMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ topicId: 'topic-round' }),
+ windowCursor,
+ );
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['u1', 'u2']);
+ });
+
+ it('never fetches when the window already holds the topic start', async () => {
+ await runMessageListQuery(context, async () => ({
+ messages: windowMessages,
+ olderCursor: null,
+ }));
+ const store = createStore({ context });
+ store.getState().replaceMessages(windowMessages);
+
+ await store.getState().loadEarlierMessages();
+
+ expect(messageService.getEarlierMessages).not.toHaveBeenCalled();
+ });
+ });
+
+ it('echoes the committed extended transcript after head revalidation', async () => {
+ clearMessageListClientCacheState();
+ const context = { agentId: 'review-agent', topicId: 'review-topic', threadId: null };
+ const old = { id: 'old', role: 'user', content: 'older', createdAt: 1 } as UIChatMessage;
+ const head = { id: 'head', role: 'user', content: 'newest', createdAt: 2 } as UIChatMessage;
+ const cursor = { id: 'head', createdAt: '1970-01-01T00:00:00.002Z' };
+ await runMessageListQuery(context, async () => ({ messages: [head], olderCursor: cursor }));
+ const onMessagesChange = vi.fn();
+ const store = createStore({ context });
+ store.setState({ onMessagesChange });
+ store.getState().replaceMessages([head]);
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValueOnce({
+ messages: [old],
+ olderCursor: null,
+ });
+ await store.getState().loadEarlierMessages();
+ onMessagesChange.mockClear();
+ vi.mocked(messageService.getMessageListPage).mockResolvedValueOnce({
+ messages: [head],
+ olderCursor: cursor,
+ });
+ fetchMessagesOf(store)(context);
+ await waitFor(() =>
+ expect(onMessagesChange).toHaveBeenCalledWith([old, head], context, { source: 'fetch' }),
+ );
+ expect(store.getState().dbMessages).toEqual([old, head]);
+ });
+
+ it('resets paging after an unpaged replacement but keeps it for an unchanged host echo', () => {
+ const context = { agentId: 'replace-agent', topicId: 'replace-topic', threadId: null };
+ const store = createStore({ context });
+ const rows = ['older', 'head'].map((id, i) => ({
+ id,
+ role: 'user',
+ content: id,
+ createdAt: i,
+ })) as UIChatMessage[];
+ const paging = {
+ currentPage: 2,
+ pageSize: 1,
+ hasMore: true,
+ anchorId: 'head',
+ nextCursor: { id: 'older', createdAt: 'old' },
+ pages: [{ count: 1 }, { count: 1 }],
+ };
+ store.setState({ dbMessages: rows, messagePaging: paging });
+ store.getState().replaceMessages([...rows], { skipOnMessagesChange: true });
+ expect(store.getState().messagePaging).toEqual(paging);
+ store.getState().replaceMessages([rows[1]]);
+ expect(store.getState().messagePaging).toEqual({ currentPage: 0, pageSize: 1, hasMore: true });
+ });
+
+ describe('transcript persistence', () => {
+ it('keeps streamed writes in memory and persists once the run settles', async () => {
+ let running = true;
+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockImplementation(
+ () => () => running,
+ );
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const storageSet = vi
+ .spyOn(conversationMessagesResource.storage!, 'set')
+ .mockResolvedValue(undefined);
+ const store = createStore({
+ context: { agentId: 'agent-persist', threadId: null, topicId: 'topic-persist' },
+ });
+
+ for (const id of ['m1', 'm2']) {
+ store.getState().internal_dispatchMessage({
+ id,
+ type: 'createMessage',
+ value: { content: id, role: 'assistant' } as any,
+ });
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(storageSet.mock.calls.some(([, row]) => Array.isArray((row.data as any)?.items))).toBe(
+ false,
+ );
+
+ running = false;
+ store.getState().replaceMessages(store.getState().dbMessages);
+
+ // The engine also tracks its stored keys in an index row.
+ const transcriptWrites = () =>
+ storageSet.mock.calls.filter(([, row]) => Array.isArray((row.data as any)?.items));
+ await waitFor(() => expect(transcriptWrites()).toHaveLength(1));
+ const [[, row]] = transcriptWrites();
+ expect((row.data as any).items.map((m: UIChatMessage) => m.id)).toEqual(['m1', 'm2']);
+ });
+ });
+
describe('replaceMessages', () => {
it('should replace all messages with new data', () => {
const store = createTestStore();
@@ -861,14 +1056,14 @@ describe('DataSlice', () => {
{ ...streaming, content: '...' },
]);
- store.getState().useFetchMessages(context, { refreshInterval: 2000 });
+ fetchMessagesOf(store)(context, { refreshInterval: 2000 });
await waitFor(() => expect(store.getState().dbMessages[0]).toEqual(answered));
expect(store.getState().dbMessages[1]).toBe(streaming);
expect(onMessagesChange).toHaveBeenCalledWith([answered, streaming], context, {
source: 'fetch',
});
- expect(useClientDataSWRWithSync).toHaveBeenCalledWith(
+ expect(useClientDataSWR).toHaveBeenCalledWith(
expect.any(Array),
expect.any(Function),
expect.objectContaining({
@@ -901,13 +1096,13 @@ describe('DataSlice', () => {
const store = createStore({ context });
store.setState({ dbMessages: [pending] });
vi.mocked(messageService.getMessages).mockResolvedValue([answered]);
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
await waitFor(() => expect(store.getState().dbMessages).toEqual([answered]));
clearMessageListClientCacheState();
const rollback = { ...pending, updatedAt: 1 };
vi.mocked(messageService.getMessages).mockResolvedValue([rollback]);
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
await act(async () => {
await Promise.resolve();
});
@@ -932,7 +1127,7 @@ describe('DataSlice', () => {
});
// Call useFetchMessages - this triggers the SWR mock
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: 'test-thread',
@@ -964,7 +1159,7 @@ describe('DataSlice', () => {
const onMessagesChange = vi.fn();
store.setState({ onMessagesChange });
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
await waitFor(() => {
expect(onMessagesChange).toHaveBeenCalledWith(mockMessages, context, { source: 'fetch' });
@@ -993,7 +1188,7 @@ describe('DataSlice', () => {
const store = createStore({ context });
store.setState({ messagesInit: false });
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
await waitFor(() => {
expect(store.getState().messagesInit).toBe(true);
@@ -1031,7 +1226,7 @@ describe('DataSlice', () => {
const store = createStore({ context });
store.setState({ dbMessages: [...fetched, streamed], messagesInit: true });
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
await waitFor(() => {
expect(store.getState().dbMessages.map((m) => m.id)).toContain('msg-member-tool');
@@ -1051,7 +1246,7 @@ describe('DataSlice', () => {
const loaded = [{ ...fetched[0], content: 'local' }];
store.setState({ dbMessages: loaded, messagesInit: true });
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
await waitFor(() => {
expect(messageService.getMessages).toHaveBeenCalled();
@@ -1085,7 +1280,7 @@ describe('DataSlice', () => {
const onMessagesChange = vi.fn();
store.setState({ onMessagesChange });
- store.getState().useFetchMessages(oldContext);
+ fetchMessagesOf(store)(oldContext);
store.setState({
context: currentContext,
dbMessages: currentMessages,
@@ -1127,7 +1322,7 @@ describe('DataSlice', () => {
context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1148,14 +1343,14 @@ describe('DataSlice', () => {
context: { agentId: '', topicId: null, threadId: null },
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: '',
topicId: null,
threadId: null,
});
// SWR should be called with null key (disabled)
- expect(vi.mocked(useClientDataSWRWithSync)).toHaveBeenCalledWith(
+ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(
null,
expect.any(Function),
expect.any(Object),
@@ -1167,7 +1362,7 @@ describe('DataSlice', () => {
context: { agentId: 'test-session', topicId: null, threadId: null },
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: null,
threadId: null,
@@ -1175,7 +1370,7 @@ describe('DataSlice', () => {
// SWR should be called with null key when topicId is null
// This prevents fetching empty data that would overwrite local optimistic updates
- expect(vi.mocked(useClientDataSWRWithSync)).toHaveBeenCalledWith(
+ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(
null,
expect.any(Function),
expect.any(Object),
@@ -1190,14 +1385,14 @@ describe('DataSlice', () => {
context: { agentId: 'test-session', topicId: null, threadId: null },
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: undefined as any,
threadId: null,
});
// SWR should be called with null key when topicId is undefined
- expect(vi.mocked(useClientDataSWRWithSync)).toHaveBeenCalledWith(
+ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(
null,
expect.any(Function),
expect.any(Object),
@@ -1209,25 +1404,25 @@ describe('DataSlice', () => {
context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-1' },
});
- store1.getState().useFetchMessages({
+ fetchMessagesOf(store1)({
agentId: 'session-1',
topicId: 'topic-1',
threadId: 'thread-1',
});
- const firstCallKey = vi.mocked(useClientDataSWRWithSync).mock.calls[0][0];
+ const firstCallKey = messageSyncKeys()[0];
const store2 = createStore({
context: { agentId: 'session-1', topicId: 'topic-1', threadId: 'thread-2' },
});
- store2.getState().useFetchMessages({
+ fetchMessagesOf(store2)({
agentId: 'session-1',
topicId: 'topic-1',
threadId: 'thread-2',
});
- const secondCallKey = vi.mocked(useClientDataSWRWithSync).mock.calls[1][0];
+ const secondCallKey = messageSyncKeys()[1];
// Keys should be different because threadIds are different
expect(firstCallKey).not.toEqual(secondCallKey);
@@ -1240,13 +1435,13 @@ describe('DataSlice', () => {
context: { agentId: 'test-session', topicId: 'test-topic', threadId: 'test-thread' },
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: 'test-thread',
});
- const swrKey = vi.mocked(useClientDataSWRWithSync).mock.calls[0][0] as any[];
+ const swrKey = messageSyncKeys()[0]!;
// Key should be an array with prefix and context object
expect(Array.isArray(swrKey)).toBe(true);
@@ -1269,9 +1464,9 @@ describe('DataSlice', () => {
vi.mocked(messageService.getMessages).mockResolvedValue([]);
const store = createStore({ context });
- store.getState().useFetchMessages(context);
+ fetchMessagesOf(store)(context);
- expect(vi.mocked(useClientDataSWRWithSync)).toHaveBeenCalledWith(
+ expect(vi.mocked(useClientDataSWR)).toHaveBeenCalledWith(
expect.any(Array),
expect.any(Function),
expect.objectContaining({
@@ -1315,7 +1510,7 @@ describe('DataSlice', () => {
});
// Call useFetchMessages with groupId - this triggers the SWR mock
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'supervisor-agent',
topicId: 'test-topic',
threadId: null,
@@ -1350,7 +1545,7 @@ describe('DataSlice', () => {
context: { agentId: 'test-session', topicId: 'test-topic', threadId: null },
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1400,7 +1595,7 @@ describe('DataSlice', () => {
],
} as any);
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1442,7 +1637,7 @@ describe('DataSlice', () => {
},
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1483,7 +1678,7 @@ describe('DataSlice', () => {
},
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1519,7 +1714,7 @@ describe('DataSlice', () => {
});
store.setState({ dbMessages: [settledLocalVoiceMessage] });
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1563,7 +1758,7 @@ describe('DataSlice', () => {
},
});
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
@@ -1606,7 +1801,7 @@ describe('DataSlice', () => {
],
} as any);
- store.getState().useFetchMessages({
+ fetchMessagesOf(store)({
agentId: 'test-session',
topicId: 'test-topic',
threadId: null,
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index f31a8902605..64f994f102a 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -1,20 +1,28 @@
import { parse } from '@lobechat/conversation-flow';
import { type ChatTopic, type ConversationContext, type UIChatMessage } from '@lobechat/types';
import debug from 'debug';
-import { type SWRResponse } from 'swr';
+import { useEffect, useMemo, useRef } from 'react';
import { type StateCreator } from 'zustand/vanilla';
import { readConversationMessageListPage } from '@/helpers/conversationMessageRead';
-import { useClientDataSWRWithSync } from '@/libs/swr';
+import { createReplicaSlice, type ReplicaLens } from '@/libs/replica';
import { messageService } from '@/services/message';
import {
- getEarlierHistoryStatus,
getMessageListCacheIdentity,
getMessageListFetchPolicy,
- loadEarlierMessagePage,
- messageListKey,
+ getMessageListWindowOlderCursor,
runMessageListQuery,
+ supportsRoundCursor,
} from '@/services/message/cache';
+import {
+ type ConversationMessageFetch,
+ type ConversationMessagePage,
+ type ConversationMessageParams,
+ conversationMessagesKey,
+ conversationMessagesResource,
+ toPersistedTranscript,
+ transcriptOf,
+} from '@/services/message/replica';
import { topicService } from '@/services/topic';
import { getChatStoreState, useChatStore } from '@/store/chat';
import { operationSelectors, topicSelectors } from '@/store/chat/selectors';
@@ -167,356 +175,520 @@ export interface DataAction {
skipFetch?: boolean;
syncInterventions?: boolean;
},
- ) => SWRResponse<UIChatMessage[]>;
+ ) => MessageSyncResult;
+}
+
+/** Fetch flags of the transcript sync. The rows live in the store (`dbMessages`). */
+export interface MessageSyncResult {
+ error: unknown;
+ /** A first fetch is in flight and nothing is on screen yet. */
+ isLoading: boolean;
+ isValidating: boolean;
+ /** Re-run the head sync. */
+ mutate: () => Promise<unknown>;
}
+/** What a head response resolved to, handed from `prepareHead` to the sync's `onSuccess`. */
+interface HeadResolution {
+ completed: boolean;
+ /** The response changed nothing during a stream: kept off the transcript. */
+ dropped: boolean;
+ isStreaming: boolean;
+ mergedMessages: UIChatMessage[];
+ ownsTopic: boolean;
+ snapshot?: InterventionSnapshot;
+}
+
+const isStreamingContext = (context: ConversationContext) =>
+ operationSelectors.isAgentRuntimeRunningByContext(context)(useChatStore.getState());
+
export const dataSlice: StateCreator<
ConversationStore,
[['zustand/devtools', never]],
[],
DataAction
-> = (set, get) => ({
- internal_dispatchMessage: (payload) => {
- const contextKey = messageMapKey(get().context);
-
- log(
- '[dispatchMessage] start | contextKey=%s | type=%s | id=%s',
- contextKey,
- payload.type,
- 'id' in payload ? payload.id : 'ids' in payload ? payload.ids.join(',') : 'N/A',
- );
-
- // Special handling for messageGroup metadata updates
- // MessageGroups are not in dbMessages, they're injected during query
- if (payload.type === 'updateMessageGroupMetadata') {
- const displayMessages = get().displayMessages;
- const index = displayMessages.findIndex((m) => m.id === payload.id);
- if (index < 0) return;
-
- const newDisplayMessages = [...displayMessages];
- newDisplayMessages[index] = {
- ...newDisplayMessages[index],
- metadata: { ...newDisplayMessages[index].metadata, ...payload.value },
+> = (set, get) => {
+ const sync = getInterventionSync(get);
+ /** Head responses resolved by `prepareHead`, read back by the sync's `onSuccess`. */
+ const headResolutions = new WeakMap<UIChatMessage[], HeadResolution>();
+
+ // ---- transcript view -------------------------------------------------------
+ // The store holds one conversation: `dbMessages` (rows) + `messagePaging`
+ // (bookkeeping) are the replica's view of the current context's entry, and
+ // the parsed `displayMessages` is derived in the same commit.
+ const NO_PAGING = {} as Omit<ConversationMessagePage, 'items'>;
+ const views = new WeakMap<UIChatMessage[], WeakMap<object, ConversationMessagePage>>();
+ const remember = (items: UIChatMessage[], paging: object, view: ConversationMessagePage) => {
+ let byPaging = views.get(items);
+ if (!byPaging) views.set(items, (byPaging = new WeakMap()));
+ byPaging.set(paging, view);
+ return view;
+ };
+ const hasTranscript = (state: ConversationStore) =>
+ !!state.messagePaging || state.dbMessages.length > 0;
+
+ const transcriptLens: ReplicaLens<ConversationStore, ConversationMessagePage> = {
+ clear: () => ({ dbMessages: [], displayMessages: [], messagePaging: undefined }),
+ get: (state, key) => {
+ if (key !== conversationMessagesKey(state.context) || !hasTranscript(state)) return undefined;
+ const paging = state.messagePaging ?? NO_PAGING;
+ return (
+ views.get(state.dbMessages)?.get(paging) ??
+ remember(
+ state.dbMessages,
+ paging,
+ state.messagePaging
+ ? { ...state.messagePaging, items: state.dbMessages }
+ : transcriptOf(state.dbMessages),
+ )
+ );
+ },
+ keys: (state) => (hasTranscript(state) ? [conversationMessagesKey(state.context)] : []),
+ set: (state, key, data) => {
+ // Late writes for a conversation this store no longer shows are dropped.
+ if (key !== conversationMessagesKey(state.context)) return {};
+ if (!data) return { dbMessages: [], displayMessages: [], messagePaging: undefined };
+ const { items, ...paging } = data;
+ remember(items, paging, data);
+ // parse() rebuilds every message/block/tool reference, so pin unchanged
+ // subtrees back to their previous identity to preserve memo bailouts.
+ const { flatList } = parse(items, undefined, { threadId: state.context.threadId });
+ return {
+ dbMessages: items,
+ displayMessages: stabilizeReferences(state.displayMessages, flatList),
+ messagePaging: paging,
};
+ },
+ };
- set({ displayMessages: stabilizeReferences(displayMessages, newDisplayMessages) }, false, {
- payload,
- type: `dispatchMessage/${payload.type}`,
+ // ---- reads ---------------------------------------------------------------
+ const fetchHead = async (context: ConversationMessageParams): Promise<UIChatMessage[]> => {
+ const syncKey = getMessageListCacheIdentity(context);
+ const dbMessages = get().dbMessages;
+ const topicAtRequest = context.topicId
+ ? topicSelectors.getTopicById(context.topicId)(getChatStoreState())
+ : undefined;
+ const wasPending = hasPendingInterventions(dbMessages);
+ let messages = await runMessageListQuery(context, readConversationMessageListPage);
+ if (!context.syncInterventions || !context.topicId) return messages;
+ if (wasPending || hasPendingInterventions(messages)) sync.pending.add(syncKey);
+ if (!sync.pending.has(syncKey) || hasPendingInterventions(messages)) return messages;
+
+ // The decision must precede the liveness read. A startup reservation is
+ // still live even before runningOperation is published.
+ const topic = await topicService.getTopicDetail(context.topicId);
+ if (!isInterventionRunActive(topic)) {
+ // Read after completion without dropping loaded history or its cursor.
+ messages = await runMessageListQuery(context, readConversationMessageListPage, {
+ force: true,
});
- return;
}
+ const result = [...messages];
+ sync.snapshots.set(result, { dbMessages, topic, topicAtRequest });
+ return result;
+ };
+
+ const fetchOlder = async (
+ context: ConversationMessageParams,
+ cursor: NonNullable<ConversationMessagePage['nextCursor']>,
+ ): Promise<ConversationMessageFetch> => {
+ const page = await messageService.getEarlierMessages(
+ {
+ agentId: context.agentId,
+ agentShareId: context.agentShareId,
+ groupId: context.groupId,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ topicShareId: context.topicShareId,
+ },
+ cursor,
+ );
+ // Without a reported cursor, `length < pageSize` is NOT a reliable end
+ // signal β€” the round-start trim legitimately shortens full pages β€” so only
+ // an empty page marks the top (`applyNextPage`).
+ return { items: page.messages, nextCursor: page.olderCursor };
+ };
- const dbMessages = get().dbMessages;
-
- // Apply array-based reducer - preserves message order
- const newDbMessages = messagesReducer(dbMessages, payload);
-
- // Check if anything changed
- if (newDbMessages === dbMessages) {
- log('[dispatchMessage] no change | contextKey=%s', contextKey);
- return;
+ /**
+ * Fold a fetched head window into the shown transcript the way the
+ * conversation always has: drop results for a conversation no longer shown,
+ * keep streamed rows and unanswered interventions during a run, and keep
+ * client rows the server snapshot cannot know yet.
+ */
+ const prepareHead = (
+ incoming: ConversationMessageFetch,
+ current: ConversationMessagePage | undefined,
+ context: ConversationMessageParams,
+ ): ConversationMessageFetch | undefined => {
+ if (!Array.isArray(incoming)) return incoming;
+ if (!context.topicId) return undefined;
+
+ const storeContextKey = messageMapKey(get().context);
+ if (storeContextKey !== messageMapKey(context)) {
+ log(
+ '[useFetchMessages] dropped stale result | requestContextKey=%s | storeContextKey=%s',
+ messageMapKey(context),
+ storeContextKey,
+ );
+ return undefined;
}
- // Re-parse for display order and grouping
- const { flatList } = parse(newDbMessages, undefined, { threadId: get().context.threadId });
- // parse() rebuilds every message/block/tool reference, so pin unchanged
- // subtrees back to their previous identity to preserve memo bailouts.
- const stableFlatList = stabilizeReferences(get().displayMessages, flatList);
+ // DB chunk writes can lag behind pushed content, even at an equal
+ // updatedAt. Keep streamed rows, but allow answers and unseen rows in.
+ // A parked run must not block the first load of the conversation.
+ const prevDbMessages = current?.items ?? get().dbMessages;
+ const snapshot = sync.snapshots.get(incoming);
+ sync.snapshots.delete(incoming);
+ const chat = getChatStoreState();
+ const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);
+ const ownsTopic = !!snapshot && currentTopic === snapshot.topicAtRequest;
+ const completed = ownsTopic && !isInterventionRunActive(snapshot!.topic);
+ const isStreaming =
+ get().messagesInit &&
+ operationSelectors.isAgentRuntimeRunningByContext(context)(chat) &&
+ !(completed && snapshot!.dbMessages === prevDbMessages);
+ const activeVoiceMessageIds = new Set(Object.keys(chat.voiceMessageUploadMap));
+ const mergedMessages = isStreaming
+ ? reconcileStreamingInterventions(prevDbMessages, incoming)
+ : mergeFetchedMessagesWithLocalState(incoming, prevDbMessages, activeVoiceMessageIds);
+ const dropped = isStreaming && mergedMessages === prevDbMessages;
+
+ headResolutions.set(incoming, {
+ completed,
+ dropped,
+ isStreaming,
+ mergedMessages,
+ ownsTopic,
+ snapshot,
+ });
+ if (dropped) return undefined;
log(
- '[dispatchMessage] updated | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d',
- contextKey,
- dbMessages.length,
- newDbMessages.length,
- stableFlatList.length,
+ '[useFetchMessages] head | contextKey=%s | prevCount=%d | fetchedCount=%d',
+ storeContextKey,
+ prevDbMessages.length,
+ mergedMessages.length,
);
+ return { items: mergedMessages, nextCursor: getMessageListWindowOlderCursor(context) };
+ };
+
+ const transcript = createReplicaSlice(conversationMessagesResource, {
+ actionPrefix: 'conversationMessages',
+ fetcher: (context, cursor) => (cursor ? fetchOlder(context, cursor) : fetchHead(context)),
+ get,
+ prepareHead,
+ set,
+ stateKey: 'messageReplica',
+ toPersisted: toPersistedTranscript,
+ view: transcriptLens,
+ });
- set({ dbMessages: newDbMessages, displayMessages: stableFlatList }, false, {
- payload,
- type: `dispatchMessage/${payload.type}`,
- });
-
- // Sync changes to external store (ChatStore)
- get().onMessagesChange?.(newDbMessages, get().context);
- },
+ /** Write rows to the shown transcript (memory only; see `settleTranscript`). */
+ const writeTranscript = (messages: UIChatMessage[], preservePaging = false) =>
+ transcript.update(
+ conversationMessagesKey(get().context),
+ (current) =>
+ current &&
+ (preservePaging ||
+ (current.items.length === messages.length &&
+ current.items.every((item, index) => item.id === messages[index].id)))
+ ? { ...current, items: messages }
+ : transcriptOf(messages),
+ { persist: false },
+ );
- loadEarlierMessages: async (options) => {
+ /**
+ * Persist the shown transcript once it is settled β€” never per streamed
+ * chunk; the snapshot written at run end is the one that survives a reload.
+ */
+ const settleTranscript = () => {
const context = get().context;
- if (!context.agentId || !context.topicId) return;
- if (get().earlierMessagesError !== undefined && !options?.retry) return;
- const status = getEarlierHistoryStatus(context);
- if (status.loading || status.exhausted) return;
-
- set(
- { earlierMessagesError: undefined, isLoadingEarlierMessages: true },
- false,
- 'loadEarlierMessages/start',
- );
- try {
- const merged = await loadEarlierMessagePage(
- context,
- // Read on demand: the cursor comes from the transcript at request time,
- // while the merge runs against the transcript at completion β€” a stream
- // or edit may have changed it meanwhile. A conversation switch yields
- // `undefined` so the other conversation's rows are never merged.
- () => (isSameConversationContext(context, get().context) ? get().dbMessages : undefined),
- (cursor) =>
- messageService.getEarlierMessages(
- {
- agentId: context.agentId,
- agentShareId: context.agentShareId,
- groupId: context.groupId,
- threadId: context.threadId,
- topicId: context.topicId,
- topicShareId: context.topicShareId,
- },
- cursor,
- ),
+ if (isStreamingContext(context)) return;
+ transcript.persist(conversationMessagesKey(context));
+ };
+
+ return {
+ internal_dispatchMessage: (payload) => {
+ const contextKey = messageMapKey(get().context);
+
+ log(
+ '[dispatchMessage] start | contextKey=%s | type=%s | id=%s',
+ contextKey,
+ payload.type,
+ 'id' in payload ? payload.id : 'ids' in payload ? payload.ids.join(',') : 'N/A',
);
- // `undefined` β†’ nothing to prepend (no cursor, already loading, the
- // beginning was reached, or the request went stale while in flight).
- if (!merged) return;
+
+ // Special handling for messageGroup metadata updates
+ // MessageGroups are not in dbMessages, they're injected during query
+ if (payload.type === 'updateMessageGroupMetadata') {
+ const displayMessages = get().displayMessages;
+ const index = displayMessages.findIndex((m) => m.id === payload.id);
+ if (index < 0) return;
+
+ const newDisplayMessages = [...displayMessages];
+ newDisplayMessages[index] = {
+ ...newDisplayMessages[index],
+ metadata: { ...newDisplayMessages[index].metadata, ...payload.value },
+ };
+
+ set({ displayMessages: stabilizeReferences(displayMessages, newDisplayMessages) }, false, {
+ payload,
+ type: `dispatchMessage/${payload.type}`,
+ });
+ return;
+ }
+
+ const dbMessages = get().dbMessages;
+
+ // Apply array-based reducer - preserves message order
+ const newDbMessages = messagesReducer(dbMessages, payload);
+
+ // Check if anything changed
+ if (newDbMessages === dbMessages) {
+ log('[dispatchMessage] no change | contextKey=%s', contextKey);
+ return;
+ }
log(
- '[loadEarlierMessages] prepended | contextKey=%s | mergedCount=%d',
- messageMapKey(context),
- merged.length,
+ '[dispatchMessage] updated | contextKey=%s | prevCount=%d | newCount=%d',
+ contextKey,
+ dbMessages.length,
+ newDbMessages.length,
);
- get().replaceMessages(merged, { expectedContext: context });
- } catch (error) {
- log('[loadEarlierMessages] failed | contextKey=%s | %O', messageMapKey(context), error);
- // The list fires this without awaiting, so the failure is surfaced
- // through state (inline error row with Retry) instead of a rejection.
- if (isSameConversationContext(context, get().context)) {
- set({ earlierMessagesError: error }, false, 'loadEarlierMessages/error');
+
+ writeTranscript(newDbMessages, true);
+ settleTranscript();
+
+ // Sync changes to external store (ChatStore)
+ get().onMessagesChange?.(newDbMessages, get().context);
+ },
+
+ loadEarlierMessages: async (options) => {
+ const context = get().context;
+ if (!context.agentId || !context.topicId) return;
+ if (get().earlierMessagesError !== undefined && !options?.retry) return;
+
+ const key = conversationMessagesKey(context);
+ const read = () => transcriptLens.get(get(), key);
+ const view = read();
+ if (!view || view.isLoadingMore) return;
+
+ // A transcript seeded by the host (not yet confirmed by this store's own
+ // sync) pages from the window cursor this session already fetched. A
+ // cursor rebuilt from a row's millisecond `createdAt` would skip older
+ // rows sharing that millisecond, so a round-cursor read waits for it.
+ if (get().messageReplica.entries[key]?.source !== 'server' && view.nextCursor === undefined) {
+ const windowCursor = getMessageListWindowOlderCursor(context);
+ if (windowCursor === undefined && supportsRoundCursor(context)) return;
+ if (windowCursor !== undefined)
+ transcript.update(
+ key,
+ (data) => data && { ...data, hasMore: windowCursor !== null, nextCursor: windowCursor },
+ { persist: false },
+ );
}
- } finally {
+ if (!read()?.hasMore) return;
+
+ set(
+ { earlierMessagesError: undefined, isLoadingEarlierMessages: true },
+ false,
+ 'loadEarlierMessages/start',
+ );
+ const before = get().dbMessages;
+ await transcript.loadMore(key, context);
+
// The flag is conversation-wide state: after a context switch it belongs
// to the new conversation (reset by createEphemeralResetState), so a
// late settle from the previous one must not clear it.
- if (isSameConversationContext(context, get().context)) {
- set({ isLoadingEarlierMessages: false }, false, 'loadEarlierMessages/end');
+ if (!isSameConversationContext(context, get().context)) return;
+ // Hand the extended transcript to the host: its next sync back into this
+ // store would otherwise replace the rows with the shorter window.
+ if (get().dbMessages !== before) get().onMessagesChange?.(get().dbMessages, context);
+ const error = read()?.loadMoreError;
+ if (error)
+ log('[loadEarlierMessages] failed | contextKey=%s | %O', messageMapKey(context), error);
+ set(
+ { earlierMessagesError: error ?? undefined, isLoadingEarlierMessages: false },
+ false,
+ 'loadEarlierMessages/end',
+ );
+ },
+
+ replaceMessages: (messages, options) => {
+ const currentContext = get().context;
+ const contextKey = messageMapKey(currentContext);
+ if (
+ options?.expectedContext &&
+ !isSameConversationContext(options.expectedContext, currentContext)
+ ) {
+ log(
+ '[replaceMessages] dropped stale result | requestContextKey=%s | storeContextKey=%s',
+ messageMapKey(options.expectedContext),
+ contextKey,
+ );
+ return;
}
- }
- },
-
- replaceMessages: (messages, options) => {
- const currentContext = get().context;
- const contextKey = messageMapKey(currentContext);
- if (
- options?.expectedContext &&
- !isSameConversationContext(options.expectedContext, currentContext)
- ) {
+
log(
- '[replaceMessages] dropped stale result | requestContextKey=%s | storeContextKey=%s',
- messageMapKey(options.expectedContext),
+ '[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | skipOnMessagesChange=%s | messageIds=%o',
contextKey,
+ get().dbMessages.length,
+ messages.length,
+ options?.skipOnMessagesChange,
+ messages.slice(0, 5).map((m) => m.id),
);
- return;
- }
- const prevDbMessages = get().dbMessages;
+ writeTranscript(messages);
+ settleTranscript();
- // Parse messages using conversation-flow
- const { flatList } = parse(messages, undefined, { threadId: get().context.threadId });
- const stableFlatList = stabilizeReferences(get().displayMessages, flatList);
+ // Sync changes to external store (ChatStore) β€” skipped for external prop
+ // sync, which would only echo the external store's own data back and
+ // poison the SWR cache (see interface doc).
+ if (!options?.skipOnMessagesChange) {
+ get().onMessagesChange?.(messages, options?.expectedContext ?? currentContext);
+ }
+ },
- log(
- '[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d | skipOnMessagesChange=%s | messageIds=%o',
- contextKey,
- prevDbMessages.length,
- messages.length,
- stableFlatList.length,
- options?.skipOnMessagesChange,
- messages.slice(0, 5).map((m) => m.id),
- );
+ switchMessageBranch: async (messageId, branchIndex) => {
+ const state = get();
- set({ dbMessages: messages, displayMessages: stableFlatList }, false, 'replaceMessages');
+ // Get the current message to find its parent
+ const message = dataSelectors.getDbMessageById(messageId)(state);
+ if (!message || !message.parentId) return;
- // Sync changes to external store (ChatStore) β€” skipped for external prop
- // sync, which would only echo the external store's own data back and
- // poison the SWR cache (see interface doc).
- if (!options?.skipOnMessagesChange) {
- get().onMessagesChange?.(messages, options?.expectedContext ?? currentContext);
- }
- },
-
- switchMessageBranch: async (messageId, branchIndex) => {
- const state = get();
-
- // Get the current message to find its parent
- const message = dataSelectors.getDbMessageById(messageId)(state);
- if (!message || !message.parentId) return;
-
- // Update the parent's metadata.activeBranchIndex
- // because the branch indicator is on the child message,
- // but the activeBranchIndex is stored on the parent
- await state.updateMessageMetadata(message.parentId, { activeBranchIndex: branchIndex });
- },
-
- useFetchMessages: (context, options) => {
- const { skipFetch, revalidateOnFocus, refreshInterval = 0 } = options ?? {};
- // When skipFetch is true, SWR key is null - no fetch occurs
- // This is used when external messages are provided (e.g., creating new thread)
- // Also skip fetch when topicId is null (new conversation state) - there's no server data,
- // only local optimistic updates. Fetching would return empty array and overwrite local data.
- const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;
- const contextKey = messageMapKey(context);
- const sync = getInterventionSync(get);
- const syncKey = getMessageListCacheIdentity(context);
- // Shared views use share-authorized services; thread runs do not own the
- // topic's main runningOperation marker. Keep their existing refresh path.
- const syncContinuation =
- options?.syncInterventions &&
- !context.agentShareId &&
- !context.topicShareId &&
- !context.threadId;
- const storeContextKeyAtRequest = messageMapKey(get().context);
- const onMessagesChange = get().onMessagesChange;
+ // Update the parent's metadata.activeBranchIndex
+ // because the branch indicator is on the child message,
+ // but the activeBranchIndex is stored on the parent
+ await state.updateMessageMetadata(message.parentId, { activeBranchIndex: branchIndex });
+ },
- log(
- '[useFetchMessages] hook | contextKey=%s | shouldFetch=%s | skipFetch=%s | agentId=%s | topicId=%s',
- contextKey,
- shouldFetch,
- skipFetch,
- context.agentId,
- context.topicId,
- );
+ useFetchMessages: (context, options) => {
+ const { skipFetch, revalidateOnFocus, refreshInterval = 0 } = options ?? {};
+ // When skipFetch is true no fetch occurs. This is used when external
+ // messages are provided (e.g., creating new thread). Also skip when
+ // topicId is null (new conversation state) - there's no server data,
+ // only local optimistic updates. Fetching would return empty array and
+ // overwrite local data.
+ const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;
+ const syncKey = getMessageListCacheIdentity(context);
+ // Shared views use share-authorized services; thread runs do not own the
+ // topic's main runningOperation marker. Keep their existing refresh path.
+ const syncContinuation =
+ !!options?.syncInterventions &&
+ !context.agentShareId &&
+ !context.topicShareId &&
+ !context.threadId;
+ const onMessagesChange = get().onMessagesChange;
+ // Stable identity: the poll timer restarts whenever the interval option
+ // changes, so a fresh function per render would postpone every tick.
+ const pollInterval = useMemo(
+ () =>
+ syncContinuation
+ ? () => (sync.pending.has(syncKey) ? INTERVENTION_REFRESH_INTERVAL : refreshInterval)
+ : refreshInterval,
+ [syncContinuation, syncKey, refreshInterval],
+ );
- return useClientDataSWRWithSync<UIChatMessage[]>(
- shouldFetch ? messageListKey(context) : null,
-
- async () => {
- const dbMessages = get().dbMessages;
- const topicAtRequest = context.topicId
- ? topicSelectors.getTopicById(context.topicId)(getChatStoreState())
- : undefined;
- const wasPending = hasPendingInterventions(dbMessages);
- let messages = await runMessageListQuery(context, readConversationMessageListPage);
- if (!syncContinuation || !context.topicId) return messages;
- if (wasPending || hasPendingInterventions(messages)) sync.pending.add(syncKey);
- if (!sync.pending.has(syncKey) || hasPendingInterventions(messages)) return messages;
-
- // The decision must precede the liveness read. A startup reservation is
- // still live even before runningOperation is published.
- const topic = await topicService.getTopicDetail(context.topicId);
- if (!isInterventionRunActive(topic)) {
- // Read after completion without dropping loaded history or its cursor.
- messages = await runMessageListQuery(context, readConversationMessageListPage, {
- force: true,
- });
- }
- const result = [...messages];
- sync.snapshots.set(result, { dbMessages, topic, topicAtRequest });
- return result;
- },
- {
- ...getMessageListFetchPolicy(context),
- // Pending cards must observe answers from another device before the
- // normal message cache's 30-second verification window expires.
- ...((refreshInterval > 0 || sync.pending.has(syncKey)) && { dedupingInterval: 1000 }),
- refreshInterval: syncContinuation
- ? () => (sync.pending.has(syncKey) ? INTERVENTION_REFRESH_INTERVAL : refreshInterval)
- : refreshInterval,
- refreshWhenHidden: false,
- refreshWhenOffline: false,
- ...(revalidateOnFocus !== undefined && { revalidateOnFocus }),
- // Fresh in-memory or prefetched data can render without an immediate
- // switch-time revalidation. Missing cache data still fetches because
- // SWR always loads when `data` is undefined.
- onData: (data) => {
- if (!data) return;
- if (!context.topicId) return;
-
- const storeContextKey = messageMapKey(get().context);
- if (storeContextKeyAtRequest !== storeContextKey) {
- log(
- '[useFetchMessages] dropped stale result | requestStoreContextKey=%s | storeContextKey=%s',
- storeContextKeyAtRequest,
- storeContextKey,
- );
- return;
- }
-
- // DB chunk writes can lag behind pushed content, even at an equal
- // updatedAt. Keep streamed rows, but allow answers and unseen rows in.
- // A parked run must not block the first load of the conversation.
- const prevDbMessages = get().dbMessages;
- const snapshot = sync.snapshots.get(data);
- sync.snapshots.delete(data);
- const chat = getChatStoreState();
- const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);
- const ownsTopic = snapshot && currentTopic === snapshot.topicAtRequest;
- const completed = ownsTopic && !isInterventionRunActive(snapshot.topic);
- const isStreaming =
- get().messagesInit &&
- operationSelectors.isAgentRuntimeRunningByContext(context)(chat) &&
- !(completed && snapshot.dbMessages === prevDbMessages);
- const activeVoiceMessageIds = new Set(
- Object.keys(getChatStoreState().voiceMessageUploadMap),
- );
- const mergedMessages = isStreaming
- ? reconcileStreamingInterventions(prevDbMessages, data)
- : mergeFetchedMessagesWithLocalState(data, prevDbMessages, activeVoiceMessageIds);
- // Do not replace a topic marker claimed by a local send or newer push.
- if (snapshot && !hasPendingInterventions(mergedMessages) && ownsTopic) {
- if (completed && !isStreaming) sync.pending.delete(syncKey);
- const runningOperation = snapshot.topic?.metadata?.runningOperation;
- if (
- runningOperation &&
- currentTopic?.metadata?.runningOperation?.operationId !== runningOperation.operationId
- ) {
- // Publish the marker for useGatewayReconnect; it owns connection
- // deduplication and retry. Do not open a second socket here.
- if (currentTopic) {
- chat.internal_dispatchTopic({
- id: context.topicId,
- type: 'updateTopic',
- containerKey: topicSelectors.getTopicContainerKeyById(context.topicId)(chat),
- agentId: context.agentId,
- groupId: context.groupId,
- value: { metadata: { ...currentTopic.metadata, runningOperation } },
- });
- } else if (snapshot.topic) {
- useChatStore.setState({
- topicDetailMap: { ...chat.topicDetailMap, [context.topicId]: snapshot.topic },
- });
+ log(
+ '[useFetchMessages] hook | contextKey=%s | shouldFetch=%s | skipFetch=%s',
+ messageMapKey(context),
+ shouldFetch,
+ skipFetch,
+ );
+
+ const result = transcript.useSync(
+ { ...context, syncInterventions: syncContinuation },
+ {
+ ...getMessageListFetchPolicy(context),
+ enabled: shouldFetch,
+ // Pending cards must observe answers from another device before the
+ // normal message cache's 30-second verification window expires.
+ ...((refreshInterval > 0 || sync.pending.has(syncKey)) && { dedupingInterval: 1000 }),
+ onSuccess: (fetched) => {
+ const resolution = Array.isArray(fetched) ? headResolutions.get(fetched) : undefined;
+ if (!resolution || !context.topicId) return;
+ headResolutions.delete(fetched as UIChatMessage[]);
+ const { completed, dropped, isStreaming, mergedMessages, ownsTopic, snapshot } =
+ resolution;
+
+ // Do not replace a topic marker claimed by a local send or newer push.
+ if (snapshot && !hasPendingInterventions(mergedMessages) && ownsTopic) {
+ if (completed && !isStreaming) sync.pending.delete(syncKey);
+ const chat = getChatStoreState();
+ const currentTopic = topicSelectors.getTopicById(context.topicId)(chat);
+ const runningOperation = snapshot.topic?.metadata?.runningOperation;
+ if (
+ runningOperation &&
+ currentTopic?.metadata?.runningOperation?.operationId !==
+ runningOperation.operationId
+ ) {
+ // Publish the marker for useGatewayReconnect; it owns connection
+ // deduplication and retry. Do not open a second socket here.
+ if (currentTopic) {
+ chat.internal_dispatchTopic({
+ agentId: context.agentId,
+ containerKey: topicSelectors.getTopicContainerKeyById(context.topicId)(chat),
+ groupId: context.groupId,
+ id: context.topicId,
+ type: 'updateTopic',
+ value: { metadata: { ...currentTopic.metadata, runningOperation } },
+ });
+ } else if (snapshot.topic) {
+ useChatStore.setState({
+ topicDetailMap: { ...chat.topicDetailMap, [context.topicId]: snapshot.topic },
+ });
+ }
}
}
- }
- if (isStreaming && mergedMessages === prevDbMessages) return;
-
- // Parse messages using conversation-flow
- const { flatList } = parse(mergedMessages, undefined, { threadId: context.threadId });
- const stableFlatList = stabilizeReferences(get().displayMessages, flatList);
-
- log(
- '[useFetchMessages] onData | requestContextKey=%s | storeContextKey=%s | prevCount=%d | fetchedCount=%d | displayCount=%d | messageIds=%o',
- contextKey,
- storeContextKey,
- prevDbMessages.length,
- mergedMessages.length,
- stableFlatList.length,
- mergedMessages.slice(0, 5).map((m) => m.id),
- );
-
- set({
- dbMessages: mergedMessages,
- displayMessages: stableFlatList,
- messagesInit: true,
- });
-
- // Use the callback and context captured when this fetch was registered.
- // The store-context guard above rejects results after a topic switch;
- // capturing the callback also prevents routing through a later handler instance.
- // `source: 'fetch'` marks this as a server-snapshot echo: handlers must
- // NOT write it through the SWR cache β€” at mount, this fires with the
- // stale cached list while the revalidation is in flight, and a cache
- // mutate here trips SWR's mutation race guard, discarding the fresh
- // result (conversation locks on the stale/partial list).
- onMessagesChange?.(mergedMessages, context, { source: 'fetch' });
+ if (dropped) return;
+ set({ messagesInit: true }, false, 'useFetchMessages/init');
+
+ // Use the callback and context captured when this fetch was
+ // registered. `source: 'fetch'` marks this as a server-snapshot
+ // echo: handlers must NOT write it through the SWR cache.
+ onMessagesChange?.(get().dbMessages, context, { source: 'fetch' });
+ },
+ refreshInterval: pollInterval,
+ refreshWhenHidden: false,
+ refreshWhenOffline: false,
+ ...(revalidateOnFocus !== undefined && { revalidateOnFocus }),
},
- },
- );
- },
-});
+ );
+
+ // Streamed chunks stay in memory; the transcript is persisted once the
+ // run settles, so a reload restores the finished reply.
+ const isStreaming = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));
+ const streamingKey = conversationMessagesKey(context);
+ const wasStreamingRef = useRef({ key: streamingKey, running: isStreaming });
+ useEffect(() => {
+ if (
+ wasStreamingRef.current.key === streamingKey &&
+ wasStreamingRef.current.running &&
+ !isStreaming
+ )
+ settleTranscript();
+ wasStreamingRef.current = { key: streamingKey, running: isStreaming };
+ }, [isStreaming, streamingKey]);
+
+ // A transcript painted from storage before the network answers is
+ // handed to the host too, so its views (and runs) see the same rows.
+ const key = conversationMessagesKey(context);
+ const bridgedKeyRef = useRef<string>(undefined);
+ useEffect(() => {
+ if (!result.isHydrated || bridgedKeyRef.current === key) return;
+ bridgedKeyRef.current = key;
+ const state = get();
+ if (state.messageReplica.entries[key]?.source !== 'storage') return;
+ set({ messagesInit: true }, false, 'useFetchMessages/hydrated');
+ onMessagesChange?.(state.dbMessages, context, { source: 'fetch' });
+ }, [result.isHydrated, key]);
+
+ return {
+ error: result.error,
+ isLoading: result.isValidating && !get().messagesInit,
+ isValidating: result.isValidating,
+ mutate: result.revalidate,
+ };
+ },
+ };
+};
diff --git a/src/features/Conversation/store/slices/data/approvalSync.test.ts b/src/features/Conversation/store/slices/data/approvalSync.test.ts
index 9a7a93a25e3..97d900d99f8 100644
--- a/src/features/Conversation/store/slices/data/approvalSync.test.ts
+++ b/src/features/Conversation/store/slices/data/approvalSync.test.ts
@@ -5,11 +5,7 @@ import { SWRConfig } from 'swr';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
-import {
- clearMessageListClientCacheState,
- getEarlierHistoryStatus,
- loadEarlierMessagePage,
-} from '@/services/message/cache';
+import { clearMessageListClientCacheState } from '@/services/message/cache';
import { topicService } from '@/services/topic';
import { useChatStore } from '@/store/chat';
import { operationSelectors, topicSelectors } from '@/store/chat/selectors';
@@ -24,6 +20,7 @@ vi.mock('@/services/message', () => {
const getMessages = vi.fn();
return {
messageService: {
+ getEarlierMessages: vi.fn(),
getMessages,
getMessageListPage: vi.fn(async (params: unknown) => ({
messages: await getMessages(params),
@@ -103,12 +100,14 @@ describe('pending approval message polling', () => {
createdAt: 0,
updatedAt: 0,
};
- const history = await loadEarlierMessagePage(
- context,
- () => store.getState().dbMessages,
- async () => ({ messages: [older], olderCursor: null }),
- );
- act(() => store.getState().replaceMessages(history!));
+ vi.mocked(messageService.getEarlierMessages).mockResolvedValue({
+ messages: [older],
+ olderCursor: null,
+ });
+ await act(async () => {
+ await store.getState().loadEarlierMessages();
+ });
+ expect(store.getState().dbMessages.map((m) => m.id)).toEqual(['older', 'question']);
const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };
const reply: UIChatMessage = {
id: 'reply',
@@ -122,7 +121,7 @@ describe('pending approval message polling', () => {
await vi.advanceTimersByTimeAsync(2000);
});
expect(store.getState().dbMessages).toEqual([older, answered, reply]);
- expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
+ expect(store.getState().messagePaging?.hasMore).toBe(false);
expect(messageService.getMessageListPage).toHaveBeenCalledTimes(3);
});
diff --git a/src/features/Conversation/store/slices/data/initialState.ts b/src/features/Conversation/store/slices/data/initialState.ts
index 1938b62dffb..59cdca75cee 100644
--- a/src/features/Conversation/store/slices/data/initialState.ts
+++ b/src/features/Conversation/store/slices/data/initialState.ts
@@ -1,5 +1,8 @@
import { type UIChatMessage } from '@lobechat/types';
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import { type ConversationMessagePage } from '@/services/message/replica';
+
export interface DataState {
/**
* Raw messages from DB (before parsing)
@@ -26,6 +29,18 @@ export interface DataState {
*/
isLoadingEarlierMessages: boolean;
+ /**
+ * Paging bookkeeping of the transcript in `dbMessages` (cursor of the next
+ * older page, loaded depth). Absent until a fetch or hydration lands.
+ */
+ messagePaging?: Omit<ConversationMessagePage, 'items'>;
+
+ /**
+ * Replica bookkeeping of this conversation's transcript (`dbMessages` +
+ * `messagePaging` are its view).
+ */
+ messageReplica: ReplicaState<ConversationMessagePage>;
+
/**
* Whether messages have been initialized
*/
@@ -48,5 +63,6 @@ export const dataInitialState: DataState = {
dbMessages: [],
displayMessages: [],
isLoadingEarlierMessages: false,
+ messageReplica: createReplicaState(),
messagesInit: false,
};
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
index 9388c906a07..d5e7a1f3b62 100644
--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
@@ -93,6 +93,7 @@ vi.mock('@/store/agent/selectors', () => ({
}));
vi.mock('@/store/chat/selectors', () => ({
+ operationSelectors: { isAgentRuntimeRunningByContext: () => () => false },
topicSelectors: {
getTopicById: () => () => mockTopic,
getTopicHeteroPinById: () => () =>
diff --git a/src/features/Conversation/store/slices/message/action/state.test.ts b/src/features/Conversation/store/slices/message/action/state.test.ts
index d024f44375a..04d31b4353a 100644
--- a/src/features/Conversation/store/slices/message/action/state.test.ts
+++ b/src/features/Conversation/store/slices/message/action/state.test.ts
@@ -8,6 +8,8 @@ import { createStore } from '../../../index';
const { chatStoreMock } = vi.hoisted(() => ({
chatStoreMock: {
cancelOperations: vi.fn(),
+ operations: {},
+ operationsByContext: {},
},
}));
diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
index f47e4d8b8cb..54e833b49f3 100644
--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts
@@ -3,11 +3,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
agentChatTopicListLoader,
PRE_PAINT_HYDRATE_TIMEOUT,
+ preHydrateMessagesForRoute,
preHydrateTopicListForRoute,
} from './topicListLoader';
const preHydrateTopicListMock = vi.hoisted(() => vi.fn(async () => true));
const getSidebarTopicListParamsMock = vi.hoisted(() => vi.fn());
+const readPersistedTranscriptMock = vi.hoisted(() => vi.fn());
+const chatState = vi.hoisted(() => ({
+ dbMessagesMap: {} as Record<string, unknown[]>,
+ replaceMessages: vi.fn(),
+}));
const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);
vi.mock('@lobechat/builtin-agents', () => ({
@@ -30,7 +36,13 @@ vi.mock('@/store/agent/selectors', () => ({
}));
vi.mock('@/store/chat', () => ({
- useChatStore: { getState: () => ({ preHydrateTopicList: preHydrateTopicListMock }) },
+ useChatStore: {
+ getState: () => ({ ...chatState, preHydrateTopicList: preHydrateTopicListMock }),
+ },
+}));
+
+vi.mock('@/services/message/replica', () => ({
+ readPersistedTranscript: readPersistedTranscriptMock,
}));
const loaderArgs = (aid?: string) => ({ params: aid ? { aid } : {} }) as never;
@@ -92,3 +104,43 @@ describe('agent chat topic list loader', () => {
await expect(agentChatTopicListLoader(loaderArgs('agt_1'))).resolves.toBeNull();
});
});
+
+describe('agent chat transcript pre-hydrate', () => {
+ const rows = [{ content: 'hi', id: 'msg_1', role: 'user' }];
+
+ beforeEach(() => {
+ chatState.dbMessagesMap = {};
+ chatState.replaceMessages.mockClear();
+ readPersistedTranscriptMock.mockReset();
+ readPersistedTranscriptMock.mockResolvedValue({ items: rows });
+ });
+
+ it("seeds the topic's persisted transcript into the chat store before the route commits", async () => {
+ await agentChatTopicListLoader({ params: { aid: 'agt_1', topicId: 'tpc_1' } } as never);
+
+ const context = { agentId: 'agt_1', scope: 'main', topicId: 'tpc_1' };
+ expect(readPersistedTranscriptMock).toHaveBeenCalledWith(context);
+ expect(chatState.replaceMessages).toHaveBeenCalledWith(rows, {
+ action: 'preHydrateMessages',
+ context,
+ source: 'fetch',
+ });
+ });
+
+ it('never replaces rows the chat store already holds', async () => {
+ chatState.dbMessagesMap = { main_agt_1_tpc_1: [] };
+
+ await preHydrateMessagesForRoute('agt_1', 'tpc_1');
+
+ expect(chatState.replaceMessages).not.toHaveBeenCalled();
+ });
+
+ it('skips a route without a topic and a miss in storage', async () => {
+ await preHydrateMessagesForRoute('agt_1');
+ expect(readPersistedTranscriptMock).not.toHaveBeenCalled();
+
+ readPersistedTranscriptMock.mockResolvedValue(undefined);
+ await preHydrateMessagesForRoute('agt_1', 'tpc_1');
+ expect(chatState.replaceMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.ts
index 81848733b20..5067eec0f52 100644
--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts
+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts
@@ -2,9 +2,11 @@ import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import type { LoaderFunctionArgs } from 'react-router';
import { getSidebarTopicListParams } from '@/hooks/chatTopicListQuery';
+import { readPersistedTranscript } from '@/services/message/replica';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
@@ -63,9 +65,47 @@ export const preHydrateTopicListForRoute = async (routeAgentId?: string): Promis
);
};
+/**
+ * Seed the persisted transcript of a route's topic into the chat store.
+ *
+ * The conversation is hosted on the chat store's bucket, so rows landing there
+ * before the route commits reach the Conversation as its first-frame messages:
+ * a topic opened before paints from local data and only revalidates in the
+ * background, instead of painting a skeleton until the network answers.
+ */
+export const preHydrateMessagesForRoute = async (
+ routeAgentId?: string,
+ topicId?: string,
+): Promise<void> => {
+ const agentId = resolveRouteAgentId(routeAgentId);
+ if (!agentId || !topicId) return;
+
+ const context = { agentId, scope: 'main' as const, topicId };
+ const seed = async () => {
+ const transcript = await readPersistedTranscript(context);
+ if (!transcript?.items.length) return;
+
+ const chat = useChatStore.getState();
+ // Rows already in memory (this session's, or streamed) are newer.
+ if (chat.dbMessagesMap[messageMapKey(context)]) return;
+ // `source: 'fetch'`: a stored server snapshot, not a local edit β€” it must
+ // not be written through as if it were fresh.
+ chat.replaceMessages(transcript.items, {
+ action: 'preHydrateMessages',
+ context,
+ source: 'fetch',
+ });
+ };
+
+ await settleWithin(seed(), PRE_PAINT_HYDRATE_TIMEOUT);
+};
+
/** Loader for the agent chat routes (`/agent/:aid`, `/agent/:aid/:topicId`). */
export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {
- await preHydrateTopicListForRoute(params.aid);
+ await Promise.all([
+ preHydrateTopicListForRoute(params.aid),
+ preHydrateMessagesForRoute(params.aid, params.topicId),
+ ]);
return null;
};
diff --git a/src/services/message/cache.test.ts b/src/services/message/cache.test.ts
index 23f528cf473..eca89292171 100644
--- a/src/services/message/cache.test.ts
+++ b/src/services/message/cache.test.ts
@@ -5,14 +5,12 @@ import { MESSAGE_CACHE_VERSION } from '@/libs/swr/keys';
import {
clearMessageListClientCacheState,
- getEarlierHistoryStatus,
getMessageListFetchPolicy,
+ getMessageListWindowOlderCursor,
invalidateMessageListClientState,
isMessageListServerVerified,
- loadEarlierMessagePage,
MESSAGE_LIST_VERIFICATION_INTERVAL,
messageListKey,
- type MessageListPage,
runMessageListQuery,
} from './cache';
@@ -249,311 +247,17 @@ describe('message list client cache', () => {
});
});
-describe('earlier history (round-cursor pages)', () => {
- const message = (id: string, createdAt: number, role = 'assistant') =>
- ({ content: id, createdAt, id, role, updatedAt: createdAt }) as unknown as UIChatMessage;
-
- const ids = (list: UIChatMessage[] | undefined) => list?.map((item) => item.id);
-
- // Threads have no round-cursor read, so their pages derive the cursor from
- // the oldest loaded row β€” the legacy path these cases pin down.
- const threadContext = { ...context, threadId: 'thread-1' };
-
- /** A page from a read path that reports no round cursor (older history unknown). */
- const asPage = (messages: UIChatMessage[]): MessageListPage => ({ messages });
-
- it('starts a fresh generation without losing loaded history or joining an older request', async () => {
- const window = [message('u2', 10, 'user')];
- const older = message('u1', 1, 'user');
- const cursor = { createdAt: new Date(10).toISOString(), id: 'u2' };
- await runMessageListQuery(context, async () => ({ messages: window, olderCursor: cursor }));
- await loadEarlierMessagePage(
- context,
- () => window,
- async () => ({
- messages: [older],
- olderCursor: null,
- }),
- );
-
- const pending = deferred<MessageListPage>();
- const staleRequest = runMessageListQuery(context, () => pending.promise);
- const reply = message('reply', 20);
- const freshQuery = vi.fn(async () => ({ messages: [...window, reply], olderCursor: cursor }));
- const freshRequest = runMessageListQuery(context, freshQuery, { force: true });
- await Promise.resolve();
- expect(freshQuery).toHaveBeenCalledTimes(1);
- pending.resolve({ messages: window, olderCursor: cursor });
-
- await expect(freshRequest).resolves.toEqual([older, ...window, reply]);
- await expect(staleRequest).resolves.toEqual([older, ...window, reply]);
- expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
- });
-
- it('fetches a page older than the oldest mainline row and returns the merged transcript', async () => {
- const window = [message('u2', 10, 'user'), message('a2', 11)];
- const fetcher = vi.fn().mockResolvedValue(asPage([message('u1', 1, 'user'), message('a1', 2)]));
-
- const merged = await loadEarlierMessagePage(threadContext, () => window, fetcher);
-
- expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10).toISOString(), id: 'u2' });
- expect(ids(merged)).toEqual(['u1', 'a1', 'u2', 'a2']);
- });
-
- it('never uses a synthetic group node as the round cursor', async () => {
- const window = [message('group-1', 5, 'compressedGroup'), message('u2', 10, 'user')];
- const fetcher = vi.fn().mockResolvedValue(asPage([message('u1', 1, 'user')]));
-
- await loadEarlierMessagePage(threadContext, () => window, fetcher);
-
- expect(fetcher).toHaveBeenCalledWith({ createdAt: new Date(10).toISOString(), id: 'u2' });
- });
-
- it('re-attaches loaded history to later revalidations of the same identity', async () => {
- const window = [message('u2', 10, 'user'), message('a2', 11)];
- await loadEarlierMessagePage(
- threadContext,
- () => window,
- async () => asPage([message('u1', 1, 'user')]),
- );
-
- const revalidated = await runMessageListQuery(threadContext, async () => window);
-
- expect(ids(revalidated)).toEqual(['u1', 'u2', 'a2']);
- });
-
- it('drops cached pages when the fresh window slid past the join point', async () => {
- const window = [message('u2', 10, 'user'), message('a2', 11)];
- await loadEarlierMessagePage(
- threadContext,
- () => window,
- async () => asPage([message('u1', 1, 'user')]),
- );
-
- // The window moved forward: u2 (the join point) fell out of it. Merging
- // would leave an invisible gap, so the transcript collapses to the window.
- const slidWindow = [message('u3', 20, 'user'), message('a3', 21)];
- const revalidated = await runMessageListQuery(threadContext, async () => slidWindow);
-
- expect(revalidated).toBe(slidWindow);
- });
-
- it('deduplicates rows the fresh window already contains', async () => {
- const window = [message('u2', 10, 'user'), message('a2', 11)];
- await loadEarlierMessagePage(
- threadContext,
- () => window,
- async () => asPage([message('u1', 1, 'user'), message('a1', 2)]),
- );
-
- // A later window that reaches further back overlaps the cached page.
- const extendedWindow = [message('a1', 2), message('u2', 10, 'user'), message('a2', 11)];
- const revalidated = await runMessageListQuery(threadContext, async () => extendedWindow);
-
- expect(ids(revalidated)).toEqual(['u1', 'a1', 'u2', 'a2']);
- });
-
- it('marks the identity exhausted only on an empty page and stops fetching', async () => {
- const window = [message('u1', 10, 'user')];
- const fetcher = vi.fn().mockResolvedValue(asPage([]));
-
- const merged = await loadEarlierMessagePage(threadContext, () => window, fetcher);
-
- expect(merged).toBeUndefined();
- expect(getEarlierHistoryStatus(threadContext).exhausted).toBe(true);
-
- await loadEarlierMessagePage(threadContext, () => window, fetcher);
- expect(fetcher).toHaveBeenCalledTimes(1);
- });
-
- it('ignores a second load while one page is in flight', async () => {
- const window = [message('u2', 10, 'user')];
- const firstPage = deferred<UIChatMessage[]>();
- const fetcher = vi.fn().mockReturnValue(firstPage.promise.then(asPage));
-
- const first = loadEarlierMessagePage(threadContext, () => window, fetcher);
- const second = await loadEarlierMessagePage(threadContext, () => window, fetcher);
-
- expect(second).toBeUndefined();
- expect(fetcher).toHaveBeenCalledTimes(1);
-
- firstPage.resolve([message('u1', 1, 'user')]);
- expect(ids(await first)).toEqual(['u1', 'u2']);
- });
+describe('window older cursor', () => {
+ it("records the cursor of the identity's latest newest-first window", async () => {
+ const cursor = { createdAt: '1970-01-01T00:00:00.010123Z', id: 'message-1' };
+ expect(getMessageListWindowOlderCursor(context)).toBeUndefined();
- it('merges the page into the latest transcript, not the one at request time', async () => {
- let current = [message('u2', 10, 'user')];
- const page = deferred<UIChatMessage[]>();
+ await runMessageListQuery(context, async () => ({ messages, olderCursor: cursor }));
+ expect(getMessageListWindowOlderCursor(context)).toEqual(cursor);
- const pending = loadEarlierMessagePage(
- threadContext,
- () => current,
- () => page.promise.then(asPage),
- );
- // A stream appends a reply while the page is in flight.
- current = [message('u2', 10, 'user'), message('a2', 11)];
- page.resolve([message('u1', 1, 'user')]);
-
- expect(ids(await pending)).toEqual(['u1', 'u2', 'a2']);
- });
-
- it('discards a page whose identity was invalidated while in flight', async () => {
- const window = [message('u2', 10, 'user')];
- const page = deferred<UIChatMessage[]>();
-
- const pending = loadEarlierMessagePage(
- threadContext,
- () => window,
- () => page.promise.then(asPage),
- );
+ // A window that reached the topic start reports `null`.
invalidateMessageListClientState(() => true);
- page.resolve([message('u1', 1, 'user')]);
-
- expect(await pending).toBeUndefined();
- const revalidated = await runMessageListQuery(threadContext, async () => window);
- expect(revalidated).toBe(window);
- });
-
- it('skips the merge when the caller no longer has a transcript to extend', async () => {
- let current: UIChatMessage[] | undefined = [message('u2', 10, 'user')];
- const page = deferred<UIChatMessage[]>();
-
- const pending = loadEarlierMessagePage(
- threadContext,
- () => current,
- () => page.promise.then(asPage),
- );
- current = undefined;
- page.resolve([message('u1', 1, 'user')]);
-
- expect(await pending).toBeUndefined();
- // The page is still remembered for the next revalidation of this identity.
- const revalidated = await runMessageListQuery(threadContext, async () => [
- message('u2', 10, 'user'),
- ]);
- expect(ids(revalidated)).toEqual(['u1', 'u2']);
- });
-
- it('clears cached history on invalidation so stale rows cannot resurrect', async () => {
- const window = [message('u2', 10, 'user')];
- await loadEarlierMessagePage(
- threadContext,
- () => window,
- async () => asPage([message('u1', 1, 'user')]),
- );
-
- invalidateMessageListClientState(() => true);
-
- const revalidated = await runMessageListQuery(threadContext, async () => window);
- expect(revalidated).toBe(window);
- });
-
- describe('with a round cursor reported by the server', () => {
- const cursorOf = (id: string, createdAt: string) => ({ createdAt, id });
-
- it('waits for the server cursor instead of deriving one on a cursor-paged topic', async () => {
- // A window restored from the persisted cache before its revalidation
- // lands carries no server cursor yet.
- const window = [message('u2', 10, 'user'), message('a2', 11)];
- const fetcher = vi.fn();
-
- expect(await loadEarlierMessagePage(context, () => window, fetcher)).toBeUndefined();
- expect(fetcher).not.toHaveBeenCalled();
- expect(getEarlierHistoryStatus(context).exhausted).toBe(false);
-
- // Once revalidation reports the lossless cursor, the next gesture pages.
- const windowCursor = cursorOf('u2', '1970-01-01T00:00:00.010123Z');
- await runMessageListQuery(context, async () => ({
- messages: window,
- olderCursor: windowCursor,
- }));
- fetcher.mockResolvedValue({ messages: [message('u1', 1, 'user')], olderCursor: null });
-
- await loadEarlierMessagePage(context, () => window, fetcher);
- expect(fetcher).toHaveBeenCalledWith(windowCursor);
- });
-
- it('never fetches when the window already holds the topic start', async () => {
- const window = [message('u1', 10, 'user'), message('a1', 11)];
- await runMessageListQuery(context, async () => ({ messages: window, olderCursor: null }));
- const fetcher = vi.fn();
-
- const merged = await loadEarlierMessagePage(context, () => window, fetcher);
-
- expect(merged).toBeUndefined();
- expect(fetcher).not.toHaveBeenCalled();
- expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
- });
-
- it("pages from the window's lossless cursor instead of the oldest row", async () => {
- const window = [message('u2', 10, 'user'), message('a2', 11)];
- const windowCursor = cursorOf('u2', '1970-01-01T00:00:00.010123Z');
- await runMessageListQuery(context, async () => ({
- messages: window,
- olderCursor: windowCursor,
- }));
- const fetcher = vi
- .fn()
- .mockResolvedValue({ messages: [message('u1', 1, 'user')], olderCursor: null });
-
- const merged = await loadEarlierMessagePage(context, () => window, fetcher);
-
- expect(fetcher).toHaveBeenCalledWith(windowCursor);
- expect(ids(merged)).toEqual(['u1', 'u2', 'a2']);
- });
-
- it('stops after the page that reached the topic start', async () => {
- const window = [message('u3', 20, 'user')];
- await runMessageListQuery(context, async () => ({
- messages: window,
- olderCursor: cursorOf('u3', '1970-01-01T00:00:00.020Z'),
- }));
- const olderCursor = cursorOf('u2', '1970-01-01T00:00:00.010Z');
- const fetcher = vi
- .fn()
- .mockResolvedValueOnce({ messages: [message('u2', 10, 'user')], olderCursor })
- .mockResolvedValueOnce({ messages: [message('u1', 1, 'user')], olderCursor: null });
-
- let current: UIChatMessage[] = window;
- current = (await loadEarlierMessagePage(context, () => current, fetcher)) ?? current;
- current = (await loadEarlierMessagePage(context, () => current, fetcher)) ?? current;
- await loadEarlierMessagePage(context, () => current, fetcher);
-
- expect(fetcher).toHaveBeenCalledTimes(2);
- expect(fetcher).toHaveBeenLastCalledWith(olderCursor);
- expect(ids(current)).toEqual(['u1', 'u2', 'u3']);
- expect(getEarlierHistoryStatus(context).exhausted).toBe(true);
- });
- });
-
- it('evicts the least-recently-used identity once the earlier-history cache is full', async () => {
- const window = [message('u2', 10, 'user')];
- const oldest = { ...threadContext, topicId: 'topic-evicted' };
- // Exhaust the first identity, then flood the cache with 30 more.
- await loadEarlierMessagePage(
- oldest,
- () => window,
- async () => asPage([]),
- );
- expect(getEarlierHistoryStatus(oldest).exhausted).toBe(true);
-
- for (let i = 0; i < 30; i++) {
- await loadEarlierMessagePage(
- { ...threadContext, topicId: `topic-fill-${i}` },
- () => window,
- async () => asPage([message('u1', 1, 'user')]),
- );
- }
-
- // The exhausted marker was evicted with the entry: the identity fetches again.
- expect(getEarlierHistoryStatus(oldest).exhausted).toBe(false);
- const fetcher = vi.fn().mockResolvedValue(asPage([]));
- await loadEarlierMessagePage(oldest, () => window, fetcher);
- expect(fetcher).toHaveBeenCalledTimes(1);
-
- // The most recent identity survives: its cached page still re-attaches.
- const survivor = { ...threadContext, topicId: 'topic-fill-29' };
- const revalidated = await runMessageListQuery(survivor, async () => window);
- expect(ids(revalidated)).toEqual(['u1', 'u2']);
+ await runMessageListQuery(context, async () => ({ messages, olderCursor: null }));
+ expect(getMessageListWindowOlderCursor(context)).toBeNull();
});
});
diff --git a/src/services/message/cache.ts b/src/services/message/cache.ts
index 0e603128a0b..c701d510f4c 100644
--- a/src/services/message/cache.ts
+++ b/src/services/message/cache.ts
@@ -79,187 +79,14 @@ const recordWindowOlderCursor = (
};
/**
- * Client-held pages of history OLDER than the server's newest-first window
- * The chat read path only ever fetches the newest round-aligned
- * page; when the user walks back past it, the older pages are fetched once via
- * a round cursor and kept here so every later revalidation of the same
- * identity re-merges them instead of collapsing the view back to the window.
+ * The older-history cursor the latest newest-first window of `context` came
+ * back with: `null` when the topic start is loaded, `undefined` when unknown
+ * (no round cursor for this read path, or no window fetched yet).
*/
-interface EarlierHistoryState {
- /**
- * The oldest mainline row of the live window when history was first
- * extended β€” the join point. A fresh window that no longer contains this id
- * has slid past the cached pages (a gap), so the cache is dropped rather
- * than merged.
- */
- anchorId: string;
- cacheScope: string;
- context: CanonicalMessageListContext;
- /** The topic start has been loaded: nothing older remains to fetch. */
- exhausted: boolean;
- loading: boolean;
- /** Ascending rows strictly older than `anchorId`. */
- messages: UIChatMessage[];
- /** Cursor for the page older than `messages`; `undefined` until a page reports one. */
- olderCursor?: MessageRoundCursor;
-}
-
-const earlierHistoryStates = new Map<string, EarlierHistoryState>();
-
-/**
- * Each entry can hold thousands of full message rows, so the cap is much
- * tighter than `MAX_MESSAGE_LIST_CLIENT_STATES`. Insertion order doubles as
- * recency: `touchEarlierHistoryState` re-appends on every merge, and pruning
- * evicts the least-recently-merged identities that are not mid-fetch.
- */
-const MAX_EARLIER_HISTORY_STATES = 30;
-
-const touchEarlierHistoryState = (identity: string, state: EarlierHistoryState) => {
- earlierHistoryStates.delete(identity);
- earlierHistoryStates.set(identity, state);
-};
-
-const pruneEarlierHistoryStates = () => {
- if (earlierHistoryStates.size <= MAX_EARLIER_HISTORY_STATES) return;
- for (const [identity, state] of earlierHistoryStates.entries()) {
- if (earlierHistoryStates.size <= MAX_EARLIER_HISTORY_STATES) return;
- if (state.loading) continue;
- earlierHistoryStates.delete(identity);
- }
-};
-
-/** Synthetic MessageGroup nodes are injected by the query, not DB rows β€” they
- * can never serve as a round cursor. */
-const isSyntheticGroupNode = (message: UIChatMessage) =>
- message.role === 'compressedGroup' || message.role === 'compareGroup';
-
-const byCreatedAtAscending = (a: UIChatMessage, b: UIChatMessage) =>
- new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
-
-const mergeEarlierHistory = (identity: string, fresh: UIChatMessage[]): UIChatMessage[] => {
- const state = earlierHistoryStates.get(identity);
- if (!state || state.messages.length === 0) return fresh;
-
- if (!fresh.some((message) => message.id === state.anchorId)) {
- // The window slid past the join point β€” merging would hide an invisible
- // gap in the middle of the transcript. Collapse back to the window; the
- // user can walk back again from the new boundary.
- earlierHistoryStates.delete(identity);
- return fresh;
- }
-
- const freshIds = new Set(fresh.map((message) => message.id));
- const prefix = state.messages.filter((message) => !freshIds.has(message.id));
- touchEarlierHistoryState(identity, state);
- // Stable sort: group nodes carried by the fresh window can predate the whole
- // prefix, and rows inside each list keep their relative order.
- return [...prefix, ...fresh].sort(byCreatedAtAscending);
-};
-
-/**
- * Where the next older page starts: the last loaded page's cursor once history
- * was extended, otherwise the window's. `null` β†’ the start is loaded;
- * `undefined` β†’ unknown, derive it from the oldest loaded row.
- */
-const resolveOlderCursor = (
- identity: string,
- state: EarlierHistoryState | undefined,
-): MessageRoundCursor | null | undefined =>
- state && state.messages.length > 0 ? state.olderCursor : windowOlderCursors.get(identity);
-
-export const getEarlierHistoryStatus = (context: MessageListQueryContext) => {
- const identity = getMessageListCacheIdentity(context);
- const state = earlierHistoryStates.get(identity);
- return {
- exhausted: (state?.exhausted ?? false) || resolveOlderCursor(identity, state) === null,
- loading: state?.loading ?? false,
- };
-};
-
-/**
- * Fetch one round-aligned page of history older than the oldest mainline row
- * of `getCurrentMessages()`, remember it for future revalidation merges, and
- * return the full merged transcript β€” or `undefined` when there is nothing to
- * apply (no cursor, already loading, the beginning was reached, or the request
- * went stale while in flight).
- *
- * `getCurrentMessages` is read twice: once for the cursor, and again AFTER the
- * page arrives so the merge lands on the latest transcript rather than a
- * snapshot taken before the await (a stream or an edit may have changed it
- * meanwhile). Return `undefined` from it to skip the merge, e.g. after the
- * caller switched conversations; the page itself is still cached.
- */
-export const loadEarlierMessagePage = async (
+export const getMessageListWindowOlderCursor = (
context: MessageListQueryContext,
- getCurrentMessages: () => UIChatMessage[] | undefined,
- fetcher: (cursor: MessageRoundCursor) => Promise<MessageListPage>,
-): Promise<UIChatMessage[] | undefined> => {
- const identity = getMessageListCacheIdentity(context);
- const existing = earlierHistoryStates.get(identity);
- if (existing?.exhausted || existing?.loading) return undefined;
-
- const knownCursor = resolveOlderCursor(identity, existing);
- // The window (or the last page) already reached the topic start.
- if (knownCursor === null) return undefined;
- // A cursor-paged conversation shown from the persisted cache before its
- // revalidation lands has no server cursor yet. A cursor rebuilt from the
- // oldest row's millisecond `createdAt` would skip older rows sharing that
- // millisecond, so wait for the window's lossless cursor instead; the next
- // upward gesture after revalidation pages normally.
- if (knownCursor === undefined && supportsRoundCursor(context)) return undefined;
-
- const oldest = getCurrentMessages()?.find((message) => !isSyntheticGroupNode(message));
- if (!oldest) return undefined;
-
- // A read path without round cursors: page from the oldest loaded row.
- const cursor = knownCursor ?? {
- createdAt: new Date(oldest.createdAt).toISOString(),
- id: oldest.id,
- };
-
- const state: EarlierHistoryState = existing ?? {
- anchorId: oldest.id,
- cacheScope: getCacheScope(),
- context: normalizeMessageListQueryContext(context),
- exhausted: false,
- loading: false,
- messages: [],
- };
- state.loading = true;
- touchEarlierHistoryState(identity, state);
- pruneEarlierHistoryStates();
-
- try {
- const { messages: page, olderCursor } = await fetcher(cursor);
-
- // An invalidation (edit/delete refresh) dropped this identity while the
- // page was in flight: its rows may be exactly what changed, so discard it.
- if (earlierHistoryStates.get(identity) !== state) return undefined;
-
- // Without a reported cursor, `length < pageSize` is NOT a reliable end
- // signal β€” the round-start trim legitimately shortens full pages β€” so only
- // an empty page marks the top.
- if (page.length === 0 || olderCursor === null) state.exhausted = true;
- state.olderCursor = olderCursor ?? undefined;
- if (page.length === 0) return undefined;
-
- const pageIds = new Set(page.map((message) => message.id));
- state.messages = [
- ...page,
- ...state.messages.filter((message) => !pageIds.has(message.id)),
- ].sort(byCreatedAtAscending);
-
- const latest = getCurrentMessages();
- if (!latest) return undefined;
-
- const merged = mergeEarlierHistory(identity, latest);
- // No join point in the latest transcript (it slid or was replaced): there
- // is nothing to prepend, and returning `latest` would only echo it back.
- return merged === latest ? undefined : merged;
- } finally {
- state.loading = false;
- }
-};
+): MessageRoundCursor | null | undefined =>
+ windowOlderCursors.get(getMessageListCacheIdentity(context));
export const messageListKey = (context: MessageListQueryContext) => messageKeys.list(context);
@@ -375,10 +202,7 @@ const startCurrentGenerationQuery = (
state.verifiedAt = Date.now();
touchState(state);
pruneClientStates();
- // Re-attach client-held older history (loaded via round cursor) so a
- // revalidation doesn't collapse an extended transcript back to the
- // newest-first window.
- return mergeEarlierHistory(state.identity, messages);
+ return messages;
})
.finally(() => {
state.activeRequestGenerations.delete(requestGeneration);
@@ -434,19 +258,9 @@ export const invalidateMessageListClientState = (
state.generation += 1;
state.verifiedAt = undefined;
}
-
- // A force refresh signals the persisted rows may have changed (edits or
- // deletes can target rounds inside the extended range). Cached older pages
- // could resurrect stale rows through the merge, so drop them; the user can
- // walk back again from the refreshed window.
- for (const [identity, state] of earlierHistoryStates.entries()) {
- if (state.cacheScope !== cacheScope || !predicate(state.context)) continue;
- earlierHistoryStates.delete(identity);
- }
};
export const clearMessageListClientCacheState = () => {
messageListClientStates.clear();
- earlierHistoryStates.clear();
windowOlderCursors.clear();
};
diff --git a/src/services/message/replica.ts b/src/services/message/replica.ts
new file mode 100644
index 00000000000..6e8880be7af
--- /dev/null
+++ b/src/services/message/replica.ts
@@ -0,0 +1,176 @@
+import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+
+import {
+ defineReplica,
+ type ReplicaPagedData,
+ type ReplicaPageResult,
+ type ReplicaPagingConfig,
+ ReplicaWriteQueue,
+} from '@/libs/replica';
+import { normalizeMessageListQueryContext } from '@/libs/swr/keys';
+import {
+ getMessageListWindowOlderCursor,
+ messageListKey,
+ type MessageRoundCursor,
+} from '@/services/message/cache';
+import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+/** A conversation transcript as the replica keeps it: rows oldest-first, plus paging bookkeeping. */
+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.
+ */
+export type ConversationMessageFetch =
+ UIChatMessage[] | ReplicaPageResult<UIChatMessage, MessageRoundCursor>;
+
+/** What a transcript sync is asked for: the conversation, plus how its head is read. */
+export interface ConversationMessageParams extends ConversationContext {
+ /** Re-read the head after a parked intervention run completes (main topics only). */
+ syncInterventions?: boolean;
+}
+
+/** Synthetic MessageGroup nodes are injected by the query, not DB rows. */
+const isSyntheticGroupNode = (message: UIChatMessage) =>
+ message.role === 'compressedGroup' || message.role === 'compareGroup';
+
+/**
+ * Whether a transcript may survive a reload. Shared views read through
+ * share-authorized endpoints and are not the viewer's data; scoped buckets
+ * (page copilot `documentId`, group-agent `subAgentId`, `isNew`) carry a
+ * discriminator the canonical read drops, so persisting them would store the
+ * scoped transcript under the ordinary conversation.
+ */
+const isPersistableContext = (context: ConversationContext) => {
+ if (!context.agentId || !context.topicId) return false;
+ if (context.agentShareId || context.topicShareId) return false;
+ const canonical = messageMapKey({
+ agentId: context.agentId,
+ groupId: context.groupId,
+ scope: context.threadId ? 'thread' : context.groupId ? 'group' : 'main',
+ threadId: context.threadId,
+ topicId: context.topicId,
+ });
+ return messageMapKey(context) === canonical;
+};
+
+/**
+ * Entry identity of a conversation. Persistable conversations key by the
+ * canonical read context (`p:`), so the route loader and every surface showing
+ * the same conversation address one row; the rest key by their bucket (`m:`)
+ * and stay in memory.
+ */
+export const conversationMessagesKey = (context: ConversationContext) =>
+ isPersistableContext(context)
+ ? `p:${JSON.stringify(normalizeMessageListQueryContext(context))}`
+ : `m:${messageMapKey(context)}`;
+
+const transcriptPaging: ReplicaPagingConfig<UIChatMessage, MessageRoundCursor> = {
+ // Only reached for read paths without round cursors (threads, shared
+ // views): main topics always report the window's lossless cursor.
+ deriveCursor: (message) => ({
+ createdAt: new Date(message.createdAt).toISOString(),
+ id: message.id,
+ }),
+ direction: 'backward',
+ getId: (message) => message.id,
+ isCursorable: (message) => !isSyntheticGroupNode(message) && !isLocalOnlyMessage(message),
+ mode: 'cursor',
+ // The newest window survives a reload; older history is fetched again.
+ persist: { pages: 1 },
+};
+
+export const conversationMessagesResource = defineReplica<
+ ConversationMessageParams,
+ ConversationMessagePage,
+ ConversationMessageFetch
+>({
+ key: conversationMessagesKey,
+ name: 'conversationMessages',
+ 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,
+});
+
+/** 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;
+ return { ...data, items: data.items.filter((message) => !isLocalOnlyMessage(message)) };
+};
+
+/**
+ * A transcript value for rows that arrived without paging bookkeeping. Whether
+ * older history exists is unknown, so it is assumed until an empty page says
+ * otherwise.
+ */
+export const transcriptOf = (items: UIChatMessage[]): ConversationMessagePage => ({
+ currentPage: 0,
+ hasMore: items.length > 0,
+ items,
+ pageSize: items.length,
+});
+
+/**
+ * The transcript persisted for a conversation, read without a store β€” for the
+ * route loader, which runs before any Conversation store exists. `undefined`
+ * when the conversation is kept in memory only or nothing is stored.
+ */
+export const readPersistedTranscript = async (
+ context: ConversationContext,
+): Promise<ConversationMessagePage | undefined> => {
+ const { persistKey, scope, storage, storageKey } = conversationMessagesResource;
+ if (!storage || !persistKey(conversationMessagesKey(context))) return undefined;
+ const row = await storage.get({ queryKey: storageKey(context), scope: scope.get() });
+ return row?.data;
+};
+
+// Terminal host updates also arrive for conversations whose component has unmounted.
+const settledTranscriptWrites = new ReplicaWriteQueue(conversationMessagesResource.storage!);
+
+export const persistSettledTranscript = (
+ context: ConversationContext,
+ messages: UIChatMessage[],
+) => {
+ const resource = conversationMessagesResource;
+ const scope = resource.scope.get();
+ if (!resource.scope.canPersist() || !resource.persistKey(resource.key(context))) return;
+ const cursor = getMessageListWindowOlderCursor(context);
+ settledTranscriptWrites.update({ queryKey: resource.storageKey(context), scope }, (current) => {
+ const previous = current?.data;
+ const cursorBoundary = cursor ? messages.findIndex((message) => message.id === cursor.id) : -1;
+ // Threads have no round cursor. The persisted projection still identifies
+ // their head window, including synthetic nodes sorted before its first row.
+ const previousIds = new Set(
+ previous?.items.filter((item) => !isSyntheticGroupNode(item)).map((item) => item.id),
+ );
+ const boundary =
+ cursorBoundary >= 0 ? cursorBoundary : messages.findIndex((item) => previousIds.has(item.id));
+ const syntheticIds = new Set(
+ previous?.items.filter(isSyntheticGroupNode).map((item) => item.id),
+ );
+ const head =
+ cursor === null
+ ? messages
+ : boundary >= 0
+ ? messages.filter((item, index) => index >= boundary || syntheticIds.has(item.id))
+ : previous
+ ? messages.slice(-previous.items.length)
+ : messages;
+ const data = transcriptOf(head);
+ if (cursor === null || cursorBoundary >= 0) {
+ data.nextCursor = cursor;
+ data.hasMore = cursor !== null;
+ } else if (boundary >= 0 && previous?.items[0]?.id === messages[boundary]?.id) {
+ data.nextCursor = previous.nextCursor;
+ data.hasMore = previous.hasMore;
+ }
+ return { data: toPersistedTranscript(data), updatedAt: Date.now() };
+ });
+};
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index e21e8a1865b..9293d4e1c45 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -1,10 +1,11 @@
import { type UIChatMessage } from '@lobechat/types';
import { TraceEventType } from '@lobechat/types';
import { copyToClipboard } from '@lobehub/ui';
-import { act, renderHook } from '@testing-library/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
import { type Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cacheScope } from '@/libs/replica';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { messageService } from '@/services/message';
import {
@@ -13,6 +14,7 @@ import {
messageListKey,
runMessageListQuery,
} from '@/services/message/cache';
+import { conversationMessagesKey, conversationMessagesResource } from '@/services/message/replica';
import { topicService } from '@/services/topic';
import { LOCAL_MESSAGE_SCOPE } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -1290,6 +1292,73 @@ describe('chatMessage actions', () => {
});
describe('replaceMessages cache write-through', () => {
+ it('persists a finished background topic under its own context', async () => {
+ vi.spyOn(conversationMessagesResource.storage!, 'get').mockResolvedValue(undefined);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const storageSet = vi.spyOn(conversationMessagesResource.storage!, 'set').mockResolvedValue();
+ const context = { agentId: 'background-agent', topicId: 'background-topic' };
+ useChatStore.setState({ activeAgentId: context.agentId, activeTopicId: 'visible-topic' });
+ const operationId = useChatStore
+ .getState()
+ .startOperation({ type: 'execAgentRuntime', context }).operationId;
+ const messages = [
+ { id: 'background-message', role: 'assistant', content: 'finished' },
+ ] as UIChatMessage[];
+ useChatStore.getState().replaceMessages(messages, { context });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storageSet).not.toHaveBeenCalled();
+ // Gateway applies its terminal snapshot before marking the operation complete.
+ useChatStore.getState().completeOperation(operationId);
+ await waitFor(() =>
+ expect(storageSet).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: conversationMessagesKey(context) }),
+ expect.objectContaining({ data: expect.objectContaining({ items: messages }) }),
+ ),
+ );
+ expect(
+ storageSet.mock.calls.every(
+ ([key]) =>
+ key.queryKey !== conversationMessagesKey({ ...context, topicId: 'visible-topic' }),
+ ),
+ ).toBe(true);
+ });
+
+ it('keeps only the persisted thread head when a run settles after loading older pages', async () => {
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ const context = {
+ agentId: 'thread-agent',
+ topicId: 'thread-topic',
+ threadId: 'thread-id',
+ scope: 'thread' as const,
+ };
+ const older = { id: 'older', role: 'user', content: 'older history' } as UIChatMessage;
+ const head = { id: 'head', role: 'user', content: 'latest question' } as UIChatMessage;
+ const reply = { id: 'reply', role: 'assistant', content: 'finished' } as UIChatMessage;
+ vi.spyOn(conversationMessagesResource.storage!, 'get').mockResolvedValue({
+ data: { currentPage: 0, hasMore: true, items: [head], pageSize: 1 },
+ updatedAt: 1,
+ });
+ const storageSet = vi.spyOn(conversationMessagesResource.storage!, 'set').mockResolvedValue();
+ useChatStore.setState({
+ activeAgentId: context.agentId,
+ activeTopicId: context.topicId,
+ activeThreadId: context.threadId,
+ });
+ const { operationId } = useChatStore
+ .getState()
+ .startOperation({ type: 'execAgentRuntime', context });
+ useChatStore.getState().replaceMessages([older, head, reply], { context });
+ useChatStore.getState().completeOperation(operationId);
+ await waitFor(() =>
+ expect(storageSet).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: conversationMessagesKey(context) }),
+ expect.objectContaining({
+ data: expect.objectContaining({ items: [head, reply], currentPage: 0 }),
+ }),
+ ),
+ );
+ });
+
beforeEach(() => {
(mutate as Mock).mockClear();
});
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index a7e97e0cf15..8abb3afd8d3 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -15,6 +15,7 @@ import {
messageListKey,
runMessageListQuery,
} from '@/services/message/cache';
+import { persistSettledTranscript } from '@/services/message/replica';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { type ChatStore } from '@/store/chat/store';
import {
@@ -331,6 +332,14 @@ export class MessageQueryActionImpl {
// A concrete canonical key creates the cache entry even when no subscriber
// has mounted yet, which lets a later conversation switch render locally.
void mutate(messageListKey(ctx), messages, { revalidate: false });
+ const active = this.#get();
+ if (
+ ctx.agentId !== active.activeAgentId ||
+ ctx.topicId !== active.activeTopicId ||
+ (ctx.threadId ?? null) !== (active.activeThreadId ?? null)
+ ) {
+ persistSettledTranscript({ ...ctx, agentId: ctx.agentId, topicId: ctx.topicId }, messages);
+ }
};
useFetchMessages = (
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index dc27f658751..f006faaf64a 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -2,6 +2,7 @@ import { nanoid } from '@lobechat/utils';
import debug from 'debug';
import { produce } from 'immer';
+import { persistSettledTranscript } from '@/services/message/replica';
import { type ChatStore } from '@/store/chat/store';
import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -10,6 +11,7 @@ import { getHomeStoreState } from '@/store/home';
import { type StoreSetter } from '@/store/types';
import { setNamespace } from '@/utils/storeDebug';
+import { operationSelectors } from './selectors';
import {
type AfterCompletionCallback,
AI_RUNTIME_OPERATION_TYPES,
@@ -318,6 +320,24 @@ export class OperationActionsImpl {
false,
n(`completeOperation/${operationId}`),
);
+
+ if (
+ operation &&
+ AI_RUNTIME_OPERATION_TYPES.includes(operation.type) &&
+ operation.status !== 'completed'
+ ) {
+ const state = this.#get();
+ const { agentId, topicId } = operation.context;
+ if (!agentId || !topicId) return;
+ // A run that finishes after the user switched away must still persist to
+ // its own conversation, so rebuild the operation's context with a definite
+ // agent/topic: `OperationContext` exposes them as optional, but the runtime
+ // check, the message key and the persist call all need a concrete agentId.
+ const context = { ...operation.context, agentId, topicId };
+ if (operationSelectors.isAgentRuntimeRunningByContext(context)(state)) return;
+ const messages = state.dbMessagesMap[messageMapKey(context)];
+ if (messages) persistSettledTranscript(context, messages);
+ }
};
getOperationAbortSignal = (operationId: string): AbortSignal => {