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): keep streamed reply visible after stopping a gateway run (#22920)

Arvin Xu435d3fc15490
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
index cd55b033e1b..9b1cd5f336e 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
@@ -355,5 +355,41 @@ describe('GatewayActionImpl (multiplexed gateway transport)', () => {
expect(refreshMessages).toHaveBeenCalledWith({ agentId: 'a', topicId: 'topic-1' });
expect(refreshTopic).toHaveBeenCalledTimes(1);
});
+
+ // ROOT CAUSE:
+ //
+ // The hub forwards `op_lifecycle` asynchronously, so a stopped run's
+ // `interrupted` notice can land after its socket closed on the terminal
+ // frame but before the server's in-flight step persisted the partial reply.
+ // The run then looked unowned, and its refetch replaced the streamed text
+ // the terminal handler had kept with the step's empty placeholder.
+ //
+ // Before: the notice refetched the topic's messages.
+ // After: a run stopped in this tab settles through its own stream only.
+ it('does not refetch messages when a run stopped here ends after its socket closed', () => {
+ const { mux, refreshMessages, refreshTopic, state } = setup();
+ state.operations = {
+ 'local-run': {
+ context: { agentId: 'a', scope: 'main', threadId: null, topicId: 'topic-1' },
+ id: 'local-run',
+ metadata: { serverOperationId: 'stopped-op' },
+ status: 'cancelled',
+ type: 'execServerAgentRuntime',
+ },
+ };
+
+ mux.emit('lifecycle', lifecycle('stopped-op', 'interrupted', { agentId: 'a', topicId: 't' }));
+
+ expect(refreshMessages).not.toHaveBeenCalled();
+ expect(refreshTopic).not.toHaveBeenCalled();
+ });
+
+ it('still refetches messages when a run stopped elsewhere ends', () => {
+ const { mux, refreshMessages } = setup();
+
+ mux.emit('lifecycle', lifecycle('other-op', 'interrupted', { agentId: 'a', topicId: 't' }));
+
+ expect(refreshMessages).toHaveBeenCalledWith({ agentId: 'a', topicId: 't' });
+ });
});
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopMidStream.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopMidStream.test.ts
new file mode 100644
index 00000000000..131bda6545a
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopMidStream.test.ts
@@ -0,0 +1,333 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import { LOADING_FLAT } from '@lobechat/const';
+import type { UIChatMessage } from '@lobechat/types';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { aiAgentService, type ExecAgentResult } from '@/services/aiAgent';
+import { messageService } from '@/services/message';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+
+vi.mock('../transports/gateway/serverSteerQueue', () => ({
+ reclaimServerQueuedMessages: vi.fn().mockResolvedValue(undefined),
+ restoreServerQueuedMessages: vi.fn(),
+ withdrawQueuedMessage: vi.fn(),
+}));
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: { execAgentTask: vi.fn(), interruptTask: vi.fn(), refreshGatewayToken: vi.fn() },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: { execAgentTask: vi.fn(), interruptTask: vi.fn() },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: vi.fn().mockResolvedValue([]),
+ updateMessageError: vi.fn().mockResolvedValue({ success: true }),
+ },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ getTopicDetail: vi.fn().mockResolvedValue(null),
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatComposerAttachments: vi.fn() }),
+}));
+
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ getUserStoreState: vi.fn(() => mockUserState),
+ useUserStore: { getState: vi.fn(() => mockUserState) },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ settingsSelectors: { defaultAgentConfig: () => ({ chatConfig: {} }) },
+ toolInterventionSelectors: { allowList: () => [], approvalMode: () => 'manual' },
+ userGeneralSettingsSelectors: { telemetry: () => false },
+ userProfileSelectors: { userId: (state: typeof mockUserState) => state.profile.id },
+}));
+
+vi.mock('@/const/version', async (importOriginal) => ({
+ ...(await importOriginal<typeof ConstVersion>()),
+ isDesktop: false,
+}));
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: vi.fn() },
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: () => ({ activeAgentId: undefined, agentMap: {} }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => undefined,
+ getAgentById: () => () => undefined,
+ },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
+ chatConfigByIdSelectors: {
+ getChatConfigById: () => () => ({}),
+ isChatModeById: () => () => false,
+ isLocalSystemEnabledById: () => () => false,
+ },
+}));
+
+vi.mock('@/store/chat/utils/desktopNotification', () => ({
+ notifyDesktopAgentFailed: vi.fn().mockResolvedValue(undefined),
+ notifyDesktopAgentFinished: vi.fn().mockResolvedValue(undefined),
+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({
+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+ delete (globalThis as any).window;
+});
+
+const user = { content: 'Count to four', id: 'usr-1', role: 'user' } as UIChatMessage;
+/** The assistant row as the DB holds it until the interrupted step returns. */
+const placeholder = {
+ content: LOADING_FLAT,
+ id: 'ast-1',
+ parentId: 'usr-1',
+ role: 'assistant',
+} as UIChatMessage;
+
+const serverResult: ExecAgentResult = {
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+};
+
+let eventSeq = 0;
+const event = (type: AgentStreamEvent['type'], data?: unknown): AgentStreamEvent => ({
+ data,
+ id: String((eventSeq += 1)),
+ operationId: 'server-op',
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type,
+});
+
+const flush = async () => {
+ for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 10));
+};
+
+/**
+ * A ChatStore stand-in whose message buckets follow every write the transport
+ * and its event handler make, so assertions read what the conversation shows.
+ */
+const createConversationStore = () => {
+ let opSeq = 0;
+ const state: Record<string, any> = {
+ dbMessagesMap: {},
+ gatewayConnections: {},
+ gatewayFeed: {},
+ operations: {},
+ operationsByContext: {},
+ topicDataMap: {},
+ };
+ const set = vi.fn((updater: any) => {
+ Object.assign(state, typeof updater === 'function' ? updater(state) : updater);
+ });
+ const updateMessage = (id: string, value: Partial<UIChatMessage>) => {
+ for (const [key, messages] of Object.entries(state.dbMessagesMap)) {
+ state.dbMessagesMap[key] = (messages as UIChatMessage[]).map((message) =>
+ message.id === id ? { ...message, ...value } : message,
+ );
+ }
+ };
+ const actions = {
+ associateMessageWithOperation: vi.fn(),
+ completeOperation: vi.fn((id: string) => {
+ const op = state.operations[id];
+ if (op && op.status !== 'cancelled') op.status = 'completed';
+ }),
+ connectToGateway: vi.fn(),
+ drainQueuedMessages: vi.fn(() => []),
+ failOperation: vi.fn(),
+ internal_dispatchMessage: vi.fn((action: any) => {
+ if (action.type === 'updateMessage') updateMessage(action.id, action.value);
+ }),
+ internal_dispatchTopic: vi.fn(),
+ internal_replaceTopicId: vi.fn(),
+ internal_toggleToolCallingStreaming: vi.fn(),
+ markTopicUnread: vi.fn(),
+ moveQueuedMessages: vi.fn(),
+ moveVoiceMessages: vi.fn(),
+ onOperationCancel: vi.fn(),
+ refreshTopic: vi.fn().mockResolvedValue(undefined),
+ refreshTopicDetail: vi.fn().mockResolvedValue(undefined),
+ replaceMessages: vi.fn((messages: UIChatMessage[], params: { context: any }) => {
+ state.dbMessagesMap[messageMapKey(params.context)] = messages;
+ }),
+ startOperation: vi.fn((params: any) => {
+ const operationId = `local-op-${(opSeq += 1)}`;
+ state.operations[operationId] = {
+ abortController: new AbortController(),
+ context: params.context,
+ id: operationId,
+ metadata: { startTime: Date.now(), ...params.metadata },
+ status: 'running',
+ type: params.type,
+ };
+ return { abortController: new AbortController(), operationId };
+ }),
+ switchTopic: vi.fn(),
+ updateOperationMetadata: vi.fn(),
+ updateTopicStatus: vi.fn().mockResolvedValue(undefined),
+ };
+ const get = vi.fn(() => Object.assign(state, actions)) as any;
+ return { get, set, state };
+};
+
+/**
+ * The wire order of a protocol v2 run stopped mid-answer: the step streams,
+ * the user presses Stop (local op cancelled, `interruptTask` confirmed), and
+ * the server's `interruptOperation` publishes the terminal frame as soon as it
+ * saves `interrupted` β€” the in-flight step writes the partial text later, so
+ * any DB read at that point still returns the placeholder.
+ */
+const sendStreamAndStop = async (params: {
+ context: Record<string, any>;
+ optimisticTopic?: { id: string; title: string };
+ /** `false`: Stop lands before the step produced any output. */
+ streams?: boolean;
+ topicId: string;
+}) => {
+ const { get, set, state } = createConversationStore();
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ const resolvedContext = { ...params.context, topicId: params.topicId };
+ const key = messageMapKey(resolvedContext as any);
+ // An existing topic already shows the turn; a new topic's bucket is seeded
+ // from the server's rows right after the topic id handoff.
+ if (!params.optimisticTopic) state.dbMessagesMap[key] = [user, placeholder];
+ vi.mocked(messageService.getMessages).mockResolvedValue([user, placeholder]);
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ ...serverResult,
+ topicId: params.topicId,
+ });
+ vi.mocked(aiAgentService.interruptTask).mockResolvedValue({
+ operationId: 'server-op',
+ success: true,
+ });
+
+ await action.executeGatewayAgent({
+ context: params.context as any,
+ message: 'Count to four',
+ optimisticTopic: params.optimisticTopic,
+ });
+
+ const [{ onEvent }] = state.connectToGateway.mock.calls.at(-1);
+ const [localOpId, onCancel] = state.onOperationCancel.mock.calls.at(-1);
+
+ if (params.streams !== false) {
+ onEvent(event('step_start', { messageRevision: 0 }));
+ onEvent(
+ event('stream_start', {
+ assistantMessage: { id: 'ast-1', parentId: 'usr-1', role: 'assistant' },
+ }),
+ );
+ onEvent(event('stream_chunk', { chunkType: 'text', content: 'One two' }));
+ onEvent(event('stream_chunk', { chunkType: 'text', content: ' three four' }));
+ await flush();
+ }
+ const shownBeforeStop = state.dbMessagesMap[key]?.find((m: UIChatMessage) => m.id === 'ast-1');
+
+ // Stop: `cancelOperation` flips the op and runs the transport's cancel hook.
+ state.operations[localOpId].status = 'cancelled';
+ await onCancel();
+ vi.mocked(messageService.getMessages).mockClear();
+ onEvent(
+ event('agent_runtime_end', {
+ messagePatchMode: true,
+ messageRevision: 1,
+ reason: 'interrupted',
+ }),
+ );
+ await flush();
+
+ const reply = state.dbMessagesMap[key]?.find((m: UIChatMessage) => m.id === 'ast-1');
+ return { reply, shownBeforeStop };
+};
+
+describe('stopping a Gateway run while its reply streams', () => {
+ const context = { agentId: 'agent-1', scope: 'main', threadId: null };
+
+ // ROOT CAUSE:
+ //
+ // A v2 terminal frame carries `messagePatchMode` with a revision ahead of
+ // the last patch (a Stop lands mid-step), and the handler checked that
+ // branch before the mid-stream-interrupt one: it refetched the DB, which
+ // still held the step's placeholder, and replaced the streamed reply. The
+ // socket closes on that frame, so only a reload brought the text back.
+ //
+ // Before: the reply turned back into the empty placeholder after Stop.
+ // After: the streamed text stays, matching what the server persists.
+ it('keeps the streamed reply in an existing topic', async () => {
+ const { reply, shownBeforeStop } = await sendStreamAndStop({
+ context: { ...context, topicId: 'topic-1' },
+ topicId: 'topic-1',
+ });
+
+ expect(shownBeforeStop?.content).toBe('One two three four');
+ expect(reply?.content).toBe('One two three four');
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ });
+
+ it('keeps the streamed reply of the first message in a new topic', async () => {
+ const { reply, shownBeforeStop } = await sendStreamAndStop({
+ context: { ...context, topicId: null },
+ optimisticTopic: { id: 'tmp-topic', title: 'Count to four' },
+ topicId: 'tpc_created',
+ });
+
+ expect(shownBeforeStop?.content).toBe('One two three four');
+ expect(reply?.content).toBe('One two three four');
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ });
+
+ // Nothing streamed yet: the optimistic rows are all the client has, so the
+ // terminal frame still reconciles them with the server.
+ it('still reconciles from the server when Stop lands before any output', async () => {
+ const { reply } = await sendStreamAndStop({
+ context: { ...context, topicId: 'topic-1' },
+ streams: false,
+ topicId: 'topic-1',
+ });
+
+ expect(messageService.getMessages).toHaveBeenCalled();
+ expect(reply).toEqual(placeholder);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index b09a575f1ab..54e36f3065b 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -82,7 +82,7 @@ import {
markGatewayMuxUnavailable,
} from './muxRegistry';
import { flagQueuedMessagesOnRunStart, syncQueuedMessagesFlag } from './queuedMessagesFlag';
-import { gatewayRunOperationMetadata } from './runOperationMetadata';
+import { gatewayRunOperationMetadata, isLocalStopNotice } from './runOperationMetadata';
import { isCompletedRuntimeEnd } from './runtimeEndReason';
import * as serverSteerQueue from './serverSteerQueue';
import { watchSubAgentRun, type WatchSubAgentRunParams } from './watchSubAgentRun';
@@ -347,8 +347,8 @@ export class GatewayActionImpl {
* up as a sub-agent (right panel, the result message's thread link); when
* its parent is not streaming here (a background sub-agent), refetch the
* messages on its end too so its tool card settles.
- * - A top-level run ending that this tab did not follow: refetch the topic's
- * messages and row, in case the live attach missed a short run.
+ * - A top-level run ending that this tab neither followed nor stopped: refetch
+ * its messages and row, in case the live attach missed a short run.
*/
#followUnownedRun = (lifecycle: MuxOpLifecycleMessage): void => {
const { agentId, groupId, parentOperationId, topicId } = lifecycle.meta ?? {};
@@ -379,7 +379,8 @@ export class GatewayActionImpl {
// and a short wake-up may finish before anything else refetches the topic
// β€” so its end converges the conversation even if the live attach missed.
if (!parentOperationId) {
- // A turn of this tab still finishing settles through its own stream.
+ // A turn of this tab still finishing, or stopped here, settles through its own stream.
+ if (isLocalStopNotice(state.operations, lifecycle)) return;
if (ended && !operationSelectors.isInputLoadingByContext({ agentId, topicId })(state)) {
state.refreshMessages({ agentId, topicId }).catch(console.error);
state.refreshTopic(topicMapKey({ agentId, groupId })).catch(console.error);
@@ -389,9 +390,7 @@ export class GatewayActionImpl {
// The parent's stream carries the child's result but never the topic's
// thread list, so the sub-agent list refreshes either way.
- if (lifecycle.status === 'running' || ended) {
- state.refreshThreads(topicId).catch(console.error);
- }
+ if (lifecycle.status === 'running' || ended) state.refreshThreads(topicId).catch(console.error);
if (ended && !state.gatewayConnections[parentOperationId]) {
state.refreshMessages({ agentId, topicId }).catch(console.error);
}
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 9dbddcb27f3..faf64b988ef 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -1289,6 +1289,16 @@ export const createGatewayEventHandler = (
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' &&
@@ -1299,28 +1309,11 @@ export const createGatewayEventHandler = (
} else {
terminalMessages = get().dbMessagesMap[messageMapKey(context)] ?? [];
}
- } else if (
- (data?.reason === 'interrupted' || data?.reason === 'waiting_for_async_tool') &&
- hasStreamedContent
- ) {
- // MID-stream cancel, or a deferred-tool pause
- // (`waiting_for_async_tool`). The server's
+ } else if (data?.reason === 'waiting_for_async_tool' && hasStreamedContent) {
+ // Deferred-tool pause. The server's
// `AgentRuntimeCoordinator.resolveUiMessages` omits uiMessages
- // for both statuses precisely so we can preserve the
- // in-memory streamed content here. The executor's partial-
- // finalize catch writes the real content to DB asynchronously,
- // but it may not be durable yet β€” refetching here would race
- // against that update and clobber the streamed content with
- // the LOADING_FLAT placeholder. Keep what we have; the next
- // explicit refresh (route change, user-driven mutate) picks
- // up the finalized partial content from DB.
- //
- // The `hasStreamedContent` guard limits this skip to the case
- // where server state actually landed (server-assigned assistant
- // id from stream_start OR any chunk dispatched). If cancel
- // 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.
+ // 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);
}
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/runOperationMetadata.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/runOperationMetadata.ts
index f8988cf704c..aa985f0107f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/runOperationMetadata.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/runOperationMetadata.ts
@@ -1,4 +1,4 @@
-import type { OperationMetadata } from '@/store/chat/slices/operation/types';
+import type { Operation, OperationMetadata } from '@/store/chat/slices/operation/types';
/**
* Builds the metadata a local operation mirroring a top-level Gateway run starts with.
@@ -27,3 +27,28 @@ export const gatewayRunOperationMetadata = ({
heteroType,
serverOperationId: operationId,
});
+
+/**
+ * Whether a hub `op_lifecycle` notice reports the end of a run the user stopped in this tab.
+ *
+ * Use when:
+ * - Deciding whether such a notice should refetch the conversation. It is forwarded
+ * asynchronously and can land after the run's socket closed on the terminal frame, yet before
+ * the server's in-flight step persisted the partial reply: a refetch then replaces the
+ * streamed text with the step's empty placeholder, which the terminal handler kept on purpose.
+ *
+ * Returns:
+ * - `true` for an `interrupted` notice whose run a cancelled local `execServerAgentRuntime` op
+ * mirrors.
+ */
+export const isLocalStopNotice = (
+ operations: Record<string, Operation> | undefined,
+ notice: { operationId: string; status: string },
+): boolean =>
+ notice.status === 'interrupted' &&
+ Object.values(operations ?? {}).some(
+ (op) =>
+ op.type === 'execServerAgentRuntime' &&
+ op.status === 'cancelled' &&
+ op.metadata.serverOperationId === notice.operationId,
+ );