Skip to content

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

🩻 feat(insights): Scope Insights to Authorized Agents (#15549)

Ravi Kumar L000349681e4d
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index 65b85d5971..f366c6d253 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -1317,6 +1317,7 @@ class BaseClient {
context: 'api/app/clients/BaseClient.js - saveMessageToDatabase #saveConvo',
unsetFields,
noUpsert: req?._agentEventBindingParentConversationId != null,
+ initialAgentId: hasNonEphemeralAgent ? options.agent?.id : null,
createdAtOnInsert: shouldSetCreatedAtOnInsert ? validCreatedAtOnInsert : undefined,
...(savedMessage?._id != null ? { appendMessageIds: [savedMessage._id] } : {}),
});
diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.js
index 139e9e9518..92a96eb649 100644
--- a/api/app/clients/specs/BaseClient.test.js
+++ b/api/app/clients/specs/BaseClient.test.js
@@ -1944,6 +1944,11 @@ describe('BaseClient', () => {
test('saveMessageToDatabase uses snapshot of options, immune to mid-await disposal', async () => {
const savedOptions = TestClient.options;
+ TestClient.options = {
+ ...savedOptions,
+ endpoint: 'agents',
+ agent: { id: 'agent_persisted' },
+ };
saveMessage.mockClear();
saveConvo.mockClear();
@@ -1957,7 +1962,7 @@ describe('BaseClient', () => {
const result = await TestClient.saveMessageToDatabase(
{ messageId: 'msg-1', conversationId: 'conv-1', isCreatedByUser: true, text: 'hi' },
- { endpoint: 'openAI' },
+ { endpoint: 'agents', agent_id: 'agent_persisted' },
null,
);
@@ -1965,6 +1970,11 @@ describe('BaseClient', () => {
expect(result).toHaveProperty('message');
expect(result).toHaveProperty('conversation');
expect(saveMessage).toHaveBeenCalled();
+ expect(saveConvo).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ initialAgentId: 'agent_persisted' }),
+ );
TestClient.options = savedOptions;
saveMessage.mockReset();
diff --git a/api/server/controllers/PermissionsController.js b/api/server/controllers/PermissionsController.js
index d112904d7a..6bfe9028f9 100644
--- a/api/server/controllers/PermissionsController.js
+++ b/api/server/controllers/PermissionsController.js
@@ -5,9 +5,18 @@
const mongoose = require('mongoose');
const { logger, getTenantId, SYSTEM_TENANT_ID } = require('@librechat/data-schemas');
const { ResourceType, PrincipalType, PermissionBits } = require('librechat-data-provider');
-const { enrichRemoteAgentPrincipals, backfillRemoteAgentPermissions } = require('@librechat/api');
+const {
+ enrichRemoteAgentPrincipals,
+ backfillRemoteAgentPermissions,
+ auditInsightsPermissionChanges,
+ getInsightsPrincipalState,
+ maskAgentInsightsBit,
+ sanitizeInsightsPermissionPrincipals,
+ validateInsightsPermissionUpdates,
+} = require('@librechat/api');
const {
bulkUpdateResourcePermissions,
+ restoreInsightsPermissionChanges,
ensureGroupPrincipalExists,
getResourcePermissionsMap,
findAccessibleResources,
@@ -65,14 +74,24 @@ const updateResourcePermissions = async (req, res) => {
/** @type {TUpdateResourcePermissionsRequest} */
const { updated, removed, public: isPublic, publicAccessRoleId } = req.body;
const { id: userId } = req.user;
+ const updatedList = Array.isArray(updated) ? updated : [];
+ const removedList = Array.isArray(removed) ? removed : [];
+ const insightsValidation = validateInsightsPermissionUpdates({
+ resourceType,
+ userRole: req.user.role,
+ updatedPrincipals: updatedList,
+ });
+ if (insightsValidation) {
+ return res.status(insightsValidation.status).json({ error: insightsValidation.error });
+ }
// Prepare principals for the service call
const updatedPrincipals = [];
const revokedPrincipals = [];
// Add updated principals
- if (updated && Array.isArray(updated)) {
- updatedPrincipals.push(...updated);
+ if (updatedList.length > 0) {
+ updatedPrincipals.push(...updatedList);
}
// Add public permission if enabled
@@ -138,8 +157,8 @@ const updateResourcePermissions = async (req, res) => {
}
// Add removed principals
- if (removed && Array.isArray(removed)) {
- revokedPrincipals.push(...removed);
+ if (removedList.length > 0) {
+ revokedPrincipals.push(...removedList);
}
// If public is explicitly disabled, add public to revoked list
@@ -158,6 +177,24 @@ const updateResourcePermissions = async (req, res) => {
grantedBy: userId,
});
+ await auditInsightsPermissionChanges({
+ req,
+ resourceId,
+ changes: results.insightsChanges ?? [],
+ failClosed: process.env.AUDIT_LOG_FAIL_CLOSED === 'true',
+ deps: {
+ getAgent: db.getAgent,
+ recordAuditEntry: db.recordAuditEntry,
+ restoreInsightsPermissionChanges: (changes) =>
+ restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes,
+ }),
+ logger,
+ },
+ });
+
if (resourceType === ResourceType.CODE_ENVIRONMENT) {
await invalidateCodeEnvironmentConfigCache(req.user.tenantId).catch((error) => {
// Cached environment metadata is authorization-filtered against the live ACL on every
@@ -179,10 +216,15 @@ const updateResourcePermissions = async (req, res) => {
}
/** @type {TUpdateResourcePermissionsResponse} */
+ const responsePrincipals = sanitizeInsightsPermissionPrincipals({
+ resourceType,
+ userRole: req.user.role,
+ principals: results.granted,
+ });
const response = {
message: 'Permissions updated successfully',
results: {
- principals: results.granted,
+ principals: responsePrincipals,
...(isPublic !== undefined ? { public: isPublic } : {}),
publicAccessRoleId: isPublic ? publicAccessRoleId : undefined,
},
@@ -191,7 +233,7 @@ const updateResourcePermissions = async (req, res) => {
res.status(200).json(response);
} catch (error) {
logger.error('Error updating resource permissions:', error);
- res.status(400).json({
+ res.status(error.statusCode ?? 400).json({
error: 'Failed to update permissions',
details: error.message,
});
@@ -254,6 +296,7 @@ const getResourcePermissions = async (req, res) => {
accessRoleId: { $arrayElemAt: ['$role.accessRoleId', 0] },
userInfo: { $arrayElemAt: ['$userInfo', 0] },
groupInfo: { $arrayElemAt: ['$groupInfo', 0] },
+ permBits: 1,
},
},
]);
@@ -281,6 +324,12 @@ const getResourcePermissions = async (req, res) => {
source: !result.userInfo._id ? 'entra' : 'local',
idOnTheSource: result.userInfo.idOnTheSource || result.userInfo._id.toString(),
accessRoleId: result.accessRoleId,
+ ...getInsightsPrincipalState({
+ principalType: PrincipalType.USER,
+ principalRole: result.userInfo.role,
+ requesterRole: req.user.role,
+ permBits: result.permBits,
+ }),
});
} else if (
result.principalType === PrincipalType.GROUP &&
@@ -297,6 +346,11 @@ const getResourcePermissions = async (req, res) => {
source: result.groupInfo.source || 'local',
idOnTheSource: result.groupInfo.idOnTheSource || result.groupInfo._id.toString(),
accessRoleId: result.accessRoleId,
+ ...getInsightsPrincipalState({
+ principalType: PrincipalType.GROUP,
+ requesterRole: req.user.role,
+ permBits: result.permBits,
+ }),
});
} else if (result.principalType === PrincipalType.ROLE) {
principals.push({
@@ -307,6 +361,12 @@ const getResourcePermissions = async (req, res) => {
name: result.principalId,
description: `System role: ${result.principalId}`,
accessRoleId: result.accessRoleId,
+ ...getInsightsPrincipalState({
+ principalType: PrincipalType.ROLE,
+ principalRole: result.principalId,
+ requesterRole: req.user.role,
+ permBits: result.permBits,
+ }),
});
}
}
@@ -391,7 +451,11 @@ const getUserEffectivePermissions = async (req, res) => {
});
res.status(200).json({
- permissionBits,
+ permissionBits: maskAgentInsightsBit({
+ resourceType,
+ userRole: req.user.role,
+ permBits: permissionBits,
+ }),
});
} catch (error) {
logger.error('Error getting user effective permissions:', error);
@@ -556,7 +620,11 @@ const getAllEffectivePermissions = async (req, res) => {
// Convert Map to plain object for JSON response
const result = {};
for (const [resourceId, permBits] of permissionsMap) {
- result[resourceId] = permBits;
+ result[resourceId] = maskAgentInsightsBit({
+ resourceType,
+ userRole: req.user.role,
+ permBits,
+ });
}
res.status(200).json(result);
diff --git a/api/server/controllers/__tests__/PermissionsController.spec.js b/api/server/controllers/__tests__/PermissionsController.spec.js
index 95236f2ca3..2a578b75e7 100644
--- a/api/server/controllers/__tests__/PermissionsController.spec.js
+++ b/api/server/controllers/__tests__/PermissionsController.spec.js
@@ -9,17 +9,21 @@ jest.mock('@librechat/data-schemas', () => ({
SYSTEM_TENANT_ID: '__SYSTEM__',
}));
-const { AccessRoleIds, ResourceType, PrincipalType } =
+const { AccessRoleIds, ResourceType, PrincipalType, SystemRoles } =
jest.requireActual('librechat-data-provider');
jest.mock('librechat-data-provider', () => ({
...jest.requireActual('librechat-data-provider'),
}));
-jest.mock('@librechat/api', () => ({
- enrichRemoteAgentPrincipals: jest.fn(),
- backfillRemoteAgentPermissions: jest.fn(),
-}));
+jest.mock('@librechat/api', () => {
+ const actual = jest.requireActual('@librechat/api');
+ return {
+ ...actual,
+ enrichRemoteAgentPrincipals: jest.fn(),
+ backfillRemoteAgentPermissions: jest.fn(),
+ };
+});
const mockInvalidateCodeEnvironmentConfigCache = jest.fn().mockResolvedValue(undefined);
jest.mock('~/server/services/Config', () => ({
@@ -28,9 +32,11 @@ jest.mock('~/server/services/Config', () => ({
}));
const mockBulkUpdateResourcePermissions = jest.fn();
+const mockRestoreInsightsPermissionChanges = jest.fn();
jest.mock('~/server/services/PermissionService', () => ({
bulkUpdateResourcePermissions: (...args) => mockBulkUpdateResourcePermissions(...args),
+ restoreInsightsPermissionChanges: (...args) => mockRestoreInsightsPermissionChanges(...args),
ensureGroupPrincipalExists: jest.fn(),
getEffectivePermissions: jest.fn(),
ensurePrincipalExists: jest.fn(),
@@ -40,6 +46,7 @@ jest.mock('~/server/services/PermissionService', () => ({
}));
const mockRemoveAgentFromUserFavorites = jest.fn();
+const mockRecordAuditEntry = jest.fn();
jest.mock('~/models', () => ({
aggregateAclEntries: jest.fn(),
@@ -47,6 +54,8 @@ jest.mock('~/models', () => ({
sortPrincipalsByRelevance: jest.fn(),
calculateRelevanceScore: jest.fn(),
removeAgentFromUserFavorites: (...args) => mockRemoveAgentFromUserFavorites(...args),
+ getAgent: jest.fn(),
+ recordAuditEntry: (...args) => mockRecordAuditEntry(...args),
}));
jest.mock('~/server/services/GraphApiService', () => ({
@@ -221,6 +230,7 @@ describe('PermissionsController', () => {
name: 'Current User',
avatar: 'current-user.png',
+ role: SystemRoles.ADMIN,
},
},
{
@@ -247,6 +257,7 @@ describe('PermissionsController', () => {
type: PrincipalType.USER,
id: userId.toString(),
+ isAdmin: true,
}),
expect.objectContaining({
type: PrincipalType.GROUP,
@@ -262,6 +273,7 @@ describe('PermissionsController', () => {
const revokedUserId = new mongoose.Types.ObjectId().toString();
beforeEach(() => {
+ delete process.env.AUDIT_LOG_FAIL_CLOSED;
mockBulkUpdateResourcePermissions.mockResolvedValue({
granted: [],
updated: [],
@@ -270,6 +282,210 @@ describe('PermissionsController', () => {
});
mockRemoveAgentFromUserFavorites.mockResolvedValue(undefined);
+ db.getAgent.mockResolvedValue({ _id: agentObjectId, id: 'agent-a', name: 'Agent A' });
+ mockRecordAuditEntry.mockResolvedValue({});
+ mockRestoreInsightsPermissionChanges.mockResolvedValue(undefined);
+ });
+
+ it('rejects Insights permission changes from non-admin users', async () => {
+ const req = createMockReq({
+ params: { resourceType: ResourceType.AGENT, resourceId: agentObjectId },
+ body: {
+ updated: [
+ {
+ type: PrincipalType.ROLE,
+ id: 'USER',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ removed: [],
+ },
+ });
+ const res = createMockRes();
+
+ await updateResourcePermissions(req, res);
+
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(mockBulkUpdateResourcePermissions).not.toHaveBeenCalled();
+ });
+
+ it('rejects non-boolean Insights permission values', async () => {
+ const req = createMockReq({
+ params: { resourceType: ResourceType.AGENT, resourceId: agentObjectId },
+ body: {
+ updated: [
+ {
+ type: PrincipalType.ROLE,
+ id: 'USER',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: null,
+ },
+ ],
+ removed: [],
+ },
+ user: { id: 'admin-id', role: SystemRoles.ADMIN },
+ });
+ const res = createMockRes();
+
+ await updateResourcePermissions(req, res);
+
+ expect(res.status).toHaveBeenCalledWith(400);
+ expect(mockBulkUpdateResourcePermissions).not.toHaveBeenCalled();
+ });
+
+ it('audits each actual Insights access transition made by an admin', async () => {
+ mockBulkUpdateResourcePermissions.mockResolvedValue({
+ granted: [
+ {
+ type: PrincipalType.ROLE,
+ id: 'USER',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ updated: [],
+ revoked: [],
+ insightsChanges: [
+ { action: 'assigned', principal: { type: PrincipalType.ROLE, id: 'USER' } },
+ ],
+ errors: [],
+ });
+ const req = createMockReq({
+ params: { resourceType: ResourceType.AGENT, resourceId: agentObjectId },
+ body: {
+ updated: [
+ {
+ type: PrincipalType.ROLE,
+ id: 'USER',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ removed: [],
+ },
+ user: {
+ _id: new mongoose.Types.ObjectId(),
+ id: 'admin-id',
+ name: 'Admin',
+ role: SystemRoles.ADMIN,
+ tenantId: 'tenant-a',
+ },
+ });
+ const res = createMockRes();
+
+ await updateResourcePermissions(req, res);
+
+ expect(mockRecordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: 'permission.insights_assigned',
+ tenantId: 'tenant-a',
+ target: expect.objectContaining({ id: 'agent-a' }),
+ metadata: { principalType: PrincipalType.ROLE, principalId: 'USER' },
+ }),
+ { failClosed: false },
+ );
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json.mock.calls[0][0].results.principals[0]).toEqual(
+ expect.objectContaining({ viewInsights: true }),
+ );
+ });
+
+ it('restores unaudited Insights transitions when fail-closed auditing fails', async () => {
+ process.env.AUDIT_LOG_FAIL_CLOSED = 'true';
+ const changes = [{ action: 'assigned', principal: { type: PrincipalType.ROLE, id: 'USER' } }];
+ mockBulkUpdateResourcePermissions.mockResolvedValue({
+ granted: [],
+ updated: [],
+ revoked: [],
+ insightsChanges: changes,
+ errors: [],
+ });
+ mockRecordAuditEntry.mockRejectedValue(new Error('audit unavailable'));
+ const req = createMockReq({
+ params: { resourceType: ResourceType.AGENT, resourceId: agentObjectId },
+ body: {
+ updated: [
+ {
+ type: PrincipalType.ROLE,
+ id: 'USER',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ removed: [],
+ },
+ user: { id: 'admin-id', role: SystemRoles.ADMIN, tenantId: 'tenant-a' },
+ });
+ const res = createMockRes();
+
+ await updateResourcePermissions(req, res);
+
+ expect(mockRestoreInsightsPermissionChanges).toHaveBeenCalledWith({
+ resourceType: ResourceType.AGENT,
+ resourceId: agentObjectId,
+ changes,
+ });
+ expect(res.status).toHaveBeenCalledWith(500);
+ });
+
+ it('keeps a successful permission response when audit target lookup fails open', async () => {
+ mockBulkUpdateResourcePermissions.mockResolvedValue({
+ granted: [],
+ updated: [],
+ revoked: [],
+ insightsChanges: [
+ { action: 'assigned', principal: { type: PrincipalType.ROLE, id: 'USER' } },
+ ],
+ errors: [],
+ });
+ db.getAgent.mockRejectedValue(new Error('agent lookup unavailable'));
+ const req = createMockReq({
+ params: { resourceType: ResourceType.AGENT, resourceId: agentObjectId },
+ user: { id: 'admin-id', role: SystemRoles.ADMIN, tenantId: 'tenant-a' },
+ });
+ const res = createMockRes();
+
+ await updateResourcePermissions(req, res);
+
+ expect(mockRestoreInsightsPermissionChanges).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(200);
+ });
+
+ it('does not expose the protected bit in non-admin mutation responses', async () => {
+ mockBulkUpdateResourcePermissions.mockResolvedValue({
+ granted: [
+ {
+ type: PrincipalType.USER,
+ id: revokedUserId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ viewInsights: true,
+ },
+ ],
+ updated: [],
+ revoked: [],
+ insightsChanges: [],
+ errors: [],
+ });
+ const req = createMockReq({
+ params: { resourceType: ResourceType.AGENT, resourceId: agentObjectId },
+ body: {
+ updated: [
+ {
+ type: PrincipalType.USER,
+ id: revokedUserId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ },
+ ],
+ removed: [],
+ },
+ });
+ const res = createMockRes();
+
+ await updateResourcePermissions(req, res);
+
+ expect(res.status).toHaveBeenCalledWith(200);
+ expect(res.json.mock.calls[0][0].results.principals[0]).not.toHaveProperty('viewInsights');
});
it('removes agent from revoked users favorites on AGENT resource type', async () => {
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index fd49e3bfd4..a0891694cb 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -3610,9 +3610,11 @@ describe('ResumableAgentController resume metadata', () => {
const req = createFailedRequest({
conversationId: undefined,
clientRequestId: 'failed-new-conversation',
+ agent_id: 'unverified-agent',
parentMessageId: '00000000-0000-0000-0000-000000000000',
endpointOption: {
endpoint: 'azureOpenAI',
+ agent_id: 'unverified-agent',
modelOptions: { model: 'gpt-4o' },
chatProjectId: '507f1f77bcf86cd799439011',
},
@@ -3643,7 +3645,7 @@ describe('ResumableAgentController resume metadata', () => {
model: 'gpt-4o',
chatProjectId: '507f1f77bcf86cd799439011',
}),
- expect.any(Object),
+ expect.objectContaining({ initialAgentId: null }),
);
});
});
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index 7d9a22a908..b1bdd555cd 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -272,6 +272,7 @@ async function saveErrorTurn(
liveUserMessage,
liveResponseMessageId,
sender,
+ initialAgentId,
},
) {
try {
@@ -413,7 +414,15 @@ async function saveErrorTurn(
await saveConvo(
reqCtx,
{ conversationId, ...convoFields },
- seedConvo ? { context } : { context, noUpsert: true },
+ seedConvo
+ ? {
+ context,
+ initialAgentId:
+ typeof initialAgentId === 'string' && !isEphemeralAgentId(initialAgentId)
+ ? initialAgentId
+ : null,
+ }
+ : { context, noUpsert: true },
);
} catch (err) {
logger.error('[AgentController] Failed to persist error turn', err);
@@ -1371,6 +1380,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
});
let client = null;
+ let verifiedInitialAgentId = null;
let jobCreatedAt;
let providerExecutionId;
let releaseEventChildLease;
@@ -1763,6 +1773,12 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
});
startupTelemetry?.mark('client_initialized');
client = result.client;
+ if (
+ typeof client?.options?.agent?.id === 'string' &&
+ !isEphemeralAgentId(client.options.agent.id)
+ ) {
+ verifiedInitialAgentId = client.options.agent.id;
+ }
/** Request-shape validation rejects every known edit/regenerate path, but
* the client owns the final persistence decision. Fail closed if a future
@@ -2997,6 +3013,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
liveUserMessage: userMessage,
liveResponseMessageId,
sender: client?.sender,
+ initialAgentId: verifiedInitialAgentId,
}),
})) === true;
/** A true completion means this owner won the terminal CAS and
@@ -3201,6 +3218,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
endpointOption,
isNewConvo,
errorText: initializationError,
+ initialAgentId: verifiedInitialAgentId,
}),
})
: GenerationJobManager.completeJob(streamId, initializationError, jobCreatedAt);
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index 606f4733be..4903abf569 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -453,11 +453,14 @@ async function saveConversation(req, conversationId, agentId, agent) {
{
conversationId,
endpoint: EModelEndpoint.agents,
- agentId,
+ agent_id: agentId,
...(title != null && { title }),
model: agent?.model,
},
- { context: 'Responses API - save conversation' },
+ {
+ context: 'Responses API - save conversation',
+ initialAgentId: agent?.id === agentId ? agentId : null,
+ },
);
}
diff --git a/api/server/experimental.js b/api/server/experimental.js
index 78ed711a79..102c6bbfed 100644
--- a/api/server/experimental.js
+++ b/api/server/experimental.js
@@ -634,7 +634,7 @@ if (cluster.isMaster) {
/** Routes */
app.use('/oauth', preAuthTenantMiddleware, routes.oauth);
app.use('/api/auth', preAuthTenantMiddleware, routes.auth);
- app.use('/api/admin/insights', routes.insights);
+ app.use('/api/insights', routes.insights);
app.use('/api/admin', routes.adminAuth);
app.use('/api/admin/skills', routes.adminSkills);
app.use('/api/admin/code-environments', routes.adminCodeEnvironments);
diff --git a/api/server/index.js b/api/server/index.js
index 5d25eb248f..046004252d 100644
--- a/api/server/index.js
+++ b/api/server/index.js
@@ -380,7 +380,7 @@ const startServer = async () => {
app.use('/oauth', preAuthTenantMiddleware, routes.oauth);
/* API Endpoints */
app.use('/api/auth', preAuthTenantMiddleware, routes.auth);
- app.use('/api/admin/insights', routes.insights);
+ app.use('/api/insights', routes.insights);
app.use('/api/admin', routes.adminAuth);
app.use('/api/admin/config', routes.adminConfig);
app.use('/api/admin/code-environments', routes.adminCodeEnvironments);
diff --git a/api/server/middleware/checkPeoplePickerAccess.js b/api/server/middleware/checkPeoplePickerAccess.js
index 50f137285e..83329f56a3 100644
--- a/api/server/middleware/checkPeoplePickerAccess.js
+++ b/api/server/middleware/checkPeoplePickerAccess.js
@@ -1,5 +1,10 @@
const { logger } = require('@librechat/data-schemas');
-const { PrincipalType, PermissionTypes, Permissions } = require('librechat-data-provider');
+const {
+ PrincipalType,
+ PermissionTypes,
+ Permissions,
+ SystemRoles,
+} = require('librechat-data-provider');
const { getRoleByName } = require('~/models');
const VALID_PRINCIPAL_TYPES = new Set([
@@ -27,6 +32,10 @@ const checkPeoplePickerAccess = async (req, res, next) => {
});
}
+ if (user.role === SystemRoles.ADMIN) {
+ return next();
+ }
+
const role = await getRoleByName(user.role);
if (!role || !role.permissions) {
return res.status(403).json({
diff --git a/api/server/middleware/checkPeoplePickerAccess.spec.js b/api/server/middleware/checkPeoplePickerAccess.spec.js
index c394bbae65..45097ef290 100644
--- a/api/server/middleware/checkPeoplePickerAccess.spec.js
+++ b/api/server/middleware/checkPeoplePickerAccess.spec.js
@@ -1,5 +1,10 @@
const { logger } = require('@librechat/data-schemas');
-const { PrincipalType, PermissionTypes, Permissions } = require('librechat-data-provider');
+const {
+ PrincipalType,
+ PermissionTypes,
+ Permissions,
+ SystemRoles,
+} = require('librechat-data-provider');
const { checkPeoplePickerAccess } = require('./checkPeoplePickerAccess');
const { getRoleByName } = require('~/models');
@@ -53,6 +58,16 @@ describe('checkPeoplePickerAccess', () => {
expect(next).not.toHaveBeenCalled();
});
+ it('allows a literal admin regardless of configured people picker permissions', async () => {
+ req.user.role = SystemRoles.ADMIN;
+
+ await checkPeoplePickerAccess(req, res, next);
+
+ expect(next).toHaveBeenCalled();
+ expect(getRoleByName).not.toHaveBeenCalled();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
it('should allow access when searching for users with VIEW_USERS permission', async () => {
req.query.type = PrincipalType.USER;
getRoleByName.mockResolvedValue({
diff --git a/api/server/routes/__tests__/insights.spec.js b/api/server/routes/__tests__/insights.spec.js
index 3f754eb0e8..e173cb23eb 100644
--- a/api/server/routes/__tests__/insights.spec.js
+++ b/api/server/routes/__tests__/insights.spec.js
@@ -3,21 +3,27 @@ const request = require('supertest');
const mockCreateInsightsAccessHandler = jest.fn(() => (_req, res) => res.json({ access: true }));
const mockCreateInsightsHandler = jest.fn(() => (_req, res) => res.json({ summary: {} }));
-const mockGrantedCapabilities = new Set(['access:admin', 'read:insights']);
+const mockGetAccessibleAgents = jest.fn();
const mockGetInsights = jest.fn();
-let mockUser = { id: 'admin-id', role: 'ADMIN' };
+let mockResolverCreateCount = 0;
+let mockAccessHandlerDeps;
+let mockDashboardHandlerDeps;
+let mockUser = { id: 'user-id', role: 'USER' };
jest.mock('@librechat/api', () => ({
- createInsightsAccessHandler: (...args) => mockCreateInsightsAccessHandler(...args),
- createInsightsHandler: (...args) => mockCreateInsightsHandler(...args),
- isEnabled: (value) => value === 'true',
-}));
-
-jest.mock('@librechat/data-schemas', () => ({
- SystemCapabilities: {
- ACCESS_ADMIN: 'access:admin',
- READ_INSIGHTS: 'read:insights',
+ createInsightsAccessHandler: (...args) => {
+ [mockAccessHandlerDeps] = args;
+ return mockCreateInsightsAccessHandler(...args);
+ },
+ createInsightsAgentAccessResolver: () => {
+ mockResolverCreateCount += 1;
+ return mockGetAccessibleAgents;
+ },
+ createInsightsHandler: (...args) => {
+ [mockDashboardHandlerDeps] = args;
+ return mockCreateInsightsHandler(...args);
},
+ isEnabled: (value) => value === 'true',
}));
jest.mock('~/server/middleware', () => ({
@@ -25,69 +31,49 @@ jest.mock('~/server/middleware', () => ({
req.user = mockUser;
next();
},
- checkAdmin: (req, res, next) => {
- if (req.user.role !== 'ADMIN') {
- return res.status(403).json({ message: 'Forbidden' });
- }
- next();
- },
-}));
-
-jest.mock('~/server/middleware/roles/capabilities', () => ({
- requireCapability: (capability) => (_req, res, next) => {
- if (!mockGrantedCapabilities.has(capability)) {
- return res.status(403).json({ message: 'Forbidden' });
- }
- next();
- },
}));
jest.mock('~/models', () => ({
+ findAccessibleResources: jest.fn(),
+ getAgents: jest.fn(),
getInsights: (...args) => mockGetInsights(...args),
+ getUserPrincipals: jest.fn(),
+ hasCapabilityForPrincipals: jest.fn(),
}));
const insightsRouter = require('../insights');
function createApp() {
const app = express();
- app.use('/api/admin/insights', insightsRouter);
+ app.use('/api/insights', insightsRouter);
return app;
}
describe('Insights routes', () => {
beforeEach(() => {
- mockUser = { id: 'admin-id', role: 'ADMIN' };
- mockGrantedCapabilities.clear();
- mockGrantedCapabilities.add('access:admin');
- mockGrantedCapabilities.add('read:insights');
+ mockUser = { id: 'user-id', role: 'USER' };
});
- it('requires the ADMIN role', async () => {
- mockUser = { id: 'delegated-admin-id', role: 'DELEGATED_ADMIN' };
-
- const response = await request(createApp()).get('/api/admin/insights');
-
- expect(response.status).toBe(403);
- });
-
- it('serves the access probe and dashboard', async () => {
+ it('serves the access probe and dashboard for authenticated users', async () => {
const app = createApp();
- await expect(request(app).get('/api/admin/insights/access')).resolves.toMatchObject({
+ await expect(request(app).get('/api/insights/access')).resolves.toMatchObject({
status: 200,
body: { access: true },
});
- await expect(request(app).get('/api/admin/insights')).resolves.toMatchObject({
+ await expect(request(app).get('/api/insights')).resolves.toMatchObject({
status: 200,
body: { summary: {} },
});
});
- it.each(['access:admin', 'read:insights'])('requires %s', async (capability) => {
- mockGrantedCapabilities.delete(capability);
-
- const response = await request(createApp()).get('/api/admin/insights');
-
- expect(response.status).toBe(403);
+ it('uses one shared agent access resolver for both handlers', () => {
+ expect(mockResolverCreateCount).toBe(1);
+ expect(mockAccessHandlerDeps).toEqual(
+ expect.objectContaining({ getAccessibleAgents: mockGetAccessibleAgents }),
+ );
+ expect(mockDashboardHandlerDeps).toEqual(
+ expect.objectContaining({ getAccessibleAgents: mockGetAccessibleAgents }),
+ );
});
});
diff --git a/api/server/routes/accessPermissions.js b/api/server/routes/accessPermissions.js
index 311f059300..96aa8c8a3e 100644
--- a/api/server/routes/accessPermissions.js
+++ b/api/server/routes/accessPermissions.js
@@ -6,6 +6,7 @@ const {
ResourceType,
PermissionBits,
} = require('librechat-data-provider');
+const { createAgentAdminPermissionAccess, isAgentPermissionsAdmin } = require('@librechat/api');
const {
getUserEffectivePermissions,
getAllEffectivePermissions,
@@ -20,7 +21,8 @@ const {
} = require('~/server/middleware/checkSharePublicAccess');
const { requireJwtAuth, checkBan, uaParser, canAccessResource } = require('~/server/middleware');
const { checkPeoplePickerAccess } = require('~/server/middleware/checkPeoplePickerAccess');
-const { findMCPServerByObjectId, getSkillById } = require('~/models');
+const db = require('~/models');
+const { findMCPServerByObjectId, getSkillById } = db;
const router = express.Router();
@@ -52,63 +54,74 @@ router.get('/:resourceType/roles', getResourceRoles);
* @param {string} requiredPermission - The permission bit required (e.g., SHARE)
* @returns Express middleware function
*/
-const checkResourcePermissionAccess = (requiredPermission) => (req, res, next) => {
- const { resourceType } = req.params;
- let middleware;
-
- if (resourceType === ResourceType.AGENT) {
- middleware = canAccessResource({
- resourceType: ResourceType.AGENT,
- requiredPermission,
- resourceIdParam: 'resourceId',
- });
- } else if (resourceType === ResourceType.REMOTE_AGENT) {
- middleware = canAccessResource({
- resourceType: ResourceType.REMOTE_AGENT,
- requiredPermission,
- resourceIdParam: 'resourceId',
- });
- } else if (resourceType === ResourceType.PROMPTGROUP) {
- middleware = canAccessResource({
- resourceType: ResourceType.PROMPTGROUP,
- requiredPermission,
- resourceIdParam: 'resourceId',
- });
- } else if (resourceType === ResourceType.MCPSERVER) {
- middleware = canAccessResource({
- resourceType: ResourceType.MCPSERVER,
- requiredPermission,
- resourceIdParam: 'resourceId',
- idResolver: findMCPServerByObjectId,
- });
- } else if (resourceType === ResourceType.SKILL) {
- middleware = canAccessResource({
- resourceType: ResourceType.SKILL,
- requiredPermission,
- resourceIdParam: 'resourceId',
- idResolver: getSkillById,
- });
- } else if (resourceType === ResourceType.CODE_ENVIRONMENT) {
- middleware = canAccessResource({
- resourceType: ResourceType.CODE_ENVIRONMENT,
- requiredPermission,
- resourceIdParam: 'resourceId',
- });
- } else if (resourceType === ResourceType.SHARED_LINK) {
- middleware = canAccessResource({
- resourceType: ResourceType.SHARED_LINK,
- requiredPermission,
- resourceIdParam: 'resourceId',
- });
- } else {
- return res.status(400).json({
- error: 'Bad Request',
- message: `Unsupported resource type: ${resourceType}`,
- });
+const checkResourcePermissionAccess = (requiredPermission) =>
+ createAgentAdminPermissionAccess({
+ getAgent: db.getAgent,
+ fallback: (req, res, next) => {
+ const { resourceType } = req.params;
+ let middleware;
+
+ if (resourceType === ResourceType.AGENT) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.AGENT,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ });
+ } else if (resourceType === ResourceType.REMOTE_AGENT) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.REMOTE_AGENT,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ });
+ } else if (resourceType === ResourceType.PROMPTGROUP) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.PROMPTGROUP,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ });
+ } else if (resourceType === ResourceType.MCPSERVER) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.MCPSERVER,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ idResolver: findMCPServerByObjectId,
+ });
+ } else if (resourceType === ResourceType.SKILL) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.SKILL,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ idResolver: getSkillById,
+ });
+ } else if (resourceType === ResourceType.CODE_ENVIRONMENT) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.CODE_ENVIRONMENT,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ });
+ } else if (resourceType === ResourceType.SHARED_LINK) {
+ middleware = canAccessResource({
+ resourceType: ResourceType.SHARED_LINK,
+ requiredPermission,
+ resourceIdParam: 'resourceId',
+ });
+ } else {
+ return res.status(400).json({
+ error: 'Bad Request',
+ message: `Unsupported resource type: ${resourceType}`,
+ });
+ }
+
+ // Execute the middleware
+ middleware(req, res, next);
+ },
+ });
+
+const checkShareAccessUnlessAgentAdmin = (req, res, next) => {
+ if (isAgentPermissionsAdmin(req)) {
+ return next();
}
-
- // Execute the middleware
- middleware(req, res, next);
+ return checkShareAccess(req, res, next);
};
const rejectSharedLinkOwnerPermissionChanges = async (req, res, next) => {
@@ -182,7 +195,7 @@ router.get(
router.put(
'/:resourceType/:resourceId',
checkResourcePermissionAccess(PermissionBits.SHARE),
- checkShareAccess,
+ checkShareAccessUnlessAgentAdmin,
checkSharePublicAccess,
rejectSharedLinkOwnerPermissionChanges,
updateResourcePermissions,
diff --git a/api/server/routes/insights.js b/api/server/routes/insights.js
index 2f58bb82df..6f0e13c9ae 100644
--- a/api/server/routes/insights.js
+++ b/api/server/routes/insights.js
@@ -1,17 +1,27 @@
const express = require('express');
-const { createInsightsAccessHandler, createInsightsHandler, isEnabled } = require('@librechat/api');
-const { SystemCapabilities } = require('@librechat/data-schemas');
-const { requireJwtAuth, checkAdmin } = require('~/server/middleware');
-const { requireCapability } = require('~/server/middleware/roles/capabilities');
+const {
+ createInsightsAccessHandler,
+ createInsightsAgentAccessResolver,
+ createInsightsHandler,
+ isEnabled,
+} = require('@librechat/api');
+const { requireJwtAuth } = require('~/server/middleware');
const db = require('~/models');
const router = express.Router();
-const requireAdminAccess = requireCapability(SystemCapabilities.ACCESS_ADMIN);
-const requireInsightsAccess = requireCapability(SystemCapabilities.READ_INSIGHTS);
const isInsightsEnabled = () => isEnabled(process.env.ENABLE_INSIGHTS);
+const getAccessibleAgents = createInsightsAgentAccessResolver({
+ getAgents: db.getAgents,
+ getUserPrincipals: db.getUserPrincipals,
+ hasCapabilityForPrincipals: db.hasCapabilityForPrincipals,
+ findAccessibleResources: db.findAccessibleResources,
+});
-router.use(requireJwtAuth, checkAdmin, requireAdminAccess, requireInsightsAccess);
-router.get('/access', createInsightsAccessHandler({ isInsightsEnabled }));
-router.get('/', createInsightsHandler({ isInsightsEnabled, getInsights: db.getInsights }));
+router.use(requireJwtAuth);
+router.get('/access', createInsightsAccessHandler({ isInsightsEnabled, getAccessibleAgents }));
+router.get(
+ '/',
+ createInsightsHandler({ isInsightsEnabled, getAccessibleAgents, getInsights: db.getInsights }),
+);
module.exports = router;
diff --git a/api/server/services/PermissionService.js b/api/server/services/PermissionService.js
index 7d166505ca..41533ee0f2 100644
--- a/api/server/services/PermissionService.js
+++ b/api/server/services/PermissionService.js
@@ -1,13 +1,12 @@
const mongoose = require('mongoose');
-const { isEnabled } = require('@librechat/api');
+const { AccessControlService, isEnabled } = require('@librechat/api');
const {
- getTransactionSupport,
tenantStorage,
getTenantId,
logger,
runAfterTransaction,
} = require('@librechat/data-schemas');
-const { ResourceType, PrincipalType, PrincipalModel } = require('librechat-data-provider');
+const { ResourceType, PrincipalType } = require('librechat-data-provider');
const {
entraIdPrincipalFeatureEnabled,
getUserOwnedEntraGroups,
@@ -18,9 +17,6 @@ const {
} = require('~/server/services/GraphApiService');
const db = require('~/models');
-/** @type {boolean|null} */
-let transactionSupportCache = null;
-
/**
* Validates that the resourceType is one of the supported enum values
* @param {string} resourceType - The resource type to validate
@@ -711,256 +707,12 @@ const hasPublicPermission = async ({ resourceType, resourceId, requiredPermissio
}
};
-/**
- * Bulk update permissions for a resource (grant, update, revoke)
- * Efficiently handles multiple permission changes in a single transaction
- *
- * @param {Object} params - Parameters for bulk permission update
- * @param {string} params.resourceType - Type of resource (e.g., 'agent')
- * @param {string|mongoose.Types.ObjectId} params.resourceId - The ID of the resource
- * @param {Array<TPrincipal>} params.updatedPrincipals - Array of principals to grant/update permissions for
- * @param {Array<TPrincipal>} params.revokedPrincipals - Array of principals to revoke permissions from
- * @param {string|mongoose.Types.ObjectId} params.grantedBy - User ID making the changes
- * @param {mongoose.ClientSession} [params.session] - Optional MongoDB session for transactions
- * @returns {Promise<Object>} Results object with granted, updated, revoked arrays and error details
- */
-const bulkUpdateResourcePermissions = async ({
- resourceType,
- resourceId,
- updatedPrincipals = [],
- revokedPrincipals = [],
- grantedBy,
- session,
-}) => {
- const supportsTransactions = await getTransactionSupport(mongoose, transactionSupportCache);
- transactionSupportCache = supportsTransactions;
- let localSession = session;
- let shouldEndSession = false;
-
- try {
- if (!Array.isArray(updatedPrincipals)) {
- throw new Error('updatedPrincipals must be an array');
- }
-
- if (!Array.isArray(revokedPrincipals)) {
- throw new Error('revokedPrincipals must be an array');
- }
-
- if (!resourceId || !mongoose.Types.ObjectId.isValid(resourceId)) {
- throw new Error(`Invalid resource ID: ${resourceId}`);
- }
-
- if (!localSession && supportsTransactions) {
- localSession = await mongoose.startSession();
- localSession.startTransaction();
- shouldEndSession = true;
- }
-
- const sessionOptions = localSession ? { session: localSession } : {};
-
- const roles = await db.findRolesByResourceType(resourceType);
- const rolesMap = new Map();
- roles.forEach((role) => {
- rolesMap.set(role.accessRoleId, role);
- });
-
- const results = {
- granted: [],
- updated: [],
- revoked: [],
- errors: [],
- };
-
- const bulkWrites = [];
-
- /**
- * Tracks non-public principals granted in this same request so their revoke is skipped below.
- * Grants are flushed before deletes, so a principal present in both `updatedPrincipals` and
- * `revokedPrincipals` would be upserted and then deleted, stripping access the caller just set
- * (e.g. a resource owner landing in both lists from a client `id`/`idOnTheSource` mismatch).
- * Granting wins to make owner lockout impossible regardless of the client-side diff (#14316).
- *
- * PUBLIC is deliberately excluded: an explicit `public: false` disable adds the public principal
- * to the revoke list, and disabling public access must always win over a stale/contradictory
- * grant so a resource is never left public when the caller asked to make it private.
- */
- const grantedPrincipalKeys = new Set();
- const principalKey = (principal) => `${principal.type}:${principal.id}`;
-
- for (const principal of updatedPrincipals) {
- try {
- if (!principal.accessRoleId) {
- results.errors.push({
- principal,
- error: 'accessRoleId is required for updated principals',
- });
- continue;
- }
-
- const role = rolesMap.get(principal.accessRoleId);
- if (!role) {
- results.errors.push({
- principal,
- error: `Role ${principal.accessRoleId} not found`,
- });
- continue;
- }
-
- const query = {
- principalType: principal.type,
- resourceType,
- resourceId,
- };
-
- if (principal.type !== PrincipalType.PUBLIC) {
- query.principalId =
- principal.type === PrincipalType.ROLE
- ? principal.id
- : new mongoose.Types.ObjectId(principal.id);
- }
-
- const principalModelMap = {
- [PrincipalType.USER]: PrincipalModel.USER,
- [PrincipalType.GROUP]: PrincipalModel.GROUP,
- [PrincipalType.ROLE]: PrincipalModel.ROLE,
- };
-
- const update = {
- $set: {
- permBits: role.permBits,
- roleId: role._id,
- grantedBy,
- grantedAt: new Date(),
- },
- $setOnInsert: {
- principalType: principal.type,
- resourceType,
- resourceId,
- ...(principal.type !== PrincipalType.PUBLIC && {
- principalId:
- principal.type === PrincipalType.ROLE
- ? principal.id
- : new mongoose.Types.ObjectId(principal.id),
- principalModel: principalModelMap[principal.type],
- }),
- },
- };
-
- bulkWrites.push({
- updateOne: {
- filter: query,
- update: update,
- upsert: true,
- },
- });
-
- results.granted.push({
- type: principal.type,
- id: principal.id,
- name: principal.name,
- email: principal.email,
- source: principal.source,
- avatar: principal.avatar,
- description: principal.description,
- idOnTheSource: principal.idOnTheSource,
- accessRoleId: principal.accessRoleId,
- memberCount: principal.memberCount,
- memberIds: principal.memberIds,
- });
- if (principal.type !== PrincipalType.PUBLIC) {
- grantedPrincipalKeys.add(principalKey(principal));
- }
- } catch (error) {
- results.errors.push({
- principal,
- error: error.message,
- });
- }
- }
-
- if (bulkWrites.length > 0) {
- await db.bulkWriteAclEntries(bulkWrites, sessionOptions);
- }
-
- const deleteQueries = [];
- for (const principal of revokedPrincipals) {
- try {
- // Inside the try so a malformed revoke entry (e.g. a nullish principal) is recorded in
- // results.errors and skipped, rather than throwing out after grants were already flushed.
- if (
- principal.type !== PrincipalType.PUBLIC &&
- grantedPrincipalKeys.has(principalKey(principal))
- ) {
- continue;
- }
- const query = {
- principalType: principal.type,
- resourceType,
- resourceId,
- };
-
- if (principal.type !== PrincipalType.PUBLIC) {
- query.principalId =
- principal.type === PrincipalType.ROLE
- ? principal.id
- : new mongoose.Types.ObjectId(principal.id);
- }
-
- deleteQueries.push(query);
-
- results.revoked.push({
- type: principal.type,
- id: principal.id,
- name: principal.name,
- email: principal.email,
- source: principal.source,
- avatar: principal.avatar,
- description: principal.description,
- idOnTheSource: principal.idOnTheSource,
- memberCount: principal.memberCount,
- });
- } catch (error) {
- results.errors.push({
- principal,
- error: error.message,
- });
- }
- }
-
- if (deleteQueries.length > 0) {
- await db.deleteAclEntries({ $or: deleteQueries }, sessionOptions);
- }
-
- if (shouldEndSession && supportsTransactions) {
- await localSession.commitTransaction();
- }
-
- if (resourceType === ResourceType.PROMPTGROUP) {
- /** The caller's session may still be uncommitted; defer until it commits */
- await runAfterTransaction(localSession, () => db.invalidatePromptGroupAccessContext());
- }
-
- return results;
- } catch (error) {
- if (shouldEndSession && supportsTransactions) {
- try {
- await localSession.abortTransaction();
- } catch (transactionError) {
- /** best-effort abort; may fail if commit already succeeded */
- logger.error(
- `[PermissionService.bulkUpdateResourcePermissions] Error aborting transaction:`,
- transactionError,
- );
- }
- }
- logger.error(`[PermissionService.bulkUpdateResourcePermissions] Error: ${error.message}`);
- throw error;
- } finally {
- if (shouldEndSession && localSession) {
- localSession.endSession();
- }
- }
-};
+/** Typed implementation; this legacy module only binds the shared model methods. */
+const accessControlService = new AccessControlService(mongoose, db);
+const bulkUpdateResourcePermissions = (params) =>
+ accessControlService.bulkUpdateResourcePermissions(params);
+const restoreInsightsPermissionChanges = (params) =>
+ accessControlService.restoreInsightsPermissionChanges(params);
/**
* Remove all permissions for a resource (cleanup when resource is deleted)
@@ -1003,6 +755,7 @@ module.exports = {
hasPublicPermission,
getAvailableRoles,
bulkUpdateResourcePermissions,
+ restoreInsightsPermissionChanges,
ensurePrincipalExists,
ensureGroupPrincipalExists,
syncUserEntraGroupMemberships,
diff --git a/api/server/services/PermissionService.spec.js b/api/server/services/PermissionService.spec.js
index 7729412c91..65680249d7 100644
--- a/api/server/services/PermissionService.spec.js
+++ b/api/server/services/PermissionService.spec.js
@@ -6,9 +6,11 @@ const {
AccessRoleIds,
PrincipalType,
PrincipalModel,
+ PermissionBits,
} = require('librechat-data-provider');
const {
bulkUpdateResourcePermissions,
+ restoreInsightsPermissionChanges,
syncUserEntraGroupMemberships,
getEffectivePermissions,
findAccessibleResources,
@@ -18,7 +20,8 @@ const {
ensurePrincipalExists,
ensureGroupPrincipalExists,
} = require('./PermissionService');
-const { findRoleByIdentifier, getUserPrincipals, seedDefaultRoles } = require('~/models');
+const db = require('~/models');
+const { findRoleByIdentifier, getUserPrincipals, seedDefaultRoles } = db;
// Mock the getTransactionSupport function for testing
jest.mock('@librechat/data-schemas', () => ({
@@ -881,6 +884,442 @@ describe('PermissionService', () => {
expect(groupEntry.roleId.accessRoleId).toBe(AccessRoleIds.AGENT_OWNER);
});
+ test('adds, preserves, and removes agent Insights access independently of the role', async () => {
+ const grantResult = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+
+ let entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ });
+ expect(entry.permBits & PermissionBits.VIEW_INSIGHTS).toBe(PermissionBits.VIEW_INSIGHTS);
+ expect(grantResult.insightsChanges).toEqual([
+ expect.objectContaining({ action: 'assigned' }),
+ ]);
+
+ const roleResult = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ });
+ expect(entry.permBits & PermissionBits.VIEW_INSIGHTS).toBe(PermissionBits.VIEW_INSIGHTS);
+ expect(roleResult.insightsChanges).toEqual([]);
+
+ const revokeResult = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ viewInsights: false,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ });
+ expect(entry.permBits & PermissionBits.VIEW_INSIGHTS).toBe(0);
+ expect(revokeResult.insightsChanges).toEqual([
+ expect.objectContaining({ action: 'removed' }),
+ ]);
+ });
+
+ test.each([
+ {
+ updates: [true, false],
+ expectedInsights: 0,
+ expectedChanges: [],
+ },
+ {
+ updates: [false, true],
+ expectedInsights: PermissionBits.VIEW_INSIGHTS,
+ expectedChanges: [expect.objectContaining({ action: 'assigned' })],
+ },
+ ])(
+ 'uses the last Insights value for duplicate principal updates',
+ async ({ updates, expectedInsights, expectedChanges }) => {
+ const results = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: updates.map((viewInsights) => ({
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights,
+ })),
+ grantedBy: grantedById,
+ });
+
+ const entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ });
+ expect(entry.permBits & PermissionBits.VIEW_INSIGHTS).toBe(expectedInsights);
+ expect(results.granted).toHaveLength(1);
+ expect(results.insightsChanges).toEqual(expectedChanges);
+ },
+ );
+
+ test.each([
+ {
+ concurrentChange: 'grant',
+ initialInsights: false,
+ concurrentBitUpdate: { or: PermissionBits.VIEW_INSIGHTS },
+ expectedInsights: PermissionBits.VIEW_INSIGHTS,
+ },
+ {
+ concurrentChange: 'revocation',
+ initialInsights: true,
+ concurrentBitUpdate: { and: ~PermissionBits.VIEW_INSIGHTS },
+ expectedInsights: 0,
+ },
+ ])(
+ 'atomically preserves a concurrent Insights $concurrentChange during a role-only update',
+ async ({ initialInsights, concurrentBitUpdate, expectedInsights }) => {
+ if (initialInsights) {
+ await AclEntry.updateOne(
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ },
+ { $bit: { permBits: { or: PermissionBits.VIEW_INSIGHTS } } },
+ );
+ }
+
+ const originalBulkWriteAclEntries = db.bulkWriteAclEntries;
+ const bulkWriteSpy = jest
+ .spyOn(db, 'bulkWriteAclEntries')
+ .mockImplementationOnce(async (...args) => {
+ await AclEntry.updateOne(
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ },
+ { $bit: { permBits: concurrentBitUpdate } },
+ );
+ return originalBulkWriteAclEntries(...args);
+ });
+
+ try {
+ await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ } finally {
+ bulkWriteSpy.mockRestore();
+ }
+
+ const entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).populate('roleId', 'accessRoleId');
+ expect(entry.roleId.accessRoleId).toBe(AccessRoleIds.AGENT_EDITOR);
+ expect(entry.permBits & PermissionBits.VIEW_INSIGHTS).toBe(expectedInsights);
+ },
+ );
+
+ test('removes a stale-read upsert after a concurrent deletion and audit failure', async () => {
+ const originalBulkWriteAclEntries = db.bulkWriteAclEntries;
+ const bulkWriteSpy = jest
+ .spyOn(db, 'bulkWriteAclEntries')
+ .mockImplementationOnce(async (...args) => {
+ await AclEntry.deleteOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ });
+ return originalBulkWriteAclEntries(...args);
+ });
+
+ let result;
+ try {
+ result = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ } finally {
+ bulkWriteSpy.mockRestore();
+ }
+
+ expect(result.insightsChanges[0].previousEntry).toBeNull();
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ await expect(
+ AclEntry.exists({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }),
+ ).resolves.toBeNull();
+ });
+
+ test('restores the prior ACL document after an Insights audit failure', async () => {
+ const before = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ const result = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ const restored = await AclEntry.findById(before._id).lean();
+ expect(restored).toEqual(before);
+ });
+
+ test('does not overwrite or resurrect an ACL document changed after the audited update', async () => {
+ const result = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ const change = result.insightsChanges[0];
+ const ownerRole = await findRoleByIdentifier(AccessRoleIds.AGENT_OWNER);
+ const newerGrantedAt = new Date(change.writtenEntry.grantedAt.getTime() + 1000);
+
+ await AclEntry.updateOne(
+ { _id: change.previousEntry._id },
+ {
+ $set: {
+ permBits: ownerRole.permBits,
+ roleId: ownerRole._id,
+ grantedBy: otherUserId,
+ grantedAt: newerGrantedAt,
+ },
+ },
+ );
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ let current = await AclEntry.findById(change.previousEntry._id).lean();
+ expect(current.permBits).toBe(ownerRole.permBits);
+ expect(current.grantedAt).toEqual(newerGrantedAt);
+
+ await AclEntry.deleteOne({ _id: change.previousEntry._id });
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ current = await AclEntry.findById(change.previousEntry._id).lean();
+ expect(current).toBeNull();
+ });
+
+ test('removes a new ACL document after an Insights audit failure', async () => {
+ const result = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: otherUserId,
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ await expect(
+ AclEntry.exists({
+ principalType: PrincipalType.USER,
+ principalId: otherUserId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }),
+ ).resolves.toBeNull();
+ });
+
+ test('does not remove a new ACL document changed after the audited insert', async () => {
+ const result = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: otherUserId,
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ const change = result.insightsChanges[0];
+ const editorRole = await findRoleByIdentifier(AccessRoleIds.AGENT_EDITOR);
+ const newerGrantedAt = new Date(change.writtenEntry.grantedAt.getTime() + 1000);
+
+ await AclEntry.updateOne(
+ {
+ principalType: PrincipalType.USER,
+ principalId: otherUserId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ },
+ {
+ $set: {
+ permBits: editorRole.permBits,
+ roleId: editorRole._id,
+ grantedAt: newerGrantedAt,
+ },
+ },
+ );
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ const current = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: otherUserId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ expect(current.permBits).toBe(editorRole.permBits);
+ expect(current.grantedAt).toEqual(newerGrantedAt);
+ });
+
+ test('does not replace a newer ACL grant when restoring an audited deletion', async () => {
+ await AclEntry.updateOne(
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ },
+ { $bit: { permBits: { or: PermissionBits.VIEW_INSIGHTS } } },
+ );
+ const result = await bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ revokedPrincipals: [{ type: PrincipalType.USER, id: userId }],
+ grantedBy: grantedById,
+ });
+
+ await grantPermission({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ accessRoleId: AccessRoleIds.AGENT_EDITOR,
+ grantedBy: otherUserId,
+ });
+ await restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ const entries = await AclEntry.find({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ })
+ .populate('roleId', 'accessRoleId')
+ .lean();
+ expect(entries).toHaveLength(1);
+ expect(entries[0].roleId.accessRoleId).toBe(AccessRoleIds.AGENT_EDITOR);
+ });
+
test('should revoke specified permissions', async () => {
const revokedPrincipals = [
{
diff --git a/client/src/common/types.ts b/client/src/common/types.ts
index 1249bab3a2..eb3f0199ae 100644
--- a/client/src/common/types.ts
+++ b/client/src/common/types.ts
@@ -110,6 +110,7 @@ export type NavLink = {
Component?: React.ComponentType;
onClick?: (e?: React.MouseEvent) => void;
variant?: 'default' | 'ghost';
+ disabled?: boolean;
id: string;
};
diff --git a/client/src/components/Insights/InsightsView.tsx b/client/src/components/Insights/InsightsView.tsx
index bc0d18a4b9..31c80bfdda 100644
--- a/client/src/components/Insights/InsightsView.tsx
+++ b/client/src/components/Insights/InsightsView.tsx
@@ -1,13 +1,19 @@
import { useEffect, useId, useMemo, useRef, useState } from 'react';
-import { Navigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { AlertCircle, Info, Search } from 'lucide-react';
-import { Button, Input, Spinner, TooltipAnchor, useMediaQuery } from '@librechat/client';
+import { Navigate, useSearchParams } from 'react-router-dom';
+import {
+ Button,
+ Input,
+ MultiSelect,
+ Spinner,
+ TooltipAnchor,
+ useMediaQuery,
+} from '@librechat/client';
import {
INSIGHTS_MAX_RANGE_DAYS,
INSIGHTS_SEARCH_MAX_LENGTH,
INSIGHTS_SEARCH_MIN_LENGTH,
- SystemRoles,
} from 'librechat-data-provider';
import type {
InsightsRange,
@@ -17,7 +23,8 @@ import type {
TInsightsUser,
} from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
-import { useGetStartupConfig, useInsightsAccessQuery, useInsightsQuery } from '~/data-provider';
+import { clearAgentFilters, shouldRecoverAgentFilters } from './agentFilters';
+import { useGetStartupConfig, useInsightsQuery } from '~/data-provider';
import { useAuthContext, useDocumentTitle, useLocalize } from '~/hooks';
import OpenSidebar from '~/components/Chat/Menus/OpenSidebar';
import { LocalizedDateRangePicker } from '~/components/ui';
@@ -32,6 +39,7 @@ type CustomDateRange = { startDate: Date; endDate: Date };
type KpiCardData = {
id: 'conversations' | 'users' | 'messages' | 'tokens';
title: string;
+ description?: string;
value: number;
sparkline: SparklinePoint[];
};
@@ -242,7 +250,23 @@ function KpiCard({ card, locale }: { card: KpiCardData; locale: string }) {
const localize = useLocalize();
return (
<Panel>
- <h2 className="text-sm font-normal text-text-muted">{card.title}</h2>
+ <h2 className="inline-flex items-center gap-1.5 text-sm font-normal text-text-muted">
+ {card.title}
+ {card.description && (
+ <TooltipAnchor
+ description={card.description}
+ render={
+ <button
+ type="button"
+ aria-label={card.description}
+ className="text-text-muted hover:text-text-secondary"
+ >
+ <Info className="size-3.5" aria-hidden="true" />
+ </button>
+ }
+ />
+ )}
+ </h2>
<div className="mt-3 text-4xl font-semibold tabular-nums leading-none text-text-primary">
{formatValue(card.value, locale)}
</div>
@@ -450,11 +474,12 @@ function LatestConversations({
</div>
</div>
<div className="overflow-x-auto">
- <table className="w-full min-w-[760px] table-fixed text-left text-sm">
+ <table className="w-full min-w-[900px] table-fixed text-left text-sm">
<thead className="border-b border-border-medium text-xs text-text-secondary">
<tr>
<th className="w-[120px] px-2 py-2 font-medium">{localize('com_insights_date')}</th>
<th className="w-[192px] px-2 py-2 font-medium">{localize('com_insights_user')}</th>
+ <th className="w-[160px] px-2 py-2 font-medium">{localize('com_insights_agent')}</th>
<th className="px-2 py-2 font-medium">{localize('com_insights_first_message')}</th>
<th className="w-20 px-2 py-2 text-right font-medium">
{localize('com_insights_messages')}
@@ -476,6 +501,7 @@ function LatestConversations({
<td className="px-2 py-3">
<UserCell {...conversation} localize={localize} />
</td>
+ <td className="truncate px-2 py-3 text-text-secondary">{conversation.agentName}</td>
<td className="max-w-xl px-2 py-3">
<span className="line-clamp-2">
{conversation.firstMessage || localize('com_insights_no_message')}
@@ -528,6 +554,7 @@ function LatestConversations({
export default function InsightsView() {
const localize = useLocalize();
+ const [urlSearchParams, setUrlSearchParams] = useSearchParams();
const { i18n } = useTranslation();
const locale = i18n.resolvedLanguage ?? i18n.language ?? 'en';
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
@@ -541,13 +568,18 @@ export default function InsightsView() {
const dateRangeSelectionTimeout = useRef<number>();
const isSmallScreen = useMediaQuery('(max-width: 768px)');
const insightsFeatureEnabled = startupConfig?.insightsEnabled === true;
- const shouldCheckAccess = user?.role === SystemRoles.ADMIN && insightsFeatureEnabled;
- const access = useInsightsAccessQuery(user?.id, {
- enabled: shouldCheckAccess,
- });
- const isAllowed = insightsFeatureEnabled && access.data?.access === true;
+ const selectedAgentIds = useMemo(
+ () => [...new Set(urlSearchParams.getAll('agentIds').filter(Boolean))].sort(),
+ [urlSearchParams],
+ );
const insightsParams = useMemo<TInsightsParams>(() => {
- const params: TInsightsParams = { page, pageSize: 10, search, timeZone };
+ const params: TInsightsParams = {
+ page,
+ pageSize: 10,
+ search,
+ timeZone,
+ ...(selectedAgentIds.length > 0 ? { agentIds: selectedAgentIds } : {}),
+ };
if (customDateRange) {
return {
...params,
@@ -557,13 +589,38 @@ export default function InsightsView() {
};
}
return { ...params, range };
- }, [customDateRange, page, range, search, timeZone]);
+ }, [customDateRange, page, range, search, selectedAgentIds, timeZone]);
const displayDateRange = useMemo(
() => customDateRange ?? getShortcutDateRange(range),
[customDateRange, range],
);
- const insights = useInsightsQuery(insightsParams, { enabled: isAllowed });
+ const insights = useInsightsQuery(insightsParams, {
+ enabled: !!user && insightsFeatureEnabled,
+ retry: false,
+ });
const data = insights.data;
+ const insightsStatus = responseStatus(insights.error);
+ const isRecoveringAgentFilters = shouldRecoverAgentFilters(insightsStatus, selectedAgentIds);
+ const agentItems = useMemo(() => {
+ if (!data) {
+ return [];
+ }
+ const duplicateNames = new Map<string, number>();
+ for (const agent of data.agents) {
+ duplicateNames.set(agent.name, (duplicateNames.get(agent.name) ?? 0) + 1);
+ }
+ return data.agents.map((agent) => ({
+ value: agent.id,
+ label:
+ (duplicateNames.get(agent.name) ?? 0) > 1
+ ? `${agent.name} (${agent.id.slice(-6)})`
+ : agent.name,
+ }));
+ }, [data]);
+ const effectiveAgentIds = useMemo(
+ () => (selectedAgentIds.length > 0 ? selectedAgentIds : agentItems.map((agent) => agent.value)),
+ [agentItems, selectedAgentIds],
+ );
useDocumentTitle(`${localize('com_insights_title')} | LibreChat`);
@@ -589,6 +646,14 @@ export default function InsightsView() {
return () => window.clearTimeout(timeout);
}, [search, searchInput]);
+ useEffect(() => {
+ if (!isRecoveringAgentFilters) {
+ return;
+ }
+ setUrlSearchParams(clearAgentFilters(urlSearchParams), { replace: true });
+ setPage(1);
+ }, [isRecoveringAgentFilters, setUrlSearchParams, urlSearchParams]);
+
const kpiCards = useMemo<KpiCardData[]>(() => {
if (!data) {
return [];
@@ -597,6 +662,7 @@ export default function InsightsView() {
{
id: 'conversations',
title: localize('com_insights_total_conversations'),
+ description: localize('com_insights_conversations_definition'),
value: data.summary.totalConversations,
sparkline: data.daily.map((row) => ({ date: row.date, value: row.conversations })),
},
@@ -632,25 +698,37 @@ export default function InsightsView() {
}, dateRangeSelectionDelayMs);
};
- if (configLoading || (shouldCheckAccess && access.isLoading)) {
+ const handleAgentSelection = (agentIds: string[]) => {
+ if (agentIds.length === 0 || !data) {
+ return;
+ }
+ const normalizedIds = [...new Set(agentIds)].sort();
+ const allAgentIds = data.agents.map((agent) => agent.id).sort();
+ const nextParams = new URLSearchParams(urlSearchParams);
+ nextParams.delete('agentIds');
+ if (
+ normalizedIds.length !== allAgentIds.length ||
+ normalizedIds.some((agentId, index) => agentId !== allAgentIds[index])
+ ) {
+ for (const agentId of normalizedIds) {
+ nextParams.append('agentIds', agentId);
+ }
+ }
+ setUrlSearchParams(nextParams, { replace: true });
+ setPage(1);
+ };
+
+ if (
+ configLoading ||
+ (insightsFeatureEnabled && (insights.isLoading || isRecoveringAgentFilters))
+ ) {
return (
<div className="h-full w-full bg-presentation p-4">
<LoadingState message={localize('com_insights_loading')} />
</div>
);
}
- const accessStatus = responseStatus(access.error);
- if (access.isError && accessStatus !== 403 && accessStatus !== 404) {
- return (
- <div className="h-full w-full bg-presentation p-4">
- <Panel className="flex items-center gap-2">
- <AlertCircle className="size-4 text-status-error" />
- <span className="text-sm">{localize('com_insights_load_error')}</span>
- </Panel>
- </div>
- );
- }
- if (!isAllowed) {
+ if (!insightsFeatureEnabled) {
return <Navigate to="/c/new" replace />;
}
@@ -662,6 +740,42 @@ export default function InsightsView() {
<h1 className="text-base font-semibold">{localize('com_insights_title')}</h1>
</div>
<div className="flex max-w-full flex-wrap items-center gap-2 md:flex-nowrap">
+ {data && (
+ <MultiSelect
+ items={agentItems}
+ selectedValues={effectiveAgentIds}
+ setSelectedValues={handleAgentSelection}
+ disabled={agentItems.length === 1}
+ showSelectedValues
+ className="w-full min-w-0 sm:w-56"
+ selectClassName="h-8 w-full rounded border border-border-medium bg-surface-tertiary px-3 py-1 shadow-none hover:border-border-heavy data-[state=open]:border-border-heavy dark:hover:bg-chart-widget-stroke dark:data-[state=open]:bg-chart-widget-stroke"
+ itemClassName="rounded-none px-4 py-1.5"
+ popoverClassName="max-h-80 rounded border-border-medium bg-surface-primary px-0 py-2 dark:bg-chart-widget-surface"
+ renderSelectedValues={(values) => {
+ if (values.length === agentItems.length) {
+ return localize('com_insights_all_agents', { count: agentItems.length });
+ }
+ if (values.length === 1) {
+ return agentItems.find((agent) => agent.value === values[0])?.label ?? values[0];
+ }
+ return localize('com_insights_agents_selected', { count: values.length });
+ }}
+ popoverHeader={
+ <div className="border-b border-border-light pb-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-8 w-full justify-start rounded-none px-4 font-normal text-text-secondary hover:bg-surface-hover hover:text-text-primary"
+ disabled={effectiveAgentIds.length === agentItems.length}
+ onClick={() => handleAgentSelection(agentItems.map((agent) => agent.value))}
+ >
+ {localize('com_insights_select_all_agents')}
+ </Button>
+ </div>
+ }
+ />
+ )}
<div className="inline-flex rounded-lg border border-border-light p-0.5">
{ranges.map((item) => (
<Button
@@ -715,7 +829,11 @@ export default function InsightsView() {
{insights.isError && (
<Panel className="flex items-center gap-2">
<AlertCircle className="size-4 text-status-error" />
- <span className="text-sm">{localize('com_insights_load_error')}</span>
+ <span className="text-sm">
+ {insightsStatus === 403
+ ? localize('com_insights_forbidden')
+ : localize('com_insights_load_error')}
+ </span>
</Panel>
)}
{data && (
diff --git a/client/src/components/Insights/agentFilters.spec.ts b/client/src/components/Insights/agentFilters.spec.ts
new file mode 100644
index 0000000000..6bc2f12e4d
--- /dev/null
+++ b/client/src/components/Insights/agentFilters.spec.ts
@@ -0,0 +1,18 @@
+import { clearAgentFilters, shouldRecoverAgentFilters } from './agentFilters';
+
+describe('Insights agent filter recovery', () => {
+ it('removes only agent filters from a stale bookmarked URL', () => {
+ const params = clearAgentFilters(
+ new URLSearchParams('agentIds=deleted-agent&agentIds=revoked-agent&range=30d'),
+ );
+
+ expect(params.getAll('agentIds')).toEqual([]);
+ expect(params.get('range')).toBe('30d');
+ });
+
+ it('recovers only authorization failures with explicit agent filters', () => {
+ expect(shouldRecoverAgentFilters(403, ['revoked-agent'])).toBe(true);
+ expect(shouldRecoverAgentFilters(403, [])).toBe(false);
+ expect(shouldRecoverAgentFilters(500, ['agent-a'])).toBe(false);
+ });
+});
diff --git a/client/src/components/Insights/agentFilters.ts b/client/src/components/Insights/agentFilters.ts
new file mode 100644
index 0000000000..eaff810435
--- /dev/null
+++ b/client/src/components/Insights/agentFilters.ts
@@ -0,0 +1,9 @@
+export function clearAgentFilters(searchParams: URLSearchParams): URLSearchParams {
+ const nextParams = new URLSearchParams(searchParams);
+ nextParams.delete('agentIds');
+ return nextParams;
+}
+
+export function shouldRecoverAgentFilters(status: number | undefined, agentIds: string[]): boolean {
+ return status === 403 && agentIds.length > 0;
+}
diff --git a/client/src/components/Sharing/GenericGrantAccessDialog.tsx b/client/src/components/Sharing/GenericGrantAccessDialog.tsx
index 41d0def983..6f36945aa9 100644
--- a/client/src/components/Sharing/GenericGrantAccessDialog.tsx
+++ b/client/src/components/Sharing/GenericGrantAccessDialog.tsx
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';
import { Link, CopyCheck } from 'lucide';
-import { AccessRoleIds, ResourceType } from 'librechat-data-provider';
import { Share2Icon, Users, UserCheck, AlertCircle } from 'lucide-react';
+import { AccessRoleIds, ResourceType, SystemRoles } from 'librechat-data-provider';
import {
Alert,
Label,
@@ -25,9 +25,10 @@ import {
useResourcePermissionState,
useCopyToClipboard,
useCanSharePublic,
+ useAuthContext,
useLocalize,
} from '~/hooks';
-import { computeShareChanges, dedupeNewShares } from './shareChanges';
+import { computeShareChanges, dedupeNewShares, principalKey } from './shareChanges';
import UnifiedPeopleSearch from './PeoplePicker/UnifiedPeopleSearch';
import PeoplePickerAdminSettings from './PeoplePickerAdminSettings';
import PublicSharingToggle from './PublicSharingToggle';
@@ -54,16 +55,20 @@ export default function GenericGrantAccessDialog({
children?: React.ReactNode;
}) {
const localize = useLocalize();
+ const { user } = useAuthContext();
const { showToast } = useToastContext();
const [isCopying, setIsCopying] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
const peopleSectionId = React.useId();
const ownerErrorId = React.useId();
const canSharePublic = useCanSharePublic(resourceType);
+ const canEditAgentInsights =
+ resourceType === ResourceType.AGENT && user?.role === SystemRoles.ADMIN;
const { hasPeoplePickerAccess, peoplePickerTypeFilter } = usePeoplePickerPermissions();
+ const canManagePrincipals = hasPeoplePickerAccess || canEditAgentInsights;
- /** User can use the share dialog if they have people picker access OR can share publicly */
- const canUseShareDialog = hasPeoplePickerAccess || canSharePublic;
+ /** User can use the dialog if they can manage principals or share publicly. */
+ const canUseShareDialog = canManagePrincipals || canSharePublic;
const {
config,
@@ -125,6 +130,7 @@ export default function GenericGrantAccessDialog({
const sharesWithDefaults = sharesToAdd.map((share) => ({
...share,
accessRoleId: defaultPermissionId || config?.defaultViewerRoleId,
+ ...(canEditAgentInsights ? { viewInsights: false } : {}),
isExisting: false, // Mark as newly added
}));
@@ -133,16 +139,27 @@ export default function GenericGrantAccessDialog({
};
// Handler for removing individual shares
- const handleRemoveShare = (idOnTheSource: string) => {
- setAllShares(allShares.filter((s) => s.idOnTheSource !== idOnTheSource));
+ const handleRemoveShare = (shareKey: string) => {
+ setAllShares(allShares.filter((share) => principalKey(share) !== shareKey));
setHasChanges(true);
};
// Handler for changing individual share permissions
- const handleRoleChange = (idOnTheSource: string, newRole: string) => {
+ const handleRoleChange = (shareKey: string, newRole: string) => {
setAllShares(
- allShares.map((s) =>
- s.idOnTheSource === idOnTheSource ? { ...s, accessRoleId: newRole as AccessRoleIds } : s,
+ allShares.map((share) =>
+ principalKey(share) === shareKey
+ ? { ...share, accessRoleId: newRole as AccessRoleIds }
+ : share,
+ ),
+ );
+ setHasChanges(true);
+ };
+
+ const handleInsightsChange = (shareKey: string, viewInsights: boolean) => {
+ setAllShares(
+ allShares.map((share) =>
+ principalKey(share) === shareKey ? { ...share, viewInsights } : share,
),
);
setHasChanges(true);
@@ -320,7 +337,7 @@ export default function GenericGrantAccessDialog({
className="min-h-0 flex-1 overflow-y-auto px-5 py-3 sm:px-6 sm:py-4"
aria-busy={isLoadingPermissions}
>
- {hasPeoplePickerAccess && (
+ {canManagePrincipals && (
<section aria-labelledby={peopleSectionId} className="w-full min-w-0">
<div className="flex items-center justify-between gap-3 px-1 pb-3">
<h3
@@ -377,6 +394,8 @@ export default function GenericGrantAccessDialog({
onRemoveHandler={handleRemoveShare}
resourceType={resourceType}
onRoleChange={(id, newRole) => handleRoleChange(id, newRole)}
+ showInsightsAccess={canEditAgentInsights}
+ onInsightsAccessChange={handleInsightsChange}
/>
)}
</>
@@ -397,7 +416,7 @@ export default function GenericGrantAccessDialog({
</section>
)}
- {canSharePublic && !hasPeoplePickerAccess && (
+ {canSharePublic && !canManagePrincipals && (
<section className="w-full">
<PublicSharingToggle
isPublic={isPublic}
diff --git a/client/src/components/Sharing/PeoplePicker/SelectedPrincipalsList.tsx b/client/src/components/Sharing/PeoplePicker/SelectedPrincipalsList.tsx
index 774105c552..5c2460eb5c 100644
--- a/client/src/components/Sharing/PeoplePicker/SelectedPrincipalsList.tsx
+++ b/client/src/components/Sharing/PeoplePicker/SelectedPrincipalsList.tsx
@@ -1,17 +1,20 @@
import React from 'react';
-import { Users, X, ExternalLink } from 'lucide-react';
import { ResourceType } from 'librechat-data-provider';
-import { Button, useMediaQuery } from '@librechat/client';
+import { Users, X, ExternalLink, Info } from 'lucide-react';
+import { Button, Checkbox, TooltipAnchor, useMediaQuery } from '@librechat/client';
import type { TPrincipal, AccessRoleIds } from 'librechat-data-provider';
import AccessRolesPicker from '~/components/Sharing/AccessRolesPicker';
import PrincipalAvatar from '~/components/Sharing/PrincipalAvatar';
import { RESOURCE_CONFIGS } from '~/utils/resources';
+import { principalKey } from '../shareChanges';
import { useLocalize } from '~/hooks';
interface SelectedPrincipalsListProps {
principles: TPrincipal[];
- onRemoveHandler: (idOnTheSource: string) => void;
- onRoleChange?: (idOnTheSource: string, newRoleId: AccessRoleIds) => void;
+ onRemoveHandler: (principalKey: string) => void;
+ onRoleChange?: (principalKey: string, newRoleId: AccessRoleIds) => void;
+ onInsightsAccessChange?: (principalKey: string, enabled: boolean) => void;
+ showInsightsAccess?: boolean;
resourceType?: ResourceType;
className?: string;
}
@@ -21,6 +24,8 @@ export default function SelectedPrincipalsList({
onRemoveHandler,
className = '',
onRoleChange,
+ onInsightsAccessChange,
+ showInsightsAccess = false,
resourceType = ResourceType.AGENT,
}: SelectedPrincipalsListProps) {
const localize = useLocalize();
@@ -55,9 +60,16 @@ export default function SelectedPrincipalsList({
const isOwner = share.accessRoleId === ownerRoleId;
const isSharedLink = resourceType === ResourceType.SHARED_LINK;
const lockOwner = isSharedLink && isOwner;
+ const shareKey = principalKey(share);
+ const hasAutomaticInsightsAccess = share.isAdmin === true;
+ const insightsDescription = localize(
+ hasAutomaticInsightsAccess
+ ? 'com_ui_view_agent_insights_admin_description'
+ : 'com_ui_view_agent_insights_description',
+ );
return (
<div
- key={share.idOnTheSource + '-principalList'}
+ key={`${shareKey}-principalList`}
className="flex flex-col gap-3 rounded-xl border border-border-light bg-transparent p-3 sm:flex-row sm:items-center sm:justify-between"
>
<div className="flex min-w-0 flex-1 items-center gap-3">
@@ -78,6 +90,33 @@ export default function SelectedPrincipalsList({
</div>
<div className="flex w-full flex-shrink-0 items-center justify-end gap-2 sm:w-auto">
+ {showInsightsAccess && onInsightsAccessChange && (
+ <div className="mr-auto flex items-center gap-2 sm:mr-1">
+ <Checkbox
+ checked={hasAutomaticInsightsAccess || share.viewInsights === true}
+ disabled={hasAutomaticInsightsAccess}
+ onCheckedChange={(checked) =>
+ onInsightsAccessChange(shareKey, checked === true)
+ }
+ aria-label={localize('com_ui_view_agent_insights')}
+ />
+ <span className="whitespace-nowrap text-sm text-text-secondary">
+ {localize('com_ui_view_agent_insights')}
+ </span>
+ <TooltipAnchor
+ description={insightsDescription}
+ render={
+ <button
+ type="button"
+ aria-label={insightsDescription}
+ className="text-text-secondary hover:text-text-primary"
+ >
+ <Info className="size-4" aria-hidden="true" />
+ </button>
+ }
+ />
+ </div>
+ )}
{lockOwner ? (
<span className="px-3 py-2 text-sm font-medium text-text-secondary">
{localize('com_ui_role_owner')}
@@ -89,7 +128,7 @@ export default function SelectedPrincipalsList({
resourceType={resourceType}
selectedRoleId={share.accessRoleId}
onRoleChange={(newRole) => {
- onRoleChange?.(share.idOnTheSource!, newRole);
+ onRoleChange?.(shareKey, newRole);
}}
className="min-w-0"
/>
@@ -98,7 +137,7 @@ export default function SelectedPrincipalsList({
{!lockOwner && (
<Button
variant="outline"
- onClick={() => onRemoveHandler(share.idOnTheSource!)}
+ onClick={() => onRemoveHandler(shareKey)}
className="h-9 w-9 p-0 hover:border-status-error-border hover:bg-status-error-subtle hover:text-text-destructive"
aria-label={localize('com_ui_remove_user', { 0: displayName })}
>
diff --git a/client/src/components/Sharing/__tests__/GenericGrantAccessDialog.spec.tsx b/client/src/components/Sharing/__tests__/GenericGrantAccessDialog.spec.tsx
index 08f62be4c6..95e30d2851 100644
--- a/client/src/components/Sharing/__tests__/GenericGrantAccessDialog.spec.tsx
+++ b/client/src/components/Sharing/__tests__/GenericGrantAccessDialog.spec.tsx
@@ -6,6 +6,12 @@ import GenericGrantAccessDialog from '../GenericGrantAccessDialog';
const mockRefetchPermissions = jest.fn();
const mockUseResourcePermissionState = jest.fn();
+const mockUseAuthContext = jest.fn(() => ({ user: { role: 'ADMIN' } }));
+const mockUsePeoplePickerPermissions = jest.fn(() => ({
+ hasPeoplePickerAccess: true,
+ peoplePickerTypeFilter: '' as string | null,
+}));
+const mockUseCanSharePublic = jest.fn(() => true);
const config = {
defaultViewerRoleId: 'viewer',
@@ -34,10 +40,11 @@ const baseState = (overrides: Record<string, unknown> = {}) => ({
});
jest.mock('~/hooks', () => ({
+ useAuthContext: () => mockUseAuthContext(),
useLocalize: () => (key: string) => key,
useResourcePermissionState: () => mockUseResourcePermissionState(),
- usePeoplePickerPermissions: () => ({ hasPeoplePickerAccess: true, peoplePickerTypeFilter: '' }),
- useCanSharePublic: () => true,
+ usePeoplePickerPermissions: () => mockUsePeoplePickerPermissions(),
+ useCanSharePublic: () => mockUseCanSharePublic(),
useCopyToClipboard: () => jest.fn(),
}));
@@ -77,6 +84,12 @@ describe('GenericGrantAccessDialog - permissions load failure', () => {
beforeEach(() => {
mockUseResourcePermissionState.mockReset();
mockRefetchPermissions.mockReset();
+ mockUseAuthContext.mockReturnValue({ user: { role: 'ADMIN' } });
+ mockUsePeoplePickerPermissions.mockReturnValue({
+ hasPeoplePickerAccess: true,
+ peoplePickerTypeFilter: '',
+ });
+ mockUseCanSharePublic.mockReturnValue(true);
});
it('renders a compact alert button (not the share trigger, not raw text) when permissions fail to load', () => {
@@ -151,6 +164,24 @@ describe('GenericGrantAccessDialog - permissions load failure', () => {
expect(screen.queryByRole('button', { name: 'com_ui_cancel' })).not.toBeInTheDocument();
});
+ it('lets an admin manage agent principals without people picker or public sharing permissions', () => {
+ mockUseResourcePermissionState.mockReturnValue(baseState());
+ mockUsePeoplePickerPermissions.mockReturnValue({
+ hasPeoplePickerAccess: false,
+ peoplePickerTypeFilter: null,
+ });
+ mockUseCanSharePublic.mockReturnValue(false);
+
+ renderDialog();
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_share_var' }));
+
+ expect(screen.getByTestId('unified-people-search')).toBeInTheDocument();
+ expect(
+ screen.getByRole('heading', { level: 3, name: 'com_ui_user_group_permissions' }),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId('public-toggle')).not.toBeInTheDocument();
+ });
+
it('discards the draft through the shared close path', () => {
const setIsPublic = jest.fn();
const setPublicRole = jest.fn();
diff --git a/client/src/components/Sharing/__tests__/SelectedPrincipalsList.spec.tsx b/client/src/components/Sharing/__tests__/SelectedPrincipalsList.spec.tsx
new file mode 100644
index 0000000000..e6e6755751
--- /dev/null
+++ b/client/src/components/Sharing/__tests__/SelectedPrincipalsList.spec.tsx
@@ -0,0 +1,90 @@
+import React from 'react';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { AccessRoleIds, PrincipalType } from 'librechat-data-provider';
+import type { TPrincipal } from 'librechat-data-provider';
+import SelectedPrincipalsList from '../PeoplePicker/SelectedPrincipalsList';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('../AccessRolesPicker', () => ({
+ __esModule: true,
+ default: () => <div />,
+}));
+
+jest.mock('../PrincipalAvatar', () => ({
+ __esModule: true,
+ default: () => <div />,
+}));
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ TooltipAnchor: ({ render: trigger }: { render: React.ReactNode }) => trigger,
+ useMediaQuery: () => false,
+}));
+
+describe('SelectedPrincipalsList', () => {
+ it('keys Insights changes by role ID when source IDs are absent', () => {
+ const roles: TPrincipal[] = [
+ {
+ type: PrincipalType.ROLE,
+ id: 'role-one',
+ name: 'Role One',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ },
+ {
+ type: PrincipalType.ROLE,
+ id: 'role-two',
+ name: 'Role Two',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ },
+ ];
+ const onInsightsAccessChange = jest.fn();
+
+ render(
+ <SelectedPrincipalsList
+ principles={roles}
+ onRemoveHandler={jest.fn()}
+ onInsightsAccessChange={onInsightsAccessChange}
+ showInsightsAccess
+ />,
+ );
+
+ fireEvent.click(screen.getAllByRole('checkbox')[1]);
+
+ expect(onInsightsAccessChange).toHaveBeenCalledTimes(1);
+ expect(onInsightsAccessChange).toHaveBeenCalledWith('role-role-two', true);
+ });
+
+ it('shows administrator Insights access as checked and read-only', () => {
+ const onInsightsAccessChange = jest.fn();
+ const admin: TPrincipal = {
+ type: PrincipalType.USER,
+ id: 'admin-user',
+ name: 'Admin User',
+ accessRoleId: AccessRoleIds.AGENT_OWNER,
+ viewInsights: false,
+ isAdmin: true,
+ };
+
+ render(
+ <SelectedPrincipalsList
+ principles={[admin]}
+ onRemoveHandler={jest.fn()}
+ onInsightsAccessChange={onInsightsAccessChange}
+ showInsightsAccess
+ />,
+ );
+
+ const checkbox = screen.getByRole('checkbox', { name: 'com_ui_view_agent_insights' });
+ expect(checkbox).toBeChecked();
+ expect(checkbox).toBeDisabled();
+
+ fireEvent.click(checkbox);
+ expect(onInsightsAccessChange).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole('button', { name: 'com_ui_view_agent_insights_admin_description' }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Sharing/__tests__/shareChanges.spec.ts b/client/src/components/Sharing/__tests__/shareChanges.spec.ts
index ae0f8d1b4c..86193e4269 100644
--- a/client/src/components/Sharing/__tests__/shareChanges.spec.ts
+++ b/client/src/components/Sharing/__tests__/shareChanges.spec.ts
@@ -64,6 +64,39 @@ describe('computeShareChanges', () => {
expect(removed.some((p) => p.idOnTheSource === 'group-oid')).toBe(true);
expect(principalKey(currentShares[0])).toBe(`${PrincipalType.GROUP}-group-oid`);
});
+
+ it('emits an update when only Insights access changes', () => {
+ const currentShares = [principal({ id: 'viewer', viewInsights: false })];
+ const allShares = [principal({ id: 'viewer', viewInsights: true })];
+
+ const { updated, removed } = computeShareChanges(currentShares, allShares);
+
+ expect(updated).toEqual([expect.objectContaining({ id: 'viewer', viewInsights: true })]);
+ expect(removed).toEqual([]);
+ });
+
+ it('omits Insights access when a role change preserves it', () => {
+ const currentShares = [
+ principal({ id: 'viewer', accessRoleId: AccessRoleIds.AGENT_VIEWER, viewInsights: true }),
+ ];
+ const allShares = [
+ principal({ id: 'viewer', accessRoleId: AccessRoleIds.AGENT_EDITOR, viewInsights: true }),
+ ];
+
+ const { updated } = computeShareChanges(currentShares, allShares);
+
+ expect(updated).toEqual([
+ expect.objectContaining({ id: 'viewer', accessRoleId: AccessRoleIds.AGENT_EDITOR }),
+ ]);
+ expect(updated[0]).not.toHaveProperty('viewInsights');
+ });
+
+ it('does not emit a no-op Insights update', () => {
+ const currentShares = [principal({ id: 'viewer', viewInsights: true })];
+ const allShares = [principal({ id: 'viewer', viewInsights: true })];
+
+ expect(computeShareChanges(currentShares, allShares)).toEqual({ updated: [], removed: [] });
+ });
});
describe('dedupeNewShares', () => {
diff --git a/client/src/components/Sharing/shareChanges.ts b/client/src/components/Sharing/shareChanges.ts
index 0c57dbc16a..b87209f3c2 100644
--- a/client/src/components/Sharing/shareChanges.ts
+++ b/client/src/components/Sharing/shareChanges.ts
@@ -46,9 +46,23 @@ export function computeShareChanges(
// Diff over the de-duplicated map values so a principal that appears more than once
// in the input (possible while the add/dedupe path still keys on idOnTheSource) is
// never emitted multiple times.
- const updated = [...allSharesMap.values()].filter((share) => {
+ const updated = [...allSharesMap.values()].flatMap((share) => {
const original = originalSharesMap.get(principalKey(share));
- return !original || original.accessRoleId !== share.accessRoleId;
+ if (!original) {
+ return [share];
+ }
+
+ const roleChanged = original.accessRoleId !== share.accessRoleId;
+ const insightsChanged = original.viewInsights !== share.viewInsights;
+ if (!roleChanged && !insightsChanged) {
+ return [];
+ }
+ if (insightsChanged) {
+ return [share];
+ }
+
+ const { viewInsights: _preserved, ...roleUpdate } = share;
+ return [roleUpdate];
});
const removed = [...originalSharesMap.values()].filter(
diff --git a/client/src/components/SidePanel/Agents/AgentFooter.tsx b/client/src/components/SidePanel/Agents/AgentFooter.tsx
index 73d1b3d0fd..ddacdfdb34 100644
--- a/client/src/components/SidePanel/Agents/AgentFooter.tsx
+++ b/client/src/components/SidePanel/Agents/AgentFooter.tsx
@@ -60,6 +60,7 @@ export default function AgentFooter({
const canEditThisAgent = hasPermission(PermissionBits.EDIT);
const canDeleteThisAgent = hasPermission(PermissionBits.DELETE);
const canShareRemoteAgent = hasRemoteAgentPermission(PermissionBits.SHARE);
+ const isAdmin = user?.role === SystemRoles.ADMIN;
const isSaving = createMutation.isLoading || updateMutation.isLoading || isAvatarUploading;
const saveLabel = agent_id ? localize('com_ui_save') : localize('com_ui_create');
const renderSaveButton = () => (
@@ -94,8 +95,8 @@ export default function AgentFooter({
createMutation={createMutation}
/>
)}
- {(agent?.author === user?.id || user?.role === SystemRoles.ADMIN || canShareThisAgent) &&
- hasAccessToShareAgents &&
+ {(agent?.author === user?.id || isAdmin || canShareThisAgent) &&
+ (hasAccessToShareAgents || isAdmin) &&
!permissionsLoading && (
<GenericGrantAccessDialog
resourceDbId={agent?._id}
diff --git a/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx
index 8f04f188d7..1fca851cc2 100644
--- a/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx
+++ b/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx
@@ -353,6 +353,7 @@ describe('AgentFooter', () => {
test('adjusts UI based on user role', () => {
mockUseAuthContext.mockReturnValue(createAuthContext(mockUsers.admin));
+ mockUseHasAccess.mockReturnValue(false);
const { unmount } = render(<AgentFooter {...defaultProps} />);
expect(screen.getByTestId('admin-settings')).toBeInTheDocument();
expect(screen.getByTestId('grant-access-dialog-agent')).toBeInTheDocument();
diff --git a/client/src/components/UnifiedSidebar/ExpandedPanel.tsx b/client/src/components/UnifiedSidebar/ExpandedPanel.tsx
index 5e9748acc7..ab04ba9ae7 100644
--- a/client/src/components/UnifiedSidebar/ExpandedPanel.tsx
+++ b/client/src/components/UnifiedSidebar/ExpandedPanel.tsx
@@ -106,6 +106,7 @@ const NavIconButton = memo(function NavIconButton({
variant="ghost"
aria-label={localize(link.title)}
aria-pressed={isActive}
+ disabled={link.disabled}
data-testid={`nav-panel-${link.id}`}
className={cn(
'h-9 w-9 rounded-lg',
diff --git a/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx b/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx
index 5f2c93b72e..054c81a2ee 100644
--- a/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx
+++ b/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx
@@ -38,6 +38,7 @@ function ShortcutTargets({
tabIndex={-1}
data-testid={`nav-panel-${link.id}`}
aria-pressed={link.id === activeId}
+ disabled={link.disabled}
onClick={() => {
if (link.onClick) {
link.onClick();
diff --git a/client/src/hooks/Nav/useUnifiedSidebarLinks.ts b/client/src/hooks/Nav/useUnifiedSidebarLinks.ts
index 2f1e92c14a..92d6da47dd 100644
--- a/client/src/hooks/Nav/useUnifiedSidebarLinks.ts
+++ b/client/src/hooks/Nav/useUnifiedSidebarLinks.ts
@@ -3,7 +3,7 @@ import { useRecoilValue } from 'recoil';
import { BarChart3, MessagesSquare } from 'lucide-react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useUserKeyQuery } from 'librechat-data-provider/react-query';
-import { getConfigDefaults, getEndpointField, SystemRoles } from 'librechat-data-provider';
+import { getConfigDefaults, getEndpointField } from 'librechat-data-provider';
import type { TEndpointsConfig } from 'librechat-data-provider';
import type { NavLink } from '~/common';
import { useGetEndpointsQuery, useGetStartupConfig, useInsightsAccessQuery } from '~/data-provider';
@@ -29,9 +29,13 @@ export default function useUnifiedSidebarLinks() {
[startupConfig],
);
const insightsFeatureEnabled = startupConfig?.insightsEnabled === true;
- const { data: insightsAccess } = useInsightsAccessQuery(user?.id, {
- enabled: user?.role === SystemRoles.ADMIN && insightsFeatureEnabled,
- });
+ const isInsightsRoute = location.pathname.startsWith('/insights');
+ const { data: insightsAccess, isLoading: isInsightsAccessLoading } = useInsightsAccessQuery(
+ user?.id,
+ {
+ enabled: !!user && insightsFeatureEnabled && !isInsightsRoute,
+ },
+ );
const endpointType = useMemo(
() => getEndpointField(endpointsConfig, endpoint, 'type'),
@@ -68,7 +72,10 @@ export default function useUnifiedSidebarLinks() {
Component: ConversationsSection,
};
- if (!insightsFeatureEnabled || insightsAccess?.access !== true) {
+ if (
+ !insightsFeatureEnabled ||
+ (!isInsightsRoute && !isInsightsAccessLoading && insightsAccess?.access !== true)
+ ) {
return [conversationLink, ...sideNavLinks];
}
@@ -77,6 +84,7 @@ export default function useUnifiedSidebarLinks() {
label: '',
icon: BarChart3,
id: 'insights',
+ disabled: !isInsightsRoute && isInsightsAccessLoading,
onClick: () => {
if (!location.pathname.startsWith('/insights')) {
navigate('/insights');
@@ -88,7 +96,15 @@ export default function useUnifiedSidebarLinks() {
nextLinks.splice(mcpIndex >= 0 ? mcpIndex + 1 : nextLinks.length, 0, insightsLink);
return [conversationLink, ...nextLinks];
- }, [insightsAccess?.access, insightsFeatureEnabled, location.pathname, navigate, sideNavLinks]);
+ }, [
+ insightsAccess?.access,
+ insightsFeatureEnabled,
+ isInsightsAccessLoading,
+ isInsightsRoute,
+ location.pathname,
+ navigate,
+ sideNavLinks,
+ ]);
return links;
}
diff --git a/client/src/hooks/Sharing/__tests__/useResourcePermissionState.spec.ts b/client/src/hooks/Sharing/__tests__/useResourcePermissionState.spec.ts
new file mode 100644
index 0000000000..91aac98969
--- /dev/null
+++ b/client/src/hooks/Sharing/__tests__/useResourcePermissionState.spec.ts
@@ -0,0 +1,58 @@
+import { renderHook } from '@testing-library/react';
+import { AccessRoleIds, PrincipalType, ResourceType } from 'librechat-data-provider';
+import { useResourcePermissionState } from '../useResourcePermissionState';
+
+const mockUseGetResourcePermissionsQuery = jest.fn();
+const mockUseUpdateResourcePermissionsMutation = jest.fn();
+
+jest.mock('librechat-data-provider/react-query', () => ({
+ useGetResourcePermissionsQuery: (...args: unknown[]) =>
+ mockUseGetResourcePermissionsQuery(...args),
+ useUpdateResourcePermissionsMutation: () => mockUseUpdateResourcePermissionsMutation(),
+}));
+
+jest.mock('~/utils', () => {
+ const { AccessRoleIds: roleIds } = jest.requireActual('librechat-data-provider');
+ return {
+ getResourceConfig: () => ({ defaultViewerRoleId: roleIds.AGENT_VIEWER }),
+ };
+});
+
+describe('useResourcePermissionState', () => {
+ beforeEach(() => {
+ mockUseUpdateResourcePermissionsMutation.mockReturnValue({ mutateAsync: jest.fn() });
+ mockUseGetResourcePermissionsQuery.mockReturnValue({
+ data: {
+ principals: [
+ {
+ type: PrincipalType.ROLE,
+ id: 'role-with-insights',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ {
+ type: PrincipalType.ROLE,
+ id: 'role-without-insights',
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: false,
+ },
+ ],
+ },
+ isLoading: false,
+ isFetching: false,
+ error: null,
+ refetch: jest.fn(),
+ });
+ });
+
+ it('preserves Insights access in the persisted-share snapshot', () => {
+ const { result } = renderHook(() =>
+ useResourcePermissionState(ResourceType.AGENT, 'agent-db-id', true),
+ );
+
+ expect(result.current.currentShares).toEqual([
+ expect.objectContaining({ id: 'role-with-insights', viewInsights: true }),
+ expect.objectContaining({ id: 'role-without-insights', viewInsights: false }),
+ ]);
+ });
+});
diff --git a/client/src/hooks/Sharing/useResourcePermissionState.ts b/client/src/hooks/Sharing/useResourcePermissionState.ts
index 875fe17832..1f9d617d8b 100644
--- a/client/src/hooks/Sharing/useResourcePermissionState.ts
+++ b/client/src/hooks/Sharing/useResourcePermissionState.ts
@@ -47,6 +47,7 @@ export const useResourcePermissionState = (
description: principal.description,
accessRoleId: principal.accessRoleId,
idOnTheSource: principal.idOnTheSource,
+ viewInsights: principal.viewInsights,
})) || [];
const currentIsPublic = permissionsData?.public ?? false;
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index da18254b50..b53665905b 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1710,6 +1710,9 @@
"com_ui_permissions_failed_load": "Failed to load permissions. Please try again.",
"com_ui_permissions_failed_update": "Failed to update permissions. Please try again.",
"com_ui_permissions_updated_success": "Permissions updated successfully",
+ "com_ui_view_agent_insights": "View insights",
+ "com_ui_view_agent_insights_description": "Allows this principal to view usage and conversation content for this agent.",
+ "com_ui_view_agent_insights_admin_description": "Administrators always have access to insights.",
"com_ui_pin": "Pin",
"com_ui_pin_error": "Failed to pin conversation",
"com_ui_pinned": "Pinned",
@@ -2542,13 +2545,19 @@
"com_insights_navigation": "Insights",
"com_insights_loading": "Loading insights",
"com_insights_load_error": "Insights could not be loaded. Try again.",
+ "com_insights_forbidden": "You do not have access to insights for these agents.",
+ "com_insights_all_agents": "All {{count}} agents",
+ "com_insights_agents_selected": "{{count}} agents",
+ "com_insights_select_all_agents": "Select all",
"com_insights_total_users": "Unique users",
"com_insights_total_conversations": "Conversations",
+ "com_insights_conversations_definition": "Conversations created during the selected period for the selected agents.",
"com_insights_churned_users": "Churned users",
- "com_insights_churned_users_definition": "Users whose latest message sent to an assistant reached 28 days old during the selected date range.",
+ "com_insights_churned_users_definition": "Users whose latest message to any selected agent reached 28 days old during the selected date range.",
"com_insights_top_users": "Top users",
"com_insights_no_data": "No data yet",
"com_insights_user": "User",
+ "com_insights_agent": "Agent",
"com_insights_unknown_user": "Unknown user",
"com_insights_chats": "Chats",
"com_insights_search_placeholder": "Search by chat id or user",
diff --git a/docs/agent-insights-access-design.md b/docs/agent-insights-access-design.md
new file mode 100644
index 0000000000..334fd8e34a
--- /dev/null
+++ b/docs/agent-insights-access-design.md
@@ -0,0 +1,90 @@
+# Agent-Scoped Insights Design
+
+Status: design reference for work based on `upstream/dev` after PR #14898.
+
+## Access Model
+
+- `ENABLE_INSIGHTS` remains the only feature flag.
+- Literal tenant admins can view insights for every current persisted agent.
+- A global `read:insights` grant permits viewing every current persisted agent.
+- Otherwise, a user needs at least one effective per-agent insights grant to open Insights.
+- Add `PermissionBits.VIEW_INSIGHTS = 16` to the existing agent ACL entry.
+- One ACL entry must contain both `VIEW` and `VIEW_INSIGHTS`; bits from separate entries do not combine.
+- Users, groups, and roles can receive the bit. Public principals cannot.
+- Agent creators and owners do not receive it automatically. Do not backfill existing ACL entries.
+- Only literal admins can change the bit, for any agent in their tenant.
+- Ordinary dashboard reads are not written to the audit log.
+
+## Permission Updates
+
+- Extend the existing agent sharing dialog and permission update API.
+- Show an admin-only **View insights** checkbox on each principal row.
+- Explain: "Allows this principal to view usage and conversation content for this agent."
+- Treat `viewInsights` as tri-state: omitted preserves the bit, `true` adds it, and `false` removes it.
+- Removing ordinary `VIEW` also removes the dependent insights bit.
+- Save role and insights changes through the existing bulk transaction boundary. Each ACL document is updated atomically.
+- Audit each actual insights grant or revoke separately. Follow `AUDIT_LOG_FAIL_CLOSED`; compensate any transition that cannot be audited, and do not audit no-op saves.
+
+## API And Authorization
+
+- Replace `/api/admin/insights` with `/api/insights`; no compatibility alias is required.
+- Keep `/api/insights/access` as a lightweight sidebar authorization check.
+- Outside Insights, the sidebar calls `/access`. On Insights itself, skip `/access` and call `/api/insights` immediately.
+- `/api/insights` independently resolves authorization and validates the requested agent IDs before starting its data aggregations in parallel.
+- The main response includes the authorized alphabetized `{ id, name }` agent list and dashboard data.
+- Omitted `agentIds` means all currently authorized agents. Repeated `agentIds` request an exact subset.
+- Sort and deduplicate IDs. Return `403` if any requested ID is missing or unauthorized.
+- Return `404` when the feature flag is off. Return `403` when the feature is on but the user has no accessible agents.
+- Resolve access on every protected request; do not add an authorization cache.
+- Every Agent, ACL, Conversation, Message, and User query must be tenant-scoped.
+- Transcript and attachment viewing are out of scope.
+
+## Agent Filter
+
+- Put a simple multi-select in the sticky header before the date controls.
+- Show current persisted agents only, in alphabetical order. Include agents with no activity.
+- Do not show deleted agents or their historical data.
+- Select all accessible agents by default, without a synthetic "All" row.
+- Provide a **Select all** command and prevent an empty selection.
+- Keep a one-agent selector visible but disabled.
+- Show one agent name, `N agents`, or `All N agents` in the trigger.
+- For duplicate names only, append a short stable agent ID.
+- Preserve the date range and conversation search when the filter changes; reset conversation pagination.
+- Omit `agentIds` from the URL for the default all-agent view; use repeated values for a subset.
+- Reserve the Insights icon slot while access loads so the icon rail does not move.
+
+## Metric Attribution
+
+- Add an immutable, server-owned `initial_agent_id` to conversations.
+- On insert, set it to the verified same-tenant persisted agent ID, or explicitly to `null` when the conversation did not start with one.
+- Never accept client writes to `initial_agent_id` and never change it after insertion.
+- Do not migrate existing conversations. For legacy rows where the field is absent, fall back to `agent_id`.
+- Conversation metrics and the conversations table use `initial_agent_id`, or the legacy fallback, as the primary agent.
+- Show only that primary agent in each conversations-table row.
+- Assistant messages use the persisted top-level `Message.model` agent ID.
+- User messages, which do not consistently store an agent ID, inherit the conversation's primary agent.
+- Ignore nested agent IDs in message content; subagent activity does not grant access to the parent conversation.
+- Exclude persisted `subagentThread` conversations and messages as standalone Insights data.
+- In a mixed-agent conversation, conversation metrics remain with the primary agent while assistant messages and output tokens can count for the agent in `Message.model`.
+- Unique users include users with any attributed message.
+- Top users counts attributed messages and distinct conversations containing them.
+- Churn uses user-authored messages only, across all selected agents, with the existing 28-day threshold.
+- Keep the Conversations label and add a tooltip stating that it counts conversations created during the selected period.
+- Text search affects only the conversations table. Agent and date filters affect every panel.
+- Archived and automated top-level persisted-agent conversations remain included.
+- Temporary, unattributed, deleted-agent, remote-agent, ephemeral-agent, and newly created normal chats later converted to agents are excluded.
+- Empty periods keep the dashboard visible, show zero summaries, and show localized empty states.
+
+## DocumentDB Constraints
+
+- Do not use `$facet` or correlated `$lookup` pipelines.
+- Bound conversation agent filters by indexed persisted fields before projection. Bound message queries by tenant and date before joining.
+- Use equality `$lookup` only where user messages must inherit conversation attribution, then validate tenant and owner after the join.
+- Add the required conversation agent/date index and message attribution index.
+- Cover the final pipelines in the DocumentDB compatibility tests.
+
+## Delivery
+
+- Implement the complete change in one PR.
+- Add the required indexes with the code; no separate index rollout is needed at current query volume.
+- Preserve the existing date, search, pagination, churn, and empty-state behavior except where this document explicitly changes it.
diff --git a/packages/api/src/acl/accessControlService.spec.ts b/packages/api/src/acl/accessControlService.spec.ts
index 40df893b05..474ad33aec 100644
--- a/packages/api/src/acl/accessControlService.spec.ts
+++ b/packages/api/src/acl/accessControlService.spec.ts
@@ -1,7 +1,14 @@
import mongoose, { Types, Model } from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
-import { ResourceType, AccessRoleIds, PrincipalType } from 'librechat-data-provider';
import { createModels, createMethods, logger, RoleBits } from '@librechat/data-schemas';
+import {
+ ResourceType,
+ AccessRoleIds,
+ PermissionBits,
+ PrincipalModel,
+ PrincipalType,
+} from 'librechat-data-provider';
+import type { IAclEntry } from '@librechat/data-schemas';
import { AccessControlService } from './accessControlService';
// Mock the logger
@@ -16,7 +23,7 @@ jest.mock('@librechat/data-schemas', () => ({
}));
let mongoServer: MongoMemoryServer;
-let AclEntry: Model<unknown>;
+let AclEntry: Model<IAclEntry>;
let service: AccessControlService;
let dbMethods: ReturnType<typeof createMethods>;
@@ -31,7 +38,7 @@ beforeAll(async () => {
// Initialize all models
createModels(mongoose);
- AclEntry = mongoose.models.AclEntry;
+ AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
// Create methods and seed default roles
dbMethods = createMethods(mongoose);
@@ -66,6 +73,283 @@ describe('AccessControlService', () => {
const resourceId = new Types.ObjectId();
const grantedById = new Types.ObjectId();
+ describe('bulkUpdateResourcePermissions', () => {
+ test('records only the revocation that actually deleted Insights access', async () => {
+ await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId.toString(),
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+
+ const revoke = () =>
+ service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ revokedPrincipals: [{ type: PrincipalType.USER, id: userId.toString() }],
+ grantedBy: grantedById,
+ });
+ const results = await Promise.all([revoke(), revoke()]);
+
+ expect(results.flatMap((result) => result.insightsChanges)).toEqual([
+ expect.objectContaining({ action: 'removed' }),
+ ]);
+ await expect(
+ AclEntry.exists({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ permBits: { $bitsAllSet: PermissionBits.VIEW_INSIGHTS },
+ }),
+ ).resolves.toBeNull();
+ });
+
+ test('removes duplicate ACL entries for a revoked principal', async () => {
+ await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId.toString(),
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ const entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ await AclEntry.create({ ...entry, _id: new Types.ObjectId() });
+
+ const result = await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ revokedPrincipals: [{ type: PrincipalType.USER, id: userId.toString() }],
+ grantedBy: grantedById,
+ });
+
+ expect(result.insightsChanges).toHaveLength(1);
+ await expect(
+ AclEntry.countDocuments({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }),
+ ).resolves.toBe(0);
+ });
+
+ test('removes Insights access from every duplicate ACL entry', async () => {
+ await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId.toString(),
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ const entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ await AclEntry.create({
+ ...entry,
+ _id: new Types.ObjectId(),
+ permBits: PermissionBits.VIEW,
+ });
+
+ const result = await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId.toString(),
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: false,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+
+ expect(result.insightsChanges).toEqual([expect.objectContaining({ action: 'removed' })]);
+ const entries = await AclEntry.find({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ expect(entries).toHaveLength(2);
+ expect(
+ entries.every((candidate) => (candidate.permBits & PermissionBits.VIEW_INSIGHTS) === 0),
+ ).toBe(true);
+ });
+
+ test('removes Insights from every duplicate when an assignment is rolled back', async () => {
+ await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId.toString(),
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: false,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ const entry = await AclEntry.findOne({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ await AclEntry.create({ ...entry, _id: new Types.ObjectId() });
+
+ const result = await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ id: userId.toString(),
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ viewInsights: true,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+ await service.restoreInsightsPermissionChanges({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ changes: result.insightsChanges,
+ });
+
+ const entries = await AclEntry.find({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ }).lean();
+ expect(entries).toHaveLength(2);
+ expect(
+ entries.every((candidate) => (candidate.permBits & PermissionBits.VIEW_INSIGHTS) === 0),
+ ).toBe(true);
+ });
+
+ test('audits a revoke when any duplicate ACL entry has Insights access', async () => {
+ const viewerRole = await dbMethods.findRoleByIdentifier(AccessRoleIds.AGENT_VIEWER);
+ await AclEntry.create([
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ permBits: PermissionBits.VIEW,
+ roleId: viewerRole?._id,
+ grantedBy: grantedById,
+ grantedAt: new Date(),
+ },
+ {
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ permBits: PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
+ roleId: viewerRole?._id,
+ grantedBy: grantedById,
+ grantedAt: new Date(),
+ },
+ ]);
+
+ const result = await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ revokedPrincipals: [{ type: PrincipalType.USER, id: userId.toString() }],
+ grantedBy: grantedById,
+ });
+
+ expect(result.insightsChanges).toEqual([
+ expect.objectContaining({
+ action: 'removed',
+ previousEntry: expect.objectContaining({
+ permBits: PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
+ }),
+ }),
+ ]);
+ });
+
+ test('does not treat a non-agent permission bit as an Insights revocation', async () => {
+ await AclEntry.create({
+ principalType: PrincipalType.USER,
+ principalId: userId,
+ principalModel: PrincipalModel.USER,
+ resourceType: ResourceType.PROMPTGROUP,
+ resourceId,
+ permBits: PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
+ grantedBy: grantedById,
+ grantedAt: new Date(),
+ });
+
+ const result = await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.PROMPTGROUP,
+ resourceId,
+ revokedPrincipals: [{ type: PrincipalType.USER, id: userId.toString() }],
+ grantedBy: grantedById,
+ });
+
+ expect(result.insightsChanges).toEqual([]);
+ await expect(
+ AclEntry.exists({ resourceType: ResourceType.PROMPTGROUP, resourceId }),
+ ).resolves.toBeNull();
+ });
+
+ test('rejects a missing user id instead of generating an orphan ACL id', async () => {
+ const result = await service.bulkUpdateResourcePermissions({
+ resourceType: ResourceType.AGENT,
+ resourceId,
+ updatedPrincipals: [
+ {
+ type: PrincipalType.USER,
+ accessRoleId: AccessRoleIds.AGENT_VIEWER,
+ },
+ ],
+ grantedBy: grantedById,
+ });
+
+ expect(result.granted).toEqual([]);
+ expect(result.errors).toEqual([
+ expect.objectContaining({ error: 'Invalid principal ID: undefined' }),
+ ]);
+ await expect(
+ AclEntry.exists({ resourceType: ResourceType.AGENT, resourceId }),
+ ).resolves.toBeNull();
+ });
+ });
+
describe('grantPermission', () => {
describe('validation', () => {
test('should throw error for invalid principal type', async () => {
diff --git a/packages/api/src/acl/accessControlService.ts b/packages/api/src/acl/accessControlService.ts
index c7b9da5616..f82e23578e 100644
--- a/packages/api/src/acl/accessControlService.ts
+++ b/packages/api/src/acl/accessControlService.ts
@@ -1,25 +1,51 @@
import { Types } from 'mongoose';
-import { createMethods, logger } from '@librechat/data-schemas';
+import {
+ createMethods,
+ getTransactionSupport,
+ logger,
+ RoleBits,
+ runAfterTransaction,
+} from '@librechat/data-schemas';
import {
CacheKeys,
AccessRoleIds,
PermissionBits,
+ PrincipalModel,
PrincipalType,
ResourceType,
} from 'librechat-data-provider';
import type { AllMethods, IAclEntry } from '@librechat/data-schemas';
import type { ClientSession, DeleteResult } from 'mongoose';
-
+import type { TPrincipal } from 'librechat-data-provider';
+import type { InsightsPermissionChange, InsightsWrittenEntry } from './insightsPermissions';
import type { ResolvedPrincipal } from '~/types/principal';
import { userPrincipalsCache } from '~/cache';
+type BulkPrincipal = Omit<TPrincipal, 'id'> & {
+ id?: string | Types.ObjectId;
+ memberIds?: string[];
+};
+
+export type BulkPermissionUpdateResult = {
+ granted: BulkPrincipal[];
+ updated: BulkPrincipal[];
+ revoked: BulkPrincipal[];
+ insightsChanges: InsightsPermissionChange[];
+ errors: Array<{ principal: BulkPrincipal; error: string }>;
+};
+
export class AccessControlService {
private _dbMethods: AllMethods;
-
- constructor(mongoose: typeof import('mongoose')) {
- this._dbMethods = createMethods(mongoose, {
- getCache: (key) => (key === CacheKeys.USER_PRINCIPALS ? userPrincipalsCache() : undefined),
- });
+ private _mongoose: typeof import('mongoose');
+ private _transactionSupportCache: boolean | null = null;
+
+ constructor(mongoose: typeof import('mongoose'), dbMethods?: AllMethods) {
+ this._mongoose = mongoose;
+ this._dbMethods =
+ dbMethods ??
+ createMethods(mongoose, {
+ getCache: (key) => (key === CacheKeys.USER_PRINCIPALS ? userPrincipalsCache() : undefined),
+ });
}
/**
@@ -378,6 +404,415 @@ export class AccessControlService {
}
}
+ public async bulkUpdateResourcePermissions({
+ resourceType,
+ resourceId,
+ updatedPrincipals = [],
+ revokedPrincipals = [],
+ grantedBy,
+ session,
+ }: {
+ resourceType: ResourceType;
+ resourceId: string | Types.ObjectId;
+ updatedPrincipals?: BulkPrincipal[];
+ revokedPrincipals?: BulkPrincipal[];
+ grantedBy: string | Types.ObjectId;
+ session?: ClientSession;
+ }): Promise<BulkPermissionUpdateResult> {
+ const supportsTransactions = await getTransactionSupport(
+ this._mongoose,
+ this._transactionSupportCache,
+ );
+ this._transactionSupportCache = supportsTransactions;
+ let localSession = session;
+ let shouldEndSession = false;
+
+ try {
+ if (!Array.isArray(updatedPrincipals)) {
+ throw new Error('updatedPrincipals must be an array');
+ }
+ if (!Array.isArray(revokedPrincipals)) {
+ throw new Error('revokedPrincipals must be an array');
+ }
+ if (!resourceId || !Types.ObjectId.isValid(resourceId)) {
+ throw new Error(`Invalid resource ID: ${resourceId}`);
+ }
+
+ if (!localSession && supportsTransactions) {
+ localSession = await this._mongoose.startSession();
+ localSession.startTransaction();
+ shouldEndSession = true;
+ }
+ const sessionOptions = localSession ? { session: localSession } : {};
+ const [roles, currentEntries] = await Promise.all([
+ this._dbMethods.findRolesByResourceType(resourceType),
+ resourceType === ResourceType.AGENT
+ ? this._dbMethods.findEntriesByResource(resourceType, resourceId, localSession)
+ : Promise.resolve([]),
+ ]);
+ const rolesMap = new Map(roles.map((role) => [role.accessRoleId, role]));
+ const results: BulkPermissionUpdateResult = {
+ granted: [],
+ updated: [],
+ revoked: [],
+ insightsChanges: [],
+ errors: [],
+ };
+ const bulkWrites: Parameters<AllMethods['bulkWriteAclEntries']>[0] = [];
+ const insightsChangesByBulkWriteIndex = new Map<number, InsightsPermissionChange>();
+
+ const updatedPrincipalKey = (principal: BulkPrincipal | null | undefined) => {
+ if (!principal?.type) return null;
+ if (principal.type === PrincipalType.PUBLIC) return `${PrincipalType.PUBLIC}:null`;
+ return principal.id == null ? null : `${principal.type}:${principal.id}`;
+ };
+ const lastUpdateIndexByPrincipal = new Map<string, number>();
+ updatedPrincipals.forEach((principal, index) => {
+ const key = updatedPrincipalKey(principal);
+ if (key != null) lastUpdateIndexByPrincipal.set(key, index);
+ });
+ const effectiveUpdatedPrincipals = updatedPrincipals.filter((principal, index) => {
+ const key = updatedPrincipalKey(principal);
+ return key == null || lastUpdateIndexByPrincipal.get(key) === index;
+ });
+
+ /**
+ * A grant wins when the same non-public principal is also in the revoke list. The client can
+ * produce both forms when `id` and `idOnTheSource` differ, and applying the revoke would remove
+ * the permission just written. Public access is excluded because an explicit disable must win.
+ */
+ const grantedPrincipalKeys = new Set<string>();
+ const principalKey = (principal: BulkPrincipal) => `${principal.type}:${principal.id}`;
+ const queryPrincipalId = (principal: BulkPrincipal) => {
+ if (principal.type === PrincipalType.ROLE) {
+ if (typeof principal.id !== 'string' || principal.id.trim().length === 0) {
+ throw new Error(`Invalid role ID: ${principal.id}`);
+ }
+ return principal.id;
+ }
+ const id = principal.id?.toString();
+ if (!id || !Types.ObjectId.isValid(id)) {
+ throw new Error(`Invalid principal ID: ${principal.id}`);
+ }
+ return new Types.ObjectId(id);
+ };
+ const currentEntriesByPrincipal = new Map<string, IAclEntry>();
+ for (const entry of currentEntries) {
+ const key = `${entry.principalType}:${entry.principalId == null ? 'null' : entry.principalId.toString()}`;
+ const current = currentEntriesByPrincipal.get(key);
+ const entryHasInsights =
+ (entry.permBits & PermissionBits.VIEW_INSIGHTS) === PermissionBits.VIEW_INSIGHTS;
+ const currentHasInsights =
+ current != null &&
+ (current.permBits & PermissionBits.VIEW_INSIGHTS) === PermissionBits.VIEW_INSIGHTS;
+ if (!current || (entryHasInsights && !currentHasInsights)) {
+ currentEntriesByPrincipal.set(key, entry);
+ }
+ }
+
+ for (const principal of effectiveUpdatedPrincipals) {
+ try {
+ if (!principal?.accessRoleId) {
+ results.errors.push({
+ principal,
+ error: 'accessRoleId is required for updated principals',
+ });
+ continue;
+ }
+ const role = rolesMap.get(principal.accessRoleId);
+ if (!role) {
+ results.errors.push({
+ principal,
+ error: `Role ${principal.accessRoleId} not found`,
+ });
+ continue;
+ }
+
+ const query: Record<string, unknown> = {
+ principalType: principal.type,
+ resourceType,
+ resourceId,
+ };
+ if (principal.type !== PrincipalType.PUBLIC) {
+ query.principalId = queryPrincipalId(principal);
+ }
+
+ const existingEntry = currentEntriesByPrincipal.get(
+ `${principal.type}:${principal.type === PrincipalType.PUBLIC ? 'null' : principal.id}`,
+ );
+ const hadInsights =
+ ((existingEntry?.permBits ?? 0) & PermissionBits.VIEW_INSIGHTS) ===
+ PermissionBits.VIEW_INSIGHTS;
+ const roleCanView = (role.permBits & PermissionBits.VIEW) === PermissionBits.VIEW;
+ const requestedInsights =
+ typeof principal.viewInsights === 'boolean' ? principal.viewInsights : undefined;
+ const preserveInsights =
+ resourceType === ResourceType.AGENT &&
+ principal.type !== PrincipalType.PUBLIC &&
+ roleCanView &&
+ requestedInsights === undefined;
+ const wantsInsights =
+ resourceType === ResourceType.AGENT &&
+ principal.type !== PrincipalType.PUBLIC &&
+ roleCanView &&
+ (requestedInsights === undefined ? hadInsights : requestedInsights);
+ const permBits = wantsInsights
+ ? role.permBits | PermissionBits.VIEW_INSIGHTS
+ : role.permBits & ~PermissionBits.VIEW_INSIGHTS;
+ const grantedAt = new Date();
+ const principalModelMap: Partial<Record<PrincipalType, PrincipalModel>> = {
+ [PrincipalType.USER]: PrincipalModel.USER,
+ [PrincipalType.GROUP]: PrincipalModel.GROUP,
+ [PrincipalType.ROLE]: PrincipalModel.ROLE,
+ };
+ const update = {
+ $set: {
+ ...(!preserveInsights && { permBits }),
+ roleId: role._id,
+ grantedBy,
+ grantedAt,
+ },
+ ...(preserveInsights && {
+ $bit: {
+ permBits: {
+ or: role.permBits & RoleBits.OWNER,
+ and: ~(RoleBits.OWNER & ~role.permBits),
+ },
+ },
+ }),
+ $setOnInsert: {
+ principalType: principal.type,
+ resourceType,
+ resourceId,
+ ...(principal.type !== PrincipalType.PUBLIC && {
+ principalId: queryPrincipalId(principal),
+ principalModel: principalModelMap[principal.type],
+ }),
+ },
+ };
+ const bulkWriteIndex = bulkWrites.length;
+ bulkWrites.push({
+ updateMany: { filter: query, update, upsert: true },
+ });
+ results.granted.push({
+ type: principal.type,
+ id: principal.id,
+ name: principal.name,
+ email: principal.email,
+ source: principal.source,
+ avatar: principal.avatar,
+ description: principal.description,
+ idOnTheSource: principal.idOnTheSource,
+ accessRoleId: principal.accessRoleId,
+ memberCount: principal.memberCount,
+ memberIds: principal.memberIds,
+ ...(resourceType === ResourceType.AGENT ? { viewInsights: wantsInsights } : {}),
+ });
+ if (hadInsights !== wantsInsights) {
+ const writtenEntry: InsightsWrittenEntry = {
+ permBits,
+ roleId: role._id,
+ grantedBy,
+ grantedAt,
+ };
+ const change: InsightsPermissionChange = {
+ action: wantsInsights ? 'assigned' : 'removed',
+ previousEntry: existingEntry ?? null,
+ writtenEntry,
+ principal: { type: principal.type, id: principal.id, name: principal.name },
+ };
+ results.insightsChanges.push(change);
+ insightsChangesByBulkWriteIndex.set(bulkWriteIndex, change);
+ }
+ if (principal.type !== PrincipalType.PUBLIC) {
+ grantedPrincipalKeys.add(principalKey(principal));
+ }
+ } catch (error) {
+ results.errors.push({
+ principal,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ if (bulkWrites.length > 0) {
+ const bulkWriteResult = await this._dbMethods.bulkWriteAclEntries(
+ bulkWrites,
+ sessionOptions,
+ );
+ for (const [writeIndex, change] of insightsChangesByBulkWriteIndex) {
+ if (bulkWriteResult.upsertedIds?.[writeIndex] && change.previousEntry) {
+ change.previousEntry = null;
+ }
+ }
+ }
+
+ for (const principal of revokedPrincipals) {
+ try {
+ if (
+ principal?.type !== PrincipalType.PUBLIC &&
+ principal != null &&
+ grantedPrincipalKeys.has(principalKey(principal))
+ ) {
+ continue;
+ }
+ const query: Record<string, unknown> = {
+ principalType: principal.type,
+ resourceType,
+ resourceId,
+ };
+ if (principal.type !== PrincipalType.PUBLIC) {
+ query.principalId = queryPrincipalId(principal);
+ }
+ const deleteResult = await this._dbMethods.deleteAclEntries(query, sessionOptions);
+ const existingEntry = currentEntriesByPrincipal.get(
+ `${principal.type}:${principal.type === PrincipalType.PUBLIC ? 'null' : principal.id}`,
+ );
+ results.revoked.push({
+ type: principal.type,
+ id: principal.id,
+ name: principal.name,
+ email: principal.email,
+ source: principal.source,
+ avatar: principal.avatar,
+ description: principal.description,
+ idOnTheSource: principal.idOnTheSource,
+ memberCount: principal.memberCount,
+ });
+ if (
+ resourceType === ResourceType.AGENT &&
+ deleteResult.deletedCount > 0 &&
+ existingEntry &&
+ (existingEntry.permBits & PermissionBits.VIEW_INSIGHTS) === PermissionBits.VIEW_INSIGHTS
+ ) {
+ results.insightsChanges.push({
+ action: 'removed',
+ previousEntry: existingEntry,
+ writtenEntry: null,
+ principal: { type: principal.type, id: principal.id, name: principal.name },
+ });
+ }
+ } catch (error) {
+ results.errors.push({
+ principal,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ if (shouldEndSession && supportsTransactions) {
+ await localSession?.commitTransaction();
+ }
+ if (resourceType === ResourceType.PROMPTGROUP) {
+ await runAfterTransaction(localSession, () =>
+ this._dbMethods.invalidatePromptGroupAccessContext(),
+ );
+ }
+ return results;
+ } catch (error) {
+ if (shouldEndSession && supportsTransactions) {
+ try {
+ await localSession?.abortTransaction();
+ } catch (transactionError) {
+ logger.error(
+ '[AccessControlService.bulkUpdateResourcePermissions] Error aborting transaction:',
+ transactionError,
+ );
+ }
+ }
+ logger.error(
+ `[AccessControlService.bulkUpdateResourcePermissions] Error: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ throw error;
+ } finally {
+ if (shouldEndSession && localSession) {
+ await localSession.endSession();
+ }
+ }
+ }
+
+ public async restoreInsightsPermissionChanges({
+ resourceType,
+ resourceId,
+ changes = [],
+ }: {
+ resourceType: ResourceType;
+ resourceId: string | Types.ObjectId;
+ changes?: InsightsPermissionChange[];
+ }): Promise<void> {
+ const operations: Parameters<AllMethods['bulkWriteAclEntries']>[0] = changes.flatMap(
+ (change): Parameters<AllMethods['bulkWriteAclEntries']>[0] => {
+ const filter: Record<string, unknown> = {
+ principalType: change.principal.type,
+ resourceType,
+ resourceId,
+ };
+ if (change.principal.type !== PrincipalType.PUBLIC) {
+ if (change.principal.type === PrincipalType.ROLE) {
+ filter.principalId = change.principal.id;
+ } else {
+ const id = change.principal.id?.toString();
+ if (!id || !Types.ObjectId.isValid(id)) {
+ throw new Error(`Invalid principal ID: ${change.principal.id}`);
+ }
+ filter.principalId = new Types.ObjectId(id);
+ }
+ }
+ if (change.previousEntry && change.writtenEntry) {
+ return [
+ {
+ replaceOne: {
+ filter: { _id: change.previousEntry._id, ...change.writtenEntry },
+ replacement: change.previousEntry,
+ timestamps: false,
+ },
+ },
+ {
+ updateMany: {
+ filter: {
+ ...filter,
+ ...change.writtenEntry,
+ _id: { $ne: change.previousEntry._id },
+ },
+ update: {
+ $set: {
+ permBits: change.previousEntry.permBits,
+ roleId: change.previousEntry.roleId,
+ grantedBy: change.previousEntry.grantedBy,
+ grantedAt: change.previousEntry.grantedAt,
+ },
+ },
+ timestamps: false,
+ },
+ },
+ ];
+ }
+ if (change.previousEntry) {
+ return [
+ {
+ updateOne: {
+ filter,
+ update: { $setOnInsert: change.previousEntry },
+ upsert: true,
+ timestamps: false,
+ },
+ },
+ ];
+ }
+ return [
+ {
+ deleteMany: {
+ filter: { ...filter, ...change.writtenEntry },
+ },
+ },
+ ];
+ },
+ );
+ if (operations.length > 0) {
+ await this._dbMethods.bulkWriteAclEntries(operations);
+ }
+ }
+
/**
* Check if a user has specific permission bits on a resource
* @param {Object} params - Parameters for checking permissions
diff --git a/packages/api/src/acl/insightsPermissions.spec.ts b/packages/api/src/acl/insightsPermissions.spec.ts
new file mode 100644
index 0000000000..cdbe4bdaaa
--- /dev/null
+++ b/packages/api/src/acl/insightsPermissions.spec.ts
@@ -0,0 +1,73 @@
+import { PermissionBits, PrincipalType, ResourceType, SystemRoles } from 'librechat-data-provider';
+import type { ServerRequest } from '~/types';
+import {
+ auditInsightsPermissionChanges,
+ maskAgentInsightsBit,
+ validateInsightsPermissionUpdates,
+} from './insightsPermissions';
+
+describe('Insights permissions', () => {
+ test('allows only admins to assign a boolean agent Insights grant', () => {
+ expect(
+ validateInsightsPermissionUpdates({
+ resourceType: ResourceType.AGENT,
+ userRole: SystemRoles.USER,
+ updatedPrincipals: [{ type: PrincipalType.USER, viewInsights: true }],
+ }),
+ ).toEqual({ status: 403, error: 'Only administrators can change Insights access' });
+ expect(
+ validateInsightsPermissionUpdates({
+ resourceType: ResourceType.AGENT,
+ userRole: SystemRoles.ADMIN,
+ updatedPrincipals: [{ type: PrincipalType.USER, viewInsights: true }],
+ }),
+ ).toBeNull();
+ });
+
+ test('hides the Insights bit from non-admin effective permissions', () => {
+ expect(
+ maskAgentInsightsBit({
+ resourceType: ResourceType.AGENT,
+ userRole: SystemRoles.USER,
+ permBits: PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
+ }),
+ ).toBe(PermissionBits.VIEW);
+ });
+
+ test('restores unaudited changes when fail-closed audit persistence fails', async () => {
+ const restore = jest.fn().mockResolvedValue(undefined);
+ const record = jest.fn().mockRejectedValue(new Error('audit unavailable'));
+ const change = {
+ action: 'assigned' as const,
+ previousEntry: null,
+ writtenEntry: null,
+ principal: { type: PrincipalType.ROLE, id: SystemRoles.USER },
+ };
+ const req = {
+ user: {
+ _id: { toString: () => 'admin-id' },
+ id: 'admin-id',
+ email: '[email protected]',
+ role: SystemRoles.ADMIN,
+ tenantId: 'tenant-a',
+ },
+ headers: {},
+ } as unknown as ServerRequest;
+
+ await expect(
+ auditInsightsPermissionChanges({
+ req,
+ resourceId: 'resource-id',
+ changes: [change],
+ failClosed: true,
+ deps: {
+ getAgent: jest.fn().mockResolvedValue({ id: 'agent-id', name: 'Agent' }),
+ recordAuditEntry: record,
+ restoreInsightsPermissionChanges: restore,
+ logger: { error: jest.fn() },
+ },
+ }),
+ ).rejects.toMatchObject({ statusCode: 500 });
+ expect(restore).toHaveBeenCalledWith([change]);
+ });
+});
diff --git a/packages/api/src/acl/insightsPermissions.ts b/packages/api/src/acl/insightsPermissions.ts
new file mode 100644
index 0000000000..7f03c3a468
--- /dev/null
+++ b/packages/api/src/acl/insightsPermissions.ts
@@ -0,0 +1,229 @@
+import { PermissionBits, PrincipalType, ResourceType, SystemRoles } from 'librechat-data-provider';
+import type {
+ IAclEntry,
+ IUser,
+ RecordAuditEntryInput,
+ RecordAuditEntryOptions,
+} from '@librechat/data-schemas';
+import type { TPrincipal } from 'librechat-data-provider';
+import type { Types } from 'mongoose';
+import type { ServerRequest } from '~/types';
+import { buildAuditContext } from '~/admin/context';
+
+export type InsightsPermissionPrincipal = {
+ type: PrincipalType;
+ id?: string | Types.ObjectId | null;
+ name?: string;
+};
+
+export type InsightsWrittenEntry = {
+ permBits: number;
+ roleId: Types.ObjectId;
+ grantedBy: string | Types.ObjectId;
+ grantedAt: Date;
+};
+
+export type InsightsPermissionChange = {
+ action: 'assigned' | 'removed';
+ previousEntry: IAclEntry | null;
+ writtenEntry: InsightsWrittenEntry | null;
+ principal: InsightsPermissionPrincipal;
+};
+
+type ValidationResult = { status: 400 | 403; error: string } | null;
+
+type AuditDeps = {
+ getAgent: (
+ filter: Record<string, unknown>,
+ projection: string,
+ ) => Promise<{ id: string; name?: string } | null>;
+ recordAuditEntry: (
+ input: RecordAuditEntryInput,
+ options?: RecordAuditEntryOptions,
+ ) => Promise<unknown>;
+ restoreInsightsPermissionChanges: (changes: InsightsPermissionChange[]) => Promise<void>;
+ logger: {
+ error: (message: string, error?: unknown) => void;
+ };
+};
+
+const hasOwn = (value: unknown, key: string): boolean =>
+ value != null && typeof value === 'object' && Object.prototype.hasOwnProperty.call(value, key);
+
+export function validateInsightsPermissionUpdates({
+ resourceType,
+ userRole,
+ updatedPrincipals,
+}: {
+ resourceType: ResourceType;
+ userRole?: string;
+ updatedPrincipals: unknown[];
+}): ValidationResult {
+ if (resourceType !== ResourceType.AGENT) {
+ return null;
+ }
+
+ const insightsUpdates = updatedPrincipals.filter((principal) =>
+ hasOwn(principal, 'viewInsights'),
+ );
+ if (
+ insightsUpdates.some(
+ (principal) => typeof (principal as { viewInsights?: unknown }).viewInsights !== 'boolean',
+ )
+ ) {
+ return { status: 400, error: 'viewInsights must be a boolean when provided' };
+ }
+ if (insightsUpdates.length > 0 && userRole !== SystemRoles.ADMIN) {
+ return { status: 403, error: 'Only administrators can change Insights access' };
+ }
+ if (
+ insightsUpdates.some(
+ (principal) => (principal as { type?: unknown }).type === PrincipalType.PUBLIC,
+ )
+ ) {
+ return { status: 400, error: 'Public principals cannot receive Insights access' };
+ }
+ return null;
+}
+
+export function maskAgentInsightsBit({
+ resourceType,
+ userRole,
+ permBits,
+}: {
+ resourceType: ResourceType;
+ userRole?: string;
+ permBits: number;
+}): number {
+ return resourceType === ResourceType.AGENT && userRole !== SystemRoles.ADMIN
+ ? permBits & ~PermissionBits.VIEW_INSIGHTS
+ : permBits;
+}
+
+export function sanitizeInsightsPermissionPrincipals({
+ resourceType,
+ userRole,
+ principals,
+}: {
+ resourceType: ResourceType;
+ userRole?: string;
+ principals: TPrincipal[];
+}): TPrincipal[] {
+ if (resourceType !== ResourceType.AGENT || userRole === SystemRoles.ADMIN) {
+ return principals;
+ }
+ return principals.map(({ viewInsights: _protected, ...principal }) => principal);
+}
+
+export function getInsightsPrincipalState({
+ principalType,
+ principalRole,
+ requesterRole,
+ permBits,
+}: {
+ principalType: PrincipalType;
+ principalRole?: string;
+ requesterRole?: string;
+ permBits: number;
+}): { isAdmin?: true; viewInsights?: boolean } {
+ const isAdmin =
+ (principalType === PrincipalType.USER || principalType === PrincipalType.ROLE) &&
+ principalRole === SystemRoles.ADMIN;
+ return {
+ ...(isAdmin ? { isAdmin: true } : {}),
+ ...(requesterRole === SystemRoles.ADMIN
+ ? {
+ viewInsights: (permBits & PermissionBits.VIEW_INSIGHTS) === PermissionBits.VIEW_INSIGHTS,
+ }
+ : {}),
+ };
+}
+
+function statusError(message: string): Error & { statusCode: number } {
+ return Object.assign(new Error(message), { statusCode: 500 });
+}
+
+export async function auditInsightsPermissionChanges({
+ req,
+ resourceId,
+ changes,
+ failClosed,
+ deps,
+}: {
+ req: ServerRequest;
+ resourceId: string;
+ changes: InsightsPermissionChange[];
+ failClosed: boolean;
+ deps: AuditDeps;
+}): Promise<void> {
+ if (changes.length === 0) {
+ return;
+ }
+
+ const user = req.user as IUser | undefined;
+ const actorId = user?._id?.toString() ?? user?.id;
+ if (!user || !actorId) {
+ throw statusError('Authenticated user required for Insights permission audit');
+ }
+
+ let agent: { id: string; name?: string } | null;
+ try {
+ agent = await deps.getAgent(
+ {
+ _id: resourceId,
+ ...(user.tenantId ? { tenantId: user.tenantId } : { tenantId: { $exists: false } }),
+ },
+ '_id id name',
+ );
+ if (!agent) {
+ throw new Error('Agent not found for Insights permission audit');
+ }
+ } catch (error) {
+ if (!failClosed) {
+ deps.logger.error('[InsightsPermissions] Audit target lookup failed', error);
+ return;
+ }
+ await deps
+ .restoreInsightsPermissionChanges(changes)
+ .catch((restoreError) =>
+ deps.logger.error('[InsightsPermissions] Permission rollback failed', restoreError),
+ );
+ throw statusError(
+ error instanceof Error ? error.message : 'Insights audit target lookup failed',
+ );
+ }
+
+ const actorName = user.name || user.username || user.email || actorId;
+ for (let index = 0; index < changes.length; index++) {
+ const change = changes[index];
+ const input: RecordAuditEntryInput = {
+ action:
+ change.action === 'assigned'
+ ? 'permission.insights_assigned'
+ : 'permission.insights_removed',
+ outcome: 'success',
+ severity: 'warning',
+ actor: { type: 'user', id: actorId, name: actorName },
+ target: { type: ResourceType.AGENT, id: agent.id, name: agent.name || agent.id },
+ metadata: {
+ principalType: change.principal.type,
+ principalId: change.principal.id?.toString() ?? '',
+ },
+ context: buildAuditContext(req),
+ tenantId: user.tenantId,
+ };
+ try {
+ await deps.recordAuditEntry(input, { failClosed });
+ } catch (error) {
+ if (failClosed) {
+ await deps
+ .restoreInsightsPermissionChanges(changes.slice(index))
+ .catch((restoreError) =>
+ deps.logger.error('[InsightsPermissions] Permission rollback failed', restoreError),
+ );
+ throw statusError(error instanceof Error ? error.message : 'Insights audit failed');
+ }
+ deps.logger.error('[InsightsPermissions] Audit persistence failed', error);
+ }
+ }
+}
diff --git a/packages/api/src/acl/middleware.spec.ts b/packages/api/src/acl/middleware.spec.ts
new file mode 100644
index 0000000000..ae98ea2993
--- /dev/null
+++ b/packages/api/src/acl/middleware.spec.ts
@@ -0,0 +1,83 @@
+import { Types } from 'mongoose';
+import { ResourceType, SystemRoles } from 'librechat-data-provider';
+import type { AllMethods } from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { AgentPermissionsRequest } from './middleware';
+import { createAgentAdminPermissionAccess } from './middleware';
+
+describe('agent admin permission access', () => {
+ const resourceId = new Types.ObjectId().toString();
+ const setup = (
+ role = SystemRoles.ADMIN,
+ resourceType = ResourceType.AGENT,
+ tenantId?: string,
+ ) => {
+ const getAgent = jest.fn().mockResolvedValue({ _id: resourceId });
+ const fallback = jest.fn();
+ const next = jest.fn();
+ const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
+ const req = { params: { resourceType, resourceId }, user: { role, tenantId } };
+ const middleware = createAgentAdminPermissionAccess({
+ getAgent: getAgent as AllMethods['getAgent'],
+ fallback,
+ });
+ return {
+ getAgent,
+ fallback,
+ next,
+ res,
+ req,
+ run: () => middleware(req as AgentPermissionsRequest, res as unknown as Response, next),
+ };
+ };
+
+ it.each(['tenant-a', undefined])('scopes the admin lookup to %s', async (tenantId) => {
+ const test = setup(SystemRoles.ADMIN, ResourceType.AGENT, tenantId);
+ await test.run();
+ expect(test.getAgent).toHaveBeenCalledWith(
+ { _id: resourceId, tenantId: tenantId ?? { $exists: false } },
+ '_id',
+ );
+ expect(test.next).toHaveBeenCalledTimes(1);
+ expect(test.fallback).not.toHaveBeenCalled();
+ });
+
+ it('uses the ordinary permission check for non-admins', async () => {
+ const test = setup(SystemRoles.USER);
+ await test.run();
+ expect(test.fallback).toHaveBeenCalled();
+ expect(test.getAgent).not.toHaveBeenCalled();
+ });
+
+ it('uses the ordinary permission check for other resource types', async () => {
+ const test = setup(SystemRoles.ADMIN, ResourceType.PROMPTGROUP);
+ await test.run();
+ expect(test.fallback).toHaveBeenCalled();
+ expect(test.getAgent).not.toHaveBeenCalled();
+ });
+
+ it('rejects malformed IDs before looking up an agent', async () => {
+ const test = setup();
+ test.req.params.resourceId = 'invalid';
+ await test.run();
+ expect(test.res.status).toHaveBeenCalledWith(404);
+ expect(test.getAgent).not.toHaveBeenCalled();
+ expect(test.next).not.toHaveBeenCalled();
+ });
+
+ it('rejects missing or out-of-tenant agents', async () => {
+ const test = setup();
+ test.getAgent.mockResolvedValue(null);
+ await test.run();
+ expect(test.res.status).toHaveBeenCalledWith(404);
+ expect(test.next).not.toHaveBeenCalled();
+ });
+
+ it('fails closed on lookup errors', async () => {
+ const test = setup();
+ test.getAgent.mockRejectedValue(new Error('database unavailable'));
+ await test.run();
+ expect(test.res.status).toHaveBeenCalledWith(500);
+ expect(test.next).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/acl/middleware.ts b/packages/api/src/acl/middleware.ts
new file mode 100644
index 0000000000..587e51fa3b
--- /dev/null
+++ b/packages/api/src/acl/middleware.ts
@@ -0,0 +1,47 @@
+import { Types } from 'mongoose';
+import { ResourceType, SystemRoles } from 'librechat-data-provider';
+import type { AllMethods } from '@librechat/data-schemas';
+import type { NextFunction, Response } from 'express';
+import type { ServerRequest } from '~/types';
+
+export type AgentPermissionsRequest = ServerRequest & {
+ params: { resourceType: string; resourceId: string };
+};
+
+type Middleware = (req: AgentPermissionsRequest, res: Response, next: NextFunction) => unknown;
+
+export function isAgentPermissionsAdmin(req: AgentPermissionsRequest): boolean {
+ return req.params.resourceType === ResourceType.AGENT && req.user?.role === SystemRoles.ADMIN;
+}
+
+export function createAgentAdminPermissionAccess({
+ getAgent,
+ fallback,
+}: Pick<AllMethods, 'getAgent'> & { fallback: Middleware }): Middleware {
+ return async (req, res, next) => {
+ if (!isAgentPermissionsAdmin(req)) {
+ return fallback(req, res, next);
+ }
+ const { resourceId } = req.params;
+ if (!Types.ObjectId.isValid(resourceId)) {
+ return res.status(404).json({ message: 'Resource not found' });
+ }
+ try {
+ const agent = await getAgent(
+ {
+ _id: resourceId,
+ ...(req.user?.tenantId
+ ? { tenantId: req.user.tenantId }
+ : { tenantId: { $exists: false } }),
+ },
+ '_id',
+ );
+ if (!agent) {
+ return res.status(404).json({ message: 'Resource not found' });
+ }
+ } catch (_error) {
+ return res.status(500).json({ message: 'Failed to validate resource access' });
+ }
+ return next();
+ };
+}
diff --git a/packages/api/src/admin/index.ts b/packages/api/src/admin/index.ts
index c5259aeab0..84f565c03f 100644
--- a/packages/api/src/admin/index.ts
+++ b/packages/api/src/admin/index.ts
@@ -7,6 +7,7 @@ export { createAdminSkillsSyncAccess, createAdminSkillsSyncHandlers } from './sk
export { createAdminUsersHandlers } from './users';
export { createAdminAuditLogHandlers } from './auditLog';
export { createAdminCodeEnvironmentHandlers } from './code';
+export { buildAuditContext } from './context';
export { resolveConfigSecret, redactConfigSecretMaps } from './secrets';
export type { AdminConfigDeps } from './config';
export type { AdminLangfuseDeps } from './langfuse';
diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts
index 914b43a99e..4479e69b3a 100644
--- a/packages/api/src/index.ts
+++ b/packages/api/src/index.ts
@@ -1,4 +1,7 @@
export * from './app';
+export * from './acl/accessControlService';
+export * from './acl/insightsPermissions';
+export * from './acl/middleware';
export * from './credentials';
/* Artifacts */
export * from './artifacts';
diff --git a/packages/api/src/insights/access.spec.ts b/packages/api/src/insights/access.spec.ts
new file mode 100644
index 0000000000..cda6402f34
--- /dev/null
+++ b/packages/api/src/insights/access.spec.ts
@@ -0,0 +1,75 @@
+import { Types } from 'mongoose';
+import { PermissionBits, PrincipalType, ResourceType, SystemRoles } from 'librechat-data-provider';
+import { createInsightsAgentAccessResolver, type InsightsAgentAccessDeps } from './access';
+
+const agentA = { _id: new Types.ObjectId(), id: 'agent-a', name: 'Zulu', tenantId: 'tenant-a' };
+const agentB = { _id: new Types.ObjectId(), id: 'agent-b', name: 'Alpha', tenantId: 'tenant-a' };
+
+const createDeps = (): jest.Mocked<InsightsAgentAccessDeps> =>
+ ({
+ getAgents: jest.fn().mockResolvedValue([agentA, agentB]),
+ getUserPrincipals: jest
+ .fn()
+ .mockResolvedValue([
+ { principalType: PrincipalType.USER, principalId: new Types.ObjectId() },
+ { principalType: PrincipalType.PUBLIC },
+ ]),
+ hasCapabilityForPrincipals: jest.fn().mockResolvedValue(false),
+ findAccessibleResources: jest.fn().mockResolvedValue([]),
+ }) as jest.Mocked<InsightsAgentAccessDeps>;
+
+describe('createInsightsAgentAccessResolver', () => {
+ it('returns every tenant agent for a literal admin', async () => {
+ const deps = createDeps();
+ const resolve = createInsightsAgentAccessResolver(deps);
+
+ const result = await resolve({
+ id: 'admin-id',
+ role: SystemRoles.ADMIN,
+ tenantId: 'tenant-a',
+ });
+
+ expect(deps.getAgents).toHaveBeenCalledWith({ tenantId: 'tenant-a' }, '_id id name tenantId');
+ expect(deps.getUserPrincipals).not.toHaveBeenCalled();
+ expect(result).toEqual([
+ { id: 'agent-b', name: 'Alpha' },
+ { id: 'agent-a', name: 'Zulu' },
+ ]);
+ });
+
+ it('returns every tenant agent for a global read:insights grant', async () => {
+ const deps = createDeps();
+ deps.hasCapabilityForPrincipals.mockResolvedValue(true);
+ const resolve = createInsightsAgentAccessResolver(deps);
+
+ const result = await resolve({ id: 'user-id', role: 'USER', tenantId: 'tenant-a' });
+
+ expect(deps.findAccessibleResources).not.toHaveBeenCalled();
+ expect(result).toHaveLength(2);
+ });
+
+ it('requires VIEW and VIEW_INSIGHTS on the same non-public ACL entry', async () => {
+ const deps = createDeps();
+ deps.findAccessibleResources.mockResolvedValue([agentA._id]);
+ const resolve = createInsightsAgentAccessResolver(deps);
+
+ const result = await resolve({ id: 'user-id', role: 'USER', tenantId: 'tenant-a' });
+
+ expect(deps.findAccessibleResources).toHaveBeenCalledWith(
+ [expect.objectContaining({ principalType: PrincipalType.USER })],
+ ResourceType.AGENT,
+ PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
+ [agentA._id, agentB._id],
+ );
+ expect(result).toEqual([{ id: 'agent-a', name: 'Zulu' }]);
+ });
+
+ it('returns no agents without a global or per-agent grant', async () => {
+ const deps = createDeps();
+ const resolve = createInsightsAgentAccessResolver(deps);
+
+ await expect(resolve({ id: 'user-id', role: 'USER', tenantId: 'tenant-a' })).resolves.toEqual(
+ [],
+ );
+ });
+});
diff --git a/packages/api/src/insights/access.ts b/packages/api/src/insights/access.ts
new file mode 100644
index 0000000000..61a969c06b
--- /dev/null
+++ b/packages/api/src/insights/access.ts
@@ -0,0 +1,90 @@
+import { SystemCapabilities } from '@librechat/data-schemas';
+import { PermissionBits, PrincipalType, ResourceType, SystemRoles } from 'librechat-data-provider';
+import type { TInsightsAgent } from 'librechat-data-provider';
+import type { Types } from 'mongoose';
+
+type Principal = { principalType: PrincipalType; principalId?: string | Types.ObjectId };
+type AgentRecord = { _id: Types.ObjectId; id: string; name?: string; tenantId?: string };
+
+export type InsightsAccessUser = {
+ id: string;
+ role?: string;
+ tenantId?: string;
+ idOnTheSource?: string | null;
+};
+
+export type InsightsAgentAccessDeps = {
+ getAgents: (
+ filter: Record<string, unknown>,
+ select?: string | Record<string, number>,
+ ) => Promise<AgentRecord[]>;
+ getUserPrincipals: (input: {
+ userId: string;
+ role?: string | null;
+ idOnTheSource?: string | null;
+ }) => Promise<Principal[]>;
+ hasCapabilityForPrincipals: (input: {
+ principals: Principal[];
+ capability: typeof SystemCapabilities.READ_INSIGHTS;
+ tenantId?: string;
+ }) => Promise<boolean>;
+ findAccessibleResources: (
+ principals: Principal[],
+ resourceType: ResourceType,
+ requiredBits: number,
+ resourceIds: Types.ObjectId[],
+ ) => Promise<Types.ObjectId[]>;
+};
+
+const toChoice = (agent: AgentRecord): TInsightsAgent => ({
+ id: agent.id,
+ name: agent.name?.trim() || agent.id,
+});
+
+export function createInsightsAgentAccessResolver(deps: InsightsAgentAccessDeps) {
+ return async (user: InsightsAccessUser): Promise<TInsightsAgent[]> => {
+ const tenantFilter = user.tenantId
+ ? { tenantId: user.tenantId }
+ : { tenantId: { $exists: false } };
+ const agentsPromise = deps.getAgents(tenantFilter, '_id id name tenantId');
+
+ if (user.role === SystemRoles.ADMIN) {
+ return (await agentsPromise)
+ .map(toChoice)
+ .sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
+ }
+
+ const principals = await deps.getUserPrincipals({
+ userId: user.id,
+ role: user.role,
+ idOnTheSource: user.idOnTheSource,
+ });
+ const [agents, hasGlobalAccess] = await Promise.all([
+ agentsPromise,
+ deps.hasCapabilityForPrincipals({
+ principals,
+ capability: SystemCapabilities.READ_INSIGHTS,
+ tenantId: user.tenantId,
+ }),
+ ]);
+
+ let accessibleAgents = agents;
+ if (!hasGlobalAccess && agents.length > 0) {
+ const privatePrincipals = principals.filter(
+ (principal) => principal.principalType !== PrincipalType.PUBLIC,
+ );
+ const resourceIds = await deps.findAccessibleResources(
+ privatePrincipals,
+ ResourceType.AGENT,
+ PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
+ agents.map((agent) => agent._id),
+ );
+ const allowed = new Set(resourceIds.map((id) => id.toString()));
+ accessibleAgents = agents.filter((agent) => allowed.has(agent._id.toString()));
+ }
+
+ return accessibleAgents
+ .map(toChoice)
+ .sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
+ };
+}
diff --git a/packages/api/src/insights/handlers.spec.ts b/packages/api/src/insights/handlers.spec.ts
index 97d1499733..20c822331e 100644
--- a/packages/api/src/insights/handlers.spec.ts
+++ b/packages/api/src/insights/handlers.spec.ts
@@ -1,4 +1,4 @@
-import type { TInsightsResponse } from 'librechat-data-provider';
+import type { TInsightsAgent, TInsightsResponse } from 'librechat-data-provider';
import type { Response } from 'express';
import type { ServerRequest } from '~/types';
import { createInsightsAccessHandler, createInsightsHandler } from './handlers';
@@ -7,7 +7,12 @@ jest.mock('@librechat/data-schemas', () => ({
logger: { error: jest.fn() },
}));
+const agents: TInsightsAgent[] = [
+ { id: 'agent-a', name: 'Alpha' },
+ { id: 'agent-b', name: 'Beta' },
+];
const emptyInsights: TInsightsResponse = {
+ agents,
summary: {
totalUsers: 0,
totalConversations: 0,
@@ -22,6 +27,7 @@ const emptyInsights: TInsightsResponse = {
const insightsEnabled = jest.fn(() => true);
const insightsDisabled = jest.fn(() => false);
+const getAccessibleAgents = jest.fn().mockResolvedValue(agents);
const createResponse = () => {
const status = jest.fn();
@@ -37,49 +43,81 @@ const createResponse = () => {
const createRequest = (query: ServerRequest['query'] = {}): ServerRequest =>
({
query,
- user: { id: 'admin-id', role: 'ADMIN', tenantId: 'tenant-a' },
+ user: { id: 'user-id', role: 'USER', tenantId: 'tenant-a' },
}) as ServerRequest;
+const createDashboardHandler = (getInsights = jest.fn().mockResolvedValue(emptyInsights)) => ({
+ getInsights,
+ handler: createInsightsHandler({
+ isInsightsEnabled: insightsEnabled,
+ getAccessibleAgents,
+ getInsights,
+ }),
+});
+
describe('Insights handlers', () => {
beforeEach(() => {
jest.clearAllMocks();
+ getAccessibleAgents.mockResolvedValue(agents);
});
- it('returns access when Insights is enabled', async () => {
- const handler = createInsightsAccessHandler({ isInsightsEnabled: insightsEnabled });
+ it('returns access when at least one agent is accessible', async () => {
+ const handler = createInsightsAccessHandler({
+ isInsightsEnabled: insightsEnabled,
+ getAccessibleAgents,
+ });
const { response, json } = createResponse();
await handler(createRequest(), response);
- expect(insightsEnabled).toHaveBeenCalledTimes(1);
expect(json).toHaveBeenCalledWith({ access: true });
});
+ it('returns 403 from the access endpoint when no agent is accessible', async () => {
+ getAccessibleAgents.mockResolvedValueOnce([]);
+ const handler = createInsightsAccessHandler({
+ isInsightsEnabled: insightsEnabled,
+ getAccessibleAgents,
+ });
+ const { response, status } = createResponse();
+
+ await handler(createRequest(), response);
+
+ expect(status).toHaveBeenCalledWith(403);
+ });
+
it('returns 404 from the access endpoint when Insights is disabled', async () => {
- const handler = createInsightsAccessHandler({ isInsightsEnabled: insightsDisabled });
+ const handler = createInsightsAccessHandler({
+ isInsightsEnabled: insightsDisabled,
+ getAccessibleAgents,
+ });
const { response, status, json } = createResponse();
await handler(createRequest(), response);
expect(status).toHaveBeenCalledWith(404);
expect(json).toHaveBeenCalledWith({ message: 'Not found' });
+ expect(getAccessibleAgents).not.toHaveBeenCalled();
});
- it('returns 404 when Insights is disabled', async () => {
+ it('returns 404 without resolving access when Insights is disabled', async () => {
const getInsights = jest.fn();
- const handler = createInsightsHandler({ isInsightsEnabled: insightsDisabled, getInsights });
- const { response, status, json } = createResponse();
+ const handler = createInsightsHandler({
+ isInsightsEnabled: insightsDisabled,
+ getAccessibleAgents,
+ getInsights,
+ });
+ const { response, status } = createResponse();
await handler(createRequest(), response);
expect(status).toHaveBeenCalledWith(404);
- expect(json).toHaveBeenCalledWith({ message: 'Not found' });
+ expect(getAccessibleAgents).not.toHaveBeenCalled();
expect(getInsights).not.toHaveBeenCalled();
});
- it('loads a bounded page for the authenticated tenant', async () => {
- const getInsights = jest.fn().mockResolvedValue(emptyInsights);
- const handler = createInsightsHandler({ isInsightsEnabled: insightsEnabled, getInsights });
+ it('loads all accessible agents for the authenticated tenant', async () => {
+ const { handler, getInsights } = createDashboardHandler();
const { response, json } = createResponse();
await handler(
@@ -91,6 +129,8 @@ describe('Insights handlers', () => {
page: 3,
pageSize: 50,
tenantId: 'tenant-a',
+ agents,
+ agentIds: ['agent-a', 'agent-b'],
search: undefined,
range: '30d',
fromTimestamp: undefined,
@@ -100,9 +140,29 @@ describe('Insights handlers', () => {
expect(json).toHaveBeenCalledWith(emptyInsights);
});
+ it('sorts and deduplicates an authorized agent subset', async () => {
+ const { handler, getInsights } = createDashboardHandler();
+ const { response } = createResponse();
+
+ await handler(createRequest({ agentIds: ['agent-b', 'agent-a', 'agent-b'] }), response);
+
+ expect(getInsights).toHaveBeenCalledWith(
+ expect.objectContaining({ agentIds: ['agent-a', 'agent-b'] }),
+ );
+ });
+
+ it('returns 403 before loading data for an unauthorized agent', async () => {
+ const { handler, getInsights } = createDashboardHandler();
+ const { response, status } = createResponse();
+
+ await handler(createRequest({ agentIds: ['agent-c'] }), response);
+
+ expect(status).toHaveBeenCalledWith(403);
+ expect(getInsights).not.toHaveBeenCalled();
+ });
+
it('passes custom dates and a valid timezone to the data layer', async () => {
- const getInsights = jest.fn().mockResolvedValue(emptyInsights);
- const handler = createInsightsHandler({ isInsightsEnabled: insightsEnabled, getInsights });
+ const { handler, getInsights } = createDashboardHandler();
const { response } = createResponse();
await handler(
@@ -126,8 +186,7 @@ describe('Insights handlers', () => {
});
it('uses pagination defaults and discards an invalid timezone', async () => {
- const getInsights = jest.fn().mockResolvedValue(emptyInsights);
- const handler = createInsightsHandler({ isInsightsEnabled: insightsEnabled, getInsights });
+ const { handler, getInsights } = createDashboardHandler();
const { response } = createResponse();
await handler(
@@ -141,8 +200,7 @@ describe('Insights handlers', () => {
});
it('normalizes and bounds search input', async () => {
- const getInsights = jest.fn().mockResolvedValue(emptyInsights);
- const handler = createInsightsHandler({ isInsightsEnabled: insightsEnabled, getInsights });
+ const { handler, getInsights } = createDashboardHandler();
const { response } = createResponse();
await handler(createRequest({ search: ` ${'message'.repeat(40)} ` }), response);
@@ -153,8 +211,7 @@ describe('Insights handlers', () => {
});
it('does not run searches shorter than the minimum length', async () => {
- const getInsights = jest.fn().mockResolvedValue(emptyInsights);
- const handler = createInsightsHandler({ isInsightsEnabled: insightsEnabled, getInsights });
+ const { handler, getInsights } = createDashboardHandler();
const { response } = createResponse();
await handler(createRequest({ search: 'ab' }), response);
diff --git a/packages/api/src/insights/handlers.ts b/packages/api/src/insights/handlers.ts
index 1f06f0f72e..ccec4b8ec5 100644
--- a/packages/api/src/insights/handlers.ts
+++ b/packages/api/src/insights/handlers.ts
@@ -2,6 +2,8 @@ import { logger } from '@librechat/data-schemas';
import {
INSIGHTS_SEARCH_MAX_LENGTH,
INSIGHTS_SEARCH_MIN_LENGTH,
+ INSIGHTS_AGENT_ID_MAX_LENGTH,
+ type TInsightsAgent,
type TInsightsParams,
} from 'librechat-data-provider';
import type { InsightsMethods } from '@librechat/data-schemas';
@@ -11,9 +13,13 @@ import type { ServerRequest } from '~/types';
type InsightsHandlerDeps = {
isInsightsEnabled: () => boolean;
getInsights: InsightsMethods['getInsights'];
+ getAccessibleAgents: (user: NonNullable<ServerRequest['user']>) => Promise<TInsightsAgent[]>;
};
-type InsightsAccessHandlerDeps = Pick<InsightsHandlerDeps, 'isInsightsEnabled'>;
+type InsightsAccessHandlerDeps = Pick<
+ InsightsHandlerDeps,
+ 'isInsightsEnabled' | 'getAccessibleAgents'
+>;
const firstQueryValue = (value: unknown): string | undefined => {
if (Array.isArray(value)) {
@@ -32,6 +38,13 @@ const stringValue = (input: unknown): string | undefined => {
return value ? value : undefined;
};
+const stringValues = (input: unknown): string[] => {
+ const values = Array.isArray(input) ? input : [input];
+ return [
+ ...new Set(values.map(stringValue).filter((value): value is string => value != null)),
+ ].sort((a, b) => a.localeCompare(b));
+};
+
const validRanges = new Set<TInsightsParams['range']>(['24h', '7d', '30d', 'custom']);
const insightsRange = (value: unknown): TInsightsParams['range'] | undefined => {
@@ -52,14 +65,27 @@ const timeZoneValue = (value: unknown): string | undefined => {
}
};
-export function createInsightsAccessHandler({ isInsightsEnabled }: InsightsAccessHandlerDeps) {
- return async (_req: ServerRequest, res: Response): Promise<void> => {
+export function createInsightsAccessHandler({
+ isInsightsEnabled,
+ getAccessibleAgents,
+}: InsightsAccessHandlerDeps) {
+ return async (req: ServerRequest, res: Response): Promise<void> => {
try {
if (!isInsightsEnabled()) {
res.status(404).json({ message: 'Not found' });
return;
}
+ if (!req.user) {
+ res.status(401).json({ message: 'Authentication required' });
+ return;
+ }
+ const agents = await getAccessibleAgents(req.user);
+ if (agents.length === 0) {
+ res.status(403).json({ message: 'Forbidden' });
+ return;
+ }
+
res.json({ access: true });
} catch (error) {
logger.error('[Insights] Failed to load access status', error);
@@ -68,13 +94,39 @@ export function createInsightsAccessHandler({ isInsightsEnabled }: InsightsAcces
};
}
-export function createInsightsHandler({ isInsightsEnabled, getInsights }: InsightsHandlerDeps) {
+export function createInsightsHandler({
+ isInsightsEnabled,
+ getInsights,
+ getAccessibleAgents,
+}: InsightsHandlerDeps) {
return async (req: ServerRequest, res: Response): Promise<void> => {
try {
if (!isInsightsEnabled()) {
res.status(404).json({ message: 'Not found' });
return;
}
+ if (!req.user) {
+ res.status(401).json({ message: 'Authentication required' });
+ return;
+ }
+
+ const agents = await getAccessibleAgents(req.user);
+ if (agents.length === 0) {
+ res.status(403).json({ message: 'Forbidden' });
+ return;
+ }
+ const requestedAgentIds = stringValues(req.query.agentIds);
+ const authorizedAgentIds = new Set(agents.map((agent) => agent.id));
+ if (
+ requestedAgentIds.some(
+ (agentId) =>
+ agentId.length > INSIGHTS_AGENT_ID_MAX_LENGTH || !authorizedAgentIds.has(agentId),
+ )
+ ) {
+ res.status(403).json({ message: 'Forbidden' });
+ return;
+ }
+ const agentIds = requestedAgentIds.length > 0 ? requestedAgentIds : [...authorizedAgentIds];
const page = positiveInteger(req.query.page, 1);
const pageSize = Math.min(50, Math.max(5, positiveInteger(req.query.pageSize, 10)));
@@ -88,6 +140,8 @@ export function createInsightsHandler({ isInsightsEnabled, getInsights }: Insigh
page,
pageSize,
tenantId,
+ agents,
+ agentIds,
search,
range: insightsRange(req.query.range),
fromTimestamp: stringValue(req.query.fromTimestamp),
diff --git a/packages/api/src/insights/index.ts b/packages/api/src/insights/index.ts
index 6c6f862d01..28e0a7d9c1 100644
--- a/packages/api/src/insights/index.ts
+++ b/packages/api/src/insights/index.ts
@@ -1 +1,2 @@
export * from './handlers';
+export * from './access';
diff --git a/packages/client/src/components/MultiSelect.tsx b/packages/client/src/components/MultiSelect.tsx
index 6e9ffe19da..2e4da83d1b 100644
--- a/packages/client/src/components/MultiSelect.tsx
+++ b/packages/client/src/components/MultiSelect.tsx
@@ -46,6 +46,9 @@ interface MultiSelectProps<T extends string> {
defaultContent: React.ReactNode,
isSelected: boolean,
) => React.ReactNode;
+ popoverHeader?: React.ReactNode;
+ disabled?: boolean;
+ showSelectedValues?: boolean;
}
function defaultRender<T extends string>(
@@ -85,6 +88,9 @@ export default function MultiSelect<T extends string>({
selectedValues = [],
setSelectedValues,
renderItemContent,
+ popoverHeader,
+ disabled = false,
+ showSelectedValues = false,
}: MultiSelectProps<T>): JSX.Element {
const selectRef = useRef<HTMLButtonElement>(null);
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
@@ -111,9 +117,12 @@ export default function MultiSelect<T extends string>({
)}
<Select
ref={selectRef}
+ disabled={disabled}
+ data-state={isPopoverOpen ? 'open' : 'closed'}
className={cn(
'flex items-center justify-between gap-2 rounded-xl px-3 py-2 text-sm',
'bg-surface-tertiary text-text-primary shadow-sm hover:cursor-pointer hover:bg-surface-hover',
+ 'disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-surface-tertiary',
'outline-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary',
selectClassName,
selectedValues.length > 0 && selectItemsClassName != null && selectItemsClassName,
@@ -121,12 +130,13 @@ export default function MultiSelect<T extends string>({
onChange={(e) => e.stopPropagation()}
>
{selectIcon && <span>{selectIcon as React.JSX.Element}</span>}
- <span className="mr-auto hidden truncate md:block">
+ <span className={cn('mr-auto truncate', !showSelectedValues && 'hidden md:block')}>
{renderSelectedValues(selectedValues, placeholder, items)}
</span>
<SelectArrow
className={cn(
- 'ml-1 hidden stroke-1 text-base opacity-75 transition-transform duration-300 md:block',
+ 'ml-1 stroke-1 text-base opacity-75 transition-transform duration-300',
+ !showSelectedValues && 'hidden md:block',
isPopoverOpen && 'rotate-180',
)}
/>
@@ -146,6 +156,7 @@ export default function MultiSelect<T extends string>({
popoverClassName,
)}
>
+ {popoverHeader}
{items.map((item) => {
const value = getItemValue(item);
const label = getItemLabel(item);
diff --git a/packages/data-provider/src/accessPermissions.ts b/packages/data-provider/src/accessPermissions.ts
index ebefb0f0d1..b59bb7a8c5 100644
--- a/packages/data-provider/src/accessPermissions.ts
+++ b/packages/data-provider/src/accessPermissions.ts
@@ -64,6 +64,8 @@ export enum PermissionBits {
DELETE = 4,
/** 1000 - Can share agent with others (future) */
SHARE = 8,
+ /** 10000 - Can view Insights data for an agent when VIEW is also present */
+ VIEW_INSIGHTS = 16,
}
/**
@@ -107,6 +109,8 @@ export const principalSchema = z.object({
description: z.string().optional(), // for group and role types
idOnTheSource: z.string().optional(), // Entra ID for users/groups
accessRoleId: z.nativeEnum(AccessRoleIds).optional(), // Access role ID for permissions
+ viewInsights: z.boolean().optional(),
+ isAdmin: z.boolean().optional(),
memberCount: z.number().optional(), // for group type
});
@@ -231,6 +235,7 @@ export type TPrincipalSearchResult = {
memberCount?: number; // for groups
description?: string; // for groups
idOnTheSource?: string; // Entra ID for users (maps to openidId) and groups (maps to idOnTheSource)
+ isAdmin?: boolean;
};
/**
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 77087f53bc..3a0d1b08bb 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -464,7 +464,7 @@ export const skillFiles = (id: string) => `${getSkill(id)}/files`;
export const skillFile = (id: string, relativePath: string) =>
`${skillFiles(id)}/${encodeURIComponent(relativePath)}`;
-export const insights = () => `${BASE_URL}/api/admin/insights`;
+export const insights = () => `${BASE_URL}/api/insights`;
export const insightsAccess = () => `${insights()}/access`;
export const adminSkillsSync = () => `${BASE_URL}/api/admin/skills/sync`;
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 933570aaf8..2c24a51a0f 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -22,7 +22,9 @@ import * as r from './roles';
export function getInsights(params: TInsightsParams = {}): Promise<TInsightsResponse> {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
- if (value !== undefined && value !== null && value !== '') {
+ if (Array.isArray(value)) {
+ value.forEach((item) => query.append(key, String(item)));
+ } else if (value !== undefined && value !== null && value !== '') {
query.set(key, String(value));
}
}
diff --git a/packages/data-provider/src/types/insights.ts b/packages/data-provider/src/types/insights.ts
index 594e273a9d..6be52871a1 100644
--- a/packages/data-provider/src/types/insights.ts
+++ b/packages/data-provider/src/types/insights.ts
@@ -3,16 +3,23 @@ export type InsightsRange = '24h' | '7d' | '30d' | 'custom';
export const INSIGHTS_MAX_RANGE_DAYS = 30;
export const INSIGHTS_SEARCH_MIN_LENGTH = 3;
export const INSIGHTS_SEARCH_MAX_LENGTH = 200;
+export const INSIGHTS_AGENT_ID_MAX_LENGTH = 256;
export type TInsightsParams = {
range?: InsightsRange;
fromTimestamp?: string;
toTimestamp?: string;
timeZone?: string;
search?: string;
+ agentIds?: string[];
page?: number;
pageSize?: number;
};
+export type TInsightsAgent = {
+ id: string;
+ name: string;
+};
+
export type TInsightsDailyPoint = {
date: string;
conversations: number;
@@ -36,6 +43,8 @@ export type TInsightsChurnedUser = TInsightsUser & {
export type TInsightsConversation = {
conversationId: string;
+ agentId: string;
+ agentName: string;
date: string;
userId: string;
name: string;
@@ -53,6 +62,7 @@ export type TInsightsSummary = {
};
export type TInsightsResponse = {
+ agents: TInsightsAgent[];
summary: TInsightsSummary;
daily: TInsightsDailyPoint[];
topUsers: TInsightsUser[];
diff --git a/packages/data-schemas/src/methods/aclEntry.parity.spec.ts b/packages/data-schemas/src/methods/aclEntry.parity.spec.ts
index 2c2e4b7f46..bfe68d0a80 100644
--- a/packages/data-schemas/src/methods/aclEntry.parity.spec.ts
+++ b/packages/data-schemas/src/methods/aclEntry.parity.spec.ts
@@ -1,12 +1,12 @@
import mongoose from 'mongoose';
import { performance } from 'node:perf_hooks';
+import { MongoMemoryServer } from 'mongodb-memory-server';
import {
ResourceType,
PrincipalType,
PrincipalModel,
PermissionBits,
} from 'librechat-data-provider';
-import { MongoMemoryServer } from 'mongodb-memory-server';
import type * as t from '~/types';
import { createAclEntryMethods } from './aclEntry';
import aclEntrySchema from '~/schema/aclEntry';
@@ -67,7 +67,7 @@ async function seedVariedPermissions(
grantedBy: mongoose.Types.ObjectId,
count: number,
): Promise<void> {
- /** Every permBits value from 0..15 appears roughly `count/16` times, giving
+ /** Every permBits value from 0..31 appears roughly `count/32` times, giving
* a uniform distribution for parity + perf assertions. */
const docs: Partial<t.IAclEntry>[] = [];
for (let i = 0; i < count; i++) {
@@ -77,7 +77,7 @@ async function seedVariedPermissions(
principalModel: PrincipalModel.USER,
resourceType: ResourceType.AGENT,
resourceId: new mongoose.Types.ObjectId(),
- permBits: i % 16,
+ permBits: i % 32,
grantedBy,
});
}
@@ -106,6 +106,8 @@ describe('ACL $bitsAllSet vs $in parity (issue #12729)', () => {
PermissionBits.EDIT,
PermissionBits.DELETE,
PermissionBits.SHARE,
+ PermissionBits.VIEW_INSIGHTS,
+ PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
PermissionBits.VIEW | PermissionBits.EDIT,
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
@@ -142,7 +144,7 @@ describe('ACL $bitsAllSet vs $in parity (issue #12729)', () => {
principalType: PrincipalType.PUBLIC,
resourceType: ResourceType.AGENT,
resourceId: new mongoose.Types.ObjectId(),
- permBits: i % 16,
+ permBits: i % 32,
grantedBy: grantedById,
});
}
@@ -161,8 +163,8 @@ describe('ACL $bitsAllSet vs $in parity (issue #12729)', () => {
test('hasPermission returns the same boolean as `$bitsAllSet` across all permBits patterns', async () => {
const sharedResourceId = new mongoose.Types.ObjectId();
- /** One entry per permBits value (0..15) on the same resource. */
- for (let permBits = 0; permBits <= 15; permBits++) {
+ /** One entry per permBits value (0..31) on the same resource. */
+ for (let permBits = 0; permBits <= 31; permBits++) {
await AclEntry.create({
principalType: PrincipalType.USER,
principalId: new mongoose.Types.ObjectId(),
@@ -181,6 +183,7 @@ describe('ACL $bitsAllSet vs $in parity (issue #12729)', () => {
PermissionBits.EDIT,
PermissionBits.DELETE,
PermissionBits.SHARE,
+ PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
PermissionBits.VIEW | PermissionBits.EDIT,
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
]) {
diff --git a/packages/data-schemas/src/methods/aclEntry.spec.ts b/packages/data-schemas/src/methods/aclEntry.spec.ts
index 908fe36c45..a2831fa22c 100644
--- a/packages/data-schemas/src/methods/aclEntry.spec.ts
+++ b/packages/data-schemas/src/methods/aclEntry.spec.ts
@@ -1683,19 +1683,23 @@ describe('AclEntry Model Tests', () => {
* coverage independent of the higher-level parity and behavior specs.
*/
describe('permissionBitSupersets', () => {
- test('requiredBits=0 matches every permBits value in [0, 15]', () => {
+ test('requiredBits=0 matches every permBits value in [0, 31]', () => {
const result = permissionBitSupersets(0);
- expect(result).toHaveLength(16);
- expect([...result].sort((a, b) => a - b)).toEqual([
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
- ]);
+ expect(result).toHaveLength(32);
+ expect([...result].sort((a, b) => a - b)).toEqual(
+ Array.from({ length: 32 }, (_, value) => value),
+ );
});
- test('requiredBits=15 (all four bits) matches only [15]', () => {
+ test('all permission bits match only the upper bound', () => {
const result = permissionBitSupersets(
- PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE,
+ PermissionBits.VIEW |
+ PermissionBits.EDIT |
+ PermissionBits.DELETE |
+ PermissionBits.SHARE |
+ PermissionBits.VIEW_INSIGHTS,
);
- expect([...result].sort((a, b) => a - b)).toEqual([15]);
+ expect([...result].sort((a, b) => a - b)).toEqual([31]);
});
test('every returned value is a bitwise superset of requiredBits', () => {
@@ -1704,6 +1708,8 @@ describe('AclEntry Model Tests', () => {
PermissionBits.EDIT,
PermissionBits.DELETE,
PermissionBits.SHARE,
+ PermissionBits.VIEW_INSIGHTS,
+ PermissionBits.VIEW | PermissionBits.VIEW_INSIGHTS,
PermissionBits.VIEW | PermissionBits.EDIT,
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE,
]) {
@@ -1717,12 +1723,12 @@ describe('AclEntry Model Tests', () => {
test('returns exactly the values satisfying $bitsAllSet semantics', () => {
/**
* Parity check against the literal definition: for every required mask,
- * the returned set must equal the set of all v in [0,15] whose bits
+ * the returned set must equal the set of all v in [0,31] whose bits
* include `required`.
*/
- for (let required = 0; required <= 15; required++) {
+ for (let required = 0; required <= 31; required++) {
const expected: number[] = [];
- for (let v = 0; v <= 15; v++) {
+ for (let v = 0; v <= 31; v++) {
if ((v & required) === required) {
expected.push(v);
}
@@ -1759,7 +1765,11 @@ describe('AclEntry Model Tests', () => {
*/
describe('rejection of out-of-range inputs (cache-growth safety)', () => {
const MAX =
- PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+ PermissionBits.VIEW |
+ PermissionBits.EDIT |
+ PermissionBits.DELETE |
+ PermissionBits.SHARE |
+ PermissionBits.VIEW_INSIGHTS;
const FIRST_TRUNCATED_32_BIT_VALUE = 2 ** 32;
const SHARED_EMPTY = permissionBitSupersets(MAX + 1);
@@ -1793,11 +1803,11 @@ describe('AclEntry Model Tests', () => {
test('rejects inputs with bits above MAX_PERM_BITS even if some in-range bits are set', () => {
/**
- * `permBits = 17 = 0b10001` has VIEW set AND bit 4 (out of range). A
- * stored `permBits` can never be both ≤ 15 and have bit 4 set, so the
+ * `permBits = 33 = 0b100001` has VIEW set and an out-of-range bit. A
+ * stored `permBits` can never be both ≤ 31 and have bit 5 set, so the
* match set is necessarily empty — reject before caching.
*/
- expect(permissionBitSupersets(MAX + PermissionBits.VIEW)).toBe(SHARED_EMPTY);
+ expect(permissionBitSupersets(MAX + 1 + PermissionBits.VIEW)).toBe(SHARED_EMPTY);
});
test('does NOT cache rejected inputs (reference identity)', () => {
@@ -1867,7 +1877,11 @@ describe('AclEntry Model Tests', () => {
*/
describe('permBits schema bounds', () => {
const MAX_PERM_BITS =
- PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+ PermissionBits.VIEW |
+ PermissionBits.EDIT |
+ PermissionBits.DELETE |
+ PermissionBits.SHARE |
+ PermissionBits.VIEW_INSIGHTS;
test('accepts permBits at the upper bound (all enum bits set)', async () => {
const resource = new mongoose.Types.ObjectId();
diff --git a/packages/data-schemas/src/methods/aclEntry.ts b/packages/data-schemas/src/methods/aclEntry.ts
index e0a6d09666..d80f0ae370 100644
--- a/packages/data-schemas/src/methods/aclEntry.ts
+++ b/packages/data-schemas/src/methods/aclEntry.ts
@@ -7,7 +7,7 @@ import type {
DeleteResult,
Model,
} from 'mongoose';
-import type { AclEntry, IAclEntry } from '~/types';
+import type { IAclEntry } from '~/types';
import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';
import { MAX_PERM_BITS } from '~/common/permissions';
@@ -42,8 +42,8 @@ const supersetCache = new Map<number, readonly number[]>();
* which is the right behavior for a request asking for bits the system does
* not recognize.
*
- * For the current 4-bit `PermissionBits` enum the worst case is `required = 0`
- * which expands to 16 values; the best case (all bits required) expands to 1.
+ * For the current 5-bit `PermissionBits` enum the worst case is `required = 0`
+ * which expands to 32 values; the best case (all bits required) expands to 1.
* Results are memoized per `requiredBits` so the expansion runs at most once
* per distinct mask over the process lifetime.
*/
@@ -85,6 +85,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
findEntriesByResource: (
resourceType: string,
resourceId: string | Types.ObjectId,
+ session?: ClientSession,
) => Promise<IAclEntry[]>;
findEntriesByPrincipalsAndResource: (
principalsList: Array<{ principalType: string; principalId?: string | Types.ObjectId }>,
@@ -146,7 +147,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
options?: { session?: ClientSession },
) => Promise<DeleteResult>;
bulkWriteAclEntries: (
- ops: AnyBulkWriteOperation<AclEntry>[],
+ ops: AnyBulkWriteOperation[],
options?: { session?: ClientSession },
) => Promise<import('mongodb').BulkWriteResult>;
findPublicResourceIds: (
@@ -190,9 +191,14 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
async function findEntriesByResource(
resourceType: string,
resourceId: string | Types.ObjectId,
+ session?: ClientSession,
): Promise<IAclEntry[]> {
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
- return await AclEntry.find({ resourceType, resourceId }).lean<IAclEntry[]>();
+ const query = AclEntry.find({ resourceType, resourceId });
+ if (session) {
+ query.session(session);
+ }
+ return await query.lean<IAclEntry[]>();
}
/**
@@ -543,7 +549,7 @@ export function createAclEntryMethods(mongoose: typeof import('mongoose')): {
* @param options - Optional query options (e.g., { session })
*/
async function bulkWriteAclEntries(
- ops: AnyBulkWriteOperation<AclEntry>[],
+ ops: AnyBulkWriteOperation[],
options?: { session?: ClientSession },
): Promise<import('mongodb').BulkWriteResult> {
const AclEntry = mongoose.models.AclEntry as Model<IAclEntry>;
diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts
index ea8efb175c..5306ca1bb8 100644
--- a/packages/data-schemas/src/methods/agent.ts
+++ b/packages/data-schemas/src/methods/agent.ts
@@ -483,7 +483,10 @@ export function createAgentMethods(
getAgentWithVersionCount: (
searchParameter: FilterQuery<IAgent>,
) => Promise<(IAgent & { version: number }) | null>;
- getAgents: (searchParameter: FilterQuery<IAgent>) => Promise<IAgent[]>;
+ getAgents: (
+ searchParameter: FilterQuery<IAgent>,
+ select?: string | Record<string, number>,
+ ) => Promise<IAgent[]>;
createAgent: (agentData: Record<string, unknown>) => Promise<IAgent>;
getAgentIdsByMCPServerName: (serverName: string) => Promise<Types.ObjectId[]>;
getAgentsWithMCPServerNames: () => Promise<Array<Pick<IAgent, '_id' | 'mcpServerNames'>>>;
@@ -691,9 +694,12 @@ export function createAgentMethods(
/**
* Get multiple agent documents based on the provided search parameters.
*/
- async function getAgents(searchParameter: FilterQuery<IAgent>): Promise<IAgent[]> {
+ async function getAgents(
+ searchParameter: FilterQuery<IAgent>,
+ select?: string | Record<string, number>,
+ ): Promise<IAgent[]> {
const Agent = mongoose.models.Agent as Model<IAgent>;
- return await Agent.find(searchParameter).lean<IAgent[]>();
+ return await Agent.find(searchParameter, select).lean<IAgent[]>();
}
/** Returns the ids of every agent referencing `serverName`, the candidate set
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 47d3d5effd..7a1f99af36 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -174,6 +174,48 @@ describe('Conversation Operations', () => {
expect(savedConvo?.title).toBe('Test Conversation');
});
+ it('sets immutable agent attribution from server metadata only on insert', async () => {
+ await saveConvo(
+ mockCtx,
+ {
+ ...mockConversationData,
+ agent_id: 'agent-a',
+ initial_agent_id: 'forged-agent',
+ },
+ { initialAgentId: 'agent-a' },
+ );
+ await saveConvo(
+ mockCtx,
+ {
+ conversationId: mockConversationData.conversationId,
+ agent_id: 'agent-b',
+ initial_agent_id: 'forged-agent-b',
+ },
+ { initialAgentId: 'agent-b' },
+ );
+
+ const saved = await Conversation.findOne({
+ conversationId: mockConversationData.conversationId,
+ user: mockCtx.userId,
+ })
+ .select('+initial_agent_id')
+ .lean();
+ expect(saved?.initial_agent_id).toBe('agent-a');
+ expect(saved?.agent_id).toBe('agent-b');
+ });
+
+ it('stores explicit null attribution for a new non-agent conversation', async () => {
+ await saveConvo(mockCtx, mockConversationData);
+
+ const saved = await Conversation.findOne({
+ conversationId: mockConversationData.conversationId,
+ user: mockCtx.userId,
+ })
+ .select('+initial_agent_id')
+ .lean();
+ expect(saved).toHaveProperty('initial_agent_id', null);
+ });
+
it('should query messages when saving a conversation', async () => {
// Mock messages as ObjectIds
const mockMessages = [new mongoose.Types.ObjectId(), new mongoose.Types.ObjectId()];
@@ -275,6 +317,24 @@ describe('Conversation Operations', () => {
expect(refreshedProject?.conversationCount).toBe(1);
});
+ it('bulkSaveConvos strips supplied attribution and stores explicit null on insert', async () => {
+ const conversationId = uuidv4();
+
+ await methods.bulkSaveConvos([
+ {
+ conversationId,
+ user: mockCtx.userId,
+ endpoint: EModelEndpoint.openAI,
+ initial_agent_id: 'forged-agent',
+ },
+ ]);
+
+ const saved = await Conversation.findOne({ conversationId, user: mockCtx.userId })
+ .select('+initial_agent_id')
+ .lean();
+ expect(saved).toHaveProperty('initial_agent_id', null);
+ });
+
it('refreshes both projects when a save moves a conversation between them', async () => {
const projectA = await ChatProject.create({
user: mockCtx.userId,
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index c6576134b9..d7dc47c55c 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -257,6 +257,8 @@ export interface ConversationMethods {
noUpsert?: boolean;
createdAtOnInsert?: Date;
preserveUpdatedAt?: boolean;
+ /** Same-tenant persisted agent already resolved by the request layer. */
+ initialAgentId?: string | null;
/** `_id`s of messages this save just wrote. When present, they are appended with
* `$addToSet` and the O(n) read-and-rewrite of the `messages` array is skipped;
* every save without this option still rebuilds the array from the database. */
@@ -2124,6 +2126,7 @@ export function createConversationMethods(
noUpsert?: boolean;
createdAtOnInsert?: Date;
preserveUpdatedAt?: boolean;
+ initialAgentId?: string | null;
appendMessageIds?: Types.ObjectId[];
},
) {
@@ -2137,12 +2140,14 @@ export function createConversationMethods(
const appendMessageIds = metadata?.appendMessageIds;
const update: Record<string, unknown> = { ...convo, user: userId };
+ delete update.initial_agent_id;
if (appendMessageIds == null) {
update.messages = await getMessages({ conversationId, user: userId }, '_id');
} else {
delete update.messages;
}
const unsetFields: Record<string, number> = { ...(metadata?.unsetFields ?? {}) };
+ delete unsetFields.initial_agent_id;
if (Object.prototype.hasOwnProperty.call(update, 'chatProjectId') && update.chatProjectId) {
const chatProjectId = typeof update.chatProjectId === 'string' ? update.chatProjectId : '';
@@ -2229,6 +2234,14 @@ export function createConversationMethods(
timestampOptions.timestamps = false;
}
+ const canUpsert = metadata?.noUpsert !== true;
+ const initialAgentId =
+ canUpsert &&
+ typeof metadata?.initialAgentId === 'string' &&
+ metadata.initialAgentId.trim() !== ''
+ ? metadata.initialAgentId
+ : null;
+
const buildOperation = (setFields: Record<string, unknown>) => {
const operation: Record<string, unknown> = { $set: setFields };
if (appendMessageIds != null && appendMessageIds.length > 0) {
@@ -2241,14 +2254,14 @@ export function createConversationMethods(
? (createdAtOnInsert ??
(!preserveUpdatedAt && update.updatedAt instanceof Date ? update.updatedAt : undefined))
: createdAtOnInsert;
- if (createdAtForInsert) {
- operation.$setOnInsert = { createdAt: createdAtForInsert };
- }
+ operation.$setOnInsert = {
+ initial_agent_id: initialAgentId,
+ ...(createdAtForInsert ? { createdAt: createdAtForInsert } : {}),
+ };
return operation;
};
const baseFilter = { conversationId, user: userId };
- const canUpsert = metadata?.noUpsert !== true;
const runUpdate = (
filter: Record<string, unknown>,
operation: Record<string, unknown>,
@@ -2507,6 +2520,7 @@ export function createConversationMethods(
const affectedProjectStats = new Map<string, { user: string; projectId: string }>();
const bulkOps = conversations.map((convo) => {
const sanitized = { ...convo };
+ delete sanitized.initial_agent_id;
if (typeof sanitized.user === 'string' && typeof sanitized.chatProjectId === 'string') {
if (ownedProjects.has(`${sanitized.user}:${sanitized.chatProjectId}`)) {
affectedProjectStats.set(`${sanitized.user}:${sanitized.chatProjectId}`, {
@@ -2536,7 +2550,10 @@ export function createConversationMethods(
conversationId: sanitized.conversationId,
user: sanitized.user,
},
- update: sanitized,
+ update: {
+ $set: sanitized,
+ $setOnInsert: { initial_agent_id: null },
+ },
upsert: true,
timestamps: false,
},
diff --git a/packages/data-schemas/src/methods/insights.spec.ts b/packages/data-schemas/src/methods/insights.spec.ts
index db8f7e472a..d48eaa344d 100644
--- a/packages/data-schemas/src/methods/insights.spec.ts
+++ b/packages/data-schemas/src/methods/insights.spec.ts
@@ -6,6 +6,40 @@ import { createInsightsMethods } from './insights';
import { createUserModel } from '../models/user';
let mongoServer: MongoMemoryServer;
+const selectedAgents = [{ id: 'agent-a', name: 'Agent A' }];
+
+const fixtures = {
+ conversations: {
+ insertOne: (document: Record<string, unknown>) =>
+ mongoose.models.Conversation.collection.insertOne({ agent_id: 'agent-a', ...document }),
+ insertMany: (documents: Array<Record<string, unknown>>) =>
+ mongoose.models.Conversation.collection.insertMany(
+ documents.map((document) => ({ agent_id: 'agent-a', ...document })),
+ ),
+ },
+ messages: {
+ insertOne: (document: Record<string, unknown>) =>
+ mongoose.models.Message.collection.insertOne({
+ ...(document.isCreatedByUser === false ? { model: 'agent-a' } : {}),
+ ...document,
+ }),
+ insertMany: (documents: Array<Record<string, unknown>>) =>
+ mongoose.models.Message.collection.insertMany(
+ documents.map((document) => ({
+ ...(document.isCreatedByUser === false ? { model: 'agent-a' } : {}),
+ ...document,
+ })),
+ ),
+ },
+};
+
+function createScopedInsightsMethods() {
+ const methods = createInsightsMethods(mongoose);
+ return {
+ getInsights: (options: Parameters<typeof methods.getInsights>[0]) =>
+ methods.getInsights({ ...options, agents: selectedAgents, agentIds: ['agent-a'] }),
+ };
+}
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
@@ -61,7 +95,7 @@ describe('Insights methods', () => {
},
]);
- await mongoose.models.Conversation.collection.insertMany([
+ await fixtures.conversations.insertMany([
{
conversationId: 'old-conversation',
tenantId: 'tenant-a',
@@ -97,7 +131,7 @@ describe('Insights methods', () => {
['other-assistant', 'other-conversation', otherTenantUserId, false],
] as const;
- await mongoose.models.Message.collection.insertMany([
+ await fixtures.messages.insertMany([
...messages.map(([messageId, conversationId, userId, isCreatedByUser]) => ({
messageId,
conversationId,
@@ -136,7 +170,7 @@ describe('Insights methods', () => {
},
]);
- const result = await createInsightsMethods(mongoose).getInsights({
+ const result = await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: '7d',
});
@@ -204,7 +238,45 @@ describe('Insights methods', () => {
},
]);
- await mongoose.models.Message.collection.insertMany([
+ await fixtures.conversations.insertMany([
+ {
+ conversationId: 'churned-conversation-1',
+ tenantId: 'tenant-a',
+ user: churnedUserId.toString(),
+ createdAt: daysAgo(60),
+ isTemporary: false,
+ },
+ {
+ conversationId: 'churned-conversation-2',
+ tenantId: 'tenant-a',
+ user: churnedUserId.toString(),
+ createdAt: daysAgo(29),
+ isTemporary: false,
+ },
+ {
+ conversationId: 'previously-churned-conversation',
+ tenantId: 'tenant-a',
+ user: previouslyChurnedUserId.toString(),
+ createdAt: daysAgo(40),
+ isTemporary: false,
+ },
+ {
+ conversationId: 'active-conversation',
+ tenantId: 'tenant-a',
+ user: activeUserId.toString(),
+ createdAt: daysAgo(27),
+ isTemporary: false,
+ },
+ {
+ conversationId: 'other-conversation',
+ tenantId: 'tenant-b',
+ user: otherTenantUserId.toString(),
+ createdAt: daysAgo(35),
+ isTemporary: false,
+ },
+ ]);
+
+ await fixtures.messages.insertMany([
{
messageId: 'churned-first-prompt',
conversationId: 'churned-conversation-1',
@@ -277,7 +349,7 @@ describe('Insights methods', () => {
},
]);
- const result = await createInsightsMethods(mongoose).getInsights({
+ const result = await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: '7d',
});
@@ -288,7 +360,7 @@ describe('Insights methods', () => {
name: 'Churned User',
conversations: 2,
- messages: 4,
+ messages: 3,
firstSeen: daysAgo(60).toISOString(),
lastSeen: daysAgo(29).toISOString(),
},
@@ -314,7 +386,7 @@ describe('Insights methods', () => {
},
]);
- await mongoose.models.Conversation.collection.insertMany([
+ await fixtures.conversations.insertMany([
{
conversationId: 'shared-client-id',
tenantId: 'tenant-a',
@@ -334,7 +406,7 @@ describe('Insights methods', () => {
isTemporary: false,
},
]);
- await mongoose.models.Message.collection.insertMany([
+ await fixtures.messages.insertMany([
{
messageId: 'first-prompt',
conversationId: 'shared-client-id',
@@ -389,7 +461,7 @@ describe('Insights methods', () => {
},
]);
- const methods = createInsightsMethods(mongoose);
+ const methods = createScopedInsightsMethods();
const insights = await methods.getInsights({ tenantId: 'tenant-a', range: '7d' });
const byUser = new Map(insights.latest.conversations.map((row) => [row.userId, row]));
@@ -418,6 +490,132 @@ describe('Insights methods', () => {
]);
});
+ it('attributes conversations to their immutable primary agent and messages to their source', async () => {
+ const now = new Date();
+ const userId = new mongoose.Types.ObjectId();
+ await mongoose.models.User.collection.insertOne({
+ _id: userId,
+ tenantId: 'tenant-a',
+ name: 'Mixed Agent User',
+ email: '[email protected]',
+ });
+ await fixtures.conversations.insertMany([
+ {
+ conversationId: 'legacy-agent-a',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ createdAt: now,
+ updatedAt: now,
+ isTemporary: false,
+ },
+ {
+ conversationId: 'primary-agent-a',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ initial_agent_id: 'agent-a',
+ agent_id: 'agent-b',
+ createdAt: now,
+ updatedAt: now,
+ isTemporary: false,
+ },
+ {
+ conversationId: 'explicitly-unattributed',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ initial_agent_id: null,
+ agent_id: 'agent-a',
+ createdAt: now,
+ updatedAt: now,
+ isTemporary: false,
+ },
+ {
+ conversationId: 'subagent-thread',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ initial_agent_id: 'agent-a',
+ subagentThread: { parentConversationId: 'primary-agent-a' },
+ createdAt: now,
+ updatedAt: now,
+ isTemporary: false,
+ },
+ ]);
+ await fixtures.messages.insertMany([
+ {
+ messageId: 'primary-user',
+ conversationId: 'primary-agent-a',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ createdAt: now,
+ updatedAt: now,
+ isCreatedByUser: true,
+ isTemporary: false,
+ text: 'Use the primary agent',
+ tokenCount: 5,
+ },
+ {
+ messageId: 'secondary-assistant',
+ conversationId: 'primary-agent-a',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ createdAt: now,
+ updatedAt: now,
+ isCreatedByUser: false,
+ isTemporary: false,
+ model: 'agent-b',
+ text: 'Answered by a secondary agent',
+ tokenCount: 7,
+ },
+ {
+ messageId: 'unattributed-assistant',
+ conversationId: 'explicitly-unattributed',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ createdAt: now,
+ updatedAt: now,
+ isCreatedByUser: false,
+ isTemporary: false,
+ model: 'agent-a',
+ text: 'Must remain unattributed',
+ tokenCount: 13,
+ },
+ {
+ messageId: 'subagent-assistant',
+ conversationId: 'subagent-thread',
+ tenantId: 'tenant-a',
+ user: userId.toString(),
+ createdAt: now,
+ updatedAt: now,
+ isCreatedByUser: false,
+ isTemporary: false,
+ model: 'agent-a',
+ text: 'Nested work',
+ tokenCount: 11,
+ },
+ ]);
+
+ const methods = createInsightsMethods(mongoose);
+ const agentAInsights = await methods.getInsights({
+ tenantId: 'tenant-a',
+ range: '7d',
+ agents: selectedAgents,
+ agentIds: ['agent-a'],
+ });
+ const agentBInsights = await methods.getInsights({
+ tenantId: 'tenant-a',
+ range: '7d',
+ agents: [{ id: 'agent-b', name: 'Agent B' }],
+ agentIds: ['agent-b'],
+ });
+
+ expect(agentAInsights.summary).toEqual(
+ expect.objectContaining({ totalConversations: 2, totalMessages: 1, totalTokens: 5 }),
+ );
+ expect(agentAInsights.agents).toEqual(selectedAgents);
+ expect(agentBInsights.summary).toEqual(
+ expect.objectContaining({ totalConversations: 0, totalMessages: 1, totalTokens: 7 }),
+ );
+ });
+
it('bounds latest conversation message totals to a custom range', async () => {
const from = new Date('2026-01-01T00:00:00.000Z');
const to = new Date('2026-01-07T23:59:59.999Z');
@@ -432,7 +630,7 @@ describe('Insights methods', () => {
name: 'Historical User',
});
- await mongoose.models.Conversation.collection.insertOne({
+ await fixtures.conversations.insertOne({
conversationId: 'historical-conversation',
tenantId: 'tenant-a',
user: userId.toString(),
@@ -441,7 +639,7 @@ describe('Insights methods', () => {
updatedAt: afterRange,
isTemporary: false,
});
- await mongoose.models.Message.collection.insertMany([
+ await fixtures.messages.insertMany([
{
messageId: 'temporary-prompt',
conversationId: 'historical-conversation',
@@ -492,7 +690,7 @@ describe('Insights methods', () => {
},
]);
- const result = await createInsightsMethods(mongoose).getInsights({
+ const result = await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: 'custom',
fromTimestamp: from.toISOString(),
@@ -519,7 +717,7 @@ describe('Insights methods', () => {
name: 'Pacific User',
});
- await mongoose.models.Conversation.collection.insertMany(
+ await fixtures.conversations.insertMany(
activity.map((createdAt, index) => ({
conversationId: `pacific-${index}`,
tenantId: 'tenant-a',
@@ -529,7 +727,7 @@ describe('Insights methods', () => {
isTemporary: false,
})),
);
- await mongoose.models.Message.collection.insertMany(
+ await fixtures.messages.insertMany(
activity.map((createdAt, index) => ({
messageId: `pacific-message-${index}`,
conversationId: `pacific-${index}`,
@@ -543,7 +741,7 @@ describe('Insights methods', () => {
})),
);
- const result = await createInsightsMethods(mongoose).getInsights({
+ const result = await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: 'custom',
fromTimestamp: '2026-08-01T07:00:00.000Z',
@@ -568,7 +766,7 @@ describe('Insights methods', () => {
name: 'Eastern User',
});
- await mongoose.models.Conversation.collection.insertOne({
+ await fixtures.conversations.insertOne({
conversationId: 'dst-fallback',
tenantId: 'tenant-a',
user: userId.toString(),
@@ -576,7 +774,7 @@ describe('Insights methods', () => {
updatedAt: activity,
isTemporary: false,
});
- await mongoose.models.Message.collection.insertOne({
+ await fixtures.messages.insertOne({
messageId: 'dst-fallback-message',
conversationId: 'dst-fallback',
tenantId: 'tenant-a',
@@ -588,7 +786,7 @@ describe('Insights methods', () => {
text: 'Message before the repeated hour',
});
- const result = await createInsightsMethods(mongoose).getInsights({
+ const result = await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: 'custom',
fromTimestamp: '2026-10-04T04:00:00.000Z',
@@ -605,7 +803,7 @@ describe('Insights methods', () => {
});
it('fills every local calendar date across a daylight saving time change', async () => {
- const result = await createInsightsMethods(mongoose).getInsights({
+ const result = await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: 'custom',
fromTimestamp: '2026-03-08T04:30:00.000Z',
@@ -646,7 +844,7 @@ describe('Insights methods', () => {
},
]);
- await mongoose.models.Conversation.collection.insertMany([
+ await fixtures.conversations.insertMany([
{
conversationId: 'incident-review-123',
tenantId: 'tenant-a',
@@ -672,7 +870,7 @@ describe('Insights methods', () => {
isTemporary: false,
},
]);
- await mongoose.models.Message.collection.insertMany([
+ await fixtures.messages.insertMany([
{
messageId: 'message-a',
conversationId: 'incident-review-123',
@@ -708,7 +906,7 @@ describe('Insights methods', () => {
},
]);
- const methods = createInsightsMethods(mongoose);
+ const methods = createScopedInsightsMethods();
const byConversationId = await methods.getInsights({
tenantId: 'tenant-a',
range: '7d',
@@ -746,7 +944,7 @@ describe('Insights methods', () => {
const messageAggregateSpy = jest.spyOn(mongoose.models.Message, 'aggregate');
try {
- await createInsightsMethods(mongoose).getInsights({
+ await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: '7d',
search: 'conversation-id',
@@ -757,6 +955,7 @@ describe('Insights methods', () => {
$facet?: Record<string, unknown>;
$limit?: number;
$lookup?: Record<string, unknown>;
+ $match?: Record<string, unknown>;
$setWindowFields?: Record<string, unknown>;
$unionWith?: unknown;
};
@@ -781,6 +980,14 @@ describe('Insights methods', () => {
stage.$facet == null && stage.$setWindowFields == null && stage.$unionWith == null,
),
).toBe(true);
+ expect(JSON.stringify(allStages)).not.toContain('"$expr"');
+ expect(JSON.stringify(allStages)).not.toContain('"$type"');
+ expect(
+ conversationPipelines.every((pipeline) => {
+ const firstMatch = pipeline.find((stage) => stage.$match)?.$match;
+ return Array.isArray(firstMatch?.$or);
+ }),
+ ).toBe(true);
expect(searchedPipelines).toHaveLength(2);
expect(searchedPipelines.some((pipeline) => pipeline.some((stage) => stage.$count))).toBe(
true,
@@ -799,7 +1006,7 @@ describe('Insights methods', () => {
const aggregateSpy = jest.spyOn(mongoose.models.Conversation, 'aggregate');
try {
- await createInsightsMethods(mongoose).getInsights({
+ await createScopedInsightsMethods().getInsights({
tenantId: 'tenant-a',
range: '7d',
search: '[email protected]',
@@ -813,7 +1020,9 @@ describe('Insights methods', () => {
.map(([pipeline]) => pipeline as SearchStage[])
.find((pipeline) => pipeline.some((stage) => stage.$lookup));
const identityLookup = searchedPipeline?.find((stage) => stage.$lookup)?.$lookup;
- const ownerConversion = searchedPipeline?.find((stage) => stage.$addFields)?.$addFields;
+ const ownerConversion = searchedPipeline?.find(
+ (stage) => stage.$addFields?.insightsUserId,
+ )?.$addFields;
expect(identityLookup).toEqual({
from: 'users',
diff --git a/packages/data-schemas/src/methods/insights.ts b/packages/data-schemas/src/methods/insights.ts
index cb032afd80..afe18199ca 100644
--- a/packages/data-schemas/src/methods/insights.ts
+++ b/packages/data-schemas/src/methods/insights.ts
@@ -4,18 +4,20 @@ import {
INSIGHTS_SEARCH_MIN_LENGTH,
} from 'librechat-data-provider';
import type {
- TInsightsResponse,
- TInsightsParams,
- TInsightsDailyPoint,
- TInsightsUser,
+ TInsightsAgent,
TInsightsChurnedUser,
TInsightsConversation,
+ TInsightsDailyPoint,
+ TInsightsParams,
+ TInsightsResponse,
+ TInsightsUser,
} from 'librechat-data-provider';
import type { Model, PipelineStage } from 'mongoose';
import type { IConversation, IMessage, IUser } from '~/types';
export type InsightsOptions = TInsightsParams & {
tenantId?: string;
+ agents?: TInsightsAgent[];
};
export type InsightsResult = TInsightsResponse;
@@ -25,69 +27,25 @@ export type InsightsMethods = {
};
type CountResult = { total: number };
-
-type ConversationDay = {
- date: string;
- conversations: number;
-};
-
-type DailyUsers = {
- date: string;
- users: number;
-};
-
-type UserMessageTotals = {
- messages: number;
-};
-
-type RecentConversation = {
- conversationId: string;
- date: Date;
- userId: string;
-};
-
-type MessageSummary = {
- _id: string;
- messages: number;
-};
-
-type ChurnedUserActivity = {
- _id: string;
- lastSeen: Date;
-};
-
+type ConversationDay = { date: string; conversations: number };
+type DailyUsers = { date: string; users: number };
+type UserMessageTotals = { messages: number };
+type RecentConversation = { conversationId: string; agentId: string; date: Date; userId: string };
+type MessageSummary = UserMessageTotals & { _id: string };
+type ChurnedUserActivity = { _id: string; lastSeen: Date };
type ChurnedUserSummary = UserMessageTotals & {
_id: string;
conversations: number;
firstSeen: Date;
};
-
-type ConversationOwner = {
- conversationId: string;
- userId: string;
-};
-
+type ConversationOwner = { conversationId: string; userId: string };
type ConversationMessageSummary = UserMessageTotals & {
_id: ConversationOwner;
totalTokens: number;
};
-
-type UserConversationCount = {
- _id: string;
- conversations: number;
-};
-
-type MessageDay = {
- date: string;
- messages: number;
- totalTokens: number;
-};
-
-type FirstMessage = {
- _id: ConversationOwner;
- text: string;
-};
-
+type UserConversationCount = { _id: string; conversations: number };
+type MessageDay = { date: string; messages: number; totalTokens: number };
+type FirstMessage = { _id: ConversationOwner; text: string };
type UserSummary = {
_id: { toString(): string };
name?: string;
@@ -95,24 +53,24 @@ type UserSummary = {
email?: string;
};
-const rangeDays = {
- '24h': 1,
- '7d': 7,
- '30d': 30,
-};
-
+const rangeDays = { '24h': 1, '7d': 7, '30d': 30 };
const defaultRange = '7d';
const churnedUserWindowDays = 28;
const churnedUserLimit = 8;
const dayMs = 24 * 60 * 60 * 1000;
+
function tenantMatch(tenantId?: string) {
return tenantId ? { tenantId } : { tenantId: { $exists: false } };
}
+function joinedTenantMatch(tenantId?: string) {
+ return tenantId
+ ? { 'insightsConversation.tenantId': tenantId }
+ : { 'insightsConversation.tenantId': { $exists: false } };
+}
+
function validTimeZone(timeZone?: string) {
- if (!timeZone) {
- return 'UTC';
- }
+ if (!timeZone) return 'UTC';
try {
new Intl.DateTimeFormat('en', { timeZone }).format();
return timeZone;
@@ -178,19 +136,6 @@ function startOfZonedDate(key: string, timeZone: string) {
return new Date(instant);
}
-const isNonEmptyString = (value: unknown): value is string =>
- typeof value === 'string' && value.trim() !== '';
-
-const conversationOwnerKey = ({ conversationId, userId }: ConversationOwner): string =>
- JSON.stringify([conversationId, userId]);
-
-const conversationOwnerMatch = ({ conversationId, userId }: ConversationOwner) => ({
- conversationId,
- user: userId,
-});
-
-const escapeRegex = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-
function resolveRange(options: InsightsOptions) {
const now = new Date();
const range = options.range ?? defaultRange;
@@ -215,6 +160,102 @@ function resolveRange(options: InsightsOptions) {
return { from: new Date(now.getTime() - days * dayMs), to: now };
}
+const isNonEmptyString = (value: unknown): value is string =>
+ typeof value === 'string' && value.trim() !== '';
+const escapeRegex = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+const conversationOwnerKey = ({ conversationId, userId }: ConversationOwner): string =>
+ JSON.stringify([conversationId, userId]);
+const conversationOwnerMatch = ({ conversationId, userId }: ConversationOwner) => ({
+ conversationId,
+ user: userId,
+});
+
+function conversationScope(match: Record<string, unknown>, agentIds: string[]): PipelineStage[] {
+ return [
+ {
+ $match: {
+ ...match,
+ $or: [
+ { initial_agent_id: { $in: agentIds } },
+ { initial_agent_id: { $exists: false }, agent_id: { $in: agentIds } },
+ ],
+ },
+ },
+ { $addFields: { insightsAgentId: { $ifNull: ['$initial_agent_id', '$agent_id'] } } },
+ ];
+}
+
+function messageScope(
+ match: Record<string, unknown>,
+ agentIds: string[],
+ tenantId?: string,
+): PipelineStage[] {
+ const attributedMatch =
+ match.isCreatedByUser === true
+ ? match
+ : {
+ $and: [
+ match,
+ {
+ $or: [
+ { isCreatedByUser: true },
+ { isCreatedByUser: { $ne: true }, model: { $in: agentIds } },
+ ],
+ },
+ ],
+ };
+ return [
+ { $match: attributedMatch },
+ {
+ $lookup: {
+ from: 'conversations',
+ localField: 'conversationId',
+ foreignField: 'conversationId',
+ as: 'insightsConversation',
+ },
+ },
+ { $unwind: '$insightsConversation' },
+ {
+ $addFields: {
+ insightsOwnerMatches: { $eq: ['$user', '$insightsConversation.user'] },
+ },
+ },
+ {
+ $match: {
+ ...joinedTenantMatch(tenantId),
+ 'insightsConversation.isTemporary': { $ne: true },
+ 'insightsConversation.subagentThread': { $exists: false },
+ 'insightsConversation.user': { $nin: [null, ''] },
+ insightsOwnerMatches: true,
+ $or: [
+ { isCreatedByUser: true, 'insightsConversation.initial_agent_id': { $in: agentIds } },
+ {
+ isCreatedByUser: true,
+ 'insightsConversation.initial_agent_id': { $exists: false },
+ 'insightsConversation.agent_id': { $in: agentIds },
+ },
+ {
+ isCreatedByUser: { $ne: true },
+ model: { $in: agentIds },
+ $or: [
+ {
+ 'insightsConversation.initial_agent_id': {
+ $exists: true,
+ $nin: [null, ''],
+ },
+ },
+ {
+ 'insightsConversation.initial_agent_id': { $exists: false },
+ 'insightsConversation.agent_id': { $exists: true, $nin: [null, ''] },
+ },
+ ],
+ },
+ ],
+ },
+ },
+ ];
+}
+
const addDay = (days: Map<string, TInsightsDailyPoint>, date: string): TInsightsDailyPoint => {
const current = days.get(date) ?? {
date,
@@ -250,17 +291,16 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
const User = mongoose.models.User as Model<IUser>;
const page = Math.max(1, Math.floor(options.page ?? 1));
const pageSize = Math.min(50, Math.max(5, Math.floor(options.pageSize ?? 10)));
+ const agentIds = [...new Set(options.agentIds ?? [])].sort((a, b) => a.localeCompare(b));
const { from, to } = resolveRange(options);
const timeZone = validTimeZone(options.timeZone);
const churnedCutoff = new Date(to.getTime() - churnedUserWindowDays * dayMs);
const churnedActivityFrom = new Date(from.getTime() - churnedUserWindowDays * dayMs);
const tenant = tenantMatch(options.tenantId);
- const tenantConversations = {
+ const conversationMatch = {
...tenant,
isTemporary: { $ne: true },
- };
- const conversationMatch = {
- ...tenantConversations,
+ subagentThread: { $exists: false },
user: { $nin: [null, ''] },
createdAt: { $gte: from, $lte: to },
};
@@ -270,15 +310,15 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
isTemporary: { $ne: true },
createdAt: { $gte: from, $lte: to },
};
- const conversationScope = [{ $match: conversationMatch }];
- const messageScope = [{ $match: messageMatch }];
+ const conversationPipeline = conversationScope(conversationMatch, agentIds);
+ const messagePipeline = messageScope(messageMatch, agentIds, options.tenantId);
const requestedSearch = options.search?.trim().slice(0, INSIGHTS_SEARCH_MAX_LENGTH) ?? '';
const search = requestedSearch.length >= INSIGHTS_SEARCH_MIN_LENGTH ? requestedSearch : '';
const searchRegex = search ? new RegExp(escapeRegex(search), 'i') : undefined;
- const searchedConversationScope: PipelineStage[] = searchRegex
+ const searchedConversationPipeline: PipelineStage[] = searchRegex
? [
- { $match: conversationMatch },
+ ...conversationPipeline,
{
$addFields: {
insightsUserId: {
@@ -302,9 +342,7 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
{
matchedIdentity: {
$elemMatch: {
- ...(options.tenantId
- ? { tenantId: options.tenantId }
- : { tenantId: { $exists: false } }),
+ ...tenant,
$or: [
{ name: searchRegex },
{ username: searchRegex },
@@ -317,20 +355,23 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
},
},
]
- : [];
+ : conversationPipeline;
- const insightsAggregations = await Promise.all([
+ const [
+ conversationDays,
+ latestRows,
+ searchedConversationCount,
+ messageDays,
+ userCount,
+ dailyUsers,
+ topMessageUsers,
+ churnedUserRows,
+ ] = await Promise.all([
Conversation.aggregate<ConversationDay>([
- ...conversationScope,
+ ...conversationPipeline,
{
$group: {
- _id: {
- $dateToString: {
- format: '%Y-%m-%d',
- date: '$createdAt',
- timezone: timeZone,
- },
- },
+ _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt', timezone: timeZone } },
conversations: { $sum: 1 },
},
},
@@ -338,7 +379,7 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
{ $sort: { date: 1 } },
]),
Conversation.aggregate<RecentConversation>([
- ...(searchRegex ? searchedConversationScope : conversationScope),
+ ...searchedConversationPipeline,
{ $sort: { createdAt: -1, _id: -1 } },
{ $skip: (page - 1) * pageSize },
{ $limit: pageSize },
@@ -346,25 +387,23 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
$project: {
_id: 0,
conversationId: 1,
+ agentId: '$insightsAgentId',
date: '$createdAt',
userId: '$user',
},
},
]),
searchRegex
- ? Conversation.aggregate<CountResult>([...searchedConversationScope, { $count: 'total' }])
+ ? Conversation.aggregate<CountResult>([
+ ...searchedConversationPipeline,
+ { $count: 'total' },
+ ])
: Promise.resolve([] as CountResult[]),
Message.aggregate<MessageDay>([
- ...messageScope,
+ ...messagePipeline,
{
$group: {
- _id: {
- $dateToString: {
- format: '%Y-%m-%d',
- date: '$createdAt',
- timezone: timeZone,
- },
- },
+ _id: { $dateToString: { format: '%Y-%m-%d', date: '$createdAt', timezone: timeZone } },
messages: { $sum: 1 },
totalTokens: { $sum: { $ifNull: ['$tokenCount', 0] } },
},
@@ -373,21 +412,17 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
{ $sort: { date: 1 } },
]),
Message.aggregate<CountResult>([
- { $match: { ...messageMatch, isCreatedByUser: true } },
+ ...messagePipeline,
{ $group: { _id: '$user' } },
{ $count: 'total' },
]),
Message.aggregate<DailyUsers>([
- { $match: { ...messageMatch, isCreatedByUser: true } },
+ ...messagePipeline,
{
$group: {
_id: {
date: {
- $dateToString: {
- format: '%Y-%m-%d',
- date: '$createdAt',
- timezone: timeZone,
- },
+ $dateToString: { format: '%Y-%m-%d', date: '$createdAt', timezone: timeZone },
},
user: '$user',
},
@@ -398,47 +433,30 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
{ $sort: { date: 1 } },
]),
Message.aggregate<MessageSummary>([
- ...messageScope,
- {
- $group: {
- _id: '$user',
- messages: { $sum: 1 },
- },
- },
+ ...messagePipeline,
+ { $group: { _id: '$user', messages: { $sum: 1 } } },
{ $sort: { messages: -1, _id: 1 } },
{ $limit: 8 },
]),
Message.aggregate<ChurnedUserActivity>([
- {
- $match: {
+ ...messageScope(
+ {
...tenant,
isTemporary: { $ne: true },
- user: { $nin: [null, ''] },
isCreatedByUser: true,
+ user: { $nin: [null, ''] },
createdAt: { $gte: churnedActivityFrom, $lte: to },
},
- },
- {
- $group: {
- _id: '$user',
- lastSeen: { $max: '$createdAt' },
- },
- },
+ agentIds,
+ options.tenantId,
+ ),
+ { $group: { _id: '$user', lastSeen: { $max: '$createdAt' } } },
{ $match: { lastSeen: { $gte: churnedActivityFrom, $lte: churnedCutoff } } },
{ $sort: { lastSeen: -1, _id: 1 } },
{ $limit: churnedUserLimit },
]),
]);
- const [
- conversationDays,
- latestRows,
- searchedConversationCount,
- messageDays,
- userCount,
- dailyUsers,
- topMessageUsers,
- churnedUserRows,
- ] = insightsAggregations;
+
const latestConversationOwners = latestRows
.filter(
(row): row is RecentConversation & { userId: string } =>
@@ -467,15 +485,15 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
latestConversationMatches.length === 0
? Promise.resolve([] as ConversationMessageSummary[])
: Message.aggregate<ConversationMessageSummary>([
- {
- $match: {
- ...tenant,
- isTemporary: { $ne: true },
+ ...messageScope(
+ {
+ ...messageMatch,
conversationId: { $in: latestConversationIds },
$or: latestConversationMatches,
- createdAt: { $gte: from, $lte: to },
},
- },
+ agentIds,
+ options.tenantId,
+ ),
{
$group: {
_id: { conversationId: '$conversationId', userId: '$user' },
@@ -487,15 +505,17 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
latestConversationMatches.length === 0
? Promise.resolve([] as FirstMessage[])
: Message.aggregate<FirstMessage>([
- {
- $match: {
+ ...messageScope(
+ {
...tenant,
isTemporary: { $ne: true },
+ isCreatedByUser: true,
conversationId: { $in: latestConversationIds },
$or: latestConversationMatches,
- isCreatedByUser: true,
},
- },
+ agentIds,
+ options.tenantId,
+ ),
{ $sort: { createdAt: 1, _id: 1 } },
{
$group: {
@@ -507,36 +527,28 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
topUserIds.length === 0
? Promise.resolve([] as UserConversationCount[])
: Message.aggregate<UserConversationCount>([
- {
- $match: {
- ...messageMatch,
- user: { $in: topUserIds },
- isCreatedByUser: true,
- },
- },
- {
- $group: {
- _id: { user: '$user', conversationId: '$conversationId' },
- },
- },
- {
- $group: {
- _id: '$_id.user',
- conversations: { $sum: 1 },
- },
- },
+ ...messageScope(
+ { ...messageMatch, user: { $in: topUserIds } },
+ agentIds,
+ options.tenantId,
+ ),
+ { $group: { _id: { user: '$user', conversationId: '$conversationId' } } },
+ { $group: { _id: '$_id.user', conversations: { $sum: 1 } } },
]),
churnedUserIds.length === 0
? Promise.resolve([] as ChurnedUserSummary[])
: Message.aggregate<ChurnedUserSummary>([
- {
- $match: {
+ ...messageScope(
+ {
...tenant,
isTemporary: { $ne: true },
+ isCreatedByUser: true,
user: { $in: churnedUserIds },
createdAt: { $lte: to },
},
- },
+ agentIds,
+ options.tenantId,
+ ),
{
$group: {
_id: { user: '$user', conversationId: '$conversationId' },
@@ -561,6 +573,7 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
]);
const users = new Map(userRows.map((user) => [user._id.toString(), user]));
+ const agentNames = new Map((options.agents ?? []).map((agent) => [agent.id, agent.name]));
const latestSummaries = new Map(
latestMessageSummaries.map((summary) => [conversationOwnerKey(summary._id), summary]),
);
@@ -573,19 +586,13 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
for (let key = firstDay; key <= lastDay; key = addCalendarDaysToKey(key, 1)) {
addDay(days, key);
}
- for (const row of conversationDays) {
- const day = addDay(days, row.date);
- day.conversations = row.conversations;
- }
+ for (const row of conversationDays) addDay(days, row.date).conversations = row.conversations;
for (const row of messageDays) {
const day = addDay(days, row.date);
day.messages = row.messages;
day.totalTokens = row.totalTokens;
}
- for (const row of dailyUsers) {
- const day = addDay(days, row.date);
- day.users = row.users;
- }
+ for (const row of dailyUsers) addDay(days, row.date).users = row.users;
const totalConversations = conversationDays.reduce(
(total, row) => total + row.conversations,
@@ -594,8 +601,6 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
const matchingConversations = searchRegex
? (searchedConversationCount[0]?.total ?? 0)
: totalConversations;
- const totalMessages = messageDays.reduce((total, row) => total + row.messages, 0);
- const totalTokens = messageDays.reduce((total, row) => total + row.totalTokens, 0);
const topConversationCountsByUser = new Map(
topConversationCounts.map((summary) => [summary._id, summary.conversations]),
);
@@ -604,11 +609,12 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
);
return {
+ agents: options.agents ?? [],
summary: {
totalUsers: userCount[0]?.total ?? 0,
totalConversations,
- totalMessages,
- totalTokens,
+ totalMessages: messageDays.reduce((total, row) => total + row.messages, 0),
+ totalTokens: messageDays.reduce((total, row) => total + row.totalTokens, 0),
},
daily: [...days.values()].sort((left, right) => left.date.localeCompare(right.date)),
topUsers: topMessageUsers.map((row) =>
@@ -635,6 +641,7 @@ export function createInsightsMethods(mongoose: typeof import('mongoose')): Insi
const summary = latestSummaries.get(ownerKey);
return {
...row,
+ agentName: agentNames.get(row.agentId) ?? row.agentId,
userId,
date: row.date.toISOString(),
name: user?.name || user?.username || '',
diff --git a/packages/data-schemas/src/methods/userGroup.spec.ts b/packages/data-schemas/src/methods/userGroup.spec.ts
index 991bba445c..69d47126e2 100644
--- a/packages/data-schemas/src/methods/userGroup.spec.ts
+++ b/packages/data-schemas/src/methods/userGroup.spec.ts
@@ -1516,6 +1516,7 @@ describe('userGroup methods', () => {
username: 'alice',
password: 'password123',
provider: 'local',
+ role: SystemRoles.ADMIN,
},
{
name: 'Bob Jones',
@@ -1577,6 +1578,7 @@ describe('userGroup methods', () => {
const userResults = results.filter((r) => r.type === PrincipalType.USER);
expect(userResults.length).toBeGreaterThanOrEqual(1);
expect(userResults[0].name).toBe('Alice Smith');
+ expect(userResults[0].isAdmin).toBe(true);
});
it('finds matching groups', async () => {
diff --git a/packages/data-schemas/src/methods/userGroup.ts b/packages/data-schemas/src/methods/userGroup.ts
index 2532fde043..8d6d225eda 100644
--- a/packages/data-schemas/src/methods/userGroup.ts
+++ b/packages/data-schemas/src/methods/userGroup.ts
@@ -1,6 +1,6 @@
import { Types } from 'mongoose';
import { AsyncLocalStorage } from 'async_hooks';
-import { CacheKeys, PrincipalType } from 'librechat-data-provider';
+import { CacheKeys, PrincipalType, SystemRoles } from 'librechat-data-provider';
import type { TPrincipalSearchResult } from 'librechat-data-provider';
import type { Model, ClientSession, FilterQuery } from 'mongoose';
import type { CacheStore, IGroup, IRole, IUser } from '~/types';
@@ -1077,7 +1077,7 @@ export function createUserGroupMethods(
function transformUserToTPrincipalSearchResult(
user: Pick<
IUser,
- 'id' | 'name' | 'email' | 'username' | 'avatar' | 'provider' | 'idOnTheSource'
+ 'id' | 'name' | 'email' | 'username' | 'avatar' | 'provider' | 'idOnTheSource' | 'role'
>,
): TPrincipalSearchResult {
return {
@@ -1090,6 +1090,7 @@ export function createUserGroupMethods(
provider: user.provider,
source: 'local',
idOnTheSource: user.idOnTheSource || user.id,
+ isAdmin: user.role === SystemRoles.ADMIN,
};
}
@@ -1137,7 +1138,7 @@ export function createUserGroupMethods(
if (!typeFilter || typeFilter.includes(PrincipalType.USER)) {
/** Note: searchUsers is imported from ~/models and needs to be passed in or implemented */
- const userFields = 'name email username avatar provider idOnTheSource';
+ const userFields = 'name email username avatar provider idOnTheSource role';
/** For now, we'll use a direct query instead of searchUsers */
const User = mongoose.models.User as Model<IUser>;
const regex = new RegExp(escapedPattern, 'i');
@@ -1162,6 +1163,7 @@ export function createUserGroupMethods(
avatar: user.avatar,
provider: user.provider,
idOnTheSource: user.idOnTheSource,
+ role: user.role,
}),
),
),
@@ -1199,6 +1201,7 @@ export function createUserGroupMethods(
name: role.name,
source: 'local' as const,
idOnTheSource: role.name,
+ isAdmin: role.name === SystemRoles.ADMIN,
})),
),
);
diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.ts
index c853b1b160..0b291973c4 100644
--- a/packages/data-schemas/src/schema/convo.ts
+++ b/packages/data-schemas/src/schema/convo.ts
@@ -44,6 +44,11 @@ const convoSchema: Schema<IConversation> = new Schema(
agent_id: {
type: String,
},
+ initial_agent_id: {
+ type: String,
+ default: undefined,
+ select: false,
+ },
subagentThread: {
type: {
rootConversationId: { type: String, required: true },
@@ -371,6 +376,10 @@ convoSchema.index({ expiredAt: 1 }, { expireAfterSeconds: 0 });
convoSchema.index({ createdAt: 1, updatedAt: 1 });
convoSchema.index({ conversationId: 1, user: 1, tenantId: 1 }, { unique: true });
convoSchema.index({ tenantId: 1, isTemporary: 1, createdAt: -1, _id: -1 });
+/** Insights attributes new conversations by an immutable primary agent and falls back
+ * to the mutable agent field only for legacy rows where the primary field is absent. */
+convoSchema.index({ tenantId: 1, isTemporary: 1, initial_agent_id: 1, createdAt: -1, _id: -1 });
+convoSchema.index({ tenantId: 1, isTemporary: 1, agent_id: 1, createdAt: -1, _id: -1 });
convoSchema.index({ user: 1, _id: 1 });
convoSchema.index({ user: 1, chatProjectId: 1, updatedAt: -1, _id: -1 });
convoSchema.index({ user: 1, chatProjectId: 1, createdAt: -1, _id: -1 });
diff --git a/packages/data-schemas/src/schema/insights.spec.ts b/packages/data-schemas/src/schema/insights.spec.ts
index e24b8ef7de..83b5321988 100644
--- a/packages/data-schemas/src/schema/insights.spec.ts
+++ b/packages/data-schemas/src/schema/insights.spec.ts
@@ -36,5 +36,33 @@ describe('Insights indexes', () => {
_id: -1,
}),
).toBe(true);
+ expect(
+ hasIndex(conversationSchema.indexes(), {
+ tenantId: 1,
+ isTemporary: 1,
+ initial_agent_id: 1,
+ createdAt: -1,
+ _id: -1,
+ }),
+ ).toBe(true);
+ expect(
+ hasIndex(conversationSchema.indexes(), {
+ tenantId: 1,
+ isTemporary: 1,
+ agent_id: 1,
+ createdAt: -1,
+ _id: -1,
+ }),
+ ).toBe(true);
+ expect(
+ hasIndex(messageSchema.indexes(), {
+ tenantId: 1,
+ isTemporary: 1,
+ isCreatedByUser: 1,
+ model: 1,
+ createdAt: -1,
+ _id: -1,
+ }),
+ ).toBe(true);
});
});
diff --git a/packages/data-schemas/src/schema/message.ts b/packages/data-schemas/src/schema/message.ts
index 4418fff967..0bd3609e85 100644
--- a/packages/data-schemas/src/schema/message.ts
+++ b/packages/data-schemas/src/schema/message.ts
@@ -308,6 +308,15 @@ messageSchema.index({ expiredAt: 1 }, { expireAfterSeconds: 0 });
messageSchema.index({ createdAt: 1 });
messageSchema.index({ messageId: 1, user: 1, tenantId: 1 }, { unique: true });
messageSchema.index({ tenantId: 1, isTemporary: 1, createdAt: -1, _id: -1 });
+/** Insights attributes assistant activity from the persisted top-level agent model. */
+messageSchema.index({
+ tenantId: 1,
+ isTemporary: 1,
+ isCreatedByUser: 1,
+ model: 1,
+ createdAt: -1,
+ _id: -1,
+});
messageSchema.index({
tenantId: 1,
isTemporary: 1,
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index 4fa7254b10..665a1623e1 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -65,13 +65,20 @@ export type AuditCategory = (typeof AUDIT_CATEGORIES)[number];
* action maps unambiguously to a category. The Mongoose schema enum and the
* HTTP handler's whitelist both consume this constant so they cannot drift.
*/
-export const AUDIT_ACTIONS = ['grant.assigned', 'grant.removed'] as const;
+export const AUDIT_ACTIONS = [
+ 'grant.assigned',
+ 'grant.removed',
+ 'permission.insights_assigned',
+ 'permission.insights_removed',
+] as const;
export type AuditAction = (typeof AUDIT_ACTIONS)[number];
/** Maps each action to its category so writers never pass both. */
export const AUDIT_ACTION_CATEGORY: Record<AuditAction, AuditCategory> = {
'grant.assigned': 'grant',
'grant.removed': 'grant',
+ 'permission.insights_assigned': 'permission',
+ 'permission.insights_removed': 'permission',
};
/** Result of the audited operation. Kept first-class instead of being encoded
diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.ts
index 0362977926..cabdd1371f 100644
--- a/packages/data-schemas/src/types/convo.ts
+++ b/packages/data-schemas/src/types/convo.ts
@@ -264,6 +264,8 @@ export interface IConversation extends Document {
resendFiles?: boolean;
imageDetail?: string;
agent_id?: string;
+ /** Immutable primary persisted-agent attribution for Insights. */
+ initial_agent_id?: string | null;
subagentThread?: TSubagentThreadLineage;
/** Internal execution fence. Excluded from ordinary conversation reads. */
subagentThreadLease?: ISubagentThreadLease;