π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): sync cross-device approval answers and continuation (#20204)
Tsuki3510fe3a4d87
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 6ff6f6764e6..4cfc7a24628 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -12,6 +12,10 @@ import { getMessageListCacheIdentity } from '@/services/message/cache';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';+import {+ hasPendingInterventions,+ INTERVENTION_REFRESH_INTERVAL,+} from '@/store/chat/utils/interventionSync';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';import { useUserStore } from '@/store/user';import { authSelectors, settingsSelectors } from '@/store/user/selectors';@@ -123,12 +127,10 @@ const ChatList = memo<ChatListProps>(s.useFetchMessages,]);const activeAgentId = useChatStore((s) => s.activeAgentId);- // Suppress SWR focus revalidate while the current topic is streaming β- // the server-pushed UIChatMessage[] snapshot at step boundaries is the- // source of truth during that window. A focus refetch could hit DB- // mid-fan-out and clobber the in-memory streamed state with a stale- // assistant placeholder.+ // Pending cards still refresh during streaming; the data slice merges only+ // intervention changes so lagging DB snapshots cannot replace live text.const isStreaming = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));+ const hasPendingApproval = useConversationStore((s) => hasPendingInterventions(s.dbMessages));// A client-minted topic whose server row does not exist yet (first-send// window) must not be fetched: the query would legitimately return an empty// list and `onData` would wipe the optimistic messages already on screen.@@ -139,8 +141,10 @@ const ChatList = memo<ChatListProps>();const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);const messagesSWR = useFetchMessages(context, {- revalidateOnFocus: !isStreaming,+ refreshInterval: hasPendingApproval ? INTERVENTION_REFRESH_INTERVAL : 0,+ revalidateOnFocus: hasPendingApproval || !isStreaming,skipFetch: skipFetch || isCreatingTopic,+ syncInterventions: true,});const refreshError = useMessageRefreshError({error: messagesSWR.error,diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.tsindex 72de750f229..0bde274160c 100644--- a/src/features/Conversation/store/slices/data/action.test.ts+++ b/src/features/Conversation/store/slices/data/action.test.ts@@ -820,11 +820,100 @@ describe('DataSlice', () => {describe('useFetchMessages', () => {beforeEach(() => {+ vi.restoreAllMocks();vi.clearAllMocks();clearMessageListClientCacheState();useChatStore.setState({ voiceMessageUploadMap: {} });});+ it.each(['approved', 'rejected', 'aborted'] as const)(+ 'observes a remote %s while preserving locally streaming content',+ async (status) => {+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);+ const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };+ const pending: UIChatMessage = {+ content: '',+ createdAt: 1,+ id: 'question',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 10,+ pluginIntervention: { status: 'pending' },+ };+ const streaming: UIChatMessage = {+ content: 'Streaming content that has not been persisted yet',+ createdAt: 2,+ id: 'assistant',+ role: 'assistant',+ updatedAt: 10,+ };+ const answered: UIChatMessage = {+ ...pending,+ content: 'Remote answer',+ updatedAt: 1,+ pluginIntervention: { status },+ };+ const store = createStore({ context });+ const onMessagesChange = vi.fn();+ store.setState({ dbMessages: [pending, streaming], messagesInit: true, onMessagesChange });+ vi.mocked(messageService.getMessages).mockResolvedValue([+ answered,+ { ...streaming, content: '...' },+ ]);++ store.getState().useFetchMessages(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.any(Array),+ expect.any(Function),+ expect.objectContaining({+ dedupingInterval: 1000,+ refreshInterval: 2000,+ refreshWhenHidden: false,+ refreshWhenOffline: false,+ }),+ );+ },+ );++ it('settles a remote answer and permits an authoritative rollback at the same timestamp', async () => {+ const context = { agentId: 'test-session', threadId: null, topicId: 'test-topic' };+ const pending: UIChatMessage = {+ content: '',+ createdAt: 1,+ id: 'question',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 10,+ pluginIntervention: { status: 'pending' },+ };+ const answered: UIChatMessage = {+ ...pending,+ content: 'Remote answer',+ updatedAt: 1,+ pluginIntervention: { status: 'approved' },+ };+ const store = createStore({ context });+ store.setState({ dbMessages: [pending] });+ vi.mocked(messageService.getMessages).mockResolvedValue([answered]);+ store.getState().useFetchMessages(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);+ await act(async () => {+ await Promise.resolve();+ });+ expect(store.getState().dbMessages).toEqual([rollback]);+ });+it('should pass threadId to messageService.getMessages', async () => {const mockMessages: UIChatMessage[] = [{diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.tsindex 4952f60c6fa..4029e32e67e 100644--- a/src/features/Conversation/store/slices/data/action.ts+++ b/src/features/Conversation/store/slices/data/action.ts@@ -1,5 +1,5 @@import { parse } from '@lobechat/conversation-flow';-import { type ConversationContext, type UIChatMessage } from '@lobechat/types';+import { type ChatTopic, type ConversationContext, type UIChatMessage } from '@lobechat/types';import debug from 'debug';import { type SWRResponse } from 'swr';import { type StateCreator } from 'zustand/vanilla';@@ -8,13 +8,22 @@ import { useClientDataSWRWithSync } from '@/libs/swr';import { messageService } from '@/services/message';import {getEarlierHistoryStatus,+ getMessageListCacheIdentity,getMessageListFetchPolicy,loadEarlierMessagePage,messageListKey,runMessageListQuery,} from '@/services/message/cache';-import { getChatStoreState } from '@/store/chat';-import { operationSelectors } from '@/store/chat/selectors';+import { topicService } from '@/services/topic';+import { getChatStoreState, useChatStore } from '@/store/chat';+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';+import {+ hasPendingInterventions,+ INTERVENTION_REFRESH_INTERVAL,+ isInterventionRunActive,+ reconcileIntervention,+ reconcileStreamingInterventions,+} from '@/store/chat/utils/interventionSync';import {isLocalOnlyMessage,mergeLocalMessagesByCreatedAt,@@ -30,6 +39,26 @@ import { stabilizeReferences } from './stabilizeReferences';const log = debug('lobe-render:features:Conversation');+interface InterventionSnapshot {+ dbMessages: UIChatMessage[];+ topic: ChatTopic | null;+ topicAtRequest?: ChatTopic;+}++const interventionSync = new WeakMap<+ () => ConversationStore,+ { pending: Set<string>; snapshots: WeakMap<UIChatMessage[], InterventionSnapshot> }+>();++const getInterventionSync = (get: () => ConversationStore) => {+ let sync = interventionSync.get(get);+ if (!sync) {+ sync = { pending: new Set(), snapshots: new WeakMap() };+ interventionSync.set(get, sync);+ }+ return sync;+};+const mergeFetchedMessagesWithLocalState = (fetchedMessages: UIChatMessage[],localMessages: UIChatMessage[],@@ -45,6 +74,8 @@ const mergeFetchedMessagesWithLocalState = (const localMessage = localById.get(message.id);if (!localMessage) return message;+ const resolved = reconcileIntervention(localMessage, message);+ if (resolved) return resolved;// Once the server returns this id, its persisted row replaces the local-only preview.if (isLocalOnlyMessage(localMessage)) return message;if (localMessage.updatedAt <= message.updatedAt) return message;@@ -129,7 +160,12 @@ export interface DataAction {*/useFetchMessages: (context: ConversationContext,- options?: { revalidateOnFocus?: boolean; skipFetch?: boolean },+ options?: {+ refreshInterval?: number;+ revalidateOnFocus?: boolean;+ skipFetch?: boolean;+ syncInterventions?: boolean;+ },) => SWRResponse<UIChatMessage[]>;}@@ -318,13 +354,22 @@ export const dataSlice: StateCreator<},useFetchMessages: (context, options) => {- const { skipFetch, revalidateOnFocus } = 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;@@ -340,9 +385,40 @@ export const dataSlice: StateCreator<return useClientDataSWRWithSync<UIChatMessage[]>(shouldFetch ? messageListKey(context) : null,- () => runMessageListQuery(context, messageService.getMessageListPage),+ async () => {+ const dbMessages = get().dbMessages;+ const topicAtRequest = context.topicId+ ? topicSelectors.getTopicById(context.topicId)(getChatStoreState())+ : undefined;+ const wasPending = hasPendingInterventions(dbMessages);+ let messages = await runMessageListQuery(context, messageService.getMessageListPage);+ 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, messageService.getMessageListPage, {+ 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@@ -361,45 +437,53 @@ export const dataSlice: StateCreator<return;}- // Defense-in-depth gate: drop any SWR onData while the- // topic is streaming. DB fan-out for chunk writes is async and lags- // the WS push by anywhere from 100ms to several seconds; an SWR- // refetch that lands inside that window returns the assistant row- // as the LOADING_FLAT placeholder (cLen=3) and would collapse the- // in-memory streamed content. SWR's own cache still receives the- // value, so once streaming ends a normal revalidate writes through.- //- // This is the catch-all backstop sitting BELOW the SoT consumption- // in gatewayEventHandler β `mergeFetchedMessagesWithLocalState`'s- // updatedAt tie-breaker handles most cases on its own, but the- // updatedAt comparison degenerates when server's pushed snapshot- // carries a DB updatedAt equal to a later stale fetch's row.- //- // Only rows the store already holds are protected. The first load, and- // rows the store has never seen, still land: a run can stay `running`- // for a long time (a group supervisor parked on a member's approval),- // and dropping them left a reloaded list on its skeleton, or on a stale- // cached snapshot missing the parked member's rows, for good.+ // 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;- let fetchedMessages = data;- if (+ 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)(getChatStoreState())- ) {- const knownIds = new Set(prevDbMessages.map((m) => m.id));- const unseen = data.filter((m) => !knownIds.has(m.id));- if (unseen.length === 0) return;- fetchedMessages = [...prevDbMessages, ...unseen];- }-+ operationSelectors.isAgentRuntimeRunningByContext(context)(chat) &&+ !(completed && snapshot.dbMessages === prevDbMessages);const activeVoiceMessageIds = new Set(Object.keys(getChatStoreState().voiceMessageUploadMap),);- const mergedMessages = mergeFetchedMessagesWithLocalState(- fetchedMessages,- prevDbMessages,- activeVoiceMessageIds,- );+ 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 },+ });+ }+ }+ }+ if (isStreaming && mergedMessages === prevDbMessages) return;// Parse messages using conversation-flowconst { flatList } = parse(mergedMessages, undefined, { threadId: context.threadId });diff --git a/src/features/Conversation/store/slices/data/approvalSync.test.ts b/src/features/Conversation/store/slices/data/approvalSync.test.tsnew file mode 100644index 00000000000..9a7a93a25e3--- /dev/null+++ b/src/features/Conversation/store/slices/data/approvalSync.test.ts@@ -0,0 +1,298 @@+import type { UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+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 { topicService } from '@/services/topic';+import { useChatStore } from '@/store/chat';+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';+import {+ hasPendingInterventions,+ INTERVENTION_REFRESH_INTERVAL,+} from '@/store/chat/utils/interventionSync';++import { createStore } from '../../index';++vi.mock('@/services/message', () => {+ const getMessages = vi.fn();+ return {+ messageService: {+ getMessages,+ getMessageListPage: vi.fn(async (params: unknown) => ({+ messages: await getMessages(params),+ olderCursor: null,+ })),+ },+ };+});+vi.mock('@/services/topic', () => ({ topicService: { getTopicDetail: vi.fn() } }));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => undefined,+ useActiveWorkspaceId: () => undefined,+}));++const context = { agentId: 'sync-agent', threadId: null, topicId: 'sync-topic' };+const pending: UIChatMessage = {+ content: '',+ createdAt: 1,+ id: 'question',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 10,+ pluginIntervention: { status: 'pending' },+};++describe('pending approval message polling', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ clearMessageListClientCacheState();+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: {} });+ vi.mocked(messageService.getMessages).mockResolvedValue([pending]);+ vi.mocked(messageService.getMessageListPage).mockImplementation(async (params) => ({+ messages: await messageService.getMessages(params),+ olderCursor: null,+ }));+ vi.mocked(topicService.getTopicDetail).mockResolvedValue(null);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ const mountPolling = async () => {+ const store = createStore({ context });+ store.setState({ dbMessages: [pending] });+ const cache = new Map();+ renderHook(+ () => {+ const hasPending = store((state) => hasPendingInterventions(state.dbMessages));+ store.getState().useFetchMessages(context, {+ refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,+ syncInterventions: true,+ });+ },+ {+ wrapper: ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children),+ },+ );+ await act(async () => {+ await Promise.resolve();+ });+ return store;+ };++ it('keeps loaded history and its exhausted cursor after the final approval refresh', async () => {+ vi.mocked(messageService.getMessageListPage).mockImplementation(async () => ({+ messages: await messageService.getMessages(context),+ olderCursor: { createdAt: new Date(1).toISOString(), id: pending.id },+ }));+ const store = await mountPolling();+ const older: UIChatMessage = {+ id: 'older',+ role: 'user',+ content: 'Earlier round',+ createdAt: 0,+ updatedAt: 0,+ };+ const history = await loadEarlierMessagePage(+ context,+ () => store.getState().dbMessages,+ async () => ({ messages: [older], olderCursor: null }),+ );+ act(() => store.getState().replaceMessages(history!));+ const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };+ const reply: UIChatMessage = {+ id: 'reply',+ role: 'assistant',+ content: 'Final reply',+ createdAt: 20,+ updatedAt: 20,+ };+ vi.mocked(messageService.getMessages).mockResolvedValue([answered, reply]);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(store.getState().dbMessages).toEqual([older, answered, reply]);+ expect(getEarlierHistoryStatus(context).exhausted).toBe(true);+ expect(messageService.getMessageListPage).toHaveBeenCalledTimes(3);+ });++ it('waits for a startup reservation and publishes the new operation for the existing reconnect hook', async () => {+ const store = await mountPolling();+ const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };+ vi.mocked(messageService.getMessages).mockResolvedValue([answered]);+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({+ id: context.topicId,+ status: 'active',+ metadata: {+ taskCallbackReservation: { messageId: 'resume', reservedAt: new Date().toISOString() },+ },+ } as Awaited<ReturnType<typeof topicService.getTopicDetail>>);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(store.getState().dbMessages[0].pluginIntervention?.status).toBe('approved');+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(vi.mocked(messageService.getMessages).mock.calls.length).toBeGreaterThan(requests);+ const runningOperation = { assistantMessageId: 'reply', operationId: 'new-run' };+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({+ id: context.topicId,+ status: 'running',+ metadata: { runningOperation },+ } as Awaited<ReturnType<typeof topicService.getTopicDetail>>);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(+ topicSelectors.getTopicById(context.topicId)(useChatStore.getState())?.metadata+ ?.runningOperation,+ ).toEqual(runningOperation);+ });++ it('reads final messages after the decision and topic, even with a stale local streaming flag', async () => {+ vi.spyOn(operationSelectors, 'isAgentRuntimeRunningByContext').mockReturnValue(() => true);+ const store = await mountPolling();+ const order: string[] = [];+ const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };+ vi.mocked(messageService.getMessages).mockImplementation(async () => {+ order.push('messages');+ return order.includes('topic')+ ? [+ answered,+ {+ id: 'reply',+ role: 'assistant',+ content: 'Final reply',+ createdAt: 20,+ updatedAt: 20,+ },+ ]+ : [answered];+ });+ vi.mocked(topicService.getTopicDetail).mockImplementation(async () => {+ order.push('topic');+ return null;+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(order).toEqual(['messages', 'topic', 'messages']);+ expect(store.getState().dbMessages.at(-1)?.content).toBe('Final reply');+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(messageService.getMessages).toHaveBeenCalledTimes(requests);+ });++ it('follows a slow remote continuation after the Ask closes without focus or remount', async () => {+ const store = createStore({ context });+ store.setState({ dbMessages: [pending] });+ const cache = new Map();+ renderHook(+ () => {+ const hasPending = store((state) => hasPendingInterventions(state.dbMessages));+ store.getState().useFetchMessages(context, {+ refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,+ syncInterventions: true,+ });+ },+ {+ wrapper: ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children),+ },+ );+ await act(async () => {+ await Promise.resolve();+ });+ const answered = { ...pending, pluginIntervention: { status: 'approved' as const } };+ vi.mocked(messageService.getMessages).mockResolvedValue([answered]);+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({+ id: context.topicId,+ status: 'running',+ metadata: { runningOperation: { assistantMessageId: 'reply', operationId: 'continuation' } },+ } as Awaited<ReturnType<typeof topicService.getTopicDetail>>);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(store.getState().dbMessages[0].pluginIntervention?.status).toBe('approved');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(60_000);+ });+ vi.mocked(topicService.getTopicDetail).mockResolvedValue(null);+ vi.mocked(messageService.getMessages).mockResolvedValue([+ answered,+ {+ id: 'reply',+ role: 'assistant',+ content: 'Late continuation',+ createdAt: 20,+ updatedAt: 20,+ },+ ]);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(store.getState().dbMessages.at(-1)?.content).toBe('Late continuation');+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(messageService.getMessages).toHaveBeenCalledTimes(requests);+ });++ it.each(['approved', 'rejected', 'aborted'] as const)(+ 'updates the mounted peer on remote %s, then stops polling',+ async (status) => {+ const store = createStore({ context });+ store.setState({ dbMessages: [pending] });+ const usePollingMessages = () => {+ const hasPending = store((state) => hasPendingInterventions(state.dbMessages));+ const result = store((state) => state.dbMessages[0]?.pluginIntervention?.status);+ store.getState().useFetchMessages(context, {+ refreshInterval: hasPending ? INTERVENTION_REFRESH_INTERVAL : 0,+ syncInterventions: true,+ });+ return result;+ };+ const cache = new Map();+ const { result } = renderHook(usePollingMessages, {+ wrapper: ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { provider: () => cache } }, children),+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(result.current).toBe('pending');+ const answered: UIChatMessage = {+ ...pending,+ updatedAt: 1,+ content: 'Remote answer',+ pluginIntervention: { status },+ };+ vi.mocked(messageService.getMessages).mockResolvedValue([answered]);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2000);+ });+ expect(result.current).toBe(status);+ expect(store.getState().dbMessages).toEqual([answered]);+ const requests = vi.mocked(messageService.getMessages).mock.calls.length;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(messageService.getMessages).toHaveBeenCalledTimes(requests);+ },+ );+});diff --git a/src/services/message/cache.test.ts b/src/services/message/cache.test.tsindex 03805cf35d2..23f528cf473 100644--- a/src/services/message/cache.test.ts+++ b/src/services/message/cache.test.ts@@ -262,6 +262,34 @@ describe('earlier history (round-cursor pages)', () => {/** 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)]));diff --git a/src/services/message/cache.ts b/src/services/message/cache.tsindex 0bd5c75a1fc..0e603128a0b 100644--- a/src/services/message/cache.ts+++ b/src/services/message/cache.ts@@ -407,7 +407,17 @@ const startCurrentGenerationQuery = (export const runMessageListQuery = (context: MessageListQueryContext,query: MessageListQuery,-): Promise<UIChatMessage[]> => startCurrentGenerationQuery(getOrCreateState(context), query);+ options?: { force?: boolean },+): Promise<UIChatMessage[]> => {+ const state = getOrCreateState(context);+ if (options?.force) {+ // A read after a completion barrier must not join an earlier request.+ // Unlike mutation invalidation, this read keeps client-held history pages.+ state.generation += 1;+ state.verifiedAt = undefined;+ }+ return startCurrentGenerationQuery(state, query);+};/*** Synchronously invalidate verification and advance the request generation fordiff --git a/src/store/chat/utils/interventionSync.test.ts b/src/store/chat/utils/interventionSync.test.tsnew file mode 100644index 00000000000..ec7bf14776f--- /dev/null+++ b/src/store/chat/utils/interventionSync.test.ts@@ -0,0 +1,119 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ hasPendingInterventions,+ reconcileIntervention,+ reconcileStreamingInterventions,+} from './interventionSync';++const question = (+ status: 'pending' | 'approved' | 'rejected' | 'aborted',+ updatedAt = 1,+): UIChatMessage => ({+ id: 'question',+ content: status === 'pending' ? '' : 'User submitted: answer',+ createdAt: 1,+ updatedAt,+ role: 'tool',+ tool_call_id: 'call-1',+ pluginIntervention: { status },+});++describe('cross-device intervention reconciliation', () => {+ it('settles an existing Ask and adds unseen rows without replacing streamed content', () => {+ const pending = question('pending', 10);+ const answered = question('approved', 1);+ const streamed: UIChatMessage = {+ id: 'assistant',+ role: 'assistant',+ content: 'live text',+ createdAt: 2,+ updatedAt: 10,+ };+ const unseen: UIChatMessage = {+ id: 'member-tool',+ role: 'tool',+ content: '',+ createdAt: 3,+ updatedAt: 10,+ };+ expect(+ reconcileStreamingInterventions(+ [pending, streamed],+ [answered, { ...streamed, content: '...' }, unseen],+ ),+ ).toEqual([answered, streamed, unseen]);+ });++ it('preserves the array when a fetch has no intervention changes', () => {+ const local = [question('pending')];+ expect(reconcileStreamingInterventions(local, [question('pending')])).toBe(local);+ expect(reconcileStreamingInterventions(local, [])).toBe(local);+ });++ it('reopens a newer rolled-back question while preserving streaming assistant rows', () => {+ const answered = question('approved', 10);+ const rollback = question('pending', 11);+ const assistant: UIChatMessage = {+ id: 'assistant',+ role: 'assistant',+ content: 'live text',+ createdAt: 1,+ updatedAt: 10,+ };+ const merged = reconcileStreamingInterventions(+ [answered, assistant],+ [rollback, { ...assistant, content: '...' }],+ );+ expect(merged[0]).toBe(rollback);+ expect(merged[1]).toBe(assistant);+ });+ it.each(['approved', 'rejected', 'aborted'] as const)(+ 'accepts a remote %s without a message timestamp change',+ (status) => {+ const pending = question('pending', 10);+ const answered = question(status, 1);+ expect(hasPendingInterventions([pending])).toBe(true);+ expect(reconcileIntervention(pending, answered)).toBe(answered);+ expect(hasPendingInterventions([answered])).toBe(false);+ },+ );++ it('allows authoritative rollback instead of treating terminal as irreversible', () => {+ const answered = question('approved', 10);+ // Equal timestamps use the normal fetch/version rules, not a status lock.+ expect(reconcileIntervention(answered, question('pending', 10))).toBeUndefined();+ const rollback = question('pending', 11);+ expect(reconcileIntervention(answered, rollback)).toBe(rollback);+ });++ it('keeps a different request or sealed batch isolated', () => {+ const pending = question('pending');+ const answered = question('approved');+ expect(reconcileIntervention(pending, { ...answered, tool_call_id: 'call-2' })).toBeUndefined();+ expect(+ reconcileIntervention(pending, {+ ...answered,+ pluginIntervention: { batchId: 'new-batch', status: 'approved' },+ }),+ ).toBeUndefined();+ });++ it('supports legacy plugin intervention rows and ignores optimistic rows', () => {+ const legacy = {+ ...question('pending'),+ pluginIntervention: undefined,+ plugin: {+ apiName: 'askUserQuestion',+ arguments: '{}',+ identifier: 'lobe-agent',+ type: 'builtin' as const,+ intervention: { status: 'pending' as const },+ },+ };+ expect(hasPendingInterventions([legacy])).toBe(true);+ expect(hasPendingInterventions([{ ...legacy, id: 'tmp_question' }])).toBe(false);+ expect(hasPendingInterventions([])).toBe(false);+ });+});diff --git a/src/store/chat/utils/interventionSync.ts b/src/store/chat/utils/interventionSync.tsnew file mode 100644index 00000000000..edbc5a2fd24--- /dev/null+++ b/src/store/chat/utils/interventionSync.ts@@ -0,0 +1,71 @@+import type { ChatTopic, UIChatMessage } from '@lobechat/types';++export const INTERVENTION_REFRESH_INTERVAL = 2000;++/** A missing operation marker can still mean the continuation is starting. */+export const isInterventionRunActive = (topic: ChatTopic | null) =>+ !!topic?.metadata?.runningOperation ||+ !!topic?.metadata?.taskCallbackReservation ||+ topic?.status === 'running' ||+ topic?.status === 'waitingForHuman';++const intervention = (message: UIChatMessage) =>+ message.pluginIntervention ?? message.plugin?.intervention;++export const hasPendingInterventions = (messages: UIChatMessage[]) =>+ messages.some(+ (message) =>+ message.role === 'tool' &&+ !message.id.startsWith('tmp_') &&+ intervention(message)?.status === 'pending',+ );++const isTerminal = (status: string | undefined) =>+ status === 'approved' || status === 'rejected' || status === 'aborted';++/** Plugin rows can change without advancing the parent message's updatedAt. */+export const reconcileIntervention = (+ local: UIChatMessage,+ incoming: UIChatMessage,+): UIChatMessage | undefined => {+ const previous = intervention(local);+ const next = intervention(incoming);+ if (+ local.role !== 'tool' ||+ incoming.role !== 'tool' ||+ local.id !== incoming.id ||+ local.tool_call_id !== incoming.tool_call_id ||+ previous?.operationId !== next?.operationId ||+ previous?.batchId !== next?.batchId+ )+ return;++ if (previous?.status === 'pending' && isTerminal(next?.status)) return incoming;+ // Continuation startup can fail and restore this request to pending.+ if (+ isTerminal(previous?.status) &&+ next?.status === 'pending' &&+ incoming.updatedAt > local.updatedAt+ )+ return incoming;+};++/** Apply remote answers while leaving the locally streaming transcript intact. */+export const reconcileStreamingInterventions = (+ local: UIChatMessage[],+ incoming: UIChatMessage[],+) => {+ const incomingById = new Map(incoming.map((message) => [message.id, message]));+ let changed = false;+ const merged = local.map((message) => {+ const fetched = incomingById.get(message.id);+ incomingById.delete(message.id);+ const resolved = fetched && reconcileIntervention(message, fetched);+ if (!resolved) return message;+ changed = true;+ return resolved;+ });+ // A parked run can discover new member/tool rows while older rows stream.+ if (incomingById.size > 0) return [...merged, ...incomingById.values()];+ return changed ? merged : local;+};