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.

⚡️ perf(conversation): persist projected tool result payloads through a replica (#20843)

Arvin Xu04f441395913
diff --git a/src/hooks/useToolResultPayload.test.ts b/src/hooks/useToolResultPayload.test.ts
new file mode 100644
index 00000000000..34ba9d5aced
--- /dev/null
+++ b/src/hooks/useToolResultPayload.test.ts
@@ -0,0 +1,181 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * Projected tool payloads are a replica keyed by message id: after a reload the
+ * card paints the persisted body on the first frame and the read confirms it.
+ */
+import { randomUUID } from 'node:crypto';
+
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, unstable_serialize, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, replicaKeys } from '@/libs/replica';
+import { CACHE_TIERS } from '@/libs/swr/localStorageProvider';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { messageService } from '@/services/message';
+import {
+ TOOL_RESULT_PAYLOAD_MAX_PERSISTED_CHARS,
+ TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES,
+ toolResultPayloadResource,
+} from '@/services/message/replica';
+import {
+ initialToolResultPayloadState,
+ useToolResultPayloadStore,
+} from '@/store/toolResultPayload/store';
+
+import { useToolResultPayload } from './useToolResultPayload';
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+/** Never-resolving read: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const storage = toolResultPayloadResource.storage!;
+
+describe('useToolResultPayload replica', () => {
+ const scopes = new Set<string>();
+ const ids = new Set<string>();
+ let scope = '';
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+ const rowKey = (messageId: string, inScope = scope) => {
+ ids.add(messageId);
+ return { queryKey: toolResultPayloadResource.storageKey(messageId), scope: inScope };
+ };
+ /** A fresh session: empty memory, same IndexedDB. */
+ const reload = () => act(() => useToolResultPayloadStore.setState(initialToolResultPayloadState));
+
+ beforeEach(() => {
+ useScope(`tool-payload-user-${randomUUID()}:personal`);
+ reload();
+ });
+
+ afterEach(async () => {
+ await Promise.all(
+ [...scopes].flatMap((value) => [...ids].map((id) => storage.remove(rowKey(id, value)))),
+ );
+ scopes.clear();
+ ids.clear();
+ vi.restoreAllMocks();
+ });
+
+ // Regression: the payload lived only in SWR's memory cache, so after a reload
+ // opening the card showed the payload skeleton until the read returned.
+ it('paints the persisted payload after a reload, then revalidates', async () => {
+ const cached = { content: '# page body v1', pluginState: { url: 'https://example.com' } };
+ await storage.set(rowKey('msg-1'), { data: { value: cached as any }, updatedAt: 1 });
+
+ let resolveFresh!: (value: any) => void;
+ const fetch = vi
+ .spyOn(messageService, 'getToolResultPayload')
+ .mockReturnValue(new Promise((resolve) => (resolveFresh = resolve)));
+
+ const { result } = renderHook(() => useToolResultPayload('msg-1', true), { wrapper });
+
+ await waitFor(() => expect(result.current).toEqual({ isLoading: false, payload: cached }));
+ expect(fetch).toHaveBeenCalledWith('msg-1');
+
+ const fresh = { content: '# page body v2' };
+ await act(async () => resolveFresh(fresh));
+ await waitFor(() => expect(result.current.payload).toEqual(fresh));
+ });
+
+ it('persists a fetched payload so the next session paints it without the network', async () => {
+ const payload = { content: 'scraped body', pluginState: { status: 'ok' } };
+ vi.spyOn(messageService, 'getToolResultPayload').mockResolvedValue(payload as any);
+ const first = renderHook(() => useToolResultPayload('msg-2', true), { wrapper });
+ await waitFor(() => expect(first.result.current.payload).toEqual(payload));
+ await waitFor(async () =>
+ expect((await storage.get(rowKey('msg-2')))?.data).toEqual({ value: payload }),
+ );
+ first.unmount();
+
+ reload();
+ vi.spyOn(messageService, 'getToolResultPayload').mockImplementation(pending);
+ const second = renderHook(() => useToolResultPayload('msg-2', true), { wrapper });
+ await waitFor(() => expect(second.result.current).toEqual({ isLoading: false, payload }));
+ });
+
+ it('shows the loading state and fetches nothing until enabled', async () => {
+ const fetch = vi.spyOn(messageService, 'getToolResultPayload').mockImplementation(pending);
+ const { result, rerender } = renderHook(
+ ({ enabled }) => useToolResultPayload('msg-3', enabled),
+ { initialProps: { enabled: false }, wrapper },
+ );
+ expect(result.current).toEqual({ isLoading: false, payload: undefined });
+ expect(fetch).not.toHaveBeenCalled();
+
+ rerender({ enabled: true });
+ await waitFor(() => expect(fetch).toHaveBeenCalledWith('msg-3'));
+ expect(result.current.isLoading).toBe(true);
+ });
+
+ it('keeps payloads over the size cap in memory only and drops an older row', async () => {
+ await storage.set(rowKey('msg-big'), { data: { value: { content: 'old' } }, updatedAt: 1 });
+ const huge = { content: 'x'.repeat(TOOL_RESULT_PAYLOAD_MAX_PERSISTED_CHARS + 1) };
+ vi.spyOn(messageService, 'getToolResultPayload').mockResolvedValue(huge as any);
+
+ const { result } = renderHook(() => useToolResultPayload('msg-big', true), { wrapper });
+ await waitFor(() => expect(result.current.payload).toEqual(huge));
+ await waitFor(async () => expect(await storage.get(rowKey('msg-big'))).toBeUndefined());
+ });
+
+ it('never paints another identity’s payload', async () => {
+ await storage.set(rowKey('msg-4'), { data: { value: { content: 'mine' } }, updatedAt: 1 });
+ useScope(`tool-payload-other-${randomUUID()}:personal`);
+ vi.spyOn(messageService, 'getToolResultPayload').mockImplementation(pending);
+
+ const { result } = renderHook(() => useToolResultPayload('msg-4', true), { wrapper });
+ await waitFor(() => expect(result.current.isLoading).toBe(true));
+ expect(result.current.payload).toBeUndefined();
+ });
+
+ it('evicts the least recently opened payload past the entry cap', async () => {
+ vi.spyOn(messageService, 'getToolResultPayload').mockImplementation(
+ async (id) => ({ content: `body of ${id}` }) as any,
+ );
+ const slice = useToolResultPayloadStore.getState().payload;
+ const total = TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES + 1;
+ for (let i = 0; i < total; i++) {
+ ids.add(`msg-lru-${i}`);
+ await slice.fetch(`msg-lru-${i}`);
+ }
+
+ await waitFor(async () => {
+ expect(await storage.get(rowKey('msg-lru-0'))).toBeUndefined();
+ expect(await storage.get(rowKey(`msg-lru-${total - 1}`))).toBeDefined();
+ });
+ expect(await storage.get(rowKey('msg-lru-1'))).toBeDefined();
+ });
+
+ it('is bounded, and its network read is not persisted again by the SWR cache', () => {
+ expect(toolResultPayloadResource.maxPersistedEntries).toBe(
+ TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES,
+ );
+ const syncKey = unstable_serialize(
+ replicaKeys.sync(toolResultPayloadResource.name, 1, scope, 'msg_abc', 'msg_abc'),
+ );
+ const tiers: string[] = [...CACHE_TIERS.idb, ...CACHE_TIERS.local];
+ expect(tiers.filter((pattern) => syncKey.includes(pattern))).toEqual([]);
+ });
+});
diff --git a/src/hooks/useToolResultPayload.ts b/src/hooks/useToolResultPayload.ts
index aa571962cc1..e19da61d603 100644
--- a/src/hooks/useToolResultPayload.ts
+++ b/src/hooks/useToolResultPayload.ts
@@ -1,6 +1,4 @@
-import useSWR from 'swr';
-
-import { messageService } from '@/services/message';
+import { useToolResultPayloadStore } from '@/store/toolResultPayload/store';
/**
* Fetch the stored tool payload for a message the read path projected.
@@ -9,13 +7,22 @@ import { messageService } from '@/services/message';
* raw viewer. Tying it to render instead would pull every omitted payload back
* down as soon as a conversation loads, which is the exact cost the projection
* exists to avoid.
+ *
+ * The payload is a replica keyed by message id (`toolResultPayloadResource`),
+ * so after a reload the card paints the persisted copy at once and the read
+ * confirms it behind it.
*/
export const useToolResultPayload = (messageId: string | undefined, enabled: boolean) => {
- const { data, isLoading } = useSWR(
- enabled && messageId ? ['toolResultPayload', messageId] : null,
- ([, id]: [string, string]) => messageService.getToolResultPayload(id),
- { revalidateOnFocus: false },
+ const params = enabled && messageId ? messageId : null;
+ const stored = useToolResultPayloadStore((s) =>
+ params ? s.toolResultPayloadMap[params] : undefined,
);
+ const { error, isHydrated, isValidating } = useToolResultPayloadStore
+ .getState()
+ .payload.useSync(params, { revalidateOnFocus: false });
- return { isLoading: enabled && isLoading, payload: data };
+ return {
+ isLoading: !!params && stored === undefined && !error && (!isHydrated || isValidating),
+ payload: stored?.value,
+ };
};
diff --git a/src/services/message/replica.ts b/src/services/message/replica.ts
index 6e8880be7af..e3a2114e99b 100644
--- a/src/services/message/replica.ts
+++ b/src/services/message/replica.ts
@@ -1,13 +1,19 @@
import type { ConversationContext, UIChatMessage } from '@lobechat/types';
+import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';
import {
defineReplica,
+ REPLICA_INDEX_KEY,
type ReplicaPagedData,
type ReplicaPageResult,
type ReplicaPagingConfig,
+ type ReplicaRow,
+ type ReplicaRowKey,
+ type ReplicaStorage,
ReplicaWriteQueue,
} from '@/libs/replica';
import { normalizeMessageListQueryContext } from '@/libs/swr/keys';
+import type { MessageService } from '@/services/message';
import {
getMessageListWindowOlderCursor,
messageListKey,
@@ -174,3 +180,84 @@ export const persistSettledTranscript = (
return { data: toPersistedTranscript(data), updatedAt: Date.now() };
});
};
+
+// ---- tool result payloads ------------------------------------------------
+
+/**
+ * The stored body of one tool message the conversation read projected away
+ * (`payloadOmitted`), fetched back when the user opens the card. `value` is
+ * wrapped so an answered-but-empty payload still replaces a stale row.
+ */
+export interface ToolResultPayloadRead {
+ value?: ToolResultPayload;
+}
+
+export type ToolResultPayload = Awaited<ReturnType<MessageService['getToolResultPayload']>>;
+
+/**
+ * Rows larger than this stay in memory only: a single tool result can be
+ * megabytes (a page scrape, a long log), and a reload refetching that one is
+ * cheaper than keeping it on disk.
+ */
+export const TOOL_RESULT_PAYLOAD_MAX_PERSISTED_CHARS = 128 * 1024;
+
+/** Recently opened payloads that survive a reload; older rows are evicted LRU. */
+export const TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES = 200;
+
+const TOOL_RESULT_PAYLOAD_NAME = 'toolResultPayload';
+const TOOL_RESULT_PAYLOAD_VERSION = 1;
+
+const serializedLength = (value: unknown) => {
+ try {
+ return JSON.stringify(value)?.length ?? 0;
+ } catch {
+ return Infinity;
+ }
+};
+
+/**
+ * IndexedDB storage that refuses oversized payload rows: the write becomes a
+ * delete, so neither the large body nor an older copy of it hydrates later.
+ * The engine's own index row passes through untouched.
+ */
+export class SizeCappedPayloadStorage implements ReplicaStorage<ToolResultPayloadRead> {
+ readonly #inner: ReplicaStorage<ToolResultPayloadRead>;
+ readonly #maxChars: number;
+
+ constructor(inner: ReplicaStorage<ToolResultPayloadRead>, maxChars: number) {
+ this.#inner = inner;
+ this.#maxChars = maxChars;
+ }
+
+ get = (key: ReplicaRowKey) => this.#inner.get(key);
+
+ getStrict = (key: ReplicaRowKey) =>
+ this.#inner.getStrict ? this.#inner.getStrict(key) : this.#inner.get(key);
+
+ remove = (key: ReplicaRowKey) => this.#inner.remove(key);
+
+ set = (key: ReplicaRowKey, row: ReplicaRow<ToolResultPayloadRead>) => {
+ if (key.queryKey !== REPLICA_INDEX_KEY && serializedLength(row.data) > this.#maxChars)
+ return this.#inner.remove(key);
+ return this.#inner.set(key, row);
+ };
+}
+
+/**
+ * Projected tool payloads by message id. Immutable per message, so after a
+ * reload the card paints the persisted copy and the read only confirms it.
+ * Partitioned by the cache scope (user + workspace), bounded by count and by
+ * row size.
+ */
+export const toolResultPayloadResource = defineReplica<string, ToolResultPayloadRead>({
+ key: (messageId) => messageId,
+ name: TOOL_RESULT_PAYLOAD_NAME,
+ persist: { maxEntries: TOOL_RESULT_PAYLOAD_MAX_PERSISTED_ENTRIES },
+ storage: new SizeCappedPayloadStorage(
+ new IndexedDBQueryProjectionStorage<ToolResultPayloadRead>({
+ namespace: `replica:${TOOL_RESULT_PAYLOAD_NAME}:v${TOOL_RESULT_PAYLOAD_VERSION}`,
+ }),
+ TOOL_RESULT_PAYLOAD_MAX_PERSISTED_CHARS,
+ ),
+ version: TOOL_RESULT_PAYLOAD_VERSION,
+});
diff --git a/src/store/toolResultPayload/store.ts b/src/store/toolResultPayload/store.ts
new file mode 100644
index 00000000000..734686c3ff9
--- /dev/null
+++ b/src/store/toolResultPayload/store.ts
@@ -0,0 +1,56 @@
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+} from '@/libs/replica';
+import { messageService } from '@/services/message';
+import { type ToolResultPayloadRead, toolResultPayloadResource } from '@/services/message/replica';
+import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
+
+export interface ToolResultPayloadStoreState {
+ /** Message id → the projected tool payload fetched back for it. */
+ toolResultPayloadMap: Record<string, ToolResultPayloadRead>;
+ toolResultPayloadReplica: ReplicaState<ToolResultPayloadRead>;
+}
+
+export const initialToolResultPayloadState: ToolResultPayloadStoreState = {
+ toolResultPayloadMap: {},
+ toolResultPayloadReplica: createReplicaState(),
+};
+
+const createPayloadSlice = (
+ set: (partial: Partial<ToolResultPayloadStore>, replace?: false, action?: any) => void,
+ get: () => ToolResultPayloadStore,
+) =>
+ createReplicaSlice(toolResultPayloadResource, {
+ actionPrefix: 'toolResultPayload',
+ fetcher: async (messageId: string) => ({
+ value: await messageService.getToolResultPayload(messageId),
+ }),
+ get,
+ set,
+ stateKey: 'toolResultPayloadReplica',
+ view: recordLens<ToolResultPayloadStore, ToolResultPayloadRead>('toolResultPayloadMap'),
+ });
+
+export interface ToolResultPayloadStore extends ToolResultPayloadStoreState {
+ /** @internal The replica slice; read through `useToolResultPayload`. */
+ payload: ReturnType<typeof createPayloadSlice>;
+}
+
+const devtools = createDevtools('toolResultPayload');
+
+export const useToolResultPayloadStore = createWithEqualityFn<ToolResultPayloadStore>()(
+ devtools((set, get) => ({
+ ...initialToolResultPayloadState,
+ payload: createPayloadSlice(set, get),
+ })),
+ shallow,
+);
+
+expose('toolResultPayload', useToolResultPayloadStore);