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

🔎 feat: Filter the Conversation List by Date, Endpoint, Files, and Sharing (#16245)

Marco Berettac0ea79ad12f7
diff --git a/api/server/routes/__test-utils__/convos-route-mocks.js b/api/server/routes/__test-utils__/convos-route-mocks.js
index 2738e44959..32e7c5899b 100644
--- a/api/server/routes/__test-utils__/convos-route-mocks.js
+++ b/api/server/routes/__test-utils__/convos-route-mocks.js
@@ -109,6 +109,12 @@ module.exports = {
const raw = Array.isArray(value) ? value[0] : value;
return raw === 'asc' || raw === 'desc' ? raw : fallback;
}),
+ /** The real resolver and parser, so the route tests see the same 400s and configured
+ * limits a request would. */
+ resolveConversationListFilters: jest.fn(
+ jest.requireActual('../../../../packages/api/src/conversations/filters.ts')
+ .resolveConversationListFilters,
+ ),
resolveImportMaxFileSize: jest.fn(() => 262144000),
createAxiosInstance: jest.fn(() => ({
get: jest.fn(),
@@ -219,6 +225,8 @@ module.exports = {
}),
dataProvider: (overrides = {}) => ({
+ conversationListConfigSchema:
+ jest.requireActual('librechat-data-provider').conversationListConfigSchema,
CacheKeys: { GEN_TITLE: 'GEN_TITLE' },
EModelEndpoint: {
azureAssistants: 'azureAssistants',
@@ -237,6 +245,9 @@ module.exports = {
toolCallModel: () => ({ deleteToolCalls: jest.fn() }),
+ /** The list route reads its filter limits from the base config. */
+ appConfig: () => ({ getAppConfig: jest.fn().mockResolvedValue({}) }),
+
sharedModels: () => ({
getConvosByCursor: jest.fn(),
getConvo: jest.fn(),
diff --git a/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js b/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js
index 4eb472d6e6..ebd6c67ffe 100644
--- a/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js
+++ b/api/server/routes/__tests__/convos-duplicate-ratelimit.spec.js
@@ -41,6 +41,7 @@ jest.mock('~/server/middleware', () => {
};
});
+jest.mock('~/server/services/Config', () => require(MOCKS).appConfig());
jest.mock('~/server/utils/import/fork', () => require(MOCKS).forkUtils());
jest.mock('~/server/utils/import', () => require(MOCKS).importUtils());
jest.mock('~/server/routes/files/multer', () => require(MOCKS).multerSetup());
diff --git a/api/server/routes/__tests__/convos.spec.js b/api/server/routes/__tests__/convos.spec.js
index 83f8421042..1fd874b4c6 100644
--- a/api/server/routes/__tests__/convos.spec.js
+++ b/api/server/routes/__tests__/convos.spec.js
@@ -43,6 +43,7 @@ jest.mock('@librechat/api', () =>
jest.mock('@librechat/data-schemas', () => require(MOCKS).dataSchemas());
jest.mock('librechat-data-provider', () => require(MOCKS).dataProvider());
jest.mock('~/models', () => require(MOCKS).sharedModels());
+jest.mock('~/server/services/Config', () => require(MOCKS).appConfig());
jest.mock('~/server/middleware/requireJwtAuth', () => require(MOCKS).requireJwtAuth());
jest.mock('~/server/middleware', () => require(MOCKS).middlewarePassthrough());
jest.mock('~/server/utils/import/fork', () => require(MOCKS).forkUtils());
@@ -1878,6 +1879,119 @@ describe('Convos Routes', () => {
});
});
+ describe('GET / list facets', () => {
+ const { getConvosByCursor } = require('~/models');
+ const { getAppConfig } = require('~/server/services/Config');
+
+ beforeEach(() => {
+ getConvosByCursor.mockResolvedValue({ conversations: [], nextCursor: null });
+ });
+
+ it('forwards the date cutoffs as dates', async () => {
+ const response = await request(app)
+ .get('/api/convos')
+ .query({ updatedAfter: '2026-09-01T00:00:00.000Z' });
+
+ expect(response.status).toBe(200);
+ const [, options] = getConvosByCursor.mock.calls.at(-1);
+ expect(options.updatedAfter).toBeInstanceOf(Date);
+ expect(options.updatedAfter.toISOString()).toBe('2026-09-01T00:00:00.000Z');
+ });
+
+ it('forwards repeated endpoint params as one list', async () => {
+ const response = await request(app)
+ .get('/api/convos')
+ .query('endpoints=openAI&endpoints=agents');
+
+ expect(response.status).toBe(200);
+ expect(getConvosByCursor).toHaveBeenCalledWith(
+ 'test-user-123',
+ expect.objectContaining({ endpoints: ['openAI', 'agents'] }),
+ );
+ });
+
+ it('forwards the attachment flag only when it is on', async () => {
+ await request(app).get('/api/convos').query({ hasFiles: 'true' });
+ expect(getConvosByCursor).toHaveBeenLastCalledWith(
+ 'test-user-123',
+ expect.objectContaining({ hasFiles: true }),
+ );
+
+ await request(app).get('/api/convos').query({ hasFiles: 'false' });
+ const [, options] = getConvosByCursor.mock.calls.at(-1);
+ expect(options.hasFiles).toBeUndefined();
+ });
+
+ /** Dropping a filter the caller sent would answer with conversations they asked
+ * to exclude, which is worse than refusing the request. */
+ it('refuses a malformed cutoff instead of listing unfiltered', async () => {
+ const response = await request(app)
+ .get('/api/convos')
+ .query({ updatedAfter: 'last tuesday' });
+
+ expect(response.status).toBe(400);
+ expect(response.body.error).toMatch(/updatedAfter/);
+ expect(getConvosByCursor).not.toHaveBeenCalled();
+ });
+
+ it('refuses a mistyped flag instead of listing unfiltered', async () => {
+ const response = await request(app).get('/api/convos').query({ hasFiles: 'tru' });
+
+ expect(response.status).toBe(400);
+ expect(response.body.error).toMatch(/hasFiles/);
+ expect(getConvosByCursor).not.toHaveBeenCalled();
+ });
+
+ /** The limits are deployment-level, so the list reads the base config instead of
+ * resolving the caller's merged config on every sidebar request. */
+ it('enforces the endpoint limit the deployment configures', async () => {
+ const query = 'endpoints=openAI&endpoints=agents&endpoints=google';
+
+ const withinDefault = await request(app).get('/api/convos').query(query);
+ expect(withinDefault.status).toBe(200);
+
+ getAppConfig.mockResolvedValueOnce({
+ conversationList: { maxEndpointFilters: 2, maxEndpointNameLength: 128 },
+ });
+ const overConfigured = await request(app).get('/api/convos').query(query);
+ expect(overConfigured.status).toBe(400);
+ expect(overConfigured.body.error).toMatch(/at most 2 names/);
+ });
+
+ it('answers the route error when an endpoint filter cannot read its limits', async () => {
+ getAppConfig.mockRejectedValueOnce(new Error('config unavailable'));
+
+ const response = await request(app).get('/api/convos').query({ endpoints: 'openAI' });
+
+ expect(response.status).toBe(500);
+ expect(response.body.error).toBe('Error fetching conversations');
+ expect(getConvosByCursor).not.toHaveBeenCalled();
+ });
+
+ it('forwards the shared flag only when it is on', async () => {
+ await request(app).get('/api/convos').query({ sharedOnly: 'true' });
+ expect(getConvosByCursor).toHaveBeenLastCalledWith(
+ 'test-user-123',
+ expect.objectContaining({ sharedOnly: true }),
+ );
+
+ await request(app).get('/api/convos').query({ sharedOnly: 'false' });
+ const [, options] = getConvosByCursor.mock.calls.at(-1);
+ expect(options.sharedOnly).toBeUndefined();
+ });
+
+ it('sends no facet keys when the request carries none', async () => {
+ await request(app).get('/api/convos');
+
+ const [, options] = getConvosByCursor.mock.calls.at(-1);
+ expect(options.updatedAfter).toBeUndefined();
+ expect(options.createdAfter).toBeUndefined();
+ expect(options.endpoints).toBeUndefined();
+ expect(options.hasFiles).toBeUndefined();
+ expect(options.sharedOnly).toBeUndefined();
+ });
+ });
+
describe('GET / sort normalization', () => {
const { getConvosByCursor } = require('~/models');
diff --git a/api/server/routes/convos.js b/api/server/routes/convos.js
index b46c9952fd..e9f1f008e8 100644
--- a/api/server/routes/convos.js
+++ b/api/server/routes/convos.js
@@ -7,6 +7,7 @@ const {
normalizeLimit,
normalizeSortDirection,
normalizeSortField,
+ resolveConversationListFilters,
CONVERSATION_SORT_FIELDS,
openCheckpointDeletion,
waitForGenerationPersistence,
@@ -53,6 +54,7 @@ const { forkConversation, duplicateConversation } = require('~/server/utils/impo
const { storage, importFileFilter } = require('~/server/routes/files/multer');
const requireJwtAuth = require('~/server/middleware/requireJwtAuth');
const { importConversations } = require('~/server/utils/import');
+const { getAppConfig } = require('~/server/services/Config');
const subagentThreadTaskStore = require('~/server/services/Endpoints/agents/subagentThreadStore');
const {
pendingBackgroundToolCompletions,
@@ -189,6 +191,14 @@ router.get('/', async (req, res) => {
}
try {
+ const { filters, error: filterError } = await resolveConversationListFilters(
+ req.query,
+ getAppConfig,
+ );
+ if (filterError) {
+ return res.status(400).json({ error: filterError });
+ }
+
const result = await db.getConvosByCursor(req.user.id, {
cursor,
limit,
@@ -199,6 +209,7 @@ router.get('/', async (req, res) => {
sortBy,
sortDirection,
projectId,
+ ...filters,
});
res.status(200).json(result);
} catch (error) {
diff --git a/e2e/specs/mock/scenarios/conversation-list-filters.spec.ts b/e2e/specs/mock/scenarios/conversation-list-filters.spec.ts
new file mode 100644
index 0000000000..94a056286d
--- /dev/null
+++ b/e2e/specs/mock/scenarios/conversation-list-filters.spec.ts
@@ -0,0 +1,310 @@
+import { randomUUID } from 'node:crypto';
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { deleteConversations, deleteMessagesByConversation, withMongo } from '../db';
+import { getAccessToken, NEW_CHAT_PATH } from '../helpers';
+import { getE2EUser } from '../../../setup/user';
+
+type ListResponse = { conversations: { conversationId: string; isShared?: boolean }[] };
+type SeedRow = {
+ conversationId: string;
+ createdAt?: Date;
+ updatedAt?: Date;
+ endpoint?: string;
+ files?: string[];
+};
+
+const userEmail = getE2EUser().email;
+const DAY = 24 * 60 * 60 * 1000;
+const createdConversationIds: string[] = [];
+
+/* Every spec in the run shares this user, so each test lists through its own endpoint name:
+ * the rows it seeded are then the only rows the facet can return, and the assertions can be
+ * exact instead of "contains". */
+const uniqueEndpoint = () => `e2e-filter-${randomUUID().slice(0, 8)}`;
+
+async function userId(): Promise<string> {
+ const user = await withMongo((db) => db.collection('users').findOne({ email: userEmail }));
+ if (!user) throw new Error(`E2E seed: user "${userEmail}" not found`);
+ return user._id.toString();
+}
+
+async function seedRows(endpoint: string, rows: SeedRow[]): Promise<void> {
+ const user = await userId();
+ createdConversationIds.push(...rows.map((row) => row.conversationId));
+ await withMongo((db) =>
+ db.collection('conversations').insertMany(
+ rows.map((row) => ({
+ conversationId: row.conversationId,
+ title: `Filter ${row.conversationId.slice(0, 8)}`,
+ user,
+ endpoint: row.endpoint ?? endpoint,
+ isArchived: false,
+ ...(row.files ? { files: row.files } : {}),
+ createdAt: row.createdAt ?? new Date(),
+ updatedAt: row.updatedAt ?? new Date(),
+ __v: 0,
+ })),
+ ),
+ );
+}
+
+async function seedUserMessageWithFile(conversationId: string): Promise<void> {
+ const user = await userId();
+ await withMongo((db) =>
+ db.collection('messages').insertOne({
+ messageId: randomUUID(),
+ parentMessageId: '00000000-0000-0000-0000-000000000000',
+ conversationId,
+ user,
+ text: 'See attached',
+ isCreatedByUser: true,
+ sender: 'User',
+ endpoint: 'openAI',
+ error: false,
+ unfinished: false,
+ files: [{ file_id: randomUUID(), filename: 'notes.txt', type: 'text/plain' }],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ __v: 0,
+ }),
+ );
+}
+
+async function seedAssistantMessage(
+ conversationId: string,
+ fields: Record<string, unknown>,
+): Promise<void> {
+ const user = await userId();
+ await withMongo((db) =>
+ db.collection('messages').insertOne({
+ messageId: randomUUID(),
+ parentMessageId: '00000000-0000-0000-0000-000000000000',
+ conversationId,
+ user,
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ endpoint: 'openAI',
+ error: false,
+ unfinished: false,
+ content: [{ type: 'text', text: 'Working on it' }],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ __v: 0,
+ ...fields,
+ }),
+ );
+}
+
+async function seedShare(conversationId: string, expiredAt: Date | null): Promise<void> {
+ const user = await userId();
+ await withMongo((db) =>
+ db.collection('sharedlinks').insertOne({
+ conversationId,
+ user,
+ shareId: randomUUID(),
+ title: 'Shared',
+ messages: [],
+ isPublic: true,
+ expiredAt,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ __v: 0,
+ }),
+ );
+}
+
+async function list(page: Page, query: string): Promise<{ status: number; body: unknown }> {
+ const token = await getAccessToken(page);
+ const response = await page.request.get(`/api/convos?${query}`, {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ return { status: response.status(), body: await response.json().catch(() => null) };
+}
+
+async function listIds(page: Page, query: string): Promise<string[]> {
+ const { status, body } = await list(page, query);
+ expect(status).toBe(200);
+ return (body as ListResponse).conversations.map((convo) => convo.conversationId).sort();
+}
+
+test.beforeEach(async ({ page }) => {
+ await page.goto(NEW_CHAT_PATH);
+});
+
+test.afterEach(async () => {
+ const ids = createdConversationIds.splice(0, createdConversationIds.length);
+ if (ids.length === 0) {
+ return;
+ }
+ await withMongo((db) =>
+ db.collection('sharedlinks').deleteMany({ conversationId: { $in: ids } }),
+ );
+ await deleteMessagesByConversation(ids);
+ await deleteConversations(ids);
+});
+
+test('a date cutoff lists only conversations active since it @scenario:list-date-cutoff-excludes-older', async ({
+ page,
+}) => {
+ const endpoint = uniqueEndpoint();
+ const recent = randomUUID();
+ const stale = randomUUID();
+ const oldButCreatedRecently = randomUUID();
+ const now = Date.now();
+ await seedRows(endpoint, [
+ { conversationId: recent, createdAt: new Date(now - DAY), updatedAt: new Date(now - DAY) },
+ {
+ conversationId: stale,
+ createdAt: new Date(now - 30 * DAY),
+ updatedAt: new Date(now - 30 * DAY),
+ },
+ {
+ conversationId: oldButCreatedRecently,
+ createdAt: new Date(now - 30 * DAY),
+ updatedAt: new Date(now - DAY),
+ },
+ ]);
+ const cutoff = encodeURIComponent(new Date(now - 7 * DAY).toISOString());
+
+ expect(await listIds(page, `endpoints=${endpoint}&updatedAfter=${cutoff}`)).toEqual(
+ [recent, oldButCreatedRecently].sort(),
+ );
+ expect(await listIds(page, `endpoints=${endpoint}&createdAfter=${cutoff}`)).toEqual([recent]);
+});
+
+test('an endpoint facet lists only conversations that ran on the named endpoints @scenario:list-endpoint-facet-matches-any', async ({
+ page,
+}) => {
+ const first = uniqueEndpoint();
+ const second = uniqueEndpoint();
+ const other = uniqueEndpoint();
+ const onFirst = randomUUID();
+ const onSecond = randomUUID();
+ const onOther = randomUUID();
+ await seedRows(first, [
+ { conversationId: onFirst },
+ { conversationId: onSecond, endpoint: second },
+ { conversationId: onOther, endpoint: other },
+ ]);
+
+ expect(await listIds(page, `endpoints=${first}`)).toEqual([onFirst]);
+ expect(await listIds(page, `endpoints=${first}&endpoints=${second}`)).toEqual(
+ [onFirst, onSecond].sort(),
+ );
+});
+
+test('the attachment facet finds a chat whose only file rides on a message @scenario:list-files-facet-reads-message-attachments', async ({
+ page,
+}) => {
+ const endpoint = uniqueEndpoint();
+ const uploadedInChat = randomUUID();
+ const steeredWithFile = randomUUID();
+ const nativeImage = randomUUID();
+ const toolOutput = randomUUID();
+ const downloadOnly = randomUUID();
+ const importedWithFiles = randomUUID();
+ const emptiedFiles = randomUUID();
+ const plain = randomUUID();
+ await seedRows(endpoint, [
+ { conversationId: uploadedInChat },
+ { conversationId: steeredWithFile },
+ { conversationId: nativeImage },
+ { conversationId: toolOutput },
+ { conversationId: downloadOnly },
+ { conversationId: importedWithFiles, files: [randomUUID()] },
+ { conversationId: emptiedFiles, files: [] },
+ { conversationId: plain },
+ ]);
+ await seedUserMessageWithFile(uploadedInChat);
+ await seedAssistantMessage(steeredWithFile, {
+ content: [
+ {
+ type: 'steer',
+ steer: 'Use this file too',
+ steerId: randomUUID(),
+ files: [{ file_id: randomUUID(), filename: 'extra.txt', type: 'text/plain' }],
+ },
+ ],
+ });
+ await seedAssistantMessage(nativeImage, {
+ content: [{ type: 'image_file', image_file: { file_id: randomUUID() } }],
+ });
+ await seedAssistantMessage(toolOutput, {
+ attachments: [{ file_id: randomUUID(), filename: 'plot.png', toolCallId: randomUUID() }],
+ });
+ await seedAssistantMessage(downloadOnly, {
+ attachments: [{ filename: 'report.csv', filepath: '/api/files/code/download/s/report.csv' }],
+ });
+
+ expect(await listIds(page, `endpoints=${endpoint}&hasFiles=true`)).toEqual(
+ [
+ uploadedInChat,
+ steeredWithFile,
+ nativeImage,
+ toolOutput,
+ downloadOnly,
+ importedWithFiles,
+ ].sort(),
+ );
+ expect(await listIds(page, `endpoints=${endpoint}&hasFiles=false`)).toHaveLength(8);
+});
+
+test('the shared facet follows live links and drops expired ones @scenario:list-shared-facet-follows-live-links', async ({
+ page,
+}) => {
+ const endpoint = uniqueEndpoint();
+ const live = randomUUID();
+ const expiring = randomUUID();
+ const lapsed = randomUUID();
+ const unshared = randomUUID();
+ await seedRows(endpoint, [
+ { conversationId: live },
+ { conversationId: expiring },
+ { conversationId: lapsed },
+ { conversationId: unshared },
+ ]);
+ await seedShare(live, null);
+ await seedShare(expiring, new Date(Date.now() + DAY));
+ await seedShare(lapsed, new Date(Date.now() - DAY));
+
+ const { status, body } = await list(page, `endpoints=${endpoint}&sharedOnly=true`);
+ expect(status).toBe(200);
+ const rows = (body as ListResponse).conversations;
+ expect(rows.map((row) => row.conversationId).sort()).toEqual([live, expiring].sort());
+ expect(rows.every((row) => row.isShared === true)).toBe(true);
+});
+
+test('a malformed facet is refused instead of listing unfiltered @scenario:list-malformed-facet-refused', async ({
+ page,
+}) => {
+ for (const query of [
+ 'updatedAfter=2026-02-30',
+ 'createdAfter=last%20tuesday',
+ 'hasFiles=tru',
+ 'sharedOnly=yes',
+ `endpoints=${'x'.repeat(129)}`,
+ ]) {
+ const { status, body } = await list(page, query);
+ expect(status, query).toBe(400);
+ expect((body as { error?: string }).error, query).toEqual(expect.any(String));
+ expect((body as { conversations?: unknown }).conversations, query).toBeUndefined();
+ }
+});
+
+test('a list request without facets still returns every visible conversation @scenario:list-without-facets-unchanged', async ({
+ page,
+}) => {
+ const endpoint = uniqueEndpoint();
+ const plain = randomUUID();
+ const withFiles = randomUUID();
+ await seedRows(endpoint, [
+ { conversationId: plain },
+ { conversationId: withFiles, files: [randomUUID()] },
+ ]);
+
+ const { status, body } = await list(page, 'limit=100');
+ expect(status).toBe(200);
+ const ids = (body as ListResponse).conversations.map((convo) => convo.conversationId);
+ expect(ids).toEqual(expect.arrayContaining([plain, withFiles]));
+});
diff --git a/packages/api/src/conversations/filters.spec.ts b/packages/api/src/conversations/filters.spec.ts
new file mode 100644
index 0000000000..f473265a30
--- /dev/null
+++ b/packages/api/src/conversations/filters.spec.ts
@@ -0,0 +1,239 @@
+import { conversationListConfigSchema } from 'librechat-data-provider';
+import type { TConversationListConfig } from 'librechat-data-provider';
+import {
+ resolveConversationListFilters,
+ parseConversationListFilters as parseWithLimits,
+} from './filters';
+
+const defaults = conversationListConfigSchema.parse({});
+
+/** The parser with the schema's default limits, overridable per test. */
+const parseConversationListFilters = (
+ query: Record<string, unknown>,
+ limits: Partial<TConversationListConfig> = {},
+) => parseWithLimits(query, { ...defaults, ...limits });
+
+describe('parseConversationListFilters', () => {
+ it('leaves every facet undefined when the query carries none', () => {
+ const { filters, error } = parseConversationListFilters({});
+
+ expect(error).toBeUndefined();
+ expect(filters).toEqual({});
+ });
+
+ it('reads the date cutoffs as dates', () => {
+ const { filters, error } = parseConversationListFilters({
+ updatedAfter: '2026-09-01T00:00:00.000Z',
+ createdAfter: '2026-08-01T00:00:00.000Z',
+ });
+
+ expect(error).toBeUndefined();
+ expect(filters.updatedAfter?.toISOString()).toBe('2026-09-01T00:00:00.000Z');
+ expect(filters.createdAfter?.toISOString()).toBe('2026-08-01T00:00:00.000Z');
+ });
+
+ it('rejects a malformed date rather than dropping the filter', () => {
+ /** Dropping it would answer with conversations the user asked to exclude. */
+ const { filters, error } = parseConversationListFilters({ updatedAfter: 'last tuesday' });
+
+ expect(error).toBe('updatedAfter must be an ISO 8601 date');
+ expect(filters).toEqual({});
+ });
+
+ it('rejects dates JavaScript would silently normalize', () => {
+ /** February 30th rolls over to March and a bare number becomes 2001, so both
+ * would apply a cutoff the caller never named. */
+ expect(parseConversationListFilters({ updatedAfter: '2026-02-30' }).error).toBe(
+ 'updatedAfter must be an ISO 8601 date',
+ );
+ expect(parseConversationListFilters({ updatedAfter: '1' }).error).toBe(
+ 'updatedAfter must be an ISO 8601 date',
+ );
+ expect(parseConversationListFilters({ updatedAfter: '2026-13-01' }).error).toBe(
+ 'updatedAfter must be an ISO 8601 date',
+ );
+ expect(parseConversationListFilters({ createdAfter: '2026-09-01T25:00:00Z' }).error).toBe(
+ 'createdAfter must be an ISO 8601 date',
+ );
+ });
+
+ it('accepts a date-only cutoff as UTC midnight and an offset-bearing one', () => {
+ expect(
+ parseConversationListFilters({
+ updatedAfter: '2026-09-01',
+ }).filters.updatedAfter?.toISOString(),
+ ).toBe('2026-09-01T00:00:00.000Z');
+ expect(
+ parseConversationListFilters({
+ updatedAfter: '2026-09-01T12:00:00+02:00',
+ }).filters.updatedAfter?.toISOString(),
+ ).toBe('2026-09-01T10:00:00.000Z');
+ });
+
+ it('accepts fractional seconds finer than milliseconds', () => {
+ expect(
+ parseConversationListFilters({
+ updatedAfter: '2026-09-01T00:00:00.123456Z',
+ }).filters.updatedAfter?.toISOString(),
+ ).toBe('2026-09-01T00:00:00.123Z');
+ expect(
+ parseConversationListFilters({
+ createdAfter: '2026-09-01T00:00:00.123456789',
+ }).filters.createdAfter?.toISOString(),
+ ).toBe('2026-09-01T00:00:00.123Z');
+ });
+
+ it('reads a timestamp without an offset as UTC, not the server zone', () => {
+ expect(
+ parseConversationListFilters({
+ updatedAfter: '2026-09-01T12:00:00',
+ }).filters.updatedAfter?.toISOString(),
+ ).toBe('2026-09-01T12:00:00.000Z');
+ expect(
+ parseConversationListFilters({
+ createdAfter: '2026-09-01 08:30',
+ }).filters.createdAfter?.toISOString(),
+ ).toBe('2026-09-01T08:30:00.000Z');
+ });
+
+ it('accepts one endpoint or many, and de-duplicates them', () => {
+ expect(parseConversationListFilters({ endpoints: 'openAI' }).filters.endpoints).toEqual([
+ 'openAI',
+ ]);
+ expect(
+ parseConversationListFilters({ endpoints: ['openAI', 'agents', 'openAI'] }).filters.endpoints,
+ ).toEqual(['openAI', 'agents']);
+ });
+
+ it('ignores blank endpoint entries', () => {
+ const { filters } = parseConversationListFilters({ endpoints: ['', ' ', 'agents'] });
+
+ expect(filters.endpoints).toEqual(['agents']);
+ });
+
+ it('treats an all-blank endpoint list as no filter at all', () => {
+ const { filters, error } = parseConversationListFilters({ endpoints: ['', ' '] });
+
+ expect(error).toBeUndefined();
+ expect(filters.endpoints).toBeUndefined();
+ });
+
+ it('refuses an endpoint list long enough to be an unbounded query', () => {
+ const endpoints = Array.from({ length: 51 }, (_, index) => `endpoint-${index}`);
+ const { filters, error } = parseConversationListFilters({ endpoints });
+
+ expect(error).toMatch(/at most 50/);
+ expect(filters).toEqual({});
+ });
+
+ it('refuses an oversized endpoint name', () => {
+ const { error } = parseConversationListFilters({ endpoints: 'e'.repeat(129) });
+
+ expect(error).toMatch(/128 characters/);
+ });
+
+ it('refuses a non-string endpoint', () => {
+ const { error } = parseConversationListFilters({ endpoints: [{ $ne: null }] });
+
+ expect(error).toMatch(/endpoints must be/);
+ });
+
+ it('only treats hasFiles as a filter when it is on', () => {
+ expect(parseConversationListFilters({ hasFiles: 'true' }).filters.hasFiles).toBe(true);
+ expect(parseConversationListFilters({ hasFiles: 'false' }).filters.hasFiles).toBeUndefined();
+ expect(parseConversationListFilters({}).filters.hasFiles).toBeUndefined();
+ });
+
+ it('only treats sharedOnly as a filter when it is on', () => {
+ expect(parseConversationListFilters({ sharedOnly: 'true' }).filters.sharedOnly).toBe(true);
+ expect(
+ parseConversationListFilters({ sharedOnly: 'false' }).filters.sharedOnly,
+ ).toBeUndefined();
+ expect(parseConversationListFilters({}).filters.sharedOnly).toBeUndefined();
+ });
+
+ it('refuses a mistyped flag rather than reading it as absent', () => {
+ /** `hasFiles=tru` arriving as "no filter" would widen the list past what the
+ * user asked to see, which is the one failure this parser exists to prevent. */
+ expect(parseConversationListFilters({ hasFiles: 'tru' }).error).toBe(
+ 'hasFiles must be true or false',
+ );
+ expect(parseConversationListFilters({ sharedOnly: 'yes' }).error).toBe(
+ 'sharedOnly must be true or false',
+ );
+ expect(parseConversationListFilters({ sharedOnly: 'TRUE' }).error).toBe(
+ 'sharedOnly must be true or false',
+ );
+ });
+
+ it('honors deployment-configured endpoint limits over the defaults', () => {
+ const endpoints = Array.from({ length: 3 }, (_, index) => `endpoint-${index}`);
+ const underCustom = parseConversationListFilters({ endpoints }, { maxEndpointFilters: 3 });
+ const overCustom = parseConversationListFilters({ endpoints }, { maxEndpointFilters: 2 });
+
+ expect(underCustom.error).toBeUndefined();
+ expect(overCustom.error).toMatch(/at most 2/);
+ expect(
+ parseConversationListFilters(
+ { endpoints: 'e'.repeat(9) },
+ {
+ maxEndpointNameLength: 8,
+ },
+ ).error,
+ ).toMatch(/8 characters/);
+ });
+
+ it('refuses more endpoints than the schema default allows', () => {
+ const endpoints = Array.from({ length: 51 }, (_, index) => `endpoint-${index}`);
+ const { error } = parseConversationListFilters({ endpoints });
+
+ expect(error).toMatch(/at most 50 names of 128 characters/);
+ });
+
+ it('takes the first value when a param is repeated', () => {
+ const { filters } = parseConversationListFilters({
+ updatedAfter: ['2026-09-01T00:00:00.000Z', '2020-01-01T00:00:00.000Z'],
+ });
+
+ expect(filters.updatedAfter?.toISOString()).toBe('2026-09-01T00:00:00.000Z');
+ });
+});
+
+describe('resolveConversationListFilters', () => {
+ it('reads the limits from the base config, never the merged one', async () => {
+ const getAppConfig = jest.fn().mockResolvedValue({
+ conversationList: { maxEndpointFilters: 1, maxEndpointNameLength: 128 },
+ });
+
+ const { error } = await resolveConversationListFilters(
+ { endpoints: ['openAI', 'agents'] },
+ getAppConfig,
+ );
+
+ expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(error).toMatch(/at most 1 names/);
+ });
+
+ it('reads no config for a request that names no endpoints', async () => {
+ const getAppConfig = jest.fn().mockRejectedValue(new Error('config unavailable'));
+
+ const { filters, error } = await resolveConversationListFilters(
+ { hasFiles: 'true' },
+ getAppConfig,
+ );
+
+ expect(getAppConfig).not.toHaveBeenCalled();
+ expect(error).toBeUndefined();
+ expect(filters.hasFiles).toBe(true);
+ });
+
+ it('falls back to the schema defaults when the config carries none', async () => {
+ const endpoints = Array.from({ length: 51 }, (_, index) => `endpoint-${index}`);
+ const { error } = await resolveConversationListFilters(
+ { endpoints },
+ jest.fn().mockResolvedValue({}),
+ );
+
+ expect(error).toMatch(/at most 50/);
+ });
+});
diff --git a/packages/api/src/conversations/filters.ts b/packages/api/src/conversations/filters.ts
new file mode 100644
index 0000000000..8cb50d585b
--- /dev/null
+++ b/packages/api/src/conversations/filters.ts
@@ -0,0 +1,211 @@
+import { conversationListConfigSchema } from 'librechat-data-provider';
+import type { TConversationListConfig } from 'librechat-data-provider';
+import type { Request } from 'express';
+
+/**
+ * A conversation-list request carries user input straight into a database query, so the
+ * facets are parsed here rather than in the route: one place decides what a valid filter
+ * is, and the route keeps only the call.
+ */
+export interface ConversationListFilters {
+ updatedAfter?: Date;
+ createdAfter?: Date;
+ endpoints?: string[];
+ hasFiles?: boolean;
+ sharedOnly?: boolean;
+}
+
+export interface ConversationListFilterResult {
+ filters: ConversationListFilters;
+ /** Set when the request is malformed; the route answers 400 with it. */
+ error?: string;
+}
+
+/** Reads the deployment config; injected so this module does not reach for the app's. */
+export type ConversationListConfigReader = (options: {
+ baseOnly: true;
+}) => Promise<{ conversationList?: TConversationListConfig }>;
+
+const firstValue = (value: unknown): unknown => (Array.isArray(value) ? value[0] : value);
+
+/**
+ * The documented contract is ISO 8601, so anything `new Date()` would quietly accept
+ * beyond that is rejected here rather than applied as an unintended cutoff: `2026-02-30`
+ * rolls over to March, and `1` becomes January 1, 2001. A date-only string means UTC
+ * midnight, matching how `new Date()` parses it, and a timestamp without an offset is
+ * UTC as well: left to `new Date()` it would take the server's local zone, so the same
+ * request would select different conversations on hosts in different zones.
+ */
+const ISO_DATE =
+ /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;
+
+const parseDate = (value: unknown): { date?: Date; invalid?: boolean } => {
+ const raw = firstValue(value);
+ if (raw == null || raw === '') {
+ return {};
+ }
+ if (typeof raw !== 'string') {
+ return { invalid: true };
+ }
+ const match = ISO_DATE.exec(raw);
+ if (match == null) {
+ return { invalid: true };
+ }
+ const [, year, month, day, hour = '00', minute = '00', second = '00', , zone] = match;
+ const utc = new Date(
+ Date.UTC(
+ Number(year),
+ Number(month) - 1,
+ Number(day),
+ Number(hour),
+ Number(minute),
+ Number(second),
+ ),
+ );
+ /* A calendar-valid write reads back unchanged; February 30th does not. */
+ const readsBackClean =
+ utc.getUTCFullYear() === Number(year) &&
+ utc.getUTCMonth() === Number(month) - 1 &&
+ utc.getUTCDate() === Number(day) &&
+ utc.getUTCHours() === Number(hour) &&
+ utc.getUTCMinutes() === Number(minute) &&
+ utc.getUTCSeconds() === Number(second);
+ if (!readsBackClean) {
+ return { invalid: true };
+ }
+ /* An offset the regex could not rule out can still be unparsable; a NaN date would
+ reach the query builder as a filter it silently drops. */
+ const hasTime = match[4] != null;
+ const date = new Date(`${raw.replace(' ', 'T')}${hasTime && zone == null ? 'Z' : ''}`);
+ if (Number.isNaN(date.getTime())) {
+ return { invalid: true };
+ }
+ return { date };
+};
+
+const parseEndpoints = (
+ value: unknown,
+ limits: TConversationListConfig,
+): { endpoints?: string[]; invalid?: boolean } => {
+ if (value == null) {
+ return {};
+ }
+ const raw = Array.isArray(value) ? value : [value];
+ const endpoints: string[] = [];
+ for (const entry of raw) {
+ if (typeof entry !== 'string') {
+ return { invalid: true };
+ }
+ const trimmed = entry.trim();
+ if (trimmed === '') {
+ continue;
+ }
+ if (trimmed.length > limits.maxEndpointNameLength) {
+ return { invalid: true };
+ }
+ /** Repeated values would widen the `$in` without widening the result. */
+ if (!endpoints.includes(trimmed)) {
+ endpoints.push(trimmed);
+ }
+ }
+ if (endpoints.length === 0) {
+ return {};
+ }
+ if (endpoints.length > limits.maxEndpointFilters) {
+ return { invalid: true };
+ }
+ return { endpoints };
+};
+
+/** A supplied flag must be `true` or `false`; a typo fails the request rather than
+ * silently widening the list past what the user asked to see. */
+const parseFlag = (value: unknown): { set?: boolean; invalid?: boolean } => {
+ const raw = firstValue(value);
+ if (raw == null || raw === '') {
+ return {};
+ }
+ if (raw === 'true') {
+ return { set: true };
+ }
+ if (raw === 'false') {
+ return { set: false };
+ }
+ return { invalid: true };
+};
+
+/**
+ * Reads the list facets off a request query. An absent facet is left undefined so the
+ * query builder can tell "not filtering" from "filtering on nothing", and anything
+ * malformed fails the request rather than being silently dropped: a filter that is
+ * quietly ignored shows the user more conversations than they asked to see.
+ */
+export function parseConversationListFilters(
+ query: Request['query'] | Record<string, unknown>,
+ limits: TConversationListConfig,
+): ConversationListFilterResult {
+ const updated = parseDate(query.updatedAfter);
+ if (updated.invalid === true) {
+ return { filters: {}, error: 'updatedAfter must be an ISO 8601 date' };
+ }
+
+ const created = parseDate(query.createdAfter);
+ if (created.invalid === true) {
+ return { filters: {}, error: 'createdAfter must be an ISO 8601 date' };
+ }
+
+ const endpoints = parseEndpoints(query.endpoints, limits);
+ if (endpoints.invalid === true) {
+ return {
+ filters: {},
+ error: `endpoints must be at most ${limits.maxEndpointFilters} names of ${limits.maxEndpointNameLength} characters or fewer`,
+ };
+ }
+
+ const hasFiles = parseFlag(query.hasFiles);
+ if (hasFiles.invalid === true) {
+ return { filters: {}, error: 'hasFiles must be true or false' };
+ }
+ const sharedOnly = parseFlag(query.sharedOnly);
+ if (sharedOnly.invalid === true) {
+ return { filters: {}, error: 'sharedOnly must be true or false' };
+ }
+
+ const filters: ConversationListFilters = {};
+ if (updated.date) {
+ filters.updatedAfter = updated.date;
+ }
+ if (created.date) {
+ filters.createdAfter = created.date;
+ }
+ if (endpoints.endpoints) {
+ filters.endpoints = endpoints.endpoints;
+ }
+ /** Only the positive case is a filter: an explicit "false" means the user is not
+ filtering, same as leaving the facet out. */
+ if (hasFiles.set === true) {
+ filters.hasFiles = true;
+ }
+ if (sharedOnly.set === true) {
+ filters.sharedOnly = true;
+ }
+
+ return { filters };
+}
+
+/**
+ * The list route's entry point. The limits are deployment-level, so they come from the
+ * base config rather than the caller's merged config, and only a request naming endpoints
+ * reads it at all: the limits bound nothing else, and an unfiltered sidebar request should
+ * not wait on, or fail with, a config cache it does not use.
+ */
+export async function resolveConversationListFilters(
+ query: Request['query'],
+ getAppConfig: ConversationListConfigReader,
+): Promise<ConversationListFilterResult> {
+ const { conversationList } =
+ query.endpoints == null ? {} : await getAppConfig({ baseOnly: true });
+ return parseConversationListFilters(
+ query,
+ conversationList ?? conversationListConfigSchema.parse({}),
+ );
+}
diff --git a/packages/api/src/conversations/index.ts b/packages/api/src/conversations/index.ts
index 535f017835..793a428ff2 100644
--- a/packages/api/src/conversations/index.ts
+++ b/packages/api/src/conversations/index.ts
@@ -1,6 +1,7 @@
export * from './announce';
export * from './archive';
export * from './chatgpt';
+export * from './filters';
export * from './import';
export * from './lineage';
export * from './read';
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 18ddfbb798..7c60e5da03 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -3332,6 +3332,22 @@ export type TOpenIdDiscoveryConfig = z.infer<typeof openIdDiscoverySchema>;
/** Maximum CAS attempts per ACL document, including the initial attempt. */
export const permissionWriteAttemptsSchema = z.number().int().min(1).max(100).default(3);
+/**
+ * Validation limits for the conversation list's filter facets. The field defaults are the
+ * only definition of these values: `getConfigDefaults()` resolves them for AppService, and
+ * the parser takes what AppService resolved.
+ */
+export const conversationListConfigSchema = z.object({
+ /** How many endpoint names one filter request may name. The list is a fixed menu of the
+ * endpoints a deployment serves, so a request naming more than this is not a user
+ * choosing filters: it is an unbounded `$in` arriving from somewhere else. */
+ maxEndpointFilters: z.number().int().min(1).max(1_000).default(50),
+ /** One endpoint name. Long enough for a custom endpoint, short enough to bound the query. */
+ maxEndpointNameLength: z.number().int().min(1).max(1_024).default(128),
+});
+
+export type TConversationListConfig = z.infer<typeof conversationListConfigSchema>;
+
export const configSchema = z.object({
version: z.string(),
permissions: z.object({ maxWriteAttempts: permissionWriteAttemptsSchema }).optional(),
@@ -3344,6 +3360,9 @@ export const configSchema = z.object({
skillSync: skillSyncConfigSchema,
secureImageLinks: z.boolean().optional(),
imageOutputType: z.nativeEnum(EImageOutputType).default(EImageOutputType.PNG),
+ conversationList: conversationListConfigSchema.default(() =>
+ conversationListConfigSchema.parse({}),
+ ),
includedTools: z.array(z.string()).optional(),
filteredTools: z.array(z.string()).optional(),
mcpServers: MCPServersSchema.optional(),
diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.ts
index 20d1911622..4d7dbc8820 100644
--- a/packages/data-provider/src/types/queries.ts
+++ b/packages/data-provider/src/types/queries.ts
@@ -23,6 +23,19 @@ export type ConversationListParams = {
tags?: string[];
search?: string;
projectId?: string;
+ /**
+ * Absolute cutoffs rather than a named window, so the server validates one thing
+ * (a date) instead of an enum it would have to keep in step with the client, and a
+ * caller can ask for a range the menu does not offer. ISO 8601, inclusive.
+ */
+ updatedAfter?: string;
+ createdAfter?: string;
+ /** OR-matched: a conversation qualifies if it ran on any of these endpoints. */
+ endpoints?: string[];
+ /** Only conversations carrying at least one attachment. */
+ hasFiles?: boolean;
+ /** Only conversations the user is actively sharing through a link. */
+ sharedOnly?: boolean;
};
export type MinimalConversation = Pick<
diff --git a/packages/data-schemas/src/app/service.spec.ts b/packages/data-schemas/src/app/service.spec.ts
index 906f7978d3..7bb0320086 100644
--- a/packages/data-schemas/src/app/service.spec.ts
+++ b/packages/data-schemas/src/app/service.spec.ts
@@ -309,6 +309,40 @@ describe('AppService MCP App sandbox configuration', () => {
});
});
+describe('AppService conversation list limits', () => {
+ it('carries the configured filter limits onto the app config', async () => {
+ const result = await AppService({
+ config: {
+ conversationList: { maxEndpointFilters: 200, maxEndpointNameLength: 256 },
+ } as DeepPartial<TCustomConfig>,
+ });
+
+ expect(result.conversationList).toEqual({
+ maxEndpointFilters: 200,
+ maxEndpointNameLength: 256,
+ });
+ });
+
+ it('fills the schema defaults when the deployment configures none', async () => {
+ const result = await AppService({ config: {} as DeepPartial<TCustomConfig> });
+ expect(result.conversationList).toEqual({ maxEndpointFilters: 50, maxEndpointNameLength: 128 });
+ });
+
+ it('keeps the defaults when the configured block is invalid', async () => {
+ const result = await AppService({
+ config: { conversationList: { maxEndpointFilters: 0 } } as DeepPartial<TCustomConfig>,
+ });
+ expect(result.conversationList).toEqual({ maxEndpointFilters: 50, maxEndpointNameLength: 128 });
+ });
+
+ it('keeps the default for a limit the deployment leaves out', async () => {
+ const result = await AppService({
+ config: { conversationList: { maxEndpointFilters: 10 } } as DeepPartial<TCustomConfig>,
+ });
+ expect(result.conversationList).toEqual({ maxEndpointFilters: 10, maxEndpointNameLength: 128 });
+ });
+});
+
describe('AppService memory capability', () => {
it('strips the memory capability when no memory config is present', async () => {
const result = await AppService({ config: {} as DeepPartial<TCustomConfig> });
diff --git a/packages/data-schemas/src/app/service.ts b/packages/data-schemas/src/app/service.ts
index 2a40be0fee..132afaed7c 100644
--- a/packages/data-schemas/src/app/service.ts
+++ b/packages/data-schemas/src/app/service.ts
@@ -2,6 +2,7 @@ import {
AgentCapabilities,
EModelEndpoint,
filtersConfigSchema,
+ conversationListConfigSchema,
hasActiveFiltersConfig,
getConfigDefaults,
langfuseConfigSchema,
@@ -91,6 +92,19 @@ export function loadLangfuseConfig(config: DeepPartial<TCustomConfig>): AppConfi
return parsed.data;
}
+/** Resolves the list filter limits, schema defaults included; an invalid block keeps the
+ * defaults rather than lifting a bound the operator meant to set. */
+export function loadConversationListConfig(
+ config: DeepPartial<TCustomConfig>,
+): NonNullable<AppConfig['conversationList']> {
+ const parsed = conversationListConfigSchema.safeParse(config.conversationList ?? {});
+ if (parsed.success) {
+ return parsed.data;
+ }
+ logger.warn('[AppService] Invalid conversationList config', parsed.error.flatten());
+ return conversationListConfigSchema.parse({});
+}
+
export function loadFiltersConfig(config: DeepPartial<TCustomConfig>): AppConfig['filters'] {
const raw = config.filters;
if (raw === undefined) {
@@ -203,6 +217,7 @@ export const AppService = async (params?: {
fileStrategies: config.fileStrategies,
cloudfront: config.cloudfront as AppConfig['cloudfront'],
secureImageLinks: config.secureImageLinks !== false,
+ conversationList: loadConversationListConfig(config),
};
const agentsDefaults = agentsConfigSetup(config);
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index a75eafba1e..97897c1aec 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -8465,4 +8465,411 @@ describe('Conversation Operations', () => {
]);
});
});
+ describe('getConvosByCursor list facets', () => {
+ const user = 'facet-user';
+ const day = 24 * 60 * 60 * 1000;
+
+ /** `timestamps: true` rewrites both dates on save, so a test that needs an old
+ * conversation has to set them afterwards. */
+ const makeConvo = async (
+ overrides: Partial<{
+ title: string;
+ endpoint: string;
+ updatedAt: Date;
+ createdAt: Date;
+ files: string[];
+ }> = {},
+ ) => {
+ const convo = await Conversation.create({
+ conversationId: uuidv4(),
+ user,
+ title: overrides.title ?? 'Facet conversation',
+ endpoint: overrides.endpoint ?? EModelEndpoint.openAI,
+ ...(overrides.files ? { files: overrides.files } : {}),
+ });
+
+ if (overrides.updatedAt || overrides.createdAt) {
+ /** Through the driver, not the model: Mongoose suppresses `updatedAt` only with
+ * `timestamps: false` and refuses `createdAt` outright, since it marks the
+ * field immutable. */
+ await Conversation.collection.updateOne(
+ { _id: convo._id },
+ {
+ $set: {
+ ...(overrides.updatedAt ? { updatedAt: overrides.updatedAt } : {}),
+ ...(overrides.createdAt ? { createdAt: overrides.createdAt } : {}),
+ },
+ },
+ );
+ }
+
+ return convo;
+ };
+
+ beforeEach(async () => {
+ await Conversation.deleteMany({ user });
+ });
+
+ it('keeps only conversations updated at or after the cutoff', async () => {
+ const recent = await makeConvo({ title: 'recent', updatedAt: new Date() });
+ await makeConvo({ title: 'stale', updatedAt: new Date(Date.now() - 30 * day) });
+
+ const result = await getConvosByCursor(user, {
+ updatedAfter: new Date(Date.now() - 7 * day),
+ });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([recent.conversationId]);
+ });
+
+ it('filters on createdAt independently of updatedAt', async () => {
+ /** An old chat replied to today has a new updatedAt and an old createdAt. */
+ const revived = await makeConvo({
+ title: 'revived',
+ createdAt: new Date(Date.now() - 30 * day),
+ updatedAt: new Date(),
+ });
+ const fresh = await makeConvo({ title: 'fresh', createdAt: new Date() });
+
+ const byCreated = await getConvosByCursor(user, {
+ createdAfter: new Date(Date.now() - 7 * day),
+ });
+ expect(byCreated.conversations.map((c) => c.conversationId)).toEqual([fresh.conversationId]);
+
+ const byUpdated = await getConvosByCursor(user, {
+ updatedAfter: new Date(Date.now() - 7 * day),
+ });
+ expect(byUpdated.conversations.map((c) => c.conversationId).sort()).toEqual(
+ [revived.conversationId, fresh.conversationId].sort(),
+ );
+ });
+
+ it('matches any of the requested endpoints', async () => {
+ const openai = await makeConvo({ endpoint: EModelEndpoint.openAI });
+ const anthropic = await makeConvo({ endpoint: EModelEndpoint.anthropic });
+ await makeConvo({ endpoint: EModelEndpoint.google });
+
+ const result = await getConvosByCursor(user, {
+ endpoints: [EModelEndpoint.openAI, EModelEndpoint.anthropic],
+ });
+
+ expect(result.conversations.map((c) => c.conversationId).sort()).toEqual(
+ [openai.conversationId, anthropic.conversationId].sort(),
+ );
+ });
+
+ it('treats a missing and an emptied file list alike when filtering on attachments', async () => {
+ const withFiles = await makeConvo({ title: 'with files', files: ['file-1'] });
+ await makeConvo({ title: 'no field' });
+ await makeConvo({ title: 'emptied', files: [] });
+
+ const result = await getConvosByCursor(user, { hasFiles: true });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([withFiles.conversationId]);
+ });
+
+ it('includes conversations whose attachments ride on messages', async () => {
+ /** The standard send flow persists uploads on the user message, so a facet that
+ * only read the conversation's own array would miss every ordinary chat. */
+ const Message = mongoose.models.Message as mongoose.Model<{
+ user: string;
+ conversationId: string;
+ messageId: string;
+ files: unknown[];
+ }>;
+ const messageFiles = await makeConvo({ title: 'message files' });
+ await makeConvo({ title: 'neither' });
+ await Message.create({
+ user,
+ conversationId: messageFiles.conversationId,
+ messageId: uuidv4(),
+ text: 'here you go',
+ sender: 'User',
+ isCreatedByUser: true,
+ files: [{ file_id: 'file-1' }],
+ });
+
+ const result = await getConvosByCursor(user, { hasFiles: true });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([
+ messageFiles.conversationId,
+ ]);
+ });
+
+ it('reads files attached to a message content part, such as a steer', async () => {
+ const Message = mongoose.models.Message as mongoose.Model<{
+ user: string;
+ conversationId: string;
+ messageId: string;
+ content: unknown[];
+ }>;
+ const steered = await makeConvo({ title: 'steered' });
+ const textOnly = await makeConvo({ title: 'text only' });
+ await Message.create([
+ {
+ user,
+ conversationId: steered.conversationId,
+ messageId: uuidv4(),
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ content: [
+ { type: 'text', text: 'working on it' },
+ { type: 'steer', steer: 'use this', steerId: 's-1', files: [{ file_id: 'f-1' }] },
+ ],
+ },
+ {
+ user,
+ conversationId: textOnly.conversationId,
+ messageId: uuidv4(),
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ content: [{ type: 'steer', steer: 'no file', steerId: 's-2', files: [] }],
+ },
+ ]);
+
+ const result = await getConvosByCursor(user, { hasFiles: true });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([steered.conversationId]);
+ });
+
+ it.each([
+ ['a provider-native file part', { type: 'file', file: { file_id: 'f-native' } }],
+ ['an image_file part', { type: 'image_file', image_file: { file_id: 'f-image' } }],
+ ['a part carrying a bare file_id', { type: 'file', file_id: 'f-bare' }],
+ ])('reads files attached as %s', async (_label, part) => {
+ const Message = mongoose.models.Message as mongoose.Model<{
+ user: string;
+ conversationId: string;
+ messageId: string;
+ content: unknown[];
+ }>;
+ const attached = await makeConvo({ title: 'attached' });
+ await makeConvo({ title: 'text only' });
+ await Message.create({
+ user,
+ conversationId: attached.conversationId,
+ messageId: uuidv4(),
+ sender: 'User',
+ isCreatedByUser: true,
+ content: [{ type: 'text', text: 'see this' }, part],
+ });
+
+ const result = await getConvosByCursor(user, { hasFiles: true });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([attached.conversationId]);
+ });
+
+ it('reads files a tool or assistant attached to its response', async () => {
+ const Message = mongoose.models.Message as mongoose.Model<{
+ user: string;
+ conversationId: string;
+ messageId: string;
+ attachments: unknown[];
+ }>;
+ const generated = await makeConvo({ title: 'generated file' });
+ const downloadOnly = await makeConvo({ title: 'download-only file' });
+ const searched = await makeConvo({ title: 'search results only' });
+ await Message.create([
+ {
+ user,
+ conversationId: generated.conversationId,
+ messageId: uuidv4(),
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ attachments: [{ file_id: 'f-out', filename: 'plot.png', toolCallId: 't-1' }],
+ },
+ {
+ user,
+ conversationId: downloadOnly.conversationId,
+ messageId: uuidv4(),
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ attachments: [
+ { filename: 'report.csv', filepath: '/api/files/code/download/s/report.csv' },
+ ],
+ },
+ {
+ user,
+ conversationId: searched.conversationId,
+ messageId: uuidv4(),
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ attachments: [
+ { type: 'web_search', toolCallId: 't-2' },
+ { filename: 'blank.txt', filepath: '' },
+ ],
+ },
+ ]);
+
+ const result = await getConvosByCursor(user, { hasFiles: true });
+
+ expect(result.conversations.map((c) => c.conversationId).sort()).toEqual(
+ [generated.conversationId, downloadOnly.conversationId].sort(),
+ );
+ });
+
+ it('combines facets rather than widening the result', async () => {
+ const match = await makeConvo({
+ title: 'match',
+ endpoint: EModelEndpoint.openAI,
+ files: ['file-1'],
+ updatedAt: new Date(),
+ });
+ await makeConvo({ title: 'wrong endpoint', endpoint: EModelEndpoint.google, files: ['f'] });
+ await makeConvo({ title: 'no files', endpoint: EModelEndpoint.openAI });
+ await makeConvo({
+ title: 'too old',
+ endpoint: EModelEndpoint.openAI,
+ files: ['f'],
+ updatedAt: new Date(Date.now() - 30 * day),
+ });
+
+ const result = await getConvosByCursor(user, {
+ endpoints: [EModelEndpoint.openAI],
+ hasFiles: true,
+ updatedAfter: new Date(Date.now() - 7 * day),
+ });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([match.conversationId]);
+ });
+
+ it('carries the facets across a paged cursor', async () => {
+ const wanted = [] as string[];
+ for (let index = 0; index < 3; index++) {
+ const convo = await makeConvo({
+ title: `wanted ${index}`,
+ endpoint: EModelEndpoint.openAI,
+ updatedAt: new Date(Date.now() - index * 1000),
+ });
+ wanted.push(convo.conversationId);
+ }
+ for (let index = 0; index < 3; index++) {
+ await makeConvo({ title: `other ${index}`, endpoint: EModelEndpoint.google });
+ }
+
+ const first = await getConvosByCursor(user, {
+ endpoints: [EModelEndpoint.openAI],
+ limit: 2,
+ });
+ expect(first.conversations).toHaveLength(2);
+ expect(first.nextCursor).not.toBeNull();
+
+ const second = await getConvosByCursor(user, {
+ endpoints: [EModelEndpoint.openAI],
+ limit: 2,
+ cursor: first.nextCursor,
+ });
+
+ const paged = [...first.conversations, ...second.conversations].map((c) => c.conversationId);
+ /** The second page must not reintroduce the rows the filter excluded. */
+ expect(paged.sort()).toEqual(wanted.sort());
+ });
+
+ it('keeps only conversations with an active shared link', async () => {
+ const SharedLink = mongoose.models.SharedLink as mongoose.Model<{
+ conversationId: string;
+ user: string;
+ shareId: string;
+ expiredAt?: Date | null;
+ }>;
+ const shared = await makeConvo({ title: 'shared' });
+ await makeConvo({ title: 'not shared' });
+ const expired = await makeConvo({ title: 'share expired' });
+
+ await SharedLink.create([
+ { conversationId: shared.conversationId, user, shareId: `share-${uuidv4()}` },
+ {
+ conversationId: expired.conversationId,
+ user,
+ shareId: `share-${uuidv4()}`,
+ expiredAt: new Date('2020-01-01T00:00:00.000Z'),
+ },
+ ]);
+
+ const result = await getConvosByCursor(user, { sharedOnly: true });
+
+ /** A lapsed link is not a shared chat, which is why this reads the links rather
+ * than a flag stored on the conversation. */
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([shared.conversationId]);
+ /** The filter already resolved the share set, so the row carries its flag from
+ * that answer rather than waiting on a second lookup. */
+ expect(result.conversations[0].isShared).toBe(true);
+
+ await SharedLink.deleteMany({ user });
+ });
+
+ it('returns nothing when the user shares nothing', async () => {
+ await makeConvo({ title: 'present' });
+
+ const result = await getConvosByCursor(user, { sharedOnly: true });
+
+ /** An empty `$in` would match every document, so this must short-circuit. */
+ expect(result.conversations).toEqual([]);
+ expect(result.nextCursor).toBeNull();
+ });
+
+ it('returns nothing when the deployment has sharing switched off', async () => {
+ const SharedLink = mongoose.models.SharedLink as mongoose.Model<{
+ conversationId: string;
+ user: string;
+ shareId: string;
+ }>;
+ const shared = await makeConvo({ title: 'shared' });
+ await SharedLink.create({
+ conversationId: shared.conversationId,
+ user,
+ shareId: `share-${uuidv4()}`,
+ });
+
+ const previous = process.env.ALLOW_SHARED_LINKS;
+ process.env.ALLOW_SHARED_LINKS = 'false';
+ try {
+ const result = await getConvosByCursor(user, { sharedOnly: true });
+ expect(result.conversations).toEqual([]);
+ } finally {
+ if (previous === undefined) {
+ delete process.env.ALLOW_SHARED_LINKS;
+ } else {
+ process.env.ALLOW_SHARED_LINKS = previous;
+ }
+ await SharedLink.deleteMany({ user });
+ }
+ });
+
+ it('narrows shared chats further with another facet', async () => {
+ const SharedLink = mongoose.models.SharedLink as mongoose.Model<{
+ conversationId: string;
+ user: string;
+ shareId: string;
+ }>;
+ const match = await makeConvo({ title: 'shared openai', endpoint: EModelEndpoint.openAI });
+ const wrongEndpoint = await makeConvo({
+ title: 'shared google',
+ endpoint: EModelEndpoint.google,
+ });
+
+ await SharedLink.create([
+ { conversationId: match.conversationId, user, shareId: `share-${uuidv4()}` },
+ { conversationId: wrongEndpoint.conversationId, user, shareId: `share-${uuidv4()}` },
+ ]);
+
+ const result = await getConvosByCursor(user, {
+ sharedOnly: true,
+ endpoints: [EModelEndpoint.openAI],
+ });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([match.conversationId]);
+
+ await SharedLink.deleteMany({ user });
+ });
+
+ it('ignores an invalid date rather than filtering on NaN', async () => {
+ const convo = await makeConvo({ title: 'present' });
+
+ const result = await getConvosByCursor(user, {
+ updatedAfter: new Date('not a date'),
+ });
+
+ expect(result.conversations.map((c) => c.conversationId)).toEqual([convo.conversationId]);
+ });
+ });
});
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index e527a0b134..f5235c1f16 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -21,6 +21,7 @@ import type {
IChatProjectDocument,
IActiveSubagentThreadLease,
IConversation,
+ IMessage,
ISharedLink,
ISubagentThreadReservation,
} from '~/types';
@@ -344,6 +345,11 @@ export interface ConversationMethods {
sortBy?: string;
sortDirection?: string;
projectId?: string;
+ updatedAfter?: Date;
+ createdAfter?: Date;
+ endpoints?: string[];
+ hasFiles?: boolean;
+ sharedOnly?: boolean;
},
): Promise<{ conversations: IConversation[]; nextCursor: string | null }>;
getConvosQueried(
@@ -3067,6 +3073,63 @@ export function createConversationMethods(
}
}
+ /**
+ * Conversations with a file on any of this user's messages. A message holds files in
+ * three places: uploads on `files`, tool and assistant output on `attachments` (a stored
+ * file, or a download-only one the client renders by its `filepath`), and content parts
+ * in every shape replay reads (a steer's `files`, a provider-native `file` or
+ * `image_file`, or a bare `file_id`).
+ */
+ async function getMessageFileConversationIds(user: string): Promise<string[] | null> {
+ const Message = mongoose.models.Message as Model<IMessage> | undefined;
+ if (!Message) {
+ return null;
+ }
+ return Message.find({
+ user,
+ $or: [
+ { 'files.0': { $exists: true } },
+ { 'attachments.file_id': { $type: 'string' } },
+ { 'attachments.filepath': { $type: 'string', $gt: '' } },
+ { 'content.files.0': { $exists: true } },
+ { 'content.file.file_id': { $type: 'string' } },
+ { 'content.image_file.file_id': { $type: 'string' } },
+ { 'content.file_id': { $type: 'string' } },
+ ],
+ }).distinct('conversationId');
+ }
+
+ /**
+ * The conversations this user is actively sharing.
+ *
+ * Shared state is not a field on the conversation: it is a live link that can expire,
+ * so a denormalized flag would keep saying "shared" after a link lapsed. This asks the
+ * links themselves, indexed by `{ user, conversationId }`, and returns `null` when the
+ * deployment has sharing switched off so the caller can tell "no links" from "not
+ * applicable".
+ */
+ async function getSharedConversationIds(user: string): Promise<string[] | null> {
+ const SharedLink = mongoose.models.SharedLink as Model<ISharedLink> | undefined;
+ if (!SharedLink) {
+ return null;
+ }
+ const allowSharedLinks = process.env.ALLOW_SHARED_LINKS;
+ if (allowSharedLinks !== undefined && allowSharedLinks.toLowerCase().trim() !== 'true') {
+ return null;
+ }
+
+ /* Distinct, not find: the only thing this caller can use is the set of IDs, so the
+ server dedupes and returns nothing else. Covered by `{ user, conversationId }`. */
+ const sharedIds = await SharedLink.find({
+ user,
+ ...activeExpirationFilter<ISharedLink>(),
+ }).distinct('conversationId');
+
+ return sharedIds.filter(
+ (conversationId): conversationId is string => typeof conversationId === 'string',
+ );
+ }
+
/**
* Retrieves conversations using cursor-based pagination.
*/
@@ -3082,6 +3145,11 @@ export function createConversationMethods(
sortBy = 'updatedAt',
sortDirection = 'desc',
projectId,
+ updatedAfter,
+ createdAfter,
+ endpoints,
+ hasFiles,
+ sharedOnly,
}: {
cursor?: string | null;
limit?: number;
@@ -3092,6 +3160,11 @@ export function createConversationMethods(
sortBy?: string;
sortDirection?: string;
projectId?: string;
+ updatedAfter?: Date;
+ createdAfter?: Date;
+ endpoints?: string[];
+ hasFiles?: boolean;
+ sharedOnly?: boolean;
} = {},
) {
const Conversation = mongoose.models.Conversation as Model<IConversation> &
@@ -3126,6 +3199,54 @@ export function createConversationMethods(
filters.push({ chatProjectId: projectId } as FilterQuery<IConversation>);
}
+ /* Ranges are half-open on purpose: the caller sends the start of the window it
+ means, and "since midnight" must not depend on how the clock rounds. */
+ if (updatedAfter instanceof Date && !Number.isNaN(updatedAfter.getTime())) {
+ filters.push({ updatedAt: { $gte: updatedAfter } } as FilterQuery<IConversation>);
+ }
+ if (createdAfter instanceof Date && !Number.isNaN(createdAfter.getTime())) {
+ filters.push({ createdAt: { $gte: createdAfter } } as FilterQuery<IConversation>);
+ }
+
+ if (Array.isArray(endpoints) && endpoints.length > 0) {
+ filters.push({ endpoint: { $in: endpoints } } as FilterQuery<IConversation>);
+ }
+
+ /* The two facet lookups are independent user-scoped reads, so they start together
+ instead of adding their latencies on every page that combines them. */
+ const [messageFileIds, activeShares] = await Promise.all([
+ hasFiles === true ? getMessageFileConversationIds(user) : null,
+ sharedOnly === true ? getSharedConversationIds(user) : null,
+ ]);
+
+ /* Attachments are not one field: the standard flow rides them on messages, imports
+ can land them on the conversation, and `files` is absent or `[]` when empty. The
+ conversation-side predicate alone would miss every ordinary chat with an upload,
+ so the message-side conversation IDs are OR-matched in. */
+ if (hasFiles === true) {
+ const orClauses: FilterQuery<IConversation>[] = [
+ { files: { $exists: true, $not: { $size: 0 } } } as FilterQuery<IConversation>,
+ ];
+ if (messageFileIds != null && messageFileIds.length > 0) {
+ orClauses.push({ conversationId: { $in: messageFileIds } } as FilterQuery<IConversation>);
+ }
+ filters.push({ $or: orClauses } as FilterQuery<IConversation>);
+ }
+
+ /* When this filter runs, the page's rows are already known to be shared, so the set
+ is kept and used to mark `isShared` directly instead of issuing a second
+ SharedLink query after the conversation query for the same answers. */
+ let sharedIds: Set<string> | null = null;
+ if (sharedOnly === true) {
+ /* Nothing shared, or sharing switched off, means nothing can match. Returning early
+ also keeps an empty `$in` out of the query, which would match every document. */
+ if (activeShares == null || activeShares.length === 0) {
+ return { conversations: [], nextCursor: null };
+ }
+ sharedIds = new Set(activeShares);
+ filters.push({ conversationId: { $in: activeShares } } as FilterQuery<IConversation>);
+ }
+
filters.push(getVisibleConversationRetentionFilter());
filters.push(getHumanConversationFilter());
@@ -3313,7 +3434,13 @@ export function createConversationMethods(
nextCursor = Buffer.from(JSON.stringify(composite)).toString('base64');
}
- await attachSharedFlags(user, convos);
+ if (sharedIds != null) {
+ for (const convo of convos) {
+ convo.isShared = sharedIds.has(convo.conversationId);
+ }
+ } else {
+ await attachSharedFlags(user, convos);
+ }
return { conversations: convos, nextCursor };
} catch (error) {
diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.ts
index 67aac88d3b..abbe370389 100644
--- a/packages/data-schemas/src/schema/convo.ts
+++ b/packages/data-schemas/src/schema/convo.ts
@@ -425,6 +425,13 @@ convoSchema.index({ user: 1, isArchived: 1, updatedAt: -1, _id: -1 });
convoSchema.index({ user: 1, isArchived: 1, createdAt: -1, updatedAt: -1, _id: -1 });
convoSchema.index({ user: 1, isArchived: 1, title: 1, updatedAt: 1, _id: 1 });
+/** The endpoint facet, on the default sort. Without `endpoint` in the key MongoDB has
+ * to fetch every document in the user's list order just to discard it, so a filter that
+ * matches few rows reads the whole list; with it the scan stays inside the index.
+ * Date-range facets need no index of their own: they are a bound on the sort key the
+ * indexes above already lead with. */
+convoSchema.index({ user: 1, isArchived: 1, endpoint: 1, updatedAt: -1, _id: -1 });
+
/** The sidebar's pinned section filters on user + pinned and pages by `updatedAt`. */
convoSchema.index({ user: 1, pinned: 1, updatedAt: -1, _id: -1 });
diff --git a/packages/data-schemas/src/schema/share.ts b/packages/data-schemas/src/schema/share.ts
index f1cf0a6b33..bacc3cd7e1 100644
--- a/packages/data-schemas/src/schema/share.ts
+++ b/packages/data-schemas/src/schema/share.ts
@@ -86,6 +86,10 @@ const shareSchema: Schema<ISharedLink> = new Schema(
shareSchema.index({ expiredAt: 1 }, { expireAfterSeconds: 0 });
shareSchema.index({ conversationId: 1, user: 1, targetMessageId: 1, tenantId: 1 });
+/** The sidebar's "shared" filter asks the opposite question of the index above: which
+ * conversations has THIS user shared. That leads with `conversationId`, so a user-scoped
+ * lookup could not use it and would scan every link in the deployment. */
+shareSchema.index({ user: 1, conversationId: 1 });
shareSchema.index({ updatedAt: -1 });
export default shareSchema;
diff --git a/packages/data-schemas/src/types/app.ts b/packages/data-schemas/src/types/app.ts
index 1a0b3a5d9f..4d7a656cc2 100644
--- a/packages/data-schemas/src/types/app.ts
+++ b/packages/data-schemas/src/types/app.ts
@@ -13,6 +13,7 @@ import type {
TAssistantEndpoint,
TAnthropicEndpoint,
SummarizationConfig,
+ TConversationListConfig,
SkillSyncConfig,
FiltersConfig,
} from 'librechat-data-provider';
@@ -112,6 +113,8 @@ export interface AppConfig {
fileConfig?: TFileConfig;
/** Secure image links configuration, enabled unless explicitly disabled */
secureImageLinks?: TCustomConfig['secureImageLinks'];
+ /** Validation limits for the conversation list's filter facets */
+ conversationList?: TConversationListConfig;
/** Processed model specifications */
modelSpecs?: TCustomConfig['modelSpecs'];
/** Available tools */