π€― 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(agent-runtime): preserve streamed content across mid-stream cancel (#15173)
Arvin Xua8faccff66b5
diff --git a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex c9972a6e170..43281d7cf42 100644--- a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -113,9 +113,21 @@ export class AgentRuntimeCoordinator {* failures β stream-event publishing must never fail the surrounding* save. Errors are logged and surfaced to the client as a missing field,* which falls back to the legacy refresh path.+ *+ * LOBE-9523: skip the resolve entirely when the run is moving into+ * `interrupted`. The executor's per-step finalize at line 1078 of+ * RuntimeExecutors only runs on the success path, so a mid-stream cancel+ * leaves the assistant row as the LOADING_FLAT placeholder. Pushing that+ * placeholder as SoT would clobber the client's in-memory streamed+ * content. The executor's catch-block partial-finalize (LOBE-9523 fix #1)+ * writes the real partial content asynchronously, but that update may+ * not be durable by the time we publish β leaving the field undefined+ * lets the client preserve its in-memory state (`gatewayEventHandler.ts`+ * also skips the DB refetch fallback when reason='interrupted').*/private async resolveUiMessages(state: AgentState): Promise<UIChatMessage[] | undefined> {if (!this.uiMessagesResolver) return undefined;+ if (state.status === 'interrupted') return undefined;try {return await this.uiMessagesResolver(state);} catch (error) {diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 68fd2402ca4..8c1ee7621b2 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -1196,6 +1196,47 @@ export const createRuntimeExecutors = (continue;}+ // LOBE-9523: cancel/interrupt path β the model-runtime stream was aborted+ // before reaching the post-stream finalize at line 1078, so the DB row is+ // still the LOADING_FLAT placeholder. Persist whatever partial content the+ // `onText` / `onThinking` / `onToolsCalling` callbacks already accumulated+ // so (a) a subsequent reload still shows the user's streamed answer, and+ // (b) the agent_runtime_end uiMessages snapshot doesn't carry placeholder+ // values that would clobber the client's in-memory streamed content.+ if (interrupted && (content || thinkingContent || toolsCalling.length > 0)) {+ try {+ const persistedTools =+ toolsCalling.length > 0+ ? toolsCalling.map((t) => ({+ ...t,+ arguments: sanitizeToolCallArguments(t.arguments),+ }))+ : undefined;+ const interruptedReasoning = thinkingContent+ ? { content: thinkingContent }+ : undefined;+ const interruptedMetadata: Record<string, any> = { interruptedMidStream: true };+ if (currentStepUsage && typeof currentStepUsage === 'object') {+ Object.assign(interruptedMetadata, currentStepUsage);+ }+ await ctx.messageModel.update(assistantMessageItem.id, {+ content,+ metadata: interruptedMetadata,+ reasoning: interruptedReasoning,+ tools: persistedTools,+ });+ log(+ '[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',+ operationLogId,+ content.length,+ thinkingContent.length,+ toolsCalling.length,+ );+ } catch (persistErr) {+ log('[%s] Interrupted finalize update failed: %O', operationLogId, persistErr);+ }+ }+throw error;}}diff --git a/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.tsindex a7d0fd81df1..a69d4d79002 100644--- a/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts@@ -505,5 +505,63 @@ describe('AgentRuntimeCoordinator', () => {uiMessages: undefined,});});++ // LOBE-9523: cancel/interrupt path leaves the streaming assistant row+ // at the LOADING_FLAT placeholder until the executor's partial-finalize+ // catch writes the accumulated content asynchronously. Publishing a+ // pre-finalize snapshot would clobber the client's in-memory streamed+ // content, so the resolver is skipped entirely for status='interrupted'.+ it('skips uiMessages on saveAgentState when status=interrupted (LOBE-9523)', async () => {+ const resolver = vi.fn().mockResolvedValue([{ id: 'placeholder', role: 'assistant' }]);+ const coordinatorWithResolver = new AgentRuntimeCoordinator({+ stateManager: mockStateManager,+ streamEventManager: mockStreamManager,+ uiMessagesResolver: resolver,+ });++ const previousState = { status: 'running', stepCount: 3 };+ const newState = { status: 'interrupted', stepCount: 3 };+ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinatorWithResolver.saveAgentState('op-int-1', newState as any);++ // Resolver should NOT be called β the whole point is to avoid the DB+ // read that would return the LOADING_FLAT placeholder.+ expect(resolver).not.toHaveBeenCalled();+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: newState,+ operationId: 'op-int-1',+ reason: 'interrupted',+ stepIndex: 3,+ uiMessages: undefined,+ });+ });++ it('skips uiMessages on saveStepResult when stepResult.newState.status=interrupted (LOBE-9523)', async () => {+ const resolver = vi.fn().mockResolvedValue([{ id: 'placeholder', role: 'assistant' }]);+ const coordinatorWithResolver = new AgentRuntimeCoordinator({+ stateManager: mockStateManager,+ streamEventManager: mockStreamManager,+ uiMessagesResolver: resolver,+ });++ const stepResult = {+ executionTime: 100,+ newState: { status: 'interrupted', stepCount: 2 },+ stepIndex: 2,+ };+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 1 });++ await coordinatorWithResolver.saveStepResult('op-int-2', stepResult as any);++ expect(resolver).not.toHaveBeenCalled();+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({+ finalState: stepResult.newState,+ operationId: 'op-int-2',+ reason: 'interrupted',+ stepIndex: 2,+ uiMessages: undefined,+ });+ });});});diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 2f5dc744a09..bf8f08a0b54 100644--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -1377,6 +1377,140 @@ describe('RuntimeExecutors', () => {expect(callArgs).not.toHaveProperty('onboardingContext');});});++ // LOBE-9523: cancel/interrupt mid-stream β the model-runtime call is+ // aborted before the post-stream finalize at line 1078, so the DB row+ // would normally stay at LOADING_FLAT placeholder. The executor's+ // inner catch must persist whatever partial content the streaming+ // callbacks already accumulated so (a) reload doesn't lose the user's+ // streamed answer and (b) any later uiMessages snapshot reflects real+ // content instead of placeholder.+ describe('interrupted mid-stream partial finalize (LOBE-9523)', () => {+ it('persists accumulated content + reasoning when stream throws and operation is interrupted', async () => {+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {+ await options?.callback?.onText?.('Hello, this is a partial ');+ await options?.callback?.onText?.('streamed answer.');+ await options?.callback?.onThinking?.('Let me think step by step. ');+ await options?.callback?.onThinking?.('First, consider the context.');+ throw new Error('AbortError: stream aborted');+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);++ // Make isOperationInterrupted return true so the catch hits the+ // partial-finalize branch instead of the retry path.+ const interruptedCtx: RuntimeExecutorContext = {+ ...ctx,+ loadAgentState: vi.fn().mockResolvedValue({ status: 'interrupted' }),+ };+ mockMessageModel.create.mockResolvedValueOnce({ id: 'asst-interrupted' });++ const executors = createRuntimeExecutors(interruptedCtx);+ const state = createMockState();++ await expect(+ executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hi', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ },+ state,+ ),+ ).rejects.toThrow();++ // The success-path update at line 1078 is unreachable when the+ // stream throws β only the cancel-path partial-finalize remains.+ expect(mockMessageModel.update).toHaveBeenCalledWith(+ 'asst-interrupted',+ expect.objectContaining({+ content: 'Hello, this is a partial streamed answer.',+ reasoning: { content: 'Let me think step by step. First, consider the context.' },+ metadata: expect.objectContaining({ interruptedMidStream: true }),+ }),+ );+ });++ it('does NOT persist when interrupted but no content was streamed (avoid empty-content noise)', async () => {+ const mockChat = vi.fn().mockImplementation(async () => {+ throw new Error('AbortError: stream aborted before any chunks');+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);++ const interruptedCtx: RuntimeExecutorContext = {+ ...ctx,+ loadAgentState: vi.fn().mockResolvedValue({ status: 'interrupted' }),+ };+ mockMessageModel.create.mockResolvedValueOnce({ id: 'asst-empty-interrupt' });++ const executors = createRuntimeExecutors(interruptedCtx);+ const state = createMockState();++ await expect(+ executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hi', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ },+ state,+ ),+ ).rejects.toThrow();++ // No content / reasoning / tools accumulated β skip the update so+ // we don't overwrite the placeholder with another empty record+ // (and don't bump `updated_at` for no functional reason).+ expect(mockMessageModel.update).not.toHaveBeenCalled();+ });++ it('does NOT persist partial content on non-interrupt errors (preserves existing retry/error flow)', async () => {+ // Use a stop-classified error (status 400) so the retry loop exits+ // immediately and the test doesn't burn the timeout on backoff sleeps.+ const mockChat = vi.fn().mockImplementation(async (_payload, options) => {+ await options?.callback?.onText?.('Partial before crash');+ const err: any = new Error('invalid_request_error: bad input');+ err.errorType = 'ProviderBizError';+ err.status = 400;+ throw err;+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ chat: mockChat } as any);++ // loadAgentState returns running β not interrupted β so the partial-+ // finalize branch should be skipped even with accumulated content.+ const runningCtx: RuntimeExecutorContext = {+ ...ctx,+ loadAgentState: vi.fn().mockResolvedValue({ status: 'running' }),+ };+ mockMessageModel.create.mockResolvedValueOnce({ id: 'asst-error' });++ const executors = createRuntimeExecutors(runningCtx);+ const state = createMockState();++ await expect(+ executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hi', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ },+ state,+ ),+ ).rejects.toThrow();++ expect(mockMessageModel.update).not.toHaveBeenCalled();+ });+ });});describe('call_tool executor', () => {diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex c2c8ab029f5..3714c9bcae3 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -654,6 +654,77 @@ describe('createGatewayEventHandler', () => {}),);});++ // LOBE-9523: MID-stream cancel. The server-side coordinator skips the+ // uiMessages snapshot when state.status='interrupted' to avoid pushing+ // a LOADING_FLAT placeholder. The client must mirror that intent: when+ // `reason='interrupted'` arrives without uiMessages AND we already have+ // server-confirmed streamed state, do NOT fall back to a DB refetch β+ // the executor's partial-finalize catch is still racing to write the+ // real content, and a fetch here would return placeholder and clobber+ // in-memory streamed content.+ it('should NOT refetch from DB when reason=interrupted AND stream had progressed (LOBE-9523)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // Simulate a stream that had progressed: server-assigned assistant id+ // arrived via stream_start, then a text chunk landed.+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-server' } }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'partial answer' }));+ await flush();+ vi.mocked(messageService.getMessages).mockClear();+ store.replaceMessages.mockClear();++ handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(messageService.getMessages).not.toHaveBeenCalled();+ expect(store.replaceMessages).not.toHaveBeenCalled();+ });++ // Reviewer feedback on PR #15173: if cancel arrives BEFORE any+ // stream activity (no server-assigned assistant id, no chunks), the+ // optimistic `tmp_*` placeholder messages are the only client-side+ // state and they need the DB refetch to be reconciled with the+ // server-side rows. Skipping the fallback would leave the tmp_*+ // ids stuck in the store indefinitely.+ it('should refetch from DB when reason=interrupted but stream never progressed (LOBE-9523 reviewer fix)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ // No stream_start / stream_chunk before the cancel β only optimistic+ // local state exists, no server-confirmed assistant id, no chunks.+ handler(makeEvent('agent_runtime_end', { reason: 'interrupted' }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ // Refetch IS called so the tmp_* placeholders get reconciled.+ expect(messageService.getMessages).toHaveBeenCalled();+ expect(store.replaceMessages).toHaveBeenCalled();+ });++ it('should still use uiMessages SoT when reason=interrupted but server included a snapshot', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const uiMessages = [{ id: 'msg-initial', role: 'assistant', content: 'partial' }];++ handler(+ makeEvent('agent_runtime_end', {+ reason: 'interrupted',+ uiMessages,+ }),+ );+ await flush();++ // uiMessages present takes precedence over the interrupted skip β the+ // SoT push is authoritative when server chose to send it.+ expect(store.replaceMessages).toHaveBeenCalledWith(uiMessages, {+ action: 'gateway/agent_runtime_end',+ context: expect.any(Object),+ });+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });});describe('error', () => {diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex 8c8423d888d..eb7bf62ad6d 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -219,6 +219,15 @@ export const createGatewayEventHandler = (let accumulatedContent = '';let accumulatedReasoning = '';+ // LOBE-9523: tracks whether any server-confirmed state has actually arrived+ // (server-assigned assistant id, streamed text/reasoning/tools, or a SoT+ // uiMessages snapshot). Used by `agent_runtime_end` to decide between+ // preserving in-memory streamed content (when interrupted MID-stream) vs.+ // falling back to a DB refetch (when interrupted BEFORE any server state+ // landed β otherwise the optimistic `tmp_*` placeholder messages stay in+ // the store indefinitely).+ let hasStreamedContent = false;+// Active reasoning sub-op id. Mirrors the LLM `StreamingHandler` lifecycle so// `isMessageInReasoning(messageId)` (which drives the Thinking UI's// "thinking..." title + auto-expand) flips to `true` while thinking is@@ -269,6 +278,9 @@ export const createGatewayEventHandler = (currentAssistantMessageId = newAssistantMessageId;// Associate the new message with the operation so UI shows generating stateget().associateMessageWithOperation(currentAssistantMessageId, operationId);+ // Server-confirmed assistant id is durable state β preserve it on+ // interrupt instead of falling back to a placeholder-clobbering refetch.+ hasStreamedContent = true;}// Close any reasoning op carried over from the previous step.@@ -343,6 +355,7 @@ export const createGatewayEventHandler = (// `StreamingHandler.handleText` for the same transition.endReasoningIfNeeded();accumulatedContent += data.content;+ hasStreamedContent = true;get().internal_dispatchMessage({id: currentAssistantMessageId,@@ -356,6 +369,7 @@ export const createGatewayEventHandler = (if (data.chunkType === 'reasoning' && data.reasoning) {startReasoningIfNeeded();accumulatedReasoning += data.reasoning;+ hasStreamedContent = true;get().internal_dispatchMessage({id: currentAssistantMessageId,@@ -368,6 +382,7 @@ export const createGatewayEventHandler = (if (data.chunkType === 'tools_calling' && data.toolsCalling) {endReasoningIfNeeded();+ hasStreamedContent = true;get().internal_dispatchMessage({id: currentAssistantMessageId,@@ -501,7 +516,7 @@ export const createGatewayEventHandler = (case 'agent_runtime_end': {enqueue(async () => {- const data = event.data as { uiMessages?: UIChatMessage[] } | undefined;+ const data = event.data as { reason?: string; uiMessages?: UIChatMessage[] } | undefined;void emitClientAgentSignalSourceEvent({payload: {@@ -536,6 +551,24 @@ export const createGatewayEventHandler = (action: 'gateway/agent_runtime_end',context,});+ } else if (data?.reason === 'interrupted' && hasStreamedContent) {+ // LOBE-9523: MID-stream cancel. The server's+ // `AgentRuntimeCoordinator.resolveUiMessages` omits uiMessages+ // for status='interrupted' 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.} else {await fetchAndReplaceMessages(get, context).catch(console.error);}