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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧵 fix: Hide Child Threads From Navigation (#15041)
Danny Avila9c9696de8bc9
diff --git a/api/db/indexSync.js b/api/db/indexSync.jsindex 13059033fb..9a24edc4de 100644--- a/api/db/indexSync.js+++ b/api/db/indexSync.js@@ -241,13 +241,23 @@ async function performSync(flowManager, flowId, flowType) {const messageCount = messageProgress.totalDocuments;const messagesIndexed = messageProgress.totalProcessed;const unindexedMessages = messageCount - messagesIndexed;+ const messagesPendingCleanup = messageProgress.pendingCleanup ?? 0;const noneIndexed = messagesIndexed === 0 && unindexedMessages > 0;- if (settingsUpdated || noneIndexed || unindexedMessages > syncThreshold) {+ if (+ settingsUpdated ||+ noneIndexed ||+ unindexedMessages > syncThreshold ||+ messagesPendingCleanup > 0+ ) {if (noneIndexed && !settingsUpdated) {logger.info('[indexSync] No messages marked as indexed, forcing full sync');}- logger.info(`[indexSync] Starting message sync (${unindexedMessages} unindexed)`);+ logger.info(+ messagesPendingCleanup > 0+ ? `[indexSync] Starting message sync (${unindexedMessages} unindexed, ${messagesPendingCleanup} pending cleanup)`+ : `[indexSync] Starting message sync (${unindexedMessages} unindexed)`,+ );await Message.syncWithMeili();messagesSync = true;} else if (unindexedMessages > 0) {@@ -271,13 +281,23 @@ async function performSync(flowManager, flowId, flowType) {const convoCount = convoProgress.totalDocuments;const convosIndexed = convoProgress.totalProcessed;const unindexedConvos = convoCount - convosIndexed;+ const convosPendingCleanup = convoProgress.pendingCleanup ?? 0;const noneConvosIndexed = convosIndexed === 0 && unindexedConvos > 0;- if (settingsUpdated || noneConvosIndexed || unindexedConvos > syncThreshold) {+ if (+ settingsUpdated ||+ noneConvosIndexed ||+ unindexedConvos > syncThreshold ||+ convosPendingCleanup > 0+ ) {if (noneConvosIndexed && !settingsUpdated) {logger.info('[indexSync] No conversations marked as indexed, forcing full sync');}- logger.info(`[indexSync] Starting convos sync (${unindexedConvos} unindexed)`);+ logger.info(+ convosPendingCleanup > 0+ ? `[indexSync] Starting convos sync (${unindexedConvos} unindexed, ${convosPendingCleanup} pending cleanup)`+ : `[indexSync] Starting convos sync (${unindexedConvos} unindexed)`,+ );await Conversation.syncWithMeili();convosSync = true;} else if (unindexedConvos > 0) {diff --git a/api/db/indexSync.spec.js b/api/db/indexSync.spec.jsindex dbe07c7595..9191714dce 100644--- a/api/db/indexSync.spec.js+++ b/api/db/indexSync.spec.js@@ -527,4 +527,28 @@ describe('performSync() - syncThreshold logic', () => {'[indexSync] 6 convos unindexed (below threshold: 1000, skipping)',);});++ test('forces sync when search contains documents that are now excluded', async () => {+ Message.getSyncProgress.mockResolvedValue({+ totalProcessed: 100,+ totalDocuments: 100,+ pendingCleanup: 1,+ isComplete: false,+ });+ Conversation.getSyncProgress.mockResolvedValue({+ totalProcessed: 50,+ totalDocuments: 50,+ pendingCleanup: 0,+ isComplete: true,+ });++ const indexSync = require('./indexSync');+ await indexSync();++ expect(Message.syncWithMeili).toHaveBeenCalledTimes(1);+ expect(Conversation.syncWithMeili).not.toHaveBeenCalled();+ expect(mockLogger.info).toHaveBeenCalledWith(+ '[indexSync] Starting message sync (0 unindexed, 1 pending cleanup)',+ );+ });});diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.tsindex b87de135c7..fc38719eba 100644--- a/packages/data-schemas/src/methods/conversation.spec.ts+++ b/packages/data-schemas/src/methods/conversation.spec.ts@@ -1392,6 +1392,52 @@ describe('Conversation Operations', () => {expect(result?.convoMap[expiredRetainedConvo.conversationId]).toBeUndefined();expect(result?.convoMap[tempConvo.conversationId]).toBeUndefined();});++ it('hides durable subagent threads from conversation lists and search results', async () => {+ const parentId = uuidv4();+ const childId = uuidv4();+ const messageId = 'message-1';+ const normalConversation = await Conversation.create({+ conversationId: parentId,+ user: 'user123',+ endpoint: EModelEndpoint.agents,+ title: 'Parent conversation',+ });+ await Conversation.create({+ conversationId: childId,+ user: 'user123',+ endpoint: EModelEndpoint.agents,+ title: 'Subagent: implementation',+ subagentThread: {+ rootConversationId: parentId,+ parentConversationId: parentId,+ parentMessageId: messageId,+ parentToolCallId: 'tool-1',+ subagentType: 'agent-child',+ subagentKind: 'agent',+ depth: 1,+ },+ });+ Object.assign(Conversation, {+ meiliSearch: jest.fn().mockResolvedValue({+ hits: [{ conversationId: parentId }, { conversationId: childId }],+ }),+ });++ const listed = await getConvosByCursor('user123', { search: 'implementation' });+ const queried = await getConvosQueried('user123', [+ { conversationId: parentId },+ { conversationId: childId },+ ]);++ expect(listed.conversations.map((convo) => convo.conversationId)).toEqual([+ normalConversation.conversationId,+ ]);+ expect(queried.conversations.map((convo) => convo.conversationId)).toEqual([+ normalConversation.conversationId,+ ]);+ expect(queried.convoMap[childId]).toBeUndefined();+ });});describe('searchConversation', () => {@@ -1832,21 +1878,43 @@ describe('Conversation Operations', () => {const first = uuidv4();const second = uuidv4();const otherUsers = uuidv4();+ const childThread = uuidv4();await Conversation.create([{ conversationId: first, user: 'user123', endpoint: EModelEndpoint.openAI },{ conversationId: second, user: 'user123', endpoint: EModelEndpoint.openAI },{ conversationId: otherUsers, user: 'user456', endpoint: EModelEndpoint.openAI },+ {+ conversationId: childThread,+ user: 'user123',+ endpoint: EModelEndpoint.agents,+ subagentThread: {+ rootConversationId: first,+ parentConversationId: first,+ parentMessageId: 'parent-message',+ parentToolCallId: 'parent-tool-call',+ subagentType: 'agent-child',+ subagentKind: 'agent',+ depth: 1,+ },+ },]);const result = await archiveAllConvos('user123');expect(result.archivedCount).toBe(2);- const archived = await Conversation.find({ user: 'user123' }).lean<IConversation[]>();+ const archived = await Conversation.find({+ user: 'user123',+ conversationId: { $in: [first, second] },+ }).lean<IConversation[]>();expect(archived.every((convo) => convo.isArchived === true)).toBe(true);const untouched = await Conversation.findOne({conversationId: otherUsers,}).lean<IConversation>();expect(untouched?.isArchived).not.toBe(true);+ const child = await Conversation.findOne({+ conversationId: childThread,+ }).lean<IConversation>();+ expect(child?.isArchived).not.toBe(true);});it('archives large snapshots in bounded batches', async () => {diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.tsindex 0703e5129c..c9c7e60318 100644--- a/packages/data-schemas/src/methods/conversation.ts+++ b/packages/data-schemas/src/methods/conversation.ts@@ -220,6 +220,11 @@ export function createConversationMethods(return buildRetentionVisibilityFilter<IConversation>();}+ /** Child threads are durable execution records, not user-navigable conversations. */+ function getHumanConversationFilter(): FilterQuery<IConversation> {+ return { subagentThread: { $exists: false } } as FilterQuery<IConversation>;+ }+/*** Searches for a conversation by conversationId and returns a lean document with only conversationId and user.*/@@ -1044,6 +1049,7 @@ export function createConversationMethods(}filters.push(getVisibleConversationRetentionFilter());+ filters.push(getHumanConversationFilter());if (search) {try {@@ -1233,10 +1239,12 @@ export function createConversationMethods(const conversationIds = convoIds.map((convo) => convo.conversationId);const results = await Conversation.find({- user,- conversationId: { $in: conversationIds },- ...getVisibleConversationRetentionFilter(),- }).lean<IConversation[]>();+ $and: [+ { user, conversationId: { $in: conversationIds } },+ getVisibleConversationRetentionFilter(),+ getHumanConversationFilter(),+ ],+ } as FilterQuery<IConversation>).lean<IConversation[]>();results.sort((a, b) => new Date(b.updatedAt ?? 0).getTime() - new Date(a.updatedAt ?? 0).getTime(),@@ -1445,6 +1453,7 @@ export function createConversationMethods($and: [{ $or: [{ isArchived: false }, { isArchived: { $exists: false } }] },getVisibleConversationRetentionFilter(),+ getHumanConversationFilter(),],} as FilterQuery<IConversation>;diff --git a/packages/data-schemas/src/models/convo.ts b/packages/data-schemas/src/models/convo.tsindex d636718373..31833934de 100644--- a/packages/data-schemas/src/models/convo.ts+++ b/packages/data-schemas/src/models/convo.ts@@ -16,6 +16,7 @@ export function createConversationModel(/** Note: Will get created automatically if it doesn't exist already */indexName: 'convos',primaryKey: 'conversationId',+ excludeFromIndexPath: 'subagentThread',});}return (diff --git a/packages/data-schemas/src/models/message.ts b/packages/data-schemas/src/models/message.tsindex 2dfcf66fe4..64a0f956c7 100644--- a/packages/data-schemas/src/models/message.ts+++ b/packages/data-schemas/src/models/message.ts@@ -13,6 +13,7 @@ export function createMessageModel(mongoose: typeof import('mongoose')): Model<tapiKey: process.env.MEILI_MASTER_KEY,indexName: 'messages',primaryKey: 'messageId',+ excludeFromIndexPath: 'subagentTask',});}diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts b/packages/data-schemas/src/models/plugins/mongoMeili.spec.tsindex 2556873728..70835a5c4a 100644--- a/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts+++ b/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts@@ -59,6 +59,8 @@ const mockUpdateDocuments = jest.fn();const mockDeleteDocument = jest.fn();const mockDeleteDocuments = jest.fn();const mockGetDocument = jest.fn();+const mockGetDocuments = jest.fn().mockResolvedValue({ results: [] });+const mockWaitForTask = jest.fn().mockResolvedValue({ status: 'succeeded' });const mockIndex = jest.fn().mockReturnValue({getRawInfo: jest.fn(),updateSettings: jest.fn(),@@ -68,13 +70,14 @@ const mockIndex = jest.fn().mockReturnValue({deleteDocument: mockDeleteDocument,deleteDocuments: mockDeleteDocuments,getDocument: mockGetDocument,- getDocuments: jest.fn().mockReturnValue({ results: [] }),+ getDocuments: mockGetDocuments,});jest.mock('meilisearch', () => {return {MeiliSearch: jest.fn().mockImplementation(() => {return {index: mockIndex,+ waitForTask: mockWaitForTask,};}),};@@ -103,8 +106,10 @@ describe('Meilisearch Mongoose plugin', () => {mockAddDocumentsInBatches.mockClear();mockUpdateDocuments.mockClear();mockDeleteDocument.mockClear();- mockDeleteDocuments.mockClear();+ mockDeleteDocuments.mockReset().mockResolvedValue({ taskUid: 1 });mockGetDocument.mockClear();+ mockGetDocuments.mockReset().mockResolvedValue({ results: [] });+ mockWaitForTask.mockReset().mockResolvedValue({ status: 'succeeded' });});afterAll(async () => {@@ -166,6 +171,121 @@ describe('Meilisearch Mongoose plugin', () => {expect(mockAddDocuments).toHaveBeenCalled();});+ test('saving a subagent thread does NOT index its conversation or messages', async () => {+ const conversationId = new mongoose.Types.ObjectId().toString();+ const user = new mongoose.Types.ObjectId().toString();++ await createConversationModel(mongoose).create({+ conversationId,+ user,+ title: 'Subagent thread',+ endpoint: EModelEndpoint.agents,+ subagentThread: {+ rootConversationId: 'root-conversation',+ parentConversationId: 'parent-conversation',+ parentMessageId: 'parent-message',+ parentToolCallId: 'parent-tool-call',+ subagentType: 'agent-child',+ subagentKind: 'agent',+ depth: 1,+ },+ });+ await createMessageModel(mongoose).create({+ messageId: new mongoose.Types.ObjectId().toString(),+ conversationId,+ user,+ isCreatedByUser: true,+ text: 'Private child transcript',+ subagentTask: {+ attemptKey: 'attempt-key',+ status: 'running',+ },+ });++ expect(mockAddDocuments).not.toHaveBeenCalled();+ });++ test('findOneAndUpdate loads the private child marker before deciding to index', async () => {+ const messageModel = createMessageModel(mongoose);+ const messageId = new mongoose.Types.ObjectId().toString();++ const savedMessage = await messageModel.findOneAndUpdate(+ { messageId, user: 'user-123' },+ {+ messageId,+ conversationId: new mongoose.Types.ObjectId().toString(),+ user: 'user-123',+ isCreatedByUser: true,+ text: 'Private child transcript',+ subagentTask: {+ attemptKey: 'attempt-key',+ status: 'running',+ },+ },+ { upsert: true, new: true },+ );++ expect(mockAddDocuments).not.toHaveBeenCalled();+ expect(savedMessage?.subagentTask).toBeUndefined();+ });++ test('findOneAndUpdate hides its injected private marker from lean results', async () => {+ const messageModel = createMessageModel(mongoose);+ const messageId = new mongoose.Types.ObjectId().toString();++ const savedMessage = await messageModel+ .findOneAndUpdate(+ { messageId, user: 'user-lean' },+ {+ messageId,+ conversationId: new mongoose.Types.ObjectId().toString(),+ user: 'user-lean',+ isCreatedByUser: true,+ text: 'Private child transcript',+ subagentTask: {+ attemptKey: 'attempt-key',+ status: 'running',+ },+ },+ { upsert: true, new: true, projection: { unfinished: 1 } },+ )+ .lean();++ expect(savedMessage).not.toBeNull();+ expect(savedMessage?.subagentTask).toBeUndefined();+ expect(mockAddDocuments).not.toHaveBeenCalled();+ });++ test('findOneAndUpdate preserves a private marker explicitly projected by a lean caller', async () => {+ const messageModel = createMessageModel(mongoose);+ const messageId = new mongoose.Types.ObjectId().toString();+ await messageModel.collection.insertOne({+ messageId,+ conversationId: new mongoose.Types.ObjectId().toString(),+ user: 'user-explicit',+ isCreatedByUser: true,+ text: 'Completed child result',+ subagentTask: {+ attemptKey: 'attempt-key',+ status: 'completed',+ },+ });++ const savedMessage = await messageModel+ .findOneAndUpdate(+ { messageId, user: 'user-explicit' },+ { $set: { 'subagentTask.resultClaim': { kind: 'manual', claimId: 'claim-1' } } },+ { new: true, projection: { messageId: 1, subagentTask: 1 } },+ )+ .lean();++ expect(savedMessage?.subagentTask).toMatchObject({+ status: 'completed',+ resultClaim: { kind: 'manual', claimId: 'claim-1' },+ });+ expect(mockAddDocuments).not.toHaveBeenCalled();+ });+test('saving expired retained non-temporary conversation does NOT index w/ meilisearch', async () => {await createConversationModel(mongoose).create({conversationId: new mongoose.Types.ObjectId(),@@ -379,6 +499,123 @@ describe('Meilisearch Mongoose plugin', () => {expect(storedDoc?._meiliIndex).toBe(false);});+ test('sync removes an existing child conversation from Meili and clears its index flag', async () => {+ const conversationModel = createConversationModel(+ mongoose,+ ) as unknown as SchemaWithMeiliMethods;+ await conversationModel.deleteMany({});+ const conversationId = new mongoose.Types.ObjectId().toString();++ await conversationModel.collection.insertOne({+ conversationId,+ user: new mongoose.Types.ObjectId().toString(),+ title: 'Indexed child conversation',+ endpoint: EModelEndpoint.agents,+ subagentThread: {+ rootConversationId: 'root-conversation',+ parentConversationId: 'parent-conversation',+ parentMessageId: 'parent-message',+ parentToolCallId: 'parent-tool-call',+ subagentType: 'agent-child',+ subagentKind: 'agent',+ depth: 1,+ },+ _meiliIndex: true,+ createdAt: new Date(),+ updatedAt: new Date(),+ });+ mockGetDocuments.mockResolvedValueOnce({ results: [{ conversationId }] });++ const progress = await conversationModel.getSyncProgress();+ await conversationModel.syncWithMeili();+ const storedDoc = await conversationModel.collection.findOne({ conversationId });++ expect(progress).toMatchObject({ pendingCleanup: 1, isComplete: false });+ expect(mockDeleteDocuments).toHaveBeenCalledWith([conversationId]);+ expect(mockWaitForTask).toHaveBeenCalledWith(1, {+ timeOutMs: 10000,+ intervalMs: 100,+ });+ expect(storedDoc?._meiliIndex).toBeUndefined();+ });++ test('keeps cleanup pending when Meili fails the asynchronous deletion task', async () => {+ const conversationModel = createConversationModel(+ mongoose,+ ) as unknown as SchemaWithMeiliMethods;+ await conversationModel.deleteMany({});+ const conversationId = new mongoose.Types.ObjectId().toString();++ await conversationModel.collection.insertOne({+ conversationId,+ user: new mongoose.Types.ObjectId().toString(),+ title: 'Indexed child conversation',+ endpoint: EModelEndpoint.agents,+ subagentThread: {+ rootConversationId: 'root-conversation',+ parentConversationId: 'parent-conversation',+ parentMessageId: 'parent-message',+ parentToolCallId: 'parent-tool-call',+ subagentType: 'agent-child',+ subagentKind: 'agent',+ depth: 1,+ },+ _meiliIndex: true,+ createdAt: new Date(),+ updatedAt: new Date(),+ });+ mockGetDocuments.mockResolvedValueOnce({ results: [{ conversationId }] });+ mockWaitForTask.mockResolvedValueOnce({ status: 'failed' });++ await conversationModel.syncWithMeili();+ const storedDoc = await conversationModel.collection.findOne({ conversationId });++ expect(mockDeleteDocuments).toHaveBeenCalledWith([conversationId]);+ expect(storedDoc?._meiliIndex).toBe(true);+ });++ test('retries cleanup when Meili deletion succeeds before the Mongo flag update fails', async () => {+ const conversationModel = createConversationModel(+ mongoose,+ ) as unknown as SchemaWithMeiliMethods;+ await conversationModel.deleteMany({});+ const conversationId = new mongoose.Types.ObjectId().toString();++ await conversationModel.collection.insertOne({+ conversationId,+ user: new mongoose.Types.ObjectId().toString(),+ title: 'Indexed child conversation',+ endpoint: EModelEndpoint.agents,+ subagentThread: {+ rootConversationId: 'root-conversation',+ parentConversationId: 'parent-conversation',+ parentMessageId: 'parent-message',+ parentToolCallId: 'parent-tool-call',+ subagentType: 'agent-child',+ subagentKind: 'agent',+ depth: 1,+ },+ _meiliIndex: true,+ createdAt: new Date(),+ updatedAt: new Date(),+ });+ jest+ .spyOn(conversationModel, 'updateMany')+ .mockRejectedValueOnce(new Error('Mongo acknowledgment failed'));++ await conversationModel.syncWithMeili();+ expect((await conversationModel.collection.findOne({ conversationId }))?._meiliIndex).toBe(+ true,+ );++ mockGetDocuments.mockResolvedValue({ results: [] });+ await conversationModel.syncWithMeili();+ expect(mockDeleteDocuments).toHaveBeenCalledTimes(2);+ expect(+ (await conversationModel.collection.findOne({ conversationId }))?._meiliIndex,+ ).toBeUndefined();+ });+test('saving hydrated legacy temporary conversations without isTemporary does NOT index', async () => {const conversationModel = createConversationModel(mongoose,@@ -468,6 +705,62 @@ describe('Meilisearch Mongoose plugin', () => {expect(storedDoc?._meiliIndex).toBe(false);});+ test('sync removes an existing child message even when its index flag is false', async () => {+ const messageModel = createMessageModel(mongoose) as unknown as SchemaWithMeiliMethods;+ await messageModel.deleteMany({});+ const messageId = new mongoose.Types.ObjectId().toString();++ await messageModel.collection.insertOne({+ messageId,+ conversationId: new mongoose.Types.ObjectId().toString(),+ user: new mongoose.Types.ObjectId().toString(),+ isCreatedByUser: true,+ text: 'Indexed child transcript',+ subagentTask: {+ attemptKey: 'attempt-key',+ status: 'completed',+ },+ _meiliIndex: false,+ createdAt: new Date(),+ updatedAt: new Date(),+ });+ mockGetDocuments.mockResolvedValueOnce({ results: [{ messageId }] });++ const progress = await messageModel.getSyncProgress();+ await messageModel.syncWithMeili();+ const storedDoc = await messageModel.collection.findOne({ messageId });++ expect(progress).toMatchObject({ pendingCleanup: 1, isComplete: false });+ expect(mockDeleteDocuments).toHaveBeenCalledWith([messageId]);+ expect(storedDoc?._meiliIndex).toBeUndefined();+ });++ test('defines partial indexes for pending excluded-document cleanup', () => {+ const conversationIndexes = createConversationModel(mongoose).schema.indexes();+ const messageIndexes = createMessageModel(mongoose).schema.indexes();++ expect(conversationIndexes).toContainEqual([+ { _meiliIndex: 1, conversationId: 1 },+ expect.objectContaining({+ name: 'meili_excluded_cleanup',+ partialFilterExpression: {+ subagentThread: { $exists: true },+ _meiliIndex: { $exists: true },+ },+ }),+ ]);+ expect(messageIndexes).toContainEqual([+ { _meiliIndex: 1, messageId: 1 },+ expect.objectContaining({+ name: 'meili_excluded_cleanup',+ partialFilterExpression: {+ subagentTask: { $exists: true },+ _meiliIndex: { $exists: true },+ },+ }),+ ]);+ });+test('sync w/ meili treats null isTemporary with no expiration like missing legacy fields', async () => {const modelName = `DynamicMeiliNullTemporary${new mongoose.Types.ObjectId().toString()}`;const dynamicModel = createDynamicMeiliModel(modelName);diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.ts b/packages/data-schemas/src/models/plugins/mongoMeili.tsindex 5c5bea44c5..06467a5ae2 100644--- a/packages/data-schemas/src/models/plugins/mongoMeili.ts+++ b/packages/data-schemas/src/models/plugins/mongoMeili.ts@@ -23,6 +23,8 @@ interface MongoMeiliOptions {mongoose: typeof import('mongoose');syncBatchSize?: number;syncDelayMs?: number;+ /** Documents carrying this path remain in MongoDB but are excluded from search. */+ excludeFromIndexPath?: string;}interface MeiliIndexable {@@ -34,6 +36,7 @@ interface SyncProgress {lastSyncedId?: string;totalProcessed: number;totalDocuments: number;+ pendingCleanup: number;isComplete: boolean;}@@ -98,14 +101,45 @@ const hasSchemaPath = (schema: Schema, path: string): boolean =>const explicitTemporaryFlagKey = 'meiliExplicitTemporaryFlag';-const buildIndexableQuery = (schema: Schema): FilterQuery<unknown> => {- if (!hasSchemaPath(schema, 'isTemporary')) {- return hasSchemaPath(schema, 'expiredAt') ? legacyPermanentExpirationFilter() : {};+const buildRetentionIndexableQuery = (schema: Schema): FilterQuery<unknown> => {+ if (hasSchemaPath(schema, 'isTemporary')) {+ return buildRetentionVisibilityFilter();}+ if (hasSchemaPath(schema, 'expiredAt')) {+ return legacyPermanentExpirationFilter();+ }+ return {};+};- return buildRetentionVisibilityFilter();+const buildIndexableQuery = (+ schema: Schema,+ excludeFromIndexPath?: string,+): FilterQuery<unknown> => {+ const retentionFilter = buildRetentionIndexableQuery(schema);++ if (excludeFromIndexPath == null) {+ return retentionFilter;+ }++ return {+ $and: [retentionFilter, { [excludeFromIndexPath]: { $exists: false } }],+ };};+const buildExcludedIndexedQuery = (excludeFromIndexPath?: string): FilterQuery<unknown> | null => {+ if (excludeFromIndexPath == null) {+ return null;+ }++ return {+ [excludeFromIndexPath]: { $exists: true },+ _meiliIndex: { $exists: true },+ };+};++const isExcludedFromIndex = (doc: DocumentWithMeiliIndex, excludeFromIndexPath?: string): boolean =>+ excludeFromIndexPath != null && !_.isNil(_.get(doc, excludeFromIndexPath));+const hasActiveExpiration = (expiredAt?: Date | null): boolean =>_.isNil(expiredAt) || new Date(expiredAt).getTime() > Date.now();@@ -130,11 +164,12 @@ const captureExplicitTemporaryFlag = (doc: DocumentWithMeiliIndex): void => {* plus legacy permanent records that have no retention deadline. Legacy records* with an expiration are treated as temporary and stay out of search.*/-const isIndexableDocument = (doc: DocumentWithMeiliIndex): boolean =>- (doc.isTemporary === false &&+const isIndexableDocument = (doc: DocumentWithMeiliIndex, excludeFromIndexPath?: string): boolean =>+ !isExcludedFromIndex(doc, excludeFromIndexPath) &&+ ((doc.isTemporary === false &&hasExplicitTemporaryFlag(doc) &&hasActiveExpiration(doc.expiredAt)) ||- (!hasExplicitTemporaryFlag(doc) && _.isNil(doc.expiredAt));+ (!hasExplicitTemporaryFlag(doc) && _.isNil(doc.expiredAt)));/*** Validates the required options for configuring the mongoMeili plugin.@@ -181,14 +216,20 @@ const processBatch = async <T>(* @returns A class definition that will be loaded into the Mongoose schema.*/const createMeiliMongooseModel = ({+ client,index,getIndexableQuery,+ getExcludedIndexedQuery,+ excludeFromIndexPath,attributesToIndex,primaryKey,syncOptions,}: {+ client: MeiliSearch;index: Index<MeiliIndexable>;getIndexableQuery: () => FilterQuery<unknown>;+ getExcludedIndexedQuery: () => FilterQuery<unknown> | null;+ excludeFromIndexPath?: string;attributesToIndex: string[];primaryKey: string;syncOptions: { batchSize: number; delayMs: number };@@ -201,16 +242,23 @@ const createMeiliMongooseModel = ({*/static async getSyncProgress(this: SchemaWithMeiliMethods): Promise<SyncProgress> {const indexableQuery = getIndexableQuery();- const totalDocuments = await this.countDocuments(indexableQuery);- const indexedDocuments = await this.countDocuments({- ...indexableQuery,- _meiliIndex: true,- });+ const excludedIndexedQuery = getExcludedIndexedQuery();+ const [totalDocuments, indexedDocuments, pendingCleanup] = await Promise.all([+ this.countDocuments(indexableQuery),+ this.countDocuments({+ ...indexableQuery,+ _meiliIndex: true,+ }),+ excludedIndexedQuery == null+ ? Promise.resolve(0)+ : this.countDocuments(excludedIndexedQuery),+ ]);return {totalProcessed: indexedDocuments,totalDocuments,- isComplete: indexedDocuments === totalDocuments,+ pendingCleanup,+ isComplete: indexedDocuments === totalDocuments && pendingCleanup === 0,};}@@ -337,6 +385,47 @@ const createMeiliMongooseModel = ({delayMs: number,): Promise<void> {try {+ const excludedIndexedQuery = getExcludedIndexedQuery();+ if (excludedIndexedQuery != null) {+ let hasPendingExcludedDocuments = true;+ while (hasPendingExcludedDocuments) {+ const pendingExcludedDocuments = await this.find(excludedIndexedQuery)+ .select(primaryKey)+ .limit(batchSize)+ .lean();+ if (pendingExcludedDocuments.length === 0) {+ hasPendingExcludedDocuments = false;+ break;+ }++ const pendingIds = pendingExcludedDocuments.map(+ (doc: Record<string, unknown>) => doc[primaryKey],+ );+ const deletion = await index.deleteDocuments(pendingIds.map(String));+ const deletionTask = await client.waitForTask(deletion.taskUid, {+ timeOutMs: 10000,+ intervalMs: 100,+ });+ if (deletionTask.status !== 'succeeded') {+ throw new Error(+ `Meili cleanup task ${deletion.taskUid} ended with ${deletionTask.status}`,+ );+ }+ await this.updateMany(+ { ...excludedIndexedQuery, [primaryKey]: { $in: pendingIds } },+ { $unset: { _meiliIndex: '' } },+ { timestamps: false },+ );++ if (pendingExcludedDocuments.length < batchSize) {+ break;+ }+ if (delayMs > 0) {+ await new Promise((resolve) => setTimeout(resolve, delayMs));+ }+ }+ }+let offset = 0;let moreDocuments = true;@@ -362,7 +451,21 @@ const createMeiliMongooseModel = ({// Delete documents that don't exist in MongoDBconst toDelete = meiliIds.filter((id) => !existingIds.has(id));if (toDelete.length > 0) {- await index.deleteDocuments(toDelete.map(String));+ const deletion = await index.deleteDocuments(toDelete.map(String));+ const deletionTask = await client.waitForTask(deletion.taskUid, {+ timeOutMs: 10000,+ intervalMs: 100,+ });+ if (deletionTask.status !== 'succeeded') {+ throw new Error(+ `Meili cleanup task ${deletion.taskUid} ended with ${deletionTask.status}`,+ );+ }+ await this.updateMany(+ { [primaryKey]: { $in: toDelete } },+ { $unset: { _meiliIndex: '' } },+ { timestamps: false },+ );logger.debug(`[cleanupMeiliIndex] Deleted ${toDelete.length} orphaned documents`);}// if fetch documents request returns less documents than limit, all documents are processed@@ -467,7 +570,7 @@ const createMeiliMongooseModel = ({this: DocumentWithMeiliIndex,next: CallbackWithoutResultAndOptionalError,): Promise<void> {- if (!isIndexableDocument(this)) {+ if (!isIndexableDocument(this, excludeFromIndexPath)) {return next();}@@ -512,7 +615,7 @@ const createMeiliMongooseModel = ({next: CallbackWithoutResultAndOptionalError,): Promise<void> {try {- if (!isIndexableDocument(this)) {+ if (!isIndexableDocument(this, excludeFromIndexPath)) {await index.deleteDocument(String(this[primaryKey as keyof DocumentWithMeiliIndex]));const model = this.constructor as Model<DocumentWithMeiliIndex>;await model.updateOne(@@ -619,6 +722,7 @@ const createMeiliMongooseModel = ({* @param options.primaryKey - The primary key field for indexing.* @param options.syncBatchSize - Batch size for sync operations.* @param options.syncDelayMs - Delay between batches in milliseconds.+ * @param options.excludeFromIndexPath - Presence of this path makes a document non-searchable.*/export default function mongoMeili(schema: Schema, options: MongoMeiliOptions): void {const mongoose = options.mongoose;@@ -634,7 +738,26 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):},});+ if (options.excludeFromIndexPath != null) {+ schema.index(+ { _meiliIndex: 1, [options.primaryKey]: 1 },+ {+ name: 'meili_excluded_cleanup',+ partialFilterExpression: {+ [options.excludeFromIndexPath]: { $exists: true },+ _meiliIndex: { $exists: true },+ },+ },+ );+ }+const { host, apiKey, indexName, primaryKey } = options;+ const privateExcludedPath =+ options.excludeFromIndexPath != null &&+ schema.path(options.excludeFromIndexPath)?.options?.select === false+ ? options.excludeFromIndexPath+ : undefined;+ const queriesWithInjectedPrivatePath = new WeakSet<object>();const syncOptions = {batchSize: options.syncBatchSize || getSyncConfig().batchSize,delayMs: options.syncDelayMs || getSyncConfig().delayMs,@@ -709,8 +832,11 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):schema.loadClass(createMeiliMongooseModel({+ client,index,- getIndexableQuery: () => buildIndexableQuery(schema),+ getIndexableQuery: () => buildIndexableQuery(schema, options.excludeFromIndexPath),+ getExcludedIndexedQuery: () => buildExcludedIndexedQuery(options.excludeFromIndexPath),+ excludeFromIndexPath: options.excludeFromIndexPath,attributesToIndex,primaryKey,syncOptions,@@ -729,6 +855,25 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):doc.postSaveHook?.(next);});+ schema.pre('findOneAndUpdate', function (next) {+ if (privateExcludedPath != null) {+ const query = this as Query<unknown, unknown>;+ const projection = query.projection() as Record<string, number> | null;+ const callerRequestedPrivatePath = Object.entries(projection ?? {}).some(+ ([path, included]) =>+ included === 1 &&+ (path === privateExcludedPath ||+ path === `+${privateExcludedPath}` ||+ path.startsWith(`${privateExcludedPath}.`)),+ );+ if (!callerRequestedPrivatePath) {+ query.select(`+${privateExcludedPath}`);+ queriesWithInjectedPrivatePath.add(query);+ }+ }+ next();+ });+schema.post('updateOne', function (doc: DocumentWithMeiliIndex, next) {if (typeof doc.postUpdateHook === 'function') {return doc.postUpdateHook(next);@@ -805,17 +950,40 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):res: DocumentWithMeiliIndex | { value: DocumentWithMeiliIndex | null } | null,next: CallbackWithoutResultAndOptionalError,) {- if (!meiliEnabled) {- return next();- }-// `saveConvo` issues `findOneAndUpdate` with `includeResultMetadata: true`, so// the hook receives the raw `{ value, ok, lastErrorObject }` result instead of// the document. Unwrap `value` so indexing runs for that path too.- const doc = res instanceof mongoose.Document ? res : (res?.value ?? null);+ let doc: DocumentWithMeiliIndex | null;+ if (res instanceof mongoose.Document) {+ doc = res;+ } else if (res != null && 'value' in res) {+ doc = res.value;+ } else {+ doc = res;+ }+ const finish = (error?: Error | null): void => {+ if (+ doc != null &&+ privateExcludedPath != null &&+ queriesWithInjectedPrivatePath.has(this)+ ) {+ if (doc instanceof mongoose.Document) {+ doc.set(privateExcludedPath, undefined);+ } else {+ _.unset(doc, privateExcludedPath);+ }+ }+ next(error ?? undefined);+ };++ if (!meiliEnabled) {+ finish();+ return;+ }if (!doc || doc.unfinished) {- return next();+ finish();+ return;}let meiliDoc: Record<string, unknown> | undefined;@@ -832,14 +1000,16 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):}if (meiliDoc && meiliDoc.title === doc.title) {- return next();+ finish();+ return;}if (typeof doc.postSaveHook === 'function') {- return doc.postSaveHook(next);+ await doc.postSaveHook(finish);+ return;}- return next();+ finish();},);}