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: Make Ledger, Plugin, Memory and Preset Writes Atomic (#17463)
Marco Beretta6723f96733c2
diff --git a/e2e/specs/mock/scenarios/atomic-writes.spec.ts b/e2e/specs/mock/scenarios/atomic-writes.spec.tsnew file mode 100644index 0000000000..ccb11e3e7f--- /dev/null+++ b/e2e/specs/mock/scenarios/atomic-writes.spec.ts@@ -0,0 +1,221 @@+import { randomUUID } from 'crypto';+import { expect, test } from '@playwright/test';+import type { APIRequestContext } from '@playwright/test';+import { withMongo } from '../db';++const PASSWORD = 'Atomic-Writes-1!';++type Session = { headers: Record<string, string>; userId: string };++async function signUp(request: APIRequestContext): Promise<Session> {+ const email = `atomic-${randomUUID().slice(0, 8)}@example.com`;+ const register = await request.post('/api/auth/register', {+ data: { email, name: 'Atomic Writes', password: PASSWORD, confirm_password: PASSWORD },+ });+ expect(register.ok()).toBeTruthy();+ const login = await request.post('/api/auth/login', { data: { email, password: PASSWORD } });+ expect(login.ok()).toBeTruthy();+ const { token, user } = (await login.json()) as {+ token: string;+ user: { id?: string; _id?: string };+ };+ const userId = user.id ?? user._id;+ expect(userId).toBeTruthy();+ return { headers: { Authorization: `Bearer ${token}` }, userId: String(userId) };+}++async function getPlugins(request: APIRequestContext, session: Session): Promise<string[]> {+ const response = await request.get('/api/user', { headers: session.headers });+ expect(response.ok()).toBeTruthy();+ const { plugins } = (await response.json()) as { plugins?: string[] };+ return plugins ?? [];+}++test.describe('atomic user-owned writes', () => {+ test('concurrent tool installs all persist and an uninstall removes only its tool @scenario:plugin-installs-concurrent-persist', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ try {+ const session = await signUp(request);+ const keys = ['calculator', 'web_search', 'dalle', 'wolfram', 'google'];++ const installs = await Promise.all(+ keys.map((pluginKey) =>+ request.post('/api/user/plugins', {+ headers: session.headers,+ data: { pluginKey, action: 'install' },+ }),+ ),+ );+ installs.forEach((response) => expect(response.status()).toBe(200));+ expect((await getPlugins(request, session)).sort()).toEqual([...keys].sort());++ const reinstall = await request.post('/api/user/plugins', {+ headers: session.headers,+ data: { pluginKey: 'calculator', action: 'install' },+ });+ expect(reinstall.status()).toBe(200);+ expect(+ (await getPlugins(request, session)).filter((key) => key === 'calculator'),+ ).toHaveLength(1);++ const uninstall = await request.post('/api/user/plugins', {+ headers: session.headers,+ data: { pluginKey: 'dalle', action: 'uninstall' },+ });+ expect(uninstall.status()).toBe(200);+ expect((await getPlugins(request, session)).sort()).toEqual(+ keys.filter((key) => key !== 'dalle').sort(),+ );+ } finally {+ await request.dispose();+ }+ });++ test('saving a tool credential again replaces it instead of adding a second record @scenario:plugin-credential-resave-single-record', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ try {+ const session = await signUp(request);+ const pluginKey = 'wolfram';+ const authField = 'WOLFRAM_APP_ID';++ const readRecords = () =>+ withMongo((db) =>+ db+ .collection('pluginauths')+ .find({ userId: session.userId, pluginKey, authField })+ .toArray(),+ );++ const first = await request.post('/api/user/plugins', {+ headers: session.headers,+ data: { pluginKey, action: 'install', auth: { [authField]: 'first-app-id' } },+ });+ expect(first.status()).toBe(200);+ const created = await readRecords();+ expect(created).toHaveLength(1);+ expect(created[0].createdAt).toBeTruthy();++ const second = await request.post('/api/user/plugins', {+ headers: session.headers,+ data: { pluginKey, action: 'install', auth: { [authField]: 'second-app-id' } },+ });+ expect(second.status()).toBe(200);+ const replaced = await readRecords();+ expect(replaced).toHaveLength(1);+ expect(String(replaced[0]._id)).toBe(String(created[0]._id));+ expect(replaced[0].value).not.toBe(created[0].value);+ } finally {+ await request.dispose();+ }+ });++ test('creating a memory with a key that already exists is refused and keeps the original @scenario:memory-duplicate-key-conflict', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ try {+ const session = await signUp(request);++ const created = await request.post('/api/memories', {+ headers: session.headers,+ data: { key: 'favorite_color', value: 'blue' },+ });+ expect(created.status()).toBe(201);+ const { memory } = (await created.json()) as { memory: { key: string; value: string } };+ expect(memory).toMatchObject({ key: 'favorite_color', value: 'blue' });++ const duplicate = await request.post('/api/memories', {+ headers: session.headers,+ data: { key: 'favorite_color', value: 'red' },+ });+ expect(duplicate.status()).toBe(409);+ expect(await duplicate.json()).toEqual({ error: 'Memory with this key already exists.' });++ const list = await request.get('/api/memories', { headers: session.headers });+ expect(list.ok()).toBeTruthy();+ const { memories } = (await list.json()) as {+ memories: Array<{ key: string; value: string }>;+ };+ const matching = memories.filter((entry) => entry.key === 'favorite_color');+ expect(matching).toHaveLength(1);+ expect(matching[0].value).toBe('blue');+ } finally {+ await request.dispose();+ }+ });++ test('turning memories off and on is reflected in the user profile @scenario:memory-preferences-toggle', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ try {+ const session = await signUp(request);++ for (const enabled of [false, true]) {+ const response = await request.patch('/api/memories/preferences', {+ headers: session.headers,+ data: { memories: enabled },+ });+ expect(response.status()).toBe(200);+ expect(await response.json()).toEqual({+ updated: true,+ preferences: { memories: enabled },+ });+ const user = await request.get('/api/user', { headers: session.headers });+ const { personalization } = (await user.json()) as {+ personalization?: { memories?: boolean };+ };+ expect(personalization?.memories).toBe(enabled);+ }+ } finally {+ await request.dispose();+ }+ });++ test('marking a preset as default leaves it the only default @scenario:preset-default-single', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ try {+ const session = await signUp(request);+ const savePreset = async (presetId: string, title: string) => {+ const response = await request.post('/api/presets', {+ headers: session.headers,+ data: { presetId, title, endpoint: 'openAI', model: 'gpt-4o', defaultPreset: true },+ });+ expect(response.status()).toBe(201);+ };+ const defaults = async () => {+ const response = await request.get('/api/presets', { headers: session.headers });+ expect(response.ok()).toBeTruthy();+ const presets = (await response.json()) as Array<{+ presetId: string;+ defaultPreset?: boolean;+ }>;+ return presets.filter((preset) => preset.defaultPreset).map((preset) => preset.presetId);+ };++ const first = randomUUID();+ const second = randomUUID();+ await savePreset(first, 'First default');+ expect(await defaults()).toEqual([first]);++ await savePreset(second, 'Second default');+ expect(await defaults()).toEqual([second]);++ await savePreset(second, 'Second default renamed');+ expect(await defaults()).toEqual([second]);+ } finally {+ await request.dispose();+ }+ });+});diff --git a/packages/api/src/agents/transactions.spec.ts b/packages/api/src/agents/transactions.spec.tsindex 99fb7cdd85..8027660a45 100644--- a/packages/api/src/agents/transactions.spec.ts+++ b/packages/api/src/agents/transactions.spec.ts@@ -398,6 +398,33 @@ describe('bulkWriteTransactions (real DB)', () => {const bal = await Balance.findOne({ user: testUserId }).lean();expect(bal).toBeNull();});++ it('should not debit the balance when inserting the ledger entries fails', async () => {+ await Balance.create({ user: testUserId, tokenCredits: 1000 });+ const docs: PreparedEntry[] = [+ {+ doc: { user: testUserId, conversationId: 'c1', tokenType: 'prompt', tokenValue: -100 },+ tokenValue: -100,+ balance: { enabled: true },+ },+ ];+ const updateBalance = jest.fn(dbMethods.updateBalance);+ const dbOps = {+ insertMany: jest.fn().mockRejectedValue(new Error('insert failed')),+ updateBalance,+ };++ await expect(bulkWriteTransactions({ user: testUserId, docs }, dbOps)).rejects.toThrow(+ 'insert failed',+ );++ expect(updateBalance).not.toHaveBeenCalled();+ const bal = (await Balance.findOne({ user: testUserId }).lean()) as Record<+ string,+ unknown+ > | null;+ expect(bal!.tokenCredits).toBe(1000);+ });});describe('end-to-end: prepare → bulk write → verify', () => {diff --git a/packages/api/src/agents/transactions.ts b/packages/api/src/agents/transactions.tsindex f673235432..146c9d5ce1 100644--- a/packages/api/src/agents/transactions.ts+++ b/packages/api/src/agents/transactions.ts@@ -371,9 +371,13 @@ export async function bulkWriteTransactions(return doc;});+ /**+ * Ledger first, then balance (same order as `createTransaction`): a failed insert+ * must never leave a debit without its transaction records.+ */+ await dbOps.insertMany(plainDocs);+if (balanceEnabled) {await dbOps.updateBalance({ user, incrementValue: totalTokenValue });}-- await dbOps.insertMany(plainDocs);}diff --git a/packages/data-schemas/src/methods/memory.spec.ts b/packages/data-schemas/src/methods/memory.spec.tsindex 09d9d7dec2..3c007c489d 100644--- a/packages/data-schemas/src/methods/memory.spec.ts+++ b/packages/data-schemas/src/methods/memory.spec.ts@@ -239,6 +239,20 @@ describe('memory partitions', () => {expect(created.ok).toBe(true);});+ it('createMemory never overwrites an existing entry and stores one document per key', async () => {+ await methods.createMemory({ userId, key: 'context', value: 'original', tokenCount: 1 });+ const results = await Promise.allSettled([+ methods.createMemory({ userId, key: 'context', value: 'dupe 1', tokenCount: 9 }),+ methods.createMemory({ userId, key: 'context', value: 'dupe 2', tokenCount: 9 }),+ ]);++ expect(results.every((result) => result.status === 'rejected')).toBe(true);+ const stored = await MemoryEntry.find({ userId, key: 'context' }).lean();+ expect(stored).toHaveLength(1);+ expect(stored[0].value).toBe('original');+ expect(stored[0].tokenCount).toBe(1);+ });+it('formats memories per partition with partition-scoped totals', async () => {await methods.setMemory({ userId, key: 'one', value: 'personal one', tokenCount: 5 });await methods.setMemory({ userId, key: 'two', value: 'agent two', tokenCount: 7, agentId });diff --git a/packages/data-schemas/src/methods/memory.ts b/packages/data-schemas/src/methods/memory.tsindex c41f3763da..36bd4ae683 100644--- a/packages/data-schemas/src/methods/memory.ts+++ b/packages/data-schemas/src/methods/memory.ts@@ -57,24 +57,23 @@ export function createMemoryMethods(mongoose: typeof import('mongoose')): {}const MemoryEntry = mongoose.models.MemoryEntry;- const existingMemory = await MemoryEntry.findOne({- userId,- key,- ...partitionFilter(agentId),- });- if (existingMemory) {+ /** Insert-only upsert: one round trip decides existence, unlike a find-then-create. */+ const result = await MemoryEntry.updateOne(+ { userId, key, ...partitionFilter(agentId) },+ {+ $setOnInsert: {+ value,+ tokenCount,+ ...(agentId ? { agentId } : {}),+ updated_at: new Date(),+ },+ },+ { upsert: true },+ );+ if (!result.upsertedCount) {throw new Error('Memory with this key already exists');}- await MemoryEntry.create({- userId,- key,- value,- tokenCount,- ...(agentId ? { agentId } : {}),- updated_at: new Date(),- });-return { ok: true };} catch (error) {throw new Error(diff --git a/packages/data-schemas/src/methods/pluginAuth.spec.ts b/packages/data-schemas/src/methods/pluginAuth.spec.tsnew file mode 100644index 0000000000..a69f40e7ad--- /dev/null+++ b/packages/data-schemas/src/methods/pluginAuth.spec.ts@@ -0,0 +1,52 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import type { PluginAuthMethods } from './pluginAuth';+import { createPluginAuthMethods } from './pluginAuth';+import { createModels } from '~/models';++jest.mock('~/config/winston', () => ({+ error: jest.fn(),+ warn: jest.fn(),+ info: jest.fn(),+ debug: jest.fn(),+}));++let mongoServer: InstanceType<typeof MongoMemoryServer>;+let methods: PluginAuthMethods;++const userId = new mongoose.Types.ObjectId().toString();+const key = { userId, pluginKey: 'web_search', authField: 'API_KEY' };++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ createModels(mongoose);+ methods = createPluginAuthMethods(mongoose);+ await mongoose.connect(mongoServer.getUri());+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+});++beforeEach(async () => {+ await mongoose.models.PluginAuth.deleteMany({});+});++describe('updatePluginAuth', () => {+ it('creates the credential when missing and returns it', async () => {+ const created = await methods.updatePluginAuth({ ...key, value: 'first' });++ expect(created).toMatchObject({ ...key, value: 'first' });+ expect(await mongoose.models.PluginAuth.countDocuments(key)).toBe(1);+ });++ it('updates the existing credential in place instead of inserting another', async () => {+ const created = await methods.updatePluginAuth({ ...key, value: 'first' });+ const updated = await methods.updatePluginAuth({ ...key, value: 'second' });++ expect(updated?._id?.toString()).toBe(created?._id?.toString());+ expect(updated?.value).toBe('second');+ expect(await mongoose.models.PluginAuth.countDocuments(key)).toBe(1);+ });+});diff --git a/packages/data-schemas/src/methods/pluginAuth.ts b/packages/data-schemas/src/methods/pluginAuth.tsindex 3aed689ccb..38cd13f627 100644--- a/packages/data-schemas/src/methods/pluginAuth.ts+++ b/packages/data-schemas/src/methods/pluginAuth.ts@@ -89,28 +89,12 @@ export function createPluginAuthMethods(mongoose: typeof import('mongoose')): {}: UpdatePluginAuthParams): Promise<IPluginAuth> {try {const PluginAuth: Model<IPluginAuth> = mongoose.models.PluginAuth;- const existingAuth = await PluginAuth.findOne({- userId,- pluginKey,- authField,- }).lean<IPluginAuth>();-- if (existingAuth) {- return await PluginAuth.findOneAndUpdate(- { userId, pluginKey, authField },- { $set: { value } },- { new: true, upsert: true },- ).lean<IPluginAuth>();- } else {- const newPluginAuth = await new PluginAuth({- userId,- authField,- value,- pluginKey,- });- await newPluginAuth.save();- return newPluginAuth.toObject();- }+ /** Single atomic upsert: a find-then-save let concurrent writers insert duplicates. */+ return await PluginAuth.findOneAndUpdate(+ { userId, pluginKey, authField },+ { $set: { value } },+ { new: true, upsert: true, setDefaultsOnInsert: true },+ ).lean<IPluginAuth>();} catch (error) {throw new Error(`Failed to update plugin auth: ${error instanceof Error ? error.message : 'Unknown error'}`,diff --git a/packages/data-schemas/src/methods/preset.spec.ts b/packages/data-schemas/src/methods/preset.spec.tsnew file mode 100644index 0000000000..6250ff0551--- /dev/null+++ b/packages/data-schemas/src/methods/preset.spec.ts@@ -0,0 +1,82 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createPresetMethods } from './preset';+import { createModels } from '~/models';++jest.mock('~/config/winston', () => ({+ error: jest.fn(),+ warn: jest.fn(),+ info: jest.fn(),+ debug: jest.fn(),+}));++let mongoServer: InstanceType<typeof MongoMemoryServer>;+let methods: ReturnType<typeof createPresetMethods>;++const user = new mongoose.Types.ObjectId().toString();+const otherUser = new mongoose.Types.ObjectId().toString();++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ createModels(mongoose);+ methods = createPresetMethods(mongoose);+ await mongoose.connect(mongoServer.getUri());+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+});++beforeEach(async () => {+ await mongoose.models.Preset.deleteMany({});+});++async function defaultsFor(owner: string): Promise<string[]> {+ const docs = await mongoose.models.Preset.find({ user: owner, defaultPreset: true }).lean();+ return docs.map((doc) => doc.presetId as string).sort();+}++describe('savePreset default handling', () => {+ it('demotes every other default of the same user, leaving other users untouched', async () => {+ await mongoose.models.Preset.create([+ { user, presetId: 'a', title: 'a', endpoint: 'openAI', defaultPreset: true, order: 0 },+ { user, presetId: 'b', title: 'b', endpoint: 'openAI', defaultPreset: true, order: 0 },+ {+ user: otherUser,+ presetId: 'x',+ title: 'x',+ endpoint: 'openAI',+ defaultPreset: true,+ order: 0,+ },+ ]);++ await methods.savePreset(user, {+ presetId: 'c',+ title: 'c',+ endpoint: 'openAI',+ defaultPreset: true,+ });++ expect(await defaultsFor(user)).toEqual(['c']);+ expect(await defaultsFor(otherUser)).toEqual(['x']);+ });++ it('keeps the default flag when re-saving the current default', async () => {+ await methods.savePreset(user, {+ presetId: 'a',+ title: 'a',+ endpoint: 'openAI',+ defaultPreset: true,+ });+ await methods.savePreset(user, {+ presetId: 'a',+ title: 'renamed',+ endpoint: 'openAI',+ defaultPreset: true,+ });++ expect(await defaultsFor(user)).toEqual(['a']);+ });+});diff --git a/packages/data-schemas/src/methods/preset.ts b/packages/data-schemas/src/methods/preset.tsindex 559e2de2d6..202bda761f 100644--- a/packages/data-schemas/src/methods/preset.ts+++ b/packages/data-schemas/src/methods/preset.ts@@ -159,13 +159,11 @@ export function createPresetMethods(mongoose: typeof import('mongoose')): {update.defaultPreset = defaultPreset;update.order = 0;- const currentDefault = await Preset.findOne({ defaultPreset: true, user });-- if (currentDefault && currentDefault.presetId !== presetId) {- await Preset.findByIdAndUpdate(currentDefault._id, {- $unset: { defaultPreset: '', order: '' },- });- }+ /** One write demotes every other default, instead of a read then a by-id update. */+ await Preset.updateMany(+ { user, defaultPreset: true, ...(presetId != null && { presetId: { $ne: presetId } }) },+ { $unset: { defaultPreset: '', order: '' } },+ );} else if (defaultPreset === false) {update.defaultPreset = undefined;update.order = undefined;diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.tsindex 7bffe5e381..4723760e22 100644--- a/packages/data-schemas/src/methods/user.methods.spec.ts+++ b/packages/data-schemas/src/methods/user.methods.spec.ts@@ -1939,6 +1939,48 @@ describe('User Methods - Database Tests', () => {});});+ describe('updateUserPlugins', () => {+ test('keeps concurrent installs made from the same stale snapshot', async () => {+ const user = await User.create({+ name: 'Test User',+ email: '[email protected]',+ provider: 'local',+ plugins: ['existing'],+ });+ const userId = user._id?.toString() ?? '';+ const staleSnapshot = ['existing'];++ await Promise.all([+ methods.updateUserPlugins(userId, staleSnapshot, 'alpha', 'install'),+ methods.updateUserPlugins(userId, staleSnapshot, 'beta', 'install'),+ methods.updateUserPlugins(userId, staleSnapshot, 'alpha', 'install'),+ ]);++ const stored = await User.findById(userId).lean();+ expect([...(stored?.plugins ?? [])].sort()).toEqual(['alpha', 'beta', 'existing']);+ });++ test('uninstall removes only the target plugin, ignoring the stale snapshot', async () => {+ const user = await User.create({+ name: 'Test User',+ email: '[email protected]',+ provider: 'local',+ plugins: ['alpha', 'beta', 'gamma'],+ });+ const userId = user._id?.toString() ?? '';++ const updated = await methods.updateUserPlugins(userId, ['alpha'], 'alpha', 'uninstall');++ expect(updated?.plugins).toEqual(['beta', 'gamma']);+ });++ test('returns null for an unknown user', async () => {+ const fakeId = new mongoose.Types.ObjectId().toString();+ const result = await methods.updateUserPlugins(fakeId, [], 'alpha', 'install');+ expect(result).toBeNull();+ });+ });+describe('toggleUserMemories', () => {test('should enable memories for user', async () => {const user = await User.create({diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.tsindex 94aaddb6f1..f8123c7199 100644--- a/packages/data-schemas/src/methods/user.ts+++ b/packages/data-schemas/src/methods/user.ts@@ -851,13 +851,7 @@ export function createUserMethods(): Promise<IUser | null> {const User = mongoose.models.User;- // First, ensure the personalization object exists- const user = await User.findById(userId);- if (!user) {- return null;- }-- // Use $set to update the nested field, which will create the personalization object if it doesn't exist+ /** `$set` on the nested path creates `personalization` when missing; a missing user yields null. */const updateOperation = {$set: {'personalization.memories': memoriesEnabled,@@ -1005,29 +999,36 @@ export function createUserMethods(};/**- * Updates the plugins for a user based on the action specified (install/uninstall).+ * Installs or uninstalls a plugin with a single atomic array operator, so concurrent+ * install/uninstall requests cannot overwrite each other.* @param userId - The user ID whose plugins are to be updated- * @param plugins - The current plugins array+ * @param _plugins - Ignored; the caller's possibly stale snapshot, kept for signature compatibility* @param pluginKey - The key of the plugin to install or uninstall* @param action - The action to perform, 'install' or 'uninstall'- * @returns The result of the update operation or null if action is invalid+ * @returns The updated user, or null if the action is invalid or the user is missing*/async function updateUserPlugins(userId: string,- plugins: string[] | undefined,+ _plugins: string[] | undefined,pluginKey: string,action: 'install' | 'uninstall',): Promise<IUser | null> {- const userPlugins = plugins ?? [];+ let arrayOperation: Record<string, { plugins: string }>;if (action === 'install') {- return updateUser(userId, { plugins: [...userPlugins, pluginKey] });- }- if (action === 'uninstall') {- return updateUser(userId, {- plugins: userPlugins.filter((plugin) => plugin !== pluginKey),- });+ arrayOperation = { $addToSet: { plugins: pluginKey } };+ } else if (action === 'uninstall') {+ arrayOperation = { $pull: { plugins: pluginKey } };+ } else {+ return null;}- return null;+ const User = mongoose.models.User;+ const updated = await User.findByIdAndUpdate(+ userId,+ { ...arrayOperation, $unset: { expiresAt: '' } },+ { new: true, runValidators: true },+ ).lean<IUser>();+ await invalidateAuthUserDocCache(userId);+ return updated;}return {