Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🚿 fix: Bound Chat Message IDs and Remove Backtracking (#17388)

lia-by-librechat[bot]f18b16baedab
diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
index 26cbc25df1..6e72aae8d3 100644
--- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
+++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js
@@ -20,7 +20,11 @@ jest.mock('@librechat/data-schemas', () => ({
jest.mock('librechat-data-provider', () => ({
...jest.requireActual('librechat-data-provider'),
Tools: {},
- Constants: { mcp_delimiter: '_mcp_', mcp_prefix: 'mcp_' },
+ Constants: {
+ ...jest.requireActual('librechat-data-provider').Constants,
+ mcp_delimiter: '_mcp_',
+ mcp_prefix: 'mcp_',
+ },
FileSources: {},
}));
diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
index 3a33108351..9f4ef855af 100644
--- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
+++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
@@ -66,7 +66,11 @@ jest.mock('@librechat/api', () => {
jest.mock('librechat-data-provider', () => ({
...jest.requireActual('librechat-data-provider'),
Tools: {},
- Constants: { mcp_delimiter: '::', mcp_prefix: 'mcp_' },
+ Constants: {
+ ...jest.requireActual('librechat-data-provider').Constants,
+ mcp_delimiter: '::',
+ mcp_prefix: 'mcp_',
+ },
FileSources: {},
ResourceType: {},
}));
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index 2dd726abd5..4e797ab4c2 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -256,6 +256,9 @@ jest.mock('@librechat/data-schemas', () => ({
}));
jest.mock('@librechat/api', () => ({
+ getPreliminaryResponseMessageId: jest.requireActual(
+ '../../../../../packages/api/src/utils/message',
+ ).getPreliminaryResponseMessageId,
savePrivateTextMessage: (save, _req, ...args) => save(...args),
savePrivateTextErrorTurn: (...args) =>
jest.requireActual('@librechat/api').savePrivateTextErrorTurn(...args),
@@ -3823,6 +3826,30 @@ describe('ResumableAgentController resume metadata', () => {
},
);
+ it('does not persist an oversized raw identity after a post-ack initialization failure', async () => {
+ const req = createFailedRequest({
+ conversationId: undefined,
+ messageId: '_'.repeat(80_000) + 'X',
+ });
+ const res = createResumableResponse();
+ const initializeClient = jest.fn(async () => {
+ expect(res.json).toHaveBeenCalled();
+ throw new Error('The model "gpt-4o" is not available.');
+ });
+
+ await AgentController(req, res, jest.fn(), initializeClient, null);
+
+ expect(initializeClient).toHaveBeenCalledTimes(1);
+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(
+ expect.any(String),
+ 'The model "gpt-4o" is not available.',
+ 1000,
+ expect.objectContaining({ beforeErrorPublication: expect.any(Function) }),
+ );
+ expect(mockSaveMessage).not.toHaveBeenCalled();
+ expect(mockSaveConvo).not.toHaveBeenCalled();
+ });
+
it('persists an initialization failure before terminal error publication', async () => {
const events = [];
mockSaveConvo.mockImplementation(async () => {
@@ -3956,6 +3983,118 @@ describe('ResumableAgentController resume metadata', () => {
);
});
+ it.each(['a'.repeat(256) + '_', 'a'.repeat(257)])(
+ 'persists a failed compaction without overwriting a maximum-length anchor',
+ async (anchorId) => {
+ mockGetMessages.mockImplementation(async ({ messageId }) =>
+ messageId === anchorId ? [{ _id: 'persisted-anchor' }] : [],
+ );
+ const client = {
+ options: {},
+ sendMessage: jest.fn(async (_text, options) => {
+ options.onStart(
+ { messageId: anchorId, conversationId, text: '' },
+ 'compaction-response',
+ );
+ throw new Error('compaction failed');
+ }),
+ };
+
+ await AgentController(
+ createFailedRequest({ compact: true, messageId: anchorId, parentMessageId: anchorId }),
+ createResumableResponse(),
+ jest.fn(),
+ jest.fn().mockResolvedValue({ client }),
+ null,
+ );
+ await flushBackgroundGeneration();
+
+ expect(client.sendMessage).toHaveBeenCalledTimes(1);
+ expect(mockSaveMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-123' }),
+ expect.objectContaining({
+ messageId: 'compaction-response',
+ parentMessageId: anchorId,
+ error: true,
+ }),
+ expect.any(Object),
+ );
+ expect(mockSaveMessage.mock.calls.map(([, message]) => message.messageId)).not.toContain(
+ anchorId,
+ );
+ const { validateChatMessageIds } = jest.requireActual(
+ '../../../../../packages/api/src/middleware/messageIds',
+ );
+ const responseId = mockSaveMessage.mock.calls.find(([, message]) => message.error)[1]
+ .messageId;
+ const next = jest.fn();
+ const res = createResumableResponse();
+ validateChatMessageIds(
+ { body: { compact: true, messageId: responseId, parentMessageId: responseId } },
+ res,
+ next,
+ );
+ expect(next).toHaveBeenCalledTimes(1);
+ expect(res.status).not.toHaveBeenCalledWith(400);
+ },
+ );
+
+ it('keeps repeated failed compactions admissible without rewriting their anchors', async () => {
+ let anchorId = 'a'.repeat(257);
+ const rows = new Map([[anchorId, { _id: 'original-anchor', messageId: anchorId }]]);
+ mockGetMessages.mockImplementation(async ({ messageId }) =>
+ rows.has(messageId) ? [rows.get(messageId)] : [],
+ );
+ mockSaveMessage.mockImplementation(async (_ctx, message) => {
+ rows.set(message.messageId, message);
+ return message;
+ });
+ const { validateChatMessageIds } = jest.requireActual(
+ '../../../../../packages/api/src/middleware/messageIds',
+ );
+
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const originalAnchor = rows.get(anchorId);
+ const request = createFailedRequest({
+ compact: true,
+ messageId: anchorId,
+ parentMessageId: anchorId,
+ });
+ const res = createResumableResponse();
+ const next = jest.fn();
+ validateChatMessageIds(request, res, next);
+ expect(next).toHaveBeenCalledTimes(1);
+ const client = {
+ options: {},
+ sendMessage: jest.fn(async (_text, options) => {
+ options.onStart(
+ { messageId: anchorId, conversationId, text: '' },
+ `compaction-response-${attempt}`,
+ );
+ throw new Error('compaction failed');
+ }),
+ };
+ await AgentController(
+ request,
+ res,
+ jest.fn(),
+ jest.fn().mockResolvedValue({ client }),
+ null,
+ );
+ await flushBackgroundGeneration();
+
+ const saved = mockSaveMessage.mock.calls.at(-1)[1];
+ expect(mockSaveMessage).toHaveBeenCalledTimes(attempt + 1);
+ expect(saved.messageId).not.toBe(anchorId);
+ expect(saved.messageId.length).toBeLessThanOrEqual(257);
+ expect(saved.parentMessageId).toBe(anchorId);
+ expect(rows.get(anchorId)).toBe(originalAnchor);
+ anchorId = saved.messageId;
+ }
+ expect(mockDecrementPendingRequest).toHaveBeenCalledTimes(3);
+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledTimes(3);
+ });
+
it('uses the live user identity after generation starts', async () => {
const serverUserMessage = {
messageId: 'server-user',
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index 807b9debca..9cdba77cb2 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -67,6 +67,7 @@ const {
resolveDisconnectSnapshotMode,
markAbortedCompactionContent,
isTemporaryTurn,
+ getPreliminaryResponseMessageId,
} = require('@librechat/api');
const { disposeClient } = require('~/server/cleanup');
const {
@@ -171,18 +172,6 @@ async function attachConversationCreatedAt(req, conversationId, conversationAnch
}
}
-function getPreliminaryResponseMessageId({ messageId, responseMessageId }) {
- if (typeof responseMessageId === 'string' && responseMessageId.length > 0) {
- return responseMessageId;
- }
-
- if (typeof messageId !== 'string' || messageId.length === 0) {
- return null;
- }
-
- return `${messageId.replace(/_+$/, '')}_`;
-}
-
/**
* Manual compaction runs as a summarize-only turn hung off the branch's leaf.
* It needs an existing branch to summarize, and it cannot be combined with the
@@ -421,7 +410,11 @@ async function saveErrorTurn(
if (liveUserMessage?.messageId == null) {
return;
}
- errorMessageId = getPreliminaryResponseMessageId({ messageId: liveUserMessage.messageId });
+ errorMessageId = getPreliminaryResponseMessageId({
+ compact: true,
+ messageId: liveUserMessage.messageId,
+ liveResponseMessageId,
+ });
errorParentMessageId = liveUserMessage.messageId;
} else if (isRegenerate) {
errorMessageId =
diff --git a/api/server/routes/agents/__tests__/chat.contentFilter.spec.js b/api/server/routes/agents/__tests__/chat.contentFilter.spec.js
index 01602cb7b7..e8502b605a 100644
--- a/api/server/routes/agents/__tests__/chat.contentFilter.spec.js
+++ b/api/server/routes/agents/__tests__/chat.contentFilter.spec.js
@@ -1,3 +1,5 @@
+const express = require('express');
+const request = require('supertest');
const mockGetFiles = jest.fn();
const mockCreateMessageFilterPii = jest.fn(() => (_req, _res, next) => next());
const mockGetSafeErrorMetadata = jest.fn((error) => ({
@@ -13,6 +15,9 @@ jest.mock('@librechat/data-schemas', () => ({
}));
jest.mock('@librechat/api', () => ({
+ validateChatMessageIds: jest.requireActual(
+ '../../../../../packages/api/src/middleware/messageIds',
+ ).validateChatMessageIds,
createMessageFilterPii: mockCreateMessageFilterPii,
generateCheckAccess: jest.fn(() => (_req, _res, next) => next()),
skipAgentCheck: jest.fn(),
@@ -84,3 +89,140 @@ describe('agents chat content filtering', () => {
expect(next).toHaveBeenCalledTimes(1);
});
});
+
+describe('agents chat message-ID ingress', () => {
+ function createAuthenticatedApp() {
+ const app = express();
+ app.use(express.json({ limit: '3mb' }));
+ app.use((req, res, next) => {
+ if (req.headers.authorization !== 'Bearer test-user') {
+ return res.sendStatus(401);
+ }
+ req.user = { id: 'user-123' };
+ next();
+ });
+ app.use('/api/agents/chat', require('../chat'));
+ app.get('/health', (_req, res) => res.sendStatus(200));
+ return app;
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it.each(['/', '/openAI', '/resume'])(
+ 'rejects oversized message identities before admission at %s',
+ async (path) => {
+ const app = createAuthenticatedApp();
+ const controller = require('~/server/controllers/agents/request');
+ const resumeController = require('~/server/controllers/agents/resume');
+ const api = require('@librechat/api');
+ const payload = '_'.repeat(80_000) + 'X';
+ for (const field of ['messageId', 'responseMessageId']) {
+ const response = await request(app)
+ .post(`/api/agents/chat${path}`)
+ .set('Authorization', 'Bearer test-user')
+ .send({ [field]: payload, conversationId: 'new' });
+ expect(response.status).toBe(400);
+ expect(response.body).toEqual({
+ code: 'INVALID_MESSAGE_ID',
+ error: expect.stringContaining(field),
+ });
+ expect(JSON.stringify(response.body)).not.toContain(payload);
+ }
+ expect(controller).not.toHaveBeenCalled();
+ expect(resumeController).not.toHaveBeenCalled();
+ expect(api.GenerationJobManager.getJob).not.toHaveBeenCalled();
+ await request(app).get('/health').set('Authorization', 'Bearer test-user').expect(200);
+ },
+ );
+
+ it.each(['', 42, {}, [], 'invalid/id', 'invalid id', 'invalid\n'])(
+ 'rejects malformed message identities',
+ async (messageId) => {
+ await request(createAuthenticatedApp())
+ .post('/api/agents/chat')
+ .set('Authorization', 'Bearer test-user')
+ .send({ messageId })
+ .expect(400);
+ expect(require('~/server/controllers/agents/request')).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ['fresh user', { messageId: 'a'.repeat(257) + '_' }],
+ ['fresh user at 257', { messageId: 'a'.repeat(256) + '_' }],
+ ['compaction', { messageId: 'a'.repeat(257) + '_', compact: true }],
+ ['response', { responseMessageId: 'a'.repeat(257) + '_' }],
+ ])('rejects oversized %s identities at the protocol boundary', async (_label, body) => {
+ await request(createAuthenticatedApp())
+ .post('/api/agents/chat')
+ .set('Authorization', 'Bearer test-user')
+ .send(body)
+ .expect(400);
+ expect(require('~/server/controllers/agents/request')).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['overrideUserMessageId', 'a'.repeat(257)],
+ ['overrideUserMessageId', 'a'.repeat(257) + '__0'],
+ ['overrideUserMessageId', 'safe__' + '0'.repeat(80_000)],
+ ['overrideUserMessageId', 'a'.repeat(256) + '__' + '0'.repeat(17)],
+ ['overrideUserMessageId', '_'.repeat(80_000) + 'X'],
+ ['overrideUserMessageId', '__0'],
+ ['overrideUserMessageId', 'invalid/id__0'],
+ ['overrideUserMessageId', 'valid__invalid/id'],
+ ['overrideUserMessageId', ''],
+ ['overrideUserMessageId', 42],
+ ['overrideParentMessageId', 'a'.repeat(257)],
+ ['overrideParentMessageId', 'invalid/id'],
+ ['parentMessageId', 'a'.repeat(258)],
+ ['parentMessageId', {}],
+ ])('rejects an invalid effective identity from %s before admission', async (field, value) => {
+ const app = createAuthenticatedApp();
+ const response = await request(app)
+ .post('/api/agents/chat/agents')
+ .set('Authorization', 'Bearer test-user')
+ .send({ messageId: 'valid-user', responseMessageId: 'valid-response', [field]: value });
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('INVALID_MESSAGE_ID');
+ expect(response.body.error).toContain(field);
+ expect(require('~/server/controllers/agents/request')).not.toHaveBeenCalled();
+ expect(require('@librechat/api').GenerationJobManager.getJob).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {},
+ {
+ messageId: null,
+ responseMessageId: null,
+ overrideUserMessageId: null,
+ overrideParentMessageId: null,
+ },
+ { messageId: 'valid-user', overrideUserMessageId: 'recovery-user' },
+ { messageId: 'valid-user', overrideUserMessageId: 'a'.repeat(256) + '__0' },
+ { messageId: 'valid-user', overrideUserMessageId: 'a'.repeat(256) + '__9007199254740991' },
+ { messageId: 'valid-user', overrideUserMessageId: 'existing-user__1' },
+ { messageId: 'valid-user', overrideParentMessageId: 'a'.repeat(256), isRegenerate: true },
+ { messageId: 'valid-user', parentMessageId: 'a'.repeat(257) },
+ { messageId: '550e8400-e29b-41d4-a716-446655440000' },
+ {
+ compact: true,
+ conversationId: 'existing-conversation',
+ messageId: 'a'.repeat(256) + '_',
+ parentMessageId: 'a'.repeat(256) + '_',
+ },
+ { messageId: 'a'.repeat(256), responseMessageId: 'a'.repeat(256) + '_', isRegenerate: true },
+ { messageId: 'nanoid_-', responseMessageId: 'event-turn:assistant', isRegenerate: true },
+ { messageId: 'edited-user__', responseMessageId: 'existing-response', editedContent: {} },
+ ])('preserves supported turn shapes', async (body) => {
+ const controller = require('~/server/controllers/agents/request');
+ controller.mockImplementationOnce((_req, res) => res.sendStatus(202));
+ await request(createAuthenticatedApp())
+ .post('/api/agents/chat')
+ .set('Authorization', 'Bearer test-user')
+ .send(body)
+ .expect(202);
+ expect(controller).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/api/server/routes/agents/chat.js b/api/server/routes/agents/chat.js
index 1a1fff7ae7..84d3f44ad3 100644
--- a/api/server/routes/agents/chat.js
+++ b/api/server/routes/agents/chat.js
@@ -9,6 +9,7 @@ const {
applyResumeRequest,
GenerationJobManager,
getSafeErrorMetadata,
+ validateChatMessageIds,
} = require('@librechat/api');
const { PermissionTypes, Permissions, PermissionBits } = require('librechat-data-provider');
const {
@@ -61,6 +62,7 @@ const restoreResumeContext = async (req, res, next) => {
next();
};
+router.use(validateChatMessageIds);
router.use(restoreResumeContext);
router.use(
createMessageFilterPii({
diff --git a/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts b/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts
new file mode 100644
index 0000000000..3bada5b807
--- /dev/null
+++ b/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts
@@ -0,0 +1,110 @@
+import { createPayload, EModelEndpoint } from 'librechat-data-provider';
+import { mergeErrorMessages, mergeResponseMessage } from '@librechat/chat';
+import type { Request, Response } from 'express';
+import type { TOptions } from '~/common';
+import { validateChatMessageIds } from '../../../../../packages/api/src/middleware/messageIds';
+import { buildTurn } from '../ask/turn';
+
+jest.mock('~/utils', () => ({
+ getRouteChatProjectId: () => null,
+ logger: { log: jest.fn(), dir: jest.fn() },
+}));
+
+describe('turn message-ID protocol', () => {
+ it.each<[string, string, TOptions]>([
+ ['regenerate', 'a'.repeat(257), { isRegenerate: true }],
+ ['regenerate preliminary', 'a'.repeat(256) + '_', { isRegenerate: true }],
+ ['regenerate ordinary', 'assistant-1', { isRegenerate: true }],
+ ['regenerate boundary', 'a'.repeat(256), { isRegenerate: true }],
+ ['regenerate underscored', 'a'.repeat(255) + '__', { isRegenerate: true }],
+ ['edit', 'a'.repeat(257), { isEdited: true }],
+ ['continue', 'a'.repeat(257), { isContinued: true, isEdited: true }],
+ ['compact', 'a'.repeat(257), { compact: true }],
+ ])('admits the real %s builder payload at the response boundary', (_label, id, options) => {
+ const user = {
+ messageId: 'user-1',
+ parentMessageId: null,
+ conversationId: 'conversation-1',
+ text: 'Hello',
+ isCreatedByUser: true,
+ };
+ const response = {
+ messageId: id,
+ parentMessageId: user.messageId,
+ conversationId: user.conversationId,
+ text: 'Answer',
+ isCreatedByUser: false,
+ };
+ const turn = buildTurn({
+ text: options.compact ? '' : user.text,
+ params: options.compact
+ ? { text: '', messageId: id, parentMessageId: id }
+ : { text: user.text, messageId: user.messageId },
+ options: {
+ ...options,
+ ...(options.isEdited && { editedMessageId: id }),
+ targetResponseMessageId: id,
+ },
+ index: 0,
+ conversationId: user.conversationId,
+ conversation: {
+ conversationId: user.conversationId,
+ endpoint: EModelEndpoint.agents,
+ title: null,
+ createdAt: '2026-10-23T00:00:00.000Z',
+ updatedAt: '2026-10-23T00:00:00.000Z',
+ },
+ latestMessage: response,
+ cachedMessages: [user, response],
+ canClearFiles: false,
+ isTemporary: false,
+ ephemeralAgent: null,
+ getSender: () => 'Assistant',
+ userKey: undefined,
+ reasoningOverride: undefined,
+ manualSkills: [],
+ quotes: [],
+ code: { approvalMode: undefined, environmentMode: undefined, workspaces: undefined },
+ });
+ const { payload } = createPayload(turn.submission);
+ const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
+ const next = jest.fn();
+ validateChatMessageIds({ body: payload } as Request, res as unknown as Response, next);
+
+ expect(next).toHaveBeenCalledTimes(1);
+ expect(res.status).not.toHaveBeenCalled();
+ expect(turn.initialResponse.messageId.length).toBeLessThanOrEqual(257);
+ expect(payload.responseMessageId).toBe(turn.submission.userMessage.responseMessageId);
+ if (options.isRegenerate) {
+ expect(payload.responseMessageId).toBe(turn.initialResponse.messageId);
+ expect(payload.responseMessageId).toMatch(/_$/);
+ expect(payload.overrideParentMessageId).toBe(user.messageId);
+ expect(turn.submission.messages).toEqual([user]);
+ const updated = { ...turn.initialResponse, messageId: 'allocated-response', text: 'New' };
+ const optimistic = [...turn.submission.messages, turn.initialResponse];
+ const merged = mergeResponseMessage(
+ {
+ submission: { ...turn.submission, initialResponse: turn.initialResponse },
+ getMessages: () => optimistic,
+ setMessages: jest.fn(),
+ },
+ optimistic,
+ updated,
+ updated.messageId,
+ );
+ expect(merged.map((message) => message.messageId)).toEqual([
+ user.messageId,
+ updated.messageId,
+ ]);
+ const restored = mergeErrorMessages({
+ ...turn.submission,
+ errorMessage: { ...updated, error: true },
+ });
+ expect(restored.find((message) => message.messageId === id)).toBe(response);
+ }
+ if (options.isEdited) {
+ expect(payload.responseMessageId).toBe(id);
+ }
+ expect(response.messageId).toBe(id);
+ });
+});
diff --git a/client/src/hooks/Chat/ask/turn.ts b/client/src/hooks/Chat/ask/turn.ts
index 532bfefd08..bfd966d7bc 100644
--- a/client/src/hooks/Chat/ask/turn.ts
+++ b/client/src/hooks/Chat/ask/turn.ts
@@ -344,7 +344,8 @@ export function buildTurn({
let editPrefixLength: number | undefined;
const initialResponseId =
responseMessageId ??
- `${regenerateShaped ? messageId : intermediateId}`.replace(/_+$/, '') + '_';
+ getPreliminaryRegenerateResponseMessageId(`${regenerateShaped ? messageId : intermediateId}`) ??
+ `${v4()}_`;
const initialResponse: TMessage = {
sender: responseSender,
diff --git a/packages/api/src/agents/compaction.spec.ts b/packages/api/src/agents/compaction.spec.ts
index e58602c77f..2e58d808f9 100644
--- a/packages/api/src/agents/compaction.spec.ts
+++ b/packages/api/src/agents/compaction.spec.ts
@@ -1268,6 +1268,65 @@ describe('settleExistingRowsBeforeErrorTurn', () => {
/** The error row's own path announces the persisted turn; a finalized live
* row stands in for it, so it is announced the same way. */
+ it('finalizes a partial row when the bounded error identity is the live response', async () => {
+ const announceSettledTurn = jest.fn(async () => undefined);
+ const { saved, deps: d } = deps({ 'live-response': [partialSummaryRow()] });
+
+ await expect(
+ settleExistingRowsBeforeErrorTurn(
+ { compact: true },
+ { ...d, errorMessageId: 'live-response', announceSettledTurn },
+ ),
+ ).resolves.toEqual({ covered: true });
+
+ expect(d.getMessages).toHaveBeenCalledTimes(1);
+ expect(d.getMessages).toHaveBeenCalledWith(
+ { user: 'user-1', messageId: 'live-response', conversationId: 'conversation-1' },
+ undefined,
+ );
+ expect(saved).toHaveLength(1);
+ expect(saved[0]).toMatchObject({
+ messageId: 'live-response',
+ unfinished: false,
+ error: true,
+ });
+ expect(announceSettledTurn).toHaveBeenCalledWith('live-response');
+ });
+
+ it('propagates persistence failures when finalizing the bounded live identity', async () => {
+ const outage = new Error('database unavailable');
+ const { deps: d } = deps({ 'live-response': [partialSummaryRow()] });
+ const announceSettledTurn = jest.fn();
+ await expect(
+ settleExistingRowsBeforeErrorTurn(
+ { compact: true },
+ {
+ ...d,
+ errorMessageId: 'live-response',
+ saveFinalizedTurn: async () => {
+ throw outage;
+ },
+ announceSettledTurn,
+ },
+ ),
+ ).rejects.toBe(outage);
+ expect(announceSettledTurn).not.toHaveBeenCalled();
+ });
+
+ it('writes under the bounded live identity when its response has not persisted', async () => {
+ const { saved, deps: d } = deps({});
+
+ await expect(
+ settleExistingRowsBeforeErrorTurn(
+ { compact: true },
+ { ...d, errorMessageId: 'live-response' },
+ ),
+ ).resolves.toEqual({ covered: false, errorRowMessageId: 'live-response' });
+
+ expect(d.getMessages).toHaveBeenCalledTimes(1);
+ expect(saved).toHaveLength(0);
+ });
+
it('announces the live row it finalized', async () => {
const announceSettledTurn = jest.fn(async () => undefined);
const { deps: d } = deps({ 'live-response': [partialSummaryRow()] });
diff --git a/packages/api/src/agents/compaction.ts b/packages/api/src/agents/compaction.ts
index dbe7780b96..cbf3c5e66f 100644
--- a/packages/api/src/agents/compaction.ts
+++ b/packages/api/src/agents/compaction.ts
@@ -521,7 +521,7 @@ export async function settleExistingRowsBeforeErrorTurn(
): Promise<ErrorTurnSettlement> {
const isCompaction = requestBody?.compact === true;
const settleLiveRow = async (): Promise<boolean> => {
- if (liveResponseMessageId == null || liveResponseMessageId === errorMessageId) {
+ if (liveResponseMessageId == null) {
return false;
}
/** Full documents only where the compaction finalization needs the
@@ -543,6 +543,12 @@ export async function settleExistingRowsBeforeErrorTurn(
}
return true;
};
+ /** The bounded fallback already names this run's response, not the anchor. */
+ if (isCompaction && errorMessageId === liveResponseMessageId) {
+ return (await settleLiveRow())
+ ? { covered: true }
+ : { covered: false, errorRowMessageId: errorMessageId };
+ }
const existing = await getMessages(
{ user: userId, messageId: errorMessageId, conversationId },
'_id',
@@ -563,7 +569,7 @@ export async function settleExistingRowsBeforeErrorTurn(
}
return { covered: true };
}
- if (await settleLiveRow()) {
+ if (liveResponseMessageId !== errorMessageId && (await settleLiveRow())) {
return { covered: true };
}
return { covered: false, errorRowMessageId: errorMessageId };
diff --git a/packages/api/src/agents/queuedTurnHttp.spec.ts b/packages/api/src/agents/queuedTurnHttp.spec.ts
index f2afbffb8f..3e77c5c4ff 100644
--- a/packages/api/src/agents/queuedTurnHttp.spec.ts
+++ b/packages/api/src/agents/queuedTurnHttp.spec.ts
@@ -44,6 +44,55 @@ function requestBody() {
}
describe('Agent queued-turn HTTP admission receipts', () => {
+ it.each(['a'.repeat(257), 'a'.repeat(256) + '_'])(
+ 'accepts and replays a queued turn under a maximum-length response parent',
+ async (parentMessageId) => {
+ const saved = { ...turn('queued'), parentMessageId };
+ const enqueue = jest.fn(async () => ({ turn: saved, replayed: false }));
+ const getConvo = jest.fn(async () => ({ agent_id: 'agent_1', endpoint: 'agents' }));
+ const methods = {
+ getConvo,
+ getAgentQueuedTurnByClientRequestId: jest
+ .fn()
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(saved),
+ enqueueAgentQueuedTurn: enqueue,
+ listActiveAgentQueuedTurns: jest.fn(async () => [saved]),
+ } as unknown as AgentQueuedTurnMethods & { getConvo: typeof getConvo };
+ const deps = {
+ methods,
+ checkAgentAccess: jest.fn(async () => true),
+ lifecycle: { schedule: jest.fn(), cancel: jest.fn() },
+ } satisfies AgentQueuedTurnHttpDeps;
+ const body = { ...requestBody(), parentMessageId };
+ for (let attempt = 0; attempt < 2; attempt++) {
+ await expect(
+ handleAgentQueuedTurnEnqueue({ id: USER_ID }, body, deps),
+ ).resolves.toMatchObject({ status: 202, body: { receipt: { parentMessageId } } });
+ }
+ expect(enqueue).toHaveBeenCalledTimes(1);
+ expect(getConvo).toHaveBeenCalledTimes(1);
+ expect(enqueue).toHaveBeenCalledWith(expect.objectContaining({ parentMessageId }));
+ },
+ );
+
+ it('rejects oversized response parents before ownership lookup or persistence', async () => {
+ const getConvo = jest.fn();
+ const enqueueAgentQueuedTurn = jest.fn();
+ const methods = { getConvo, enqueueAgentQueuedTurn } as unknown as AgentQueuedTurnMethods & {
+ getConvo: typeof getConvo;
+ };
+ await expect(
+ handleAgentQueuedTurnEnqueue(
+ { id: USER_ID },
+ { ...requestBody(), parentMessageId: 'a'.repeat(258) },
+ { methods, lifecycle: { schedule: jest.fn(), cancel: jest.fn() } },
+ ),
+ ).resolves.toMatchObject({ status: 400, body: { code: 'INVALID_QUEUED_TURN' } });
+ expect(getConvo).not.toHaveBeenCalled();
+ expect(enqueueAgentQueuedTurn).not.toHaveBeenCalled();
+ });
+
it('refuses snapshot writes on v1 before ownership lookup or persistence', async () => {
const getConvo = jest.fn();
const methods = { getConvo } as unknown as AgentQueuedTurnMethods & {
diff --git a/packages/api/src/middleware/index.ts b/packages/api/src/middleware/index.ts
index 9bbb1127f8..80a6c0dfbc 100644
--- a/packages/api/src/middleware/index.ts
+++ b/packages/api/src/middleware/index.ts
@@ -32,3 +32,4 @@ export * from './generationRetry';
export * from './code';
export * from './management';
export * from './twoFactor';
+export * from './messageIds';
diff --git a/packages/api/src/middleware/messageIds.ts b/packages/api/src/middleware/messageIds.ts
new file mode 100644
index 0000000000..0453b5133a
--- /dev/null
+++ b/packages/api/src/middleware/messageIds.ts
@@ -0,0 +1,49 @@
+import { Constants } from 'librechat-data-provider';
+import type { Request, Response, NextFunction } from 'express';
+import {
+ MAX_MESSAGE_ID_LENGTH,
+ MAX_RESPONSE_MESSAGE_ID_LENGTH,
+ isValidMessageId,
+} from '../utils/message';
+
+/** An override carries an optional writer index serialized from a JS safe integer. */
+const MAX_OVERRIDE_MESSAGE_ID_LENGTH =
+ MAX_MESSAGE_ID_LENGTH + Constants.COMMON_DIVIDER.length + String(Number.MAX_SAFE_INTEGER).length;
+
+/** Reject invalid client turn identities before chat admission or resume lookups. */
+export function validateChatMessageIds(req: Request, res: Response, next: NextFunction): void {
+ for (const field of [
+ 'messageId',
+ 'responseMessageId',
+ 'parentMessageId',
+ 'overrideUserMessageId',
+ 'overrideParentMessageId',
+ ] as const) {
+ const value: unknown = req.body?.[field];
+ if (value == null) {
+ continue;
+ }
+ let maxLength = MAX_MESSAGE_ID_LENGTH;
+ if (field === 'overrideUserMessageId') {
+ maxLength = MAX_OVERRIDE_MESSAGE_ID_LENGTH;
+ } else if (
+ field === 'responseMessageId' ||
+ field === 'parentMessageId' ||
+ (field === 'messageId' && req.body?.compact === true)
+ ) {
+ maxLength = MAX_RESPONSE_MESSAGE_ID_LENGTH;
+ }
+ if (
+ !isValidMessageId(value, maxLength) ||
+ (field === 'overrideUserMessageId' &&
+ !isValidMessageId(value.split(Constants.COMMON_DIVIDER, 1)[0]))
+ ) {
+ res.status(400).json({
+ code: 'INVALID_MESSAGE_ID',
+ error: `${field} must be a 1-${maxLength} character identifier using letters, digits, _, :, ., or -.`,
+ });
+ return;
+ }
+ }
+ next();
+}
diff --git a/packages/api/src/utils/message.spec.ts b/packages/api/src/utils/message.spec.ts
index 3cc6c4b2f6..8e4d4486fe 100644
--- a/packages/api/src/utils/message.spec.ts
+++ b/packages/api/src/utils/message.spec.ts
@@ -6,6 +6,9 @@ import {
getThreadData,
isPreliminaryMessageId,
isUnpersistedPreliminaryParent,
+ getPreliminaryResponseMessageId,
+ isValidMessageId,
+ MAX_MESSAGE_ID_LENGTH,
} from './message';
/** Cast to string for type compatibility with ThreadMessage */
@@ -631,3 +634,117 @@ describe('getThreadData', () => {
});
});
});
+
+describe('bounded turn message identities', () => {
+ it.each([
+ '550e8400-e29b-41d4-a716-446655440000',
+ 'nanoid_-.123',
+ 'steer-recovery:turn:user',
+ 'message__',
+ 'a'.repeat(MAX_MESSAGE_ID_LENGTH),
+ ])('accepts supported identifier %s', (messageId) => {
+ expect(isValidMessageId(messageId)).toBe(true);
+ });
+
+ it.each([
+ undefined,
+ null,
+ '',
+ 42,
+ {},
+ [],
+ 'a b',
+ 'a/b',
+ 'a\n',
+ 'a\0',
+ 'é',
+ 'a'.repeat(MAX_MESSAGE_ID_LENGTH + 1),
+ '_'.repeat(80_000) + 'X',
+ ])('rejects malformed or oversized identities', (messageId) => {
+ expect(isValidMessageId(messageId)).toBe(false);
+ expect(getPreliminaryResponseMessageId({ messageId })).toBeNull();
+ });
+
+ it.each([
+ ['message', 'message_'],
+ ['message_', 'message_'],
+ ['message___', 'message_'],
+ ['_', '_'],
+ ['____', '_'],
+ ['_'.repeat(MAX_MESSAGE_ID_LENGTH - 1) + 'X', '_'.repeat(MAX_MESSAGE_ID_LENGTH - 1) + 'X_'],
+ ])('normalizes trailing underscores without backtracking', (messageId, expected) => {
+ expect(getPreliminaryResponseMessageId({ messageId })).toBe(expected);
+ });
+
+ it('accepts a maximum-length user identity and its preliminary response on regeneration', () => {
+ const messageId = 'a'.repeat(MAX_MESSAGE_ID_LENGTH);
+ const responseMessageId = getPreliminaryResponseMessageId({ messageId });
+ expect(responseMessageId).toBe(`${messageId}_`);
+ expect(getPreliminaryResponseMessageId({ responseMessageId })).toBe(responseMessageId);
+ expect(
+ getPreliminaryResponseMessageId({ responseMessageId: `${responseMessageId}_` }),
+ ).toBeNull();
+ });
+
+ it('normalizes a maximum-length preliminary response used as a compaction anchor', () => {
+ const messageId = `${'a'.repeat(MAX_MESSAGE_ID_LENGTH)}_`;
+ expect(getPreliminaryResponseMessageId({ messageId, compact: true })).toBe(messageId);
+ expect(getPreliminaryResponseMessageId({ messageId })).toBeNull();
+ expect(
+ getPreliminaryResponseMessageId({ messageId: `${messageId}_`, compact: true }),
+ ).toBeNull();
+ expect(
+ getPreliminaryResponseMessageId({ messageId: '_'.repeat(80_000) + 'X', compact: true }),
+ ).toBeNull();
+ });
+
+ it('uses the live response when a compaction suffix would exceed the bound', () => {
+ const messageId = 'a'.repeat(MAX_MESSAGE_ID_LENGTH + 1);
+ expect(
+ getPreliminaryResponseMessageId({
+ compact: true,
+ messageId,
+ liveResponseMessageId: 'allocated-response',
+ }),
+ ).toBe('allocated-response');
+ for (const liveResponseMessageId of [undefined, '', messageId, 'b'.repeat(258), 'invalid/id']) {
+ expect(
+ getPreliminaryResponseMessageId({ compact: true, messageId, liveResponseMessageId }),
+ ).toBeNull();
+ }
+ });
+
+ it('keeps generated identities within the response contract across compaction retries', () => {
+ for (let length = 1; length <= MAX_MESSAGE_ID_LENGTH + 1; length++) {
+ for (const suffix of ['', '_', '___']) {
+ let messageId = `${'a'.repeat(length - 1)}X${suffix}`.slice(0, MAX_MESSAGE_ID_LENGTH + 1);
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const response = getPreliminaryResponseMessageId({
+ compact: true,
+ messageId,
+ liveResponseMessageId: `allocated-${attempt}`,
+ });
+ expect(response).not.toBeNull();
+ expect(isValidMessageId(response, MAX_MESSAGE_ID_LENGTH + 1)).toBe(true);
+ if (response == null) {
+ throw new Error('Missing compaction response identity');
+ }
+ messageId = response;
+ }
+ }
+ }
+ });
+
+ it('uses a valid explicit response identity', () => {
+ expect(
+ getPreliminaryResponseMessageId({ messageId: 'user', responseMessageId: 'response' }),
+ ).toBe('response');
+ });
+
+ it.each(['', {}, '_'.repeat(80_000) + 'X'])(
+ 'rejects an invalid explicit response identity',
+ (responseMessageId) => {
+ expect(getPreliminaryResponseMessageId({ messageId: 'user', responseMessageId })).toBeNull();
+ },
+ );
+});
diff --git a/packages/api/src/utils/message.ts b/packages/api/src/utils/message.ts
index 968aad5113..7fb85edecb 100644
--- a/packages/api/src/utils/message.ts
+++ b/packages/api/src/utils/message.ts
@@ -1,6 +1,58 @@
import { Constants } from 'librechat-data-provider';
import type { TFile, TMessage } from 'librechat-data-provider';
+/** Shared wire bounds, not deployment settings. */
+export const MAX_MESSAGE_ID_LENGTH: number = Constants.MAX_MESSAGE_ID_LENGTH;
+export const MAX_RESPONSE_MESSAGE_ID_LENGTH: number = Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH;
+
+export function isValidMessageId(
+ messageId: unknown,
+ maxLength: number = MAX_MESSAGE_ID_LENGTH,
+): messageId is string {
+ return (
+ typeof messageId === 'string' &&
+ messageId.length > 0 &&
+ messageId.length <= maxLength &&
+ !/[^A-Za-z0-9_:.-]/.test(messageId)
+ );
+}
+
+export function getPreliminaryResponseMessageId({
+ compact,
+ messageId,
+ responseMessageId,
+ liveResponseMessageId,
+}: {
+ messageId?: unknown;
+ responseMessageId?: unknown;
+ compact?: boolean;
+ liveResponseMessageId?: unknown;
+}): string | null {
+ if (responseMessageId != null) {
+ return isValidMessageId(responseMessageId, MAX_RESPONSE_MESSAGE_ID_LENGTH)
+ ? responseMessageId
+ : null;
+ }
+ /** Compaction uses a persisted response, not a fresh user identity. */
+ const maxLength = compact === true ? MAX_RESPONSE_MESSAGE_ID_LENGTH : MAX_MESSAGE_ID_LENGTH;
+ if (!isValidMessageId(messageId, maxLength)) {
+ return null;
+ }
+
+ let end = messageId.length;
+ while (end > 0 && messageId.charCodeAt(end - 1) === 95) {
+ end--;
+ }
+ /** A full-length compaction anchor leaves no room for the suffix. */
+ if (end >= MAX_RESPONSE_MESSAGE_ID_LENGTH) {
+ return isValidMessageId(liveResponseMessageId, MAX_RESPONSE_MESSAGE_ID_LENGTH) &&
+ liveResponseMessageId !== messageId
+ ? liveResponseMessageId
+ : null;
+ }
+ return `${messageId.slice(0, end)}_`;
+}
+
/** Minimal shape for request file entries (from `req.body.files`) */
type RequestFile = { file_id?: string };
diff --git a/packages/chat/src/core/__tests__/regenerate.spec.ts b/packages/chat/src/core/__tests__/regenerate.spec.ts
index 2f930a0704..55d324cc50 100644
--- a/packages/chat/src/core/__tests__/regenerate.spec.ts
+++ b/packages/chat/src/core/__tests__/regenerate.spec.ts
@@ -47,6 +47,35 @@ describe('regenerate helpers', () => {
expect(getPreliminaryRegenerateResponseMessageId('')).toBeNull();
});
+ it('allocates a bounded placeholder for a full-length response without truncating it', () => {
+ const responseMessageId = 'a'.repeat(257);
+ const first = getPreliminaryRegenerateResponseMessageId(responseMessageId);
+ const second = getPreliminaryRegenerateResponseMessageId(responseMessageId);
+ expect(first).toMatch(/^[0-9a-f-]{36}_$/);
+ expect(second).not.toBe(first);
+ expect(getPreliminaryRegenerateResponseMessageId(first)).toBe(first);
+ expect(getPreliminaryRegenerateResponseMessageId('a'.repeat(256) + '_')).toBe(
+ 'a'.repeat(256) + '_',
+ );
+ });
+
+ it('bounds oversized adversarial response IDs before normalization', () => {
+ expect(
+ getPreliminaryRegenerateResponseMessageId('_'.repeat(80_000) + 'X')?.length,
+ ).toBeLessThanOrEqual(257);
+ });
+
+ it('keeps response placeholders bounded and stable across the protocol boundary', () => {
+ for (let length = 1; length <= Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH + 1; length++) {
+ for (const suffix of ['', '_', '___', '_X']) {
+ const response = getPreliminaryRegenerateResponseMessageId('a'.repeat(length) + suffix);
+ expect(response).not.toBeNull();
+ expect(response?.length).toBeLessThanOrEqual(Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH);
+ expect(getPreliminaryRegenerateResponseMessageId(response)).toBe(response);
+ }
+ }
+ });
+
it('prefers the targeted response, then the latest, then the newest sibling', () => {
const first = msg({ messageId: 'a1', parentMessageId: 'u' });
const second = msg({ messageId: 'a2', parentMessageId: 'u' });
diff --git a/packages/chat/src/core/regenerate.ts b/packages/chat/src/core/regenerate.ts
index 2934eb15c5..9a806bfeaf 100644
--- a/packages/chat/src/core/regenerate.ts
+++ b/packages/chat/src/core/regenerate.ts
@@ -1,3 +1,4 @@
+import { v4 } from 'uuid';
import { Constants } from 'librechat-data-provider';
import type { TMessage } from 'librechat-data-provider';
@@ -63,7 +64,18 @@ export function getPreliminaryRegenerateResponseMessageId(
return null;
}
- return `${responseMessageId.replace(/_+$/, '')}_`;
+ if (responseMessageId.length > Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH) {
+ return `${v4()}_`;
+ }
+
+ let end = responseMessageId.length;
+ while (end > 0 && responseMessageId.charCodeAt(end - 1) === 95) {
+ end--;
+ }
+ /** Keep the placeholder distinct without truncating an existing response identity. */
+ return end >= Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH
+ ? `${v4()}_`
+ : `${responseMessageId.slice(0, end)}_`;
}
export function getRegenerateTargetResponseMessage({
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 79e5aeae05..ff809ea4a9 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -5440,6 +5440,10 @@ export enum Constants {
ENCODED_DOMAIN_LENGTH = 10,
/** Identifier for using current_model in multi-model requests. */
CURRENT_MODEL = 'current_model',
+ /** Protocol bound for UUIDs, nanoids, and derived user identities. */
+ MAX_MESSAGE_ID_LENGTH = 256,
+ /** A preliminary response reserves one trailing underscore. */
+ MAX_RESPONSE_MESSAGE_ID_LENGTH = MAX_MESSAGE_ID_LENGTH + 1,
/** Common divider for text values */
COMMON_DIVIDER = '__',
/** Max length for commands */
diff --git a/packages/data-provider/src/types/queuedTurns.spec.ts b/packages/data-provider/src/types/queuedTurns.spec.ts
index efc5875bf8..4a8aab9900 100644
--- a/packages/data-provider/src/types/queuedTurns.spec.ts
+++ b/packages/data-provider/src/types/queuedTurns.spec.ts
@@ -20,6 +20,18 @@ const request = {
};
describe('agent queued turn schemas', () => {
+ it('accepts maximum-length response parents and rejects larger ones', () => {
+ for (const parentMessageId of ['a'.repeat(257), 'a'.repeat(256) + '_']) {
+ expect(
+ enqueueAgentQueuedTurnSchema.parse({ ...request, parentMessageId }).parentMessageId,
+ ).toBe(parentMessageId);
+ }
+ expect(
+ enqueueAgentQueuedTurnSchema.safeParse({ ...request, parentMessageId: 'a'.repeat(258) })
+ .success,
+ ).toBe(false);
+ });
+
it('accepts the complete enqueue contract', () => {
expect(enqueueAgentQueuedTurnSchema.parse(request)).toEqual(request);
});
diff --git a/packages/data-provider/src/types/queuedTurns.ts b/packages/data-provider/src/types/queuedTurns.ts
index ee37706dc3..6bb575fd77 100644
--- a/packages/data-provider/src/types/queuedTurns.ts
+++ b/packages/data-provider/src/types/queuedTurns.ts
@@ -1,6 +1,7 @@
import { z } from 'zod';
import { CODE_APPROVAL_MODES } from '../code/approval';
import { reasoningOverrideSchema } from '../schemas';
+import { Constants } from '../config';
export const agentQueuedTurnStatuses = [
'queued',
@@ -26,7 +27,7 @@ export type TAgentQueuedTurnFileRef = z.infer<typeof agentQueuedTurnFileRefSchem
export const enqueueAgentQueuedTurnSchema = z.object({
conversationId: z.string().trim().min(1),
- parentMessageId: z.string().trim().min(1),
+ parentMessageId: z.string().trim().min(1).max(Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH),
clientRequestId: z.string().trim().min(1).max(128),
text: z.string(),
files: z.array(agentQueuedTurnFileRefSchema).optional(),
diff --git a/packages/data-schemas/src/methods/queuedTurn.spec.ts b/packages/data-schemas/src/methods/queuedTurn.spec.ts
index 96afb371f9..0cb96434d8 100644
--- a/packages/data-schemas/src/methods/queuedTurn.spec.ts
+++ b/packages/data-schemas/src/methods/queuedTurn.spec.ts
@@ -87,6 +87,36 @@ function rootLineageId(parentMessageId = 'parent-1') {
}
describe('agent queued turn methods', () => {
+ it.each(['a'.repeat(257), 'a'.repeat(256) + '_'])(
+ 'persists and replays a maximum-length response parent without changing lineage',
+ async (parentMessageId) => {
+ const input = enqueueInput({ parentMessageId });
+ const first = await methods.enqueueAgentQueuedTurn(input);
+ expect(first.turn.parentMessageId).toBe(parentMessageId);
+ await expect(methods.enqueueAgentQueuedTurn(input)).resolves.toMatchObject({
+ replayed: true,
+ turn: { queuedTurnId: first.turn.queuedTurnId, parentMessageId },
+ });
+ const stored = await Turn.findById(first.turn.queuedTurnId).lean();
+ expect(stored?.parentMessageId).toBe(parentMessageId);
+ await expect(
+ methods.getEffectiveAgentQueuedTurnPredecessor({
+ ...input,
+ sequence: first.turn.sequence,
+ rootParentMessageId: parentMessageId,
+ }),
+ ).resolves.toMatchObject({ lineagePredecessorId: rootLineageId(parentMessageId) });
+ },
+ );
+
+ it('rejects oversized response parents before reserving a lane or writing a row', async () => {
+ await expect(
+ methods.enqueueAgentQueuedTurn(enqueueInput({ parentMessageId: 'a'.repeat(258) })),
+ ).rejects.toBeInstanceOf(TypeError);
+ expect(await Turn.countDocuments()).toBe(0);
+ expect(await Sequence.countDocuments()).toBe(0);
+ });
+
it('normalizes payloads, replays the same request, and conflicts on changed content', async () => {
const input = enqueueInput({
text: ' follow up ',
diff --git a/packages/data-schemas/src/methods/queuedTurn.ts b/packages/data-schemas/src/methods/queuedTurn.ts
index 26c0ac4ddd..800f13b41b 100644
--- a/packages/data-schemas/src/methods/queuedTurn.ts
+++ b/packages/data-schemas/src/methods/queuedTurn.ts
@@ -1,6 +1,6 @@
import { createHash, randomUUID } from 'node:crypto';
-import { CODE_APPROVAL_MODES } from 'librechat-data-provider';
import { reasoningOverrideSchema } from 'librechat-data-provider';
+import { Constants, CODE_APPROVAL_MODES } from 'librechat-data-provider';
import type { TReasoningOverride } from 'librechat-data-provider';
import type { CodeApprovalMode } from 'librechat-data-provider';
import type { FilterQuery, Model, Types } from 'mongoose';
@@ -181,7 +181,7 @@ export interface AgentQueuedTurnPredecessor {
function getRootLineagePredecessorId(parentMessageId: string): string {
return `${ROOT_LINEAGE_PREDECESSOR_PREFIX}${createHash('sha256')
- .update(requireBoundedString(parentMessageId, 256))
+ .update(requireBoundedString(parentMessageId, Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH))
.digest('base64url')}`;
}
@@ -547,7 +547,10 @@ function requireCodeApprovalMode(mode: CodeApprovalMode): CodeApprovalMode {
function normalizeEnqueue(input: EnqueueAgentQueuedTurnInput) {
const normalized = {
agentId: requireBoundedString(input.agentId, 256),
- parentMessageId: requireBoundedString(input.parentMessageId, 256),
+ parentMessageId: requireBoundedString(
+ input.parentMessageId,
+ Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH,
+ ),
clientRequestId: requireBoundedString(input.clientRequestId, 128),
text: normalizeText(input.text),
files: normalizeFiles(input.files),
@@ -2583,7 +2586,10 @@ export function createAgentQueuedTurnMethods(
throw new TypeError('Agent queued turn sequence must be a positive integer');
}
const rootEpoch = normalizePredecessor(input.expectedPredecessorCreatedAt);
- const rootParentMessageId = requireBoundedString(input.rootParentMessageId, 256);
+ const rootParentMessageId = requireBoundedString(
+ input.rootParentMessageId,
+ Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH,
+ );
const rootLineagePredecessorId = getRootLineagePredecessorId(rootParentMessageId);
const predecessors = await Turn()
.find({
diff --git a/packages/data-schemas/src/schema/queuedTurn.ts b/packages/data-schemas/src/schema/queuedTurn.ts
index 09699ebb0c..9040720a73 100644
--- a/packages/data-schemas/src/schema/queuedTurn.ts
+++ b/packages/data-schemas/src/schema/queuedTurn.ts
@@ -1,5 +1,5 @@
import { Schema } from 'mongoose';
-import { CODE_APPROVAL_MODES } from 'librechat-data-provider';
+import { Constants, CODE_APPROVAL_MODES } from 'librechat-data-provider';
import type { IAgentQueuedTurnDocument } from '~/types/queuedTurn';
const fileRefSchema = new Schema(
@@ -67,7 +67,11 @@ const queuedTurnSchema: Schema<IAgentQueuedTurnDocument> = new Schema(
tenantId: { type: String, index: true },
conversationId: { type: String, required: true, maxlength: 256 },
agentId: { type: String, required: true, maxlength: 256 },
- parentMessageId: { type: String, required: true, maxlength: 256 },
+ parentMessageId: {
+ type: String,
+ required: true,
+ maxlength: Number(Constants.MAX_RESPONSE_MESSAGE_ID_LENGTH),
+ },
clientRequestId: { type: String, required: true, maxlength: 128 },
fingerprint: { type: String, required: true, minlength: 43, maxlength: 64 },
laneId: { type: String, required: true, maxlength: 128 },