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(chat): ignore superseded terminal snapshots (#18523)

YuTengjing29fe0432accc
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
index 032cfeb8119..e89eacff2ad 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts
@@ -62,6 +62,7 @@ function createMockStore() {
metadata: { startTime: 0 },
},
} as Record<string, any>,
+ operationsByContext: {},
replaceMessages: vi.fn(),
startOperation: vi.fn(() => {
reasoningCounter += 1;
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
index 30066d3d24d..7b999678621 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
@@ -32,6 +32,7 @@ const createStore = (dbMessagesMap: Record<string, UIChatMessage[]> = {}) =>
internal_dispatchMessage: vi.fn(),
internal_toggleToolCallingStreaming: vi.fn(),
operations: {},
+ operationsByContext: {},
replaceMessages: vi.fn(),
startOperation: vi.fn(() => ({
abortController: new AbortController(),
@@ -829,6 +830,136 @@ describe('createGatewayEventHandler', () => {
);
});
+ it('does not let a superseded run replace messages from a newer run', async () => {
+ const lifecycle = createLifecycle();
+ const store = createStore();
+ const contextKey = messageMapKey(context);
+ store.operations = {
+ 'op-1': {
+ abortController: new AbortController(),
+ context,
+ id: 'op-1',
+ metadata: { startTime: 2 },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ 'op-2': {
+ abortController: new AbortController(),
+ context,
+ id: 'op-2',
+ metadata: { startTime: 1 },
+ status: 'running',
+ type: 'sendMessage',
+ },
+ };
+ store.operationsByContext = { [contextKey]: ['op-1', 'op-2'] };
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'answer-msg',
+ context,
+ operationId: 'op-1',
+ runLifecycle: lifecycle as any,
+ runtimeType: 'gateway',
+ });
+
+ handler(
+ makeEvent('agent_runtime_end', {
+ reason: 'completed',
+ uiMessages: [
+ { content: 'old answer', id: 'answer-msg', role: 'assistant' },
+ ] as unknown as UIChatMessage[],
+ }),
+ );
+ await flush();
+
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(lifecycle.completeRun).toHaveBeenCalled();
+ });
+
+ it('does not let a superseded run refetch an older terminal snapshot', async () => {
+ const lifecycle = createLifecycle();
+ const store = createStore();
+ const contextKey = messageMapKey(context);
+ store.operations = {
+ 'op-1': {
+ abortController: new AbortController(),
+ context,
+ id: 'op-1',
+ metadata: { startTime: 1 },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ 'op-2': {
+ abortController: new AbortController(),
+ context,
+ id: 'op-2',
+ metadata: { startTime: 2 },
+ status: 'running',
+ type: 'sendMessage',
+ },
+ };
+ store.operationsByContext = { [contextKey]: ['op-1', 'op-2'] };
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'answer-msg',
+ context,
+ operationId: 'op-1',
+ runLifecycle: lifecycle as any,
+ runtimeType: 'gateway',
+ });
+ const getMessages = vi.spyOn(messageService, 'getMessages');
+
+ handler(makeEvent('agent_runtime_end', { reason: 'completed' }));
+ await flush();
+
+ expect(getMessages).not.toHaveBeenCalled();
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(lifecycle.completeRun).toHaveBeenCalled();
+ });
+
+ it('does not treat a later child operation as a new conversation owner', async () => {
+ const lifecycle = createLifecycle();
+ const store = createStore();
+ const contextKey = messageMapKey(context);
+ store.operations = {
+ 'op-1': {
+ abortController: new AbortController(),
+ context,
+ id: 'op-1',
+ metadata: { startTime: 1 },
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ },
+ 'op-member': {
+ abortController: new AbortController(),
+ context,
+ id: 'op-member',
+ metadata: { startTime: 2 },
+ parentOperationId: 'op-1',
+ status: 'completed',
+ type: 'execServerAgentRuntime',
+ },
+ };
+ store.operationsByContext = { [contextKey]: ['op-1', 'op-member'] };
+ const handler = createGatewayEventHandler(() => store, {
+ assistantMessageId: 'answer-msg',
+ context,
+ operationId: 'op-1',
+ runLifecycle: lifecycle as any,
+ runtimeType: 'gateway',
+ });
+ const uiMessages = [
+ { content: 'council result', id: 'answer-msg', role: 'assistant' },
+ ] as unknown as UIChatMessage[];
+
+ handler(makeEvent('agent_runtime_end', { reason: 'completed', uiMessages }));
+ await flush();
+
+ expect(store.replaceMessages).toHaveBeenCalledWith(uiMessages, {
+ action: 'gateway/agent_runtime_end',
+ context,
+ });
+ expect(lifecycle.completeRun).toHaveBeenCalled();
+ });
+
it('falls back to the streamed accumulator when the terminal snapshot carries no assistant text', async () => {
vi.spyOn(messageService, 'getMessages').mockResolvedValue([] as unknown as UIChatMessage[]);
const lifecycle = createLifecycle();
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
index 7068a0adbc0..cd50e607e10 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -26,6 +26,7 @@ import type {
RunScope,
} from '@/store/chat/slices/agentRun/actions/lifecycle/types';
import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -1115,12 +1116,23 @@ export const createGatewayEventHandler = (
// pushes the canonical snapshot directly on this event. Fall back
// to a DB refetch only if the snapshot is absent (older server
// builds, or push-event delivery edge cases).
+ const isSuperseded = operationSelectors.hasNewerConversationOperation(
+ operationId,
+ context,
+ )(get());
if (Array.isArray(data?.uiMessages)) {
terminalMessages = data.uiMessages;
- get().replaceMessages(data.uiMessages, {
- action: 'gateway/agent_runtime_end',
- context,
- });
+ // `visible_output_end` lets a follow-up start before this terminal
+ // event arrives. Once that happens, this run's snapshot is no longer
+ // the conversation SoT: replacing the list would erase the newer
+ // turn's optimistic rows until refresh. Keep terminalMessages for
+ // this run's notification, but do not mutate its successor's store.
+ if (!isSuperseded) {
+ get().replaceMessages(data.uiMessages, {
+ action: 'gateway/agent_runtime_end',
+ context,
+ });
+ }
} else if (
(data?.reason === 'interrupted' || data?.reason === 'waiting_for_async_tool') &&
hasStreamedContent
@@ -1143,7 +1155,7 @@ export const createGatewayEventHandler = (
// arrives BEFORE any stream activity, the optimistic `tmp_*`
// messages are the only in-memory state and they need the
// refetch to be reconciled with the server-side rows.
- } else {
+ } else if (!isSuperseded) {
await fetchAndReplaceMessages(get, context).catch(console.error);
}
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
index 828eb2860f8..e1fc6efde7c 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type StreamEvent } from '@/services/agentRuntime';
import { useChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
// Keep zustand mock as it's needed globally
vi.mock('zustand/traditional');
@@ -500,6 +501,56 @@ describe('runAgent actions', () => {
context: { agentId: 'agent-1', topicId: 'topic-1' },
});
});
+
+ it('does not let a superseded run replace messages from a newer run', async () => {
+ const replaceMessages = vi.fn();
+ const operationContext = { agentId: 'agent-1', topicId: 'topic-1' };
+ const contextKey = messageMapKey(operationContext);
+ act(() => {
+ useChatStore.setState({
+ operationsByContext: {
+ [contextKey]: [TEST_IDS.OPERATION_ID, 'new-send-operation'],
+ },
+ replaceMessages,
+ operations: {
+ [TEST_IDS.OPERATION_ID]: {
+ abortController: new AbortController(),
+ context: operationContext,
+ id: TEST_IDS.OPERATION_ID,
+ metadata: { lastEventId: '0', startTime: 2, stepCount: 0 },
+ status: 'running',
+ type: 'groupAgentStream',
+ },
+ 'new-send-operation': {
+ abortController: new AbortController(),
+ context: operationContext,
+ id: 'new-send-operation',
+ metadata: { startTime: 1 },
+ status: 'running',
+ type: 'sendMessage',
+ },
+ },
+ });
+ });
+ const { result } = renderHook(() => useChatStore());
+ const uiMessages = [{ id: 'old-run-message', role: 'assistantGroup' }] as any;
+ const event: StreamEvent = {
+ data: { finalState: { status: 'done' }, reason: 'done', uiMessages },
+ operationId: TEST_IDS.OPERATION_ID,
+ timestamp: Date.now(),
+ type: 'agent_runtime_end',
+ };
+
+ await act(async () => {
+ await result.current.internal_handleAgentStreamEvent(
+ TEST_IDS.OPERATION_ID,
+ event,
+ createStreamingContext({ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID }),
+ );
+ });
+
+ expect(replaceMessages).not.toHaveBeenCalled();
+ });
});
describe('visible_output_end event', () => {
diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.ts
index 6d1facad852..2826c69a872 100644
--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts
+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts
@@ -3,6 +3,7 @@ import debug from 'debug';
import { type StreamEvent } from '@/services/agentRuntime';
import { agentRuntimeService } from '@/services/agentRuntime';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { type ChatStore } from '@/store/chat/store';
import {
notifyDesktopAgentCompleted,
@@ -124,7 +125,13 @@ export class AgentActionImpl {
// has no later step_start to carry a fresh snapshot, so without
// this branch the streamed assistantGroup would only be reconciled
// with DB once a refetch fires — losing the SoT guarantee.
- if (Array.isArray(uiMessages)) {
+ if (
+ Array.isArray(uiMessages) &&
+ !operationSelectors.hasNewerConversationOperation(
+ operationId,
+ operation.context,
+ )(this.#get())
+ ) {
log(`Replacing messages from agent_runtime_end uiMessages (${uiMessages.length} msgs)`);
this.#get().replaceMessages(uiMessages, { context: operation.context });
}
diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.ts
index c174e26c783..51830ed2192 100644
--- a/src/store/chat/slices/operation/selectors.ts
+++ b/src/store/chat/slices/operation/selectors.ts
@@ -7,6 +7,7 @@ import {
AI_RUNTIME_OPERATION_TYPES,
INPUT_LOADING_OPERATION_TYPES,
isQueueBlockingOperation,
+ QUEUE_BLOCKING_OPERATION_TYPES,
} from './types';
// === Basic Queries ===
@@ -227,6 +228,37 @@ const getOperationsByContext =
});
};
+/**
+ * Whether a later conversation operation has taken ownership of this context.
+ *
+ * A run can publish `visible_output_end` before its terminal snapshot arrives,
+ * which intentionally lets the next send start. The old snapshot must not then
+ * replace the newer turn's optimistic messages. Status is deliberately ignored:
+ * the newer send may already have handed off to its runtime (or even settled),
+ * but its later registration in the context index still proves that the older
+ * snapshot is superseded. The index is local insertion order, so it remains
+ * monotonic even when restored server timestamps and the client clock differ.
+ * Child operations stay within their parent's turn and therefore cannot claim
+ * conversation ownership from that turn's terminal reconciliation.
+ */
+const hasNewerConversationOperation =
+ (operationId: string, context: Operation['context']) =>
+ (s: ChatStoreState): boolean => {
+ const operation = s.operations[operationId];
+ if (!operation || !context.agentId) return false;
+
+ const operations = getOperationsByContext({ ...context, agentId: context.agentId })(s);
+ const operationIndex = operations.findIndex((candidate) => candidate.id === operationId);
+ if (operationIndex < 0) return false;
+
+ return operations
+ .slice(operationIndex + 1)
+ .some(
+ (candidate) =>
+ !candidate.parentOperationId && QUEUE_BLOCKING_OPERATION_TYPES.includes(candidate.type),
+ );
+ };
+
/**
* Check if there's a running operation in a specific context
* Use this for loading states in components that display a specific conversation
@@ -903,6 +935,7 @@ export const operationSelectors = {
getRunningQueueBlockingOperationIds,
getRunningToolCallStartTime,
hasAnyRunningOperation,
+ hasNewerConversationOperation,
hasRunningOperationByContext,
hasRunningOperationType,
/** @deprecated Use isAgentRuntimeRunning instead */