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: reuse assistant messages on step retry (#17703)

YuTengjing27b26a823a2f
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts
new file mode 100644
index 00000000000..31f97cd1648
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts
@@ -0,0 +1,80 @@
+import type { CreateMessageParams } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { MessageModel } from '@/database/models/message';
+
+import { ServerMessageTransport } from './ServerMessageTransport';
+
+const params: CreateMessageParams = {
+ agentId: 'agent-1',
+ content: '',
+ parentId: 'parent-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+};
+
+const createUniqueViolation = (constraint: string) => {
+ const error = new Error('Failed query: insert into messages');
+ error.cause = {
+ code: '23505',
+ constraint,
+ message: 'duplicate key',
+ severity: 'ERROR',
+ };
+ return error;
+};
+
+describe('ServerMessageTransport', () => {
+ it('returns the first assistant message when the same idempotency key is delivered twice', async () => {
+ const existingMessage = {
+ agentId: 'agent-1',
+ id: 'assistant-1',
+ parentId: 'parent-1',
+ role: 'assistant',
+ topicId: 'topic-1',
+ };
+ const messageModel = {
+ create: vi
+ .fn()
+ .mockResolvedValueOnce(existingMessage)
+ .mockRejectedValueOnce(createUniqueViolation('message_client_id_user_unique')),
+ findByClientId: vi.fn().mockResolvedValue(existingMessage),
+ } as unknown as MessageModel;
+ const transport = new ServerMessageTransport(messageModel);
+ const options = { idempotencyKey: 'agent-runtime:op-1:step:6:assistant' };
+
+ const [first, retried] = await Promise.all([
+ transport.createAssistantMessage(params, options),
+ transport.createAssistantMessage(params, options),
+ ]);
+
+ expect(first.id).toBe('assistant-1');
+ expect(retried.id).toBe('assistant-1');
+ expect(messageModel.create).toHaveBeenCalledTimes(2);
+ expect(messageModel.create).toHaveBeenNthCalledWith(1, {
+ ...params,
+ clientId: options.idempotencyKey,
+ });
+ expect(messageModel.create).toHaveBeenNthCalledWith(2, {
+ ...params,
+ clientId: options.idempotencyKey,
+ });
+ expect(messageModel.findByClientId).toHaveBeenCalledWith(options.idempotencyKey);
+ });
+
+ it('does not swallow an unrelated unique constraint violation', async () => {
+ const error = createUniqueViolation('messages_pkey');
+ const messageModel = {
+ create: vi.fn().mockRejectedValue(error),
+ findByClientId: vi.fn(),
+ } as unknown as MessageModel;
+ const transport = new ServerMessageTransport(messageModel);
+
+ await expect(
+ transport.createAssistantMessage(params, {
+ idempotencyKey: 'agent-runtime:op-1:step:6:assistant',
+ }),
+ ).rejects.toBe(error);
+ expect(messageModel.findByClientId).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
index 85c3311ef77..561da953a51 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts
@@ -1,4 +1,5 @@
import type {
+ CreateAssistantMessageOptions,
MessageTransport,
QueryMessagesInput,
QueryMessagesOptions,
@@ -14,6 +15,7 @@ import {
createConversationParentMissingError,
isMidOperationReferenceMissingError,
} from '../messagePersistErrors';
+import { unwrapPgError } from '../pgError';
/**
* Server {@link MessageTransport} adapter — delegates to `MessageModel` (DB).
@@ -29,8 +31,43 @@ export class ServerMessageTransport implements MessageTransport {
} = {},
) {}
- createAssistantMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
- return this.messageModel.create(params);
+ /**
+ * Reuses the first persisted placeholder when an at-least-once step delivery
+ * retries after message creation but before the runtime state is committed.
+ */
+ async createAssistantMessage(
+ params: CreateMessageParams,
+ options?: CreateAssistantMessageOptions,
+ ): Promise<RuntimeMessageRef> {
+ const idempotencyKey = options?.idempotencyKey;
+ const createParams = idempotencyKey ? { ...params, clientId: idempotencyKey } : params;
+
+ try {
+ return await this.messageModel.create(createParams);
+ } catch (error) {
+ const pgError = unwrapPgError(error);
+ const isIdempotencyConflict =
+ idempotencyKey &&
+ pgError?.code === '23505' &&
+ pgError.constraint === 'message_client_id_user_unique';
+
+ if (!isIdempotencyConflict) throw error;
+
+ const existingMessage = await this.messageModel.findByClientId(idempotencyKey);
+ if (!existingMessage) throw error;
+
+ return {
+ agentId: existingMessage.agentId,
+ groupId: existingMessage.groupId,
+ id: existingMessage.id,
+ model: existingMessage.model,
+ parentId: existingMessage.parentId,
+ provider: existingMessage.provider,
+ role: existingMessage.role,
+ threadId: existingMessage.threadId,
+ topicId: existingMessage.topicId,
+ };
+ }
}
async createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
index bde6e52dfef..57bafcd69bc 100644
--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
@@ -1442,6 +1442,34 @@ describe('AgentRuntime', () => {
expect(toolMessages).toHaveLength(2);
});
+ it('should pass a stable index for each instruction in the same step', async () => {
+ const instructionIndexes: Array<number | undefined> = [];
+ const agent: Agent = {
+ async runner() {
+ return [
+ { payload: { messages: [] }, type: 'call_llm' as const },
+ { payload: { messages: [] }, type: 'call_llm' as const },
+ ];
+ },
+ };
+ const runtime = new AgentRuntime(agent, {
+ executors: {
+ call_llm: async (_instruction, state, context) => {
+ instructionIndexes.push(context?.instructionIndex);
+ return { events: [], newState: state };
+ },
+ },
+ });
+ const state = AgentRuntime.createInitialState({
+ messages: [{ content: 'Execute both calls', role: 'user' }],
+ operationId: 'instruction-index-test',
+ });
+
+ await runtime.step(state);
+
+ expect(instructionIndexes).toEqual([0, 1]);
+ });
+
it('should stop execution when encountering blocking status', async () => {
// Agent that returns mixed instructions with approval
class BlockingAgent implements Agent {
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index 84452392691..dfee448c090 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -187,20 +187,25 @@ export class AgentRuntime {
let finalNextContext: AgentRuntimeContext | undefined = undefined;
let hasFinishInstruction = false;
- for (const instruction of normalizedInstructions) {
+ for (const [instructionIndex, instruction] of normalizedInstructions.entries()) {
if (instruction.type === 'finish') hasFinishInstruction = true;
let result;
+ const instructionContext = { ...runtimeContext, instructionIndex };
// Special handling for batch tool execution
if (instruction.type === 'call_tools_batch') {
// Check if custom executor is provided (e.g., server-side with DB access)
const customExecutor = this.executors['call_tools_batch' as keyof typeof this.executors];
if (customExecutor) {
- result = await customExecutor(instruction, currentState, runtimeContext);
+ result = await customExecutor(instruction, currentState, instructionContext);
} else {
// Fallback to built-in executeToolsBatch
- result = await this.executeToolsBatch(instruction as any, currentState, runtimeContext);
+ result = await this.executeToolsBatch(
+ instruction as any,
+ currentState,
+ instructionContext,
+ );
}
} else {
const executor = this.executors[instruction.type as keyof typeof this.executors];
@@ -208,7 +213,7 @@ export class AgentRuntime {
throw new Error(`No executor found for instruction type: ${instruction.type}`);
}
// Pass runtimeContext to executor so it can access stepContext
- result = await executor(instruction, currentState, runtimeContext);
+ result = await executor(instruction, currentState, instructionContext);
}
// Accumulate events
diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.ts
index 5da011c3460..0a1dd554bd1 100644
--- a/packages/agent-runtime/src/executors/callLlm.test.ts
+++ b/packages/agent-runtime/src/executors/callLlm.test.ts
@@ -182,7 +182,10 @@ describe('callLlm executor', () => {
type: 'call_llm',
};
- const result = await callLlm(host)(instructionWithParent, state);
+ const result = await callLlm(host)(instructionWithParent, state, {
+ instructionIndex: 1,
+ phase: 'user_input',
+ });
expect(messages.findById).toHaveBeenCalledWith('parent-1');
expect(messages.createAssistantMessage).toHaveBeenCalledWith(
expect.objectContaining({
@@ -195,6 +198,9 @@ describe('callLlm executor', () => {
threadId: 'thread-1',
topicId: 'topic-1',
}),
+ {
+ idempotencyKey: 'agent-runtime:op-1:step:0:instruction:1:assistant',
+ },
);
expect(stream.publishEvent).toHaveBeenCalledWith({
data: {
diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.ts
index 51b96089c0e..df61272bd2e 100644
--- a/packages/agent-runtime/src/executors/callLlm.ts
+++ b/packages/agent-runtime/src/executors/callLlm.ts
@@ -274,7 +274,7 @@ const buildAssistantMessageSeed = (
*/
export const callLlm =
(host: AgentRuntimeHost): InstructionExecutor =>
- async (instruction, state) => {
+ async (instruction, state, runtimeContext) => {
const { operation, transports } = host;
const contextBuilder = requireContextBuilder(host);
const llm = requireLLMCallTransport(host);
@@ -307,17 +307,28 @@ export const callLlm =
const existingAssistantMessageId = llmPayload.assistantMessageId;
const assistantMessage = existingAssistantMessageId
? { id: existingAssistantMessageId }
- : await transports.messages.createAssistantMessage({
- agentId: state.metadata!.agentId!,
- content: '',
- groupId: state.metadata?.groupId ?? undefined,
- model,
- parentId,
- provider,
- role: 'assistant',
- threadId: state.metadata?.threadId,
- topicId: state.metadata?.topicId,
- });
+ : await transports.messages.createAssistantMessage(
+ {
+ agentId: state.metadata!.agentId!,
+ content: '',
+ groupId: state.metadata?.groupId ?? undefined,
+ model,
+ parentId,
+ provider,
+ role: 'assistant',
+ threadId: state.metadata?.threadId,
+ topicId: state.metadata?.topicId,
+ },
+ {
+ /**
+ * Step retries must reuse the same assistant message, while multiple LLM
+ * instructions in one step must keep independent messages.
+ */
+ idempotencyKey:
+ `agent-runtime:${operation.operationId}:step:${operation.stepIndex}:` +
+ `instruction:${runtimeContext?.instructionIndex ?? 0}:assistant`,
+ },
+ );
const assistantMessageSeed = existingAssistantMessageId
? ((await transports.messages.findById(existingAssistantMessageId)) ?? assistantMessage)
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
index edfaa0e8b5a..e4902959cd2 100644
--- a/packages/agent-runtime/src/transport/message.ts
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -13,6 +13,14 @@ export interface RuntimeMessageRef {
topicId?: string | null;
}
+export interface CreateAssistantMessageOptions {
+ /**
+ * Stable key for one logical assistant output. Persistent transports should
+ * return the existing message when a step is delivered more than once.
+ */
+ idempotencyKey?: string;
+}
+
export interface QueryMessagesInput {
agentId?: string;
current?: number;
@@ -54,7 +62,10 @@ export interface UpdateToolMessageInput {
* id the caller needs to anchor follow-up writes.
*/
export interface MessageTransport {
- createAssistantMessage: (params: CreateMessageParams) => Promise<RuntimeMessageRef>;
+ createAssistantMessage: (
+ params: CreateMessageParams,
+ options?: CreateAssistantMessageOptions,
+ ) => Promise<RuntimeMessageRef>;
createToolMessage: (params: CreateMessageParams) => Promise<RuntimeMessageRef>;
deleteMessage: (id: string) => Promise<void>;
/** Existence / parent preflight; returns the id when present. */
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 44b7156a0af..a7bfa4cbc9a 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -20,6 +20,9 @@ export interface AgentRuntimeContext {
*/
initialContext?: RuntimeInitialContext;
+ /** Zero-based instruction position within the current runtime step */
+ instructionIndex?: number;
+
metadata?: Record<string, unknown>;
/** Operation ID (links to Operation for business context) */
diff --git a/packages/database/src/models/__tests__/messages/message.create.test.ts b/packages/database/src/models/__tests__/messages/message.create.test.ts
index d6fae9873e3..524d0bdeeda 100644
--- a/packages/database/src/models/__tests__/messages/message.create.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.create.test.ts
@@ -94,6 +94,32 @@ describe('MessageModel Create Tests', () => {
expect(result.userId).toBe(userId);
});
+ it('finds a message by client id within the current user scope', async () => {
+ await Promise.all([
+ messageModel.create(
+ {
+ clientId: 'shared-client-id',
+ content: 'owned message',
+ role: 'assistant',
+ },
+ 'owned-message',
+ ),
+ new MessageModel(serverDB, otherUserId).create(
+ {
+ clientId: 'shared-client-id',
+ content: 'other message',
+ role: 'assistant',
+ },
+ 'other-message',
+ ),
+ ]);
+
+ await expect(messageModel.findByClientId('shared-client-id')).resolves.toMatchObject({
+ content: 'owned message',
+ id: 'owned-message',
+ });
+ });
+
it('promotes metadata.usage into the dedicated usage column on create', async () => {
const usage = { cost: 0.004, totalInputTokens: 70, totalOutputTokens: 30, totalTokens: 100 };
const result = await messageModel.create({
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index d9fa940246e..2ea60cbfae2 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1729,6 +1729,12 @@ export class MessageModel {
});
};
+ findByClientId = async (clientId: string) => {
+ return this.db.query.messages.findFirst({
+ where: and(eq(messages.clientId, clientId), this.ownership()),
+ });
+ };
+
findLatestAssistantMessageByThread = async ({
agentId,
threadId,
diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.ts
index 6a66807c004..d84bdda1388 100644
--- a/packages/types/src/message/ui/params.ts
+++ b/packages/types/src/message/ui/params.ts
@@ -25,6 +25,8 @@ export interface CreateMessageParams extends Partial<
Omit<UIChatMessage, 'content' | 'role' | 'topicId' | 'chunksList'>
> {
agentId?: string;
+ /** Caller-provided key for idempotent persistence within one user scope. */
+ clientId?: string;
content: string;
error?: ChatMessageError | null;
fileChunks?: MessageSemanticSearchChunk[];