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(topic): stop the scheduled-run watch from reverting its own optimistic write (#18008)

Arvin Xu4afc5d4b08d7
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 39979e2eb42..9d5b1ee85c8 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -1996,6 +1996,103 @@ describe('topic action', () => {
expect(refreshMessages).not.toHaveBeenCalled();
});
+ it('keeps the topic parked while our own scheduled write is still in flight', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const refreshMessages = vi.fn();
+ // The pre-schedule row: the rate-limited turn parked the topic as 'failed'.
+ const topic = {
+ id: topicId,
+ metadata: {},
+ status: 'failed',
+ title: 'Rate limited topic',
+ } as unknown as ChatTopic;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ refreshMessages,
+ topicDataMap: {
+ [key]: { currentPage: 0, hasMore: false, items: [topic], pageSize: 20, total: 1 },
+ },
+ });
+ });
+
+ // "Continue in ~1d 8h": the status is dispatched optimistically, the DB
+ // write is still on the wire.
+ let persistScheduled: () => void = () => {};
+ vi.spyOn(topicService, 'updateTopic').mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ persistScheduled = () => resolve();
+ }) as any,
+ );
+ act(() => {
+ void result.current.updateTopicStatus({ status: 'scheduled', topicId });
+ });
+ expect(useChatStore.getState().topicDataMap[key].items[0].status).toBe('scheduled');
+
+ // The watch this dispatch just armed fetches before the write lands, so
+ // the server still reports the pre-schedule row.
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: topicId,
+ metadata: {},
+ status: 'failed',
+ } as any);
+
+ let synced = true;
+ await act(async () => {
+ synced = await result.current.syncScheduledTopicRun(topicId);
+ });
+
+ expect(synced).toBe(false);
+ // Reverting here is what made the button read as a no-op until clicked twice.
+ expect(useChatStore.getState().topicDataMap[key].items[0].status).toBe('scheduled');
+ expect(refreshMessages).not.toHaveBeenCalled();
+
+ persistScheduled();
+ });
+
+ it('folds in a stale row once the scheduled write failed to persist', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const refreshMessages = vi.fn();
+ const topic = {
+ id: topicId,
+ metadata: {},
+ status: 'failed',
+ title: 'Rate limited topic',
+ } as unknown as ChatTopic;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ refreshMessages,
+ topicDataMap: {
+ [key]: { currentPage: 0, hasMore: false, items: [topic], pageSize: 20, total: 1 },
+ },
+ });
+ });
+
+ // The persist rejects β€” the pin is dropped, so nothing should suppress the
+ // server's view of the topic any more.
+ vi.spyOn(topicService, 'updateTopic').mockRejectedValueOnce(new Error('offline'));
+ await act(async () => {
+ await result.current.updateTopicStatus({ status: 'scheduled', topicId });
+ });
+
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: topicId,
+ metadata: {},
+ status: 'failed',
+ } as any);
+
+ let synced = false;
+ await act(async () => {
+ synced = await result.current.syncScheduledTopicRun(topicId);
+ });
+
+ expect(synced).toBe(true);
+ expect(useChatStore.getState().topicDataMap[key].items[0].status).toBe('failed');
+ });
+
it('does not fetch at all when the store topic is not scheduled', async () => {
const { result } = renderHook(() => useChatStore());
const refreshMessages = vi.fn();
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 04031d960d7..115d90d69b4 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -423,19 +423,33 @@ export class ChatTopicActionImpl {
*/
#pendingTopicStatusWrites = new Map<string, { expiresAt: number; status: ChatTopicStatus }>();
+ /**
+ * Reconcile ONE server-sourced row against the pending optimistic writes.
+ *
+ * Every path that brings a topic row back from the server must go through
+ * here before the row reaches the store β€” list fetches, search, and the
+ * single-topic pull in {@link syncScheduledTopicRun} alike. A path that
+ * bypasses it silently reverts whatever the user just did, and the reader
+ * that trips it is usually the one the optimistic write itself woke up.
+ *
+ * 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): ChatTopic => {
+ const pending = this.#pendingTopicStatusWrites.get(item.id);
+ if (!pending) return item;
+ if (pending.expiresAt <= Date.now() || item.status === pending.status) {
+ this.#pendingTopicStatusWrites.delete(item.id);
+ return item;
+ }
+ return { ...item, status: pending.status };
+ };
+
#reconcileFetchedTopics = (items: ChatTopic[], currentItems?: ChatTopic[]): ChatTopic[] => {
let next = items;
if (this.#pendingTopicStatusWrites.size > 0) {
- next = next.map((item) => {
- const pending = this.#pendingTopicStatusWrites.get(item.id);
- if (!pending) return item;
- if (pending.expiresAt <= Date.now() || item.status === pending.status) {
- this.#pendingTopicStatusWrites.delete(item.id);
- return item;
- }
- return { ...item, status: pending.status };
- });
+ next = next.map((item) => this.#applyPendingStatusWrite(item));
}
// In-flight first-send optimistic rows are client-only, so any refetch
@@ -696,8 +710,19 @@ export class ChatTopicActionImpl {
// already has a live update path (or isn't loaded in the active bucket).
if (stored?.status !== 'scheduled') return false;
- const fresh = await topicService.getTopicDetail(topicId);
- if (!fresh) return false;
+ const fetched = await topicService.getTopicDetail(topicId);
+ if (!fetched) return false;
+
+ // Same funnel every other server-sourced row goes through. It matters most
+ // here: `updateTopicStatus` dispatches `scheduled` optimistically and
+ // persists afterwards, and that dispatch is what arms this watch β€” so this
+ // fetch routinely overtakes the write and answers with the PRE-schedule row.
+ // Unreconciled, folding it in would revert the schedule the user just made
+ // (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);
+ if (fresh.status !== fetched.status) return false;
// Server still parked β€” nothing to fold in.
if (fresh.status === 'scheduled' && fresh.metadata?.scheduledRun) return false;