LibreChat/api/server/routes/admin/langfuse.js
Atef Bellaaj d481b6b695
🏬 feat: Sync Langfuse Prompts into the Catalog (#17095)
* feat(prompts): sync Langfuse prompts into the catalog

* refactor(prompts): compose the Langfuse prompt sync runner outside the admin handler

Add createLangfusePromptSyncRunner, which binds the lock, the prompt-group
methods, the ACL grant and the Mongo error predicates once and returns a
runner that takes the per-request source, connection-bound listPrompts,
lock lease and page cap. The admin handler receives that runner as one
dependency instead of forwarding its parts, and its config method
signatures return a LangfuseAdminConfig interface in place of Mongoose
document types.

In api, api/cache/distributedLock.js creates the one DistributedLock for
the process and api/server/services/LangfusePromptSync.js composes the
runner once with it; the admin route imports the composed runner.

* fix(prompts): report incomplete Langfuse syncs and gate the sync action

- Refresh the prompt-group and effective-permission queries after a failed
  sync too, because earlier imports can already be committed.
- Return `complete: false` when the page limit stops a sync before the last
  upstream page, and show a warning instead of the success message.
- Show the Sync prompts action only to users with `manage:prompts`, the
  capability the sync route requires. Resolve the Langfuse startup-config
  capabilities in one batched lookup.
- Document that an interrupted import can leave a group without its initial
  PUBLIC grant, and that a page in progress can outlast an expired lease.

---------

Co-authored-by: Rebase Probe <probe@example.com>
2026-10-24 13:48:52 +02:00

64 lines
2.5 KiB
JavaScript

const express = require('express');
const { createAdminLangfuseHandlers } = require('@librechat/api');
const { SystemCapabilities } = require('@librechat/data-schemas');
const {
hasConfigCapability,
requireCapability,
} = require('~/server/middleware/roles/capabilities');
const { syncLangfusePromptCatalog } = require('~/server/services/LangfusePromptSync');
const { invalidateConfigCaches } = require('~/server/services/Config');
const configMiddleware = require('~/server/middleware/config/app');
const { requireJwtAuth } = require('~/server/middleware');
const db = require('~/models');
const router = express.Router();
const requireAdminAccess = requireCapability(SystemCapabilities.ACCESS_ADMIN);
const requireManagePrompts = requireCapability(SystemCapabilities.MANAGE_PROMPTS);
async function requireLangfuseManage(req, res, next) {
try {
const id = req.user?.id ?? req.user?._id?.toString();
if (!id) {
return res.status(401).json({ message: 'Authentication required' });
}
const user = {
id,
role: req.user.role ?? '',
tenantId: req.user.tenantId,
idOnTheSource: req.user.idOnTheSource ?? null,
};
if (await hasConfigCapability(user, 'langfuse')) {
return next();
}
return res.status(403).json({ message: 'Forbidden' });
} catch (_err) {
return res.status(500).json({ message: 'Internal Server Error' });
}
}
const handlers = createAdminLangfuseHandlers({
findConfigByPrincipal: db.findConfigByPrincipal,
patchConfigFields: db.patchConfigFields,
toggleConfigActive: db.toggleConfigActive,
getMessages: db.getMessages,
syncPromptCatalog: syncLangfusePromptCatalog,
invalidateConfigCaches,
recordAuditEntry: db.recordAuditEntry,
});
// `configMiddleware` runs last so unauthorized callers are rejected before the
// config resolves; credential verification reads the deployment's Langfuse
// headers off `req.config`, so without it proxied hosts reject every request.
router.use(requireJwtAuth, requireAdminAccess, requireLangfuseManage, configMiddleware);
router.get('/connection', handlers.getConnection);
router.get('/connection/session/:conversationId', handlers.getSessionLink);
router.put('/connection', handlers.updateConnection);
router.post('/connection/test', handlers.testConnection);
router.put('/prompt-sync', handlers.updatePromptSync);
router.get('/prompts', handlers.listPrompts);
router.post('/prompts/sync', requireManagePrompts, handlers.syncPrompts);
router.get('/prompts/:name', handlers.getPrompt);
module.exports = router;