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
🏭 refactor: Centralize Source Prompt Imports in the Prompt Service (#17272)
Atef Bellaaja2cd772d4927
diff --git a/api/server/routes/admin/langfuse.test.js b/api/server/routes/admin/langfuse.test.jsindex 4ff8a83ea3..849aba78b1 100644--- a/api/server/routes/admin/langfuse.test.js+++ b/api/server/routes/admin/langfuse.test.js@@ -235,6 +235,7 @@ describe('admin Langfuse routes', () => {expect(handlerDepsAtLoad).not.toHaveProperty('findLangfusePromptGroup');expect(handlerDepsAtLoad).not.toHaveProperty('createLangfusePromptGroup');expect(handlerDepsAtLoad).not.toHaveProperty('deletePromptGroup');+ expect(handlerDepsAtLoad).not.toHaveProperty('promptService');});it('requires manage:prompts access, in addition to Langfuse manage access, for POST /prompts/sync', async () => {diff --git a/api/server/routes/prompts.js b/api/server/routes/prompts.jsindex 274d306760..ca15c51421 100644--- a/api/server/routes/prompts.js+++ b/api/server/routes/prompts.js@@ -1,7 +1,6 @@const express = require('express');const {generateCheckAccess,- createPromptService,createPromptHandlers,invalidateLinkedPrompt,} = require('@librechat/api');@@ -19,8 +18,8 @@ const {requireJwtAuth,configMiddleware,} = require('~/server/middleware');-const { getEffectivePermissions, grantPermission } = require('~/server/services/PermissionService');-const { getAppConfig } = require('~/server/services/Config');+const { getEffectivePermissions } = require('~/server/services/PermissionService');+const { promptService } = require('~/server/services/Prompts');const { getLogStores } = require('~/cache');const db = require('~/models');@@ -30,11 +29,7 @@ const router = express.Router();const linkedInstructionsCache = getLogStores(CacheKeys.AGENT_LINKED_INSTRUCTIONS);const handlers = createPromptHandlers({- service: createPromptService({- db,- grantPermission,- getAppConfig,- }),+ service: promptService,getPromptGroupAccessContext: db.getPromptGroupAccessContext,getEffectivePermissions,invalidateLinkedPrompt: (groupId, promptIds) =>diff --git a/api/server/services/Agents/instructionsPrompt.js b/api/server/services/Agents/instructionsPrompt.jsindex 938e33e9d5..8244a4a679 100644--- a/api/server/services/Agents/instructionsPrompt.js+++ b/api/server/services/Agents/instructionsPrompt.js@@ -1,17 +1,13 @@const { logger, SystemCapabilities } = require('@librechat/data-schemas');const {checkAccess,- createPromptService,assertModelBoundContent,createInstructionsPromptAccess,} = require('@librechat/api');const { Permissions, PermissionTypes } = require('librechat-data-provider');-const {- grantPermission,- getResourcePermissionsMap,-} = require('~/server/services/PermissionService');+const { getResourcePermissionsMap } = require('~/server/services/PermissionService');const { hasCapability } = require('~/server/middleware/roles/capabilities');-const { getAppConfig } = require('~/server/services/Config');+const { promptService } = require('~/server/services/Prompts');const db = require('~/models');/**@@ -21,11 +17,7 @@ const db = require('~/models');const instructionsPromptAccess = createInstructionsPromptAccess({getResourcePermissionsMap,canManagePrompts: (user) => hasCapability(user, SystemCapabilities.MANAGE_PROMPTS),- promptService: createPromptService({- db,- grantPermission,- getAppConfig,- }),+ promptService,assertAgentInstructionsContent: ({ instructions, filters }) =>assertModelBoundContent({ filters, agents: [{ instructions }] }),/** The same role-level gate `checkPromptAccess` applies to every `/prompts` routediff --git a/api/server/services/Endpoints/agents/linkedInstructions.js b/api/server/services/Endpoints/agents/linkedInstructions.jsindex db506a6646..1cccb4032f 100644--- a/api/server/services/Endpoints/agents/linkedInstructions.js+++ b/api/server/services/Endpoints/agents/linkedInstructions.js@@ -1,10 +1,8 @@const { logger } = require('@librechat/data-schemas');const { CacheKeys } = require('librechat-data-provider');-const { createPromptService, createLinkedInstructionsResolver } = require('@librechat/api');-const { grantPermission } = require('~/server/services/PermissionService');-const { getAppConfig } = require('~/server/services/Config');+const { createLinkedInstructionsResolver } = require('@librechat/api');+const { promptService } = require('~/server/services/Prompts');const { getLogStores } = require('~/cache');-const db = require('~/models');/*** Shared resolver for an agent's `instructionsPrompt` link. Resolve and cache@@ -13,11 +11,7 @@ const db = require('~/models');* `AGENT_LINKED_INSTRUCTIONS` cache namespace (`~/cache/getLogStores.js`).*/const linkedInstructionsResolver = createLinkedInstructionsResolver({- promptService: createPromptService({- db,- grantPermission,- getAppConfig,- }),+ promptService,cache: getLogStores(CacheKeys.AGENT_LINKED_INSTRUCTIONS),logger,});diff --git a/api/server/services/LangfusePromptSync.js b/api/server/services/LangfusePromptSync.jsindex b672cec730..24d2f5281c 100644--- a/api/server/services/LangfusePromptSync.js+++ b/api/server/services/LangfusePromptSync.js@@ -1,16 +1,12 @@const { createLangfusePromptSyncRunner } = require('@librechat/api');const { logger } = require('@librechat/data-schemas');+const { promptService } = require('~/server/services/Prompts');const { distributedLock } = require('~/cache');-const { grantPermission } = require('~/server/services/PermissionService');-const db = require('~/models');/** The one Langfuse prompt-sync runner for this process, bound to the shared `distributedLock`. */const syncLangfusePromptCatalog = createLangfusePromptSyncRunner({lock: distributedLock,- findLangfusePromptGroup: db.findLangfusePromptGroup,- createLangfusePromptGroup: db.createLangfusePromptGroup,- deletePromptGroup: db.deletePromptGroup,- grantPermission,+ promptService,logger,});diff --git a/api/server/services/LangfusePromptSync.spec.js b/api/server/services/LangfusePromptSync.spec.jsindex c899fa6623..3fda60b819 100644--- a/api/server/services/LangfusePromptSync.spec.js+++ b/api/server/services/LangfusePromptSync.spec.js@@ -1,8 +1,8 @@const mockLock = { acquire: jest.fn(), extend: jest.fn(), release: jest.fn() };const mockSyncPromptCatalog = jest.fn();const mockCreateLangfusePromptSyncRunner = jest.fn(() => mockSyncPromptCatalog);-const mockGrantPermission = jest.fn();const mockLogger = { warn: jest.fn(), error: jest.fn() };+const mockPromptService = { importSourceGroup: jest.fn() };jest.mock('@librechat/api', () => ({createLangfusePromptSyncRunner: mockCreateLangfusePromptSyncRunner,@@ -16,28 +16,18 @@ jest.mock('~/cache', () => ({distributedLock: mockLock,}));-jest.mock('~/server/services/PermissionService', () => ({- grantPermission: mockGrantPermission,-}));--jest.mock('~/models', () => ({- findLangfusePromptGroup: jest.fn(),- createLangfusePromptGroup: jest.fn(),- deletePromptGroup: jest.fn(),+jest.mock('~/server/services/Prompts', () => ({+ promptService: mockPromptService,}));describe('LangfusePromptSync', () => {- it('composes the sync runner once with the shared lock and the db methods', () => {- const db = require('~/models');+ it('composes the sync runner once with the shared lock and the shared prompt service', () => {const { syncLangfusePromptCatalog } = require('./LangfusePromptSync');expect(mockCreateLangfusePromptSyncRunner).toHaveBeenCalledTimes(1);expect(mockCreateLangfusePromptSyncRunner).toHaveBeenCalledWith({lock: mockLock,- findLangfusePromptGroup: db.findLangfusePromptGroup,- createLangfusePromptGroup: db.createLangfusePromptGroup,- deletePromptGroup: db.deletePromptGroup,- grantPermission: mockGrantPermission,+ promptService: mockPromptService,logger: mockLogger,});expect(syncLangfusePromptCatalog).toBe(mockSyncPromptCatalog);diff --git a/api/server/services/Prompts.consumers.spec.js b/api/server/services/Prompts.consumers.spec.jsnew file mode 100644index 0000000000..13d9c7f9c3--- /dev/null+++ b/api/server/services/Prompts.consumers.spec.js@@ -0,0 +1,77 @@+const mockDb = {+ getPromptGroupAccessContext: jest.fn(),+ getRoleByName: jest.fn(),+ marker: 'db',+};+jest.mock('~/models', () => mockDb);++const mockGetAppConfig = jest.fn();+jest.mock('~/server/services/Config', () => ({+ getAppConfig: mockGetAppConfig,+}));++const mockGrantPermission = jest.fn();+const mockGetEffectivePermissions = jest.fn();+const mockGetResourcePermissionsMap = jest.fn();+jest.mock('~/server/services/PermissionService', () => ({+ grantPermission: mockGrantPermission,+ getEffectivePermissions: mockGetEffectivePermissions,+ getResourcePermissionsMap: mockGetResourcePermissionsMap,+}));++const mockCacheStore = { get: jest.fn(), set: jest.fn(), delete: jest.fn() };+const mockDistributedLock = { acquire: jest.fn(), extend: jest.fn(), release: jest.fn() };+jest.mock('~/cache', () => ({+ getLogStores: jest.fn(() => mockCacheStore),+ distributedLock: mockDistributedLock,+}));++// `routes/prompts.js` pulls in `~/server/middleware`'s full index, which (via+// `buildEndpointOption` -> agents `initialize`) reaches+// `createSubagentThreadTaskStore` and validates the full `db` method surface.+// This test only cares which `promptService` reference reaches each factory,+// so the route file's other middleware imports are stubbed the same way+// `routes/prompts.test.js` stubs them.+jest.mock('~/server/middleware', () => ({+ canAccessPromptGroupResource: jest.fn(() => (_req, _res, next) => next()),+ canAccessPromptViaGroup: jest.fn(() => (_req, _res, next) => next()),+ promptUsageLimiter: jest.fn((_req, _res, next) => next()),+ promptResolveLimiter: jest.fn((_req, _res, next) => next()),+ requireJwtAuth: jest.fn((_req, _res, next) => next()),+ configMiddleware: jest.fn((_req, _res, next) => next()),+}));++describe('Prompts consumers', () => {+ it('passes the one process promptService, by identity, into every @librechat/api composition factory', () => {+ const api = jest.requireActual('@librechat/api');++ // The CJS dist exports these factories as plain `exports.x = x` assignments+ // (verified via grep on packages/api/dist/index.cjs), so `jest.spyOn` can+ // replace the property in place and every later `require('@librechat/api')`+ // in this test run (same module-registry entry) observes the spy.+ const createPromptHandlersSpy = jest.spyOn(api, 'createPromptHandlers');+ const createLinkedInstructionsResolverSpy = jest.spyOn(api, 'createLinkedInstructionsResolver');+ const createInstructionsPromptAccessSpy = jest.spyOn(api, 'createInstructionsPromptAccess');+ const createLangfusePromptSyncRunnerSpy = jest.spyOn(api, 'createLangfusePromptSyncRunner');++ const { promptService } = require('~/server/services/Prompts');+ expect(typeof promptService.importSourceGroup).toBe('function');++ require('~/server/routes/prompts');+ require('~/server/services/Endpoints/agents/linkedInstructions');+ require('~/server/services/Agents/instructionsPrompt');+ require('~/server/services/LangfusePromptSync');++ expect(createPromptHandlersSpy).toHaveBeenCalledTimes(1);+ expect(createPromptHandlersSpy.mock.calls[0][0].service).toBe(promptService);++ expect(createLinkedInstructionsResolverSpy).toHaveBeenCalledTimes(1);+ expect(createLinkedInstructionsResolverSpy.mock.calls[0][0].promptService).toBe(promptService);++ expect(createInstructionsPromptAccessSpy).toHaveBeenCalledTimes(1);+ expect(createInstructionsPromptAccessSpy.mock.calls[0][0].promptService).toBe(promptService);++ expect(createLangfusePromptSyncRunnerSpy).toHaveBeenCalledTimes(1);+ expect(createLangfusePromptSyncRunnerSpy.mock.calls[0][0].promptService).toBe(promptService);+ });+});diff --git a/api/server/services/Prompts.js b/api/server/services/Prompts.jsnew file mode 100644index 0000000000..5278dc7c8f--- /dev/null+++ b/api/server/services/Prompts.js@@ -0,0 +1,9 @@+const { createPromptService } = require('@librechat/api');+const { getAppConfig } = require('~/server/services/Config');+const { grantPermission } = require('~/server/services/PermissionService');+const db = require('~/models');++/** The one prompt service for this process. */+const promptService = createPromptService({ db, grantPermission, getAppConfig });++module.exports = { promptService };diff --git a/api/server/services/Prompts.spec.js b/api/server/services/Prompts.spec.jsnew file mode 100644index 0000000000..93d994029a--- /dev/null+++ b/api/server/services/Prompts.spec.js@@ -0,0 +1,33 @@+const mockDb = { marker: 'db' };+const mockGrantPermission = jest.fn();+const mockGetAppConfig = jest.fn();+const mockPromptServiceInstance = { marker: 'promptService' };+const mockCreatePromptService = jest.fn(() => mockPromptServiceInstance);++jest.mock('@librechat/api', () => ({+ createPromptService: mockCreatePromptService,+}));++jest.mock('~/models', () => mockDb);++jest.mock('~/server/services/PermissionService', () => ({+ grantPermission: mockGrantPermission,+}));++jest.mock('~/server/services/Config', () => ({+ getAppConfig: mockGetAppConfig,+}));++describe('Prompts', () => {+ it('builds the process prompt service once with the shared db, grantPermission and getAppConfig', () => {+ const { promptService } = require('./Prompts');++ expect(mockCreatePromptService).toHaveBeenCalledTimes(1);+ expect(mockCreatePromptService).toHaveBeenCalledWith({+ db: mockDb,+ grantPermission: mockGrantPermission,+ getAppConfig: mockGetAppConfig,+ });+ expect(promptService).toBe(mockPromptServiceInstance);+ });+});diff --git a/packages/api/src/langfuse/promptCatalogSync.spec.ts b/packages/api/src/langfuse/promptCatalogSync.spec.tsindex c9033fb086..5420df306a 100644--- a/packages/api/src/langfuse/promptCatalogSync.spec.ts+++ b/packages/api/src/langfuse/promptCatalogSync.spec.ts@@ -22,12 +22,7 @@ function listResult(function createDeps(overrides: Partial<PromptCatalogSyncDeps> = {}): PromptCatalogSyncDeps {return {listPrompts: jest.fn().mockResolvedValue(listResult([], 0)),- findPromptGroup: jest.fn().mockResolvedValue(null),- createPromptGroup: jest.fn().mockResolvedValue({ _id: 'group-1' }),- isDuplicateKeyError: jest.fn().mockReturnValue(false),- isValidationError: jest.fn().mockReturnValue(false),- grantPublicViewer: jest.fn().mockResolvedValue(undefined),- deletePromptGroup: jest.fn().mockResolvedValue(undefined),+ promptService: { importSourceGroup: jest.fn().mockResolvedValue('created') },lock: {acquire: jest.fn().mockResolvedValue('token'),extend: jest.fn().mockResolvedValue(true),@@ -194,11 +189,11 @@ describe('syncLangfusePromptCatalog', () => {expect(listPrompts).toHaveBeenCalledWith({ type: 'text', limit: 25, page: 1 });});- it('counts a found match as unchanged without creating or granting', async () => {- const findPromptGroup = jest.fn().mockResolvedValue({ _id: 'existing' });+ it('counts an unchanged outcome without affecting other counters', async () => {+ const importSourceGroup = jest.fn().mockResolvedValue('unchanged');const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),- findPromptGroup,+ promptService: { importSourceGroup },});const result = await syncLangfusePromptCatalog(source, deps);@@ -207,13 +202,13 @@ describe('syncLangfusePromptCatalog', () => {ok: true,value: { created: 0, unchanged: 1, skipped: 0, complete: true },});- expect(deps.createPromptGroup).not.toHaveBeenCalled();- expect(deps.grantPublicViewer).not.toHaveBeenCalled();});- it('creates and grants a new group on a miss', async () => {+ it('counts a created outcome and passes the identity, author and author name', async () => {+ const importSourceGroup = jest.fn().mockResolvedValue('created');const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),+ promptService: { importSourceGroup },});const result = await syncLangfusePromptCatalog(source, deps);@@ -222,56 +217,26 @@ describe('syncLangfusePromptCatalog', () => {ok: true,value: { created: 1, unchanged: 0, skipped: 0, complete: true },});- expect(deps.createPromptGroup).toHaveBeenCalledWith({- sourceDestination: 'us',- sourceProjectId: 'project-1',- sourcePromptName: 'a',+ expect(importSourceGroup).toHaveBeenCalledWith({+ identity: {+ sourceDestination: 'us',+ sourceProjectId: 'project-1',+ sourcePromptName: 'a',+ },name: 'a',author: makeSourceAuthorId('langfuse', 'project-1', undefined),authorName: 'Langfuse Sync',});- expect(deps.grantPublicViewer).toHaveBeenCalledWith('group-1');});- it('counts a duplicate-key create as unchanged without granting', async () => {- const createPromptGroup = jest.fn().mockRejectedValue(new Error('E11000'));- const isDuplicateKeyError = jest.fn().mockReturnValue(true);- const deps = createDeps({- listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),- createPromptGroup,- isDuplicateKeyError,- });-- const result = await syncLangfusePromptCatalog(source, deps);-- expect(result).toEqual({- ok: true,- value: { created: 0, unchanged: 1, skipped: 0, complete: true },- });- expect(deps.grantPublicViewer).not.toHaveBeenCalled();- });-- it('rejects when create fails with an unexpected error, releasing the lock once', async () => {- const createPromptGroup = jest.fn().mockRejectedValueOnce(new Error('boom'));- const deps = createDeps({- listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),- createPromptGroup,- });-- await expect(syncLangfusePromptCatalog(source, deps)).rejects.toThrow('boom');- expect(deps.lock.release).toHaveBeenCalledTimes(1);- });-- it('counts a validation error on create as skipped and continues the loop', async () => {- const createPromptGroup = jest+ it('counts a skipped outcome from importSourceGroup and continues the loop', async () => {+ const importSourceGroup = jest.fn()- .mockRejectedValueOnce(new Error('invalid'))- .mockResolvedValueOnce({ _id: 'group-2' });- const isValidationError = jest.fn().mockReturnValue(true);+ .mockResolvedValueOnce('skipped')+ .mockResolvedValueOnce('created');const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a'), textItem('b')], 1)),- createPromptGroup,- isValidationError,+ promptService: { importSourceGroup },});const result = await syncLangfusePromptCatalog(source, deps);@@ -280,38 +245,21 @@ describe('syncLangfusePromptCatalog', () => {ok: true,value: { created: 1, unchanged: 0, skipped: 1, complete: true },});- expect(deps.logger.warn).toHaveBeenCalledWith(- expect.stringContaining('validation'),- 'a',- expect.any(Error),- );});- it('rolls back and rejects with the original grant error when the grant throws', async () => {- const grantPublicViewer = jest.fn().mockRejectedValue(new Error('grant failed'));- const deps = createDeps({- listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),- grantPublicViewer,- });+ it('rejects when importSourceGroup rejects, stops paging and releases the lock once', async () => {+ const listPrompts = jest+ .fn()+ .mockResolvedValueOnce(listResult([textItem('a')], 2, 1))+ .mockResolvedValueOnce(listResult([textItem('b')], 2, 2));+ const importSourceGroup = jest.fn().mockRejectedValue(new Error('boom'));+ const deps = createDeps({ listPrompts, promptService: { importSourceGroup } });- await expect(syncLangfusePromptCatalog(source, deps)).rejects.toThrow('grant failed');- expect(deps.deletePromptGroup).toHaveBeenCalledWith('group-1');+ await expect(syncLangfusePromptCatalog(source, deps)).rejects.toThrow('boom');+ expect(listPrompts).toHaveBeenCalledTimes(1);expect(deps.lock.release).toHaveBeenCalledTimes(1);});- it('still rejects with the original grant error and error-logs when the rollback delete also throws', async () => {- const grantPublicViewer = jest.fn().mockRejectedValue(new Error('grant failed'));- const deletePromptGroup = jest.fn().mockRejectedValue(new Error('delete failed'));- const deps = createDeps({- listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),- grantPublicViewer,- deletePromptGroup,- });-- await expect(syncLangfusePromptCatalog(source, deps)).rejects.toThrow('grant failed');- expect(deps.logger.error).toHaveBeenCalledTimes(2);- });-it('warns and counts a non-text item as skipped', async () => {const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([chatItem('chat-1')], 1)),@@ -324,15 +272,16 @@ describe('syncLangfusePromptCatalog', () => {value: { created: 0, unchanged: 0, skipped: 1, complete: true },});expect(deps.logger.warn).toHaveBeenCalledWith(expect.stringContaining('chat-1'));- expect(deps.findPromptGroup).not.toHaveBeenCalled();+ expect(deps.promptService.importSourceGroup).not.toHaveBeenCalled();});it('counts a name repeated across pages only once', async () => {+ const importSourceGroup = jest.fn().mockResolvedValue('created');const listPrompts = jest.fn().mockResolvedValueOnce(listResult([textItem('dup')], 2, 1)).mockResolvedValueOnce(listResult([textItem('dup')], 2, 2));- const deps = createDeps({ listPrompts });+ const deps = createDeps({ listPrompts, promptService: { importSourceGroup } });const result = await syncLangfusePromptCatalog(source, deps);@@ -340,7 +289,7 @@ describe('syncLangfusePromptCatalog', () => {ok: true,value: { created: 1, unchanged: 0, skipped: 0, complete: true },});- expect(deps.findPromptGroup).toHaveBeenCalledTimes(1);+ expect(importSourceGroup).toHaveBeenCalledTimes(1);});it('releases the lock when listPrompts throws, and the error still propagates', async () => {@@ -374,20 +323,24 @@ describe('syncLangfusePromptCatalog', () => {});it('seeds the author id from the project id alone when no tenant is given', async () => {+ const importSourceGroup = jest.fn().mockResolvedValue('created');const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),+ promptService: { importSourceGroup },});await syncLangfusePromptCatalog({ destination: 'us', projectId: 'project-1' }, deps);- expect(deps.createPromptGroup).toHaveBeenCalledWith(+ expect(importSourceGroup).toHaveBeenCalledWith(expect.objectContaining({ author: makeSourceAuthorId('langfuse', 'project-1', undefined) }),);});it('seeds a different author id per tenant for the same project', async () => {+ const importSourceGroup = jest.fn().mockResolvedValue('created');const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),+ promptService: { importSourceGroup },});await syncLangfusePromptCatalog(@@ -395,12 +348,12 @@ describe('syncLangfusePromptCatalog', () => {deps,);- expect(deps.createPromptGroup).toHaveBeenCalledWith(+ expect(importSourceGroup).toHaveBeenCalledWith(expect.objectContaining({author: makeSourceAuthorId('langfuse', 'project-1', 'tenant-a'),}),);- expect(deps.createPromptGroup).not.toHaveBeenCalledWith(+ expect(importSourceGroup).not.toHaveBeenCalledWith(expect.objectContaining({ author: makeSourceAuthorId('langfuse', 'project-1', undefined) }),);});@@ -423,13 +376,15 @@ describe('syncLangfusePromptCatalog', () => {});it('always passes the Langfuse Sync author name', async () => {+ const importSourceGroup = jest.fn().mockResolvedValue('created');const deps = createDeps({listPrompts: jest.fn().mockResolvedValue(listResult([textItem('a')], 1)),+ promptService: { importSourceGroup },});await syncLangfusePromptCatalog(source, deps);- expect(deps.createPromptGroup).toHaveBeenCalledWith(+ expect(importSourceGroup).toHaveBeenCalledWith(expect.objectContaining({ authorName: 'Langfuse Sync' }),);});diff --git a/packages/api/src/langfuse/promptCatalogSync.ts b/packages/api/src/langfuse/promptCatalogSync.tsindex 0f7dc1f6c6..adf12f374e 100644--- a/packages/api/src/langfuse/promptCatalogSync.ts+++ b/packages/api/src/langfuse/promptCatalogSync.ts@@ -1,4 +1,6 @@-import type { TLangfusePromptListItem, TLangfusePromptListResponse } from 'librechat-data-provider';+import type { TLangfusePromptListResponse } from 'librechat-data-provider';+import type { PromptGroupSourceIdentity } from '~/prompts/types';+import type { PromptService } from '~/prompts/service';import type { DistributedLock } from '~/cache/lock';import { makeSourceAuthorId } from '~/utils/author';@@ -25,31 +27,13 @@ export type PromptCatalogSyncResult =| { ok: true; value: PromptCatalogSyncCounts }| { ok: false; error: { code: 'already_running' | 'lock_lost' } };-/** The identity a synced group is found or created by. */-export type PromptGroupSourceIdentity = {- sourceDestination: string;- sourceProjectId: string;- sourcePromptName: string;-};--export type PromptCatalogSyncCreateInput = PromptGroupSourceIdentity & {- name: string;- author: string;- authorName: string;-};-export type PromptCatalogSyncDeps = {listPrompts: (query: {type: 'text';limit: number;page: number;}) => Promise<TLangfusePromptListResponse>;- findPromptGroup: (identity: PromptGroupSourceIdentity) => Promise<{ _id: string } | null>;- createPromptGroup: (input: PromptCatalogSyncCreateInput) => Promise<{ _id: string }>;- isDuplicateKeyError: (error: unknown) => boolean;- isValidationError: (error: unknown) => boolean;- grantPublicViewer: (groupId: string) => Promise<void>;- deletePromptGroup: (groupId: string) => Promise<void>;+ promptService: Pick<PromptService, 'importSourceGroup'>;lock: DistributedLock;lockLeaseMs: number;logger: {@@ -60,65 +44,6 @@ export type PromptCatalogSyncDeps = {maxPages?: number;};-/** Finds-or-creates one Langfuse text prompt as a pointer-only group, granting- * a PUBLIC viewer entry only when it was just created. A match is left as is:- * no ACL write and no update statement run against an existing group. */-async function syncOne(- item: TLangfusePromptListItem,- identity: PromptGroupSourceIdentity,- author: string,- deps: PromptCatalogSyncDeps,-): Promise<'created' | 'unchanged' | 'skipped'> {- // The group insert and its initial PUBLIC grant below are separate writes. If an earlier- // run inserted the group and then exited before granting PUBLIC access, this run finds- // the group here and returns `unchanged` without retrying the grant, so the group keeps- // no PUBLIC viewer entry.- const existing = await deps.findPromptGroup(identity);- if (existing) {- return 'unchanged';- }-- let created: { _id: string };- try {- created = await deps.createPromptGroup({- ...identity,- name: item.name,- author,- authorName: LANGFUSE_SYNC_AUTHOR_NAME,- });- } catch (error) {- if (deps.isDuplicateKeyError(error)) {- return 'unchanged';- }- if (deps.isValidationError(error)) {- deps.logger.warn(- '[langfuse] Could not save a synced prompt group that failed validation:',- item.name,- error,- );- return 'skipped';- }- throw error;- }-- try {- await deps.grantPublicViewer(created._id);- } catch (error) {- deps.logger.error('[langfuse] Could not grant public access to a synced prompt group:', error);- try {- await deps.deletePromptGroup(created._id);- } catch (deleteError) {- deps.logger.error(- '[langfuse] Could not roll back an ungranted synced prompt group:',- deleteError,- );- }- throw error;- }-- return 'created';-}-/*** Syncs every Langfuse text prompt in `source`'s project into the local* prompt catalog as a read-only, pointer-only group: name and source identity@@ -199,7 +124,12 @@ export async function syncLangfusePromptCatalog(sourceProjectId: source.projectId,sourcePromptName: item.name,};- const outcome = await syncOne(item, identity, author, deps);+ const outcome = await deps.promptService.importSourceGroup({+ identity,+ name: item.name,+ author,+ authorName: LANGFUSE_SYNC_AUTHOR_NAME,+ });counts[outcome] += 1;}diff --git a/packages/api/src/langfuse/promptSyncRunner.spec.ts b/packages/api/src/langfuse/promptSyncRunner.spec.tsindex 5293d9503e..4a2a77e11a 100644--- a/packages/api/src/langfuse/promptSyncRunner.spec.ts+++ b/packages/api/src/langfuse/promptSyncRunner.spec.ts@@ -2,7 +2,6 @@ import type { TLangfusePromptListItem, TLangfusePromptListResponse } from 'libreimport type { LangfusePromptSyncRunnerDeps, LangfusePromptSyncRequest } from './promptSyncRunner';import type { DistributedLock } from '~/cache/lock';import { createLangfusePromptSyncRunner } from './promptSyncRunner';-import { makeSourceAuthorId } from '~/utils/author';function textItem(name: string): TLangfusePromptListItem {return { name, type: 'text', versions: [1], labels: [], tags: [], lastUpdatedAt: '2026-01-01' };@@ -28,10 +27,7 @@ function createFakeLock(overrides: Partial<DistributedLock> = {}): DistributedLofunction createDeps(overrides: Partial<LangfusePromptSyncRunnerDeps> = {}) {return {lock: createFakeLock(),- findLangfusePromptGroup: jest.fn().mockResolvedValue(null),- createLangfusePromptGroup: jest.fn().mockResolvedValue({ _id: 'group-1' }),- deletePromptGroup: jest.fn().mockResolvedValue({ message: 'Prompt group deleted' }),- grantPermission: jest.fn().mockResolvedValue(undefined),+ promptService: { importSourceGroup: jest.fn().mockResolvedValue('created') },logger: { warn: jest.fn(), error: jest.fn() },...overrides,};@@ -50,123 +46,6 @@ function createRequest(}describe('createLangfusePromptSyncRunner', () => {- it('creates a pointer group for a new prompt and grants the PUBLIC viewer as the system user', async () => {- const deps = createDeps();- const run = createLangfusePromptSyncRunner(deps);-- const result = await run(createRequest());-- expect(result).toEqual({- ok: true,- value: { created: 1, unchanged: 0, skipped: 0, complete: true },- });- expect(deps.findLangfusePromptGroup).toHaveBeenCalledWith({- sourceDestination: 'eu',- sourceProjectId: 'project-1',- sourcePromptName: 'greeting',- });- expect(deps.createLangfusePromptGroup).toHaveBeenCalledWith({- name: 'greeting',- author: makeSourceAuthorId('langfuse', 'project-1', 't1'),- authorName: 'Langfuse Sync',- sourceDestination: 'eu',- sourceProjectId: 'project-1',- sourcePromptName: 'greeting',- });- expect(deps.grantPermission).toHaveBeenCalledTimes(1);- expect(deps.grantPermission).toHaveBeenCalledWith({- principalType: 'public',- principalId: null,- resourceType: 'promptGroup',- resourceId: 'group-1',- accessRoleId: 'promptGroup_viewer',- grantedBy: '000000000000000000000000',- });- expect(deps.deletePromptGroup).not.toHaveBeenCalled();- expect(deps.lock.release).toHaveBeenCalledTimes(1);- });-- it('counts an existing group as unchanged without creating or granting', async () => {- const deps = createDeps({- findLangfusePromptGroup: jest.fn().mockResolvedValue({ _id: 'existing-id' }),- });- const run = createLangfusePromptSyncRunner(deps);-- const result = await run(createRequest());-- expect(result).toEqual({- ok: true,- value: { created: 0, unchanged: 1, skipped: 0, complete: true },- });- expect(deps.createLangfusePromptGroup).not.toHaveBeenCalled();- expect(deps.grantPermission).not.toHaveBeenCalled();- });-- it('maps a duplicate-key error (code 11000) on create to unchanged without granting', async () => {- const duplicateError = Object.assign(new Error('duplicate key'), { code: 11000 });- const deps = createDeps({- createLangfusePromptGroup: jest.fn().mockRejectedValue(duplicateError),- });- const run = createLangfusePromptSyncRunner(deps);-- const result = await run(createRequest());-- expect(result).toEqual({- ok: true,- value: { created: 0, unchanged: 1, skipped: 0, complete: true },- });- expect(deps.grantPermission).not.toHaveBeenCalled();- expect(deps.logger.warn).not.toHaveBeenCalled();- });-- it('maps a ValidationError on create to skipped with a warning', async () => {- const validationError = new Error('invalid document');- validationError.name = 'ValidationError';- const deps = createDeps({- createLangfusePromptGroup: jest.fn().mockRejectedValue(validationError),- });- const run = createLangfusePromptSyncRunner(deps);-- const result = await run(createRequest());-- expect(result).toEqual({- ok: true,- value: { created: 0, unchanged: 0, skipped: 1, complete: true },- });- expect(deps.grantPermission).not.toHaveBeenCalled();- expect(deps.logger.warn).toHaveBeenCalledTimes(1);- expect(deps.logger.warn).toHaveBeenCalledWith(- expect.stringContaining('failed validation'),- 'greeting',- validationError,- );- });-- it('rethrows an unexpected create error, which is neither a duplicate key nor a validation failure', async () => {- const deps = createDeps({- createLangfusePromptGroup: jest.fn().mockRejectedValue(new Error('boom')),- });- const run = createLangfusePromptSyncRunner(deps);-- await expect(run(createRequest())).rejects.toThrow('boom');- expect(deps.grantPermission).not.toHaveBeenCalled();- expect(deps.lock.release).toHaveBeenCalledTimes(1);- });-- it('deletes the created group and rethrows when the grant fails', async () => {- const grantError = new Error('grant failed');- const deps = createDeps({ grantPermission: jest.fn().mockRejectedValue(grantError) });- const run = createLangfusePromptSyncRunner(deps);-- await expect(run(createRequest())).rejects.toBe(grantError);- expect(deps.deletePromptGroup).toHaveBeenCalledWith({ _id: 'group-1' });- expect(deps.logger.error).toHaveBeenCalledWith(- expect.stringContaining('Could not grant public access'),- grantError,- );- expect(deps.lock.release).toHaveBeenCalledTimes(1);- });-it('acquires and extends the lock with the per-request lease', async () => {const deps = createDeps();const run = createLangfusePromptSyncRunner(deps);@@ -223,14 +102,6 @@ describe('createLangfusePromptSyncRunner', () => {expect(second.listPrompts).toHaveBeenCalledTimes(1);expect(deps.lock.acquire).toHaveBeenNthCalledWith(1, 'prompt-sync:langfuse:t1', 300_000);expect(deps.lock.acquire).toHaveBeenNthCalledWith(2, 'prompt-sync:langfuse:', 300_000);- expect(deps.createLangfusePromptGroup).toHaveBeenNthCalledWith(- 2,- expect.objectContaining({- sourceDestination: 'us',- sourceProjectId: 'project-2',- author: makeSourceAuthorId('langfuse', 'project-2'),- }),- );});it('returns already_running without listing when the lock is held', async () => {@@ -246,4 +117,14 @@ describe('createLangfusePromptSyncRunner', () => {expect(request.listPrompts).not.toHaveBeenCalled();expect(deps.lock.release).not.toHaveBeenCalled();});++ it('passes a rejection from importSourceGroup to the caller', async () => {+ const deps = createDeps({+ promptService: { importSourceGroup: jest.fn().mockRejectedValue(new Error('boom')) },+ });+ const run = createLangfusePromptSyncRunner(deps);++ await expect(run(createRequest())).rejects.toThrow('boom');+ expect(deps.lock.release).toHaveBeenCalledTimes(1);+ });});diff --git a/packages/api/src/langfuse/promptSyncRunner.ts b/packages/api/src/langfuse/promptSyncRunner.tsindex bc5fcc16fe..172ea0ee7f 100644--- a/packages/api/src/langfuse/promptSyncRunner.ts+++ b/packages/api/src/langfuse/promptSyncRunner.ts@@ -1,5 +1,3 @@-import { PrincipalType, ResourceType, AccessRoleIds } from 'librechat-data-provider';-import type { PromptMethods } from '@librechat/data-schemas';import type {PromptCatalogSyncDeps,PromptCatalogSyncResult,@@ -7,23 +5,11 @@ import type {} from './promptCatalogSync';import type { DistributedLock } from '~/cache/lock';import { syncLangfusePromptCatalog } from './promptCatalogSync';-import { CONSTANTS } from '~/mcp/enum';-/** Process-lifetime dependencies: the shared lock, the Mongo-backed prompt- * group methods, the ACL grant and the logger. */+/** Process-lifetime dependencies: the shared lock, the prompt service and the logger. */export interface LangfusePromptSyncRunnerDeps {lock: DistributedLock;- findLangfusePromptGroup: PromptMethods['findLangfusePromptGroup'];- createLangfusePromptGroup: PromptMethods['createLangfusePromptGroup'];- deletePromptGroup: PromptMethods['deletePromptGroup'];- grantPermission: (params: {- principalType: PrincipalType;- principalId: string | null;- resourceType: ResourceType;- resourceId: string;- accessRoleId: string;- grantedBy: string;- }) => Promise<unknown>;+ promptService: PromptCatalogSyncDeps['promptService'];logger: PromptCatalogSyncDeps['logger'];}@@ -40,55 +26,18 @@ export type LangfusePromptSyncRunner = (request: LangfusePromptSyncRequest,) => Promise<PromptCatalogSyncResult>;-/** The AI-2272 partial unique index is defense in depth: this maps the- * resulting duplicate-key race to the runner's `unchanged` outcome. */-function isDuplicateKeyError(error: unknown): boolean {- return (error as { code?: number } | undefined)?.code === 11000;-}--/** A document validation failure on `createLangfusePromptGroup`, mapped to the- * runner's `skipped` outcome. */-function isValidationError(error: unknown): boolean {- return error instanceof Error && error.name === 'ValidationError';-}--/** Binds the storage-agnostic `syncLangfusePromptCatalog` to the Mongo-backed- * prompt-group methods and the ACL grant, so the Mongo error predicates live- * here and `promptCatalogSync.ts` stays storage-agnostic. Every new group is- * granted a PUBLIC `PROMPTGROUP_VIEWER` entry by the system user; a failed- * grant deletes the group again before the error propagates. */+/** Binds the storage-agnostic `syncLangfusePromptCatalog` to the process-lifetime lock,+ * prompt service and logger, so a request supplies only the source and the+ * connection-bound page lister. */export function createLangfusePromptSyncRunner(deps: LangfusePromptSyncRunnerDeps,): LangfusePromptSyncRunner {- const {- lock,- findLangfusePromptGroup,- createLangfusePromptGroup,- deletePromptGroup,- grantPermission,- logger,- } = deps;+ const { lock, promptService, logger } = deps;return async function syncPromptCatalog({ source, listPrompts, lockLeaseMs, maxPages }) {const syncDeps: PromptCatalogSyncDeps = {listPrompts,- findPromptGroup: findLangfusePromptGroup,- createPromptGroup: createLangfusePromptGroup,- isDuplicateKeyError,- isValidationError,- grantPublicViewer: async (groupId) => {- await grantPermission({- principalType: PrincipalType.PUBLIC,- principalId: null,- resourceType: ResourceType.PROMPTGROUP,- resourceId: groupId,- accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,- grantedBy: CONSTANTS.SYSTEM_USER_ID,- });- },- deletePromptGroup: async (groupId) => {- await deletePromptGroup({ _id: groupId });- },+ promptService,lock,lockLeaseMs,maxPages,diff --git a/packages/api/src/prompts/native.spec.ts b/packages/api/src/prompts/native.spec.tsindex 45122db6e7..23a8e2218e 100644--- a/packages/api/src/prompts/native.spec.ts+++ b/packages/api/src/prompts/native.spec.ts@@ -16,6 +16,7 @@ beforeAll(async () => {await mongoose.connect(mongo.getUri());createModels(mongoose);db = createMethods(mongoose);+ await mongoose.models.PromptGroup.syncIndexes();});beforeEach(async () => {@@ -271,4 +272,83 @@ describe('createPromptCatalogStore', () => {await expect(catalog.getPromptGroup(new Types.ObjectId().toString())).resolves.toBeNull();});++ describe('findSourceGroup and createSourceGroup', () => {+ const identity = {+ sourceDestination: 'us',+ sourceProjectId: 'project-1',+ sourcePromptName: 'synced-prompt',+ };++ it('returns null for an identity with no stored group', async () => {+ const catalog = createPromptCatalogStore(db);++ await expect(catalog.findSourceGroup(identity)).resolves.toBeNull();+ });++ it('creates a source group and then finds it by identity', async () => {+ const catalog = createPromptCatalogStore(db);++ const created = await catalog.createSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(created).toEqual({ ok: true, value: { _id: expect.any(String) } });+ await expect(catalog.findSourceGroup(identity)).resolves.toEqual({+ _id: created.ok ? created.value._id : undefined,+ });+ });++ it('returns a duplicate error for a second insert with the same identity', async () => {+ const catalog = createPromptCatalogStore(db);+ await catalog.createSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });++ const result = await catalog.createSourceGroup({+ identity,+ name: 'Synced prompt again',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(result).toEqual({ ok: false, error: { code: 'duplicate' } });+ });++ it('returns an invalid error with a cause for an empty name', async () => {+ const catalog = createPromptCatalogStore(db);++ const result = await catalog.createSourceGroup({+ identity,+ name: '',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(result).toEqual({+ ok: false,+ error: { code: 'invalid', cause: expect.any(Error) },+ });+ });++ it('rethrows a non-Mongo, non-validation error', async () => {+ const catalog = createPromptCatalogStore(db);+ jest.spyOn(db, 'createLangfusePromptGroup').mockRejectedValueOnce(new Error('unavailable'));++ await expect(+ catalog.createSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ }),+ ).rejects.toThrow('unavailable');+ });+ });});diff --git a/packages/api/src/prompts/native.ts b/packages/api/src/prompts/native.tsindex d90f29b72c..bd6ef0b9c9 100644--- a/packages/api/src/prompts/native.ts+++ b/packages/api/src/prompts/native.ts@@ -90,6 +90,17 @@ function toIdString(id: StoredId): string {return typeof id === 'string' ? id : id.toString();}+/** The AI-2272 partial unique index is defense in depth: this maps the resulting+ * duplicate-key race to `createSourceGroup`'s `duplicate` outcome. */+function isDuplicateKeyError(error: unknown): boolean {+ return (error as { code?: number } | undefined)?.code === 11000;+}++/** A document validation failure, mapped to `createSourceGroup`'s `invalid` outcome. */+function isValidationError(error: unknown): boolean {+ return error instanceof Error && error.name === 'ValidationError';+}+export function selectionUnavailableReason(selection: PromptSelection): 'production' | 'revision' {return selection.type === 'production' ? 'production' : 'revision';}@@ -162,5 +173,26 @@ export function createPromptCatalogStore(db: PromptDatabase): PromptCatalogStoretoPromptGroupRecord(await db.updatePromptGroup({ _id: groupId }, updates)),incrementPromptGroupUsage: (groupId) => db.incrementPromptGroupUsage(groupId),deletePromptGroup: (groupId) => db.deletePromptGroup({ _id: groupId }),+ findSourceGroup: (identity) => db.findLangfusePromptGroup(identity),+ createSourceGroup: async (input) => {+ const { identity, name, author, authorName } = input;+ try {+ const value = await db.createLangfusePromptGroup({+ ...identity,+ name,+ author,+ authorName,+ });+ return { ok: true, value };+ } catch (error) {+ if (isDuplicateKeyError(error)) {+ return { ok: false, error: { code: 'duplicate' } };+ }+ if (isValidationError(error)) {+ return { ok: false, error: { code: 'invalid', cause: error } };+ }+ throw error;+ }+ },};}diff --git a/packages/api/src/prompts/service.spec.ts b/packages/api/src/prompts/service.spec.tsindex 7f77beb824..c1602f79cf 100644--- a/packages/api/src/prompts/service.spec.ts+++ b/packages/api/src/prompts/service.spec.ts@@ -1,3 +1,9 @@+jest.mock('~/admin/secrets', () => ({+ decryptConfigSecret: jest.fn((value: string) =>+ value === 'v3:test:tenant-a-secret' ? 'tenant-a-secret' : undefined,+ ),+}));+import mongoose, { Types } from 'mongoose';import { MongoMemoryServer } from 'mongodb-memory-server';import { AccessRoleIds, PrincipalType, ResourceType } from 'librechat-data-provider';@@ -5,6 +11,7 @@ import {logger,createModels,createMethods,+ tenantStorage,BASE_CONFIG_PRINCIPAL_ID,} from '@librechat/data-schemas';import type { FiltersConfig } from 'librechat-data-provider';@@ -19,6 +26,7 @@ import type { PromptServiceDependencies, PromptService } from './service';import { createPromptServiceFromAdapters, createPromptService } from './service';import { createPromptCatalogStore, createNativePromptAdapter } from './native';import { PromptStoreError } from './errors';+import { CONSTANTS } from '~/mcp/enum';const filters: FiltersConfig = {prompts: {@@ -44,6 +52,7 @@ beforeAll(async () => {await mongoose.connect(mongo.getUri());createModels(mongoose);db = createMethods(mongoose);+ await mongoose.models.PromptGroup.syncIndexes();});beforeEach(async () => {@@ -213,7 +222,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt: jest.fn() },catalog,grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});const rejection: unknown = await routed@@ -431,6 +441,182 @@ describe('createPromptService', () => {});});+ describe('importSourceGroup', () => {+ const identity = {+ sourceDestination: 'us',+ sourceProjectId: 'project-1',+ sourcePromptName: 'synced-prompt',+ };++ it('creates a pointer group with source fields and no productionId, and grants a PUBLIC viewer as the system user', async () => {+ const outcome = await service.importSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(outcome).toBe('created');+ const found = await db.findLangfusePromptGroup(identity);+ expect(found).not.toBeNull();+ const stored = (await mongoose.models.PromptGroup.findById(found?._id).lean()) as {+ productionId?: unknown;+ } | null;+ expect(stored).toMatchObject({+ source: 'langfuse',+ ...identity,+ name: 'Synced prompt',+ author: new Types.ObjectId(author),+ authorName: 'Langfuse Sync',+ });+ expect(stored).not.toHaveProperty('productionId');+ expect(grantPermission).toHaveBeenCalledWith({+ principalType: PrincipalType.PUBLIC,+ principalId: null,+ resourceType: ResourceType.PROMPTGROUP,+ resourceId: found?._id,+ accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,+ grantedBy: CONSTANTS.SYSTEM_USER_ID,+ });+ });++ it('leaves a second import for the same identity unchanged, without granting again', async () => {+ await service.importSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });+ grantPermission.mockClear();++ const outcome = await service.importSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(outcome).toBe('unchanged');+ expect(grantPermission).not.toHaveBeenCalled();+ });++ it('treats a race where findSourceGroup misses a row that already exists as unchanged, without granting', async () => {+ const catalog = createPromptCatalogStore(db);+ const created = await catalog.createSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });+ if (!created.ok) {+ throw new Error('Setup insert failed');+ }+ jest.spyOn(catalog, 'findSourceGroup').mockResolvedValue(null);+ const grantPublicViewer = jest.fn();+ const routed = createPromptServiceFromAdapters({+ native: createNativePromptAdapter(db),+ langfuse: { resolvePrompt: jest.fn() },+ catalog,+ grantCreatorOwnership: jest.fn(),+ grantPublicViewer,+ logger: { warn: jest.fn(), error: jest.fn() },+ });++ const outcome = await routed.importSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(outcome).toBe('unchanged');+ expect(grantPublicViewer).not.toHaveBeenCalled();+ });++ it('skips an empty name and warns with safe metadata only, saving nothing', async () => {+ const logWarn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);++ const outcome = await service.importSourceGroup({+ identity,+ name: '',+ author,+ authorName: 'Langfuse Sync',+ });++ expect(outcome).toBe('skipped');+ expect(logWarn).toHaveBeenCalledTimes(1);+ expect(logWarn).toHaveBeenCalledWith(+ '[importSourceGroup] Skipped a source group that failed validation',+ { name: '', code: 'invalid', type: 'Error' },+ );+ await expect(db.findLangfusePromptGroup(identity)).resolves.toBeNull();+ });++ it('deletes the newly created group and rethrows when the grant fails', async () => {+ const catalog = createPromptCatalogStore(db);+ const grantPublicViewer = jest.fn().mockRejectedValue(new Error('grant failed'));+ const logError = jest.fn();+ const routed = createPromptServiceFromAdapters({+ native: createNativePromptAdapter(db),+ langfuse: { resolvePrompt: jest.fn() },+ catalog,+ grantCreatorOwnership: jest.fn(),+ grantPublicViewer,+ logger: { warn: jest.fn(), error: logError },+ });++ await expect(+ routed.importSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ }),+ ).rejects.toThrow('grant failed');++ await expect(catalog.findSourceGroup(identity)).resolves.toBeNull();+ expect(logError).toHaveBeenCalledTimes(1);+ expect(logError).toHaveBeenCalledWith(expect.stringContaining('[importSourceGroup]'), {+ groupId: expect.any(String),+ type: 'Error',+ });+ });++ it('still rethrows the grant error and logs two errors when the rollback delete also fails', async () => {+ const catalog = createPromptCatalogStore(db);+ jest.spyOn(catalog, 'deletePromptGroup').mockRejectedValue(new Error('delete failed'));+ const grantPublicViewer = jest.fn().mockRejectedValue(new Error('grant failed'));+ const logError = jest.fn();+ const routed = createPromptServiceFromAdapters({+ native: createNativePromptAdapter(db),+ langfuse: { resolvePrompt: jest.fn() },+ catalog,+ grantCreatorOwnership: jest.fn(),+ grantPublicViewer,+ logger: { warn: jest.fn(), error: logError },+ });++ await expect(+ routed.importSourceGroup({+ identity,+ name: 'Synced prompt',+ author,+ authorName: 'Langfuse Sync',+ }),+ ).rejects.toThrow('grant failed');++ expect(logError).toHaveBeenCalledTimes(2);+ expect(logError).toHaveBeenNthCalledWith(1, expect.stringContaining('[importSourceGroup]'), {+ groupId: expect.any(String),+ type: 'Error',+ });+ expect(logError).toHaveBeenNthCalledWith(2, expect.stringContaining('[importSourceGroup]'), {+ groupId: expect.any(String),+ type: 'Error',+ });+ });+ });+describe('savePrompt', () => {it.each([[undefined, 'Prompt is required'],@@ -748,7 +934,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt: jest.fn() },catalog: createPromptCatalogStore(db),grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});await expect(@@ -827,7 +1014,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt },catalog: createPromptCatalogStore(db),grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});await expect(@@ -852,7 +1040,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt },catalog: createPromptCatalogStore(db),grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});await expect(@@ -881,7 +1070,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt },catalog: createPromptCatalogStore(db),grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});await expect(@@ -1047,7 +1237,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt },catalog,grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});await expect(@@ -1077,7 +1268,8 @@ describe('createPromptService', () => {langfuse: { resolvePrompt },catalog,grantCreatorOwnership: jest.fn(),- logger: { error: jest.fn() },+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },});await expect(@@ -1198,5 +1390,73 @@ describe('createPromptService', () => {expect(findConfigByPrincipal).not.toHaveBeenCalled();expect(getAppConfig).not.toHaveBeenCalled();});++ it('serves two concurrent Langfuse resolves on one shared instance, each tied to its own tenant and config', async () => {+ process.env.LANGFUSE_PROMPT_SYNC_AVAILABLE = 'true';+ const groupA = makeLangfuseGroup({+ sourcePromptName: 'prompt-a',+ sourceDestination: 'us',+ sourceProjectId: 'project-a',+ tenantId: 'a',+ });+ const groupB = makeLangfuseGroup({+ sourcePromptName: 'prompt-b',+ sourceDestination: 'us',+ sourceProjectId: 'project-b',+ tenantId: 'b',+ });++ // Each request reads its own stored credentials. Tenant a finishes later+ // with a mismatched project. Tenant b has no usable secret key.+ const findConfigByPrincipal = jest+ .spyOn(db, 'findConfigByPrincipal')+ .mockImplementation(async () => {+ const tenantId = tenantStorage.getStore()?.tenantId;+ await new Promise((resolve) => setTimeout(resolve, tenantId === 'a' ? 20 : 0));+ return {+ overrides: {+ langfuse: {+ promptSync: { enabled: true },+ publicKey: `tenant-${tenantId}-public-key`,+ secretKey: tenantId === 'a' ? 'v3:test:tenant-a-secret' : undefined,+ destination: 'us',+ projectId: tenantId === 'a' ? 'a-mismatched-project' : 'project-b',+ },+ },+ };+ });+ getAppConfig.mockResolvedValue({} as never);+ const shared = createPromptService({ db, grantPermission, getAppConfig });++ const [resultA, resultB] = await Promise.all([+ tenantStorage.run({ tenantId: 'a' }, async () =>+ shared.resolvePrompt({+ groupId: groupA._id,+ selection: { type: 'production' },+ loadedGroup: groupA,+ }),+ ),+ tenantStorage.run({ tenantId: 'b' }, async () =>+ shared.resolvePrompt({+ groupId: groupB._id,+ selection: { type: 'production' },+ loadedGroup: groupB,+ }),+ ),+ ]);++ expect(resultA).toEqual({+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason: 'source_changed' },+ });+ expect(resultB).toEqual({+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason: 'not_configured' },+ });+ expect(findConfigByPrincipal).toHaveBeenCalledTimes(2);+ expect(getAppConfig).toHaveBeenCalledTimes(2);+ expect(getAppConfig).toHaveBeenCalledWith({ tenantId: 'a' });+ expect(getAppConfig).toHaveBeenCalledWith({ tenantId: 'b' });+ });});});diff --git a/packages/api/src/prompts/service.ts b/packages/api/src/prompts/service.tsindex 50e01b91f7..f3016835b3 100644--- a/packages/api/src/prompts/service.ts+++ b/packages/api/src/prompts/service.ts@@ -12,10 +12,12 @@ import type {PromptServiceError,PromptSourceAdapter,PromptServiceResult,+ ImportSourceGroupInput,PromptCreationResult,CreatePromptGroupInput,PromptServiceAdapters,MakePromptProductionResult,+ PromptSourceImportOutcome,} from './types';import type { ProjectedStoredPrompt, ProjectedStoredPromptGroup } from './protection';import type { CreateLangfuseSourceResolverDeps } from '../langfuse/promptSync';@@ -40,6 +42,7 @@ import { createLangfuseSourceResolver } from '../langfuse/promptSync';import { createLangfusePromptAdapter } from './langfuse';import { getSafeErrorMetadata } from '~/utils';import { withPromptStage } from './errors';+import { CONSTANTS } from '~/mcp/enum';type WithPromptFilters<T> = T & { readonly filters?: FiltersConfig };type ProjectedGroup = ProjectedStoredPromptGroup<PromptGroupRecord>;@@ -118,6 +121,13 @@ export interface PromptService {}): Promise<PromptServiceResult<{ readonly message: string; readonly promptIds?: readonly string[] }>>;+ /**+ * Finds-or-creates one source-pointer group by its source identity, granting a+ * PUBLIC viewer entry only when it was just created. A match is left as is: no+ * ACL write and no update statement run against an existing group. A failed+ * grant rolls the new group back and rethrows.+ */+ importSourceGroup(input: ImportSourceGroupInput): Promise<PromptSourceImportOutcome>;}function invalidInput<T>(message: string, details?: unknown): PromptServiceResult<T> {@@ -150,7 +160,7 @@ function inspect(/** Builds the prompt service from a native adapter, a Langfuse adapter, a catalog* store and an ownership grant. */export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters): PromptService {- const { native, langfuse, catalog, grantCreatorOwnership, logger } = adapters;+ const { native, langfuse, catalog, grantCreatorOwnership, grantPublicViewer, logger } = adapters;const adaptersBySource: Record<PromptGroupRecord['source'], PromptSourceAdapter> = {native,langfuse,@@ -395,6 +405,49 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)const value = await catalog.deletePromptGroup(groupId);return { ok: true, value: promptIds == null ? value : { ...value, promptIds } };},++ async importSourceGroup({ identity, name, author, authorName }) {+ // Insertion and the initial PUBLIC grant are separate writes. If a run stops between+ // them, a later import leaves the existing group unchanged and does not retry the grant.+ const existing = await catalog.findSourceGroup(identity);+ if (existing) {+ return 'unchanged';+ }++ const created = await catalog.createSourceGroup({ identity, name, author, authorName });+ if (!created.ok) {+ if (created.error.code === 'duplicate') {+ return 'unchanged';+ }+ logger.warn('[importSourceGroup] Skipped a source group that failed validation', {+ name,+ code: 'invalid',+ ...getSafeErrorMetadata(created.error.cause),+ });+ return 'skipped';+ }++ const groupId = created.value._id;+ try {+ await grantPublicViewer({ groupId });+ } catch (error) {+ logger.error(+ '[importSourceGroup] Could not grant public access to an imported source group',+ { groupId, ...getSafeErrorMetadata(error) },+ );+ try {+ await catalog.deletePromptGroup(groupId);+ } catch (deleteError) {+ logger.error('[importSourceGroup] Could not roll back an ungranted source group', {+ groupId,+ ...getSafeErrorMetadata(deleteError),+ });+ }+ throw error;+ }++ return 'created';+ },};}@@ -402,7 +455,7 @@ export interface PromptServiceDependencies {readonly db: PromptDatabase;readonly grantPermission: (input: {principalType: PrincipalType;- principalId: string;+ principalId: string | null;resourceType: ResourceType;resourceId: string;accessRoleId: AccessRoleIds;@@ -452,6 +505,16 @@ export function createPromptService({`[createPromptGroup] Granted owner permissions to user ${userId} for promptGroup ${groupId}`,);},+ grantPublicViewer: async ({ groupId }) => {+ await grantPermission({+ principalType: PrincipalType.PUBLIC,+ principalId: null,+ resourceType: ResourceType.PROMPTGROUP,+ resourceId: groupId,+ accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,+ grantedBy: CONSTANTS.SYSTEM_USER_ID,+ });+ },logger,});}diff --git a/packages/api/src/prompts/types.ts b/packages/api/src/prompts/types.tsindex c5721d676d..b26b44efb6 100644--- a/packages/api/src/prompts/types.ts+++ b/packages/api/src/prompts/types.ts@@ -125,6 +125,36 @@ export interface PromptListInput {export type PromptOperation = 'savePrompt' | 'makePromptProduction' | 'deletePrompt';+/** The identity a synced group is found or created by. */+export type PromptGroupSourceIdentity = {+ sourceDestination: string;+ sourceProjectId: string;+ sourcePromptName: string;+};++/** The input to `PromptService.importSourceGroup`: a source-pointer group's identity+ * plus the display fields a found-or-created group is named and authored by. */+export type ImportSourceGroupInput = {+ readonly identity: PromptGroupSourceIdentity;+ readonly name: string;+ readonly author: string;+ readonly authorName: string;+};++/** `created` is a new group; `unchanged` covers both an existing match and a+ * duplicate-key race lost to a concurrent insert; `skipped` is a document that+ * failed validation and was never saved. */+export type PromptSourceImportOutcome = 'created' | 'unchanged' | 'skipped';++export type CreateSourceGroupResult =+ | { readonly ok: true; readonly value: { readonly _id: string } }+ | {+ readonly ok: false;+ readonly error:+ | { readonly code: 'duplicate' }+ | { readonly code: 'invalid'; readonly cause: unknown };+ };+export type PromptServiceError =| { readonly type: 'invalid_input'; readonly message: string; readonly details?: unknown }| { readonly type: 'blocked_content'; readonly finding: ProtectionFinding }@@ -220,6 +250,13 @@ export interface PromptCatalogStore {updatePromptGroup(groupId: string, updates: Record<string, unknown>): Promise<PromptGroupRecord>;incrementPromptGroupUsage(groupId: string): Promise<{ readonly numberOfGenerations: number }>;deletePromptGroup(groupId: string): Promise<{ readonly message: string }>;+ /** Finds a source-pointer group by its source identity, for `importSourceGroup`'s+ * find-before-create step. */+ findSourceGroup(identity: PromptGroupSourceIdentity): Promise<{ readonly _id: string } | null>;+ /** Creates a source-pointer group: name and source identity only, never content.+ * Returns a typed failure for a duplicate-key race or a document validation+ * failure; any other failure throws. */+ createSourceGroup(input: ImportSourceGroupInput): Promise<CreateSourceGroupResult>;}/** The data-schemas prompt methods the native adapter and catalog store use. */@@ -252,6 +289,15 @@ export interface PromptDatabase {updatePromptGroup(filter: { _id: string }, data: Record<string, unknown>): Promise<object>;incrementPromptGroupUsage(groupId: string): Promise<{ numberOfGenerations: number }>;deletePromptGroup(filter: { _id: string }): Promise<{ message: string }>;+ findLangfusePromptGroup(identity: PromptGroupSourceIdentity): Promise<{ _id: string } | null>;+ createLangfusePromptGroup(input: {+ name: string;+ author: string;+ authorName: string;+ sourceDestination: string;+ sourceProjectId: string;+ sourcePromptName: string;+ }): Promise<{ _id: string }>;/** Reads the deployment's base config, which the Langfuse adapter's source resolver* checks for the prompt-sync switch. Returns the plain override document, not the* Mongoose model `~/models` resolves it from. */@@ -275,7 +321,11 @@ export interface PromptServiceAdapters {readonly userId: string;readonly groupId: string;}) => Promise<void>;+ /** Grants a PUBLIC viewer entry, for a source-pointer group just imported by+ * `importSourceGroup`. */+ readonly grantPublicViewer: (input: { readonly groupId: string }) => Promise<void>;readonly logger: {- error(message: string, error: unknown): void;+ warn(message: string, ...args: unknown[]): void;+ error(message: string, ...args: unknown[]): void;};}