π€― 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-agent): name each step's assistant on published stream_start (#21682)
AmAzing-efcc0184bce4
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.publishData.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.publishData.test.tsnew file mode 100644index 00000000000..2ad1d5e9c3c--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.publishData.test.ts@@ -0,0 +1,75 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { __resetOperationStatesForTesting } from '.';+import { buildEvent, createHarness } from './testUtils';++const OP = 'op-1';+const TOPIC = 'topic-1';++describe('HeterogeneousPersistenceHandler.publishData', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ it('names the assistant row each main-agent step opened, so a replay from the newest row stays on each step', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });+ const tool = { apiName: 'Bash', arguments: '{}', id: 'tc-1', identifier: 'bash' };++ const firstStart = buildEvent('stream_start', 0, { model: 'claude-opus' });+ const secondStart = buildEvent('stream_start', 3, { newStep: true });+ const thirdStart = buildEvent('stream_start', 6, { newStep: true });+ await h.handler.ingest({+ events: [+ firstStart,+ buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),+ buildEvent('tool_result', 2, { content: 'ok', toolCallId: 'tc-1' }),+ secondStart,+ buildEvent('stream_chunk', 4, { chunkType: 'text', content: 'waiting on CI' }),+ buildEvent('stream_chunk', 5, { chunkType: 'text', content: 'still waiting' }),+ thirdStart,+ buildEvent('stream_chunk', 7, { chunkType: 'text', content: 'final answer' }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });++ const assistantIds = [...h.messages.values()]+ .filter((message) => message.role === 'assistant')+ .map((message) => message.id);+ expect(assistantIds).toHaveLength(3);++ const stamped = [firstStart, secondStart, thirdStart].map(+ (event) => h.handler.publishData(OP, event).assistantMessage?.id,+ );+ expect(stamped).toEqual(assistantIds);+ // The rest of the producer payload rides along untouched.+ expect(h.handler.publishData(OP, firstStart)).toMatchObject({ model: 'claude-opus' });+ expect(h.handler.publishData(OP, secondStart)).toMatchObject({ newStep: true });+ });++ it('leaves subagent step boundaries and non-boundary events unstamped', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });++ const subagentStart = buildEvent('stream_start', 1, {+ newStep: true,+ subagent: { parentToolCallId: 'tc-spawn-1', subagentMessageId: 'sub-msg-1' },+ });+ const chunk = buildEvent('stream_chunk', 2, { chunkType: 'text', content: 'hi' });+ await h.handler.ingest({ events: [subagentStart, chunk], operationId: OP, topicId: TOPIC });++ expect(h.handler.publishData(OP, subagentStart)).toBe(subagentStart.data);+ expect(h.handler.publishData(OP, chunk)).toBe(chunk.data);+ });++ it('forgets the mapping once the event is published, and passes data through without state', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });+ const start = buildEvent('stream_start', 0, {});+ await h.handler.ingest({ events: [start], operationId: OP, topicId: TOPIC });++ expect(h.handler.publishData(OP, start).assistantMessage?.id).toBe('asst-1');++ h.handler.markEventPublished(OP, start);+ expect(h.handler.publishData(OP, start)).toBe(start.data);+ expect(h.handler.publishData('op-unknown', start)).toBe(start.data);+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.tsindex 26758f844d4..61ca90bc4aa 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts@@ -4,7 +4,7 @@ import type {MainAgentReduceCtx,SubagentIntent,} from '@lobechat/heterogeneous-agents';-import { reduceMainAgent } from '@lobechat/heterogeneous-agents';+import { getEventScope, reduceMainAgent } from '@lobechat/heterogeneous-agents';import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';import { createNanoId } from '@lobechat/utils';@@ -36,6 +36,10 @@ const generateThreadId = () => `thd_${createNanoId(16)()}`;const opensSignalTurn = (event: AgentStreamEvent): boolean =>event.type === 'stream_start' && !!event.data?.newStep && !!event.data?.externalSignal;+/** Subagent turns live in their thread; only main-agent step boundaries name a main assistant. */+const isMainStreamStart = (event: AgentStreamEvent): boolean =>+ event.type === 'stream_start' && getEventScope(event).kind === 'main';+/** The raw text a CLI would have echoed into the answer for this failure. */const errorEchoText = (error: { body?: Record<string, unknown>; message?: string }): string => {const body = error.body ?? {};@@ -140,6 +144,9 @@ export class HeterogeneousPersistenceHandler {// would ack OK while DB state diverges from the renderer's view. Mark// only on success so a retry can complete the lost write.await this.handleEvent(state, event);+ if (isMainStreamStart(event)) {+ state.streamStartAssistantIds.set(key, state.main.currentAssistantId);+ }state.processedKeys.add(key);state.lastStepIndex = Math.max(state.lastStepIndex, event.stepIndex);}@@ -168,9 +175,34 @@ export class HeterogeneousPersistenceHandler {return events.filter((event) => !state.publishedKeys.has(eventKey(event)));}+ /**+ * Wire `data` for an event about to be published.+ *+ * A main-agent `stream_start` carries the assistant row it resolved to as+ * `assistantMessage.id`. CLI adapters never know the server's message ids,+ * 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.+ * 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 assistantId = operationStates+ .get(operationId)+ ?.streamStartAssistantIds.get(eventKey(event));+ if (!assistantId) return event.data;++ return { ...event.data, assistantMessage: { id: assistantId } };+ }+/** Latch an event as published so a batch retry skips its XADD. */markEventPublished(operationId: string, event: AgentStreamEvent): void {- operationStates.get(operationId)?.publishedKeys.add(eventKey(event));+ const state = operationStates.get(operationId);+ if (!state) return;++ const key = eventKey(event);+ state.publishedKeys.add(key);+ state.streamStartAssistantIds.delete(key);}/**diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.tsindex 3a62fbfe37d..f481cc67916 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts@@ -177,6 +177,7 @@ export async function loadOrCreateState(notifiedInterventionTransitions: new Set(),processedKeys: new Set(),publishedKeys: new Set(),+ streamStartAssistantIds: new Map(),toolMsgIdByCallId: new Map(),threadId: running?.threadId ?? undefined,topicId,diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.tsindex 087b80e560b..394e697fc8d 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/types.ts@@ -42,6 +42,12 @@ export interface OperationState {publishedKeys: Set<string>;/** User message answered by this operation, checked against its topic/thread before stamping. */sourceUserMessageId?: string;+ /**+ * Assistant row each main-agent `stream_start` resolved to, keyed by+ * `eventKey`. Read when the event is published (stamped as+ * `assistantMessage.id`) and dropped once its XADD succeeds.+ */+ streamStartAssistantIds: Map<string, string>;/** Isolation thread that owns this heterogeneous run, when applicable. */threadId: string | undefined;/**diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex 9355f46a0b2..166e1ede188 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -45,9 +45,8 @@ const createFakeStreamManager = () => {};const createFakePersistenceHandler = () => {- // Faithful publish-gate fake: same latch semantics as the real handler- // (filter by event identity, latch per event) so batch-retry tests exercise- // the real skip/resume behavior instead of a stub that returns everything.+ // Faithful publish-gate fake (filter by event identity, latch per event) so batch-retry+ // tests exercise the real skip/resume behavior; `publishData` passes data through.const publishedKeys = new Set<string>();const gateKey = (event: AgentStreamEvent) =>`${event.stepIndex}:${event.type}:${event.timestamp}`;@@ -60,6 +59,7 @@ const createFakePersistenceHandler = () => {markEventPublished: vi.fn((_operationId: string, event: AgentStreamEvent) => {publishedKeys.add(gateKey(event));}),+ publishData: vi.fn((_operationId: string, event: AgentStreamEvent) => event.data),};return handler as unknown as HeterogeneousPersistenceHandler & typeof handler;};@@ -432,14 +432,10 @@ describe('HeterogeneousAgentService', () => {}),};const persistenceHandler = {- filterUnpublishedEvents: vi.fn(- (_operationId: string, events: AgentStreamEvent[]) => events,- ),- finish: vi.fn(async () => {}),+ ...createFakePersistenceHandler(),ingest: vi.fn(async () => {callOrder.push('persist');}),- markEventPublished: vi.fn(),} as unknown as HeterogeneousPersistenceHandler;const service = new HeterogeneousAgentService({} as any, 'user-test', {agentOperationModel: createFakeAgentOperationModel() as any,diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/ingestStepIdentity.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/ingestStepIdentity.test.tsnew file mode 100644index 00000000000..14c2dd4f086--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/ingestStepIdentity.test.ts@@ -0,0 +1,62 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { HeterogeneousAgentService } from '..';+import { __resetOperationStatesForTesting } from '../HeterogeneousPersistenceHandler';+import { buildEvent, createHarness } from '../HeterogeneousPersistenceHandler/testUtils';++/**+ * A reconnecting viewer replays the whole stream starting from+ * `runningOperation.assistantMessageId` (the newest row). Without each step's+ * row on its `stream_start`, that replay wrote every earlier step onto the+ * newest row, so a run left alive by a background task flashed stale steps over+ * its final answer on every reconnect.+ */+describe('HeterogeneousAgentService.heteroIngest β step boundary identity', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ it('publishes each main-agent stream_start with the assistant row it opened', async () => {+ const h = createHarness({+ assistantMessageId: 'asst-1',+ operationId: 'op-1',+ topicId: 'tpc-1',+ });+ const publishStreamEvent = vi.fn(async (_operationId: string, _event: any) => 'ok');+ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ agentOperationModel: { touchRunning: vi.fn(async () => true) } as any,+ persistenceHandler: h.handler,+ snapshotStore: null,+ streamEventManager: { publishStreamEvent } as any,+ topicModel: h.topicModel as any,+ });+ const tool = { apiName: 'Bash', arguments: '{}', id: 'tc-1', identifier: 'bash' };++ await service.heteroIngest({+ agentType: 'claude-code',+ events: [+ buildEvent('stream_start', 0, {}),+ buildEvent('stream_chunk', 1, { chunkType: 'tools_calling', toolsCalling: [tool] }),+ buildEvent('tool_result', 2, { content: 'ok', toolCallId: 'tc-1' }),+ buildEvent('stream_start', 3, { newStep: true }),+ buildEvent('stream_chunk', 4, { chunkType: 'text', content: 'final answer' }),+ ],+ operationId: 'op-1',+ topicId: 'tpc-1',+ });++ const published = publishStreamEvent.mock.calls.map(([, event]) => event);+ const startIds = published+ .filter((event) => event.type === 'stream_start')+ .map((event) => event.data.assistantMessage?.id);+ const assistantIds = [...h.messages.values()]+ .filter((message) => message.role === 'assistant')+ .map((message) => message.id);++ expect(assistantIds).toHaveLength(2);+ expect(startIds).toEqual(assistantIds);+ expect(published.find((event) => event.type === 'stream_chunk')?.data).not.toHaveProperty(+ 'assistantMessage',+ );+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex a1b5a70debd..0c05eea92bf 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -298,10 +298,11 @@ export class HeterogeneousAgentService {);}for (const event of unpublished) {- // Each event already carries operationId; pass through unchanged so the- // wire shape on the WS side is identical to gateway-driven runs.+ // Each event already carries operationId; the wire shape matches+ // gateway-driven runs, which also name the step's assistant row on+ // `stream_start` (see `publishData`).await this.streamEventManager.publishStreamEvent(operationId, {- data: event.data,+ data: this.persistenceHandler.publishData(operationId, event),stepIndex: event.stepIndex,type: event.type,});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 491c5bb6801..74cfa3ad95a 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@@ -110,6 +110,34 @@ describe('createGatewayEventHandler β stream lifecycle events', () => {);});+ it('keeps a reconnect replay on each step row when hetero stream_start names it', async () => {+ const store = createMockStore();+ store.dbMessagesMap['main_agent-1_topic-1'] = [+ { content: 'still waiting on CI', id: 'msg-step2', role: 'assistant' },+ { content: 'final answer', id: 'msg-final', role: 'assistant' },+ ];+ // A reconnect anchors on `runningOperation.assistantMessageId` β the newest row.+ const handler = createHandler(store, { assistantMessageId: 'msg-final' });++ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-step2' }, newStep: true }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'still waiting on CI' }));+ handler(makeEvent('stream_start', { assistantMessage: { id: 'msg-final' }, newStep: true }));+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'final answer' }));+ await flush();++ const contentWrites = vi+ .mocked(store.internal_dispatchMessage)+ .mock.calls.map(([action]: any[]) => action)+ .filter((action) => action.type === 'updateMessage' && 'content' in action.value)+ .map((action) => [action.id, action.value.content]);+ expect(contentWrites).toEqual([+ ['msg-step2', 'still waiting on CI'],+ ['msg-final', 'final answer'],+ ]);+ // Both rows are already loaded, so the replay needs no DB round trip.+ expect(messageService.getMessages).not.toHaveBeenCalled();+ });+it('should reset accumulators on each stream_start', 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.tsindex 7de24fe28b0..8b94b2c6d12 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts@@ -725,12 +725,12 @@ export const createGatewayEventHandler = (// 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- // mandatory for them β it (a) pulls the executor-created- // placeholder into `dbMessagesMap` so subsequent chunks can- // dispatch to it, and (b) resolves the next-step assistant id for- // the `newStep` fallback.+ // Server-ingested hetero runs get `assistantMessage.id` stamped at+ // publish; desktop-local hetero steps and older servers send none,+ // so the DB read stays mandatory for them β it (a) pulls the+ // executor-created placeholder into `dbMessagesMap` for later+ // chunks, and (b) resolves the `newStep` fallback, which only knows+ // "the assistant after the current one" (wrong for a replay).if (!newAssistantMessageId) {const messages = await refreshMessagesFromDb({skipWorks: true,