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(hetero-agent): sync new-step assistant across replicas (#14631)

LiJian1d2f0dcdb95f
diff --git a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 47a41d7d4ad..da6827ce80e 100644
--- a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -156,6 +156,7 @@ interface OperationState {
currentAssistantMessageId: string;
lastModel: string | undefined;
lastProvider: string | undefined;
+ lastStepIndex: number;
operationId: string;
processedKeys: Set<string>;
subagentRuns: Map<string, SubagentRunState>;
@@ -238,6 +239,16 @@ export class HeterogeneousPersistenceHandler {
topicId: string;
}): Promise<void> {
const state = await this.loadOrCreateState(params.operationId, params.topicId);
+ const batchMaxStepIndex = Math.max(...params.events.map((event) => event.stepIndex));
+
+ // A different Lambda may have already processed `stream_start { newStep }`
+ // and persisted `heteroCurrentMsgId` for this operation. Warm instances keep
+ // their operation state in memory, so without an explicit resync they would
+ // keep appending later-step chunks to the PREVIOUS assistant row. Only resync
+ // when the incoming batch advances beyond the step this instance has seen.
+ if (batchMaxStepIndex > state.lastStepIndex) {
+ await this.syncAssistantPointerForAdvancedStep(state);
+ }
// Refresh content/reasoning baseline from DB before processing this batch.
//
@@ -296,6 +307,7 @@ export class HeterogeneousPersistenceHandler {
// only on success so a retry can complete the lost write.
await this.handleEvent(state, event);
state.processedKeys.add(key);
+ state.lastStepIndex = Math.max(state.lastStepIndex, event.stepIndex);
}
// Flush accumulated content after every batch so a subsequent replica
@@ -416,6 +428,7 @@ export class HeterogeneousPersistenceHandler {
currentAssistantMessageId,
lastModel: undefined,
lastProvider: undefined,
+ lastStepIndex: 0,
operationId,
processedKeys: new Set(),
subagentRuns: new Map(),
@@ -436,6 +449,49 @@ export class HeterogeneousPersistenceHandler {
return state;
}
+ private async syncAssistantPointerForAdvancedStep(state: OperationState): Promise<void> {
+ const topic = await this.deps.topicModel.findById(state.topicId);
+ const running = topic?.metadata?.runningOperation;
+
+ if (!running || running.operationId !== state.operationId) {
+ throw new Error(
+ `No matching runningOperation on topic ${state.topicId} for operation ${state.operationId} β€” orchestrator must seed topic.metadata.runningOperation before ingest`,
+ );
+ }
+
+ const stored = topic.metadata?.heteroCurrentMsgId;
+ const authoritativeAssistantMessageId =
+ stored?.operationId === state.operationId
+ ? (stored.msgId ?? running.assistantMessageId)
+ : running.assistantMessageId;
+
+ if (
+ !authoritativeAssistantMessageId ||
+ authoritativeAssistantMessageId === state.currentAssistantMessageId
+ ) {
+ return;
+ }
+
+ const currentMsg = await this.deps.messageModel.findById(authoritativeAssistantMessageId);
+ const restoredContent = (currentMsg?.content ?? '') as string;
+ const restoredReasoning = (currentMsg?.reasoning as { content?: string } | null)?.content ?? '';
+ const restoredTools = (currentMsg?.tools ?? []) as ChatToolPayload[];
+
+ state.currentAssistantMessageId = authoritativeAssistantMessageId;
+ state.accumulatedContent = restoredContent;
+ state.accumulatedReasoning = restoredReasoning;
+ state.toolState = {
+ payloads: restoredTools,
+ persistedIds: new Set(restoredTools.map((tool) => tool.id)),
+ };
+
+ log(
+ 'synced warm state op=%s to assistant=%s after step advance',
+ state.operationId,
+ authoritativeAssistantMessageId,
+ );
+ }
+
// ─── Event dispatch ──────────────────────────────────────────────────────
private async handleEvent(state: OperationState, event: AgentStreamEvent): Promise<void> {
diff --git a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index b44749a11bd..3bf07cf6b15 100644
--- a/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -37,6 +37,20 @@ interface FakeThread {
type: string;
}
+interface FakeTopicMetadata {
+ heteroCurrentMsgId?: { msgId: string; operationId: string };
+ runningOperation: {
+ assistantMessageId: string;
+ operationId: string;
+ };
+}
+
+interface FakeTopic {
+ agentId: string | null;
+ id: string;
+ metadata: FakeTopicMetadata;
+}
+
const createHarness = (params: {
assistantMessageId: string;
operationId: string;
@@ -127,7 +141,7 @@ const createHarness = (params: {
};
const topicModel = {
- findById: vi.fn(async (id: string) => {
+ findById: vi.fn(async (id: string): Promise<FakeTopic | null> => {
if (id !== params.topicId) return null;
return {
agentId: params.topicAgentId ?? null,
@@ -137,7 +151,7 @@ const createHarness = (params: {
assistantMessageId: params.assistantMessageId,
operationId: params.operationId,
},
- },
+ } satisfies FakeTopicMetadata,
};
}),
updateMetadata: vi.fn(async (_topicId: string, _patch: any) => {}),
@@ -689,7 +703,7 @@ describe('HeterogeneousPersistenceHandler', () => {
await h.handler.finish({ operationId: 'op-1', result: 'success' });
// Same operationId on a different topic should now succeed (state was dropped)
- h.topicModel.findById.mockResolvedValueOnce({
+ h.topicModel.findById.mockResolvedValue({
agentId: null,
id: 'topic-2',
metadata: {
@@ -824,4 +838,50 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(tool1Msgs).toHaveLength(1);
});
});
+
+ describe('warm replica step resync', () => {
+ it('switches to the DB-persisted step assistant when a later-step batch lands on a stale warm replica', async () => {
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 0, { chunkType: 'text', content: 'step1' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ h.messages.set('asst-2', {
+ agentId: null,
+ content: '',
+ id: 'asst-2',
+ parentId: 'asst-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+ });
+
+ h.topicModel.findById.mockResolvedValue({
+ agentId: null,
+ id: 'topic-1',
+ metadata: {
+ heteroCurrentMsgId: { msgId: 'asst-2', operationId: 'op-1' },
+ runningOperation: {
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ },
+ } satisfies FakeTopicMetadata,
+ });
+
+ await h.handler.ingest({
+ events: [buildEvent('stream_chunk', 1, { chunkType: 'text', content: 'step2' })],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ expect(h.messages.get('asst-1')?.content).toBe('step1');
+ expect(h.messages.get('asst-2')?.content).toBe('step2');
+ });
+ });
});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
index cdbed9db805..15535c9ed25 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts
@@ -101,6 +101,30 @@ describe('createGatewayEventHandler', () => {
expect(store.replaceMessages).toHaveBeenCalled();
});
+ it('should resolve the new assistant from DB on hetero newStep when the event has no assistantMessage id', async () => {
+ const store = createMockStore();
+ const handler = createHandler(store);
+
+ vi.mocked(messageService.getMessages).mockResolvedValueOnce([
+ { id: 'msg-initial', role: 'assistant' } as any,
+ { id: 'tool-1', role: 'tool' } as any,
+ { id: 'msg-step2', role: 'assistant' } as any,
+ ]);
+
+ handler(makeEvent('stream_start', { newStep: true }));
+ handler(makeEvent('stream_chunk', { chunkType: 'text', content: 'world' }));
+ await flush();
+
+ expect(store.associateMessageWithOperation).toHaveBeenCalledWith('msg-step2', 'op-1');
+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ id: 'msg-step2',
+ value: { content: 'world' },
+ }),
+ { operationId: 'op-1' },
+ );
+ });
+
it('should reset accumulators on each stream_start', async () => {
const store = createMockStore();
const handler = createHandler(store);
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index d88a961587b..aad20d6fea1 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -21,6 +21,27 @@ import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNo
const fetchAndReplaceMessages = async (get: () => ChatStore, context: ConversationContext) => {
const messages = await messageService.getMessages(context);
get().replaceMessages(messages, { context });
+ return messages;
+};
+
+type GatewayMessageLike = { id: string; role?: string };
+type HeteroStreamStartData = StreamStartData & { newStep?: boolean };
+
+const findNextAssistantMessageId = (
+ messages: GatewayMessageLike[] | undefined,
+ currentAssistantMessageId: string,
+) => {
+ if (!messages?.length) return;
+
+ const currentIndex = messages.findIndex((message) => message.id === currentAssistantMessageId);
+ if (currentIndex === -1) return;
+
+ for (let index = currentIndex + 1; index < messages.length; index += 1) {
+ const message = messages[index];
+ if (message.role === 'assistant') {
+ return message.id;
+ }
+ }
};
const toChatMessageError = (data: unknown): ChatMessageError => {
@@ -104,7 +125,7 @@ export const createGatewayEventHandler = (
switch (event.type) {
case 'stream_start': {
enqueue(async () => {
- const data = event.data as StreamStartData | undefined;
+ const data = event.data as HeteroStreamStartData | undefined;
const newAssistantMessageId = data?.assistantMessage?.id;
@@ -119,11 +140,33 @@ export const createGatewayEventHandler = (
accumulatedContent = '';
accumulatedReasoning = '';
- // Fetch from DB so the new message exists in dbMessagesMap before chunks arrive
+ // Heterogeneous CLI adapters emit `stream_start { newStep: true }`
+ // without a server-side assistant id. Pull the freshly created step
+ // assistant from DB so subsequent live chunks update the RIGHT row
+ // instead of appending onto the previous step's assistant.
+ const messages = await fetchAndReplaceMessages(get, context).catch((error) => {
+ console.error(error);
+ return undefined;
+ });
+
+ if (!newAssistantMessageId && data?.newStep) {
+ const resolvedAssistantMessageId = findNextAssistantMessageId(
+ messages as GatewayMessageLike[] | undefined,
+ currentAssistantMessageId,
+ );
+
+ if (resolvedAssistantMessageId) {
+ currentAssistantMessageId = resolvedAssistantMessageId;
+ get().associateMessageWithOperation(currentAssistantMessageId, operationId);
+ }
+ }
+
void emitClientAgentSignalSourceEvent({
payload: {
agentId: context.agentId,
- ...(newAssistantMessageId ? { assistantMessageId: newAssistantMessageId } : {}),
+ ...(currentAssistantMessageId
+ ? { assistantMessageId: currentAssistantMessageId }
+ : {}),
operationId,
stepIndex: event.stepIndex,
topicId: context.topicId ?? undefined,
@@ -131,7 +174,6 @@ export const createGatewayEventHandler = (
sourceId: `${operationId}:gateway:start:${event.stepIndex}`,
sourceType: 'client.gateway.stream_start',
});
- await fetchAndReplaceMessages(get, context).catch(console.error);
});
break;
}