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): recover a step's messages when Stop overtakes its patch (#23269)

YuTengjing8b4e5e545a40
diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.md
index bc1e7163ccb..7f626a34f3e 100644
--- a/packages/agent-gateway-client/PROTOCOL_V2.md
+++ b/packages/agent-gateway-client/PROTOCOL_V2.md
@@ -47,6 +47,11 @@ canonical conversation at every step boundary:
carries what other writers changed between the two steps.
- `agent_runtime_end.data` carries `{ messagePatchMode: true, messageRevision }` and omits
both `uiMessages` and `finalState`. The client settles only after it has that revision.
+ An `interrupted` end one past the current step's revision (the later of the last
+ applied patch and the last `step_start`) is a Stop mid-step: a client holding
+ streamed text that is not persisted yet keeps it instead of querying. Two or more
+ past means a finished step's patch is missing (a Stop between two inline steps
+ overtakes it), and the client queries.
- A missing revision or insertion anchor falls back to the existing authorized full-message
query; patches are an optimization, not a second source of truth.
diff --git a/packages/agent-signal/README.md b/packages/agent-signal/README.md
index 2cc151503c8..0f652e340a0 100644
--- a/packages/agent-signal/README.md
+++ b/packages/agent-signal/README.md
@@ -101,10 +101,10 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv
| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |
| `agent.user.message` | `AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage` | [Workflow bridge](../../apps/server/src/workflows/agentSignal/run.ts), [Bot router](../../apps/server/src/services/bot/BotMessageRouter/index.ts) | User feedback/message content that policies can analyze for memory, prompt, document, or skill changes. |
| `bot.message.merged` | `AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged` | [Bot router](../../apps/server/src/services/bot/BotMessageRouter/index.ts) | Bot-platform message content merged into a conversation scope. |
-| `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway error for a client-side runtime operation. |
-| `client.gateway.runtime_end` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway runtime finished for a client-side operation. |
-| `client.gateway.step_complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway step completed with operation and step index metadata. |
-| `client.gateway.stream_start` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway stream started with operation and first step metadata. |
+| `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts) | Browser gateway error for a client-side runtime operation. |
+| `client.gateway.runtime_end` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts) | Browser gateway runtime finished for a client-side operation. |
+| `client.gateway.step_complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts) | Browser gateway step completed with operation and step index metadata. |
+| `client.gateway.stream_start` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts) | Browser gateway stream started with operation and first step metadata. |
| `client.runtime.complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime completed with operation, topic, thread, and status metadata. |
| `client.runtime.start` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime started; workflow may bridge this into `agent.user.message` with serialized context. |
| `runtime.after_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step finished with operation, step index, topic, and context metadata. |
@@ -127,7 +127,7 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv
- [Workflow runner](../../apps/server/src/workflows/agentSignal/run.ts): workflow execution and client runtime bridge.
- [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/): server runtime source event producers.
- [Chat](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts): browser chat runtime source event producer.
-- [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts): browser gateway source event producer.
+- [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts): browser gateway source event producer.
- [Bot router](../../apps/server/src/services/bot/BotMessageRouter/index.ts): bot-platform source event producer.
## Adding A Source Event
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.failedRun.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.failedRun.test.ts
similarity index 98%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.failedRun.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.failedRun.test.ts
index 5d61d2d7e07..2fc53f05535 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.failedRun.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.failedRun.test.ts
@@ -6,7 +6,7 @@ import { messageService } from '@/services/message';
import * as agentSignalBridge from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import type { ChatStore } from '@/store/chat/store';
-import { createGatewayEventHandler } from './gatewayEventHandler';
+import { createGatewayEventHandler } from './index';
vi.mock('@/store/tool/slices/builtin/executors', () => ({
getExecutor: vi.fn(() => ({})),
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.lifecycle.test.ts
similarity index 77%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.lifecycle.test.ts
index 91a03f9c158..ea4596dd0d5 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.lifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.lifecycle.test.ts
@@ -3,9 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
import type * as WorkServiceModule from '@/services/work';
-import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
-import { createGatewayEventHandler } from './gatewayEventHandler';
-import { createHandler, createMockStore, flush, makeEvent } from './testUtils';
+import { createHandler, createMockStore, flush, makeEvent } from '../testUtils';
vi.mock('@/services/message', () => ({
messageService: {
@@ -231,109 +229,10 @@ describe('createGatewayEventHandler β€” run lifecycle characterization', () => {
expect(store.markTopicUnread).not.toHaveBeenCalled();
},
);
-
- // the agent_runtime_end handler completes the op once via
- // the shared run lifecycle, and gateway.ts onSessionComplete no longer
- // double-completes (it only completes as the terminal-missing fallback). The
- // reducer is still idempotent (a stray second completeOperation on an
- // already-'completed' op is a no-throw, no-flip no-op) β€” locked here as a
- // safety net in case any path issues a redundant completion.
- it('completeOperation is idempotent: double-calling the same op leaves status=completed (no throw, no flip)', async () => {
- // Local harness whose completeOperation MIRRORS the real reducer
- // (operation/actions.ts completeOperation): set status to 'completed'
- // unless the op was 'cancelled'.
- const operations: Record<string, any> = {
- 'op-1': {
- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },
- metadata: { startTime: 0 },
- status: 'running',
- },
- };
- const completeOperation = vi.fn((operationId: string) => {
- const op = operations[operationId];
- if (!op) return;
- if (op.status !== 'cancelled') op.status = 'completed';
- op.metadata.endTime = Date.now();
- });
- const store = {
- ...createMockStore(),
- completeOperation,
- operations,
- } as ReturnType<typeof createMockStore>;
- const get = vi.fn(() => store) as any;
- const handler = createGatewayEventHandler(get, {
- assistantMessageId: 'msg-initial',
- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,
- operationId: 'op-1',
- runLifecycle: buildRunLifecycle(get, {
- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,
- parentMessageId: 'msg-initial',
- parentMessageType: 'assistant',
- runId: 'op-1',
- runScope: 'top_level',
- runtimeType: 'gateway',
- }),
- });
-
- // First terminal completion (agent_runtime_end handler).
- handler(makeEvent('agent_runtime_end'));
- await flush();
- expect(operations['op-1'].status).toBe('completed');
-
- // Second completion (as onSessionComplete in gateway.ts would issue).
- store.completeOperation('op-1');
- expect(operations['op-1'].status).toBe('completed');
- expect(completeOperation).toHaveBeenCalledTimes(2);
- });
-
- // CURRENT BEHAVIOR: if the op was cancelled mid-flight, completeOperation
- // does NOT flip it to 'completed' (operation/actions.ts:288-291 preserves
- // the user's interruption state). Lock this so the refactor can't quietly
- // resurrect a cancelled op into 'completed' on a stray terminal event.
- it('completeOperation preserves a cancelled op (does not flip cancelled β†’ completed)', async () => {
- const operations: Record<string, any> = {
- 'op-1': {
- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },
- metadata: { startTime: 0 },
- status: 'cancelled',
- },
- };
- const completeOperation = vi.fn((operationId: string) => {
- const op = operations[operationId];
- if (!op) return;
- if (op.status !== 'cancelled') op.status = 'completed';
- op.metadata.endTime = Date.now();
- });
- const store = {
- ...createMockStore(),
- completeOperation,
- operations,
- } as ReturnType<typeof createMockStore>;
- const get = vi.fn(() => store) as any;
- const handler = createGatewayEventHandler(get, {
- assistantMessageId: 'msg-initial',
- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,
- operationId: 'op-1',
- runLifecycle: buildRunLifecycle(get, {
- context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any,
- parentMessageId: 'msg-initial',
- parentMessageType: 'assistant',
- runId: 'op-1',
- runScope: 'top_level',
- runtimeType: 'gateway',
- }),
- });
-
- handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));
- await flush();
-
- expect(store.completeOperation).toHaveBeenCalledWith('op-1');
- expect(operations['op-1'].status).toBe('cancelled');
- });
});
describe('waiting_for_async_tool parked characterization (lifecycle refactor regression net)', () => {
- // CURRENT BEHAVIOR (gatewayEventHandler.ts:568-589): the `agent_runtime_end`
+ // CURRENT BEHAVIOR (gatewayEventHandler/index.ts): the `agent_runtime_end`
// message-reconciliation branch special-cases BOTH `reason='interrupted'`
// and `reason='waiting_for_async_tool'` together, gated by
// `hasStreamedContent`. A `waiting_for_async_tool` terminal is a deferred-
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.llmRelay.test.ts
similarity index 99%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.llmRelay.test.ts
index e6037ffe5aa..729f208c1ca 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.llmRelay.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.llmRelay.test.ts
@@ -6,7 +6,7 @@ import * as agentSignalBridge from '@/store/chat/slices/agentRun/actions/lifecyc
import type { ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { createGatewayEventHandler } from './gatewayEventHandler';
+import { createGatewayEventHandler } from './index';
const relay = vi.hoisted(() => {
const owned = new Set<string>();
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.streaming.test.ts
similarity index 99%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.streaming.test.ts
index 696439dd002..af98f387e95 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.streaming.test.ts
@@ -4,7 +4,7 @@ import { messageService } from '@/services/message';
import type * as WorkServiceModule from '@/services/work';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
-import { createHandler, createMockStore, flush, makeEvent } from './testUtils';
+import { createHandler, createMockStore, flush, makeEvent } from '../testUtils';
vi.mock('@/services/message', () => ({
messageService: {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.terminal.test.ts
similarity index 70%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.terminal.test.ts
index edcbc528e5b..63efb05bbb4 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.terminal.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.terminal.test.ts
@@ -1,11 +1,12 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
import type * as WorkServiceModule from '@/services/work';
import { workService } from '@/services/work';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { createHandler, createMockStore, flush, makeEvent } from './testUtils';
+import { createHandler, createMockStore, flush, makeEvent } from '../testUtils';
vi.mock('@/services/message', () => ({
messageService: {
@@ -36,6 +37,35 @@ vi.mock('@/store/tool/slices/builtin/executors', () => ({
registerBuiltinToolExecutors: vi.fn().mockResolvedValue(undefined),
}));
+/** Starts a follow-up send in the same conversation, which then owns it. */
+const startNewerSend = (store: ReturnType<typeof createMockStore>) => {
+ const context = { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' } as any;
+ Object.assign(store.operations['op-1'], {
+ id: 'op-1',
+ status: 'running',
+ type: 'execServerAgentRuntime',
+ });
+ store.operations['op-2'] = {
+ context,
+ id: 'op-2',
+ metadata: { startTime: 1 },
+ status: 'running',
+ type: 'sendMessage',
+ };
+ store.operationsByContext = { [messageMapKey(context)]: ['op-1', 'op-2'] };
+};
+
+/** Holds the next conversation read open until the test resolves it. */
+const holdNextRead = () => {
+ let resolve!: (messages: any[]) => void;
+ vi.mocked(messageService.getMessages).mockReturnValueOnce(
+ new Promise((r) => {
+ resolve = r;
+ }) as any,
+ );
+ return (messages: any[]) => resolve(messages);
+};
+
describe('createGatewayEventHandler β€” terminal and error events', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -170,6 +200,167 @@ describe('createGatewayEventHandler β€” terminal and error events', () => {
});
expect(messageService.getMessages).not.toHaveBeenCalled();
});
+
+ // Protocol v2: a step that continues inline publishes its message patch
+ // only from the next step's entry read, so a Stop between the two steps
+ // can end the run before that patch arrives. Step 0's patch (revision 1)
+ // has been applied; a Stop after step 1 is saved ends with revision 3.
+ describe('interrupted in message patch mode', () => {
+ // A one-shot reply these tests queue must not leak into the next test.
+ afterEach(() => {
+ vi.mocked(messageService.getMessages).mockReset().mockResolvedValue([]);
+ });
+
+ const startStreamedRun = async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-server' } }));
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial answer' }));
+ handler(makeEvent('message_patch', { deletes: [], revision: 1, upserts: [] }));
+ await flush();
+ vi.mocked(messageService.getMessages).mockClear();
+ store.replaceMessages.mockClear();
+ return { handler, store };
+ };
+
+ const interruptedEnd = (messageRevision: number) =>
+ makeEvent('agent_runtime_end', {
+ messagePatchMode: true,
+ messageRevision,
+ reason: 'interrupted',
+ });
+
+ it('reads the finished step whose patch the Stop overtook', async () => {
+ const { handler, store } = await startStreamedRun();
+ const persisted = [{ content: 'summary', id: 'group-1', role: 'compressedGroup' }];
+ vi.mocked(messageService.getMessages).mockResolvedValueOnce(persisted as any);
+
+ handler(interruptedEnd(3));
+ await flush();
+
+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);
+ expect(store.replaceMessages).toHaveBeenCalledWith(persisted, {
+ context: expect.any(Object),
+ preserveWorks: undefined,
+ });
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ });
+
+ it('keeps the streamed text when the Stop lands mid-step', async () => {
+ const { handler, store } = await startStreamedRun();
+
+ handler(interruptedEnd(2));
+ await flush();
+
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ });
+
+ it('keeps the streamed text when a Stop mid-step follows a failed step_start read', async () => {
+ const { handler, store } = await startStreamedRun();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ // Revision 2's patch never arrived and the step_start read fails, so
+ // the last applied patch stays at 1 while step 2 streams.
+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('offline'));
+ handler(makeEvent('step_start', { messageRevision: 2 }));
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: ' more' }));
+ await flush();
+ vi.mocked(messageService.getMessages).mockClear();
+
+ handler(interruptedEnd(3));
+ await flush();
+
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ consoleError.mockRestore();
+ });
+
+ it('skips that read when a newer send owns the conversation', async () => {
+ const { handler, store } = await startStreamedRun();
+ startNewerSend(store);
+
+ handler(interruptedEnd(3));
+ await flush();
+
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ });
+
+ it('drops that read when a newer send starts before it returns', async () => {
+ const { handler, store } = await startStreamedRun();
+ const resolveRead = holdNextRead();
+
+ handler(interruptedEnd(3));
+ await flush();
+ startNewerSend(store);
+ resolveRead([{ content: 'summary', id: 'group-1', role: 'compressedGroup' }]);
+ await flush();
+
+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ });
+
+ it('keeps the messages it has and still settles when that read fails', async () => {
+ const { handler, store } = await startStreamedRun();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(messageService.getMessages).mockRejectedValueOnce(new Error('offline'));
+
+ handler(interruptedEnd(3));
+ await flush();
+
+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ consoleError.mockRestore();
+ });
+ });
+
+ // A send can start while a terminal read is in flight; that read's list
+ // predates the send and would erase its optimistic rows.
+ describe('a newer send that starts during the terminal read', () => {
+ afterEach(() => {
+ vi.mocked(messageService.getMessages).mockReset().mockResolvedValue([]);
+ });
+
+ it('keeps its list when a completed patch-mode run reads the missing revision', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+ handler(makeEvent('message_patch', { deletes: [], revision: 1, upserts: [] }));
+ await flush();
+ store.replaceMessages.mockClear();
+ const resolveRead = holdNextRead();
+
+ handler(makeEvent('agent_runtime_end', { messagePatchMode: true, messageRevision: 3 }));
+ await flush();
+ startNewerSend(store);
+ resolveRead([{ content: 'final', id: 'msg-1', role: 'assistant' }]);
+ await flush();
+
+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ });
+
+ it('keeps its list when the fallback read returns', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+ const resolveRead = holdNextRead();
+
+ handler(makeEvent('agent_runtime_end'));
+ await flush();
+ startNewerSend(store);
+ resolveRead([{ content: 'final', id: 'msg-1', role: 'assistant' }]);
+ await flush();
+
+ expect(messageService.getMessages).toHaveBeenCalledTimes(1);
+ expect(store.replaceMessages).not.toHaveBeenCalled();
+ expect(store.completeOperation).toHaveBeenCalledWith('op-1');
+ });
+ });
});
describe('error', () => {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.test.ts
similarity index 99%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.test.ts
index 51d239d273f..e25429f451e 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.test.ts
@@ -7,7 +7,7 @@ import * as agentSignalBridge from '@/store/chat/slices/agentRun/actions/lifecyc
import type { ChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { createGatewayEventHandler } from './gatewayEventHandler';
+import { createGatewayEventHandler } from './index';
const executorMocks = vi.hoisted(() => ({
onAfterCall: vi.fn(),
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.ts
similarity index 99%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.ts
index f73260dcfc9..6f1cdeb90d5 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.toolEvents.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.toolEvents.test.ts
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as WorkServiceModule from '@/services/work';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
-import { createHandler, createMockStore, flush, makeEvent } from './testUtils';
+import { createHandler, createMockStore, flush, makeEvent } from '../testUtils';
vi.mock('@/services/message', () => ({
messageService: {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts
similarity index 94%
rename from src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
rename to src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts
index 6b44d624a20..8dc3e1df773 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/index.ts
@@ -36,18 +36,20 @@ import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { applyMessagePatch } from './messagePatch';
+import { applyMessagePatch } from '../messagePatch';
import {
findTerminalAssistantError,
isCompletedRuntimeEnd,
resolveRuntimeEndStatus,
-} from './runtimeEndReason';
-import { applyStepMetrics } from './stepMetrics';
-import { resolveStepSideEvent } from './stepSideEvent';
-import { insertStreamStartSeeds, streamStartOperationMetadata } from './streamStartSeed';
+} from '../runtimeEndReason';
+import { applyStepMetrics } from '../stepMetrics';
+import { resolveStepSideEvent } from '../stepSideEvent';
+import { insertStreamStartSeeds, streamStartOperationMetadata } from '../streamStartSeed';
+import type { RuntimeEndData } from './runtimeEndMessages';
+import { reconcileRuntimeEndMessages } from './runtimeEndMessages';
// Lazy-loaded to break the import cycle:
-// gateway.ts β†’ gatewayEventHandler.ts β†’ executors/index.ts (which pulls in
+// gateway.ts β†’ gatewayEventHandler/index.ts β†’ executors/index.ts (which pulls in
// tool client barrels that import `@/store/chat/store`) β†’ chat store
// creation β†’ `new GatewayActionImpl(...)` while gateway.ts is still
// mid-evaluation, so the class binding is undefined.
@@ -83,12 +85,15 @@ const fetchAndReplaceMessages = async (
*/
skipWorks?: boolean;
snapshotGeneration?: { current: number };
+ /** Checked after the read: a newer operation took the conversation, so keep its list. */
+ isSuperseded?: () => boolean;
},
): Promise<UIChatMessage[] | undefined> => {
const skipWorks = options?.skipWorks;
const snapshotGeneration = options?.snapshotGeneration;
const started = snapshotGeneration?.current;
const messages = await readConversationMessages(skipWorks ? { ...context, skipWorks } : context);
+ if (options?.isSuperseded?.()) return undefined;
if (snapshotGeneration && snapshotGeneration.current !== started) return undefined;
if (snapshotGeneration) snapshotGeneration.current += 1;
get().replaceMessages(messages, { context, preserveWorks: skipWorks });
@@ -359,6 +364,8 @@ export const createGatewayEventHandler = (
let lastTextSnapshotSeq = 0;
let lastReasoningSnapshotSeq = 0;
let lastMessagePatchRevision = 0;
+ // Set even when the step_start read fails, so Stop can tell which step it landed in.
+ let lastStepStartRevision = 0;
const latestToolStateByCallId = new Map<string, ToolStateChunkData & { operationId: string }>();
const toolStateBootstrapPromiseByCallId = new Map<string, Promise<void>>();
const lastAppliedToolStateSeqByCallId = new Map<string, number>();
@@ -417,7 +424,7 @@ export const createGatewayEventHandler = (
// otherwise last-write-wins the older list over the next step.
const snapshotGeneration = { current: 0 };
- const refreshMessagesFromDb = (options?: { skipWorks?: boolean }) =>
+ const refreshMessagesFromDb = (options?: { isSuperseded?: () => boolean; skipWorks?: boolean }) =>
fetchAndReplaceMessages(get, context, { ...options, snapshotGeneration });
const applyPushedSnapshot = (
@@ -1023,6 +1030,7 @@ export const createGatewayEventHandler = (
uiMessages?: UIChatMessage[];
};
+ if (typeof data?.messageRevision === 'number') lastStepStartRevision = data.messageRevision;
if (
typeof data?.messageRevision === 'number' &&
data.messageRevision !== lastMessagePatchRevision
@@ -1204,14 +1212,7 @@ export const createGatewayEventHandler = (
case 'agent_runtime_end': {
enqueue(async () => {
- const data = event.data as
- | {
- messagePatchMode?: boolean;
- messageRevision?: number;
- reason?: string;
- uiMessages?: UIChatMessage[];
- }
- | undefined;
+ const data = event.data as RuntimeEndData | undefined;
void emitAgentSignal({
payload: {
@@ -1231,61 +1232,25 @@ export const createGatewayEventHandler = (
get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
endReasoningIfNeeded();
- // The terminal snapshot, when the server pushed one β€” the reconciled
- // Source of Truth for this run's final assistant text.
- let terminalMessages: UIChatMessage[] | undefined;
-
// Reconcile messages FIRST so the terminal run lifecycle's notification
// (afterRunComplete) can read the final assistant content from the store.
- //
- // Terminal step has no later step_start to carry SoT β€” server
- // 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;
- // `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) {
- applyPushedSnapshot(data.uiMessages, {
- action: 'gateway/agent_runtime_end',
- });
- }
- } else if (data?.reason === 'interrupted' && hasStreamedContent) {
- // MID-stream cancel. `interruptOperation` publishes this event as
- // soon as it saves `interrupted`, while the in-flight step persists
- // the partial text only when it returns afterwards. Any DB read here
- // (the patch-mode refetch too: a Stop lands mid-step, so its revision
- // is ahead of the last patch) sees the empty placeholder and wipes
- // the streamed text, and nothing repairs it: the socket closes on
- // this frame. Keep what was streamed β€” the server persists the same.
- // Without streamed content, the optimistic `tmp_*` rows are all we
- // have and still need the refetch below.
- } else if (data?.messagePatchMode) {
- if (
- typeof data.messageRevision === 'number' &&
- data.messageRevision !== lastMessagePatchRevision
- ) {
- terminalMessages = await refreshMessagesFromDb();
- if (terminalMessages) lastMessagePatchRevision = data.messageRevision;
- } else {
- terminalMessages = get().dbMessagesMap[messageMapKey(context)] ?? [];
- }
- } else if (data?.reason === 'waiting_for_async_tool' && hasStreamedContent) {
- // Deferred-tool pause. The server's
- // `AgentRuntimeCoordinator.resolveUiMessages` omits uiMessages
- // for it (as for `interrupted`) so the in-memory streamed content
- // is preserved here instead of racing the executor's DB write.
- } else if (!isSuperseded) {
- await refreshMessagesFromDb().catch(console.error);
- }
+ // Ownership is checked again after each read: Stop lets a new send
+ // start while the read is in flight.
+ const isSuperseded = () =>
+ operationSelectors.hasNewerConversationOperation(operationId, context)(get());
+ const settled = await reconcileRuntimeEndMessages({
+ applySnapshot: (messages) =>
+ applyPushedSnapshot(messages, { action: 'gateway/agent_runtime_end' }),
+ currentMessages: () => get().dbMessagesMap[messageMapKey(context)] ?? [],
+ data,
+ hasStreamedContent,
+ isSuperseded: isSuperseded(),
+ lastMessagePatchRevision,
+ lastStepStartRevision,
+ refresh: () => refreshMessagesFromDb({ isSuperseded }),
+ });
+ lastMessagePatchRevision = settled.lastMessagePatchRevision;
+ const { terminalMessages } = settled;
if (runtimeType === 'gateway' && shouldRefreshWorkViews) {
await workService
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/runtimeEndMessages.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/runtimeEndMessages.ts
new file mode 100644
index 00000000000..79321a0ae64
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler/runtimeEndMessages.ts
@@ -0,0 +1,126 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+/** The part of `agent_runtime_end.data` that decides how the run's messages settle. */
+export interface RuntimeEndData {
+ messagePatchMode?: boolean;
+ messageRevision?: number;
+ reason?: string;
+ uiMessages?: UIChatMessage[];
+}
+
+interface ReconcileRuntimeEndParams {
+ /** Replaces the store's list with the terminal snapshot the server pushed. */
+ applySnapshot: (messages: UIChatMessage[]) => void;
+ /** The store's current list for this conversation. */
+ currentMessages: () => UIChatMessage[];
+ data: RuntimeEndData | undefined;
+ /** Server-confirmed state (an assistant id, streamed output, a snapshot) has arrived. */
+ hasStreamedContent: boolean;
+ /** A newer operation owns the conversation, so this run must not replace its list. */
+ isSuperseded: boolean;
+ /** Revision of the last `message_patch` this run applied. */
+ lastMessagePatchRevision: number;
+ /** Revision the last `step_start` announced, kept even when its read failed. */
+ lastStepStartRevision: number;
+ /**
+ * Reads the conversation into the store; `undefined` when a newer snapshot won
+ * or a newer operation took the conversation while the read was in flight.
+ */
+ refresh: () => Promise<UIChatMessage[] | undefined>;
+}
+
+interface ReconcileRuntimeEndResult {
+ lastMessagePatchRevision: number;
+ /** This run's final messages when known, for the terminal notification. */
+ terminalMessages?: UIChatMessage[];
+}
+
+/**
+ * Brings the store to the run's final messages on `agent_runtime_end`, before
+ * the terminal run lifecycle's notification reads the final assistant content.
+ *
+ * The terminal step has no later `step_start` to carry the source of truth, so
+ * the server pushes the canonical snapshot on this event. A DB refetch is the
+ * fallback when it is absent (older server builds, push-event delivery edge
+ * cases).
+ */
+export const reconcileRuntimeEndMessages = async ({
+ applySnapshot,
+ currentMessages,
+ data,
+ hasStreamedContent,
+ isSuperseded,
+ lastMessagePatchRevision,
+ lastStepStartRevision,
+ refresh,
+}: ReconcileRuntimeEndParams): Promise<ReconcileRuntimeEndResult> => {
+ if (Array.isArray(data?.uiMessages)) {
+ // `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) applySnapshot(data.uiMessages);
+ return { lastMessagePatchRevision, terminalMessages: data.uiMessages };
+ }
+
+ if (data?.reason === 'interrupted' && hasStreamedContent) {
+ // MID-stream cancel. `interruptOperation` publishes this event as soon as
+ // it saves `interrupted`, while the in-flight step persists the partial
+ // text only when it returns afterwards. Any DB read here sees the empty
+ // placeholder and wipes the streamed text, and nothing repairs it: the
+ // socket closes on this frame. Keep what was streamed β€” the server
+ // persists the same. Without streamed content, the optimistic `tmp_*`
+ // rows are all we have and still need the refetch below.
+ //
+ // In patch mode a Stop mid-step ends one revision past the step it
+ // landed in: the later of the last applied patch and the last
+ // `step_start`, which still names that step when its read failed. Two or
+ // more past means a step that already finished is missing: a step
+ // that continues inline publishes its patch only from the next step's
+ // entry read, so a Stop between the two steps overtakes it, and this
+ // frame is the last one the client gets. That step is persisted and the
+ // next one has not streamed yet, so read it; otherwise its changes (a
+ // compressed group, fields the stream never carried) stay stale until a
+ // reload. A newer send that already owns the conversation keeps its own
+ // list: replacing it would erase that turn's optimistic rows.
+ if (
+ !isSuperseded &&
+ data.messagePatchMode &&
+ typeof data.messageRevision === 'number' &&
+ data.messageRevision - Math.max(lastMessagePatchRevision, lastStepStartRevision) >= 2
+ ) {
+ const messages = await refresh().catch((error) => {
+ console.error(error);
+ return undefined;
+ });
+ if (messages) {
+ return { lastMessagePatchRevision: data.messageRevision, terminalMessages: messages };
+ }
+ }
+ return { lastMessagePatchRevision };
+ }
+
+ if (data?.messagePatchMode) {
+ if (
+ typeof data.messageRevision === 'number' &&
+ data.messageRevision !== lastMessagePatchRevision
+ ) {
+ const messages = await refresh();
+ return messages
+ ? { lastMessagePatchRevision: data.messageRevision, terminalMessages: messages }
+ : { lastMessagePatchRevision };
+ }
+ return { lastMessagePatchRevision, terminalMessages: currentMessages() };
+ }
+
+ if (data?.reason === 'waiting_for_async_tool' && hasStreamedContent) {
+ // Deferred-tool pause. The server's `AgentRuntimeCoordinator.resolveUiMessages`
+ // omits uiMessages for it (as for `interrupted`) so the in-memory streamed
+ // content is preserved here instead of racing the executor's DB write.
+ return { lastMessagePatchRevision };
+ }
+
+ if (!isSuperseded) await refresh().catch(console.error);
+ return { lastMessagePatchRevision };
+};
diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.ts
index 93ba5f4d892..8f574fd85ea 100644
--- a/src/store/chat/slices/operation/__tests__/actions.test.ts
+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts
@@ -271,32 +271,6 @@ describe('Operation Actions', () => {
});
});
- describe('completeOperation', () => {
- it('should mark operation as completed with correct metadata', () => {
- const { result } = renderHook(() => useChatStore());
-
- let operationId: string;
-
- act(() => {
- operationId = result.current.startOperation({
- type: 'execAgentRuntime',
- context: { agentId: 'session1' },
- }).operationId;
- });
-
- act(() => {
- result.current.completeOperation(operationId!);
- });
-
- const operation = result.current.operations[operationId!];
-
- expect(operation.status).toBe('completed');
- expect(operation.metadata.endTime).toBeDefined();
- expect(operation.metadata.duration).toBeDefined();
- expect(operation.metadata.duration).toBeGreaterThanOrEqual(0);
- });
- });
-
describe('cancelOperation', () => {
it('should cancel operation and abort controller', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/operation/actions.completeOperation.test.ts b/src/store/chat/slices/operation/actions.completeOperation.test.ts
new file mode 100644
index 00000000000..8af7950f408
--- /dev/null
+++ b/src/store/chat/slices/operation/actions.completeOperation.test.ts
@@ -0,0 +1,88 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat/store';
+
+describe('Operation Actions', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ });
+
+ describe('completeOperation', () => {
+ it('should mark operation as completed with correct metadata', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: { agentId: 'session1' },
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.completeOperation(operationId!);
+ });
+
+ const operation = result.current.operations[operationId!];
+
+ expect(operation.status).toBe('completed');
+ expect(operation.metadata.endTime).toBeDefined();
+ expect(operation.metadata.duration).toBeDefined();
+ expect(operation.metadata.duration).toBeGreaterThanOrEqual(0);
+ });
+
+ it('keeps status completed and does not throw when completed again', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: { agentId: 'session1' },
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.completeOperation(operationId!);
+ });
+
+ expect(() => {
+ act(() => {
+ result.current.completeOperation(operationId!);
+ });
+ }).not.toThrow();
+
+ expect(result.current.operations[operationId!].status).toBe('completed');
+ });
+
+ it('keeps a cancelled operation cancelled instead of flipping it to completed', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ let operationId: string;
+
+ act(() => {
+ operationId = result.current.startOperation({
+ type: 'execAgentRuntime',
+ context: { agentId: 'session1' },
+ }).operationId;
+ });
+
+ act(() => {
+ result.current.cancelOperation(operationId!, 'User cancelled');
+ });
+
+ act(() => {
+ result.current.completeOperation(operationId!);
+ });
+
+ expect(result.current.operations[operationId!].status).toBe('cancelled');
+ });
+ });
+});