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(agent-runtime): show a server-joined steer message as soon as its reply starts (#22130)

Arvin Xua94d7f69a659
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
index e5bf94e851c..aefeb22d7a3 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -110,8 +110,10 @@ export class ServerMessageTransport implements MessageTransport {
return message
? {
agentId: message.agentId,
+ content: message.content,
groupId: message.groupId,
id: message.id,
+ metadata: message.metadata,
model: message.model,
parentId: message.parentId,
provider: message.provider,
diff --git a/packages/agent-gateway-client/src/index.ts b/packages/agent-gateway-client/src/index.ts
index bf03561c49e..2543895ec0f 100644
--- a/packages/agent-gateway-client/src/index.ts
+++ b/packages/agent-gateway-client/src/index.ts
@@ -91,6 +91,7 @@ export type {
StreamChunkData,
StreamChunkType,
StreamStartData,
+ StreamStartParentMessage,
SubAgentProgressData,
TerminalSessionStatus,
ToolEndData,
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 89250d14aa7..95ef93950d1 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -190,9 +190,25 @@ export interface StreamStartAssistantMessage {
topicId?: string | null;
}
+/**
+ * A follow-up the server joined into the running turn: the user message this
+ * step's assistant row hangs off. It is created mid-run, after the
+ * `step_start` snapshot, so without it the client has no copy until the step
+ * ends and the queued message vanishes from both the tray and the chat.
+ */
+export interface StreamStartParentMessage {
+ content: string;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ parentId?: string | null;
+ role: 'user';
+}
+
export interface StreamStartData {
assistantMessage: StreamStartAssistantMessage;
model?: string;
+ /** Sent only when the parent is a steer user message. */
+ parentMessage?: StreamStartParentMessage;
provider?: string;
}
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 73f2c3ca085..b757f7f83f8 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -170,6 +170,70 @@ const createHost = (
});
describe('callLlm executor', () => {
+ it('ships a joined steer parent on stream_start so the client can show it before the step ends', async () => {
+ const transport = createCallTransport();
+ const messages = createMessageTransport();
+ vi.mocked(messages.findById).mockResolvedValue({
+ content: 'why not the Feishu CLI',
+ id: 'steer-1',
+ metadata: { steer: true, trigger: 'chat' },
+ parentId: 'assistant-0',
+ role: 'user',
+ });
+ vi.mocked(messages.createAssistantMessage).mockResolvedValue({
+ id: 'assistant-1',
+ parentId: 'steer-1',
+ role: 'assistant',
+ });
+ const stream = createStreamSink();
+ const host = createHost(transport.llm, messages, stream);
+
+ await callLlm(host)(
+ { payload: { ...instruction.payload, parentMessageId: 'steer-1' }, type: 'call_llm' },
+ createState(),
+ { phase: 'user_input' },
+ );
+
+ expect(stream.publishEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ parentMessage: {
+ content: 'why not the Feishu CLI',
+ id: 'steer-1',
+ metadata: { steer: true, trigger: 'chat' },
+ parentId: 'assistant-0',
+ role: 'user',
+ },
+ }),
+ type: 'stream_start',
+ }),
+ );
+ });
+
+ it('leaves a non-steer parent off stream_start: the client already has it', async () => {
+ const transport = createCallTransport();
+ const messages = createMessageTransport();
+ vi.mocked(messages.findById).mockResolvedValue({
+ content: 'hello',
+ id: 'user-1',
+ metadata: {},
+ role: 'user',
+ });
+ const stream = createStreamSink();
+ const host = createHost(transport.llm, messages, stream);
+
+ await callLlm(host)(
+ { payload: { ...instruction.payload, parentId: 'user-1' }, type: 'call_llm' },
+ createState(),
+ { phase: 'user_input' },
+ );
+
+ const streamStart = vi
+ .mocked(stream.publishEvent)
+ .mock.calls.find(([event]) => event.type === 'stream_start');
+ expect(streamStart?.[0].data).not.toHaveProperty('parentMessage');
+ });
+
it('prepares the assistant message and delegates call_llm execution to the LLM transport', async () => {
const state = createState();
const transport = createCallTransport();
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index 5e003ef9064..74c937fdf5d 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -5,6 +5,7 @@ import type {
LLMRetryPolicy,
LLMTrace,
LLMTransport,
+ RuntimeMessageRef,
} from '../transport';
import type {
AgentEvent,
@@ -273,6 +274,24 @@ const buildAssistantMessageSeed = (
}),
});
+/**
+ * A steer message the server joined into the running turn is created after
+ * the step's `step_start` snapshot, so the client has no copy of it. Ship it
+ * with `stream_start` (the preflight read already loaded it) so the client
+ * shows it above this step's reply instead of only after the step ends.
+ */
+const buildSteerParentSeed = (parent: RuntimeMessageRef | undefined) => {
+ if (parent?.role !== 'user' || !parent.metadata?.steer) return;
+
+ return {
+ content: parent.content ?? '',
+ id: parent.id,
+ metadata: parent.metadata,
+ parentId: parent.parentId ?? null,
+ role: 'user' as const,
+ };
+};
+
/**
* Package-owned `call_llm` executor entry point.
*
@@ -299,9 +318,10 @@ export const callLlm =
}
const parentId = llmPayload.parentId || llmPayload.parentMessageId;
+ let parentMessage: RuntimeMessageRef | undefined;
if (parentId) {
- const parentExists = await transports.messages.findById(parentId);
- if (!parentExists) {
+ parentMessage = await transports.messages.findById(parentId);
+ if (!parentMessage) {
const error = createConversationParentMissingError(parentId);
await transports.stream.publishEvent({
data: formatErrorEventData(error, 'parent_message_preflight'),
@@ -359,11 +379,13 @@ export const callLlm =
? ((await transports.messages.findById(existingAssistantMessageId)) ?? assistantMessage)
: assistantMessage;
const stepLabel = (instruction as { stepLabel?: string }).stepLabel;
+ const steerParentSeed = buildSteerParentSeed(parentMessage);
await transports.stream.publishEvent({
data: {
assistantMessage: buildAssistantMessageSeed(assistantMessage, assistantMessageSeed),
model,
+ ...(steerParentSeed && { parentMessage: steerParentSeed }),
provider,
...(stepLabel && { stepLabel }),
},
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
index df997f9de2b..7f4fb9cdfb5 100644
--- a/packages/agent-runtime/src/transport/message.ts
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -3,8 +3,12 @@ import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@l
/** Minimal reference an executor needs back after creating a message. */
export interface RuntimeMessageRef {
agentId?: string | null;
+ /** Returned by `findById` reads only; creates leave it out. */
+ content?: string | null;
groupId?: string | null;
id: string;
+ /** Returned by `findById` reads only; creates leave it out. */
+ metadata?: Record<string, any> | null;
model?: string | null;
parentId?: string | null;
provider?: string | null;
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.streaming.test.ts
index 74cfa3ad95a..4d757642dbd 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.streaming.test.ts
@@ -74,6 +74,65 @@ describe('createGatewayEventHandler β€” stream lifecycle events', () => {
);
});
+ it('inserts a server-joined steer message ahead of the reply without a DB refetch', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ handler(
+ makeEvent('stream_start', {
+ assistantMessage: { id: 'msg-step2', parentId: 'steer-1', role: 'assistant' },
+ parentMessage: {
+ content: 'why not the Feishu CLI',
+ id: 'steer-1',
+ metadata: { steer: true },
+ parentId: 'msg-step1',
+ role: 'user',
+ },
+ }),
+ );
+ await flush();
+
+ const created = vi
+ .mocked(store.internal_dispatchMessage)
+ .mock.calls.filter(([action]) => action.type === 'createMessage')
+ .map(([action]) => action);
+ expect(created).toEqual([
+ expect.objectContaining({
+ id: 'steer-1',
+ value: expect.objectContaining({
+ content: 'why not the Feishu CLI',
+ metadata: { steer: true },
+ parentId: 'msg-step1',
+ role: 'user',
+ }),
+ }),
+ expect.objectContaining({
+ id: 'msg-step2',
+ value: expect.objectContaining({ parentId: 'steer-1', role: 'assistant' }),
+ }),
+ ]);
+ expect(messageService.getMessages).not.toHaveBeenCalled();
+ });
+
+ it('does not insert the steer parent twice when the store already has it', async () => {
+ const store = createMockStore();
+ store.dbMessagesMap = { 'session_agent-1_topic-1': [{ id: 'steer-1', role: 'user' }] };
+ const handler = createHandler(store);
+
+ handler(
+ makeEvent('stream_start', {
+ assistantMessage: { id: 'msg-step2', parentId: 'steer-1', role: 'assistant' },
+ parentMessage: { content: 'x', id: 'steer-1', role: 'user' },
+ }),
+ );
+ await flush();
+
+ expect(store.internal_dispatchMessage).not.toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'steer-1', type: 'createMessage' }),
+ expect.anything(),
+ );
+ });
+
it('should keep current ID if event data has no assistantMessage', async () => {
const store = createMockStore();
const handler = createHandler(store);
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 8b94b2c6d12..d8caa4f3baf 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts
@@ -44,6 +44,7 @@ import {
resolveRuntimeEndStatus,
} from './runtimeEndReason';
import { applyStepMetrics } from './stepMetrics';
+import { insertStreamStartSeeds } from './streamStartSeed';
// Lazy-loaded to break the import cycle:
// gateway.ts β†’ gatewayEventHandler.ts β†’ executors/index.ts (which pulls in
@@ -640,37 +641,12 @@ export const createGatewayEventHandler = (
// 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.
+ // The step_start uiMessages snapshot predates this step's rows;
+ // insert the seeded ones so chunks land on a stored message.
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,
- );
+ if (data?.assistantMessage?.role) {
+ insertStreamStartSeeds(get, data, context, dispatchContext);
} else {
// Older servers send only `{ id }` β€” fall back to a DB read.
// The row is inserted before stream_start is published, so the
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts
new file mode 100644
index 00000000000..caae4da9afe
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts
@@ -0,0 +1,69 @@
+import type { StreamStartData } from '@lobechat/agent-gateway-client';
+import type { ConversationContext } from '@lobechat/types';
+
+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
+import type { ChatStore } from '@/store/chat/store';
+
+/**
+ * Insert the rows a seeded `stream_start` names into the local store, so the
+ * step renders without a DB read. Newer servers ship the assistant seed; the
+ * caller falls back to a refetch when there is none.
+ *
+ * - The step's assistant row: the `step_start` snapshot is resolved before it
+ * is created, and chunks dispatched to a missing id are dropped.
+ * - A queued follow-up the server joined into the run (`parentMessage`): its
+ * user row is created after that snapshot too. Without it the message is
+ * gone from both the tray and the chat until the step ends.
+ */
+export const insertStreamStartSeeds = (
+ get: () => ChatStore,
+ data: StreamStartData,
+ context: ConversationContext,
+ dispatchContext: { operationId: string },
+): void => {
+ const { assistantMessage: seed, parentMessage: parent } = data;
+ const shared = {
+ agentId: seed.agentId ?? context.agentId,
+ groupId: seed.groupId ?? undefined,
+ threadId: seed.threadId ?? undefined,
+ topicId: seed.topicId ?? context.topicId ?? undefined,
+ };
+
+ // Ahead of the reply, so the list keeps the turn's order.
+ if (
+ parent &&
+ parent.id === seed.parentId &&
+ !dbMessageSelectors.getDbMessageById(parent.id)(get())
+ ) {
+ get().internal_dispatchMessage(
+ {
+ id: parent.id,
+ type: 'createMessage',
+ value: {
+ ...shared,
+ content: parent.content,
+ metadata: parent.metadata ?? undefined,
+ parentId: parent.parentId ?? undefined,
+ role: 'user',
+ },
+ },
+ dispatchContext,
+ );
+ }
+
+ get().internal_dispatchMessage(
+ {
+ id: seed.id,
+ type: 'createMessage',
+ value: {
+ ...shared,
+ content: '',
+ model: seed.model ?? data.model,
+ parentId: seed.parentId ?? undefined,
+ provider: seed.provider ?? data.provider,
+ role: 'assistant',
+ },
+ },
+ dispatchContext,
+ );
+};