🗑️ chore: Remove Deprecated Project Model and Associated Fields (#11773)

* chore: remove projects and projectIds usage

* chore: empty line linting

* chore: remove isCollaborative property across agent models and related tests

- Removed the isCollaborative property from agent models, controllers, and tests, as it is deprecated in favor of ACL permissions.
- Updated related validation schemas and data provider types to reflect this change.
- Ensured all references to isCollaborative were stripped from the codebase to maintain consistency and clarity.
This commit is contained in:
Danny Avila 2026-02-13 03:04:15 -05:00
parent 3398f6a17a
commit 37cc5faff5
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956
41 changed files with 94 additions and 821 deletions

View file

@ -1,20 +1,13 @@
import { logger } from '@librechat/data-schemas';
import { AccessRoleIds, ResourceType, PrincipalType, Constants } from 'librechat-data-provider';
import { AccessRoleIds, ResourceType, PrincipalType } from 'librechat-data-provider';
import { ensureRequiredCollectionsExist } from '../db/utils';
import type { AccessRoleMethods, IAgent } from '@librechat/data-schemas';
import type { Model, Mongoose } from 'mongoose';
const { GLOBAL_PROJECT_NAME } = Constants;
const GLOBAL_PROJECT_NAME = 'instance';
export interface MigrationCheckDbMethods {
findRoleByIdentifier: AccessRoleMethods['findRoleByIdentifier'];
getProjectByName: (
projectName: string,
fieldsToSelect?: string[] | null,
) => Promise<{
agentIds?: string[];
[key: string]: unknown;
} | null>;
}
export interface MigrationCheckParams {
@ -60,7 +53,6 @@ export async function checkAgentPermissionsMigration({
await ensureRequiredCollectionsExist(db);
}
// Verify required roles exist
const ownerRole = await methods.findRoleByIdentifier(AccessRoleIds.AGENT_OWNER);
const viewerRole = await methods.findRoleByIdentifier(AccessRoleIds.AGENT_VIEWER);
const editorRole = await methods.findRoleByIdentifier(AccessRoleIds.AGENT_EDITOR);
@ -77,9 +69,13 @@ export async function checkAgentPermissionsMigration({
};
}
// Get global project agent IDs
const globalProject = await methods.getProjectByName(GLOBAL_PROJECT_NAME, ['agentIds']);
const globalAgentIds = new Set(globalProject?.agentIds || []);
let globalAgentIds = new Set<string>();
if (db) {
const project = await db
.collection('projects')
.findOne({ name: GLOBAL_PROJECT_NAME }, { projection: { agentIds: 1 } });
globalAgentIds = new Set(project?.agentIds || []);
}
const AclEntry = mongoose.model('AclEntry');
const migratedAgentIds = await AclEntry.distinct('resourceId', {
@ -124,7 +120,6 @@ export async function checkAgentPermissionsMigration({
privateAgents: categories.privateAgents.length,
};
// Add details for debugging
if (agentsToMigrate.length > 0) {
result.details = {
globalEditAccess: categories.globalEditAccess.map((a) => ({
@ -152,7 +147,6 @@ export async function checkAgentPermissionsMigration({
return result;
} catch (error) {
logger.error('Failed to check agent permissions migration', error);
// Return zero counts on error to avoid blocking startup
return {
totalToMigrate: 0,
globalEditAccess: 0,
@ -170,7 +164,6 @@ export function logAgentMigrationWarning(result: MigrationCheckResult): void {
return;
}
// Create a visible warning box
const border = '='.repeat(80);
const warning = [
'',
@ -201,10 +194,8 @@ export function logAgentMigrationWarning(result: MigrationCheckResult): void {
'',
];
// Use console methods directly for visibility
console.log('\n' + warning.join('\n') + '\n');
// Also log with logger for consistency
logger.warn('Agent permissions migration required', {
totalToMigrate: result.totalToMigrate,
globalEditAccess: result.globalEditAccess,

View file

@ -94,9 +94,6 @@ export const agentUpdateSchema = agentBaseSchema.extend({
avatar: z.union([agentAvatarSchema, z.null()]).optional(),
provider: z.string().optional(),
model: z.string().nullable().optional(),
projectIds: z.array(z.string()).optional(),
removeProjectIds: z.array(z.string()).optional(),
isCollaborative: z.boolean().optional(),
});
interface ValidateAgentModelParams {

View file

@ -216,17 +216,12 @@ describe('access middleware', () => {
defaultParams.getRoleByName.mockResolvedValue(mockRole);
const checkObject = {
projectIds: ['project1'],
removeProjectIds: ['project2'],
};
const checkObject = {};
const result = await checkAccess({
...defaultParams,
permissions: [Permissions.USE, Permissions.SHARE],
bodyProps: {
[Permissions.SHARE]: ['projectIds', 'removeProjectIds'],
} as Record<Permissions, string[]>,
bodyProps: {} as Record<Permissions, string[]>,
checkObject,
});
expect(result).toBe(true);
@ -244,17 +239,12 @@ describe('access middleware', () => {
defaultParams.getRoleByName.mockResolvedValue(mockRole);
const checkObject = {
projectIds: ['project1'],
// missing removeProjectIds
};
const checkObject = {};
const result = await checkAccess({
...defaultParams,
permissions: [Permissions.SHARE],
bodyProps: {
[Permissions.SHARE]: ['projectIds', 'removeProjectIds'],
} as Record<Permissions, string[]>,
bodyProps: {} as Record<Permissions, string[]>,
checkObject,
});
expect(result).toBe(false);
@ -343,17 +333,12 @@ describe('access middleware', () => {
} as unknown as IRole;
mockGetRoleByName.mockResolvedValue(mockRole);
mockReq.body = {
projectIds: ['project1'],
removeProjectIds: ['project2'],
};
mockReq.body = {};
const middleware = generateCheckAccess({
permissionType: PermissionTypes.AGENTS,
permissions: [Permissions.USE, Permissions.CREATE, Permissions.SHARE],
bodyProps: {
[Permissions.SHARE]: ['projectIds', 'removeProjectIds'],
} as Record<Permissions, string[]>,
bodyProps: {} as Record<Permissions, string[]>,
getRoleByName: mockGetRoleByName,
});

View file

@ -1,20 +1,13 @@
import { logger } from '@librechat/data-schemas';
import { AccessRoleIds, ResourceType, PrincipalType, Constants } from 'librechat-data-provider';
import { AccessRoleIds, ResourceType, PrincipalType } from 'librechat-data-provider';
import { ensureRequiredCollectionsExist } from '../db/utils';
import type { AccessRoleMethods, IPromptGroupDocument } from '@librechat/data-schemas';
import type { Model, Mongoose } from 'mongoose';
const { GLOBAL_PROJECT_NAME } = Constants;
const GLOBAL_PROJECT_NAME = 'instance';
export interface PromptMigrationCheckDbMethods {
findRoleByIdentifier: AccessRoleMethods['findRoleByIdentifier'];
getProjectByName: (
projectName: string,
fieldsToSelect?: string[] | null,
) => Promise<{
promptGroupIds?: string[];
[key: string]: unknown;
} | null>;
}
export interface PromptMigrationCheckParams {
@ -53,13 +46,11 @@ export async function checkPromptPermissionsMigration({
logger.debug('Checking if prompt permissions migration is needed');
try {
/** Native MongoDB database instance */
const db = mongoose.connection.db;
if (db) {
await ensureRequiredCollectionsExist(db);
}
// Verify required roles exist
const ownerRole = await methods.findRoleByIdentifier(AccessRoleIds.PROMPTGROUP_OWNER);
const viewerRole = await methods.findRoleByIdentifier(AccessRoleIds.PROMPTGROUP_VIEWER);
const editorRole = await methods.findRoleByIdentifier(AccessRoleIds.PROMPTGROUP_EDITOR);
@ -75,11 +66,15 @@ export async function checkPromptPermissionsMigration({
};
}
/** Global project prompt group IDs */
const globalProject = await methods.getProjectByName(GLOBAL_PROJECT_NAME, ['promptGroupIds']);
const globalPromptGroupIds = new Set(
(globalProject?.promptGroupIds || []).map((id) => id.toString()),
);
let globalPromptGroupIds = new Set<string>();
if (db) {
const project = await db
.collection('projects')
.findOne({ name: GLOBAL_PROJECT_NAME }, { projection: { promptGroupIds: 1 } });
globalPromptGroupIds = new Set(
(project?.promptGroupIds || []).map((id: { toString(): string }) => id.toString()),
);
}
const AclEntry = mongoose.model('AclEntry');
const migratedGroupIds = await AclEntry.distinct('resourceId', {
@ -118,7 +113,6 @@ export async function checkPromptPermissionsMigration({
privateGroups: categories.privateGroups.length,
};
// Add details for debugging
if (promptGroupsToMigrate.length > 0) {
result.details = {
globalViewAccess: categories.globalViewAccess.map((g) => ({
@ -143,7 +137,6 @@ export async function checkPromptPermissionsMigration({
return result;
} catch (error) {
logger.error('Failed to check prompt permissions migration', error);
// Return zero counts on error to avoid blocking startup
return {
totalToMigrate: 0,
globalViewAccess: 0,
@ -160,7 +153,6 @@ export function logPromptMigrationWarning(result: PromptMigrationCheckResult): v
return;
}
// Create a visible warning box
const border = '='.repeat(80);
const warning = [
'',
@ -190,10 +182,8 @@ export function logPromptMigrationWarning(result: PromptMigrationCheckResult): v
'',
];
// Use console methods directly for visibility
console.log('\n' + warning.join('\n') + '\n');
// Also log with logger for consistency
logger.warn('Prompt permissions migration required', {
totalToMigrate: result.totalToMigrate,
globalViewAccess: result.globalViewAccess,

View file

@ -30,26 +30,6 @@ describe('updatePromptGroupSchema', () => {
}
});
it('should accept valid projectIds array', () => {
const result = updatePromptGroupSchema.safeParse({
projectIds: ['proj1', 'proj2'],
});
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.projectIds).toEqual(['proj1', 'proj2']);
}
});
it('should accept valid removeProjectIds array', () => {
const result = updatePromptGroupSchema.safeParse({
removeProjectIds: ['proj1'],
});
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.removeProjectIds).toEqual(['proj1']);
}
});
it('should accept valid command field', () => {
const result = updatePromptGroupSchema.safeParse({ command: 'my-command-123' });
expect(result.success).toBe(true);

View file

@ -14,10 +14,6 @@ export const updatePromptGroupSchema = z
oneliner: z.string().max(500).optional(),
/** Category for organizing prompt groups */
category: z.string().max(100).optional(),
/** Project IDs to add for sharing */
projectIds: z.array(z.string()).optional(),
/** Project IDs to remove from sharing */
removeProjectIds: z.array(z.string()).optional(),
/** Command shortcut for the prompt group */
command: z
.string()

View file

@ -781,7 +781,6 @@ export type TStartupConfig = {
sharedLinksEnabled: boolean;
publicSharedLinksEnabled: boolean;
analyticsGtmId?: string;
instanceProjectId: string;
bundlerURL?: string;
staticBundlerURL?: string;
sharePointFilePickerEnabled?: boolean;
@ -1748,8 +1747,6 @@ export enum Constants {
SAVED_TAG = 'Saved',
/** Max number of Conversation starters for Agents/Assistants */
MAX_CONVO_STARTERS = 4,
/** Global/instance Project Name */
GLOBAL_PROJECT_NAME = 'instance',
/** Delimiter for MCP tools */
mcp_delimiter = '_mcp_',
/** Prefix for MCP plugins */

View file

@ -241,11 +241,8 @@ export const defaultAgentFormValues = {
tools: [],
tool_options: {},
provider: {},
projectIds: [],
edges: [],
artifacts: '',
/** @deprecated Use ACL permissions instead */
isCollaborative: false,
recursion_limit: undefined,
[Tools.execute_code]: false,
[Tools.file_search]: false,

View file

@ -539,7 +539,6 @@ export type TPromptGroup = {
command?: string;
oneliner?: string;
category?: string;
projectIds?: string[];
productionId?: string | null;
productionPrompt?: Pick<TPrompt, 'prompt'> | null;
author: string;
@ -592,9 +591,7 @@ export type TCreatePromptResponse = {
group?: TPromptGroup;
};
export type TUpdatePromptGroupPayload = Partial<TPromptGroup> & {
removeProjectIds?: string[];
};
export type TUpdatePromptGroupPayload = Partial<TPromptGroup>;
export type TUpdatePromptGroupVariables = {
id: string;

View file

@ -252,15 +252,12 @@ export type Agent = {
instructions?: string | null;
additional_instructions?: string | null;
tools?: string[];
projectIds?: string[];
tool_kwargs?: Record<string, unknown>;
metadata?: Record<string, unknown>;
provider: AgentProvider;
model: string | null;
model_parameters: AgentModelParameters;
conversation_starters?: string[];
/** @deprecated Use ACL permissions instead */
isCollaborative?: boolean;
tool_resources?: AgentToolResources;
/** @deprecated Use edges instead */
agent_ids?: string[];
@ -313,9 +310,6 @@ export type AgentUpdateParams = {
provider?: AgentProvider;
model?: string | null;
model_parameters?: AgentModelParameters;
projectIds?: string[];
removeProjectIds?: string[];
isCollaborative?: boolean;
} & Pick<
Agent,
| 'agent_ids'

View file

@ -24,7 +24,6 @@ const agentSchema = new Schema({
id: { type: String, required: true },
name: { type: String, required: true },
author: { type: String },
isCollaborative: { type: Boolean, default: false },
});
const promptGroupSchema = new Schema({
@ -107,7 +106,7 @@ describeIfFerretDB('Migration anti-join → $nin - FerretDB compatibility', () =
_id: { $nin: migratedIds },
author: { $exists: true, $ne: null },
})
.select('_id id name author isCollaborative')
.select('_id id name author')
.lean();
expect(toMigrate).toHaveLength(2);
@ -197,7 +196,6 @@ describeIfFerretDB('Migration anti-join → $nin - FerretDB compatibility', () =
id: 'proj_agent',
name: 'Field Test',
author: 'user1',
isCollaborative: true,
});
const migratedIds = await AclEntry.distinct('resourceId', {
@ -209,7 +207,7 @@ describeIfFerretDB('Migration anti-join → $nin - FerretDB compatibility', () =
_id: { $nin: migratedIds },
author: { $exists: true, $ne: null },
})
.select('_id id name author isCollaborative')
.select('_id id name author')
.lean();
expect(toMigrate).toHaveLength(1);
@ -218,7 +216,6 @@ describeIfFerretDB('Migration anti-join → $nin - FerretDB compatibility', () =
expect(agent).toHaveProperty('id', 'proj_agent');
expect(agent).toHaveProperty('name', 'Field Test');
expect(agent).toHaveProperty('author', 'user1');
expect(agent).toHaveProperty('isCollaborative', true);
});
});

View file

@ -27,7 +27,6 @@ const promptGroupSchema = new Schema(
author: { type: Schema.Types.ObjectId, required: true, index: true },
authorName: { type: String, required: true },
command: { type: String },
projectIds: { type: [Schema.Types.ObjectId], default: [] },
},
{ timestamps: true },
);
@ -51,7 +50,6 @@ type PromptGroupDoc = mongoose.Document & {
oneliner: string;
numberOfGenerations: number;
command?: string;
projectIds: Types.ObjectId[];
createdAt: Date;
updatedAt: Date;
};
@ -226,7 +224,7 @@ describeIfFerretDB('Prompt $lookup replacement - FerretDB compatibility', () =>
.skip(skip)
.limit(limit)
.select(
'name numberOfGenerations oneliner category projectIds productionId author authorName createdAt updatedAt',
'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt',
)
.lean(),
PromptGroup.countDocuments(query),
@ -273,7 +271,7 @@ describeIfFerretDB('Prompt $lookup replacement - FerretDB compatibility', () =>
.sort({ updatedAt: -1, _id: 1 })
.limit(normalizedLimit + 1)
.select(
'name numberOfGenerations oneliner category projectIds productionId author authorName createdAt updatedAt',
'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt',
)
.lean();
@ -303,7 +301,7 @@ describeIfFerretDB('Prompt $lookup replacement - FerretDB compatibility', () =>
const groups = await PromptGroup.find({ _id: { $in: accessibleIds } })
.sort({ updatedAt: -1, _id: 1 })
.select(
'name numberOfGenerations oneliner category projectIds productionId author authorName createdAt updatedAt',
'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt',
)
.lean();
@ -326,7 +324,7 @@ describeIfFerretDB('Prompt $lookup replacement - FerretDB compatibility', () =>
const groups = await PromptGroup.find({})
.select(
'name numberOfGenerations oneliner category projectIds productionId author authorName createdAt updatedAt',
'name numberOfGenerations oneliner category productionId author authorName createdAt updatedAt',
)
.lean();
const result = await attachProductionPrompts(
@ -339,7 +337,6 @@ describeIfFerretDB('Prompt $lookup replacement - FerretDB compatibility', () =>
expect(item.numberOfGenerations).toBe(5);
expect(item.oneliner).toBe('A test prompt');
expect(item.category).toBe('testing');
expect(item.projectIds).toEqual([]);
expect(item.productionId).toBeDefined();
expect(item.author).toBeDefined();
expect(item.authorName).toBe('Test User');

View file

@ -37,7 +37,6 @@ const projectSchema = new Schema({
const agentSchema = new Schema({
name: { type: String, required: true },
projectIds: { type: [String], default: [] },
tool_resources: { type: Schema.Types.Mixed, default: {} },
});
@ -197,23 +196,6 @@ describeIfFerretDB('$pullAll FerretDB compatibility', () => {
expect(doc.agentIds).toEqual(['a2', 'a4']);
});
it('should remove projectIds from an agent', async () => {
await Agent.create({
name: 'Test Agent',
projectIds: ['p1', 'p2', 'p3'],
});
await Agent.findOneAndUpdate(
{ name: 'Test Agent' },
{ $pullAll: { projectIds: ['p1', 'p3'] } },
{ new: true },
);
const updated = await Agent.findOne({ name: 'Test Agent' }).lean();
const doc = updated as Record<string, unknown>;
expect(doc.projectIds).toEqual(['p2']);
});
it('should handle removing from nested dynamic paths (tool_resources)', async () => {
await Agent.create({
name: 'Resource Agent',

View file

@ -13,7 +13,6 @@ import { createActionModel } from './action';
import { createAssistantModel } from './assistant';
import { createFileModel } from './file';
import { createBannerModel } from './banner';
import { createProjectModel } from './project';
import { createKeyModel } from './key';
import { createPluginAuthModel } from './pluginAuth';
import { createTransactionModel } from './transaction';
@ -48,7 +47,6 @@ export function createModels(mongoose: typeof import('mongoose')) {
Assistant: createAssistantModel(mongoose),
File: createFileModel(mongoose),
Banner: createBannerModel(mongoose),
Project: createProjectModel(mongoose),
Key: createKeyModel(mongoose),
PluginAuth: createPluginAuthModel(mongoose),
Transaction: createTransactionModel(mongoose),

View file

@ -1,8 +0,0 @@
import projectSchema, { IMongoProject } from '~/schema/project';
/**
* Creates or returns the Project model using the provided mongoose instance and schema
*/
export function createProjectModel(mongoose: typeof import('mongoose')) {
return mongoose.models.Project || mongoose.model<IMongoProject>('Project', projectSchema);
}

View file

@ -76,10 +76,6 @@ const agentSchema = new Schema<IAgent>(
type: [{ type: Schema.Types.Mixed }],
default: [],
},
isCollaborative: {
type: Boolean,
default: undefined,
},
conversation_starters: {
type: [String],
default: [],
@ -88,11 +84,6 @@ const agentSchema = new Schema<IAgent>(
type: Schema.Types.Mixed,
default: {},
},
projectIds: {
type: [Schema.Types.ObjectId],
ref: 'Project',
index: true,
},
versions: {
type: [Schema.Types.Mixed],
default: [],

View file

@ -13,7 +13,6 @@ export { default as keySchema } from './key';
export { default as messageSchema } from './message';
export { default as pluginAuthSchema } from './pluginAuth';
export { default as presetSchema } from './preset';
export { default as projectSchema } from './project';
export { default as promptSchema } from './prompt';
export { default as promptGroupSchema } from './promptGroup';
export { default as roleSchema } from './role';

View file

@ -1,34 +0,0 @@
import { Schema, Document, Types } from 'mongoose';
export interface IMongoProject extends Document {
name: string;
promptGroupIds: Types.ObjectId[];
agentIds: string[];
createdAt?: Date;
updatedAt?: Date;
}
const projectSchema = new Schema<IMongoProject>(
{
name: {
type: String,
required: true,
index: true,
},
promptGroupIds: {
type: [Schema.Types.ObjectId],
ref: 'PromptGroup',
default: [],
},
agentIds: {
type: [String],
ref: 'Agent',
default: [],
},
},
{
timestamps: true,
},
);
export default projectSchema;

View file

@ -22,12 +22,6 @@ const promptGroupSchema = new Schema<IPromptGroupDocument>(
default: '',
index: true,
},
projectIds: {
type: [Schema.Types.ObjectId],
ref: 'Project',
index: true,
default: [],
},
productionId: {
type: Schema.Types.ObjectId,
ref: 'Prompt',

View file

@ -31,11 +31,8 @@ export interface IAgent extends Omit<Document, 'model'> {
/** @deprecated Use edges instead */
agent_ids?: string[];
edges?: GraphEdge[];
/** @deprecated Use ACL permissions instead */
isCollaborative?: boolean;
conversation_starters?: string[];
tool_resources?: unknown;
projectIds?: Types.ObjectId[];
versions?: Omit<IAgent, 'versions'>[];
category: string;
support_contact?: ISupportContact;

View file

@ -14,7 +14,6 @@ export interface IPromptGroup {
numberOfGenerations: number;
oneliner: string;
category: string;
projectIds: Types.ObjectId[];
productionId: Types.ObjectId;
author: Types.ObjectId;
authorName: string;