Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: harden pending topic status reconciliation (#19747)

YuTengjingd3435f999199
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index f7d297278d2..76b6e2d02f4 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -98,6 +98,8 @@ type TopicPatchScope = {
scope?: TopicMapScope;
};
+type PendingTopicStatusSource = 'cache' | 'server';
+
/**
* Options for switchTopic action
*/
@@ -717,7 +719,7 @@ export class ChatTopicActionImpl {
* Returns the row to trust: the fetched one, or the fetched one with the
* pending status re-applied when it predates the write.
*/
- #applyPendingStatusWrite = (item: ChatTopic, confirmMatchingStatus = true): ChatTopic => {
+ #applyPendingStatusWrite = (item: ChatTopic, source: PendingTopicStatusSource): ChatTopic => {
const pending = this.#pendingTopicStatusWrites.get(item.id);
if (!pending) return item;
if (pending.expiresAt <= Date.now()) {
@@ -725,7 +727,7 @@ export class ChatTopicActionImpl {
return item;
}
if (item.status === pending.status) {
- if (confirmMatchingStatus) this.#pendingTopicStatusWrites.delete(item.id);
+ if (source === 'server') this.#pendingTopicStatusWrites.delete(item.id);
return item;
}
return { ...item, status: pending.status };
@@ -740,21 +742,24 @@ export class ChatTopicActionImpl {
* the sidebar restores that stale spinner. This step deliberately
* handles statuses only; client-only optimistic rows are still added later by
* {@link #reconcileFetchedTopics} and never enter the persisted response.
+ * Persisting the pin also means a failed write can survive until the next
+ * successful revalidation; that bounded, self-healing window is preferable to
+ * reintroducing an older response after a confirmed local terminal event.
*/
#applyPendingStatusWrites = (
items: ChatTopic[],
- options?: { confirmMatchingStatus?: boolean },
+ source: PendingTopicStatusSource,
): ChatTopic[] => {
if (this.#pendingTopicStatusWrites.size === 0) return items;
- return items.map((item) => this.#applyPendingStatusWrite(item, options?.confirmMatchingStatus));
+ return items.map((item) => this.#applyPendingStatusWrite(item, source));
};
#reconcileFetchedTopics = (
items: ChatTopic[],
- currentItems?: ChatTopic[],
- options?: { confirmMatchingStatus?: boolean },
+ currentItems: ChatTopic[] | undefined,
+ source: PendingTopicStatusSource,
): ChatTopic[] => {
- let next = this.#applyPendingStatusWrites(items, options);
+ let next = this.#applyPendingStatusWrites(items, source);
// In-flight first-send optimistic rows are client-only, so any refetch
// landing mid-send (e.g. the fire-and-forget refreshTopic after a previous
@@ -1068,7 +1073,7 @@ export class ChatTopicActionImpl {
// (the button reading as a no-op until pressed a second time). The pin is
// dropped when the persist fails, so a write that never reached the DB
// still reverts here.
- const fresh = this.#applyPendingStatusWrite(fetched);
+ const fresh = this.#applyPendingStatusWrite(fetched, 'server');
if (fresh.status !== fetched.status) return false;
// Server still parked — nothing to fold in.
@@ -1222,7 +1227,7 @@ export class ChatTopicActionImpl {
this.#get().internal_updateTopicData(containerKey, { isExpandingPageSize: false });
}
- return { ...result, items: this.#applyPendingStatusWrites(result.items) };
+ return { ...result, items: this.#applyPendingStatusWrites(result.items, 'server') };
},
{
// onData: responsible for state updates (fires for both cached and fresh data)
@@ -1232,11 +1237,9 @@ export class ChatTopicActionImpl {
const { total: totalCount } = result;
const currentData = this.#get().topicDataMap[containerKey];
- const topics = this.#reconcileFetchedTopics(result.items, currentData?.items, {
- // `result` can be a cached response or a list already normalized by
- // the fetcher. Neither proves the server observed the pending write.
- confirmMatchingStatus: false,
- });
+ // `result` can be a cached response or a list already normalized by
+ // the fetcher. Neither proves the server observed the pending write.
+ const topics = this.#reconcileFetchedTopics(result.items, currentData?.items, 'cache');
// Fire BEFORE the no-change early return below: on a cold boot the
// cached list arrives with no `currentData`, and that first delivery
@@ -1364,12 +1367,14 @@ export class ChatTopicActionImpl {
async () => {
if (!agentId) return { items: [], total: 0 };
- return topicService.getTopics({
+ const result = await topicService.getTopics({
agentId,
current: 0,
pageSize,
withDetails,
});
+
+ return { ...result, items: this.#applyPendingStatusWrites(result.items, 'server') };
},
{
onData: (result) => {
@@ -1377,7 +1382,7 @@ export class ChatTopicActionImpl {
const { total: totalCount } = result;
const currentData = this.#get().agentTopicsViewMap[containerKey];
- const topics = this.#reconcileFetchedTopics(result.items, currentData?.items);
+ const topics = this.#reconcileFetchedTopics(result.items, currentData?.items, 'cache');
// Preserve appended pages on refresh — same convention as
// `useFetchTopics` so the user keeps their scroll position after
@@ -1462,7 +1467,8 @@ export class ChatTopicActionImpl {
withDetails,
});
- const nextItems = [...currentData.items, ...result.items];
+ const topics = this.#applyPendingStatusWrites(result.items, 'server');
+ const nextItems = [...currentData.items, ...topics];
const hasMore = result.total > nextItems.length;
this.#set(
@@ -1550,7 +1556,8 @@ export class ChatTopicActionImpl {
});
const currentTopics = currentData?.items || [];
- const nextItems = [...currentTopics, ...result.items];
+ const topics = this.#applyPendingStatusWrites(result.items, 'server');
+ const nextItems = [...currentTopics, ...topics];
const hasMore = result.total > nextItems.length;
this.#set(
@@ -1613,7 +1620,10 @@ export class ChatTopicActionImpl {
// pending status writes here too (no tmp-row re-prepend: optimistic
// rows don't belong in search results).
this.#set(
- { searchTopics: this.#reconcileFetchedTopics(data), isSearchingTopic: false },
+ {
+ isSearchingTopic: false,
+ searchTopics: this.#reconcileFetchedTopics(data, undefined, 'server'),
+ },
false,
n('useSearchTopics(success)', { keywords }),
);
@@ -2139,6 +2149,7 @@ export class ChatTopicActionImpl {
const items = this.#reconcileFetchedTopics(
params.items,
append ? undefined : currentData?.items,
+ 'cache',
);
const nextItems = append ? [...(currentData?.items || []), ...items] : items;
diff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.ts
index 73a49251a93..b3a39a977ed 100644
--- a/src/store/chat/slices/topic/topicListCache.integration.test.ts
+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts
@@ -11,6 +11,8 @@
* cached page keeps the `running` snapshot taken mid-run and the sidebar paints
* a spinner on a finished topic.
*/
+import { randomUUID } from 'node:crypto';
+
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PropsWithChildren } from 'react';
import { createElement, useEffect } from 'react';
@@ -30,14 +32,14 @@ vi.mock('@/services/topic', () => ({
topicService: { getTopics: vi.fn() },
}));
-const SCOPE = 'topic-cache-user:personal';
+const SCOPE_PREFIX = 'topic-cache-user:personal';
const AGENT_ID = 'agent-lobe-14032';
const CONTAINER_KEY = topicMapKey({ agentId: AGENT_ID });
-const makeProvider = () =>
+const makeProvider = (scope: string) =>
createCacheProvider({
debounceMs: 5,
- getScope: () => SCOPE,
+ getScope: () => scope,
idbPatterns: ['topic:'],
localPatterns: [],
});
@@ -61,9 +63,10 @@ const wrapper =
const runningTopic = { id: 'tpc-lobe-14032', status: 'running', title: '抚州明天天气查询' };
-const cachedTopicStatus = async (): Promise<string | undefined> => {
- const entries = await localDataCache.entriesByScope(SCOPE);
+const cachedTopicStatus = async (scope: string): Promise<string | undefined> => {
+ const entries = await localDataCache.entriesByScope(scope);
for (const entry of entries) {
+ if (!entry.key.includes('topic:list')) continue;
const items = (entry.data as { data?: { items?: ChatTopic[] } })?.data?.items;
const topic = items?.find((item) => item.id === runningTopic.id);
if (topic) return topic.status ?? undefined;
@@ -72,6 +75,13 @@ const cachedTopicStatus = async (): Promise<string | undefined> => {
};
describe('persisted topic list across a reload', () => {
+ const scopes = new Set<string>();
+ const createScope = () => {
+ const scope = `${SCOPE_PREFIX}:${randomUUID()}`;
+ scopes.add(scope);
+ return scope;
+ };
+
beforeEach(() => {
act(() => {
useChatStore.setState({
@@ -83,22 +93,24 @@ describe('persisted topic list across a reload', () => {
});
afterEach(async () => {
- await localDataCache.clearScope(SCOPE);
+ await Promise.all([...scopes].map((scope) => localDataCache.clearScope(scope)));
+ scopes.clear();
vi.restoreAllMocks();
vi.clearAllMocks();
});
it('paints the run’s terminal status, not the mid-run `running` snapshot', async () => {
+ const scope = createScope();
// --- session 1: the list is fetched while the run is still going ---------
vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);
- const provider1 = makeProvider();
+ const provider1 = makeProvider(scope);
const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
wrapper: wrapper(provider1),
});
await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));
- await waitFor(async () => expect(await cachedTopicStatus()).toBe('running'));
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('running'));
// --- the run ends: an optimistic status write, with no refetch behind it -
act(() => {
@@ -109,7 +121,7 @@ describe('persisted topic list across a reload', () => {
});
});
- await waitFor(async () => expect(await cachedTopicStatus()).toBe('active'));
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
session1.unmount();
// --- session 2 ("reload"): a slow network, so the cached page paints -----
@@ -118,7 +130,7 @@ describe('persisted topic list across a reload', () => {
});
vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);
- const provider2 = makeProvider();
+ const provider2 = makeProvider(scope);
await provider2.hydrateScope?.();
const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
@@ -134,18 +146,19 @@ describe('persisted topic list across a reload', () => {
});
it('keeps a terminal status after an older list request lands and the pending pin expires', async () => {
+ const scope = createScope();
const now = Date.now();
- const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now);
+ const nowSpy = vi.spyOn(Date, 'now');
vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);
- const provider1 = makeProvider();
+ const provider1 = makeProvider(scope);
const session1 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
wrapper: wrapper(provider1),
});
await waitFor(() => expect(session1.result.current.data?.items).toHaveLength(1));
- await waitFor(async () => expect(await cachedTopicStatus()).toBe('running'));
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('running'));
// The terminal write wins in Zustand and the persisted cache first.
act(() => {
@@ -155,7 +168,7 @@ describe('persisted topic list across a reload', () => {
topicId: runningTopic.id,
});
});
- await waitFor(async () => expect(await cachedTopicStatus()).toBe('active'));
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
const cacheSetSpy = vi.spyOn(localDataCache, 'set');
// A list request that started before the terminal write returns afterwards.
@@ -167,7 +180,7 @@ describe('persisted topic list across a reload', () => {
expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');
await waitFor(() => expect(cacheSetSpy).toHaveBeenCalled());
await Promise.all(cacheSetSpy.mock.results.map(({ value }) => value));
- expect(await cachedTopicStatus()).toBe('active');
+ expect(await cachedTopicStatus(scope)).toBe('active');
// The normalized first response must not be mistaken for server
// confirmation. A second older response can still be in flight and must be
@@ -178,7 +191,7 @@ describe('persisted topic list across a reload', () => {
});
await waitFor(() => expect(cacheSetSpy).toHaveBeenCalled());
await Promise.all(cacheSetSpy.mock.results.map(({ value }) => value));
- expect(await cachedTopicStatus()).toBe('active');
+ expect(await cachedTopicStatus(scope)).toBe('active');
session1.unmount();
// Regression: after the 15-second pending pin elapsed, navigating away and
@@ -190,7 +203,7 @@ describe('persisted topic list across a reload', () => {
});
vi.mocked(topicService.getTopics).mockReturnValue(new Promise<never>(() => {}) as any);
- const provider2 = makeProvider();
+ const provider2 = makeProvider(scope);
await provider2.hydrateScope?.();
const session2 = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
@@ -204,4 +217,75 @@ describe('persisted topic list across a reload', () => {
session2.unmount();
});
+
+ it('does not treat a cached agent-view row as server confirmation', async () => {
+ const scope = createScope();
+ const provider = makeProvider(scope);
+ const activeTopic = { ...runningTopic, status: 'active' };
+
+ // Prime the management-page cache with the same status a later terminal
+ // pin will carry. Replaying this row must not count as a server round-trip.
+ vi.mocked(topicService.getTopics).mockResolvedValue({
+ items: [activeTopic],
+ total: 1,
+ } as any);
+ const primedAgentView = renderHook(
+ () =>
+ useChatStore().useFetchAgentTopicsView(true, {
+ agentId: AGENT_ID,
+ withDetails: true,
+ }),
+ { wrapper: wrapper(provider) },
+ );
+ await waitFor(() =>
+ expect(primedAgentView.result.current.data?.items[0].status).toBe('active'),
+ );
+ primedAgentView.unmount();
+
+ vi.mocked(topicService.getTopics).mockImplementation(({ withDetails }) =>
+ withDetails
+ ? (new Promise<never>(() => {}) as any)
+ : (Promise.resolve({ items: [runningTopic], total: 1 }) as any),
+ );
+
+ const sidebar = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {
+ wrapper: wrapper(provider),
+ });
+ await waitFor(() => expect(sidebar.result.current.data?.items[0].status).toBe('running'));
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('running'));
+
+ act(() => {
+ useChatStore.getState().internal_pinTopicStatus({
+ agentId: AGENT_ID,
+ status: 'active',
+ topicId: runningTopic.id,
+ });
+ });
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
+
+ const replayedAgentView = renderHook(
+ () =>
+ useChatStore().useFetchAgentTopicsView(true, {
+ agentId: AGENT_ID,
+ withDetails: true,
+ }),
+ { wrapper: wrapper(provider) },
+ );
+ await waitFor(() =>
+ expect(useChatStore.getState().agentTopicsViewMap[CONTAINER_KEY]?.items[0].status).toBe(
+ 'active',
+ ),
+ );
+
+ // If the cached management row cleared the pin, this stale sidebar response
+ // would restore `running` in both Zustand and IndexedDB.
+ await act(async () => {
+ await sidebar.result.current.mutate();
+ });
+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items[0].status).toBe('active');
+ await waitFor(async () => expect(await cachedTopicStatus(scope)).toBe('active'));
+
+ replayedAgentView.unmount();
+ sidebar.unmount();
+ });
});