π€― 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(hetero): show a live steer as soon as Claude Code reads it (#23041)
Rdmclin255a4ff8494a1
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.tsindex d80a26b83ee..c17adfa0ec0 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.steer.test.ts@@ -42,16 +42,23 @@ describe('HeterogeneousPersistenceHandler β steer messages', () => {it('opens the reply to a picked-up message under it, and names it on the stream_start', async () => {consumeDelivery({ 'msg-steer': 'look at Codex too' });- const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });+ const h = createHarness({+ assistantAgentId: 'agt-exec',+ assistantMessageId: 'asst-1',+ operationId: OP,+ topicAgentId: 'agt-owner',+ topicId: TOPIC,+ });const tool = { apiName: 'Bash', arguments: '{}', id: 'tc-1', identifier: 'bash' };const reply = buildEvent('stream_start', 4, { messageId: 'cc-2', newStep: true });+ const replay = steerReplay(3, 'msg-steer');await h.handler.ingest({events: [buildEvent('stream_start', 0, { model: 'claude-opus' }),buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),buildEvent('tool_result', 2, { content: 'ok', toolCallId: 'tc-1' }),- steerReplay(3, 'msg-steer'),+ replay,reply,buildEvent('stream_chunk', 5, { chunkType: 'text', content: 'checking Codex' }),],@@ -65,6 +72,15 @@ describe('HeterogeneousPersistenceHandler β steer messages', () => {);const steer = h.messages.get('msg-steer');expect(steer).toMatchObject({ parentId: 'asst-1', role: 'user' });+ // The replay itself names the message, so the client shows it before the reply starts.+ expect(h.handler.publishData(OP, replay).steerMessage).toMatchObject({+ // The executing agent it is persisted under, not the topic owner.+ agentId: 'agt-exec',+ content: 'look at Codex too',+ id: 'msg-steer',+ parentId: 'asst-1',+ role: 'user',+ });const replyId = h.handler.publishData(OP, reply).assistantMessage?.id;expect(h.messages.get(replyId!)).toMatchObject({ parentId: 'msg-steer', role: 'assistant' });@@ -86,6 +102,8 @@ describe('HeterogeneousPersistenceHandler β steer messages', () => {topicId: TOPIC,});+ const promptReplay = steerReplay(1, 'uuid-prompt');+ expect(h.handler.publishData(OP, promptReplay)).toBe(promptReplay.data);const nextId = h.handler.publishData(OP, next).assistantMessage?.id;expect(h.messages.get(nextId!)).toMatchObject({ parentId: 'asst-1' });expect(h.handler.publishData(OP, next).parentMessage).toBeUndefined();diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.tsindex ff81840b30d..1bad295162e 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts@@ -212,11 +212,21 @@ export class HeterogeneousPersistenceHandler {* so without it a subscriber can only infer each step's row from where it* started. A reconnect starts from `runningOperation.assistantMessageId`,* the newest row, so its full replay wrote every earlier step onto that row.+ *+ * A `user_message` replay that delivered a steer carries that user message+ * as `steerMessage`, so the client shows it as soon as Claude Code reads it+ * instead of when its reply starts (the tray drops it at the same moment).+ ** Without state (a retry on a cold replica) the event goes out unchanged* and the client falls back to its DB lookup.*/publishData(operationId: string, event: AgentStreamEvent): AgentStreamEvent['data'] {const state = operationStates.get(operationId);+ if (isSteerReplay(event)) {+ const steerMessage = state?.steerMessages.get(event.data.uuid);+ return steerMessage ? { ...event.data, steerMessage } : event.data;+ }+const key = eventKey(event);const assistantId = state?.streamStartAssistantIds.get(key);if (!assistantId) return event.data;@@ -361,7 +371,7 @@ export class HeterogeneousPersistenceHandler {if (!steer) return;state.main = { ...state.main, lastSpineMessageId: steer.id };- state.steerMessages.set(steer.id, { ...steer, role: 'user' });+ state.steerMessages.set(steer.id, { ...steer, agentId: state.agentId ?? null, role: 'user' });}// βββ Main-agent reducer interpreter ββββββββββββββββββββββββββββββββββββββdiff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex bfbbc491b35..0bdbe50feec 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -199,6 +199,8 @@ export interface StreamStartAssistantMessage {* ends and the queued message vanishes from both the tray and the chat.*/export interface StreamStartParentMessage {+ /** Agent the row was persisted under (the executing agent). Absent from older servers. */+ agentId?: string | null;content: string;/** Server creation time (epoch ms). Absent from older servers. */createdAt?: number;@@ -239,6 +241,12 @@ export interface StepCompleteData {phase: string;reason?: string;reasonDetail?: string;+ /**+ * On `phase: 'user_message'`: the steer user message a heterogeneous run+ * just read from its live session. Shown at once, ahead of the reply it+ * opens. Absent from older servers and for replays that delivered nothing.+ */+ steerMessage?: StreamStartParentMessage;}/**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.tsindex 5f157200533..3dc6a649323 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@@ -284,6 +284,66 @@ describe('createGatewayEventHandler β stream lifecycle events', () => {});});+ describe('step_complete user_message (live steer read by a heterogeneous run)', () => {+ it('shows the steer message as soon as the run reads it, before its reply starts', async () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('step_complete', {+ phase: 'user_message',+ steerMessage: {+ agentId: 'agent-executing',+ content: 'summarize the refactor',+ id: 'steer-1',+ metadata: { steer: true },+ parentId: 'msg-step1',+ role: 'user',+ },+ uuid: 'steer-1',+ }),+ );+ await flush();++ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'steer-1',+ type: 'createMessage',+ value: expect.objectContaining({+ // The persisted author, not the conversation owner (`agent-1`).+ agentId: 'agent-executing',+ content: 'summarize the refactor',+ metadata: { steer: true },+ parentId: 'msg-step1',+ role: 'user',+ topicId: 'topic-1',+ }),+ }),+ { operationId: 'op-1' },+ );+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });++ it('does not insert it twice, and ignores a replay that delivered nothing', async () => {+ const store = createMockStore();+ store.dbMessagesMap = { 'session_agent-1_topic-1': [{ id: 'steer-1', role: 'user' }] };+ const handler = createHandler(store);++ handler(+ makeEvent('step_complete', {+ phase: 'user_message',+ steerMessage: { content: 'x', id: 'steer-1', role: 'user' },+ uuid: 'steer-1',+ }),+ );+ handler(makeEvent('step_complete', { phase: 'user_message', uuid: 'run-prompt' }));+ await flush();++ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });+ });+describe('stream_chunk', () => {it('should accumulate text content and pass operationId context', async () => {const store = createMockStore();diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.tsindex faf64b988ef..ab8acc2b3b8 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -8,7 +8,6 @@ import type {StepCompleteData,StreamChunkData,StreamStartData,- SubAgentProgressData,ToolEndData,ToolExecuteData,ToolStartData,@@ -44,6 +43,7 @@ import {resolveRuntimeEndStatus,} from './runtimeEndReason';import { applyStepMetrics } from './stepMetrics';+import { resolveStepSideEvent } from './stepSideEvent';import { insertStreamStartSeeds, streamStartOperationMetadata } from './streamStartSeed';// Lazy-loaded to break the import cycle:@@ -1172,41 +1172,10 @@ export const createGatewayEventHandler = (case 'step_complete': {const data = event.data as StepCompleteData | undefined;- // A parked `callSubAgent` child reporting its running totals. Patch them- // onto the placeholder tool message in memory only β the persisted values- // are written once, by `completeSubAgentBridge`, when the child finishes.- // Kept under a `progress` key so a DB refetch can never leave a stale live- // number sitting where the authoritative one belongs.- //- // ENQUEUED, not dispatched inline: the placeholder row only enters the- // store via the `toolMessageIds` refetch that the preceding `tools_calling`- // chunk queued. A fast child can emit its first progress event while that- // fetch is still in flight, and `updatePluginState` against a row the store- // doesn't have is a silent no-op β for a single-step sub-agent that lone- // sample is the whole live readout, so there is nothing later to self-heal- // it. Queueing puts this behind the fetch that creates its target.- if (data?.phase === 'subagent_progress') {- const progress = event.data as SubAgentProgressData;- if (progress.toolMessageId) {- enqueue(() => {- get().internal_dispatchMessage(- {- id: progress.toolMessageId,- key: 'progress',- type: 'updatePluginState',- value: {- model: progress.model,- totalCost: progress.totalCost,- totalInputTokens: progress.totalInputTokens,- totalOutputTokens: progress.totalOutputTokens,- totalTokens: progress.totalTokens,- totalToolCalls: progress.totalToolCalls,- },- },- dispatchContext,- );- });- }+ // Sub-agent progress and live steer reads, not step boundaries.+ const sideEvent = resolveStepSideEvent(get, data, context, dispatchContext);+ if (sideEvent) {+ if (sideEvent.apply) enqueue(sideEvent.apply);break;}diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.tsnew file mode 100644index 00000000000..80dcdfb5463--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts@@ -0,0 +1,74 @@+import type { StepCompleteData, SubAgentProgressData } from '@lobechat/agent-gateway-client';+import type { ConversationContext } from '@lobechat/types';++import type { ChatStore } from '@/store/chat/store';++import { insertSteerMessage } from './streamStartSeed';++/**+ * A `step_complete` that rides the event for something other than a step+ * boundary. `apply` is the store update it asks for (none when it carries+ * nothing to show); the caller enqueues it behind pending refetches.+ */+export interface StepSideEvent {+ apply?: () => void;+}++/**+ * Resolve a side-channel `step_complete`, or `undefined` for a real step+ * boundary (metrics, `execution_complete` refresh).+ *+ * - `subagent_progress`: a parked `callSubAgent` child reporting its running+ * totals. Patched onto the placeholder tool message in memory only β the+ * persisted values are written once, by `completeSubAgentBridge`, when the+ * child finishes. Kept under a `progress` key so a DB refetch can never leave+ * a stale live number where the authoritative one belongs. It must be+ * ENQUEUED: the placeholder row only enters the store via the refetch the+ * preceding `tools_calling` chunk queued, and `updatePluginState` against a+ * missing row is a silent no-op β for a single-step sub-agent that lone+ * sample is the whole live readout.+ * - `user_message`: a heterogeneous run read a queued follow-up from its live+ * session. The server already wrote it and the queue tray drops it now, so+ * show it at once, ahead of the reply it opens, instead of when that reply+ * starts streaming.+ */+export const resolveStepSideEvent = (+ get: () => ChatStore,+ data: StepCompleteData | undefined,+ context: ConversationContext,+ dispatchContext: { operationId: string },+): StepSideEvent | undefined => {+ if (data?.phase === 'subagent_progress') {+ const progress = data as SubAgentProgressData;+ if (!progress.toolMessageId) return {};++ return {+ apply: () =>+ get().internal_dispatchMessage(+ {+ id: progress.toolMessageId,+ key: 'progress',+ type: 'updatePluginState',+ value: {+ model: progress.model,+ totalCost: progress.totalCost,+ totalInputTokens: progress.totalInputTokens,+ totalOutputTokens: progress.totalOutputTokens,+ totalTokens: progress.totalTokens,+ totalToolCalls: progress.totalToolCalls,+ },+ },+ dispatchContext,+ ),+ };+ }++ if (data?.phase === 'user_message') {+ const steer = data.steerMessage;+ if (!steer) return {};++ return { apply: () => insertSteerMessage(get, steer, context, dispatchContext) };+ }++ return undefined;+};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.tsindex 5458f9a7036..2a838b87a6f 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/streamStartSeed.ts@@ -1,4 +1,4 @@-import type { StreamStartData } from '@lobechat/agent-gateway-client';+import type { StreamStartData, StreamStartParentMessage } from '@lobechat/agent-gateway-client';import type { ConversationContext } from '@lobechat/types';import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';@@ -24,6 +24,65 @@ const seedCreatedAt = (return Number.isFinite(parentTime) && time <= parentTime ? parentTime + 1 : time;};+interface SeedFields {+ agentId?: string | null;+ groupId?: string;+ threadId?: string;+ topicId?: string;+}++const insertSteerRow = (+ get: () => ChatStore,+ steer: StreamStartParentMessage,+ shared: SeedFields,+ dispatchContext: { operationId: string },+): void => {+ if (dbMessageSelectors.getDbMessageById(steer.id)(get())) return;++ get().internal_dispatchMessage(+ {+ createdAt: seedCreatedAt(get, steer.createdAt, steer.parentId),+ id: steer.id,+ type: 'createMessage',+ value: {+ ...shared,+ agentId: shared.agentId ?? undefined,+ content: steer.content,+ metadata: steer.metadata ?? undefined,+ parentId: steer.parentId ?? undefined,+ role: 'user',+ },+ },+ dispatchContext,+ );+};++/**+ * Insert the steer user message a heterogeneous run just read from its live+ * session (`step_complete` with `phase: 'user_message'`). The server already+ * wrote it and the queue tray drops it now; without this it is missing from+ * the chat until the reply it opens starts streaming.+ */+export const insertSteerMessage = (+ get: () => ChatStore,+ steer: StreamStartParentMessage,+ context: ConversationContext,+ dispatchContext: { operationId: string },+): void =>+ insertSteerRow(+ get,+ steer,+ {+ // The server persists it under the executing agent, which can differ+ // from the conversation owner (an @-mentioned or sub-agent run).+ agentId: steer.agentId ?? context.agentId,+ groupId: context.groupId ?? undefined,+ threadId: context.threadId ?? undefined,+ topicId: context.topicId ?? undefined,+ },+ dispatchContext,+ );+/*** 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@@ -50,27 +109,7 @@ export const insertStreamStartSeeds = (};// 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(- {- createdAt: seedCreatedAt(get, parent.createdAt, parent.parentId),- id: parent.id,- type: 'createMessage',- value: {- ...shared,- content: parent.content,- metadata: parent.metadata ?? undefined,- parentId: parent.parentId ?? undefined,- role: 'user',- },- },- dispatchContext,- );- }+ if (parent && parent.id === seed.parentId) insertSteerRow(get, parent, shared, dispatchContext);get().internal_dispatchMessage({