Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔗 feat: Link Langfuse Prompts as Agent Instructions (#17294)
Atef Bellaaj05e7f1d2e608
diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.jsindex 828aa2b6e0..e8292bf687 100644--- a/api/server/controllers/agents/v1.js+++ b/api/server/controllers/agents/v1.js@@ -834,6 +834,7 @@ const createAgentHandler = async (req, res) => {previous: undefined,next: agentData.instructionsPrompt,filters: req.config?.filters,+ linkedInstructions: req.config?.endpoints?.agents?.linkedInstructions,logger,req,});@@ -1235,6 +1236,7 @@ const updateAgentHandler = async (req, res) => {previous: existingAgent.instructionsPrompt,next: instructionsPromptField,filters: req.config?.filters,+ linkedInstructions: req.config?.endpoints?.agents?.linkedInstructions,logger,req,});diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.jsindex 25cd3d9cb3..228dab81aa 100644--- a/api/server/controllers/agents/v1.spec.js+++ b/api/server/controllers/agents/v1.spec.js@@ -124,6 +124,7 @@ const { grantPermission } = require('~/server/services/PermissionService');const { hasCapability } = require('~/server/middleware/roles/capabilities');const { getStrategyFunctions } = require('~/server/services/Files/strategies');const { resizeAvatar } = require('~/server/services/Files/images/avatar');+const { promptService } = require('~/server/services/Prompts');const db = require('~/models');/**@@ -7605,5 +7606,300 @@ describe('Agent Controllers - Mass Assignment Protection', () => {getRoleByNameSpy.mockRestore();});});++ describe('Langfuse links', () => {+ /** Restored individually so sibling describe blocks' spies survive `afterEach`. */+ let activeSpies = [];++ /** Stubs the Langfuse resolve result; the real adapter dispatch is out of scope here. */+ const stubLangfuseResolve = (overrides = {}) => {+ const spy = jest.spyOn(promptService, 'resolvePrompt').mockResolvedValue({+ ok: true,+ value: {+ source: 'langfuse',+ prompt: 'You are a Langfuse-linked assistant.',+ type: 'text',+ version: 1,+ labels: ['production'],+ ...overrides,+ },+ });+ activeSpies.push(spy);+ return spy;+ };++ /** Spies on global `fetch` only to assert the Langfuse adapter never calls it. */+ const spyOnLangfuseFetch = () => {+ const spy = jest.spyOn(global, 'fetch');+ activeSpies.push(spy);+ return spy;+ };++ const switchOn = () => {+ mockReq.config = {+ endpoints: { agents: { linkedInstructions: { langfuse: { enabled: true } } } },+ };+ };++ afterEach(() => {+ activeSpies.forEach((spy) => spy.mockRestore());+ activeSpies = [];+ });++ test('returns 400 instructions_prompt_unavailable for a new Langfuse link while the switch is off', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ mockGroupVisibility(new Set([groupId]));+ mockReq.body = {+ name: 'Switch Off Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: { source: 'langfuse', groupId, selection: { type: 'production' } },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('allows re-saving the unchanged Langfuse link, and switching it to inline, while the switch is off', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ mockGroupVisibility(new Set([groupId]));+ const link = { source: 'langfuse', groupId, selection: { type: 'production' } };+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Previously Linked Langfuse Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: link,+ });++ mockReq.params = { id: agentId };+ mockReq.body = { instructionsPrompt: link };+ await updateAgentHandler(mockReq, mockRes);+ // `updateAgentHandler` only calls `res.status` on error, so no call means success.+ expect(mockRes.status).not.toHaveBeenCalled();+ const resaved = mockRes.json.mock.calls[0][0];+ expect(resaved.instructionsPrompt).toEqual(link);+ let persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toEqual(link);++ mockRes.json.mockClear();+ mockRes.status.mockClear();+ mockReq.body = { instructionsPrompt: null, instructions: 'Inline now.' };+ await updateAgentHandler(mockReq, mockRes);+ expect(mockRes.status).not.toHaveBeenCalled();+ const updated = mockRes.json.mock.calls[0][0];+ expect(updated.instructionsPrompt).toBeUndefined();+ persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toBeUndefined();+ expect(persisted.instructions).toBe('Inline now.');+ });++ test('persists a new Langfuse link once the switch is on, using the stubbed resolve', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ const link = { source: 'langfuse', groupId, selection: { type: 'exact', version: 4 } };+ const resolveSpy = stubLangfuseResolve({ groupId, version: 4 });+ switchOn();+ mockGroupVisibility(new Set([groupId]));+ mockReq.body = {+ name: 'Langfuse Version Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: link,+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const created = mockRes.json.mock.calls[0][0];+ expect(created.instructionsPrompt).toEqual(link);+ const persisted = await Agent.findOne({ id: created.id }).lean();+ expect(persisted.instructionsPrompt).toEqual(link);+ expect(resolveSpy).toHaveBeenCalledWith(+ expect.objectContaining({ groupId, source: 'langfuse' }),+ );+ });++ test('returns 400 instructions_prompt_unavailable for a native link to a real Langfuse group, with no Langfuse network call', async () => {+ // Real group and resolver: rejected on the group's recorded source before any Langfuse call.+ const { _id: groupId } = await db.createLangfusePromptGroup({+ name: 'Mismatched Source Group',+ author: mockReq.user.id,+ authorName: 'Fixture Author',+ sourceDestination: 'env',+ sourceProjectId: 'mismatch-project',+ sourcePromptName: 'mismatch-prompt',+ });+ const fetchSpy = spyOnLangfuseFetch();+ mockGroupVisibility(new Set([groupId]));+ mockReq.body = {+ name: 'Mismatched Source Agent',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: { source: 'native', groupId, selection: { type: 'production' } },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('returns 400 instructions_prompt_unavailable for a Langfuse link to a real native group while the switch is on, with no Langfuse network call', async () => {+ const { groupId } = await createPromptGroupFixture('Native Group For Langfuse Mismatch');+ const fetchSpy = spyOnLangfuseFetch();+ switchOn();+ mockGroupVisibility(new Set([groupId]));+ mockReq.body = {+ name: 'Langfuse Link To Native Group',+ provider: 'openai',+ model: 'gpt-4',+ instructionsPrompt: { source: 'langfuse', groupId, selection: { type: 'production' } },+ };++ await createAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(400);+ expect(mockRes.json).toHaveBeenCalledWith({+ error: expect.any(String),+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ expect(await Agent.countDocuments()).toBe(0);+ });++ test('duplicateAgentHandler copies a Langfuse link verbatim and presents it with its own source when restricted', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ const link = { source: 'langfuse', groupId, selection: { type: 'production' } };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Langfuse Source Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: link,+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { id: agent.id };++ await duplicateAgentHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(201);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.agent.instructionsPrompt).toEqual({ source: 'langfuse', restricted: true });+ const persisted = await Agent.findOne({ id: response.agent.id }).lean();+ expect(persisted.instructionsPrompt).toEqual(link);+ });++ test('revertAgentVersionHandler restores a Langfuse link verbatim and presents it with its own source when restricted', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ const link = { source: 'langfuse', groupId, selection: { type: 'exact', version: 2 } };+ const agentId = `agent_${nanoid()}`;+ await Agent.create({+ id: agentId,+ author: mockReq.user.id,+ name: 'Current Unlinked Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Langfuse-Linked Snapshot',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: link,+ },+ ],+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { id: agentId };+ mockReq.body = { version_index: 0 };++ await revertAgentVersionHandler(mockReq, mockRes);++ expect(mockRes.status).not.toHaveBeenCalledWith(403);+ expect(mockRes.status).not.toHaveBeenCalledWith(400);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.name).toBe('Langfuse-Linked Snapshot');+ expect(response.instructionsPrompt).toEqual({ source: 'langfuse', restricted: true });+ const persisted = await Agent.findOne({ id: agentId }).lean();+ expect(persisted.instructionsPrompt).toEqual(link);+ });++ test('getAgentHandler EDIT branch presents a restricted stub for a Langfuse link the editor cannot VIEW', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ const link = { source: 'langfuse', groupId, selection: { type: 'production' } };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Restricted Langfuse Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: link,+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { id: agent.id };++ await getAgentHandler(mockReq, mockRes, true);++ expect(mockRes.status).toHaveBeenCalledWith(200);+ const response = mockRes.json.mock.calls[0][0];+ expect(response.instructionsPrompt).toEqual({ source: 'langfuse', restricted: true });+ });++ test('getAgentVersionsHandler redacts an inaccessible Langfuse link in a version snapshot', async () => {+ const groupId = new mongoose.Types.ObjectId().toString();+ const link = { source: 'langfuse', groupId, selection: { type: 'production' } };+ const agent = await Agent.create({+ id: `agent_${nanoid()}`,+ author: mockReq.user.id,+ name: 'Langfuse Version History Agent',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ versions: [+ {+ name: 'Old Linked Name',+ provider: 'openai',+ model: 'gpt-4',+ tools: [],+ instructionsPrompt: link,+ },+ ],+ });+ // No VIEW grant for `groupId`.++ mockReq.params = { id: agent.id };++ await getAgentVersionsHandler(mockReq, mockRes);++ expect(mockRes.status).toHaveBeenCalledWith(200);+ const versions = mockRes.json.mock.calls[0][0];+ expect(versions[0].instructionsPrompt).toEqual({+ source: 'langfuse',+ restricted: true,+ matchesCurrent: false,+ });+ });+ });});});diff --git a/api/server/routes/prompts.js b/api/server/routes/prompts.jsindex ca15c51421..8aef2a7e2a 100644--- a/api/server/routes/prompts.js+++ b/api/server/routes/prompts.js@@ -63,6 +63,12 @@ router.get(configMiddleware,handlers.resolvePrompt,);+router.get(+ '/groups/:groupId/revisions',+ promptResolveLimiter,+ canAccessPromptGroupResource({ requiredPermission: PermissionBits.VIEW }),+ handlers.listRevisions,+);router.get('/all', configMiddleware, handlers.listAllPromptGroups);router.get('/groups', configMiddleware, handlers.listPromptGroups);diff --git a/api/server/routes/prompts.test.js b/api/server/routes/prompts.test.jsindex 3ca14eb918..3e3cd9e152 100644--- a/api/server/routes/prompts.test.js+++ b/api/server/routes/prompts.test.js@@ -1711,6 +1711,121 @@ describe('GET /api/prompts/groups/:groupId/resolve', () => {});});+describe('GET /api/prompts/groups/:groupId/revisions', () => {+ afterEach(async () => {+ await Prompt.deleteMany({});+ await PromptGroup.deleteMany({});+ await AclEntry.deleteMany({});+ });++ it('lists native revisions newest first with the Production entry marked', async () => {+ const { group, prompt: production } = await createAccessiblePromptGroup({+ name: 'Revisions native group',+ prompt: 'Production text',+ });+ const draft = await Prompt.create({+ prompt: 'Draft text',+ author: testUsers.owner._id,+ type: 'text',+ groupId: group._id,+ });++ const response = await request(app)+ .get(`/api/prompts/groups/${group._id}/revisions`)+ .expect(200);++ expect(response.body).toEqual({+ source: 'native',+ groupId: group._id.toString(),+ revisions: [+ { source: 'native', promptId: draft._id.toString(), version: 2, isProduction: false },+ {+ source: 'native',+ promptId: production._id.toString(),+ version: 1,+ isProduction: true,+ },+ ],+ });+ });++ it('returns 403 without VIEW permission on the group', async () => {+ const { group } = await createAccessiblePromptGroup({+ name: 'Revisions forbidden group',+ prompt: 'Native text',+ });+ setTestUser(app, testUsers.noAccess);++ const response = await request(app)+ .get(`/api/prompts/groups/${group._id}/revisions`)+ .expect(403);++ expect(response.body.error).toBe('Forbidden');+ });++ it('returns 404 for a missing group', async () => {+ const response = await request(app)+ .get(`/api/prompts/groups/${new ObjectId()}/revisions`)+ .expect(404);++ expect(response.body).toEqual({+ error: 'Not Found',+ message: `${ResourceType.PROMPTGROUP} not found`,+ });+ });++ it('allows a user with only VIEW access, not just the owner', async () => {+ const { group } = await createAccessiblePromptGroup({+ name: 'Revisions viewer group',+ prompt: 'Native text',+ });+ await grantPermission({+ principalType: PrincipalType.USER,+ principalId: testUsers.viewer._id,+ resourceType: ResourceType.PROMPTGROUP,+ resourceId: group._id,+ accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,+ grantedBy: testUsers.owner._id,+ });+ setTestUser(app, testUsers.viewer);++ const response = await request(app)+ .get(`/api/prompts/groups/${group._id}/revisions`)+ .expect(200);++ expect(response.body.source).toBe('native');+ });++ it('returns 403 for a role without PROMPTS USE, before the group VIEW check', async () => {+ const { group } = await createAccessiblePromptGroup({+ name: 'Revisions no-PROMPTS-USE group',+ prompt: 'Native text',+ });+ // getRoleByName's mock returns null for any role besides USER/ADMIN, so this+ // role carries no PROMPTS.USE grant even though the user has group VIEW access.+ const noUseUser = await User.create({+ name: 'No Prompts Use',+ email: '[email protected]',+ role: 'NoPromptsUseRole',+ });+ await grantPermission({+ principalType: PrincipalType.USER,+ principalId: noUseUser._id,+ resourceType: ResourceType.PROMPTGROUP,+ resourceId: group._id,+ accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,+ grantedBy: testUsers.owner._id,+ });+ setTestUser(app, noUseUser);++ const response = await request(app)+ .get(`/api/prompts/groups/${group._id}/revisions`)+ .expect(403);++ expect(response.body).toEqual({ message: 'Forbidden: Insufficient permissions' });+ });+});+describe('Externally managed (Langfuse) prompt groups are read-only', () => {const readOnlyBody = { code: 'read_only', error: 'Externally managed prompts are read-only' };let group;diff --git a/client/src/components/Prompts/display/PromptSourceBadge.tsx b/client/src/components/Prompts/display/PromptSourceBadge.tsxnew file mode 100644index 0000000000..2b52da124c--- /dev/null+++ b/client/src/components/Prompts/display/PromptSourceBadge.tsx@@ -0,0 +1,37 @@+import { Cloud } from 'lucide-react';+import { TooltipAnchor } from '@librechat/client';+import type { TPromptGroupSource } from 'librechat-data-provider';+import { useLocalize } from '~/hooks';++/** Pass `interactive={false}` when nested in another interactive element. */+export default function PromptSourceBadge({+ source,+ interactive = true,+}: {+ source: TPromptGroupSource;+ interactive?: boolean;+}) {+ const localize = useLocalize();+ if (source !== 'langfuse') {+ return null;+ }+ const label = localize('com_ui_prompt_source_langfuse');+ if (!interactive) {+ return (+ <span role="img" aria-label={label} className="flex shrink-0 items-center">+ <Cloud className="text-text-secondary size-3.5" aria-hidden="true" />+ </span>+ );+ }+ return (+ <TooltipAnchor+ description={label}+ side="top"+ render={+ <span tabIndex={0} role="img" aria-label={label} className="flex shrink-0 items-center">+ <Cloud className="text-text-secondary size-3.5" aria-hidden="true" />+ </span>+ }+ />+ );+}diff --git a/client/src/components/Prompts/display/index.ts b/client/src/components/Prompts/display/index.tsindex 28cf2b23b3..b897d87713 100644--- a/client/src/components/Prompts/display/index.ts+++ b/client/src/components/Prompts/display/index.ts@@ -7,3 +7,4 @@ export { default as PromptVariables } from './PromptVariables';export { default as PromptDetailHeader } from './PromptDetailHeader';export { default as LangfusePromptMeta } from './LangfusePromptMeta';export { default as PromptResolvedBody } from './PromptResolvedBody';+export { default as PromptSourceBadge } from './PromptSourceBadge';diff --git a/client/src/components/Prompts/lists/ChatGroupItem.tsx b/client/src/components/Prompts/lists/ChatGroupItem.tsxindex 0a3349d1c6..a6f8a9506b 100644--- a/client/src/components/Prompts/lists/ChatGroupItem.tsx+++ b/client/src/components/Prompts/lists/ChatGroupItem.tsx@@ -1,7 +1,7 @@import { useState, memo, useRef, useCallback, useId, useMemo } from 'react';import * as Ariakit from '@ariakit/react';import { useNavigate, useParams } from 'react-router-dom';-import { Ellipsis, Eye, SquarePen, Trash, EarthIcon, Cloud, User } from 'lucide-react';+import { Ellipsis, Eye, SquarePen, Trash, EarthIcon, User } from 'lucide-react';import {Label,Button,@@ -26,6 +26,7 @@ import { useLocalize, useAuthContext, useSubmitMessage, usePromptContentResolverimport { useRecordPromptUsage, useDeletePromptGroup } from '~/data-provider';import useChatScopedRequest from '~/hooks/Prompts/useChatScopedRequest';import { useLiveAnnouncer, useChatContext } from '~/Providers';+import PromptSourceBadge from '../display/PromptSourceBadge';import VariableDialog from '../dialogs/VariableDialog';import PreviewPrompt from '../dialogs/PreviewPrompt';import CategoryIcon from '../utils/CategoryIcon';@@ -274,22 +275,7 @@ function ChatGroupItem({}/>)}- {isExternal && (- <TooltipAnchor- description={localize('com_ui_prompt_source_langfuse')}- side="top"- render={- <span- tabIndex={0}- role="img"- aria-label={localize('com_ui_prompt_source_langfuse')}- className="flex shrink-0 items-center"- >- <Cloud className="text-text-secondary size-3.5" aria-hidden="true" />- </span>- }- />- )}+ <PromptSourceBadge source={group.source} />{/* The menu shares the title's line, so only the title gives way to it.The snippet below keeps the full width of the row either way. */}<divdiff --git a/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsx b/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsxindex cb2c66d226..50f0e126c7 100644--- a/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsx+++ b/client/src/components/SidePanel/Agents/InstructionsPromptFields.tsx@@ -1,31 +1,68 @@import { useMemo } from 'react';import { Controller, useFormContext } from 'react-hook-form';import { Button, Label, ControlCombobox } from '@librechat/client';-import type { AgentInstructionsPromptSelection } from 'librechat-data-provider';+import type {+ PromptSelection,+ TPromptGroupSource,+ LangfuseAgentInstructionsPromptSelection,+} from 'librechat-data-provider';import type { ReactNode } from 'react';+import type { TranslationKeys } from '~/hooks';import type { AgentForm } from '~/common';import {buildPromptVersionOptions,isRestrictedInstructionsPrompt,+ getRevisionsLoadErrorKey,+ isLangfuseSelection,+ selectionValue,getHttpStatus,} from './instructionsPromptUtils';-import { useGetAllPromptGroups, useGetPrompts } from '~/data-provider';+import { useGetAllPromptGroups, useGetPromptGroupRevisions } from '~/data-provider';+import { useAgentPanelContext } from '~/Providers/AgentPanelContext';+import { PromptSourceBadge } from '~/components/Prompts/display';import { useLocalize } from '~/hooks';export const fieldWrapperClass ='flex h-9 items-center rounded-lg border border-border-light bg-surface-secondary px-3 text-sm text-text-secondary';-export function LoadError({ forbidden, onRetry }: { forbidden: boolean; onRetry: () => void }) {+export function LoadError({+ forbidden,+ messageKey,+ onRetry,+ retrying,+}: {+ forbidden?: boolean;+ /** Overrides the forbidden/generic choice below with a specific copy key. */+ messageKey?: TranslationKeys;+ onRetry: () => void;+ retrying?: boolean;+}) {const localize = useLocalize();+ const resolvedKey: TranslationKeys =+ messageKey ??+ (forbidden+ ? 'com_agents_instructions_prompt_forbidden'+ : 'com_agents_instructions_prompt_load_error');+ // Retrying a permission failure cannot succeed.+ const showRetry = resolvedKey !== 'com_agents_instructions_prompt_forbidden';return (<div className="border-border-light bg-surface-secondary text-text-secondary flex flex-col gap-1.5 rounded-lg border px-3 py-2 text-sm">- <span role="alert">- {forbidden- ? localize('com_agents_instructions_prompt_forbidden')- : localize('com_agents_instructions_prompt_load_error')}- </span>- {!forbidden && (- <Button type="button" variant="outline" size="sm" className="w-fit" onClick={onRetry}>+ <span role="alert">{localize(resolvedKey)}</span>+ {showRetry && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="w-fit"+ onClick={() => {+ // aria-disabled, not disabled: keeps focus on the button while a retry is in flight.+ if (retrying) {+ return;+ }+ onRetry();+ }}+ aria-disabled={retrying}+ >{localize('com_ui_retry')}</Button>)}@@ -33,26 +70,44 @@ export function LoadError({ forbidden, onRetry }: { forbidden: boolean; onRetry:);}+/** Labels a disabled Langfuse link's saved selection without fetching revisions. */+function formatDisabledVersionLabel(+ selection: LangfuseAgentInstructionsPromptSelection | undefined,+ localize: (key: TranslationKeys, vars?: Record<string, unknown>) => string,+): string {+ if (selection == null || selection.type === 'production') {+ return localize('com_ui_production');+ }+ return localize('com_ui_version_var', { 0: String(selection.version) });+}+function VersionSelect({groupId,- productionId,+ source,selection,onSelect,+ disabled,}: {groupId: string;- productionId?: string | null;- selection?: AgentInstructionsPromptSelection;- onSelect: (selection: AgentInstructionsPromptSelection) => void;+ source?: TPromptGroupSource;+ selection?: PromptSelection;+ onSelect: (selection: PromptSelection) => void;+ /** True for a saved Langfuse link while the switch is off. */+ disabled?: boolean;}) {const localize = useLocalize();- const promptsQuery = useGetPrompts({ groupId }, { enabled: groupId !== '' });- const promptsData = promptsQuery.data;- const prompts = useMemo(() => (Array.isArray(promptsData) ? promptsData : []), [promptsData]);+ const revisionsQuery = useGetPromptGroupRevisions(groupId, {+ enabled: groupId !== '' && !disabled,+ });+ const revisionsData = revisionsQuery.data;const options = useMemo(- () => buildPromptVersionOptions(prompts, productionId, localize),- [prompts, productionId, localize],+ () =>+ revisionsData != null && Array.isArray(revisionsData.revisions)+ ? buildPromptVersionOptions(revisionsData, selection, localize)+ : [],+ [revisionsData, selection, localize],);- const selectedValue = selection?.type === 'exact' ? selection.promptId : 'production';+ const selectedValue = selectionValue(source, selection);const selectedOption = options.find((option) => option.value === selectedValue);let content: ReactNode;@@ -62,16 +117,30 @@ function VersionSelect({{localize('com_agents_instructions_prompt_version_placeholder')}</div>);- } else if (promptsQuery.isLoading) {+ } else if (disabled) {+ // `disabled` implies a Langfuse link, so the selection is always the Langfuse shape.+ const langfuseSelection = isLangfuseSelection(selection) ? selection : undefined;+ content = (+ <div className={fieldWrapperClass}>+ {formatDisabledVersionLabel(langfuseSelection, localize)}+ </div>+ );+ } else if (revisionsQuery.isLoading) {content = <div className={fieldWrapperClass}>{localize('com_ui_loading')}</div>;- } else if (promptsQuery.isError || !Array.isArray(promptsQuery.data)) {+ } else if (+ revisionsQuery.isError ||+ revisionsData == null ||+ !Array.isArray(revisionsData.revisions)+ ) {+ // A malformed 200 (missing `revisions`) is treated as a load failure, not an empty list.content = (<LoadError- forbidden={getHttpStatus(promptsQuery.error) === 403}- onRetry={() => promptsQuery.refetch()}+ messageKey={getRevisionsLoadErrorKey(revisionsQuery.error)}+ onRetry={() => revisionsQuery.refetch()}+ retrying={revisionsQuery.isFetching}/>);- } else if (prompts.length === 0) {+ } else if (revisionsData.revisions.length === 0) {content = (<div className={fieldWrapperClass}>{localize('com_agents_instructions_prompt_empty')}</div>);@@ -102,8 +171,7 @@ function VersionSelect({<Label id="instructions-prompt-version-label" variant="section" className="mb-1 block">{localize('com_agents_instructions_prompt_version_label')}</Label>- {/* `aria-labelledby`, not `htmlFor`, because the loading/error/empty states- * render a plain `div`, not the combobox `id` a `for` would need to target. */}+ {/* `aria-labelledby`, not `htmlFor`: no state here renders a labelable control. */}<div role="group" aria-labelledby="instructions-prompt-version-label">{content}</div>@@ -111,18 +179,13 @@ function VersionSelect({);}-/**- * Prompt + Version dropdown row shown in "Prompt" instructions mode. Reads and- * writes the whole `instructionsPrompt` link through a single Controller, since- * the two dropdowns jointly determine one value.- */export default function InstructionsPromptFields() {const localize = useLocalize();- const { control } = useFormContext<AgentForm>();+ const { control, formState } = useFormContext<AgentForm>();+ const { agentsConfig } = useAgentPanelContext();+ const langfuseEnabled = agentsConfig?.linkedInstructions?.langfuse?.enabled === true;const groupsQuery = useGetAllPromptGroups();- /** The endpoint can answer a 200 with `{ message }` instead of an array (for example, on- * a permission failure that does not reach `isError`); treat that the same as a load- * failure rather than an empty prompt library. */+ // A 200 with `{ message }` instead of an array is a load failure, not an empty library.const groupsData = groupsQuery.data;const groupsFailed = groupsQuery.isError || !Array.isArray(groupsData);const groups = Array.isArray(groupsData) ? groupsData : [];@@ -147,11 +210,22 @@ export default function InstructionsPromptFields() {field.value != null && !isRestrictedInstructionsPrompt(field.value) ? field.value : null;const groupId = link?.groupId ?? '';const selectedGroup = groups.find((group) => group._id === groupId);- /** A link that survived loading but matches no listed group: the group was- * deleted, or the editor's share access to it was revoked. */+ // Falls back to the link's own source when the group is missing from the listing.+ const linkSource: TPromptGroupSource | undefined = selectedGroup?.source ?? link?.source;const linkedGroupMissing = groupId !== '' && !groupsFailed && selectedGroup == null;- /** The stub carries no `groupId`, so the dropdown's current value comes from- * this label, never from a group name: nothing here reads identity off it. */+ const isDisabledLangfuseLink = !langfuseEnabled && linkSource === 'langfuse';+ // Keyed off the saved link, not the live form value: the live groupId moves to the+ // newly picked group as soon as the user changes it, which would otherwise drop the+ // saved Langfuse group from the list on the very selection meant to keep it visible.+ const savedInstructionsPrompt = formState.defaultValues?.instructionsPrompt;+ const savedGroupId =+ savedInstructionsPrompt != null && 'groupId' in savedInstructionsPrompt+ ? savedInstructionsPrompt.groupId+ : undefined;+ const visibleGroups = langfuseEnabled+ ? groups+ : groups.filter((group) => group.source !== 'langfuse' || group._id === savedGroupId);+ // A restricted stub has no `groupId`, so the display value comes from this label.const groupDisplayValue = isRestrictedInstructionsPrompt(field.value)? localize('com_agents_instructions_prompt_restricted_title'): (selectedGroup?.name ?? '');@@ -161,11 +235,20 @@ export default function InstructionsPromptFields() {field.onChange(null);return;}- field.onChange({- source: 'native',- groupId: nextGroupId,- selection: { type: 'production' },- });+ // Keeps the saved selection: the server rejects a write that changes a pinned link.+ if (link != null && nextGroupId === link.groupId) {+ return;+ }+ const nextGroup = groups.find((group) => group._id === nextGroupId);+ const nextSource: TPromptGroupSource | undefined = nextGroup?.source ?? link?.source;+ if (nextSource == null) {+ return;+ }+ field.onChange(+ nextSource === 'langfuse'+ ? { source: 'langfuse', groupId: nextGroupId, selection: { type: 'production' } }+ : { source: 'native', groupId: nextGroupId, selection: { type: 'production' } },+ );};let groupField: ReactNode;@@ -178,17 +261,14 @@ export default function InstructionsPromptFields() {onRetry={() => groupsQuery.refetch()}/>);- } else if (groups.length === 0) {+ } else if (visibleGroups.length === 0) {groupField = (<div className={fieldWrapperClass}>{localize('com_agents_instructions_prompt_empty')}</div>);} else {- /** A missing link still gets the combobox, not just the hint below it: the- * backend allows removing or replacing a link to a deleted group, so the user- * needs a way to pick a replacement (or switch to Inline) rather than being- * stuck with prose and no control. */+ // A missing link still gets the combobox, so the user can pick a replacement.groupField = (<ControlComboboxselectId="instructions-prompt-group"@@ -197,7 +277,18 @@ export default function InstructionsPromptFields() {selectPlaceholder={localize('com_agents_instructions_prompt_select_placeholder')}searchPlaceholder={localize('com_agents_instructions_prompt_search_placeholder')}setValue={handleGroupChange}- items={groups.map((group) => ({ label: group.name, value: group._id ?? '' }))}+ items={visibleGroups.map((group) => ({+ label: group.name,+ value: group._id ?? '',+ // Non-interactive: nests inside the already-interactive `SelectItem`.+ icon: <PromptSourceBadge source={group.source} interactive={false} />,+ }))}+ SelectIcon={+ selectedGroup?.source === 'langfuse' ? (+ <PromptSourceBadge source="langfuse" interactive={false} />+ ) : undefined+ }+ iconSide="right"ariaLabel={localize('com_ui_prompt')}isCollapsed={false}showCarat={true}@@ -212,8 +303,7 @@ export default function InstructionsPromptFields() {<Label id="instructions-prompt-group-label" variant="section" className="mb-1 block">{localize('com_ui_prompt')}</Label>- {/* `aria-labelledby`, not `htmlFor`: the loading/error/empty- * states render a plain `div`, not the combobox `id` a `for` would need. */}+ {/* `aria-labelledby`, not `htmlFor`: no state here renders a labelable control. */}<div role="group" aria-labelledby="instructions-prompt-group-label">{groupField}</div>@@ -225,6 +315,14 @@ export default function InstructionsPromptFields() {{localize('com_agents_instructions_prompt_not_found')}</span>)}+ {isDisabledLangfuseLink && (+ <span+ className="text-text-secondary mt-1 text-xs transition duration-300 ease-in-out"+ role="note"+ >+ {localize('com_agents_instructions_prompt_source_disabled')}+ </span>+ )}{error && (<spanclassName="text-text-destructive mt-1 text-xs transition duration-300 ease-in-out"@@ -236,13 +334,25 @@ export default function InstructionsPromptFields() {</div><VersionSelectgroupId={groupId}- productionId={selectedGroup?.productionId}+ source={linkSource}selection={link?.selection}+ disabled={isDisabledLangfuseLink}onSelect={(selection) => {if (groupId === '') {return;}- field.onChange({ source: 'native', groupId, selection });+ // The two `exact` shapes share a `type` literal but differ by field.+ if (linkSource === 'langfuse') {+ if ('promptId' in selection) {+ return;+ }+ field.onChange({ source: 'langfuse', groupId, selection });+ } else if (linkSource === 'native') {+ if ('version' in selection) {+ return;+ }+ field.onChange({ source: 'native', groupId, selection });+ }}}/></div>diff --git a/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.ts b/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.tsindex 1531c9205e..a30eb45b7d 100644--- a/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.ts+++ b/client/src/components/SidePanel/Agents/Version/__tests__/isActiveVersion.spec.ts@@ -375,6 +375,48 @@ describe('isActiveVersion', () => {expect(isActiveVersion(version, currentAgent, versions)).toBe(false);});+ test('a Langfuse link with a pinned version matches an identical Langfuse link', () => {+ const langfuseLink = {+ source: 'langfuse',+ groupId: 'group-a',+ selection: { type: 'exact', version: 3 },+ };+ const version = createVersion({ instructionsPrompt: { ...langfuseLink } });+ const currentAgent = createAgentState({ instructionsPrompt: { ...langfuseLink } });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(true);+ });++ test('a Langfuse link does not match a native link with the same groupId and selection shape', () => {+ const version = createVersion({+ instructionsPrompt: {+ source: 'langfuse',+ groupId: 'group-a',+ selection: { type: 'production' },+ },+ });+ const currentAgent = createAgentState({+ instructionsPrompt: { ...visibleLink },+ });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(false);+ });++ test('a restricted stub carrying source "langfuse" matches an equally restricted current link', () => {+ const restrictedLangfuseStub = { source: 'langfuse', restricted: true };+ const version = createVersion({+ instructionsPrompt: { ...restrictedLangfuseStub, matchesCurrent: true },+ });+ const currentAgent = createAgentState({+ instructionsPrompt: { ...restrictedLangfuseStub },+ });+ const versions = [version];++ expect(isActiveVersion(version, currentAgent, versions)).toBe(true);+ });+test('with currentAgent null, restricted stubs never match each other, even index 0 against itself', () => {// There is no currentAgent here to resolve `matchesCurrent` against, so comparing// one version's restricted stub to another's must not trust either side's flag —diff --git a/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsxindex 04c45d2540..76d643083b 100644--- a/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/InstructionsPromptFields.spec.tsx@@ -1,7 +1,7 @@import React from 'react';import { useForm, FormProvider } from 'react-hook-form';import { render, screen, fireEvent, act } from '@testing-library/react';-import type { TPromptGroup, TPrompt } from 'librechat-data-provider';+import type { TPromptGroup, TPromptRevisionChoicesResponse } from 'librechat-data-provider';import type { UseFormReturn } from 'react-hook-form';import type { AgentForm } from '~/common';import InstructionsPromptFields from '../InstructionsPromptFields';@@ -13,17 +13,31 @@ let mockGroupsQuery: {error?: unknown;refetch: jest.Mock;};-let mockPromptsQuery: {+let mockRevisionsQuery: {data?: unknown;isLoading: boolean;isError: boolean;+ isFetching: boolean;error?: unknown;refetch: jest.Mock;};+let mockLangfuseEnabled: boolean;++// Lets a test read the `enabled` option passed to the mocked hook.+const mockUseGetPromptGroupRevisions = jest.fn(+ (_id: string, _options: { enabled?: boolean }) => mockRevisionsQuery,+);jest.mock('~/data-provider', () => ({useGetAllPromptGroups: () => mockGroupsQuery,- useGetPrompts: () => mockPromptsQuery,+ useGetPromptGroupRevisions: (id: string, options: { enabled?: boolean }) =>+ mockUseGetPromptGroupRevisions(id, options),+}));++jest.mock('~/Providers/AgentPanelContext', () => ({+ useAgentPanelContext: () => ({+ agentsConfig: { linkedInstructions: { langfuse: { enabled: mockLangfuseEnabled } } },+ }),}));jest.mock('~/hooks', () => ({@@ -43,6 +57,7 @@ jest.mock('@librechat/client', () => ({Label: ({ children, ...props }: React.ComponentProps<'label'>) => (<label {...props}>{children}</label>),+ TooltipAnchor: ({ render: content }: { render: React.ReactNode }) => content,ControlCombobox: ({ariaLabel,selectId,@@ -50,13 +65,17 @@ jest.mock('@librechat/client', () => ({selectedValue,displayValue,setValue,+ SelectIcon,+ iconSide = 'left',}: {ariaLabel: string;selectId?: string;- items: Array<{ value: string; label: string }>;+ items: Array<{ value: string; label: string; icon?: React.ReactNode }>;selectedValue: string;displayValue?: string;setValue: (value: string) => void;+ SelectIcon?: React.ReactNode;+ iconSide?: 'left' | 'right';}) => (<div>{/* Mirrors the real combobox's current-value text for the Prompt dropdown only,@@ -66,18 +85,35 @@ jest.mock('@librechat/client', () => ({{selectId === 'instructions-prompt-group' && (<span data-testid={`${selectId}-display-value`}>{displayValue}</span>)}+ {selectId === 'instructions-prompt-group' && SelectIcon != null && (+ <span data-testid={`${selectId}-select-icon`}>{SelectIcon}</span>+ )}<selectaria-label={ariaLabel}id={selectId}value={selectedValue}onChange={(event) => setValue(event.target.value)}>- {items.map((item) => (- <option key={item.value} value={item.value}>- {item.label}- </option>- ))}+ {items.map((item) => {+ // Mirrors the real option's label/badge DOM order, which `iconSide` controls,+ // so a test can read the accessible name to confirm which side the badge is on.+ const badgeMarker =+ selectId === 'instructions-prompt-group' && item.icon != null ? '○langfuse' : '';+ const optionLabel =+ iconSide === 'right' ? `${item.label}${badgeMarker}` : `${badgeMarker}${item.label}`;+ return (+ <option key={item.value} value={item.value}>+ {optionLabel}+ </option>+ );+ })}</select>+ {selectId === 'instructions-prompt-group' &&+ items.map((item) => (+ <span key={`icon-${item.value}`} data-testid={`item-icon-${item.value}`}>+ {item.icon}+ </span>+ ))}</div>),}));@@ -91,14 +127,23 @@ const group = (overrides: Partial<TPromptGroup> = {}): TPromptGroup => ({...overrides,});-const prompt = (overrides: Partial<TPrompt> = {}): TPrompt => ({+const nativeRevisions = (+ revisions: Array<{ promptId: string; version: number; isProduction?: boolean }>,+): TPromptRevisionChoicesResponse => ({+ source: 'native',groupId: 'group1',- author: 'user1',- prompt: 'text',- type: 'text',- createdAt: '',- updatedAt: '',- ...overrides,+ revisions: revisions.map((revision) => ({+ source: 'native' as const,+ promptId: revision.promptId,+ version: revision.version,+ isProduction: revision.isProduction ?? false,+ })),+});++const langfuseRevisions = (versions: number[]): TPromptRevisionChoicesResponse => ({+ source: 'langfuse',+ groupId: 'group2',+ revisions: versions.map((version) => ({ source: 'langfuse' as const, version })),});function Harness({@@ -125,6 +170,7 @@ function Harness({}beforeEach(() => {+ mockLangfuseEnabled = false;mockGroupsQuery = {data: [],isLoading: false,@@ -132,13 +178,15 @@ beforeEach(() => {error: undefined,refetch: jest.fn(),};- mockPromptsQuery = {- data: [],+ mockRevisionsQuery = {+ data: undefined,isLoading: false,isError: false,+ isFetching: false,error: undefined,refetch: jest.fn(),};+ mockUseGetPromptGroupRevisions.mockClear();});describe('InstructionsPromptFields', () => {@@ -175,7 +223,7 @@ describe('InstructionsPromptFields', () => {expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();});- it('selecting a prompt group defaults the selection to Production', () => {+ it('selecting a native prompt group defaults the selection to Production and writes source "native"', () => {mockGroupsQuery.data = [group()];let methods: UseFormReturn<AgentForm> | undefined;render(<Harness onMethods={(m) => (methods = m)} />);@@ -191,58 +239,495 @@ describe('InstructionsPromptFields', () => {});});- it('lists Production first, then versions newest to oldest', () => {- mockGroupsQuery.data = [group({ productionId: 'p2' })];- mockPromptsQuery.data = [prompt({ _id: 'p3' }), prompt({ _id: 'p2' }), prompt({ _id: 'p1' })];+ it('selecting a Langfuse prompt group defaults the selection to Production and writes source "langfuse"', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse', name: 'Langfuse group' })];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(<Harness onMethods={(m) => (methods = m)} />);++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group2' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ });+ });++ it('resets a native exact selection to Production when switching to a Langfuse group', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [+ group(),+ group({ _id: 'group2', source: 'langfuse', name: 'Langfuse group' }),+ ];+ let methods: UseFormReturn<AgentForm> | undefined;render(<HarnessdefaultInstructionsPrompt={{source: 'native',groupId: 'group1',- selection: { type: 'production' },+ selection: { type: 'exact', promptId: 'p1' },}}+ onMethods={(m) => (methods = m)}/>,);- const versionSelect = screen.getByRole('combobox', {- name: 'com_agents_instructions_prompt_version_label',+ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group2' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },});- const optionValues = Array.from(versionSelect.querySelectorAll('option')).map(- (option) => (option as HTMLOptionElement).value,- );- expect(optionValues).toEqual(['production', 'p3', 'p2', 'p1']);- expect(- screen.getByText('com_agents_instructions_prompt_production_version:{"0":"2"}'),- ).toBeInTheDocument();});- it('selecting a version produces an exact selection', () => {- mockGroupsQuery.data = [group()];- mockPromptsQuery.data = [prompt({ _id: 'p2' }), prompt({ _id: 'p1' })];+ it('resets a Langfuse exact selection to Production when switching to a native group', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [+ group(),+ group({ _id: 'group2', source: 'langfuse', name: 'Langfuse group' }),+ ];let methods: UseFormReturn<AgentForm> | undefined;render(<HarnessdefaultInstructionsPrompt={{- source: 'native',- groupId: 'group1',- selection: { type: 'production' },+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 3 },}}onMethods={(m) => (methods = m)}/>,);- fireEvent.change(- screen.getByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),- { target: { value: 'p1' } },- );+ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group1' },+ });expect(methods?.getValues('instructionsPrompt')).toEqual({source: 'native',groupId: 'group1',- selection: { type: 'exact', promptId: 'p1' },+ selection: { type: 'production' },+ });+ });++ it('shows a cloud badge icon for a Langfuse group and none for a native group', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group(), group({ _id: 'group2', source: 'langfuse' })];+ render(<Harness />);++ expect(screen.getByTestId('item-icon-group1')).toBeEmptyDOMElement();+ expect(+ screen.getByTestId('item-icon-group2').querySelector('[role="img"]'),+ ).toBeInTheDocument();+ });++ it('renders the combobox option badge with no tabindex, since it sits inside an already-interactive option', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ render(<Harness />);++ const badge = screen.getByTestId('item-icon-group2').querySelector('[role="img"]');+ expect(badge).not.toHaveAttribute('tabindex');+ });++ it('passes a SelectIcon for a selected Langfuse group', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ />,+ );++ const selectIconBadge = screen+ .getByTestId('instructions-prompt-group-select-icon')+ .querySelector('[role="img"]');+ expect(selectIconBadge).toBeInTheDocument();+ expect(selectIconBadge).not.toHaveAttribute('tabindex');+ });++ it("puts the Langfuse badge after the group name, so the option's accessible name starts with the group name", () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [+ group(),+ group({ _id: 'group2', source: 'langfuse', name: 'Langfuse group' }),+ ];+ render(<Harness />);++ const option = screen.getByRole('option', { name: /^Langfuse group/ });+ expect(option).toHaveValue('group2');+ });++ describe('the rollout switch', () => {+ it('hides a Langfuse group from the picker while the switch is off', () => {+ mockGroupsQuery.data = [group(), group({ _id: 'group2', source: 'langfuse' })];+ render(<Harness />);++ const options = Array.from(+ screen.getByRole('combobox', { name: 'com_ui_prompt' }).querySelectorAll('option'),+ ).map((option) => (option as HTMLOptionElement).value);+ expect(options).toEqual(['group1']);+ });++ it('shows the empty-state copy, not an enabled empty combobox, when every group is Langfuse and none is linked', () => {+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ render(<Harness />);++ expect(screen.getByText('com_agents_instructions_prompt_empty')).toBeInTheDocument();+ expect(screen.queryByRole('combobox', { name: 'com_ui_prompt' })).not.toBeInTheDocument();+ });++ it('still lists the currently saved Langfuse group while the switch is off', () => {+ mockGroupsQuery.data = [group(), group({ _id: 'group2', source: 'langfuse' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ />,+ );++ const options = Array.from(+ screen.getByRole('combobox', { name: 'com_ui_prompt' }).querySelectorAll('option'),+ ).map((option) => (option as HTMLOptionElement).value);+ expect(options).toEqual(['group1', 'group2']);+ });++ it('shows a disabled note next to the saved Langfuse link, keeping it and the picker usable', () => {+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse', name: 'Langfuse group' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 4 },+ }}+ />,+ );++ expect(screen.getByRole('note')).toHaveTextContent(+ 'com_agents_instructions_prompt_source_disabled',+ );+ expect(screen.getByRole('combobox', { name: 'com_ui_prompt' })).toBeInTheDocument();+ expect(screen.getByTestId('instructions-prompt-group-display-value')).toHaveTextContent(+ 'Langfuse group',+ );+ });++ it('still shows the disabled note and read-only version when the saved group is missing from the listing', () => {+ // No matching group, so the disabled state must read off the link's own `source`.+ mockGroupsQuery.data = [];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 4 },+ }}+ />,+ );++ const notes = screen.getAllByRole('note');+ expect(+ notes.some((note) => note.textContent === 'com_agents_instructions_prompt_source_disabled'),+ ).toBe(true);+ expect(screen.getByText('com_ui_version_var:{"0":"4"}')).toBeInTheDocument();+ expect(mockUseGetPromptGroupRevisions).toHaveBeenLastCalledWith(+ 'group2',+ expect.objectContaining({ enabled: false }),+ );+ });++ it('shows the saved version as plain text with no revisions request while disabled', () => {+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 4 },+ }}+ />,+ );++ expect(screen.getByText('com_ui_version_var:{"0":"4"}')).toBeInTheDocument();+ expect(+ screen.queryByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ ).not.toBeInTheDocument();+ expect(mockUseGetPromptGroupRevisions).toHaveBeenLastCalledWith(+ 'group2',+ expect.objectContaining({ enabled: false }),+ );+ });++ it('shows no disabled note and no restriction once the switch is on', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ mockRevisionsQuery.data = langfuseRevisions([4, 3]);+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 4 },+ }}+ />,+ );++ expect(+ screen.queryByText('com_agents_instructions_prompt_source_disabled'),+ ).not.toBeInTheDocument();+ expect(mockUseGetPromptGroupRevisions).toHaveBeenLastCalledWith(+ 'group2',+ expect.objectContaining({ enabled: true }),+ );+ expect(+ screen.getByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ ).toBeInTheDocument();+ });++ it('still allows switching a disabled Langfuse link to a native group', () => {+ mockGroupsQuery.data = [+ group(),+ group({ _id: 'group2', source: 'langfuse', name: 'Langfuse group' }),+ ];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group1' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ });+ // The saved Langfuse link stays listed even once it's no longer the current+ // selection: the "keep visible" check is keyed off the saved link, not the live value.+ const options = Array.from(+ screen.getByRole('combobox', { name: 'com_ui_prompt' }).querySelectorAll('option'),+ ).map((option) => (option as HTMLOptionElement).value);+ expect(options).toEqual(['group1', 'group2']);+ });++ it('still allows removing a disabled Langfuse link', () => {+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: '' },+ });++ expect(methods?.getValues('instructionsPrompt')).toBeNull();+ });++ it('keeps the saved selection when the same disabled Langfuse group is re-picked', () => {+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 4 },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_prompt' }), {+ target: { value: 'group2' },+ });++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 4 },+ });+ });+ });++ describe('native version options', () => {+ it('lists Production first, then versions newest to oldest', () => {+ mockGroupsQuery.data = [group()];+ mockRevisionsQuery.data = nativeRevisions([+ { promptId: 'p3', version: 3 },+ { promptId: 'p2', version: 2, isProduction: true },+ { promptId: 'p1', version: 1 },+ ]);+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ const versionSelect = screen.getByRole('combobox', {+ name: 'com_agents_instructions_prompt_version_label',+ });+ const optionValues = Array.from(versionSelect.querySelectorAll('option')).map(+ (option) => (option as HTMLOptionElement).value,+ );+ expect(optionValues).toEqual(['production', 'p3', 'p2', 'p1']);+ expect(+ screen.getByText('com_agents_instructions_prompt_production_version:{"0":"2"}'),+ ).toBeInTheDocument();+ });++ it('selecting a version produces an exact selection', () => {+ mockGroupsQuery.data = [group()];+ mockRevisionsQuery.data = nativeRevisions([+ { promptId: 'p2', version: 2 },+ { promptId: 'p1', version: 1 },+ ]);+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(+ screen.getByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ { target: { value: 'p1' } },+ );++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group1',+ selection: { type: 'exact', promptId: 'p1' },+ });+ });++ it('appends the saved version, labelled as missing, when it matches no listed revision', () => {+ mockGroupsQuery.data = [group()];+ mockRevisionsQuery.data = nativeRevisions([{ promptId: 'p1', version: 1 }]);+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'exact', promptId: 'deleted' },+ }}+ />,+ );++ expect(+ screen.getByText('com_agents_instructions_prompt_version_missing'),+ ).toBeInTheDocument();+ });+ });++ describe('Langfuse version options', () => {+ it('lists Production first with a plain label, then pinned versions newest to oldest', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ mockRevisionsQuery.data = langfuseRevisions([3, 2, 1]);+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ />,+ );++ const versionSelect = screen.getByRole('combobox', {+ name: 'com_agents_instructions_prompt_version_label',+ });+ const optionValues = Array.from(versionSelect.querySelectorAll('option')).map(+ (option) => (option as HTMLOptionElement).value,+ );+ expect(optionValues).toEqual(['production', 'v3', 'v2', 'v1']);+ expect(screen.getByText('com_ui_production')).toBeInTheDocument();+ });++ it('selecting a pinned version produces a Langfuse version selection', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ mockRevisionsQuery.data = langfuseRevisions([3, 2, 1]);+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ fireEvent.change(+ screen.getByRole('combobox', { name: 'com_agents_instructions_prompt_version_label' }),+ { target: { value: 'v2' } },+ );++ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'exact', version: 2 },+ });});});+ it('shows a loading state for the Version dropdown while revisions are loading', () => {+ mockGroupsQuery.data = [group()];+ mockRevisionsQuery.isLoading = true;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(+ screen.getByRole('group', { name: 'com_agents_instructions_prompt_version_label' }),+ ).toHaveTextContent('com_ui_loading');+ });+it('disables the Version dropdown until a prompt group is selected', () => {mockGroupsQuery.data = [group()];render(<Harness />);@@ -254,8 +739,8 @@ describe('InstructionsPromptFields', () => {it('surfaces a 403 for the Version dropdown separately from the Prompt dropdown', () => {mockGroupsQuery.data = [group()];- mockPromptsQuery.isError = true;- mockPromptsQuery.error = { isAxiosError: true, response: { status: 403, data: {} } };+ mockRevisionsQuery.isError = true;+ mockRevisionsQuery.error = { isAxiosError: true, response: { status: 403, data: {} } };render(<HarnessdefaultInstructionsPrompt={{@@ -267,11 +752,82 @@ describe('InstructionsPromptFields', () => {);expect(screen.getByText('com_agents_instructions_prompt_forbidden')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'com_ui_retry' })).not.toBeInTheDocument();+ });++ it('keeps the saved selection and shows Retry on a revisions load error', () => {+ mockGroupsQuery.data = [group()];+ mockRevisionsQuery.isError = true;+ mockRevisionsQuery.error = new Error('network down');+ let methods: UseFormReturn<AgentForm> | undefined;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'exact', promptId: 'p1' },+ }}+ onMethods={(m) => (methods = m)}+ />,+ );++ expect(screen.getByText('com_agents_instructions_prompt_load_error')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));+ expect(mockRevisionsQuery.refetch).toHaveBeenCalledTimes(1);+ expect(methods?.getValues('instructionsPrompt')).toEqual({+ source: 'native',+ groupId: 'group1',+ selection: { type: 'exact', promptId: 'p1' },+ });+ });++ it('marks Retry aria-disabled while a revisions retry is already in flight, so a repeated click does nothing', () => {+ mockGroupsQuery.data = [group()];+ mockRevisionsQuery.isError = true;+ mockRevisionsQuery.error = new Error('network down');+ mockRevisionsQuery.isFetching = true;+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'native',+ groupId: 'group1',+ selection: { type: 'exact', promptId: 'p1' },+ }}+ />,+ );++ const retryButton = screen.getByRole('button', { name: 'com_ui_retry' });+ expect(retryButton).toHaveAttribute('aria-disabled', 'true');+ fireEvent.click(retryButton);+ expect(mockRevisionsQuery.refetch).not.toHaveBeenCalled();+ });++ it('shows the source-unavailable copy for a Langfuse chat-prompt rejection (422)', () => {+ mockLangfuseEnabled = true;+ mockGroupsQuery.data = [group({ _id: 'group2', source: 'langfuse' })];+ mockRevisionsQuery.isError = true;+ mockRevisionsQuery.error = {+ isAxiosError: true,+ response: { status: 422, data: { code: 'unsupported_type' } },+ };+ render(+ <Harness+ defaultInstructionsPrompt={{+ source: 'langfuse',+ groupId: 'group2',+ selection: { type: 'production' },+ }}+ />,+ );++ expect(+ screen.getByText('com_agents_instructions_prompt_source_unavailable'),+ ).toBeInTheDocument();});- it('guards a 200 {message} version response as a load failure, not a crash', () => {+ it('guards a malformed 200 revisions response as a load failure, not a crash', () => {mockGroupsQuery.data = [group()];- mockPromptsQuery.data = { message: 'not allowed' };+ mockRevisionsQuery.data = { message: 'not allowed' };render(<HarnessdefaultInstructionsPrompt={{@@ -451,7 +1007,10 @@ describe('InstructionsPromptFields', () => {it('keeps the Version dropdown usable for switching away from the missing group', () => {mockGroupsQuery.data = [group({ _id: 'group_other', name: 'Other prompt' })];- mockPromptsQuery.data = [prompt({ _id: 'p2' }), prompt({ _id: 'p1' })];+ mockRevisionsQuery.data = nativeRevisions([+ { promptId: 'p2', version: 2 },+ { promptId: 'p1', version: 1 },+ ]);render(<HarnessdefaultInstructionsPrompt={{@@ -560,7 +1119,7 @@ describe('InstructionsPromptFields', () => {it('names the Version field before and after a group is selected', async () => {mockGroupsQuery.data = [group()];- mockPromptsQuery.data = [prompt()];+ mockRevisionsQuery.data = nativeRevisions([{ promptId: 'p1', version: 1 }]);let methods: UseFormReturn<AgentForm> | undefined;render(<Harness onMethods={(m) => (methods = m)} />);diff --git a/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.ts b/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.tsindex 151b679d21..d7bae3458d 100644--- a/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.ts+++ b/client/src/components/SidePanel/Agents/__tests__/instructionsPromptUtils.spec.ts@@ -1,11 +1,13 @@/*** @jest-environment jsdom*/-import type { TPrompt } from 'librechat-data-provider';+import type { TPromptRevisionChoicesResponse } from 'librechat-data-provider';import {isRestrictedInstructionsPrompt,buildPromptVersionOptions,getInstructionsPromptErrorCode,+ getRevisionsLoadErrorKey,+ selectionValue,getHttpStatus,} from '../instructionsPromptUtils';@@ -38,70 +40,170 @@ describe('isRestrictedInstructionsPrompt', () => {});});+describe('selectionValue', () => {+ it('returns "production" for an undefined selection', () => {+ expect(selectionValue(undefined, undefined)).toBe('production');+ });++ it('returns "production" for a production selection', () => {+ expect(selectionValue('native', { type: 'production' })).toBe('production');+ });++ it('returns the prompt id for a native exact selection', () => {+ expect(selectionValue('native', { type: 'exact', promptId: 'p1' })).toBe('p1');+ });++ it('returns "v<version>" for a Langfuse exact selection', () => {+ expect(selectionValue('langfuse', { type: 'exact', version: 3 })).toBe('v3');+ });+});+describe('buildPromptVersionOptions', () => {- const prompts: TPrompt[] = [- {- _id: 'p3',- groupId: 'g1',- author: 'a',- prompt: 'newest',- type: 'text',- createdAt: '',- updatedAt: '',- },- {- _id: 'p2',- groupId: 'g1',- author: 'a',- prompt: 'middle',- type: 'text',- createdAt: '',- updatedAt: '',- },- {- _id: 'p1',- groupId: 'g1',- author: 'a',- prompt: 'oldest',- type: 'text',- createdAt: '',- updatedAt: '',- },- ];-- it('lists Production first, then versions newest to oldest', () => {- const options = buildPromptVersionOptions(prompts, undefined, localize);-- expect(options.map((option) => option.value)).toEqual(['production', 'p3', 'p2', 'p1']);- expect(options[0].selection).toEqual({ type: 'production' });- expect(options[1]).toEqual({- value: 'p3',- label: 'com_ui_version_var:{"0":"3"}',- selection: { type: 'exact', promptId: 'p3' },+ const nativeData = (+ revisions: TPromptRevisionChoicesResponse['revisions'],+ ): TPromptRevisionChoicesResponse => ({+ source: 'native',+ groupId: 'g1',+ revisions,+ });++ const langfuseData = (+ revisions: TPromptRevisionChoicesResponse['revisions'],+ ): TPromptRevisionChoicesResponse => ({+ source: 'langfuse',+ groupId: 'g1',+ revisions,+ });++ describe('native', () => {+ const revisions: TPromptRevisionChoicesResponse['revisions'] = [+ { source: 'native', promptId: 'p3', version: 3, isProduction: false },+ { source: 'native', promptId: 'p2', version: 2, isProduction: true },+ { source: 'native', promptId: 'p1', version: 1, isProduction: false },+ ];++ it('lists Production first, then versions newest to oldest', () => {+ const options = buildPromptVersionOptions(nativeData(revisions), undefined, localize);++ expect(options.map((option) => option.value)).toEqual(['production', 'p3', 'p2', 'p1']);+ expect(options[0].selection).toEqual({ type: 'production' });+ expect(options[1]).toEqual({+ value: 'p3',+ label: 'com_ui_version_var:{"0":"3"}',+ selection: { type: 'exact', promptId: 'p3' },+ });+ expect(options[3]).toEqual({+ value: 'p1',+ label: 'com_ui_version_var:{"0":"1"}',+ selection: { type: 'exact', promptId: 'p1' },+ });});- expect(options[3]).toEqual({- value: 'p1',- label: 'com_ui_version_var:{"0":"1"}',- selection: { type: 'exact', promptId: 'p1' },++ it('labels Production with the revision marked `isProduction`', () => {+ const options = buildPromptVersionOptions(nativeData(revisions), undefined, localize);++ expect(options[0].label).toBe('com_agents_instructions_prompt_production_version:{"0":"2"}');});- });- it('labels Production with its display number when the revision is known', () => {- const options = buildPromptVersionOptions(prompts, 'p2', localize);+ it('falls back to a plain Production label when no revision is marked `isProduction`', () => {+ const noProduction = revisions.map((revision) => ({ ...revision, isProduction: false }));+ const options = buildPromptVersionOptions(nativeData(noProduction), undefined, localize);- expect(options[0].label).toBe('com_agents_instructions_prompt_production_version:{"0":"2"}');- });+ expect(options[0].label).toBe('com_ui_production');+ });++ it('appends the saved exact selection, labelled as missing, when it matches no revision', () => {+ const options = buildPromptVersionOptions(+ nativeData(revisions),+ {+ type: 'exact',+ promptId: 'deleted',+ },+ localize,+ );++ expect(options[options.length - 1]).toEqual({+ value: 'deleted',+ label: 'com_agents_instructions_prompt_version_missing',+ selection: { type: 'exact', promptId: 'deleted' },+ });+ });++ it('does not append anything extra when the saved selection matches a listed revision', () => {+ const options = buildPromptVersionOptions(+ nativeData(revisions),+ {+ type: 'exact',+ promptId: 'p1',+ },+ localize,+ );++ expect(options).toHaveLength(4);+ });- it('falls back to a plain Production label when the revision is unknown', () => {- const options = buildPromptVersionOptions(prompts, 'not-in-group', localize);+ it('does not append anything extra for a saved production selection', () => {+ const options = buildPromptVersionOptions(+ nativeData(revisions),+ {+ type: 'production',+ },+ localize,+ );- expect(options[0].label).toBe('com_ui_production');+ expect(options).toHaveLength(4);+ });});- it('falls back to a plain Production label when no production id is given', () => {- const options = buildPromptVersionOptions(prompts, null, localize);+ describe('langfuse', () => {+ const revisions: TPromptRevisionChoicesResponse['revisions'] = [+ { source: 'langfuse', version: 3 },+ { source: 'langfuse', version: 2 },+ { source: 'langfuse', version: 1 },+ ];++ it('lists Production first with the plain label, then versions newest to oldest', () => {+ const options = buildPromptVersionOptions(langfuseData(revisions), undefined, localize);++ expect(options.map((option) => option.value)).toEqual(['production', 'v3', 'v2', 'v1']);+ expect(options[0].label).toBe('com_ui_production');+ expect(options[0].selection).toEqual({ type: 'production' });+ expect(options[1]).toEqual({+ value: 'v3',+ label: 'com_ui_version_var:{"0":"3"}',+ selection: { type: 'exact', version: 3 },+ });+ });++ it('appends the saved pinned version, labelled as missing with the version number, when it matches no revision', () => {+ const options = buildPromptVersionOptions(+ langfuseData(revisions),+ {+ type: 'exact',+ version: 9,+ },+ localize,+ );++ expect(options[options.length - 1]).toEqual({+ value: 'v9',+ label: 'com_agents_instructions_prompt_langfuse_version_missing:{"0":"9"}',+ selection: { type: 'exact', version: 9 },+ });+ });- expect(options[0].label).toBe('com_ui_production');+ it('does not append anything extra when the saved version matches a listed revision', () => {+ const options = buildPromptVersionOptions(+ langfuseData(revisions),+ {+ type: 'exact',+ version: 2,+ },+ localize,+ );++ expect(options).toHaveLength(4);+ });});});@@ -136,3 +238,50 @@ describe('getInstructionsPromptErrorCode', () => {expect(getInstructionsPromptErrorCode(new Error('offline'))).toBeUndefined();});});++describe('getRevisionsLoadErrorKey', () => {+ it('maps a 403 to the forbidden copy', () => {+ expect(getRevisionsLoadErrorKey(axiosError(403))).toBe(+ 'com_agents_instructions_prompt_forbidden',+ );+ });++ it('maps a 404 "not_available" to the source-unavailable copy', () => {+ expect(getRevisionsLoadErrorKey(axiosError(404, 'not_available'))).toBe(+ 'com_agents_instructions_prompt_source_unavailable',+ );+ });++ it('maps a plain 404 "not_found" (missing group) to the generic load-error copy', () => {+ expect(getRevisionsLoadErrorKey(axiosError(404, 'not_found'))).toBe(+ 'com_agents_instructions_prompt_load_error',+ );+ });++ it('maps a 409 "not_configured" to the source-unavailable copy', () => {+ expect(getRevisionsLoadErrorKey(axiosError(409, 'not_configured'))).toBe(+ 'com_agents_instructions_prompt_source_unavailable',+ );+ });++ it('maps a 409 "source_changed" to the source-unavailable copy', () => {+ expect(getRevisionsLoadErrorKey(axiosError(409, 'source_changed'))).toBe(+ 'com_agents_instructions_prompt_source_unavailable',+ );+ });++ it('maps a 422 "unsupported_type" to the source-unavailable copy', () => {+ expect(getRevisionsLoadErrorKey(axiosError(422, 'unsupported_type'))).toBe(+ 'com_agents_instructions_prompt_source_unavailable',+ );+ });++ it('falls back to the generic load-error copy for anything else', () => {+ expect(getRevisionsLoadErrorKey(axiosError(500))).toBe(+ 'com_agents_instructions_prompt_load_error',+ );+ expect(getRevisionsLoadErrorKey(new Error('network down'))).toBe(+ 'com_agents_instructions_prompt_load_error',+ );+ });+});diff --git a/client/src/components/SidePanel/Agents/instructionsPromptUtils.ts b/client/src/components/SidePanel/Agents/instructionsPromptUtils.tsindex be78d53b79..5c6a6761ca 100644--- a/client/src/components/SidePanel/Agents/instructionsPromptUtils.ts+++ b/client/src/components/SidePanel/Agents/instructionsPromptUtils.ts@@ -1,10 +1,12 @@import axios from 'axios';import { InstructionsPromptErrorCode } from 'librechat-data-provider';import type {- TPrompt,+ PromptSelection,+ TPromptGroupSource,AgentInstructionsPrompt,+ LangfusePromptSelection,RestrictedAgentInstructionsPrompt,- AgentInstructionsPromptSelection,+ TPromptRevisionChoicesResponse,} from 'librechat-data-provider';import type { TranslationKeys } from '~/hooks';@@ -19,41 +21,81 @@ export const isRestrictedInstructionsPrompt = (export type PromptVersionOption = {value: string;label: string;- selection: AgentInstructionsPromptSelection;+ selection: PromptSelection;};-/**- * Builds the Version dropdown options for a prompt group's revisions.- * "Production" is always first, labelled with the current production revision's- * display number when it can be matched by `_id` against `productionId`. The- * revisions that follow are labelled "Version N", newest to oldest, matching the- * display ordinal used in `client/src/components/Prompts/display/PromptVersions.tsx`.- */+/** Narrows a selection to the Langfuse shape by the absence of `promptId`, the native-only field. */+export function isLangfuseSelection(+ selection: PromptSelection | undefined,+): selection is LangfusePromptSelection | undefined {+ return selection == null || !('promptId' in selection);+}++export function selectionValue(+ source: TPromptGroupSource | undefined,+ selection: PromptSelection | undefined,+): string {+ if (selection == null || selection.type !== 'exact') {+ return 'production';+ }+ if (source === 'native' && 'promptId' in selection) {+ return selection.promptId;+ }+ if (source === 'langfuse' && 'version' in selection) {+ return `v${selection.version}`;+ }+ return 'production';+}++/** Appends the saved selection as "no longer available" if it matches no listed revision. */export function buildPromptVersionOptions(- prompts: TPrompt[],- productionId: string | null | undefined,+ data: TPromptRevisionChoicesResponse,+ selection: PromptSelection | undefined,localize: (key: TranslationKeys, vars?: Record<string, unknown>) => string,): PromptVersionOption[] {- const total = prompts.length;- const productionIndex =- productionId != null ? prompts.findIndex((prompt) => prompt._id === productionId) : -1;- const productionLabel =- productionIndex >= 0- ? localize('com_agents_instructions_prompt_production_version', {- 0: String(total - productionIndex),- })- : localize('com_ui_production');+ let productionLabel = localize('com_ui_production');+ const versionOptions: PromptVersionOption[] = [];- const versionOptions: PromptVersionOption[] = prompts.map((prompt, index) => ({- value: prompt._id ?? '',- label: localize('com_ui_version_var', { 0: String(total - index) }),- selection: { type: 'exact', promptId: prompt._id ?? '' },- }));+ for (const revision of data.revisions) {+ if (revision.source === 'native') {+ if (revision.isProduction) {+ productionLabel = localize('com_agents_instructions_prompt_production_version', {+ 0: String(revision.version),+ });+ }+ versionOptions.push({+ value: revision.promptId,+ label: localize('com_ui_version_var', { 0: String(revision.version) }),+ selection: { type: 'exact', promptId: revision.promptId },+ });+ } else {+ versionOptions.push({+ value: `v${revision.version}`,+ label: localize('com_ui_version_var', { 0: String(revision.version) }),+ selection: { type: 'exact', version: revision.version },+ });+ }+ }- return [+ const options: PromptVersionOption[] = [{ value: 'production', label: productionLabel, selection: { type: 'production' } },...versionOptions,];++ if (selection != null && selection.type !== 'production') {+ const selectedValue = selectionValue(data.source, selection);+ if (!options.some((option) => option.value === selectedValue)) {+ const label =+ 'version' in selection+ ? localize('com_agents_instructions_prompt_langfuse_version_missing', {+ 0: String(selection.version),+ })+ : localize('com_agents_instructions_prompt_version_missing');+ options.push({ value: selectedValue, label, selection });+ }+ }++ return options;}/** Stable, machine-readable codes mapped to a localized copy key each. */@@ -81,3 +123,21 @@ export function getInstructionsPromptErrorCode(export function getHttpStatus(error: unknown): number | undefined {return axios.isAxiosError(error) ? error.response?.status : undefined;}++export function getRevisionsLoadErrorKey(error: unknown): TranslationKeys {+ const status = getHttpStatus(error);+ if (status === 403) {+ return 'com_agents_instructions_prompt_forbidden';+ }+ const code = axios.isAxiosError<{ code?: unknown }>(error)+ ? error.response?.data?.code+ : undefined;+ const isSourceUnavailable =+ (status === 404 && code === 'not_available') ||+ (status === 409 && (code === 'not_configured' || code === 'source_changed')) ||+ (status === 422 && code === 'unsupported_type');+ if (isSourceUnavailable) {+ return 'com_agents_instructions_prompt_source_unavailable';+ }+ return 'com_agents_instructions_prompt_load_error';+}diff --git a/client/src/data-provider/prompts.ts b/client/src/data-provider/prompts.tsindex 8720452bf7..4b6a7cd69b 100644--- a/client/src/data-provider/prompts.ts+++ b/client/src/data-provider/prompts.ts@@ -389,6 +389,25 @@ export const useResolvePromptGroup = ();};+/** No cache or retry: a Langfuse group's revisions can change between requests. */+export const useGetPromptGroupRevisions = (+ id: string,+ config?: { enabled?: boolean },+): QueryObserverResult<t.TPromptRevisionChoicesResponse> => {+ return useQuery<t.TPromptRevisionChoicesResponse>(+ [QueryKeys.promptGroupRevisions, id],+ () => dataService.getPromptGroupRevisions(id),+ {+ enabled: config?.enabled,+ retry: false,+ staleTime: 0,+ cacheTime: 0,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ },+ );+};+/** Imperative counterpart to `useResolvePromptGroup`, for callers (for example a* slash-command submit) that need a single resolved read rather than a hook* bound to render. */diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex dbad0de562..587b1f3f31 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -293,6 +293,7 @@"com_agents_instructions_prompt_error_unavailable": "This prompt selection isn't available right now.","com_agents_instructions_prompt_error_validation_failed": "Couldn't validate the linked prompt. Please try again.","com_agents_instructions_prompt_forbidden": "You don't have access to the prompt library.",+ "com_agents_instructions_prompt_langfuse_version_missing": "Version {{0}} (no longer available)","com_agents_instructions_prompt_load_error": "Couldn't load prompts.","com_agents_instructions_prompt_not_found": "Prompt not found","com_agents_instructions_prompt_production_version": "Production (Version {{0}})",@@ -301,7 +302,10 @@"com_agents_instructions_prompt_restricted_title": "Restricted prompt","com_agents_instructions_prompt_search_placeholder": "Search prompts by name","com_agents_instructions_prompt_select_placeholder": "Select a prompt",+ "com_agents_instructions_prompt_source_disabled": "Langfuse prompt linking is turned off. This agent runs without these instructions until it is turned on again.",+ "com_agents_instructions_prompt_source_unavailable": "This prompt's source isn't available right now.","com_agents_instructions_prompt_version_label": "Version",+ "com_agents_instructions_prompt_version_missing": "Selected version (no longer available)","com_agents_instructions_prompt_version_placeholder": "Select a prompt first","com_agents_instructions_prompt_version_select_placeholder": "Select a version","com_agents_instructions_source_inline": "Inline",diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex b3111ecd4e..8cad7a99b1 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -6095,6 +6095,90 @@ describe('initializeAgent — linked instructions', () => {expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();});+ it('falls back to empty instructions with a warning, and records no usage, when a Langfuse link is disabled', async () => {+ const langfuseLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId: 'group-1',+ selection: { type: 'production' },+ };+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({ status: 'unavailable', reason: 'disabled' });++ const result = await run({+ agentOverrides: { instructionsPrompt: langfuseLink, instructions: 'stale inline text' },+ params: { resolveLinkedInstructions },+ });+ await flush();++ expect(result.instructions).toBe('');+ expect(result.instructionsPromptFacts).toBeUndefined();+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('group-1'));+ expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();+ });++ it('resolves a linked Langfuse agent and records exactly one usage with version-shaped facts', async () => {+ const langfuseLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId: 'group-1',+ selection: { type: 'production' },+ };+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({+ status: 'resolved',+ prompt: 'Hello {{current_user}}, be concise.',+ facts: { source: 'langfuse', groupId: 'group-1', version: 3 },+ });++ const result = await run({+ agentOverrides: { instructionsPrompt: langfuseLink },+ reqOverrides: { user: { id: 'user-1', name: 'Ada' } as never },+ params: { resolveLinkedInstructions },+ });+ await flush();++ expect(resolveLinkedInstructions).toHaveBeenCalledWith(+ expect.objectContaining({ link: langfuseLink }),+ );+ expect(result.instructions).toBe('Hello Ada, be concise.');+ expect(result.instructionsPromptFacts).toEqual({+ source: 'langfuse',+ groupId: 'group-1',+ version: 3,+ });+ expect(resolveLinkedInstructions.recordUse).toHaveBeenCalledTimes(1);+ expect(resolveLinkedInstructions.recordUse).toHaveBeenCalledWith({+ source: 'langfuse',+ groupId: 'group-1',+ version: 3,+ });+ });++ it('resolves a linked Langfuse agent normally, but records no usage, when recordLinkedPromptUsage is false (resume)', async () => {+ const langfuseLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId: 'group-1',+ selection: { type: 'exact', version: 3 },+ };+ const resolveLinkedInstructions = makeResolveLinkedInstructions();+ resolveLinkedInstructions.mockResolvedValue({+ status: 'resolved',+ prompt: 'Fixed Langfuse instructions.',+ facts: { source: 'langfuse', groupId: 'group-1', version: 3 },+ });++ const result = await run({+ agentOverrides: { instructionsPrompt: langfuseLink },+ params: { resolveLinkedInstructions, recordLinkedPromptUsage: false },+ });+ await flush();++ expect(result.instructions).toBe('Fixed Langfuse instructions.');+ expect(resolveLinkedInstructions).toHaveBeenCalledWith(+ expect.objectContaining({ link: langfuseLink }),+ );+ expect(resolveLinkedInstructions.recordUse).not.toHaveBeenCalled();+ });+it('falls back to empty instructions with a warning when no resolver is provided', async () => {const result = await run({agentOverrides: { instructionsPrompt: link, instructions: 'stale inline text' },diff --git a/packages/api/src/agents/hitl/protection.spec.ts b/packages/api/src/agents/hitl/protection.spec.tsindex 86f0220a26..22395f2cae 100644--- a/packages/api/src/agents/hitl/protection.spec.ts+++ b/packages/api/src/agents/hitl/protection.spec.ts@@ -798,6 +798,36 @@ describe('assertResumeRuntimeContentAllowed', () => {).resolves.toBeUndefined();});+ it('excludes the stored inline instructions from the same scan when the agent has a valid Langfuse instructionsPrompt link', async () => {+ const input = {+ appConfig: agentInstructionsPolicy,+ endpointOption: {+ agent: Promise.resolve({+ id: 'agent-1',+ provider: 'openai',+ model: 'test-model',+ instructions: 'Contains PRIVATE-INSTRUCTION marker',+ instructionsPrompt: {+ source: 'langfuse',+ groupId: 'group-1',+ selection: { type: 'production' },+ },+ }),+ },+ conversationId: 'conversation-1',+ targetMessageId: null,+ user,+ storedMessages: [],+ seedContent: [],+ liveFiles: [],+ isTemporary: true,+ } as unknown as Parameters<typeof assertResumeContentAllowed>[0];++ await expect(+ assertResumeContentAllowed(input, basePolicyDependencies()),+ ).resolves.toBeUndefined();+ });+it('still inspects a restricted-stub link as no link — the stub carries no groupId to trust', async () => {const input = {appConfig: agentInstructionsPolicy,diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 2cf21a8c00..6934915b8a 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -929,11 +929,7 @@ export type InitializedAgent = Agent & {provisionWarnings?: string[];/** State for deferred file provisioning — actual uploads happen at tool invocation time */provisionState?: ProvisionState;- /**- * Facts about a resolved `instructionsPrompt` link (source, groupId,- * resolved promptId), surfaced for AI-2158. Never persisted — omitted for- * an agent with no link, an unresolved link, or a missing resolver.- */+ /** Facts about a resolved `instructionsPrompt` link, shaped per source. Never persisted. */instructionsPromptFacts?: LinkedInstructionsFacts;};@@ -1042,14 +1038,7 @@ export interface InitializeAgentParams {* from `db.getRoleByName`.*/resolveWebSearchGrant?: () => Promise<boolean>;- /**- * Resolves an agent's `instructionsPrompt` link (a linked native prompt- * group) into instruction text. Called only when `agent.instructionsPrompt`- * carries a resolvable `native` link. Absent, a linked agent falls back to- * empty instructions with a warning — there is no default DB-backed- * resolution path, unlike `resolveWebSearchGrant`, so every caller that- * wants linked instructions honored must supply one.- */+ /** With none supplied, a linked agent falls back to empty instructions. */resolveLinkedInstructions?: ResolveLinkedInstructions;/*** Whether resolving `agent.instructionsPrompt` should record a usagediff --git a/packages/api/src/agents/instructions/access.spec.ts b/packages/api/src/agents/instructions/access.spec.tsindex 3555525c69..e4ab59ff0d 100644--- a/packages/api/src/agents/instructions/access.spec.ts+++ b/packages/api/src/agents/instructions/access.spec.ts@@ -1,6 +1,7 @@import { InstructionsPromptErrorCode, PermissionBits, ResourceType } from 'librechat-data-provider';import type { AgentInstructionsPrompt } from 'librechat-data-provider';import { ContentTraversalLimitError } from '~/protection/adapters/nested';+import { LangfusePromptRequestError } from '~/langfuse/prompts';import { createInstructionsPromptAccess } from './access';const groupId = '507f1f77bcf86cd799439011';@@ -34,6 +35,24 @@ const thirdGroupLink: AgentInstructionsPrompt = {selection: { type: 'production' },};+const langfuseLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId: otherGroupId,+ selection: { type: 'production' },+};++const langfuseVersionLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId: otherGroupId,+ selection: { type: 'exact', version: 2 },+};++const langfuseVersionLink3: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId: otherGroupId,+ selection: { type: 'exact', version: 3 },+};+function buildAccess({visibleGroupIds = new Set<string>(),resolvePromptOk = true,@@ -337,9 +356,9 @@ describe('createInstructionsPromptAccess', () => {});expect(resolve).toHaveBeenCalledWith({groupId,+ source: 'native',selection: exactLink.selection,filters: undefined,- allowedSources: ['native'],});});@@ -349,9 +368,9 @@ describe('createInstructionsPromptAccess', () => {expect(result).toEqual({ ok: true });expect(resolve).toHaveBeenCalledWith({groupId,+ source: 'native',selection: exactLink.selection,filters: undefined,- allowedSources: ['native'],});});@@ -371,9 +390,9 @@ describe('createInstructionsPromptAccess', () => {await access.validateLinkWrite({ user, previous: null, next: productionLink, filters });expect(resolve).toHaveBeenCalledWith({groupId,+ source: 'native',selection: productionLink.selection,filters,- allowedSources: ['native'],});});@@ -585,6 +604,269 @@ describe('createInstructionsPromptAccess', () => {});});});++ describe('the Langfuse rollout switch (linkedInstructions.langfuse.enabled)', () => {+ it('rejects a new Langfuse link while the switch is off, before any USE/VIEW check', async () => {+ const { access, canUse, map } = buildAccess({ visibleGroupIds: new Set([otherGroupId]) });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(canUse).not.toHaveBeenCalled();+ expect(map).not.toHaveBeenCalled();+ });++ it('rejects a changed Langfuse link while the switch is off', async () => {+ const { access, canUse, map, resolve } = buildAccess({+ visibleGroupIds: new Set([otherGroupId]),+ });+ const result = await access.validateLinkWrite({+ user,+ previous: langfuseLink,+ next: langfuseVersionLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(canUse).not.toHaveBeenCalled();+ expect(map).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ });++ it('allows removing a Langfuse link while the switch is off', async () => {+ const { access, canUse, resolve } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: langfuseLink,+ next: null,+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ });++ it('allows re-submitting the unchanged Langfuse link while the switch is off', async () => {+ const { access, canUse, resolve } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: langfuseLink,+ next: { ...langfuseLink },+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ });++ it('allows re-submitting the unchanged pinned Langfuse link while the switch is off', async () => {+ const { access, canUse, map, resolve } = buildAccess();+ const result = await access.validateLinkWrite({+ user,+ previous: langfuseVersionLink,+ next: { ...langfuseVersionLink },+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).not.toHaveBeenCalled();+ expect(map).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ });++ it('never blocks a native replacement, regardless of the switch', async () => {+ const { access, canUse, map, resolve } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ });+ const result = await access.validateLinkWrite({+ user,+ previous: langfuseLink,+ next: productionLink,+ });+ expect(result).toEqual({ ok: true });+ expect(canUse).toHaveBeenCalled();+ expect(map).toHaveBeenCalled();+ expect(resolve).toHaveBeenCalled();+ });++ it('rejects a native replacement when USE is denied, even though the switch is off', async () => {+ const { access } = buildAccess({+ visibleGroupIds: new Set([groupId]),+ canUsePromptsResult: false,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: langfuseLink,+ next: productionLink,+ });+ expect(result).toEqual({+ ok: false,+ status: 403,+ code: InstructionsPromptErrorCode.FORBIDDEN,+ });+ });++ it('rejects a new Langfuse link when the switch is explicitly disabled', async () => {+ const { access, canUse, map, resolve } = buildAccess({+ visibleGroupIds: new Set([otherGroupId]),+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ linkedInstructions: { langfuse: { enabled: false } },+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(canUse).not.toHaveBeenCalled();+ expect(map).not.toHaveBeenCalled();+ expect(resolve).not.toHaveBeenCalled();+ });++ it('rejects a Langfuse selection that resolves with an unsupported_content error', async () => {+ const resolvePrompt = jest.fn(async () => ({+ ok: false as const,+ error: { type: 'unsupported_content' as const, reason: 'chat_prompt' as const },+ }));+ const { access } = buildAccess({+ visibleGroupIds: new Set([otherGroupId]),+ resolvePrompt,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ linkedInstructions: { langfuse: { enabled: true } },+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ });++ it('allows a new Langfuse link once the switch is on', async () => {+ const resolvePrompt = jest.fn(async () => ({+ ok: true as const,+ value: {+ source: 'langfuse' as const,+ groupId: otherGroupId,+ prompt: 'hi',+ type: 'text' as const,+ version: 3,+ labels: ['production'],+ },+ }));+ const { access } = buildAccess({+ visibleGroupIds: new Set([otherGroupId]),+ resolvePrompt,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ linkedInstructions: { langfuse: { enabled: true } },+ });+ expect(result).toEqual({ ok: true });+ expect(resolvePrompt).toHaveBeenCalledWith({+ groupId: otherGroupId,+ source: 'langfuse',+ selection: langfuseLink.selection,+ filters: undefined,+ });+ });++ it('treats a different Langfuse version number as a changed link once the switch is on', async () => {+ const { access, canUse } = buildAccess({ visibleGroupIds: new Set([otherGroupId]) });+ await access.validateLinkWrite({+ user,+ previous: langfuseVersionLink,+ next: langfuseVersionLink3,+ linkedInstructions: { langfuse: { enabled: true } },+ });+ expect(canUse).toHaveBeenCalled();+ });++ it('passes a pinned Langfuse link through as a langfuse exact-version reference', async () => {+ const { access, resolve } = buildAccess({ visibleGroupIds: new Set([otherGroupId]) });+ await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseVersionLink3,+ linkedInstructions: { langfuse: { enabled: true } },+ });+ expect(resolve).toHaveBeenCalledWith({+ groupId: otherGroupId,+ source: 'langfuse',+ selection: { type: 'exact', version: 3 },+ filters: undefined,+ });+ });+ });++ describe('Langfuse selection resolution', () => {+ it('maps a thrown LangfusePromptRequestError to UNAVAILABLE and logs only its code', async () => {+ const resolvePrompt = jest.fn(async () => {+ throw new LangfusePromptRequestError('timeout', 'Langfuse request timed out');+ });+ const { access, logger } = buildAccess({+ visibleGroupIds: new Set([otherGroupId]),+ resolvePrompt,+ });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ linkedInstructions: { langfuse: { enabled: true } },+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ expect(logger.warn).toHaveBeenCalledWith(expect.any(String), { code: 'timeout' });+ });++ it('propagates an error that is not a LangfusePromptRequestError', async () => {+ const { access } = buildAccess({+ visibleGroupIds: new Set([otherGroupId]),+ resolvePrompt: jest.fn(async () => {+ throw new Error('unexpected prompt-store failure');+ }),+ });+ await expect(+ access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ linkedInstructions: { langfuse: { enabled: true } },+ }),+ ).rejects.toThrow('unexpected prompt-store failure');+ });++ it('rejects when the resolved value source does not match the requested link source', async () => {+ // The mock `resolve` answers with a native value, so this exercises the mismatch.+ const { access } = buildAccess({ visibleGroupIds: new Set([otherGroupId]) });+ const result = await access.validateLinkWrite({+ user,+ previous: null,+ next: langfuseLink,+ linkedInstructions: { langfuse: { enabled: true } },+ });+ expect(result).toEqual({+ ok: false,+ status: 400,+ code: InstructionsPromptErrorCode.UNAVAILABLE,+ });+ });+ });});describe('presentForEditor', () => {@@ -884,6 +1166,33 @@ describe('createInstructionsPromptAccess', () => {});});});++ describe('Langfuse links', () => {+ it('stubs a redacted Langfuse link with its own source', async () => {+ const { access } = buildAccess();+ const agent = { id: 'a1', instructionsPrompt: langfuseLink };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'langfuse', restricted: true },+ });+ });++ it('fails closed on a Langfuse link, keeping its source in the stub', async () => {+ const { access, logger } = buildAccess({+ getResourcePermissionsMap: jest.fn(async () => {+ throw new Error('acl outage');+ }),+ });+ const agent = { id: 'a1', instructionsPrompt: langfuseLink };+ const result = await access.presentForEditor({ user, agent });+ expect(result).toEqual({+ id: 'a1',+ instructionsPrompt: { source: 'langfuse', restricted: true },+ });+ expect(logger.error).toHaveBeenCalledTimes(1);+ });+ });});describe('presentVersionsForEditor', () => {@@ -989,6 +1298,47 @@ describe('createInstructionsPromptAccess', () => {{ name: 'v1', instructionsPrompt: { source: 'native', restricted: true } },]);});++ it('redacts a Langfuse version link, keeping its source in the stub', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: langfuseVersionLink }];+ const result = await access.presentVersionsForEditor({ user, versions });+ expect(result).toEqual([+ { name: 'v1', instructionsPrompt: { source: 'langfuse', restricted: true } },+ ]);+ });++ it('flags a redacted Langfuse version stub as matching when the version number is equal', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: langfuseVersionLink }];+ const result = await access.presentVersionsForEditor({+ user,+ versions,+ currentLink: langfuseVersionLink,+ });+ expect(result).toEqual([+ {+ name: 'v1',+ instructionsPrompt: { source: 'langfuse', restricted: true, matchesCurrent: true },+ },+ ]);+ });++ it('flags a redacted Langfuse version stub as not matching when the version number differs', async () => {+ const { access } = buildAccess();+ const versions = [{ name: 'v1', instructionsPrompt: langfuseVersionLink }];+ const result = await access.presentVersionsForEditor({+ user,+ versions,+ currentLink: langfuseVersionLink3,+ });+ expect(result).toEqual([+ {+ name: 'v1',+ instructionsPrompt: { source: 'langfuse', restricted: true, matchesCurrent: false },+ },+ ]);+ });});});});diff --git a/packages/api/src/agents/instructions/access.ts b/packages/api/src/agents/instructions/access.tsindex 601ada0fc5..b78ca7b639 100644--- a/packages/api/src/agents/instructions/access.ts+++ b/packages/api/src/agents/instructions/access.ts@@ -1,11 +1,15 @@import { InstructionsPromptErrorCode, PermissionBits, ResourceType } from 'librechat-data-provider';import type {FiltersConfig,+ TPromptGroupSource,AgentInstructionsPrompt,RestrictedAgentInstructionsPrompt,} from 'librechat-data-provider';+import type { LinkedInstructionsConfig } from './linked';+import type { PromptReference } from '~/prompts/types';import type { PromptService } from '~/prompts';import { isContentFilterError } from '~/middleware/contentFilter';+import { LangfusePromptRequestError } from '~/langfuse/prompts';import { getSafeErrorMetadata } from '~/utils/errors';/** Matches the `logger` shape injected elsewhere in this module family@@ -76,29 +80,13 @@ export interface InstructionsPromptAccess {canViewGroup(input: Omit<InstructionsPromptAccessUser, 'id'> & { userId: string; groupId: string },): Promise<boolean>;- /**- * Validates a create/update write of `instructionsPrompt` against the stored link.- * `next === undefined` means the field is absent from the payload (no change- * requested) — ok. Keeping, removing (`next === null`), or re-submitting the- * unchanged link (`isSameLink`) is always ok: agent EDIT already authorizes all- * three, and none of them reveals anything about `previous`'s group that EDIT- * doesn't already know.- *- * A genuinely new or changed `next` requires the role-level PROMPTS `USE`- * permission (`canUsePrompts`) and PROMPTGROUP `VIEW` on `next.groupId`- * (`canViewGroup`), `FORBIDDEN` otherwise — a PROMPTGROUP `VIEW` grant on one group- * says nothing about whether the role may link prompts at all, and `next` not- * existing is indistinguishable from `next` existing but hidden, so group- * existence is never revealed through it. The two checks are independent, so both- * run concurrently instead of one gating the start of the other. Once both pass,- * the selection must still resolve and pass content policy (`UNAVAILABLE`- * otherwise).- */+ /** Checks an `instructionsPrompt` write; an unchanged link always passes. */validateLinkWrite(input: {user: InstructionsPromptAccessUser;previous: AgentInstructionsPrompt | null | undefined;next: AgentInstructionsPrompt | null | undefined;filters?: FiltersConfig;+ linkedInstructions?: Pick<LinkedInstructionsConfig, 'langfuse'>;/** Forwarded unexamined to `canUsePrompts` so its role lookup can reuse the* caller's per-request role cache. */req?: InstructionsPromptAccessRequest;@@ -152,8 +140,16 @@ function isSameLink(if (left.selection.type !== right.selection.type) {return false;}- if (left.selection.type === 'exact' && right.selection.type === 'exact') {- return left.selection.promptId === right.selection.promptId;+ // Narrows both selections to the same source's shape.+ if (left.source === 'native' && right.source === 'native') {+ return left.selection.type === 'exact' && right.selection.type === 'exact'+ ? left.selection.promptId === right.selection.promptId+ : true;+ }+ if (left.source === 'langfuse' && right.source === 'langfuse') {+ return left.selection.type === 'exact' && right.selection.type === 'exact'+ ? left.selection.version === right.selection.version+ : true;}return true;}@@ -164,7 +160,10 @@ function isRestrictedStub(return (link as RestrictedAgentInstructionsPrompt).restricted === true;}-const RESTRICTED_STUB: RestrictedAgentInstructionsPrompt = { source: 'native', restricted: true };+/** The restricted stub for a hidden link, carrying only the hidden link's own source. */+function restrictedStub(source: TPromptGroupSource): RestrictedAgentInstructionsPrompt {+ return { source, restricted: true };+}/** Every distinct, non-restricted-stub `groupId` referenced by the given links. */function collectLinkGroupIds(@@ -270,17 +269,16 @@ export function createInstructionsPromptAccess(deps: {}const stub: RestrictedAgentInstructionsPrompt =currentLink === undefined- ? RESTRICTED_STUB- : { ...RESTRICTED_STUB, matchesCurrent: isSameLink(link, currentLink) };+ ? restrictedStub(link.source)+ : { ...restrictedStub(link.source), matchesCurrent: isSameLink(link, currentLink) };return { ...carrier, instructionsPrompt: stub };}/** Unconditional stub, used only on the fail-closed path below: every link is* hidden because whether it may be shown could not be determined. */function stubLink<T extends AgentInstructionsPromptCarrier>(carrier: T): T {- return carrier.instructionsPrompt == null- ? carrier- : { ...carrier, instructionsPrompt: RESTRICTED_STUB };+ const link = carrier.instructionsPrompt;+ return link == null ? carrier : { ...carrier, instructionsPrompt: restrictedStub(link.source) };}/** Content-free failure log shared by every fail-closed path below. */@@ -307,12 +305,14 @@ export function createInstructionsPromptAccess(deps: {previous,next,filters,+ linkedInstructions,req,}: {user: InstructionsPromptAccessUser;previous: AgentInstructionsPrompt | null | undefined;next: AgentInstructionsPrompt | null | undefined;filters?: FiltersConfig;+ linkedInstructions?: Pick<LinkedInstructionsConfig, 'langfuse'>;req?: InstructionsPromptAccessRequest;}): Promise<InstructionsPromptWriteResult> {if (next === undefined) {@@ -329,6 +329,10 @@ export function createInstructionsPromptAccess(deps: {// group, is always allowed — agent EDIT is the only authority this needs.return { ok: true };}+ if (next.source === 'langfuse' && linkedInstructions?.langfuse?.enabled !== true) {+ // Reject a new or changed Langfuse link here, before any USE/VIEW check or resolve call.+ return { ok: false, status: 400, code: InstructionsPromptErrorCode.UNAVAILABLE };+ }// A genuinely new or changed link (never a removal, and never a re-selection of the// unchanged value — both returned above): the role must grant PROMPTS USE, and the// next group must be VIEWable. The two checks are independent and run concurrently;@@ -351,15 +355,35 @@ export function createInstructionsPromptAccess(deps: {// revealed through a new link.return { ok: false, status: 403, code: InstructionsPromptErrorCode.FORBIDDEN };}- const resolved = await promptService.resolvePrompt({- groupId: next.groupId,- selection: next.selection,- filters,- allowedSources: ['native'],- });+ // Built from `next` directly so narrowing on `source` also narrows `selection`.+ const reference: PromptReference =+ next.source === 'native'+ ? { source: 'native', selection: next.selection }+ : { source: 'langfuse', selection: next.selection };+ let resolved;+ try {+ resolved = await promptService.resolvePrompt({+ groupId: next.groupId,+ ...reference,+ filters,+ });+ } catch (error) {+ if (error instanceof LangfusePromptRequestError) {+ logger.warn(+ '[createInstructionsPromptAccess] Langfuse request failed validating a linked instructions-prompt write',+ { code: error.code },+ );+ return { ok: false, status: 400, code: InstructionsPromptErrorCode.UNAVAILABLE };+ }+ throw error;+ }if (!resolved.ok) {return { ok: false, status: 400, code: InstructionsPromptErrorCode.UNAVAILABLE };}+ if (resolved.value.source !== next.source) {+ /* Defensive: `reference.source` already guarantees this, so it is unreachable at runtime. */+ return { ok: false, status: 400, code: InstructionsPromptErrorCode.UNAVAILABLE };+ }try {assertAgentInstructionsContent({ instructions: resolved.value.prompt, filters });} catch (error) {@@ -393,15 +417,17 @@ export function createInstructionsPromptAccess(deps: {return failClosed(error, agent);}const topLevelLink = agent.instructionsPrompt;- const topLevelRedacted =- topLevelLink != null && !isRestrictedStub(topLevelLink) && redact.has(topLevelLink.groupId);+ const topLevelStub =+ topLevelLink != null && !isRestrictedStub(topLevelLink) && redact.has(topLevelLink.groupId)+ ? restrictedStub(topLevelLink.source)+ : null;const versionsUnchanged =versions == null ||versions.every((version) => {const link = version.instructionsPrompt;return link == null || isRestrictedStub(link) || !redact.has(link.groupId);});- if (!topLevelRedacted && versionsUnchanged) {+ if (topLevelStub == null && versionsUnchanged) {return agent;}// The agent's own raw link, used to flag a redacted version snapshot as@@ -411,7 +437,7 @@ export function createInstructionsPromptAccess(deps: {topLevelLink != null && !isRestrictedStub(topLevelLink) ? topLevelLink : null;return {...agent,- ...(topLevelRedacted ? { instructionsPrompt: RESTRICTED_STUB } : {}),+ ...(topLevelStub != null ? { instructionsPrompt: topLevelStub } : {}),...(versions == null? {}: { versions: versions.map((version) => redactIfHidden(version, redact, currentRawLink)) }),diff --git a/packages/api/src/agents/instructions/errors.ts b/packages/api/src/agents/instructions/errors.tsindex ca3d6589e2..642e039420 100644--- a/packages/api/src/agents/instructions/errors.ts+++ b/packages/api/src/agents/instructions/errors.ts@@ -5,6 +5,7 @@ import type {InstructionsPromptAccessUser,InstructionsPromptAccessRequest,} from './access';+import type { LinkedInstructionsConfig } from './linked';/** User-safe copy for each stable `instructionsPrompt` write-rejection code. */const INSTRUCTIONS_PROMPT_ERROR_MESSAGES: Record<InstructionsPromptErrorCode, string> = {@@ -45,6 +46,7 @@ export async function getInstructionsPromptLinkError({previous,next,filters,+ linkedInstructions,req,}: {access: Pick<InstructionsPromptAccess, 'validateLinkWrite'>;@@ -52,6 +54,7 @@ export async function getInstructionsPromptLinkError({previous: AgentInstructionsPrompt | null | undefined;next: AgentInstructionsPrompt | null | undefined;filters?: FiltersConfig;+ linkedInstructions?: Pick<LinkedInstructionsConfig, 'langfuse'>;/** Forwarded unexamined to `validateLinkWrite` so its role lookup can reuse the* caller's per-request role cache. */req?: InstructionsPromptAccessRequest;@@ -61,6 +64,7 @@ export async function getInstructionsPromptLinkError({previous,next,filters,+ linkedInstructions,req,});if (result.ok) {diff --git a/packages/api/src/agents/instructions/linked.spec.ts b/packages/api/src/agents/instructions/linked.spec.tsindex 66b53c88ae..af7d90a889 100644--- a/packages/api/src/agents/instructions/linked.spec.ts+++ b/packages/api/src/agents/instructions/linked.spec.ts@@ -1,9 +1,10 @@import type { FiltersConfig, AgentInstructionsPrompt } from 'librechat-data-provider';+import type { PromptService, NativeResolvedPrompt, LangfuseResolvedPrompt } from '~/prompts';import type { LinkedInstructionsCache, LinkedInstructionsLogger } from './linked';-import type { PromptService, NativeResolvedPrompt } from '~/prompts';import { createLinkedInstructionsResolver, invalidateLinkedPrompt } from './linked';import { ContentTraversalLimitError } from '~/protection/adapters/nested';import { assertModelBoundContent } from '~/middleware/modelBoundContent';+import { LangfusePromptRequestError } from '~/langfuse/prompts';jest.mock('~/middleware/modelBoundContent', () => ({...jest.requireActual('~/middleware/modelBoundContent'),@@ -88,6 +89,20 @@ const exactLink: AgentInstructionsPrompt = {selection: { type: 'exact', promptId },};+const langfuseProductionLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId,+ selection: { type: 'production' },+};++const langfuseExactLink: AgentInstructionsPrompt = {+ source: 'langfuse',+ groupId,+ selection: { type: 'exact', version: 3 },+};++const langfuseEnabledConfig = { langfuse: { enabled: true } };+function makeResolvedPrompt(overrides: Partial<NativeResolvedPrompt> = {}): NativeResolvedPrompt {return {source: 'native',@@ -99,6 +114,20 @@ function makeResolvedPrompt(overrides: Partial<NativeResolvedPrompt> = {}): Nati};}+function makeLangfuseResolvedPrompt(+ overrides: Partial<LangfuseResolvedPrompt> = {},+): LangfuseResolvedPrompt {+ return {+ source: 'langfuse',+ groupId,+ prompt: 'You are a helpful Langfuse-linked assistant.',+ type: 'text',+ version: 3,+ labels: ['production'],+ ...overrides,+ };+}+function makeLogger(): LinkedInstructionsLogger & { warn: jest.Mock; error: jest.Mock } {return { warn: jest.fn(), error: jest.fn() };}@@ -136,9 +165,9 @@ describe('createLinkedInstructionsResolver', () => {});expect(promptService.resolvePrompt).toHaveBeenCalledWith({groupId,+ source: 'native',selection: { type: 'production' },filters: undefined,- allowedSources: ['native'],});await expect(cache.get(`native:${groupId}:production`)).resolves.toMatchObject({groupId,@@ -158,9 +187,9 @@ describe('createLinkedInstructionsResolver', () => {expect(result.status).toBe('resolved');expect(promptService.resolvePrompt).toHaveBeenCalledWith({groupId,+ source: 'native',selection: { type: 'exact', promptId },filters: undefined,- allowedSources: ['native'],});await expect(cache.get(`native:${groupId}:exact:${promptId}`)).resolves.toBeDefined();});@@ -508,9 +537,36 @@ describe('createLinkedInstructionsResolver', () => {status: 'unavailable',reason: 'blocked_content',});+ // The warn must never surface `finding`, which can echo matched prompt content.+ expect(logger.warn).toHaveBeenCalledWith(+ '[linkedInstructions] resolvePrompt returned a failure result',+ { groupId, source: 'native', type: 'blocked_content' },+ );});- it('calls resolvePrompt with allowedSources native-only and maps a rejected non-native group (unsupported_source) to unavailable_selection', async () => {+ it('logs a content-free warn before returning unavailable for a failed resolvePrompt result', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'unavailable_selection', reason: 'production' },+ }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(resolver({ link: productionLink })).resolves.toEqual({+ status: 'unavailable',+ reason: 'unavailable_selection',+ });++ expect(logger.warn).toHaveBeenCalledWith(+ '[linkedInstructions] resolvePrompt returned a failure result',+ { groupId, source: 'native', type: 'unavailable_selection', reason: 'production' },+ );+ });++ it('builds a native reference and maps a rejected non-native group (unsupported_source) to unavailable_selection', async () => {const cache = new FakeCache();const promptService = makePromptService({resolvePrompt: jest.fn().mockResolvedValue({@@ -527,18 +583,17 @@ describe('createLinkedInstructionsResolver', () => {});expect(promptService.resolvePrompt).toHaveBeenCalledWith({groupId,+ source: 'native',selection: { type: 'production' },filters: undefined,- allowedSources: ['native'],});});it.each([- ['unsupported_selection', { type: 'unsupported_selection', source: 'native' }],['source_unavailable', { type: 'source_unavailable', source: 'langfuse', reason: 'disabled' }],['source_not_found', { type: 'source_not_found', source: 'langfuse' }],['unsupported_content', { type: 'unsupported_content', reason: 'chat_prompt' }],- ] as const)('maps the service error "%s" to the generic "error" reason', async (_name, error) => {+ ] as const)('maps the service error "%s" to "unavailable_selection"', async (_name, error) => {const cache = new FakeCache();const promptService = makePromptService({resolvePrompt: jest.fn().mockResolvedValue({ ok: false, error }),@@ -548,7 +603,251 @@ describe('createLinkedInstructionsResolver', () => {await expect(resolver({ link: productionLink })).resolves.toEqual({status: 'unavailable',- reason: 'error',+ reason: 'unavailable_selection',+ });+ });++ describe('Langfuse links', () => {+ it('returns unavailable "disabled" with no cache or service call when the switch is off', async () => {+ const cache = new FakeCache();+ const getSpy = jest.spyOn(cache, 'get');+ const setSpy = jest.spyOn(cache, 'set');+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(resolver({ link: langfuseProductionLink })).resolves.toEqual({+ status: 'unavailable',+ reason: 'disabled',+ });+ expect(getSpy).not.toHaveBeenCalled();+ expect(setSpy).not.toHaveBeenCalled();+ expect(promptService.resolvePrompt).not.toHaveBeenCalled();+ });++ it('returns unavailable "disabled" when the config omits the langfuse block entirely', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(resolver({ link: langfuseProductionLink, config: {} })).resolves.toEqual({+ status: 'unavailable',+ reason: 'disabled',+ });+ expect(promptService.resolvePrompt).not.toHaveBeenCalled();+ });++ it('resolves a Langfuse link fresh when the switch is on, with facts shaped by version (not promptId)', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest+ .fn()+ .mockResolvedValue({ ok: true, value: makeLangfuseResolvedPrompt() }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const result = await resolver({+ link: langfuseProductionLink,+ config: langfuseEnabledConfig,+ });++ expect(result).toEqual({+ status: 'resolved',+ prompt: 'You are a helpful Langfuse-linked assistant.',+ facts: { source: 'langfuse', groupId, version: 3 },+ });+ expect(promptService.resolvePrompt).toHaveBeenCalledWith({+ groupId,+ source: 'langfuse',+ selection: { type: 'production' },+ filters: undefined,+ });+ });++ it('passes a pinned Langfuse link through as a langfuse exact-version reference', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest+ .fn()+ .mockResolvedValue({ ok: true, value: makeLangfuseResolvedPrompt() }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await resolver({ link: langfuseExactLink, config: langfuseEnabledConfig });++ expect(promptService.resolvePrompt).toHaveBeenCalledWith({+ groupId,+ source: 'langfuse',+ selection: { type: 'exact', version: 3 },+ filters: undefined,+ });+ });++ it('never reads or writes the cache for a Langfuse link, before or after resolving', async () => {+ const cache = new FakeCache();+ const getSpy = jest.spyOn(cache, 'get');+ const setSpy = jest.spyOn(cache, 'set');+ const promptService = makePromptService({+ resolvePrompt: jest+ .fn()+ .mockResolvedValue({ ok: true, value: makeLangfuseResolvedPrompt() }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ expect(getSpy).not.toHaveBeenCalled();+ expect(setSpy).not.toHaveBeenCalled();++ await resolver({ link: langfuseProductionLink, config: langfuseEnabledConfig });+ await flush();++ expect(getSpy).not.toHaveBeenCalled();+ expect(setSpy).not.toHaveBeenCalled();+ });++ it('fetches again on a second call — no cache ever satisfies a Langfuse link', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest+ .fn()+ .mockResolvedValue({ ok: true, value: makeLangfuseResolvedPrompt() }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await resolver({ link: langfuseProductionLink, config: langfuseEnabledConfig });+ await resolver({ link: langfuseProductionLink, config: langfuseEnabledConfig });++ expect(promptService.resolvePrompt).toHaveBeenCalledTimes(2);+ });++ it('maps every source-routing and selection error to "unavailable_selection"', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'unsupported_content', reason: 'chat_prompt' },+ }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(+ resolver({ link: langfuseProductionLink, config: langfuseEnabledConfig }),+ ).resolves.toEqual({ status: 'unavailable', reason: 'unavailable_selection' });+ // The warn must carry only `type`/`reason`/ids, never prompt text.+ expect(logger.warn).toHaveBeenCalledWith(+ '[linkedInstructions] resolvePrompt returned a failure result',+ { groupId, source: 'langfuse', type: 'unsupported_content', reason: 'chat_prompt' },+ );+ });++ it('maps a resolved source mismatch (service returned native for a Langfuse link) to "unavailable_selection"', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockResolvedValue({ ok: true, value: makeResolvedPrompt() }),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(+ resolver({ link: langfuseProductionLink, config: langfuseEnabledConfig }),+ ).resolves.toEqual({ status: 'unavailable', reason: 'unavailable_selection' });+ });++ it('maps a thrown LangfusePromptRequestError to "error", logging its code and never its message text', async () => {+ const cache = new FakeCache();+ const requestError = new LangfusePromptRequestError(+ 'upstream',+ 'DO-NOT-LOG-THIS-UPSTREAM-BODY',+ 502,+ );+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockRejectedValue(requestError),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ await expect(+ resolver({ link: langfuseProductionLink, config: langfuseEnabledConfig }),+ ).resolves.toEqual({ status: 'unavailable', reason: 'error' });+ expect(logger.error).toHaveBeenCalledWith(+ '[linkedInstructions] resolvePrompt failed',+ expect.objectContaining({+ groupId,+ errorName: 'LangfusePromptRequestError',+ code: 'upstream',+ }),+ );+ const allLogCalls = [...logger.warn.mock.calls, ...logger.error.mock.calls];+ for (const call of allLogCalls) {+ expect(JSON.stringify(call)).not.toContain('DO-NOT-LOG-THIS-UPSTREAM-BODY');+ }+ });++ it('returns unavailable "timeout" when the Langfuse resolution does not settle in time', async () => {+ jest.useFakeTimers();+ try {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(() => resolve({ ok: true, value: makeLangfuseResolvedPrompt() }), 200);+ }),+ ),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const pending = resolver({+ link: langfuseProductionLink,+ config: { ...langfuseEnabledConfig, timeoutMs: 10 },+ });+ await jest.advanceTimersByTimeAsync(11);++ await expect(pending).resolves.toEqual({ status: 'unavailable', reason: 'timeout' });+ await jest.advanceTimersByTimeAsync(200);+ } finally {+ jest.useRealTimers();+ }+ });++ it('throws the abort reason for a Langfuse link and records no usage', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService({+ resolvePrompt: jest.fn().mockReturnValue(new Promise(() => {})),+ });+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ const controller = new AbortController();+ const pending = resolver({+ link: langfuseProductionLink,+ config: langfuseEnabledConfig,+ signal: controller.signal,+ });+ controller.abort();++ await expect(pending).rejects.toBe(controller.signal.reason);+ await flush();+ expect(promptService.incrementPromptGroupUsage).not.toHaveBeenCalled();+ });++ it('records usage for a resolved Langfuse link via recordUse, fire-and-forget', async () => {+ const cache = new FakeCache();+ const promptService = makePromptService();+ const logger = makeLogger();+ const resolver = createLinkedInstructionsResolver({ promptService, cache, logger });++ resolver.recordUse({ source: 'langfuse', groupId, version: 3 });+ await flush();++ expect(promptService.incrementPromptGroupUsage).toHaveBeenCalledTimes(1);+ expect(promptService.incrementPromptGroupUsage).toHaveBeenCalledWith(groupId);});});diff --git a/packages/api/src/agents/instructions/linked.ts b/packages/api/src/agents/instructions/linked.tsindex e4f026d5ce..34ad074c7d 100644--- a/packages/api/src/agents/instructions/linked.ts+++ b/packages/api/src/agents/instructions/linked.ts@@ -1,60 +1,61 @@import { scopedCacheKey } from '@librechat/data-schemas';import type {FiltersConfig,+ DeepPartial,+ TAgentsEndpoint,AgentInstructionsPrompt,AgentInstructionsPromptSelection,RestrictedAgentInstructionsPrompt,} from 'librechat-data-provider';-import type { NativeResolvedPrompt, PromptServiceError } from '~/prompts/types';+import type {+ ResolvedPrompt,+ PromptReference,+ NativeResolvedPrompt,+ PromptServiceError,+} from '~/prompts/types';import type { PromptService } from '~/prompts/service';import { assertModelBoundContent } from '~/middleware/modelBoundContent';import { isContentFilterError } from '~/middleware/contentFilter';+import { LangfusePromptRequestError } from '~/langfuse/prompts';import { inspectPromptContent } from '~/prompts/protection';-/**- * Narrows `link` to a resolvable `native` link — the same test- * `initializeAgent` uses to decide whether an agent's stored inline- * `instructions` are live text or dead text superseded by a link. A- * `RestrictedAgentInstructionsPrompt` stub (`{ source: 'native', restricted:- * true }`, no `groupId`) is never valid: it never reaches `initializeAgent`- * (that shape exists only for an editor without VIEW on the linked group),- * so it must not be treated as a link that suppresses inline text elsewhere- * either — most importantly in the HITL resume preflight, which inspects a- * stored agent snapshot rather than a live `Agent`.- */+/** A restricted stub is never valid; a disabled Langfuse link still is. */export function isValidInstructionsPromptLink(link: AgentInstructionsPrompt | RestrictedAgentInstructionsPrompt | null | undefined,): link is AgentInstructionsPrompt {- return link != null && link.source === 'native' && 'groupId' in link;+ return (+ link != null && (link.source === 'native' || link.source === 'langfuse') && 'groupId' in link+ );}-/** Facts about a resolved link, retained on the initialized agent. Never persisted. */-export type LinkedInstructionsFacts = {- source: 'native';- groupId: string;- promptId: string;-};+/** Facts about a resolved link, retained on the initialized agent but never persisted. */+export type LinkedInstructionsFacts =+ | { source: 'native'; groupId: string; promptId: string }+ | { source: 'langfuse'; groupId: string; version: number };export type LinkedInstructionsUnavailableReason =| 'unavailable_selection'| 'blocked_content'| 'timeout'+ | 'disabled'| 'error';export type LinkedInstructionsResult =| { status: 'resolved'; prompt: string; facts: LinkedInstructionsFacts }| { status: 'unavailable'; reason: LinkedInstructionsUnavailableReason };-/**- * Resolves an agent's linked native prompt-group instructions. Usage is no- * longer recorded here — call `.recordUse(facts)` (below) once the caller's- * own initialization that used a `resolved` result has itself succeeded.- */+/** Deep-partial, so a config literal built by hand (tests, a partial override) stays+ * assignable without supplying every default `agentsEndpointSchema` applies on parse. */+export type LinkedInstructionsConfig = DeepPartial<+ NonNullable<TAgentsEndpoint['linkedInstructions']>+>;++/** Never records usage itself; call `.recordUse(facts)` once initialization succeeds. */export type ResolveLinkedInstructions = ((input: {link: AgentInstructionsPrompt;signal?: AbortSignal;filters?: FiltersConfig;- config?: { timeoutMs?: number; native?: { cacheTtlMs?: number } };+ config?: LinkedInstructionsConfig;}) => Promise<LinkedInstructionsResult>) & {/*** Records a usage generation for a resolved link's prompt group. The@@ -157,23 +158,19 @@ function errorName(error: unknown): string {return error instanceof Error ? error.name : typeof error;}-/**- * Agent links stay native only (`allowedSources: ['native']` on every `resolvePrompt`- * call in this module). `blocked_content` and `unavailable_selection` map directly, and- * `unsupported_source` — returned by that `allowedSources` check when a link's group- * has since become a Langfuse group — maps to `unavailable_selection`, the same reason- * a missing native selection gets. The remaining source-routing types- * (`unsupported_selection`, `source_unavailable`, `source_not_found`,- * `unsupported_content`) never reach a native-only caller and map to the generic- * `'error'` reason only as a fallback.- */+/** Every source-routing failure collapses to `unavailable_selection`. */function mapServiceErrorReason(type: PromptServiceError['type'],): LinkedInstructionsUnavailableReason {if (type === 'blocked_content' || type === 'unavailable_selection') {return type;}- if (type === 'unsupported_source') {+ if (+ type === 'unsupported_source' ||+ type === 'source_unavailable' ||+ type === 'source_not_found' ||+ type === 'unsupported_content'+ ) {return 'unavailable_selection';}return 'error';@@ -273,45 +270,7 @@ function cacheReadBudgetMs(timeoutMs: number): number {return Math.min(250, timeoutMs / 4);}-/**- * Builds the runtime resolver for an agent's linked native prompt-group- * instructions.- *- * Cache-first: a hit is checked under both policies — prompt-library and- * agent-instructions — with the caller's *current* filters (so a policy- * change blocks a previously-cached prompt) before being returned. A miss- * calls `resolvePrompt`, which already applies the prompt-library policy- * with the same filters, so the miss path checks only the- * agent-instructions policy and writes the cache only on success, while- * unaborted, and only when `cacheTtlMs > 0`. `cacheTtlMs === 0` skips the- * cache read entirely (and never writes).- *- * Latency is bounded by one shared deadline (`config.timeoutMs` from the- * moment `resolve` is called), not by re-arming a fresh timeout per phase —- * a slow or failed cache read spends part of that budget, and only what- * remains is left for `resolvePrompt`, so the worst case stays ~`timeoutMs`- * overall instead of doubling. The cache-read phase itself is additionally- * capped at `cacheReadBudgetMs` (at most 250ms, or a quarter of `timeoutMs`- * when that is smaller) so a *hung* cache read — one that never settles —- * cannot consume the entire deadline and starve `resolvePrompt` of its own- * chance to run; a cache read failure or timeout is logged and treated as a- * miss (falls through to `resolvePrompt`) rather than failing the turn — a- * cache outage must not drop instructions. The cache write itself never- * blocks the caller: it is fire-and-forget (errors caught and logged),- * issued only when unaborted.- *- * Abort is checked before work starts and after every await and always- * throws the signal's abort reason — it is never mapped to an `unavailable`- * result, and a cancelled call never writes the cache. Failures (timeout on- * the `resolvePrompt` phase, a thrown adapter error, or an unrecognized error- * from the content-policy check) resolve to `{ status: 'unavailable', reason- * }` — the resolution is never rejected by anything other than an abort.- * Logs never include prompt text — only the reason, groupId, and the error's- * name.- *- * The returned function never records prompt-group usage itself; call its- * `.recordUse(facts)` once the caller's own initialization succeeds.- */+/** Caches native links only. One deadline covers the cache read and `resolvePrompt`. */export function createLinkedInstructionsResolver(deps: CreateLinkedInstructionsResolverDeps,): ResolveLinkedInstructions {@@ -326,17 +285,23 @@ export function createLinkedInstructionsResolver(link: AgentInstructionsPrompt;signal?: AbortSignal;filters?: FiltersConfig;- config?: { timeoutMs?: number; native?: { cacheTtlMs?: number } };+ config?: LinkedInstructionsConfig;}): Promise<LinkedInstructionsResult> {signal?.throwIfAborted();+ if (link.source === 'langfuse' && config?.langfuse?.enabled !== true) {+ return { status: 'unavailable', reason: 'disabled' };+ }+const timeoutMs = config?.timeoutMs ?? DEFAULT_TIMEOUT_MS;const cacheTtlMs = config?.native?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;- const key = scopedCacheKey(buildCacheKey(link.groupId, link.selection));+ const useCache = link.source === 'native' && cacheTtlMs > 0;const deadline = Date.now() + timeoutMs;+ let key: string | undefined;let cached: CachedLinkedPrompt | undefined;- if (cacheTtlMs > 0) {+ if (useCache && link.source === 'native') {+ key = scopedCacheKey(buildCacheKey(link.groupId, link.selection));try {const cacheBudget = Math.min(remainingMs(deadline), cacheReadBudgetMs(timeoutMs));const raw = await runBounded(cache.get(key), cacheBudget, signal);@@ -391,27 +356,36 @@ export function createLinkedInstructionsResolver(};}- let fetched: NativeResolvedPrompt;+ // Built from `link` directly so narrowing on `source` also narrows `selection`.+ const reference: PromptReference =+ link.source === 'native'+ ? { source: 'native', selection: link.selection }+ : { source: 'langfuse', selection: link.selection };++ let fetched: ResolvedPrompt;try {const result = await runBounded(promptService.resolvePrompt({groupId: link.groupId,- selection: link.selection,+ ...reference,filters,- allowedSources: ['native'],}),remainingMs(deadline),signal,);signal?.throwIfAborted();if (!result.ok) {+ logger.warn('[linkedInstructions] resolvePrompt returned a failure result', {+ groupId: link.groupId,+ source: link.source,+ type: result.error.type,+ ...('reason' in result.error ? { reason: result.error.reason } : {}),+ });return { status: 'unavailable', reason: mapServiceErrorReason(result.error.type) };}- if (result.value.source !== 'native') {- /* allowedSources: ['native'] above means the service only ever resolves- * a native group here; this check narrows the type for the compiler- * and cannot be reached at runtime. */- return { status: 'unavailable', reason: 'error' };+ if (result.value.source !== link.source) {+ /* A mismatch means the link's group has since switched source, not a bug. */+ return { status: 'unavailable', reason: 'unavailable_selection' };}fetched = result.value;} catch (error) {@@ -422,6 +396,8 @@ export function createLinkedInstructionsResolver(logger.error('[linkedInstructions] resolvePrompt failed', {groupId: link.groupId,errorName: errorName(error),+ /* Log the stable `code`, never the message, which may echo upstream response text. */+ ...(error instanceof LangfusePromptRequestError ? { code: error.code } : {}),});return { status: 'unavailable', reason: 'error' };}@@ -434,7 +410,8 @@ export function createLinkedInstructionsResolver(};}- if (cacheTtlMs > 0 && !signal?.aborted) {+ if (useCache && key && !signal?.aborted && fetched.source === 'native') {+ /* Always true at runtime; kept to narrow `fetched` to `NativeResolvedPrompt` for the compiler. *//* Fire-and-forget: the turn must not wait on the cache write, and a* write failure is a cache-warmth loss, not a resolution failure. */cache@@ -457,10 +434,15 @@ export function createLinkedInstructionsResolver(}signal?.throwIfAborted();+ const facts: LinkedInstructionsFacts =+ fetched.source === 'native'+ ? { source: 'native', groupId: fetched.groupId, promptId: fetched.promptId }+ : { source: 'langfuse', groupId: fetched.groupId, version: fetched.version };+return {status: 'resolved',prompt: fetched.prompt,- facts: { source: 'native', groupId: fetched.groupId, promptId: fetched.promptId },+ facts,};};diff --git a/packages/api/src/agents/instructions/writes.spec.ts b/packages/api/src/agents/instructions/writes.spec.tsindex 9b6b96da7c..5823d44141 100644--- a/packages/api/src/agents/instructions/writes.spec.ts+++ b/packages/api/src/agents/instructions/writes.spec.ts@@ -127,6 +127,21 @@ describe('checkInstructionsPromptWrite', () => {expect(validateLinkWrite).toHaveBeenCalledWith(expect.objectContaining({ req }));});+ it('forwards linkedInstructions to validateLinkWrite unexamined', async () => {+ const validateLinkWrite = jest.fn(async () => ({ ok: true as const }));+ const linkedInstructions = { langfuse: { enabled: true } };+ await checkInstructionsPromptWrite({+ access: { validateLinkWrite },+ operation: 'create',+ user,+ previous: undefined,+ next: link,+ linkedInstructions,+ logger,+ });+ expect(validateLinkWrite).toHaveBeenCalledWith(expect.objectContaining({ linkedInstructions }));+ });+describe('an unexpected check failure', () => {it.each(['create', 'update'] as const)('returns the fixed 500 and logs safely when validateLinkWrite throws on %s',diff --git a/packages/api/src/agents/instructions/writes.ts b/packages/api/src/agents/instructions/writes.tsindex 62b22b842e..e6364b64c1 100644--- a/packages/api/src/agents/instructions/writes.ts+++ b/packages/api/src/agents/instructions/writes.ts@@ -11,6 +11,7 @@ import type {InstructionsPromptAccessRequest,} from './access';import type { InstructionsPromptLinkErrorResponse } from './errors';+import type { LinkedInstructionsConfig } from './linked';import { getInstructionsPromptLinkError, buildInstructionsPromptError } from './errors';import { isContentFilterError } from '~/middleware/contentFilter';import { isValidInstructionsPromptLink } from './linked';@@ -58,6 +59,7 @@ export async function checkInstructionsPromptWrite({previous,next,filters,+ linkedInstructions,logger,req,}: {@@ -67,6 +69,7 @@ export async function checkInstructionsPromptWrite({previous: AgentInstructionsPrompt | null | undefined;next: AgentInstructionsPrompt | null | undefined;filters?: FiltersConfig;+ linkedInstructions?: Pick<LinkedInstructionsConfig, 'langfuse'>;logger: InstructionsPromptAccessLogger;/** Forwarded unexamined to `access.validateLinkWrite` so its role lookup can reuse* the caller's per-request role cache. */@@ -82,6 +85,7 @@ export async function checkInstructionsPromptWrite({previous: previous ?? null,next,filters,+ linkedInstructions,req,});} catch (error) {diff --git a/packages/api/src/agents/lazySubagents.spec.ts b/packages/api/src/agents/lazySubagents.spec.tsindex 8a17d56284..dc4c4ed55d 100644--- a/packages/api/src/agents/lazySubagents.spec.ts+++ b/packages/api/src/agents/lazySubagents.spec.ts@@ -107,6 +107,27 @@ describe('getLazySubagentConfigId', () => {expect(getLazySubagentConfigId(linkedA)).not.toBe(getLazySubagentConfigId(linkedB));});+ it('changes when a linked Langfuse prompt pins a different version, even at the same groupId', () => {+ const pinnedV3 = {+ ...agent,+ instructionsPrompt: {+ source: 'langfuse' as const,+ groupId: 'group-a',+ selection: { type: 'exact' as const, version: 3 },+ },+ };+ const pinnedV4 = {+ ...agent,+ instructionsPrompt: {+ source: 'langfuse' as const,+ groupId: 'group-a',+ selection: { type: 'exact' as const, version: 4 },+ },+ };++ expect(getLazySubagentConfigId(pinnedV3)).not.toBe(getLazySubagentConfigId(pinnedV4));+ });+it('leaves the descriptor identity unchanged for an agent with no linked prompt', () => {const withoutLink = getLazySubagentConfigId(agent);const explicitlyUnset = getLazySubagentConfigId({ ...agent, instructionsPrompt: undefined });diff --git a/packages/api/src/agents/management.ts b/packages/api/src/agents/management.tsindex c2311185cd..d331b226e4 100644--- a/packages/api/src/agents/management.ts+++ b/packages/api/src/agents/management.ts@@ -11,8 +11,8 @@ const DEFAULT_LIST_LIMIT = 20;const MAX_CURSOR_LENGTH = 512;/**- * `instructionsPrompt` (the Builder's link to a native prompt group) is a Builder-only- * feature in this slice: the Management API never accepts or returns it, so every+ * `instructionsPrompt` (the Builder's link to a native or Langfuse prompt group) is a+ * Builder-only feature in this slice: the Management API never accepts or returns it, so every* Management type and schema below omits the field entirely, the same way an unknown* top-level field is rejected rather than silently stripped (see the note above* `agentManagementCreateSchema`).diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.tsindex 72b16a94cb..e4e8d3c63b 100644--- a/packages/api/src/agents/openai/service.ts+++ b/packages/api/src/agents/openai/service.ts@@ -231,8 +231,8 @@ interface InitializeAgentParams {*/resolveWebSearchGrant?: () => Promise<boolean>;/**- * Resolves this agent's `instructionsPrompt` link (a linked native prompt- * group). `initializeAgent` calls it only when the agent carries a+ * Resolves this agent's `instructionsPrompt` link (a linked native or Langfuse+ * prompt group). `initializeAgent` calls it only when the agent carries a* resolvable link; absent, a linked agent falls back to empty instructions* with a warning, since there is no default resolution path.*/diff --git a/packages/api/src/agents/validation.spec.ts b/packages/api/src/agents/validation.spec.tsindex 7af87e16fd..b0607fb51d 100644--- a/packages/api/src/agents/validation.spec.ts+++ b/packages/api/src/agents/validation.spec.ts@@ -150,6 +150,86 @@ describe('agent instructions-prompt link validation', () => {});it('rejects an unknown source', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'other',+ groupId: validGroupId,+ selection: { type: 'production' },+ },+ }).success,+ ).toBe(false);+ });++ it('accepts a Langfuse production selection', () => {+ const instructionsPrompt = {+ source: 'langfuse' as const,+ groupId: validGroupId,+ selection: { type: 'production' as const },+ };+ expect(agentCreateSchema.parse({ ...base, instructionsPrompt }).instructionsPrompt).toEqual(+ instructionsPrompt,+ );+ expect(agentUpdateSchema.parse({ instructionsPrompt }).instructionsPrompt).toEqual(+ instructionsPrompt,+ );+ });++ it('accepts a Langfuse exact-version selection', () => {+ const instructionsPrompt = {+ source: 'langfuse' as const,+ groupId: validGroupId,+ selection: { type: 'exact' as const, version: 3 },+ };+ expect(agentCreateSchema.parse({ ...base, instructionsPrompt }).instructionsPrompt).toEqual(+ instructionsPrompt,+ );+ });++ it.each([0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, '3'])(+ 'rejects an invalid Langfuse version: %j',+ (version) => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'langfuse',+ groupId: validGroupId,+ selection: { type: 'exact', version },+ },+ }).success,+ ).toBe(false);+ },+ );++ it('rejects a Langfuse link using the retired "version" selection type', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'langfuse',+ groupId: validGroupId,+ selection: { type: 'version', version: 3 },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects a Langfuse exact selection carrying a promptId', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'langfuse',+ groupId: validGroupId,+ selection: { type: 'exact', promptId: validPromptId },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects extra keys on a Langfuse link and on its selection', () => {expect(agentCreateSchema.safeParse({...base,@@ -157,6 +237,30 @@ describe('agent instructions-prompt link validation', () => {source: 'langfuse',groupId: validGroupId,selection: { type: 'production' },+ extra: true,+ },+ }).success,+ ).toBe(false);+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'langfuse',+ groupId: validGroupId,+ selection: { type: 'exact', version: 3, extra: true },+ },+ }).success,+ ).toBe(false);+ });++ it('rejects a native link with an exact selection carrying a version instead of a promptId', () => {+ expect(+ agentCreateSchema.safeParse({+ ...base,+ instructionsPrompt: {+ source: 'native',+ groupId: validGroupId,+ selection: { type: 'exact', version: 3 },},}).success,).toBe(false);diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.tsindex cadfffe4c7..e1569bbeab 100644--- a/packages/api/src/agents/validation.ts+++ b/packages/api/src/agents/validation.ts@@ -389,21 +389,44 @@ const agentGitIdentityUpdateSchema: z.ZodType<AgentGitIdentity | null | undefine/** A 24-character hexadecimal Mongo ObjectId string. */const objectIdStringSchema = z.string().refine(isValidObjectIdString);-/** Selects which revision of a linked prompt group an agent's instructions follow. */-const instructionsPromptSelectionSchema = z.discriminatedUnion('type', [+const nativeInstructionsPromptSelectionSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('production') }).strict(),z.object({ type: z.literal('exact'), promptId: objectIdStringSchema }).strict(),]);+const langfuseInstructionsPromptSelectionSchema = z.discriminatedUnion('type', [+ z.object({ type: z.literal('production') }).strict(),+ z+ .object({+ type: z.literal('exact'),+ version: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),+ })+ .strict(),+]);+/** Links an agent's instructions to a native LibreChat prompt group revision. */-export const agentInstructionsPromptSchema: z.ZodType<AgentInstructionsPrompt> = z+const nativeAgentInstructionsPromptSchema = z.object({source: z.literal('native'),groupId: objectIdStringSchema,- selection: instructionsPromptSelectionSchema,+ selection: nativeInstructionsPromptSelectionSchema,+ })+ .strict();++const langfuseAgentInstructionsPromptSchema = z+ .object({+ source: z.literal('langfuse'),+ groupId: objectIdStringSchema,+ selection: langfuseInstructionsPromptSelectionSchema,}).strict();+export const agentInstructionsPromptSchema: z.ZodType<AgentInstructionsPrompt> =+ z.discriminatedUnion('source', [+ nativeAgentInstructionsPromptSchema,+ langfuseAgentInstructionsPromptSchema,+ ]);+/** Shared field schema: `.nullable().optional()` per contract, `null` removes the link. */const agentInstructionsPromptFieldSchema: z.ZodOptional<z.ZodNullable<typeof agentInstructionsPromptSchema>diff --git a/packages/api/src/endpoints/config/endpoints.spec.ts b/packages/api/src/endpoints/config/endpoints.spec.tsindex 843fa09250..19b66a25ae 100644--- a/packages/api/src/endpoints/config/endpoints.spec.ts+++ b/packages/api/src/endpoints/config/endpoints.spec.ts@@ -203,6 +203,55 @@ describe('createEndpointsConfigService', () => {},);+ describe('linkedInstructions.langfuse.enabled', () => {+ it('defaults to false when omitted from the agents config', async () => {+ const deps = createMockDeps({+ loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({+ [EModelEndpoint.agents]: { userProvide: false, order: 0 },+ }),+ getAppConfig: jest+ .fn()+ .mockResolvedValue(appConfig({ endpoints: { [EModelEndpoint.agents]: {} } })),+ });+ const { getEndpointsConfig } = createEndpointsConfigService(deps);+ const result = await getEndpointsConfig(fakeReq());++ expect(result?.[EModelEndpoint.agents]?.linkedInstructions).toEqual({+ langfuse: { enabled: false },+ });+ });++ it.each([true, false])(+ 'copies the switch through as configured (enabled=%s)',+ async (enabled) => {+ const deps = createMockDeps({+ loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({+ [EModelEndpoint.agents]: { userProvide: false, order: 0 },+ }),+ getAppConfig: jest.fn().mockResolvedValue(+ appConfig({+ endpoints: {+ [EModelEndpoint.agents]: {+ linkedInstructions: {+ timeoutMs: 5_000,+ native: { cacheTtlMs: 60_000 },+ langfuse: { enabled },+ },+ },+ },+ }),+ ),+ });+ const { getEndpointsConfig } = createEndpointsConfigService(deps);+ const result = await getEndpointsConfig(fakeReq());++ expect(result?.[EModelEndpoint.agents]?.linkedInstructions).toEqual({+ langfuse: { enabled },+ });+ },+ );+ });+it('exposes the deployment stateful environment allowlist', async () => {const deps = createMockDeps({loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({diff --git a/packages/api/src/endpoints/config/endpoints.ts b/packages/api/src/endpoints/config/endpoints.tsindex 4a7625d2b7..bbcbace958 100644--- a/packages/api/src/endpoints/config/endpoints.ts+++ b/packages/api/src/endpoints/config/endpoints.ts@@ -90,6 +90,7 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {statefulCodeSessions,maxSubagents,fileSharing,+ linkedInstructions,} = appConfig.endpoints[EModelEndpoint.agents];const toolApproval = appConfig.endpoints[EModelEndpoint.agents].toolApproval;/** Only advertise Accept edits when the endpoint fallback cannot force every@@ -141,6 +142,10 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {statefulCodeSessions: clientStatefulCodeSessions,maxSubagents,fileSharing,+ /** Only the switch reaches the client; the budget/cache fields stay server-side. */+ linkedInstructions: {+ langfuse: { enabled: linkedInstructions?.langfuse?.enabled === true },+ },toolApproval: {enabled: toolApproval?.enabled === true,agentModes: toolApproval?.enabled === true && toolApproval.agentModes === true,diff --git a/packages/api/src/langfuse/prompts.spec.ts b/packages/api/src/langfuse/prompts.spec.tsindex 3e54cf43d7..828907d291 100644--- a/packages/api/src/langfuse/prompts.spec.ts+++ b/packages/api/src/langfuse/prompts.spec.ts@@ -165,6 +165,47 @@ describe('listLangfusePrompts', () => {]);});+ it('composes nameEquals into filter and also sends it as the plain name param', async () => {+ const conn = makeConnection();+ fetchMock.mockResolvedValue(+ jsonResponse({ data: [], meta: { page: 1, limit: 1, totalItems: 0, totalPages: 0 } }),+ );++ await listLangfusePrompts(+ conn,+ { nameEquals: 'greeting', page: 1, limit: 1 },+ { timeoutMs: 5000 },+ );++ const [url] = fetchMock.mock.calls[0];+ const parsedUrl = new URL(url as string);+ expect(parsedUrl.searchParams.get('name')).toBe('greeting');+ expect(JSON.parse(parsedUrl.searchParams.get('filter') as string)).toEqual([+ { type: 'string', column: 'name', operator: '=', value: 'greeting' },+ ]);+ });++ it('ANDs nameEquals and type into one filter array, in that order, keeping the name param', async () => {+ const conn = makeConnection();+ fetchMock.mockResolvedValue(+ jsonResponse({ data: [], meta: { page: 1, limit: 1, totalItems: 0, totalPages: 0 } }),+ );++ await listLangfusePrompts(+ conn,+ { nameEquals: 'greeting', type: 'text', page: 1, limit: 1 },+ { timeoutMs: 5000 },+ );++ const [url] = fetchMock.mock.calls[0];+ const parsedUrl = new URL(url as string);+ expect(parsedUrl.searchParams.get('name')).toBe('greeting');+ expect(JSON.parse(parsedUrl.searchParams.get('filter') as string)).toEqual([+ { type: 'string', column: 'name', operator: '=', value: 'greeting' },+ { type: 'string', column: 'type', operator: '=', value: 'text' },+ ]);+ });+it('sends tag, fromUpdatedAt and toUpdatedAt as given', async () => {const conn = makeConnection();fetchMock.mockResolvedValue(diff --git a/packages/api/src/langfuse/prompts.ts b/packages/api/src/langfuse/prompts.tsindex 3aaff7cf42..da618f49d9 100644--- a/packages/api/src/langfuse/prompts.ts+++ b/packages/api/src/langfuse/prompts.ts@@ -24,6 +24,8 @@ export type LangfusePromptConnection = {export type LangfusePromptListQuery = {name?: string;+ /** Also sent as `name` for Langfuse servers without `filter` support. */+ nameEquals?: string;label?: string;tag?: string;type?: 'text' | 'chat';@@ -238,31 +240,35 @@ function appendDefined(}}-/**- * Lists prompt metadata from Langfuse. Query params are sent as-is, only those- * defined; every prompt type — including `chat` — is returned unless `type`- * is given. `type` is not a Langfuse query param itself: it is serialized as- * the `filter` parameter, the shape the Langfuse list endpoint expects for a- * column filter. `filter` is omitted entirely when `type` is unset.- */+/** `type` and `nameEquals` combine into `filter`, which Langfuse applies ahead of `name`/`label`/`tag`. */export async function listLangfusePrompts(conn: LangfusePromptConnection,query: LangfusePromptListQuery,{ timeoutMs }: { timeoutMs: number },): Promise<TLangfusePromptListResponse> {const params = new URLSearchParams();- appendDefined(params, 'name', query.name);+ appendDefined(params, 'name', query.nameEquals ?? query.name);appendDefined(params, 'label', query.label);appendDefined(params, 'tag', query.tag);appendDefined(params, 'page', query.page);appendDefined(params, 'limit', query.limit);appendDefined(params, 'fromUpdatedAt', query.fromUpdatedAt);appendDefined(params, 'toUpdatedAt', query.toUpdatedAt);+ const filterConditions: Array<{ type: 'string'; column: string; operator: '='; value: string }> =+ [];+ if (query.nameEquals != null) {+ filterConditions.push({+ type: 'string',+ column: 'name',+ operator: '=',+ value: query.nameEquals,+ });+ }if (query.type != null) {- params.set(- 'filter',- JSON.stringify([{ type: 'string', column: 'type', operator: '=', value: query.type }]),- );+ filterConditions.push({ type: 'string', column: 'type', operator: '=', value: query.type });+ }+ if (filterConditions.length > 0) {+ params.set('filter', JSON.stringify(filterConditions));}const search = params.size > 0 ? `?${params.toString()}` : '';diff --git a/packages/api/src/openapi/agents.ts b/packages/api/src/openapi/agents.tsindex bb87bbd279..1db83cb53a 100644--- a/packages/api/src/openapi/agents.ts+++ b/packages/api/src/openapi/agents.ts@@ -48,8 +48,8 @@ function withDocumentedEdges(schema: ZodTypeAny): ZodTypeAny {}/**- * `instructionsPrompt` (the Builder's link to a native prompt group) is Builder-only: the- * Management API's create/update/response schemas omit it entirely (see+ * `instructionsPrompt` (the Builder's link to a native or Langfuse prompt group) is+ * Builder-only: the Management API's create/update/response schemas omit it entirely (see* `packages/api/src/agents/management.ts`), so this document never carries the field —* neither the full link shape a request could send nor the restricted stub a Builder* response can carry (`packages/api/src/agents/instructions/access.ts`).diff --git a/packages/api/src/prompts/handlers.spec.ts b/packages/api/src/prompts/handlers.spec.tsindex fa2076682f..38f559b0af 100644--- a/packages/api/src/prompts/handlers.spec.ts+++ b/packages/api/src/prompts/handlers.spec.ts@@ -50,6 +50,9 @@ function mockRes(): Response & MockRes {function makeService(overrides: Partial<PromptService> = {}): PromptService {return {resolvePrompt: jest.fn(),+ // Defaults to native so tests that don't set a source still reach resolvePrompt.+ readPromptGroup: jest.fn().mockResolvedValue({ _id: groupId, source: 'native' }),+ listRevisions: jest.fn(),getListPromptGroupsByAccess: jest.fn(),getPrompts: jest.fn().mockResolvedValue([]),createPromptGroup: jest.fn(),@@ -583,30 +586,70 @@ describe('createPromptHandlers resolvePrompt', () => {jest.restoreAllMocks();});- function resolveReq(version?: string): PromptRequest {- return mockReq({ params: { groupId }, query: version == null ? {} : { version } });+ function resolveReq(version?: string, group?: { source: 'native' | 'langfuse' }): PromptRequest {+ return mockReq({+ params: { groupId },+ query: version == null ? {} : { version },+ resourceAccess: group ? { resourceInfo: { _id: groupId, ...group } } : undefined,+ });}- it('resolves production when no version is given', async () => {+ it('resolves production when no version is given, for a preloaded native group', async () => {const resolvePrompt = jest.fn().mockResolvedValue({ok: true,value: { source: 'native', groupId, promptId, prompt: 'Hi', type: 'text' },});- const handlers = createPromptHandlers(makeDeps({ service: makeService({ resolvePrompt }) }));+ const readPromptGroup = jest.fn();+ const handlers = createPromptHandlers(+ makeDeps({ service: makeService({ resolvePrompt, readPromptGroup }) }),+ );const res = mockRes();- await handlers.resolvePrompt(resolveReq(), res);+ await handlers.resolvePrompt(resolveReq(undefined, { source: 'native' }), res);+ expect(readPromptGroup).not.toHaveBeenCalled();expect(resolvePrompt).toHaveBeenCalledWith({groupId,+ source: 'native',selection: { type: 'production' },- loadedGroup: undefined,+ loadedGroup: { _id: groupId, source: 'native' },filters: undefined,});expect(res.statusCode).toBe(200);expect(res.body).toEqual({ source: 'native', groupId, promptId, prompt: 'Hi', type: 'text' });});+ it('resolves production when no version is given, for a preloaded Langfuse group', async () => {+ const resolvePrompt = jest.fn().mockResolvedValue({+ ok: true,+ value: {+ source: 'langfuse',+ groupId,+ prompt: 'Hi',+ type: 'text',+ version: 5,+ labels: ['production'],+ },+ });+ const readPromptGroup = jest.fn();+ const handlers = createPromptHandlers(+ makeDeps({ service: makeService({ resolvePrompt, readPromptGroup }) }),+ );+ const res = mockRes();++ await handlers.resolvePrompt(resolveReq(undefined, { source: 'langfuse' }), res);++ expect(readPromptGroup).not.toHaveBeenCalled();+ expect(resolvePrompt).toHaveBeenCalledWith({+ groupId,+ source: 'langfuse',+ selection: { type: 'production' },+ loadedGroup: { _id: groupId, source: 'langfuse' },+ filters: undefined,+ });+ expect(res.statusCode).toBe(200);+ });+it('resolves an exact version for a Langfuse group', async () => {const resolvePrompt = jest.fn().mockResolvedValue({ok: true,@@ -621,13 +664,15 @@ describe('createPromptHandlers resolvePrompt', () => {});const handlers = createPromptHandlers(makeDeps({ service: makeService({ resolvePrompt }) }));const res = mockRes();+ const loadedGroupRecord = { _id: groupId, source: 'langfuse' as const };- await handlers.resolvePrompt(resolveReq('3'), res);+ await handlers.resolvePrompt(resolveReq('3', { source: 'langfuse' }), res);expect(resolvePrompt).toHaveBeenCalledWith({groupId,- selection: { type: 'version', version: 3 },- loadedGroup: undefined,+ source: 'langfuse',+ selection: { type: 'exact', version: 3 },+ loadedGroup: loadedGroupRecord,filters: undefined,});expect(res.statusCode).toBe(200);@@ -641,6 +686,76 @@ describe('createPromptHandlers resolvePrompt', () => {});});+ it('reads the group once when a capability bypass left no loaded group, then resolves its production', async () => {+ const readPromptGroup = jest.fn().mockResolvedValue({ _id: groupId, source: 'langfuse' });+ const resolvePrompt = jest.fn().mockResolvedValue({+ ok: true,+ value: { source: 'langfuse', groupId, prompt: 'Hi', type: 'text', version: 5, labels: [] },+ });+ const handlers = createPromptHandlers(+ makeDeps({ service: makeService({ readPromptGroup, resolvePrompt }) }),+ );+ const res = mockRes();++ // No resourceAccess, as a MANAGE_PROMPTS capability bypass leaves it.+ await handlers.resolvePrompt(resolveReq(), res);++ expect(readPromptGroup).toHaveBeenCalledWith(groupId);+ expect(resolvePrompt).toHaveBeenCalledTimes(1);+ expect(resolvePrompt).toHaveBeenCalledWith({+ groupId,+ source: 'langfuse',+ selection: { type: 'production' },+ loadedGroup: { _id: groupId, source: 'langfuse' },+ filters: undefined,+ });+ expect(res.statusCode).toBe(200);+ });++ it('rejects ?version=N with 400 once a capability-bypassed read confirms the group is native', async () => {+ const readPromptGroup = jest.fn().mockResolvedValue({ _id: groupId, source: 'native' });+ const resolvePrompt = jest.fn();+ const handlers = createPromptHandlers(+ makeDeps({ service: makeService({ readPromptGroup, resolvePrompt }) }),+ );+ const res = mockRes();++ await handlers.resolvePrompt(resolveReq('2'), res);++ expect(readPromptGroup).toHaveBeenCalledWith(groupId);+ expect(res.statusCode).toBe(400);+ expect(res.body).toEqual({ code: 'invalid_request' });+ expect(resolvePrompt).not.toHaveBeenCalled();+ });++ it('maps a capability-bypassed read of a missing group to the same 404 as a missing selection', async () => {+ const readPromptGroup = jest.fn().mockResolvedValue(null);+ const resolvePrompt = jest.fn();+ const handlers = createPromptHandlers(+ makeDeps({ service: makeService({ readPromptGroup, resolvePrompt }) }),+ );+ const res = mockRes();++ await handlers.resolvePrompt(resolveReq(), res);++ expect(readPromptGroup).toHaveBeenCalledWith(groupId);+ expect(res.statusCode).toBe(404);+ expect(res.body).toEqual({ code: 'not_found' });+ expect(resolvePrompt).not.toHaveBeenCalled();+ });++ it('rejects ?version=N on a native group with 400 invalid_request, without calling the service', async () => {+ const resolvePrompt = jest.fn();+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ resolvePrompt }) }));+ const res = mockRes();++ await handlers.resolvePrompt(resolveReq('2', { source: 'native' }), res);++ expect(res.statusCode).toBe(400);+ expect(res.body).toEqual({ code: 'invalid_request' });+ expect(resolvePrompt).not.toHaveBeenCalled();+ });+it.each(['0', '-1', '1.5', 'abc'])('rejects an invalid version %s without calling the service',async (version) => {@@ -682,20 +797,6 @@ describe('createPromptHandlers resolvePrompt', () => {expect(resolvePrompt).not.toHaveBeenCalled();});- it('maps a native group rejecting ?version to 400 invalid_request', async () => {- const resolvePrompt = jest.fn().mockResolvedValue({- ok: false,- error: { type: 'unsupported_selection', source: 'native' },- });- const handlers = createPromptHandlers(makeDeps({ service: makeService({ resolvePrompt }) }));- const res = mockRes();-- await handlers.resolvePrompt(resolveReq('2'), res);-- expect(res.statusCode).toBe(400);- expect(res.body).toEqual({ code: 'invalid_request' });- });-it('maps blocked_content to the shared content filter response', async () => {const finding = {detectorId: 'pii-pattern',@@ -806,7 +907,6 @@ describe('createPromptHandlers resolvePrompt', () => {await handlers.resolvePrompt(resolveReq(), res);expect(res.statusCode).toBe(502);- expect(res.statusCode).not.toBe(401);expect(res.body).toEqual({ code: 'unauthorized' });expect(errorSpy).toHaveBeenCalled();});@@ -918,6 +1018,182 @@ describe('createPromptHandlers resolvePrompt', () => {});});+describe('createPromptHandlers listRevisions', () => {+ afterEach(() => {+ jest.restoreAllMocks();+ });++ function revisionsReq(): PromptRequest {+ return mockReq({ params: { groupId } });+ }++ it('lists revisions and calls the service without filters or a selection', async () => {+ const listed = {+ source: 'native' as const,+ groupId,+ revisions: [{ source: 'native' as const, promptId, version: 1, isProduction: true }],+ };+ const listRevisions = jest.fn().mockResolvedValue({ ok: true, value: listed });+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(listRevisions).toHaveBeenCalledWith({ groupId, loadedGroup: undefined });+ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual(listed);+ });++ it('does not increment usage', async () => {+ const incrementPromptGroupUsage = jest.fn();+ const listRevisions = jest.fn().mockResolvedValue({+ ok: true,+ value: { source: 'native', groupId, revisions: [] },+ });+ const handlers = createPromptHandlers(+ makeDeps({ service: makeService({ listRevisions, incrementPromptGroupUsage }) }),+ );+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(incrementPromptGroupUsage).not.toHaveBeenCalled();+ });++ it('maps a missing group (unavailable_selection) to 404 not_found', async () => {+ const listRevisions = jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'unavailable_selection', reason: 'revision' },+ });+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(404);+ expect(res.body).toEqual({ code: 'not_found' });+ });++ it('maps source_not_found to 404 with the Langfuse message', async () => {+ const listRevisions = jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'source_not_found', source: 'langfuse' },+ });+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(404);+ expect(res.body).toEqual({ code: 'not_found', message: 'Prompt not found in Langfuse' });+ });++ it('maps unsupported_content to 422 unsupported_type', async () => {+ const listRevisions = jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'unsupported_content', reason: 'chat_prompt' },+ });+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(422);+ expect(res.body).toEqual({ code: 'unsupported_type' });+ });++ it.each([+ ['disabled', 404, { code: 'not_available' }],+ ['not_configured', 409, { code: 'not_configured' }],+ ['source_changed', 409, { code: 'source_changed' }],+ ] as const)('maps source_unavailable reason %s to %i %j', async (reason, status, body) => {+ const listRevisions = jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason },+ });+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(status);+ expect(res.body).toEqual(body);+ });++ it('falls back to the shared sendResolveRejection default for an unlisted error variant such as unsupported_source', async () => {+ const listRevisions = jest.fn().mockResolvedValue({+ ok: false,+ error: { type: 'unsupported_source', source: 'native' },+ });+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ // An unmapped error type falls through to the generic 500.+ expect(res.statusCode).toBe(500);+ expect(res.body).toEqual({ message: 'Error resolving prompt' });+ });++ it('maps a thrown Langfuse timeout to 504', async () => {+ jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const listRevisions = jest+ .fn()+ .mockRejectedValue(new LangfusePromptRequestError('timeout', 'Langfuse request timed out'));+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(504);+ expect(res.body).toEqual({ code: 'timeout' });+ });++ it('maps a thrown Langfuse 401 to 502, never 401', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const listRevisions = jest+ .fn()+ .mockRejectedValue(+ new LangfusePromptRequestError('unauthorized', 'Langfuse responded with 401', 401),+ );+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(502);+ expect(res.body).toEqual({ code: 'unauthorized' });+ expect(errorSpy).toHaveBeenCalled();+ });++ it('maps a thrown read PromptStoreError to 404 not_found', async () => {+ jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const listRevisions = jest+ .fn()+ .mockRejectedValue(new PromptStoreError('read', new Error('db down')));+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(404);+ expect(res.body).toEqual({ code: 'not_found' });+ });++ it('returns 500 for an unexpected thrown error', async () => {+ const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);+ const listRevisions = jest.fn().mockRejectedValue(new Error('database unavailable'));+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ listRevisions }) }));+ const res = mockRes();++ await handlers.listRevisions(revisionsReq(), res);++ expect(res.statusCode).toBe(500);+ expect(res.body).toEqual({ message: 'Error listing prompt revisions' });+ expect(errorSpy).toHaveBeenCalledWith('Error listing prompt revisions', { type: 'Error' });+ });+});+describe('toResolveResponse', () => {const langfuseValue: ResolvedPrompt = {source: 'langfuse',diff --git a/packages/api/src/prompts/handlers.ts b/packages/api/src/prompts/handlers.tsindex 8ca43bfaf8..8a4398ce1a 100644--- a/packages/api/src/prompts/handlers.ts+++ b/packages/api/src/prompts/handlers.ts@@ -6,10 +6,11 @@ import {SystemRoles,DEFAULT_CACHE_CLEAR_TIMEOUT_MS,} from 'librechat-data-provider';+import type { TPromptGroupSource } from 'librechat-data-provider';import type { Response } from 'express';import type {PromptGroupRecord,- PromptSelection,+ PromptReference,PromptServiceError,ResolvedPrompt,StoredId,@@ -67,6 +68,7 @@ export interface PromptHandlersDeps {export interface PromptHandlers {getPromptGroup: PromptHandler;resolvePrompt: PromptHandler;+ listRevisions: PromptHandler;listAllPromptGroups: PromptHandler;listPromptGroups: PromptHandler;createPromptGroup: PromptHandler;@@ -137,19 +139,11 @@ export function toResolveResponse(return rest;}-/**- * Maps a `resolvePrompt` rejection to its `/resolve` response. `unsupported_source` only- * comes from the `allowedSources` check, which this route never passes, and- * `invalid_input`/`unsupported` belong to other operations; none of the three can reach- * here through this route, so they fall through to the generic 500 like any other- * unexpected failure.- */+/** Maps a `resolvePrompt` or `listRevisions` rejection to its HTTP response. */function sendResolveRejection(res: Response, error: PromptServiceError): Response {switch (error.type) {case 'blocked_content':return res.status(400).send(contentFilterBlockResponse(error.finding));- case 'unsupported_selection':- return res.status(400).send({ code: 'invalid_request' });case 'unavailable_selection':return res.status(404).send({ code: 'not_found' });case 'source_not_found':@@ -249,6 +243,8 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {* Resolves a group's content for either source: native resolves `production`* (the only selection it accepts), and Langfuse fetches live, by the `production`* label or an exact `version`. Usage is not recorded here — `/use` already does.+ *+ * Reads the group first because `source` decides which reference shape to build.*/async resolvePrompt(req, res) {const groupId = param(req, 'groupId');@@ -258,15 +254,30 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {if (!parsedVersion.success) {return res.status(400).send({ code: 'invalid_request' });}- const selection: PromptSelection =- parsedVersion.data == null- ? { type: 'production' }- : { type: 'version', version: parsedVersion.data };+ const version = parsedVersion.data;+ const buildReference = (source: TPromptGroupSource): PromptReference | null => {+ if (version == null) {+ return source === 'langfuse'+ ? { source: 'langfuse', selection: { type: 'production' } }+ : { source: 'native', selection: { type: 'production' } };+ }+ return source === 'langfuse'+ ? { source: 'langfuse', selection: { type: 'exact', version } }+ : null;+ };try {+ const group = loadedGroup(req) ?? (await service.readPromptGroup(groupId));+ if (group == null) {+ return res.status(404).send({ code: 'not_found' });+ }+ const reference = buildReference(group.source);+ if (reference == null) {+ return res.status(400).send({ code: 'invalid_request' });+ }const result = await service.resolvePrompt({groupId,- selection,- loadedGroup: loadedGroup(req),+ ...reference,+ loadedGroup: group,filters: req.config?.filters,});if (!result.ok) {@@ -289,6 +300,29 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {}},+ /** Never increments usage. */+ async listRevisions(req, res) {+ const groupId = param(req, 'groupId');+ try {+ const result = await service.listRevisions({ groupId, loadedGroup: loadedGroup(req) });+ if (!result.ok) {+ return sendResolveRejection(res, result.error);+ }+ return res.status(200).send(result.value);+ } catch (error) {+ if (error instanceof LangfusePromptRequestError) {+ logger.error('[prompts] Langfuse request failed while listing prompt revisions', error);+ const { status, body } = toLangfusePromptErrorResponse(error);+ return res.status(status).send(body);+ }+ logger.error('Error listing prompt revisions', getSafeErrorMetadata(error));+ if (isPromptStoreError(error, 'read')) {+ return res.status(404).send({ code: 'not_found' });+ }+ return res.status(500).send({ message: 'Error listing prompt revisions' });+ }+ },+async listAllPromptGroups(req, res) {try {const result = await service.getListPromptGroupsByAccess({diff --git a/packages/api/src/prompts/langfuse.spec.ts b/packages/api/src/prompts/langfuse.spec.tsindex 9d6e037d06..2a48e76b57 100644--- a/packages/api/src/prompts/langfuse.spec.ts+++ b/packages/api/src/prompts/langfuse.spec.ts@@ -160,7 +160,7 @@ describe('createLangfusePromptAdapter', () => {});});- it('sends version=N and no label for a version selection', async () => {+ it('sends version=N and no label for an exact selection', async () => {const resolveSource = jest.fn().mockResolvedValue(okResolution());const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });fetchMock.mockResolvedValue(@@ -169,7 +169,7 @@ describe('createLangfusePromptAdapter', () => {const result = await adapter.resolvePrompt({group: makeGroup(),- selection: { type: 'version', version: 3 },+ selection: { type: 'exact', version: 3 },});const [url] = fetchMock.mock.calls[0];@@ -226,23 +226,6 @@ describe('createLangfusePromptAdapter', () => {expect(result).toEqual({ ok: false, error: { type: 'source_not_found', source: 'langfuse' } });});- it('returns unsupported_selection for an exact selection without calling resolveSource or fetch', async () => {- const resolveSource = jest.fn();- const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });-- const result = await adapter.resolvePrompt({- group: makeGroup(),- selection: { type: 'exact', promptId: 'prompt-1' },- });-- expect(result).toEqual({- ok: false,- error: { type: 'unsupported_selection', source: 'langfuse' },- });- expect(resolveSource).not.toHaveBeenCalled();- expect(fetchMock).not.toHaveBeenCalled();- });-it('returns source_unavailable not_configured when the group has no sourcePromptName, without calling resolveSource or fetch', async () => {const resolveSource = jest.fn();const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });@@ -329,4 +312,176 @@ describe('createLangfusePromptAdapter', () => {expect(result).toMatchObject({ ok: true });timeoutSpy.mockRestore();});++ describe('listRevisions', () => {+ function listResponse(+ items: Array<{+ name?: string;+ type?: 'text' | 'chat';+ versions?: number[];+ }>,+ totalItems: number,+ ) {+ return jsonResponse({+ data: items.map((item) => ({+ name: 'greeting',+ type: 'text',+ versions: [1],+ labels: [],+ tags: [],+ lastUpdatedAt: '2026-01-01T00:00:00.000Z',+ ...item,+ })),+ meta: { page: 1, limit: 1, totalItems, totalPages: 1 },+ });+ }++ it('sends a filter with the name condition only, page 1 and limit 1, no type', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(listResponse([{ versions: [1, 2, 3] }], 1));++ await adapter.listRevisions({ group: makeGroup() });++ const [url] = fetchMock.mock.calls[0];+ const parsedUrl = new URL(url as string);+ expect(parsedUrl.searchParams.get('page')).toBe('1');+ expect(parsedUrl.searchParams.get('limit')).toBe('1');+ expect(parsedUrl.searchParams.get('name')).toBe('greeting');+ expect(JSON.parse(parsedUrl.searchParams.get('filter') as string)).toEqual([+ { type: 'string', column: 'name', operator: '=', value: 'greeting' },+ ]);+ });++ it('forwards the configured timeout to listPrompts', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 7000 });+ fetchMock.mockResolvedValue(listResponse([{ versions: [1] }], 1));+ const timeoutSpy = jest.spyOn(AbortSignal, 'timeout');++ await adapter.listRevisions({ group: makeGroup() });++ expect(timeoutSpy).toHaveBeenCalledWith(7000);+ timeoutSpy.mockRestore();+ });++ it('lists versions newest first for a matched text prompt', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(listResponse([{ versions: [1, 3, 2] }], 1));++ const result = await adapter.listRevisions({ group: makeGroup() });++ expect(result).toEqual({+ ok: true,+ value: {+ source: 'langfuse',+ groupId: 'group-1',+ revisions: [+ { source: 'langfuse', version: 3 },+ { source: 'langfuse', version: 2 },+ { source: 'langfuse', version: 1 },+ ],+ },+ });+ });++ it('returns source_not_found when no items and totalItems is 0', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(listResponse([], 0));++ const result = await adapter.listRevisions({ group: makeGroup() });++ expect(result).toEqual({+ ok: false,+ error: { type: 'source_not_found', source: 'langfuse' },+ });+ });++ it('returns unsupported_content chat_prompt for a matched chat prompt', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(listResponse([{ type: 'chat', versions: [1] }], 1));++ const result = await adapter.listRevisions({ group: makeGroup() });++ expect(result).toEqual({+ ok: false,+ error: { type: 'unsupported_content', reason: 'chat_prompt' },+ });+ });++ it('returns source_unavailable not_configured when the group has no sourcePromptName, without fetching', async () => {+ const resolveSource = jest.fn();+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });++ const result = await adapter.listRevisions({+ group: makeGroup({ sourcePromptName: undefined }),+ });++ expect(result).toEqual({+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason: 'not_configured' },+ });+ expect(resolveSource).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it.each(['disabled', 'not_configured', 'source_changed'] as const)(+ 'passes a resolveSource %s reason through as source_unavailable, without fetching',+ async (reason) => {+ const resolveSource = jest.fn().mockResolvedValue({ ok: false, reason });+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });++ const result = await adapter.listRevisions({ group: makeGroup() });++ expect(result).toEqual({+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason },+ });+ expect(fetchMock).not.toHaveBeenCalled();+ },+ );++ it('propagates a thrown LangfusePromptRequestError from the list request', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(new Response(null, { status: 401 }));++ expect.assertions(2);+ try {+ await adapter.listRevisions({ group: makeGroup() });+ } catch (error) {+ expect(error).toBeInstanceOf(LangfusePromptRequestError);+ expect(error).toMatchObject({ code: 'unauthorized' });+ }+ });++ it.each<[string, Array<{ name?: string; versions?: number[] }>, number]>([+ ['a returned name that differs from sourcePromptName', [{ name: 'other', versions: [1] }], 1],+ ['totalItems greater than 1 despite one item', [{ versions: [1] }], 2],+ ['items present but totalItems is 0', [{ versions: [1] }], 0],+ ['no items despite totalItems greater than 0', [], 1],+ ['a matched text prompt with no versions', [{ versions: [] }], 1],+ ])('throws invalid_response for %s', async (_label, items, totalItems) => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(listResponse(items, totalItems));++ await expect(adapter.listRevisions({ group: makeGroup() })).rejects.toMatchObject({+ code: 'invalid_response',+ });+ });++ it('does not include credentials or a URL in a successful result', async () => {+ const resolveSource = jest.fn().mockResolvedValue(okResolution());+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });+ fetchMock.mockResolvedValue(listResponse([{ versions: [1] }], 1));++ const result = await adapter.listRevisions({ group: makeGroup() });++ expect(JSON.stringify(result)).not.toMatch(/authorization|cloud\.langfuse\.test/i);+ });+ });});diff --git a/packages/api/src/prompts/langfuse.ts b/packages/api/src/prompts/langfuse.tsindex 42c2b2311b..233a080bd8 100644--- a/packages/api/src/prompts/langfuse.ts+++ b/packages/api/src/prompts/langfuse.ts@@ -1,8 +1,13 @@+import type { LangfusePromptSelection } from 'librechat-data-provider';import type { LangfuseSourceGroup, LangfuseSourceResolution } from '../langfuse/promptSync';import type { LangfuseTextPromptSelector } from '../langfuse/prompts';import type { PromptSourceAdapter } from './types';+import {+ getLangfuseTextPrompt,+ listLangfusePrompts,+ LangfusePromptRequestError,+} from '../langfuse/prompts';import { getLangfusePromptSyncTimeoutMs } from '../langfuse/policy';-import { getLangfuseTextPrompt } from '../langfuse/prompts';import { getLangfusePromptUrl } from '../langfuse/links';export interface CreateLangfusePromptAdapterDependencies {@@ -12,12 +17,14 @@ export interface CreateLangfusePromptAdapterDependencies {* `source_changed` on a mismatch. Its failure reasons pass straight through. */readonly resolveSource: (group: LangfuseSourceGroup) => Promise<LangfuseSourceResolution>;readonly getTextPrompt?: typeof getLangfuseTextPrompt;+ readonly listPrompts?: typeof listLangfusePrompts;readonly timeoutMs?: () => number;}/*** A read-only content source for a group whose `source` is `langfuse`: it fetches the* group's text prompt from Langfuse on every call, with no cache and no mutations.+ * `listRevisions` instead lists its versions, metadata only, with no cache either.** Langfuse resolves a composed prompt's `@@@langfusePrompt:…@@@` references* server-side (`resolve` defaults to `true`), so no code is needed here for that: an@@ -30,13 +37,11 @@ export interface CreateLangfusePromptAdapterDependencies {export function createLangfusePromptAdapter({resolveSource,getTextPrompt = getLangfuseTextPrompt,+ listPrompts = listLangfusePrompts,timeoutMs = getLangfusePromptSyncTimeoutMs,-}: CreateLangfusePromptAdapterDependencies): PromptSourceAdapter {+}: CreateLangfusePromptAdapterDependencies): PromptSourceAdapter<LangfusePromptSelection> {return {async resolvePrompt({ group, selection }) {- if (selection.type !== 'production' && selection.type !== 'version') {- return { ok: false, error: { type: 'unsupported_selection', source: 'langfuse' } };- }if (!group.sourcePromptName) {return {ok: false,@@ -53,7 +58,7 @@ export function createLangfusePromptAdapter({}const selector: LangfuseTextPromptSelector =- selection.type === 'version' ? { version: selection.version } : { label: 'production' };+ selection.type === 'exact' ? { version: selection.version } : { label: 'production' };const result = await getTextPrompt(resolution.connection, group.sourcePromptName, selector, {timeoutMs: timeoutMs(),});@@ -80,5 +85,57 @@ export function createLangfusePromptAdapter({},};},++ /** Rejects a response for another prompt, in case Langfuse ignores the filter. */+ async listRevisions({ group }) {+ if (!group.sourcePromptName) {+ return {+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason: 'not_configured' },+ };+ }++ const resolution = await resolveSource(group);+ if (!resolution.ok) {+ return {+ ok: false,+ error: { type: 'source_unavailable', source: 'langfuse', reason: resolution.reason },+ };+ }++ const { items, meta } = await listPrompts(+ resolution.connection,+ { nameEquals: group.sourcePromptName, page: 1, limit: 1 },+ { timeoutMs: timeoutMs() },+ );++ if (meta.totalItems === 0 && items.length === 0) {+ return { ok: false, error: { type: 'source_not_found', source: 'langfuse' } };+ }++ if (items.length === 1 && items[0].name === group.sourcePromptName && meta.totalItems === 1) {+ const [item] = items;+ if (item.type === 'text' && item.versions.length > 0) {+ return {+ ok: true,+ value: {+ source: 'langfuse',+ groupId: group._id,+ revisions: [...item.versions]+ .sort((a, b) => b - a)+ .map((version) => ({ source: 'langfuse' as const, version })),+ },+ };+ }+ if (item.type === 'chat') {+ return { ok: false, error: { type: 'unsupported_content', reason: 'chat_prompt' } };+ }+ }++ throw new LangfusePromptRequestError(+ 'invalid_response',+ 'Langfuse returned an unexpected prompt list response while listing revisions',+ );+ },};}diff --git a/packages/api/src/prompts/native.spec.ts b/packages/api/src/prompts/native.spec.tsindex e78fad4c45..adcaa51ff9 100644--- a/packages/api/src/prompts/native.spec.ts+++ b/packages/api/src/prompts/native.spec.ts@@ -163,17 +163,6 @@ describe('createNativePromptAdapter', () => {});});- it('returns unsupported_selection for a version selection', async () => {- const adapter = createNativePromptAdapter(createPromptStore(db));-- await expect(- adapter.resolvePrompt({ group, selection: { type: 'version', version: 1 } }),- ).resolves.toEqual({- ok: false,- error: { type: 'unsupported_selection', source: 'native' },- });- });-it('resolves a stored revision without a type as text', async () => {const adapter = createNativePromptAdapter(createPromptStore(db));await mongoose.models.Prompt.collection.updateMany(@@ -192,4 +181,50 @@ describe('createNativePromptAdapter', () => {}),).resolves.toMatchObject({ ok: true, value: { promptId: draft._id, type: 'text' } });});++ describe('listRevisions', () => {+ it('lists revisions newest first, numbered from the oldest, with Production marked', async () => {+ const adapter = createNativePromptAdapter(createPromptStore(db));++ await expect(adapter.listRevisions({ group })).resolves.toEqual({+ ok: true,+ value: {+ source: 'native',+ groupId: group._id,+ revisions: [+ { source: 'native', promptId: draft._id, version: 2, isProduction: false },+ { source: 'native', promptId: production._id, version: 1, isProduction: true },+ ],+ },+ });+ });++ it('marks no revision as Production when the group has none', async () => {+ const adapter = createNativePromptAdapter(createPromptStore(db));++ await expect(+ adapter.listRevisions({ group: { ...group, productionId: null } }),+ ).resolves.toEqual({+ ok: true,+ value: {+ source: 'native',+ groupId: group._id,+ revisions: [+ { source: 'native', promptId: draft._id, version: 2, isProduction: false },+ { source: 'native', promptId: production._id, version: 1, isProduction: false },+ ],+ },+ });+ });++ it('returns an empty revision list for a group with no stored revisions', async () => {+ const adapter = createNativePromptAdapter(createPromptStore(db));+ const otherGroup = { ...group, _id: new Types.ObjectId().toString() };++ await expect(adapter.listRevisions({ group: otherGroup })).resolves.toEqual({+ ok: true,+ value: { source: 'native', groupId: otherGroup._id, revisions: [] },+ });+ });+ });});diff --git a/packages/api/src/prompts/native.ts b/packages/api/src/prompts/native.tsindex 2ade8be94d..fdbfac0e19 100644--- a/packages/api/src/prompts/native.ts+++ b/packages/api/src/prompts/native.ts@@ -1,7 +1,7 @@+import type { NativePromptSelection } from 'librechat-data-provider';import type {PromptStore,PromptRecord,- PromptSelection,PromptProjection,PromptGroupRecord,PromptSourceAdapter,@@ -70,20 +70,19 @@ async function resolveProduction(: null;}-export function selectionUnavailableReason(selection: PromptSelection): 'production' | 'revision' {+export function selectionUnavailableReason(selection: {+ readonly type: 'production' | 'exact';+}): 'production' | 'revision' {return selection.type === 'production' ? 'production' : 'revision';}/** Native prompts stored in the LibreChat database; resolves content through the- * store's `getPrompt`. */+ * store's `getPrompt` and lists revisions through its `getPrompts`. */export function createNativePromptAdapter(- store: Pick<PromptStore, 'getPrompt'>,-): PromptSourceAdapter {+ store: Pick<PromptStore, 'getPrompt' | 'getPrompts'>,+): PromptSourceAdapter<NativePromptSelection> {return {resolvePrompt: async ({ group, selection, loadedRevision }) => {- if (selection.type === 'version') {- return { ok: false, error: { type: 'unsupported_selection', source: 'native' } };- }const resolved =selection.type === 'exact'? await resolveExact(store, group._id, selection.promptId, loadedRevision)@@ -96,5 +95,24 @@ export function createNativePromptAdapter(}return { ok: true, value: { source: 'native', ...resolved } };},++ listRevisions: async ({ group }) => {+ // getPrompts returns revisions newest first; version is derived from position, not stored.+ const revisions = await store.getPrompts(group._id);+ const total = revisions.length;+ return {+ ok: true,+ value: {+ source: 'native',+ groupId: group._id,+ revisions: revisions.map((revision, index) => ({+ source: 'native',+ promptId: revision._id,+ version: total - index,+ isProduction: revision._id === group.productionId,+ })),+ },+ };+ },};}diff --git a/packages/api/src/prompts/service.spec.ts b/packages/api/src/prompts/service.spec.tsindex 08e8cbd679..5a143b4dd5 100644--- a/packages/api/src/prompts/service.spec.ts+++ b/packages/api/src/prompts/service.spec.ts@@ -101,7 +101,12 @@ describe('createPromptService', () => {describe('resolvePrompt', () => {it('returns the Production revision', async () => {await expect(- service.resolvePrompt({ groupId: group._id, selection: { type: 'production' }, filters }),+ service.resolvePrompt({+ groupId: group._id,+ source: 'native',+ selection: { type: 'production' },+ filters,+ }),).resolves.toEqual({ok: true,value: {@@ -120,6 +125,7 @@ describe('createPromptService', () => {await expect(service.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'exact', promptId: blocked._id },filters,}),@@ -130,6 +136,7 @@ describe('createPromptService', () => {await expect(service.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'exact', promptId: missingId() },}),).resolves.toEqual({@@ -137,7 +144,11 @@ describe('createPromptService', () => {error: { type: 'unavailable_selection', reason: 'revision' },});await expect(- service.resolvePrompt({ groupId: missingId(), selection: { type: 'production' } }),+ service.resolvePrompt({+ groupId: missingId(),+ source: 'native',+ selection: { type: 'production' },+ }),).resolves.toEqual({ok: false,error: { type: 'unavailable_selection', reason: 'production' },@@ -148,7 +159,11 @@ describe('createPromptService', () => {const read = jest.spyOn(db, 'getPromptGroup');await expect(- service.resolvePrompt({ groupId: group._id, selection: { type: 'production' } }),+ service.resolvePrompt({+ groupId: group._id,+ source: 'native',+ selection: { type: 'production' },+ }),).resolves.toMatchObject({ ok: true, value: { promptId: production._id } });expect(read).toHaveBeenCalledTimes(1);});@@ -160,6 +175,7 @@ describe('createPromptService', () => {await expect(service.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'production' },loadedGroup: otherGroup,}),@@ -171,7 +187,11 @@ describe('createPromptService', () => {const revisionRead = jest.spyOn(db, 'getPrompt');await expect(- service.resolvePrompt({ groupId: group._id, selection: { type: 'production' } }),+ service.resolvePrompt({+ groupId: group._id,+ source: 'native',+ selection: { type: 'production' },+ }),).resolves.toMatchObject({ ok: true, value: { promptId: production._id } });expect(revisionRead).not.toHaveBeenCalled();});@@ -182,6 +202,7 @@ describe('createPromptService', () => {await expect(service.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'exact', promptId: missingId() },}),).resolves.toEqual({@@ -197,6 +218,7 @@ describe('createPromptService', () => {await expect(service.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'exact', promptId: production._id },}),).resolves.toEqual({@@ -219,7 +241,7 @@ describe('createPromptService', () => {store,sources: {native: createNativePromptAdapter(store),- langfuse: { resolvePrompt: jest.fn() },+ langfuse: { resolvePrompt: jest.fn(), listRevisions: jest.fn() },},grantCreatorOwnership: jest.fn(),grantPublicViewer: jest.fn(),@@ -229,6 +251,7 @@ describe('createPromptService', () => {const rejection: unknown = await routed.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'exact', promptId: production._id },}).catch((caught: unknown) => caught);@@ -517,7 +540,7 @@ describe('createPromptService', () => {store,sources: {native: createNativePromptAdapter(store),- langfuse: { resolvePrompt: jest.fn() },+ langfuse: { resolvePrompt: jest.fn(), listRevisions: jest.fn() },},grantCreatorOwnership: jest.fn(),grantPublicViewer,@@ -562,7 +585,7 @@ describe('createPromptService', () => {store,sources: {native: createNativePromptAdapter(store),- langfuse: { resolvePrompt: jest.fn() },+ langfuse: { resolvePrompt: jest.fn(), listRevisions: jest.fn() },},grantCreatorOwnership: jest.fn(),grantPublicViewer,@@ -595,7 +618,7 @@ describe('createPromptService', () => {store,sources: {native: createNativePromptAdapter(store),- langfuse: { resolvePrompt: jest.fn() },+ langfuse: { resolvePrompt: jest.fn(), listRevisions: jest.fn() },},grantCreatorOwnership: jest.fn(),grantPublicViewer,@@ -939,7 +962,7 @@ describe('createPromptService', () => {store,sources: {native: createNativePromptAdapter(store),- langfuse: { resolvePrompt: jest.fn() },+ langfuse: { resolvePrompt: jest.fn(), listRevisions: jest.fn() },},grantCreatorOwnership: jest.fn(),grantPublicViewer: jest.fn(),@@ -971,6 +994,78 @@ describe('createPromptService', () => {});});+ describe('listRevisions', () => {+ function makeLangfuseGroup(overrides: Partial<PromptGroupRecord> = {}): PromptGroupRecord {+ return {+ _id: missingId(),+ name: 'Langfuse group',+ author,+ authorName: 'Author',+ source: 'langfuse',+ sourcePromptName: 'langfuse-prompt',+ ...overrides,+ };+ }++ it('lists the native revisions for a loaded group', async () => {+ await expect(+ service.listRevisions({ groupId: group._id, loadedGroup: group }),+ ).resolves.toEqual({+ ok: true,+ value: {+ source: 'native',+ groupId: group._id,+ revisions: [+ { source: 'native', promptId: production._id, version: 1, isProduction: true },+ ],+ },+ });+ });++ it('reads the group once when none is loaded', async () => {+ const read = jest.spyOn(db, 'getPromptGroup');++ await expect(service.listRevisions({ groupId: group._id })).resolves.toMatchObject({+ ok: true,+ value: { source: 'native' },+ });+ expect(read).toHaveBeenCalledTimes(1);+ });++ it('returns unavailable_selection reason revision for a missing group', async () => {+ await expect(service.listRevisions({ groupId: missingId() })).resolves.toEqual({+ ok: false,+ error: { type: 'unavailable_selection', reason: 'revision' },+ });+ });++ it('dispatches a Langfuse group to the Langfuse adapter', async () => {+ const langfuseGroup = makeLangfuseGroup();+ const listed = {+ source: 'langfuse' as const,+ groupId: langfuseGroup._id,+ revisions: [{ source: 'langfuse' as const, version: 2 }],+ };+ const listRevisions = jest.fn().mockResolvedValue({ ok: true, value: listed });+ const store = createPromptStore(db);+ const routed = createPromptServiceFromAdapters({+ store,+ sources: {+ native: createNativePromptAdapter(store),+ langfuse: { resolvePrompt: jest.fn(), listRevisions },+ },+ grantCreatorOwnership: jest.fn(),+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },+ });++ await expect(+ routed.listRevisions({ groupId: langfuseGroup._id, loadedGroup: langfuseGroup }),+ ).resolves.toEqual({ ok: true, value: listed });+ expect(listRevisions).toHaveBeenCalledWith({ group: langfuseGroup });+ });+ });+describe('routing by source', () => {function makeLangfuseGroup(overrides: Partial<PromptGroupRecord> = {}): PromptGroupRecord {return {@@ -1031,7 +1126,10 @@ describe('createPromptService', () => {const store = createPromptStore(db);const routed = createPromptServiceFromAdapters({store,- sources: { native: createNativePromptAdapter(store), langfuse: { resolvePrompt } },+ sources: {+ native: createNativePromptAdapter(store),+ langfuse: { resolvePrompt, listRevisions: jest.fn() },+ },grantCreatorOwnership: jest.fn(),grantPublicViewer: jest.fn(),logger: { warn: jest.fn(), error: jest.fn() },@@ -1040,6 +1138,7 @@ describe('createPromptService', () => {await expect(routed.resolvePrompt({groupId: langfuseGroup._id,+ source: 'langfuse',selection: { type: 'production' },loadedGroup: langfuseGroup,}),@@ -1051,13 +1150,16 @@ describe('createPromptService', () => {});});- it('rejects a disallowed source before calling the adapter', async () => {+ it('rejects a native reference against a Langfuse group before calling the adapter', async () => {const langfuseGroup = makeLangfuseGroup();const resolvePrompt = jest.fn();const store = createPromptStore(db);const routed = createPromptServiceFromAdapters({store,- sources: { native: createNativePromptAdapter(store), langfuse: { resolvePrompt } },+ sources: {+ native: createNativePromptAdapter(store),+ langfuse: { resolvePrompt, listRevisions: jest.fn() },+ },grantCreatorOwnership: jest.fn(),grantPublicViewer: jest.fn(),logger: { warn: jest.fn(), error: jest.fn() },@@ -1066,9 +1168,9 @@ describe('createPromptService', () => {await expect(routed.resolvePrompt({groupId: langfuseGroup._id,+ source: 'native',selection: { type: 'production' },loadedGroup: langfuseGroup,- allowedSources: ['native'],}),).resolves.toEqual({ok: false,@@ -1077,6 +1179,34 @@ describe('createPromptService', () => {expect(resolvePrompt).not.toHaveBeenCalled();});+ it('rejects a Langfuse reference against a native group before calling the adapter', async () => {+ const resolvePrompt = jest.fn();+ const store = createPromptStore(db);+ const routed = createPromptServiceFromAdapters({+ store,+ sources: {+ native: createNativePromptAdapter(store),+ langfuse: { resolvePrompt, listRevisions: jest.fn() },+ },+ grantCreatorOwnership: jest.fn(),+ grantPublicViewer: jest.fn(),+ logger: { warn: jest.fn(), error: jest.fn() },+ });++ await expect(+ routed.resolvePrompt({+ groupId: group._id,+ source: 'langfuse',+ selection: { type: 'production' },+ loadedGroup: group,+ }),+ ).resolves.toEqual({+ ok: false,+ error: { type: 'unsupported_source', source: 'native' },+ });+ expect(resolvePrompt).not.toHaveBeenCalled();+ });+it('content-filters a resolved Langfuse prompt the same as native content', async () => {const langfuseGroup = makeLangfuseGroup();const resolved = makeLangfuseResolved({@@ -1087,7 +1217,10 @@ describe('createPromptService', () => {const store = createPromptStore(db);const routed = createPromptServiceFromAdapters({store,- sources: { native: createNativePromptAdapter(store), langfuse: { resolvePrompt } },+ sources: {+ native: createNativePromptAdapter(store),+ langfuse: { resolvePrompt, listRevisions: jest.fn() },+ },grantCreatorOwnership: jest.fn(),grantPublicViewer: jest.fn(),logger: { warn: jest.fn(), error: jest.fn() },@@ -1096,6 +1229,7 @@ describe('createPromptService', () => {await expect(routed.resolvePrompt({groupId: langfuseGroup._id,+ source: 'langfuse',selection: { type: 'production' },loadedGroup: langfuseGroup,filters,@@ -1234,17 +1368,7 @@ describe('createPromptService', () => {});});- it('returns unsupported_selection for a version selection on a native group', async () => {- await expect(- service.resolvePrompt({- groupId: group._id,- selection: { type: 'version', version: 2 },- loadedGroup: group,- }),- ).resolves.toEqual({ ok: false, error: { type: 'unsupported_selection', source: 'native' } });- });-- it('rejects a disallowed source for an exact selection with nothing preloaded', async () => {+ it('rejects a native reference against a Langfuse group for an exact selection with nothing preloaded', async () => {const langfuseGroup = makeLangfuseGroup();const store = createPromptStore(db);jest.spyOn(store, 'getPromptGroup').mockResolvedValue(langfuseGroup);@@ -1252,7 +1376,10 @@ describe('createPromptService', () => {const resolvePrompt = jest.fn();const routed = createPromptServiceFromAdapters({store,- sources: { native: createNativePromptAdapter(store), langfuse: { resolvePrompt } },+ sources: {+ native: createNativePromptAdapter(store),+ langfuse: { resolvePrompt, listRevisions: jest.fn() },+ },grantCreatorOwnership: jest.fn(),grantPublicViewer: jest.fn(),logger: { warn: jest.fn(), error: jest.fn() },@@ -1261,8 +1388,8 @@ describe('createPromptService', () => {await expect(routed.resolvePrompt({groupId: langfuseGroup._id,+ source: 'native',selection: { type: 'exact', promptId: production._id },- allowedSources: ['native'],}),).resolves.toEqual({ok: false,@@ -1272,38 +1399,6 @@ describe('createPromptService', () => {expect(revisionRead).not.toHaveBeenCalled();});- it('returns unsupported_selection for an exact selection dispatched to the Langfuse adapter', async () => {- const langfuseGroup = makeLangfuseGroup();- const store = createPromptStore(db);- jest.spyOn(store, 'getPromptGroup').mockResolvedValue(langfuseGroup);- const resolvePrompt = jest.fn().mockResolvedValue({- ok: false,- error: { type: 'unsupported_selection', source: 'langfuse' },- });- const routed = createPromptServiceFromAdapters({- store,- sources: { native: createNativePromptAdapter(store), langfuse: { resolvePrompt } },- grantCreatorOwnership: jest.fn(),- grantPublicViewer: jest.fn(),- logger: { warn: jest.fn(), error: jest.fn() },- });-- await expect(- routed.resolvePrompt({- groupId: langfuseGroup._id,- selection: { type: 'exact', promptId: production._id },- }),- ).resolves.toEqual({- ok: false,- error: { type: 'unsupported_selection', source: 'langfuse' },- });- expect(resolvePrompt).toHaveBeenCalledWith({- group: langfuseGroup,- selection: { type: 'exact', promptId: production._id },- loadedRevision: undefined,- });- });-it('returns no revisions for a Langfuse group', async () => {const langfuseGroup = makeLangfuseGroup();@@ -1312,24 +1407,19 @@ describe('createPromptService', () => {it('treats a stored group with no source field as native', async () => {// A group with no `source` field at all, not a `native` value.- // `toPromptGroupRecord` is the only place that defaults it, so routing,- // `allowedSources` and `savePrompt` must all agree the default is native- // rather than treating the absence as unresolved.+ // toPromptGroupRecord is the only place that defaults a missing source to native.await mongoose.models.PromptGroup.collection.updateOne({ _id: new Types.ObjectId(group._id) },{ $unset: { source: '' } },);- await expect(- service.resolvePrompt({ groupId: group._id, selection: { type: 'production' } }),- ).resolves.toMatchObject({ ok: true, value: { source: 'native', promptId: production._id } });await expect(service.resolvePrompt({groupId: group._id,+ source: 'native',selection: { type: 'production' },- allowedSources: ['native'],}),- ).resolves.toMatchObject({ ok: true, value: { source: 'native' } });+ ).resolves.toMatchObject({ ok: true, value: { source: 'native', promptId: production._id } });await expect(service.savePrompt({groupId: group._id,@@ -1374,6 +1464,7 @@ describe('createPromptService', () => {await expect(withLangfuse.resolvePrompt({groupId: langfuseGroup._id,+ source: 'langfuse',selection: { type: 'production' },loadedGroup: langfuseGroup,}),@@ -1387,7 +1478,7 @@ describe('createPromptService', () => {);});- it('rejects a Langfuse group excluded by allowedSources without reading config', async () => {+ it('rejects a native reference against a Langfuse group without reading config', async () => {const langfuseGroup = makeLangfuseGroup();const findConfigByPrincipal = jest.spyOn(db, 'findConfigByPrincipal');const nativeOnly = createPromptService({ db, grantPermission, getAppConfig });@@ -1395,9 +1486,9 @@ describe('createPromptService', () => {await expect(nativeOnly.resolvePrompt({groupId: langfuseGroup._id,+ source: 'native',selection: { type: 'production' },loadedGroup: langfuseGroup,- allowedSources: ['native'],}),).resolves.toEqual({ok: false,@@ -1448,6 +1539,7 @@ describe('createPromptService', () => {tenantStorage.run({ tenantId: 'a' }, async () =>shared.resolvePrompt({groupId: groupA._id,+ source: 'langfuse',selection: { type: 'production' },loadedGroup: groupA,}),@@ -1455,6 +1547,7 @@ describe('createPromptService', () => {tenantStorage.run({ tenantId: 'b' }, async () =>shared.resolvePrompt({groupId: groupB._id,+ source: 'langfuse',selection: { type: 'production' },loadedGroup: groupB,}),diff --git a/packages/api/src/prompts/service.ts b/packages/api/src/prompts/service.tsindex a83482f12f..0969caa8e4 100644--- a/packages/api/src/prompts/service.ts+++ b/packages/api/src/prompts/service.ts@@ -1,6 +1,10 @@import { logger, BASE_CONFIG_PRINCIPAL_ID } from '@librechat/data-schemas';import { AccessRoleIds, PrincipalType, ResourceType } from 'librechat-data-provider';-import type { FiltersConfig, TDeletePromptResponse } from 'librechat-data-provider';+import type {+ FiltersConfig,+ TDeletePromptResponse,+ TPromptRevisionChoicesResponse,+} from 'librechat-data-provider';import type {PromptRecord,PromptDatabase,@@ -9,6 +13,7 @@ import type {PromptOperation,PromptGroupRecord,ResolvePromptInput,+ ListRevisionsInput,PromptServiceError,PromptServiceResult,ImportSourceGroupInput,@@ -56,6 +61,11 @@ export interface PromptServiceListResult {*/export interface PromptService {resolvePrompt(input: ResolvePromptInput): Promise<PromptServiceResult<ResolvedPrompt>>;+ /** Uncached read, for a caller that needs `source` before building a `PromptReference`. */+ readPromptGroup(groupId: string): Promise<PromptGroupRecord | null>;+ listRevisions(+ input: ListRevisionsInput,+ ): Promise<PromptServiceResult<TPromptRevisionChoicesResponse>>;getListPromptGroupsByAccess(input: PromptListInput): Promise<PromptServiceListResult>;/** Returns the group's revisions, newest first. */getPrompts(@@ -168,32 +178,50 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters): withPromptStage('read', () => store.getPromptGroup(groupId));return {- async resolvePrompt({- groupId,- selection,- loadedGroup,- loadedRevision,- filters,- allowedSources,- }) {+ async resolvePrompt(input) {+ const { groupId, loadedGroup, loadedRevision, filters } = input;const group = await readGroup(groupId, loadedGroup);if (group == null) {return {ok: false,- error: { type: 'unavailable_selection', reason: selectionUnavailableReason(selection) },+ error: {+ type: 'unavailable_selection',+ reason: selectionUnavailableReason(input.selection),+ },};}- if (allowedSources != null && !allowedSources.includes(group.source)) {+ if (input.source !== group.source) {return { ok: false, error: { type: 'unsupported_source', source: group.source } };}- const adapter = sources[group.source];- const resolved = await adapter.resolvePrompt({ group, selection, loadedRevision });+ // Switches on input.source, not group.source, so TypeScript narrows input.selection to match.+ const resolved =+ input.source === 'native'+ ? await sources.native.resolvePrompt({+ group,+ selection: input.selection,+ loadedRevision,+ })+ : await sources.langfuse.resolvePrompt({+ group,+ selection: input.selection,+ loadedRevision,+ });if (!resolved.ok) {return resolved;}return inspect({ prompt: resolved.value.prompt }, filters) ?? resolved;},+ readPromptGroup: (groupId) => readGroup(groupId),++ async listRevisions({ groupId, loadedGroup }) {+ const group = await readGroup(groupId, loadedGroup);+ if (group == null) {+ return { ok: false, error: { type: 'unavailable_selection', reason: 'revision' } };+ }+ return sources[group.source].listRevisions({ group });+ },+async getListPromptGroupsByAccess(input) {const { name, category, searchShared, searchSharedOnly } = buildPromptGroupFilter(input);const accessibleIds = await filterAccessibleIdsBySharedLogic({diff --git a/packages/api/src/prompts/types.ts b/packages/api/src/prompts/types.tsindex 3fcdeca176..710410d7e7 100644--- a/packages/api/src/prompts/types.ts+++ b/packages/api/src/prompts/types.ts@@ -3,6 +3,9 @@ import type {PrincipalType,TCreatePromptRecord,TDeletePromptResponse,+ NativePromptSelection,+ LangfusePromptSelection,+ TPromptRevisionChoicesResponse,TMakePromptProductionResponse,} from 'librechat-data-provider';import type { PromptGroupSource } from '@librechat/data-schemas';@@ -58,11 +61,10 @@ export interface PromptGroupRecord {readonly sourceDestination?: string;}-export type PromptSelection =- | { readonly type: 'production' }- | { readonly type: 'exact'; readonly promptId: string }- /** Langfuse only; the native adapter returns `unsupported_selection` for it. */- | { readonly type: 'version'; readonly version: number };+/** A source-tagged selection; a mismatched `source` is rejected as `unsupported_source`. */+export type PromptReference =+ | { readonly source: 'native'; readonly selection: NativePromptSelection }+ | { readonly source: 'langfuse'; readonly selection: LangfusePromptSelection };export interface NativeResolvedPrompt {readonly source: 'native';@@ -167,10 +169,7 @@ export type PromptServiceError =* including `savePrompt`, `updatePromptGroup`, `deletePromptGroup`,* `makePromptProduction` and `deletePrompt`. */| { readonly type: 'read_only'; readonly source: PromptGroupSource }- /** The selection is not valid for `source` (for example `version` on a native group,- * or `exact` on a Langfuse group). */- | { readonly type: 'unsupported_selection'; readonly source: PromptGroupSource }- /** Returned by the `allowedSources` check in `resolvePrompt`, before any adapter runs. */+ /** The reference's `source` does not match the loaded group's `source`. */| { readonly type: 'unsupported_source'; readonly source: PromptGroupSource }| {readonly type: 'source_unavailable';@@ -193,28 +192,27 @@ export type MakePromptProductionResult =| { readonly ok: true; readonly value: TMakePromptProductionResponse; readonly groupId?: string }| { readonly ok: false; readonly error: PromptServiceError };-export interface ResolvePromptInput {+export type ResolvePromptInput = PromptReference & {readonly groupId: string;- readonly selection: PromptSelection;readonly loadedGroup?: PromptGroupRecord | null;readonly loadedRevision?: PromptRecord | null;readonly filters?: FiltersConfig;- /** Restricts dispatch to these sources; any other source returns `unsupported_source`- * before an adapter or network call runs. Agent-link resolution passes `['native']`. */- readonly allowedSources?: readonly PromptGroupSource[];+};++export interface ListRevisionsInput {+ readonly groupId: string;+ readonly loadedGroup?: PromptGroupRecord | null;}-/**- * Resolves a group's content for a selection. One adapter per `PromptGroupSource`; the- * service picks it from `group.source` and dispatches the already-resolved `group`, so- * an adapter never has to look its own group up.- */-export interface PromptSourceAdapter {+export interface PromptSourceAdapter<TSelection> {resolvePrompt(input: {readonly group: PromptGroupRecord;- readonly selection: PromptSelection;+ readonly selection: TSelection;readonly loadedRevision?: PromptRecord | null;}): Promise<PromptServiceResult<ResolvedPrompt>>;+ listRevisions(input: {+ readonly group: PromptGroupRecord;+ }): Promise<PromptServiceResult<TPromptRevisionChoicesResponse>>;}/**@@ -305,7 +303,10 @@ export interface PromptServiceAdapters {/** All local group and native-revision storage. */readonly store: PromptStore;/** The content source per `PromptGroupSource`, resolving a selection only. */- readonly sources: Record<PromptGroupSource, PromptSourceAdapter>;+ readonly sources: {+ readonly native: PromptSourceAdapter<NativePromptSelection>;+ readonly langfuse: PromptSourceAdapter<LangfusePromptSelection>;+ };readonly grantCreatorOwnership: (input: {readonly userId: string;readonly groupId: string;diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 2fea074752..9c386136d4 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -464,6 +464,8 @@ export const getPromptGroup = (_id: string) => `${prompts()}/groups/${_id}`;export const resolvePromptGroup = (_id: string, version?: number) =>`${getPromptGroup(_id)}/resolve${buildQuery({ version })}`;+export const getPromptGroupRevisions = (_id: string) => `${getPromptGroup(_id)}/revisions`;+export const getPromptGroupsWithFilters = (filter: object) => {let url = `${prompts()}/groups`;// Filter out undefined/null valuesdiff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex f01e1f33bd..677fbc7b9f 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -342,12 +342,21 @@ describe('linked instructions configuration', () => {expect(agentsEndpointSchema.parse({ linkedInstructions: {} }).linkedInstructions).toEqual({timeoutMs: 2000,native: { cacheTtlMs: 300_000, cacheClearTimeoutMs: 1000 },+ langfuse: { enabled: false },});expect(agentsEndpointSchema.parse({linkedInstructions: { timeoutMs: 5000, native: { cacheTtlMs: 0 } },}).linkedInstructions,- ).toEqual({ timeoutMs: 5000, native: { cacheTtlMs: 0, cacheClearTimeoutMs: 1000 } });+ ).toEqual({+ timeoutMs: 5000,+ native: { cacheTtlMs: 0, cacheClearTimeoutMs: 1000 },+ langfuse: { enabled: false },+ });+ expect(+ agentsEndpointSchema.parse({ linkedInstructions: { langfuse: { enabled: true } } })+ .linkedInstructions?.langfuse,+ ).toEqual({ enabled: true });for (const timeoutMs of [0, 99, 30_001, 1.5]) {expect(agentsEndpointSchema.safeParse({ linkedInstructions: { timeoutMs } }).success).toBe(false,diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex d9c87e1444..fa55aca890 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1734,6 +1734,13 @@ export const agentsEndpointSchema = baseEndpointSchema}).optional().prefault({}),+ /** Rollout switch for linking an agent's instructions to a Langfuse prompt group. */+ langfuse: z+ .object({+ enabled: z.boolean().optional().default(false),+ })+ .optional()+ .prefault({}),}).optional(),/** Cap on any agent's `recursion_limit` and on `recursionLimit`. */diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 3d97a725d2..506cc5fc4c 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1357,6 +1357,10 @@ export function resolvePromptGroup(return request.get(endpoints.resolvePromptGroup(id, version));}+export function getPromptGroupRevisions(id: string): Promise<t.TPromptRevisionChoicesResponse> {+ return request.get(endpoints.getPromptGroupRevisions(id));+}+export function createPrompt(payload: t.TCreatePrompt): Promise<t.TCreatePromptResponse> {return request.post(endpoints.postPrompt(), payload);}diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex 901e5669dd..d41c2bcc30 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -61,6 +61,7 @@ export enum QueryKeys {allPromptGroups = 'allPromptGroups',promptGroup = 'promptGroup',promptGroupContent = 'promptGroupContent',+ promptGroupRevisions = 'promptGroupRevisions',projects = 'projects',project = 'project',projectFiles = 'projectFiles',diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 89fe4851b1..74444ce41b 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -710,6 +710,10 @@ export type TConfig = {/** Effective subagents-per-agent cap served from `endpoints.agents.maxSubagents`. */maxSubagents?: number;fileSharing?: TAgentsEndpoint['fileSharing'];+ /** Rollout switches served to the Builder from `endpoints.agents.linkedInstructions`. */+ linkedInstructions?: {+ langfuse?: { enabled?: boolean };+ };/** Concurrent Code API uploads allowed per route and authenticated principal. */codeApiUploadConcurrency?: number;/** Milliseconds one operation may spend waiting on Code API rate limits. */@@ -1247,6 +1251,12 @@ export type TGetRandomPromptsRequest = {skip: number;};+export type NativePromptSelection = { type: 'production' } | { type: 'exact'; promptId: string };++export type LangfusePromptSelection = { type: 'production' } | { type: 'exact'; version: number };++export type PromptSelection = NativePromptSelection | LangfusePromptSelection;+/** `GET /api/prompts/groups/:groupId/resolve`. Native resolves the group's* production; Langfuse fetches text content live, by label `production` or* an exact `version`, with no cache. */@@ -1272,6 +1282,18 @@ export type TResolvedLangfusePrompt = {export type TResolvedPromptResponse = TResolvedNativePrompt | TResolvedLangfusePrompt;+/** One revision choice: metadata only, no prompt content. */+export type TPromptRevisionChoice =+ | { source: 'native'; promptId: string; version: number; isProduction: boolean }+ | { source: 'langfuse'; version: number };++/** Only a native revision marks `isProduction`; Langfuse resolves Production live. */+export type TPromptRevisionChoicesResponse = {+ source: TPromptGroupSource;+ groupId: string;+ revisions: TPromptRevisionChoice[];+};+/** `code` values the `/resolve` route returns, including the Langfuse request* failure codes relayed through `toLangfusePromptErrorResponse` (`unauthorized`,* `timeout`, `upstream`, `invalid_response`). A `blocked_content` rejection usesdiff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.tsindex 86aa93a2c0..f7542c1079 100644--- a/packages/data-provider/src/types/agents.ts+++ b/packages/data-provider/src/types/agents.ts@@ -6,6 +6,7 @@ import type {AgentToolOptions,ToolApprovalGrantBinding,} from './tools';+import type { TPromptGroupSource, NativePromptSelection, LangfusePromptSelection } from '../types';import type { TAttachment, TPlugin, AgentProvider, MemoryScope, SkillsScope } from 'src/schemas';import type { TTokenUsageEvent, TContextUsageEvent, TPendingSteer } from './runs';import type { StatefulCodeEnvironment } from '../stateful-code';@@ -1063,24 +1064,30 @@ export const agentGitIdentitySchema: z.ZodType<AgentGitIdentity | undefined> = z}).optional();-/** Selects which revision of a linked prompt group an agent's instructions follow. */-export type AgentInstructionsPromptSelection =- | { type: 'production' }- | { type: 'exact'; promptId: string };+export type AgentInstructionsPromptSelection = NativePromptSelection;/** A link from an agent to a native LibreChat prompt group used as its instructions. */-export type AgentInstructionsPrompt = {+export type NativeAgentInstructionsPrompt = {source: 'native';groupId: string;selection: AgentInstructionsPromptSelection;};-/** Returned to an editor who lacks VIEW on the linked group. Hides the group identity.- * `matchesCurrent` is set only on a version snapshot's stub (never on the current- * agent's own stub): whether that version's raw link equals the agent's current raw- * link (same `groupId` and selection), without revealing which group either is. */+export type LangfuseAgentInstructionsPromptSelection = LangfusePromptSelection;++export type LangfuseAgentInstructionsPrompt = {+ source: 'langfuse';+ groupId: string;+ selection: LangfuseAgentInstructionsPromptSelection;+};++export type AgentInstructionsPrompt =+ | NativeAgentInstructionsPrompt+ | LangfuseAgentInstructionsPrompt;++/** Returned to an editor who lacks VIEW on the linked group; hides its identity. */export type RestrictedAgentInstructionsPrompt = {- source: 'native';+ source: TPromptGroupSource;restricted: true;matchesCurrent?: boolean;};diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.tsindex 5a7802faf4..1434f20b8a 100644--- a/packages/data-schemas/src/methods/agent.spec.ts+++ b/packages/data-schemas/src/methods/agent.spec.ts@@ -575,6 +575,86 @@ describe('Agent Methods', () => {expect(retrievedAgent!.instructionsPrompt).toEqual(instructionsPrompt);});+ test('should persist a linked Langfuse prompt-group exact-version selection on create', async () => {+ const { agentId, authorId } = createTestIds();+ const instructionsPrompt = {+ source: 'langfuse',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'exact', version: 3 },+ };++ const newAgent = await createAgent({+ id: agentId,+ name: 'Linked Langfuse Instructions Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt,+ });++ expect(newAgent.instructionsPrompt).toEqual(instructionsPrompt);++ const retrievedAgent = await getAgent({ id: agentId });+ expect(retrievedAgent!.instructionsPrompt).toEqual(instructionsPrompt);+ });++ test('rejects an instructionsPrompt with an unknown source', async () => {+ const { agentId, authorId } = createTestIds();++ await expect(+ createAgent({+ id: agentId,+ name: 'Invalid Source Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt: {+ source: 'other',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'production' },+ },+ }),+ ).rejects.toMatchObject({ name: 'ValidationError' });+ });++ test('rejects an instructionsPrompt selection with an unknown type', async () => {+ const { agentId, authorId } = createTestIds();++ await expect(+ createAgent({+ id: agentId,+ name: 'Invalid Selection Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt: {+ source: 'native',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'latest' },+ },+ }),+ ).rejects.toMatchObject({ name: 'ValidationError' });+ });++ test('rejects a Langfuse instructionsPrompt selection using the retired "version" type', async () => {+ const { agentId, authorId } = createTestIds();++ await expect(+ createAgent({+ id: agentId,+ name: 'Retired Selection Type Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt: {+ source: 'langfuse',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'version', version: 3 },+ },+ }),+ ).rejects.toMatchObject({ name: 'ValidationError' });+ });+test('should derive mcpServerNames only from MCP tools on create', async () => {const { agentId, authorId } = createTestIds();const actionTool = `sync${Constants.mcp_delimiter}state${actionDelimiter}api---example---com`;@@ -3199,6 +3279,30 @@ describe('Agent Methods', () => {expect(revertedAgent.instructionsPrompt).toEqual(instructionsPrompt);});+ test('should restore a linked Langfuse prompt-group exact-version selection present in the reverted version', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();+ const instructionsPrompt = {+ source: 'langfuse',+ groupId: new mongoose.Types.ObjectId().toString(),+ selection: { type: 'exact', version: 5 },+ };++ await createAgent({+ id: agentId,+ name: 'Linked Langfuse Instructions Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt,+ });+ await updateAgent({ id: agentId }, { instructionsPrompt: null });++ const revertedAgent = await revertAgentVersion({ id: agentId }, 0);++ expect(revertedAgent.instructionsPrompt).toEqual(instructionsPrompt);+ });+test('should clear a Git identity absent from the restored version', async () => {const agentId = `agent_${uuidv4()}`;const authorId = new mongoose.Types.ObjectId();@@ -3742,6 +3846,43 @@ describe('Agent Methods', () => {});});+ test('should create a new version when the linked Langfuse prompt-group exact-version selection changes', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();+ const groupId = new mongoose.Types.ObjectId().toString();++ await createAgent({+ id: agentId,+ name: 'Test Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ instructionsPrompt: {+ source: 'langfuse',+ groupId,+ selection: { type: 'exact', version: 1 },+ },+ });++ const updatedAgent = await updateAgent(+ { id: agentId },+ {+ instructionsPrompt: {+ source: 'langfuse',+ groupId,+ selection: { type: 'exact', version: 2 },+ },+ },+ );++ expect(updatedAgent!.versions).toHaveLength(2);+ expect(updatedAgent!.instructionsPrompt).toMatchObject({+ source: 'langfuse',+ groupId,+ selection: { type: 'exact', version: 2 },+ });+ });+test('should handle isDuplicateVersion with mixed primitive and object arrays', async () => {const agentId = `agent_${uuidv4()}`;const authorId = new mongoose.Types.ObjectId();diff --git a/packages/data-schemas/src/schema/agent.ts b/packages/data-schemas/src/schema/agent.tsindex c959980aea..be6e471585 100644--- a/packages/data-schemas/src/schema/agent.ts+++ b/packages/data-schemas/src/schema/agent.ts@@ -100,13 +100,14 @@ const agentSchema: Schema<IAgent> = new Schema<IAgent>(instructionsPrompt: {type: new Schema({- source: { type: String, enum: ['native'], required: true },+ source: { type: String, enum: ['native', 'langfuse'], required: true },groupId: { type: String, required: true },selection: {type: new Schema({type: { type: String, enum: ['production', 'exact'], required: true },promptId: { type: String },+ version: { type: Number },},{ _id: false },),diff --git a/packages/data-schemas/src/types/agent.ts b/packages/data-schemas/src/types/agent.tsindex e849fb8c2e..9fe0945970 100644--- a/packages/data-schemas/src/types/agent.ts+++ b/packages/data-schemas/src/types/agent.ts@@ -48,7 +48,7 @@ export interface IAgent extends Omit<Document, 'model'> {code_workspace_id?: string;repositoryInstructions?: 'prefer' | 'defer' | 'off';git_identity?: AgentGitIdentity | null;- /** Links these instructions to a native prompt group revision instead of inline text. */+ /** Replaces inline instructions with a linked prompt group revision. */instructionsPrompt?: AgentInstructionsPrompt | null;/** @deprecated Use edges instead */agent_ids?: string[];