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(steer-queue): stop resending a queued follow-up whose message was already written (#21777)

Arvin Xua212726ca3bb
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
index 79bf72b6b80..ed4cbb21739 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
mergeQueuedFollowUps,
type QueuedFollowUp,
+ queuedUserMessageId,
startQueuedFollowUp,
takeSameSenderFollowUps,
} from './index';
@@ -32,6 +33,12 @@ vi.mock('@/server/services/redis', () => ({
redisService: { steerQueue: { boundOperations, drain, restore, settle } },
}));
vi.mock('./liveRuns', () => ({ findOwnLiveRuns, isRunAlive }));
+const { findMessageById } = vi.hoisted(() => ({ findMessageById: vi.fn() }));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: class {
+ findById = findMessageById;
+ },
+}));
vi.mock('../composerRun', () => ({ startComposerRun }));
vi.mock('@/server/routers/lambda/_helpers/workspaceAgentGuard', () => ({
assertCanUseWorkspaceAgent,
@@ -154,6 +161,7 @@ describe('startQueuedFollowUp', () => {
assertCanUseWorkspaceAgent.mockResolvedValue(undefined);
assertCanUseAgentRunConversation.mockResolvedValue(undefined);
startComposerRun.mockResolvedValue({ operationId: 'op-2' });
+ findMessageById.mockResolvedValue(undefined);
});
it('starts the drained follow-ups as their own turn on the same surface', async () => {
@@ -240,6 +248,73 @@ describe('startQueuedFollowUp', () => {
);
});
+ it('sends a batch under one user message id that every attempt at it shares', async () => {
+ drain.mockResolvedValue([followUp('b', 2, {}), followUp('a', 1, {})]);
+ startComposerRun.mockRejectedValueOnce(new Error('topic busy'));
+
+ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));
+ drain.mockResolvedValue([followUp('a', 1, {}), followUp('b', 2, {})]);
+ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));
+
+ const [first, second] = startComposerRun.mock.calls.map(([, request]) => request);
+ expect(first.clientIds.userMessageId).toMatch(/^msg_[\da-f]{24}$/);
+ expect(second.clientIds.userMessageId).toBe(first.clientIds.userMessageId);
+ // A single follow-up keeps the id its optimistic row was minted under.
+ const single = [followUp('a', 1, { clientIds: { userMessageId: 'msg_client' } })];
+ expect(queuedUserMessageId('user-1', single, mergeQueuedFollowUps(single))).toBe('msg_client');
+ });
+
+ it('acknowledges the follow-ups when the start failed after writing the user message', async () => {
+ // Regression: a start can write the message and still fail (a Task run lost
+ // to a concurrent send is stopped and rejected). Returning the follow-ups
+ // made the next run that ended send the same message again.
+ drain.mockResolvedValue([followUp('a', 1, {}), followUp('b', 2, {})]);
+ startComposerRun.mockImplementation(async (_ctx, request) => {
+ findMessageById.mockImplementation(async (id: string) =>
+ id === request.clientIds.userMessageId ? { id } : undefined,
+ );
+ throw new TRPCError({ code: 'CONFLICT', message: 'Another run is already live' });
+ });
+
+ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();
+
+ expect(settle).toHaveBeenCalledOnce();
+ expect(settle).toHaveBeenCalledWith(
+ { threadId: null, topicId: 'tpc-1', userId: 'user-1' },
+ expect.any(String),
+ );
+ });
+
+ it('acknowledges a batch an earlier attempt already wrote, without starting it again', async () => {
+ drain.mockResolvedValue([followUp('a', 1, { clientIds: { userMessageId: 'msg_written' } })]);
+ findMessageById.mockImplementation(async (id: string) =>
+ id === 'msg_written' ? { id } : undefined,
+ );
+
+ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toBeUndefined();
+
+ expect(startComposerRun).not.toHaveBeenCalled();
+ expect(settle).toHaveBeenCalledWith(
+ expect.objectContaining({ topicId: 'tpc-1' }),
+ expect.any(String),
+ );
+ });
+
+ it('puts the follow-ups back when it cannot tell whether a failed start wrote the message', async () => {
+ const entries = [followUp('a', 1, {})];
+ drain.mockResolvedValue(entries);
+ startComposerRun.mockRejectedValue(new Error('topic busy'));
+ findMessageById.mockRejectedValue(new Error('connection reset'));
+
+ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));
+
+ expect(settle).toHaveBeenCalledWith(
+ expect.objectContaining({ topicId: 'tpc-1' }),
+ expect.any(String),
+ entries.map((e) => e.id),
+ );
+ });
+
it('never starts a follow-up someone else queued under the run owner', async () => {
drain.mockResolvedValue([{ ...followUp('a', 1, {}), userId: 'intruder' }]);
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.ts
index 4700540f766..e3b59dcb964 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts
@@ -1,10 +1,11 @@
-import { randomUUID } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import type { AgentSenderMetadata, ComposerUserMessage, MessageMetadata } from '@lobechat/types';
import { COMPOSER_USER_MESSAGE_METADATA_KEYS, toComposerUserMessage } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
+import { MessageModel } from '@/database/models/message';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { foldLegacyUserMessageFields } from '@/server/routers/lambda/aiAgent/execSchemas';
import { assertCanUseAgentRunConversation } from '@/server/routers/lambda/aiAgent/guards';
@@ -281,6 +282,43 @@ export const checkFollowUpAccess = async (
}
};
+/**
+ * The id of the user message a drained batch is sent as. A single follow-up
+ * keeps the id its optimistic row was minted under; a merged batch gets one
+ * derived from its entries, so every attempt at the same batch names the same
+ * row and a later attempt can tell whether an earlier one already wrote it.
+ */
+export const queuedUserMessageId = (
+ userId: string,
+ entries: QueuedFollowUp[],
+ request: QueuedFollowUpRequest,
+): string =>
+ request.clientIds?.userMessageId ??
+ `msg_${createHash('sha256')
+ .update(JSON.stringify([userId, ...entries.map((entry) => entry.id).sort()]))
+ .digest('hex')
+ .slice(0, 24)}`;
+
+/**
+ * Whether the batch's user message is already in the conversation. A start
+ * that wrote it can still fail afterwards (a Task run lost to a concurrent
+ * send, an abort, a failure past turn setup); sending the batch again would
+ * then add the same message twice, or β€” with a fixed id β€” fail on it forever.
+ * `undefined` when the lookup itself failed.
+ */
+const isUserMessageWritten = async (
+ ctx: Pick<ComposerRunContext, 'db' | 'userId' | 'workspaceId'>,
+ messageId: string,
+): Promise<boolean | undefined> => {
+ try {
+ const messageModel = new MessageModel(ctx.db, ctx.userId, ctx.workspaceId ?? undefined);
+ return !!(await messageModel.findById(messageId));
+ } catch (error) {
+ console.error('[startQueuedFollowUp] reading user message %s failed: %O', messageId, error);
+ return undefined;
+ }
+};
+
/**
* A top-level run just finished on `scope`: start the follow-ups still queued
* behind it as the next turn, here on the server, instead of waiting for a
@@ -292,6 +330,8 @@ export const checkFollowUpAccess = async (
* Drain is atomic, so exactly one finishing run takes a given follow-up. When
* the next turn cannot start, the follow-ups go back to the head of the queue β€”
* the next run that ends picks them up, and the client can still list them.
+ * Only a start that never wrote the user message goes back: once it is in the
+ * conversation the follow-ups are delivered, even if the run then failed.
* When the user lost access to the agent or conversation meanwhile, they are
* dropped instead.
*
@@ -311,7 +351,9 @@ export const startQueuedFollowUp = async (
const { agentSender, rest, taken: entries } = takeSameSenderFollowUps(drained.entries);
await returnFollowUps(scope, drained, rest, 'sent by another author');
- const request = mergeQueuedFollowUps(entries);
+ const merged = mergeQueuedFollowUps(entries);
+ const userMessageId = queuedUserMessageId(ctx.userId, entries, merged);
+ const request = { ...merged, clientIds: { ...merged.clientIds, userMessageId } };
const audit = entries.at(-1)!.audit;
try {
@@ -333,6 +375,14 @@ export const startQueuedFollowUp = async (
await returnFollowUps(scope, drained, entries, `left to live run ${others[0]}`);
return;
}
+
+ // An earlier attempt wrote the message but was never acknowledged (its
+ // process died, or its batch lapsed back): it is already delivered.
+ if (await isUserMessageWritten(ctx, userMessageId)) {
+ log('[%s] Queued follow-up %s was already written', params.operationId, userMessageId);
+ await ackFollowUps(scope, drained);
+ return;
+ }
} catch (error) {
await returnFollowUps(scope, drained, entries, error);
return;
@@ -361,6 +411,15 @@ export const startQueuedFollowUp = async (
await ackFollowUps(scope, drained);
return { operationId: result.operationId };
} catch (error) {
+ if (await isUserMessageWritten(ctx, userMessageId)) {
+ console.error(
+ '[startQueuedFollowUp] queued follow-up %s was written but its run failed to start: %O',
+ userMessageId,
+ error,
+ );
+ await ackFollowUps(scope, drained);
+ return;
+ }
await returnFollowUps(scope, drained, entries, error);
return;
}