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: Unblock Detached Subagent Preparation (#15016)
Danny Avila986b1218ac00
diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.tsindex e513f12e2a..e9390160cb 100644--- a/packages/api/src/agents/subagentThreads.spec.ts+++ b/packages/api/src/agents/subagentThreads.spec.ts@@ -877,6 +877,10 @@ describe('SubagentThreadTaskStore', () => {await waitForSettled(firstWorker, config.scopeId, initial);slowThreadId = requireThreadId(initial);blockNextRead = true;+ const intervalSpy = jest.spyOn(global, 'setInterval');+ const timeoutSpy = jest.spyOn(global, 'setTimeout');+ const clearIntervalSpy = jest.spyOn(global, 'clearInterval');+ const clearTimeoutSpy = jest.spyOn(global, 'clearTimeout');const firstRun = jest.fn(taskRequest(config.scopeId).run);const first = firstWorker.start(@@ -887,6 +891,15 @@ describe('SubagentThreadTaskStore', () => {}),);await preparing;+ const heartbeatCall = intervalSpy.mock.calls.find(([, delay]) => delay === 50);+ const heartbeatIndex =+ heartbeatCall == null ? -1 : intervalSpy.mock.calls.indexOf(heartbeatCall);+ const heartbeat = intervalSpy.mock.results[heartbeatIndex]?.value as NodeJS.Timeout | undefined;+ const warningIndex = timeoutSpy.mock.calls.length - 1;+ expect(timeoutSpy.mock.calls[warningIndex]?.[1]).toBe(5_000);+ const warning = timeoutSpy.mock.results[warningIndex]?.value as NodeJS.Timeout | undefined;+ expect(heartbeat?.hasRef()).toBe(true);+ expect(warning?.hasRef()).toBe(true);/** Wait for evidence rather than a fixed delay: a renewal that succeeds after the* acquired lease's own deadline proves the heartbeat carried it past expiry. */await waitUntil(() => renewedPastDeadline, 'the shared lease to outlive its original deadline');@@ -905,6 +918,12 @@ describe('SubagentThreadTaskStore', () => {releasePreparation();await waitForSettled(firstWorker, config.scopeId, first);expect(firstRun).toHaveBeenCalledTimes(1);+ expect(clearIntervalSpy).toHaveBeenCalledWith(heartbeat);+ expect(clearTimeoutSpy).toHaveBeenCalledWith(warning);+ intervalSpy.mockRestore();+ timeoutSpy.mockRestore();+ clearIntervalSpy.mockRestore();+ clearTimeoutSpy.mockRestore();});it('cancels a child when its lease renewal only commits after expiry', async () => {diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.tsindex eb3f21fcac..b2b7199b71 100644--- a/packages/api/src/agents/subagentThreads.ts+++ b/packages/api/src/agents/subagentThreads.ts@@ -388,7 +388,6 @@ async function observeSlowPreparation<T>(const warning = setTimeout(() => {logger.warn('[subagentThreads] Child-thread preparation is still waiting', context);}, SLOW_PREPARATION_WARN_MS);- warning.unref?.();try {return await operation;} finally {@@ -631,10 +630,11 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {}throw error;}- logger.error(- '[subagentThreads] Child-thread execution failed',- publicFailureDetail(error),- );+ logger.error('[subagentThreads] Child-thread execution failed', {+ detail: publicFailureDetail(error),+ errorName: error instanceof Error ? error.name : typeof error,+ ...(error instanceof Error && error.stack != null ? { stack: error.stack } : {}),+ });if (mayPersist) {await this.persistFailure(scope,@@ -1408,7 +1408,6 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {shared.heartbeatInFlight = renewal;};shared.heartbeat = setInterval(heartbeat, this.leaseHeartbeatMs);- shared.heartbeat.unref?.();}private async renewSharedLease(@@ -1593,10 +1592,18 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {lost: false,expiresAt: now.getTime() + this.leaseTtlMs,};+ /** A detached child has no request or stream handle after its parent returns.+ * Keep the lease heartbeat referenced until settlement so Node cannot retire+ * the execution context while its provider promise is still pending. */this.startSharedLeaseHeartbeat(scopeId, scope, threadId, lease);/** Account deletion can fence the owner after the optimistic probe but before* this lease exists. Once the lease is visible, revalidate so deletion either* observes and drains us or wins before any provider work can begin. */+ logger.debug('[subagentThreads] Child-thread preparation entered stage', {+ stage: 'owner_recheck',+ taskId,+ threadId,+ });if (!(await observeSlowPreparation(this.isOwnerActive(scope.userId), {stage: 'owner_recheck',@@ -1606,6 +1613,11 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {) {throw new SubagentThreadDeletedError('The thread owner is unavailable.');}+ logger.debug('[subagentThreads] Child-thread preparation entered stage', {+ stage: 'transcript_read',+ taskId,+ threadId,+ });const allMessages = (await observeSlowPreparation(this.methods.getMessages({ conversationId: threadId, user: scope.userId },@@ -1725,6 +1737,11 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {break;}}+ logger.debug('[subagentThreads] Child-thread preparation entered stage', {+ stage: 'seed_write',+ taskId,+ threadId,+ });const savedUserMessage = await observeSlowPreparation(this.methods.saveMessage({ userId: scope.userId },diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts b/packages/data-schemas/src/models/plugins/mongoMeili.spec.tsindex 421c15c14d..2556873728 100644--- a/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts+++ b/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts@@ -114,6 +114,22 @@ describe('Meilisearch Mongoose plugin', () => {process.env = OLD_ENV;});+ test('settles query updates and deletes when no document hook is available', async () => {+ const modelName = `QueryMiddlewareResult${Date.now()}`;+ const Model = createDynamicMeiliModel(modelName);+ try {+ await Model.create({ docId: 'query-result', user: 'user', title: 'Before' });+ await expect(+ Model.updateOne({ docId: 'query-result' }, { $set: { title: 'After' } }),+ ).resolves.toMatchObject({ matchedCount: 1, modifiedCount: 1 });+ await expect(Model.deleteOne({ docId: 'query-result' })).resolves.toMatchObject({+ deletedCount: 1,+ });+ } finally {+ mongoose.deleteModel(modelName);+ }+ });+test('saving conversation indexes w/ meilisearch', async () => {await createConversationModel(mongoose).create({conversationId: new mongoose.Types.ObjectId(),diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.ts b/packages/data-schemas/src/models/plugins/mongoMeili.tsindex 405d32268f..5c5bea44c5 100644--- a/packages/data-schemas/src/models/plugins/mongoMeili.ts+++ b/packages/data-schemas/src/models/plugins/mongoMeili.ts@@ -730,11 +730,17 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):});schema.post('updateOne', function (doc: DocumentWithMeiliIndex, next) {- doc.postUpdateHook?.(next);+ if (typeof doc.postUpdateHook === 'function') {+ return doc.postUpdateHook(next);+ }+ return next();});schema.post('deleteOne', function (doc: DocumentWithMeiliIndex, next) {- doc.postRemoveHook?.(next);+ if (typeof doc.postRemoveHook === 'function') {+ return doc.postRemoveHook(next);+ }+ return next();});// Pre-deleteMany hook: remove corresponding documents from MeiliSearch when multiple documents are deleted.