π€― 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(gateway): insert assistant shell on stream_start so live text renders (#16860)
YuTengjing669fbaf09cdb
diff --git a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts b/apps/server/src/modules/AgentRuntime/executors/callLlm.tsindex 0effa62564c..50babf75f8c 100644--- a/apps/server/src/modules/AgentRuntime/executors/callLlm.ts+++ b/apps/server/src/modules/AgentRuntime/executors/callLlm.ts@@ -203,11 +203,18 @@ export const callLlm =// If assistantMessageId is provided in payload, use existing message instead of creating new oneconst existingAssistantMessageId = (llmPayload as any).assistantMessageId;let assistantMessageItem: { id: string };+ // Seed fields for the client to insert this message into its local store.+ // The step_start uiMessages snapshot is resolved BEFORE this row exists,+ // so the client has no other way to learn about it until the next DB+ // refetch β chunks would silently no-op against the missing id (LOBE-11501).+ let assistantMessageSeed: Record<string, unknown> | undefined;if (existingAssistantMessageId) {// Use existing assistant message (created by execAgent)assistantMessageItem = { id: existingAssistantMessageId };log(`${stagePrefix} Using existing assistant message: %s`, existingAssistantMessageId);+ const existingRow = await ctx.messageModel.findById(existingAssistantMessageId);+ if (existingRow) assistantMessageSeed = existingRow;} else {// Create new assistant message (legacy behavior)assistantMessageItem = await ctx.messageModel.create({@@ -221,6 +228,7 @@ export const callLlm =threadId: state.metadata?.threadId,topicId: state.metadata?.topicId,});+ assistantMessageSeed = assistantMessageItem as Record<string, unknown>;log(`${stagePrefix} Created new assistant message: %s`, assistantMessageItem.id);}@@ -228,7 +236,20 @@ export const callLlm =const stepLabel = (instruction as any).stepLabel;await streamManager.publishStreamEvent(operationId, {data: {- assistantMessage: assistantMessageItem,+ // Only the seed fields the client needs β not the whole DB row.+ assistantMessage: {+ id: assistantMessageItem.id,+ ...(assistantMessageSeed && {+ agentId: assistantMessageSeed.agentId,+ groupId: assistantMessageSeed.groupId,+ model: assistantMessageSeed.model,+ parentId: assistantMessageSeed.parentId,+ provider: assistantMessageSeed.provider,+ role: assistantMessageSeed.role,+ threadId: assistantMessageSeed.threadId,+ topicId: assistantMessageSeed.topicId,+ }),+ },model,provider,...(stepLabel && { stepLabel }),diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 733aad7125a..a2eaeed73de 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -83,8 +83,31 @@ export interface StreamChunkData {// βββ Typed Event Data βββ+/**+ * The assistant message row the server created for this step.+ *+ * `id` is always present. Newer servers also ship the seed fields the client+ * needs to insert the message into its local store: the `step_start`+ * uiMessages snapshot is resolved BEFORE this row is created, so the snapshot+ * never contains it β without a local insert, every stream_chunk/stream_end+ * dispatch for the step targets a missing id and is silently dropped+ * (LOBE-11501). Older servers send only `{ id }`; clients fall back to a DB+ * refetch in that case.+ */+export interface StreamStartAssistantMessage {+ agentId?: string | null;+ groupId?: string | null;+ id: string;+ model?: string | null;+ parentId?: string | null;+ provider?: string | null;+ role?: string;+ threadId?: string | null;+ topicId?: string | null;+}+export interface StreamStartData {- assistantMessage: { id: string };+ assistantMessage: StreamStartAssistantMessage;model?: string;provider?: string;}@@ -200,11 +223,7 @@ export interface ToolResultMessage {}export type ClientMessage =- | AuthMessage- | HeartbeatMessage- | InterruptMessage- | ResumeMessage- | ToolResultMessage;+ AuthMessage | HeartbeatMessage | InterruptMessage | ResumeMessage | ToolResultMessage;// Server β Clientexport interface AuthSuccessMessage {@@ -245,12 +264,7 @@ export interface SessionCompleteMessage {* Authoritative session status. Mirrors the gateway DO's `SessionStatus`.*/export type SessionStatus =- | 'running'- | 'waiting_input'- | 'waiting_confirmation'- | 'completed'- | 'error'- | 'interrupted';+ 'running' | 'waiting_input' | 'waiting_confirmation' | 'completed' | 'error' | 'interrupted';/*** Server β Client: sent right after a `resume` replay, carrying the DO's@@ -277,11 +291,7 @@ export type ServerMessage =// βββ Connection Status βββexport type ConnectionStatus =- | 'authenticating'- | 'connected'- | 'connecting'- | 'disconnected'- | 'reconnecting';+ 'authenticating' | 'connected' | 'connecting' | 'disconnected' | 'reconnecting';// βββ Client Events βββdiff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.tsindex 0a5c404615a..d0fc340f92c 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayEventHandler.test.ts@@ -112,14 +112,22 @@ describe('createGatewayEventHandler', () => {const store = createMockStore();const handler = createHandler(store);- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' } }));+ handler(+ makeEvent('stream_start', {+ assistantMessage: { id: 'msg-step2', role: 'assistant' },+ }),+ );await flush();expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');- // Native gateway streams carry the new assistant id directly + a SoT- // uiMessages snapshot on the preceding step_start, so stream_start must- // NOT trigger a DB refetch (the refetch is what clobbered the streamed- // assistantGroup with a stale placeholder).+ // Native gateway ships the assistant seed on stream_start, so the client+ // inserts the message shell locally (createMessage) and must NOT trigger a+ // DB refetch β the refetch is what clobbered the streamed assistantGroup+ // with a stale placeholder (LOBE-11501).+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'msg-step2', type: 'createMessage' }),+ { operationId: 'op-1' },+ );expect(messageService.getMessages).not.toHaveBeenCalled();expect(store.replaceMessages).not.toHaveBeenCalled();expect(emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(@@ -516,6 +524,12 @@ describe('createGatewayEventHandler', () => {describe('visible_output_end', () => {it('marks visible loading done without completing the operation or clearing topic loading', async () => {const store = createMockStore();+ // The streamed content has landed in the store β the visible_output_end+ // guard (LOBE-11501) only clears loading once the assistant row is present+ // with its content, so seed it here to represent that state.+ store.dbMessagesMap['main_agent-1_topic-1'] = [+ { content: 'hello back', id: 'msg-initial', role: 'assistant' },+ ];const handler = createHandler(store);handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'hello back' }));@@ -1102,7 +1116,9 @@ describe('createGatewayEventHandler', () => {const handler = createHandler(store);- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-new' } }));+ handler(+ makeEvent('stream_start', { assistantMessage: { id: 'msg-new', role: 'assistant' } }),+ );handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'Hello' }));await flush();@@ -1143,7 +1159,7 @@ describe('createGatewayEventHandler', () => {const handler = createHandler(store);// Step 1: LLM call- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-1' } }));+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-1', role: 'assistant' } }));await flush();expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-1', 'op-1');@@ -1175,7 +1191,7 @@ describe('createGatewayEventHandler', () => {// carries the id directly, so it must NOT trigger a DB refetch// Only the association switch happens.vi.clearAllMocks();- handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-2' } }));+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-2', role: 'assistant' } }));await flush();expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-2', 'op-1');expect(messageService.getMessages).not.toHaveBeenCalled();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.tsnew file mode 100644index 00000000000..a5d9b66df1e--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.test.ts@@ -0,0 +1,163 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++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';++const context = {+ agentId: 'agent-1',+ topicId: 'topic-1',+} as ConversationContext;++const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['data']) =>+ ({+ data,+ id: 'event-1',+ operationId: 'op-1',+ stepIndex: 1,+ timestamp: 0,+ type,+ }) as AgentStreamEvent;++const createStore = (dbMessagesMap: Record<string, UIChatMessage[]> = {}) =>+ ({+ associateMessageWithOperation: vi.fn(),+ completeOperation: vi.fn(),+ dbMessagesMap,+ internal_dispatchMessage: vi.fn(),+ internal_toggleToolCallingStreaming: vi.fn(),+ operations: {},+ replaceMessages: vi.fn(),+ startOperation: vi.fn(() => ({+ abortController: new AbortController(),+ operationId: 'reasoning-op',+ })),+ updateOperationMetadata: vi.fn(),+ }) as unknown as ChatStore;++// The handler enqueues work on an internal promise chain; flush the microtask+// queue so async event handlers settle before assertions.+const flush = async () => {+ for (let i = 0; i < 5; i += 1) await Promise.resolve();+};++describe('createGatewayEventHandler', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(agentSignalBridge, 'emitClientAgentSignalSourceEvent').mockResolvedValue(undefined);+ });++ it('inserts the assistant shell locally when stream_start carries the message seed (new server)', async () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed-msg',+ context,+ operationId: 'op-1',+ });++ handler(+ makeEvent('stream_start', {+ assistantMessage: {+ id: 'step2-msg',+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ },+ }),+ );+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ {+ id: 'step2-msg',+ type: 'createMessage',+ value: expect.objectContaining({+ content: '',+ model: 'gpt-4o',+ provider: 'openai',+ role: 'assistant',+ topicId: 'topic-1',+ }),+ },+ { operationId: 'op-1' },+ );+ // No DB roundtrip needed when the seed is present.+ expect(store.replaceMessages).not.toHaveBeenCalled();+ });++ it('falls back to a DB refetch when stream_start ships only { id } (old server)', async () => {+ const getMessages = vi+ .spyOn(messageService, 'getMessages')+ .mockResolvedValue([] as unknown as UIChatMessage[]);+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed-msg',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('stream_start', { assistantMessage: { id: 'step2-msg' } }));+ await flush();++ expect(getMessages).toHaveBeenCalled();+ expect(store.replaceMessages).toHaveBeenCalled();+ // No local shell insert when the seed is absent.+ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ });++ it('does not insert a shell when the assistant row is already in the store', async () => {+ const store = createStore({+ key: [{ content: 'existing', id: 'step2-msg', role: 'assistant' } as UIChatMessage],+ });+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'seed-msg',+ context,+ operationId: 'op-1',+ });++ handler(+ makeEvent('stream_start', {+ assistantMessage: { id: 'step2-msg', role: 'assistant' },+ }),+ );+ await flush();++ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ });++ it('skips the visible_output_end hint while the assistant row is missing (LOBE-11501)', async () => {+ const store = createStore();+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'missing-msg',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('visible_output_end'));+ await flush();++ expect(store.updateOperationMetadata).not.toHaveBeenCalled();+ });++ it('honors the visible_output_end hint once the streamed content has landed', async () => {+ const store = createStore({+ key: [{ content: 'answer', id: 'answer-msg', role: 'assistant' } as UIChatMessage],+ });+ const handler = createGatewayEventHandler(() => store, {+ assistantMessageId: 'answer-msg',+ context,+ operationId: 'op-1',+ });++ handler(makeEvent('visible_output_end'));+ await flush();++ expect(store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {+ visibleLoadingDone: true,+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex d9248934afa..89e74bfa05b 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -22,6 +22,7 @@ import type {AgentRunLifecycle,RunScope,} from '@/store/chat/slices/agentRun/actions/lifecycle/types';+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';import type { ChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';@@ -425,6 +426,45 @@ export const createGatewayEventHandler = (// Server-confirmed assistant id is durable state β preserve it on// interrupt instead of falling back to a placeholder-clobbering refetch.hasStreamedContent = true;++ // The step_start uiMessages snapshot is resolved BEFORE the server+ // creates this step's assistant row, so for every step after the+ // first the message is NOT in the store yet. `updateMessage`+ // dispatches on a missing id are silent no-ops, so without an+ // insert here the whole step renders nothing until the next DB+ // refetch β and the final step has none before agent_runtime_end,+ // which is how "loading cleared but no text" happened (LOBE-11501).+ const stored = dbMessageSelectors.getDbMessageById(newAssistantMessageId)(get());+ if (!stored) {+ const seed = data?.assistantMessage;+ if (seed?.role) {+ // Newer servers ship the message seed on stream_start β insert+ // the shell locally so chunks land immediately, zero roundtrips.+ get().internal_dispatchMessage(+ {+ id: newAssistantMessageId,+ type: 'createMessage',+ value: {+ agentId: seed.agentId ?? context.agentId,+ content: '',+ groupId: seed.groupId ?? undefined,+ model: seed.model ?? data?.model,+ parentId: seed.parentId ?? undefined,+ provider: seed.provider ?? data?.provider,+ role: 'assistant',+ threadId: seed.threadId ?? undefined,+ topicId: seed.topicId ?? context.topicId ?? undefined,+ },+ },+ dispatchContext,+ );+ } else {+ // Older servers send only `{ id }` β fall back to a DB read.+ // The row is inserted before stream_start is published, so the+ // fetch is guaranteed to bring it into the store.+ await fetchAndReplaceMessages(get, context).catch(console.error);+ }+ }}// Close any reasoning op carried over from the previous step.@@ -438,12 +478,11 @@ export const createGatewayEventHandler = (accumulatedReasoning = '';get().updateOperationMetadata(operationId, { visibleLoadingDone: false });- // Skip the DB read ONLY for native gateway streams β those carry- // `assistantMessage.id` directly on stream_start AND the preceding- // `step_start` already carried the SoT uiMessages snapshot, so- // chunks have a valid target in `dbMessagesMap` already. Removing- // the await here is what un-blocks the enqueue chain so live- // chunks can land mid-stream.+ // Native gateway streams carry `assistantMessage.id` directly on+ // stream_start and the shell-insert above guarantees a valid chunk+ // target in `dbMessagesMap`, so they skip this DB read β that skip+ // is what un-blocks the enqueue chain so live chunks can land+ // mid-stream.//// Hetero CLI adapters (Claude Code / Codex) never set// `assistantMessage.id` on stream_start, so the DB read stays@@ -584,6 +623,15 @@ export const createGatewayEventHandler = (case 'visible_output_end': {enqueue(() => {+ // Guard: only clear visible loading when the streamed content has+ // actually landed in the store. If the message shell is missing (or+ // text streamed but never applied), clearing here would show+ // "loading done" with the answer still invisible (LOBE-11501) β+ // skip the hint instead and let agent_runtime_end reconcile content+ // and loading in the same frame, i.e. the pre-early-hint behavior.+ const stored = dbMessageSelectors.getDbMessageById(currentAssistantMessageId)(get());+ if (!stored || (accumulatedContent && !stored.content)) return;+get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);endReasoningIfNeeded();// Example: CC/Codex may emit stream_end -> stream_start(newStep) fordiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.tsindex 935bf23384e..b833fb67393 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.test.ts@@ -3,6 +3,7 @@ import type { ConversationContext } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';import type { ChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';@@ -13,6 +14,14 @@ const context = {topicId: 'topic-1',} as ConversationContext;+const bucketKey = messageMapKey({+ agentId: context.agentId ?? '',+ groupId: context.groupId,+ scope: context.scope,+ threadId: context.threadId,+ topicId: context.topicId,+});+const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['data']) =>({data,@@ -23,11 +32,11 @@ const makeEvent = (type: AgentStreamEvent['type'], data?: AgentStreamEvent['datatype,}) as AgentStreamEvent;-const createStore = () =>+const createStore = (dbMessagesMap: Record<string, any[]> = {}) =>({associateMessageWithOperation: vi.fn(),completeOperation: vi.fn(),- dbMessagesMap: {},+ dbMessagesMap,internal_dispatchMessage: vi.fn(),startOperation: vi.fn(() => ({abortController: new AbortController(),@@ -38,7 +47,11 @@ const createStore = () =>describe('createGatewayMemberStreamHandler', () => {it('clears visible loading for the local member op without completing it', () => {- const store = createStore();+ // The member row is already hydrated into the store (group hydration done),+ // so the visible_output_end hint is honored.+ const store = createStore({+ [bucketKey]: [{ content: 'hello', id: 'member-msg', role: 'assistant' }],+ });const handler = createGatewayMemberStreamHandler(() => store, {context,ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),@@ -54,4 +67,22 @@ describe('createGatewayMemberStreamHandler', () => {});expect(store.completeOperation).not.toHaveBeenCalled();});++ it('skips the visible loading hint while the member row is not yet in the store (LOBE-11501)', () => {+ // Group hydration is still in flight, so the member row hasn't landed. Clearing+ // loading here would show a "done" column with no text β the guard skips it and+ // lets the terminal barrier reconcile.+ const store = createStore();+ const handler = createGatewayMemberStreamHandler(() => store, {+ context,+ ensureGroupHydrated: vi.fn().mockResolvedValue(undefined),+ memberOperationId: 'server-member-op',+ parentOperationId: 'owner-op',+ });++ handler(makeEvent('stream_start', { assistantMessage: { id: 'member-msg' } }));+ handler(makeEvent('visible_output_end'));++ expect(store.updateOperationMetadata).not.toHaveBeenCalled();+ });});diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.tsindex 44e22b789fa..48425270d09 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayMemberStreamHandler.ts@@ -153,6 +153,17 @@ export const createGatewayMemberStreamHandler = (// supervisor's terminal barrier refetches the group tree. Clear only// the member column's visible loading; terminal reconciliation still// belongs to agent_runtime_end/error.+ //+ // Same guard as the main handler (LOBE-11501): if the member row isn't+ // in the store yet (group hydration in flight) or its streamed text+ // hasn't landed, clearing loading would show a "done" column with no+ // text β skip the hint and let the terminal barrier reconcile both.+ if (currentAssistantMessageId) {+ const stored = (get().dbMessagesMap[bucketKey] ?? []).find(+ (m) => m.id === currentAssistantMessageId,+ );+ if (!stored || (accumulatedContent && !stored.content)) break;+ }if (localOperationId) {get().updateOperationMetadata(localOperationId, { visibleLoadingDone: true });}