Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🎴 feat: Use Langfuse Prompts from Cards and the Slash Command (#17104)

Atef Bellaaj6e397c33a265
diff --git a/api/server/routes/prompts.test.js b/api/server/routes/prompts.test.js
index ad768c6d63..3ca14eb918 100644
--- a/api/server/routes/prompts.test.js
+++ b/api/server/routes/prompts.test.js
@@ -1535,7 +1535,7 @@ describe('GET /api/prompts/groups/:groupId/resolve', () => {
});
}
- it('resolves the production label', async () => {
+ it('resolves the production label, with no sourceUrl for a non-admin', async () => {
mockLangfuseFetch(async () =>
textPromptResponse({
name: 'greeting',
@@ -1558,11 +1558,84 @@ describe('GET /api/prompts/groups/:groupId/resolve', () => {
version: 1,
labels: ['production'],
});
+ expect(response.body.sourceUrl).toBeUndefined();
const [url] = fetchSpy.mock.calls[0];
expect(url).toContain('label=production');
expect(url).not.toContain('version=');
});
+ it('resolves the production label with sourceUrl for an admin', async () => {
+ setTestUser(app, testUsers.admin);
+ mockLangfuseFetch(async () =>
+ textPromptResponse({
+ name: 'greeting',
+ version: 1,
+ type: 'text',
+ labels: ['production'],
+ prompt: 'Hello {{name}}',
+ }),
+ );
+
+ const response = await request(app)
+ .get(`/api/prompts/groups/${group._id}/resolve`)
+ .expect(200);
+
+ expect(response.body).toEqual({
+ source: 'langfuse',
+ groupId: group._id.toString(),
+ prompt: 'Hello {{name}}',
+ type: 'text',
+ version: 1,
+ labels: ['production'],
+ sourceUrl: 'https://langfuse.resolve.test/project/resolve-project/prompts/greeting',
+ });
+ });
+
+ it('allows a public viewer with no explicit grant to resolve the group, with no sourceUrl', async () => {
+ await grantPermission({
+ principalType: PrincipalType.PUBLIC,
+ principalId: null,
+ resourceType: ResourceType.PROMPTGROUP,
+ resourceId: group._id,
+ accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,
+ grantedBy: testUsers.owner._id,
+ });
+ setTestUser(app, testUsers.noAccess);
+ mockLangfuseFetch(async () =>
+ textPromptResponse({
+ name: 'greeting',
+ version: 1,
+ type: 'text',
+ labels: ['production'],
+ prompt: 'Hello {{name}}',
+ }),
+ );
+
+ const response = await request(app)
+ .get(`/api/prompts/groups/${group._id}/resolve`)
+ .expect(200);
+
+ expect(response.body).toEqual({
+ source: 'langfuse',
+ groupId: group._id.toString(),
+ prompt: 'Hello {{name}}',
+ type: 'text',
+ version: 1,
+ labels: ['production'],
+ });
+ expect(response.body.sourceUrl).toBeUndefined();
+ });
+
+ it('returns 403 for a user with no grant at all on the group', async () => {
+ setTestUser(app, testUsers.noAccess);
+
+ const response = await request(app)
+ .get(`/api/prompts/groups/${group._id}/resolve`)
+ .expect(403);
+
+ expect(response.body.error).toBe('Forbidden');
+ });
+
it('resolves an exact version and sends it with no label', async () => {
mockLangfuseFetch(async () =>
textPromptResponse({
@@ -1587,6 +1660,7 @@ describe('GET /api/prompts/groups/:groupId/resolve', () => {
version: 3,
labels: [],
});
+ expect(response.body.sourceUrl).toBeUndefined();
const [url] = fetchSpy.mock.calls[0];
expect(url).toContain('version=3');
expect(url).not.toContain('label=');
diff --git a/client/src/Providers/PromptGroupsContext.tsx b/client/src/Providers/PromptGroupsContext.tsx
index d86d6d3e6d..257c5aef5c 100644
--- a/client/src/Providers/PromptGroupsContext.tsx
+++ b/client/src/Providers/PromptGroupsContext.tsx
@@ -1,11 +1,18 @@
import React, { createContext, useContext, ReactNode, useCallback, useMemo, useState } from 'react';
+import { Cloud } from 'lucide-react';
import { PermissionTypes, Permissions } from 'librechat-data-provider';
import type { TPromptGroup } from 'librechat-data-provider';
import type { PromptOption } from '~/common';
-import { usePromptGroupsNav, useHasAccess, useCatalogReady, activateCatalog } from '~/hooks';
+import {
+ usePromptGroupsNav,
+ useHasAccess,
+ useCatalogReady,
+ activateCatalog,
+ useLocalize,
+} from '~/hooks';
+import { mapPromptGroups, isExternalPromptGroup } from '~/utils';
import { useGetAllPromptGroups } from '~/data-provider';
import { CategoryIcon } from '~/components/Prompts';
-import { mapPromptGroups } from '~/utils';
type AllPromptGroupsData =
| {
@@ -29,6 +36,7 @@ type PromptGroupsContextType =
const PromptGroupsContext = createContext<PromptGroupsContextType>(null);
export const PromptGroupsProvider = ({ children }: { children: ReactNode }) => {
+ const localize = useLocalize();
const hasAccess = useHasAccess({
permissionType: PermissionTypes.PROMPTS,
permission: Permissions.USE,
@@ -54,19 +62,31 @@ export const PromptGroupsProvider = ({ children }: { children: ReactNode }) => {
const { data: allGroupsData, isLoading: isLoadingAll } = useGetAllPromptGroups(undefined, {
enabled: promptsEnabled && allPromptsActive,
select: (data) => {
- const mappedArray: PromptOption[] = data.map((group) => ({
- id: group._id ?? '',
- type: 'prompt',
- value: group.command ?? group.name,
- label: `${group.command != null && group.command ? `/${group.command} - ` : ''}${
- group.name
- }: ${
- (group.oneliner?.length ?? 0) > 0
- ? group.oneliner
- : (group.productionPrompt?.prompt ?? '')
- }`,
- icon: <CategoryIcon category={group.category ?? ''} className="h-5 w-5" />,
- }));
+ const mappedArray: PromptOption[] = data.map((group) => {
+ if (isExternalPromptGroup(group)) {
+ return {
+ id: group._id ?? '',
+ type: 'prompt',
+ value: group.command ?? group.name,
+ label: group.name,
+ description: localize('com_ui_prompt_source_langfuse'),
+ icon: <Cloud className="h-5 w-5" />,
+ };
+ }
+ return {
+ id: group._id ?? '',
+ type: 'prompt',
+ value: group.command ?? group.name,
+ label: `${group.command != null && group.command ? `/${group.command} - ` : ''}${
+ group.name
+ }: ${
+ (group.oneliner?.length ?? 0) > 0
+ ? group.oneliner
+ : (group.productionPrompt?.prompt ?? '')
+ }`,
+ icon: <CategoryIcon category={group.category ?? ''} className="h-5 w-5" />,
+ };
+ });
const promptsMap = mapPromptGroups(data);
diff --git a/client/src/Providers/__tests__/PromptGroupsContext.spec.tsx b/client/src/Providers/__tests__/PromptGroupsContext.spec.tsx
new file mode 100644
index 0000000000..7712c3c6cb
--- /dev/null
+++ b/client/src/Providers/__tests__/PromptGroupsContext.spec.tsx
@@ -0,0 +1,107 @@
+/**
+ * Covers the `select` mapping in `PromptGroupsProvider`: a Langfuse-sourced
+ * group (pointer-only, no `productionPrompt`) renders as a `Cloud` icon with
+ * its bare name and a "Managed in Langfuse" description, so `MentionItem`
+ * shows the source instead of unresolved content; a native group keeps the
+ * existing oneliner/production-text label and category icon.
+ */
+import React from 'react';
+import { Cloud } from 'lucide-react';
+import { render, screen } from '@testing-library/react';
+import type { TPromptGroup } from 'librechat-data-provider';
+
+jest.mock('~/hooks', () => ({
+ usePromptGroupsNav: () => ({}),
+ useHasAccess: () => true,
+ useCatalogReady: () => true,
+ activateCatalog: jest.fn(),
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('~/components/Prompts', () => ({
+ CategoryIcon: () => <span data-testid="category-icon" />,
+}));
+
+const mockSampleGroups: TPromptGroup[] = [
+ {
+ _id: 'native-1',
+ name: 'Native Group',
+ source: 'native',
+ command: 'native-cmd',
+ productionPrompt: { prompt: 'Hello there' },
+ } as TPromptGroup,
+ {
+ _id: 'lf-1',
+ name: 'Langfuse Group',
+ source: 'langfuse',
+ sourcePromptName: 'lf-prompt',
+ } as TPromptGroup,
+];
+
+let mockCapturedSelect: ((data: TPromptGroup[]) => unknown) | undefined;
+
+jest.mock('~/data-provider', () => ({
+ useGetAllPromptGroups: (
+ _params: unknown,
+ options: { select: (data: TPromptGroup[]) => unknown },
+ ) => {
+ mockCapturedSelect = options.select;
+ return { data: options.select(mockSampleGroups), isLoading: false };
+ },
+}));
+
+/* Imported last, after every mock-supporting const above: the module these
+ bind to is required transitively (via `~/data-provider`/`~/components/Prompts`/
+ `~/hooks`) as soon as this import runs, so the mocks it reaches into must
+ already be initialized. */
+import { PromptGroupsProvider, usePromptGroupsContext } from '../PromptGroupsContext';
+
+function Consumer() {
+ const ctx = usePromptGroupsContext();
+ const groups = ctx?.allPromptGroups.data?.promptGroups ?? [];
+ return (
+ <ul>
+ {groups.map((group) => (
+ <li key={group.id}>
+ <span data-testid={`icon-${group.id}`}>
+ {React.isValidElement(group.icon) && group.icon.type === Cloud ? 'cloud' : 'category'}
+ </span>
+ <span data-testid={`label-${group.id}`}>{group.label}</span>
+ <span data-testid={`description-${group.id}`}>{group.description ?? ''}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+const renderProvider = () =>
+ render(
+ <PromptGroupsProvider>
+ <Consumer />
+ </PromptGroupsProvider>,
+ );
+
+describe('PromptGroupsContext select mapping', () => {
+ beforeEach(() => {
+ mockCapturedSelect = undefined;
+ });
+
+ it('gives a Langfuse group a Cloud icon, its bare name, and a source description', () => {
+ renderProvider();
+ expect(mockCapturedSelect).toBeDefined();
+ expect(screen.getByTestId('icon-lf-1')).toHaveTextContent('cloud');
+ expect(screen.getByTestId('label-lf-1')).toHaveTextContent('Langfuse Group');
+ expect(screen.getByTestId('description-lf-1')).toHaveTextContent(
+ 'com_ui_prompt_source_langfuse',
+ );
+ });
+
+ it('leaves a native group label, description, and icon unchanged', () => {
+ renderProvider();
+ expect(screen.getByTestId('icon-native-1')).toHaveTextContent('category');
+ expect(screen.getByTestId('label-native-1')).toHaveTextContent(
+ '/native-cmd - Native Group: Hello there',
+ );
+ expect(screen.getByTestId('description-native-1')).toHaveTextContent('');
+ });
+});
diff --git a/client/src/components/Chat/Input/PromptsCommand.tsx b/client/src/components/Chat/Input/PromptsCommand.tsx
index c4328388c7..4a3cd44b30 100644
--- a/client/src/components/Chat/Input/PromptsCommand.tsx
+++ b/client/src/components/Chat/Input/PromptsCommand.tsx
@@ -1,17 +1,22 @@
import { useState, useRef, useEffect, useMemo, memo, useCallback } from 'react';
import { AutoSizer, List } from 'react-virtualized';
import { useSetRecoilState, useRecoilValue } from 'recoil';
-import { Input, Spinner, useCombobox, useRemScale } from '@librechat/client';
+import { Input, Spinner, useCombobox, useRemScale, useToastContext } from '@librechat/client';
import type { TPromptGroup } from 'librechat-data-provider';
import type { PromptOption } from '~/common';
+import {
+ removeCharIfLast,
+ detectVariables,
+ isExternalPromptGroup,
+ getPromptResolveErrorMessage,
+} from '~/utils';
+import { activateCatalog, useLocalize, usePromptContentResolver } from '~/hooks';
+import useChatScopedRequest from '~/hooks/Prompts/useChatScopedRequest';
import useInitPopoverInput from '~/hooks/Input/useInitPopoverInput';
-import { removeCharIfLast, detectVariables } from '~/utils';
import { useRecordPromptUsage } from '~/data-provider';
import { VariableDialog } from '~/components/Prompts';
import { usePromptGroupsContext } from '~/Providers';
-import { activateCatalog } from '~/hooks';
import MentionItem from './MentionItem';
-import { useLocalize } from '~/hooks';
import store from '~/store';
const commandChar = '/';
@@ -22,6 +27,7 @@ const PopoverContainer = memo(
children,
isVariableDialogOpen,
variableGroup,
+ variableText,
setVariableDialogOpen,
textAreaRef,
}: {
@@ -29,6 +35,7 @@ const PopoverContainer = memo(
children: React.ReactNode;
isVariableDialogOpen: boolean;
variableGroup: TPromptGroup | null;
+ variableText: string | undefined;
setVariableDialogOpen: (isOpen: boolean) => void;
textAreaRef: React.MutableRefObject<HTMLTextAreaElement | null>;
}) => {
@@ -45,6 +52,7 @@ const PopoverContainer = memo(
});
}}
group={variableGroup}
+ promptText={variableText}
/>
</>
);
@@ -64,7 +72,9 @@ function PromptsCommand({
}) {
const localize = useLocalize();
const remScale = useRemScale();
+ const { showToast } = useToastContext();
const { mutate: recordUsage } = useRecordPromptUsage();
+ const resolvePromptContent = usePromptContentResolver();
const promptGroupsContext = usePromptGroupsContext();
const { allPromptGroups, hasAccess, requestAllPromptGroups } = promptGroupsContext ?? {};
const { data, isLoading } = allPromptGroups ?? {};
@@ -75,8 +85,17 @@ function PromptsCommand({
const inputRef = useRef<HTMLInputElement | null>(null);
const [isVariableDialogOpen, setVariableDialogOpen] = useState(false);
const [variableGroup, setVariableGroup] = useState<TPromptGroup | null>(null);
+ const [variableText, setVariableText] = useState<string | undefined>(undefined);
const setShowPromptsPopover = useSetRecoilState(store.showPromptsPopoverFamily(index));
+ /** A resolve that was started for one chat must not land on another; see
+ * `useChatScopedRequest` for the three cancellation keys. On cancel, a
+ * variable dialog opened from the stale read closes rather than
+ * surviving into the chat the user moved to. */
+ const { begin, isCurrent, isMounted } = useChatScopedRequest(index, () => {
+ setVariableDialogOpen(false);
+ });
+
const prompts = useMemo(() => data?.promptGroups, [data]);
const promptsMap = useMemo(() => data?.promptsMap, [data]);
@@ -94,7 +113,7 @@ function PromptsCommand({
});
const handleSelect = useCallback(
- (mention?: PromptOption, e?: React.KeyboardEvent<HTMLInputElement>) => {
+ async (mention?: PromptOption, e?: React.KeyboardEvent<HTMLInputElement>) => {
if (!mention) {
return;
}
@@ -112,19 +131,52 @@ function PromptsCommand({
return;
}
- const hasVariables = detectVariables(group.productionPrompt?.prompt ?? '');
- if (hasVariables) {
- if (e && e.key === 'Tab') {
- e.preventDefault();
+ const isLangfuse = isExternalPromptGroup(group);
+ /** Native resolution is synchronous, so the dialog-vs-submit split is already
+ * known here; a Langfuse group's content (and so its variables) is unknown
+ * until it resolves, so Tab's default focus move is held off either way. */
+ const hasKnownVariables =
+ !isLangfuse && detectVariables(group.productionPrompt?.prompt ?? '');
+ if (e && e.key === 'Tab' && (isLangfuse || hasKnownVariables)) {
+ e.preventDefault();
+ }
+
+ /** Supersedes a resolve still pending for a prior selection: `begin`
+ * bumps the token, so that request's own guard above now discards it
+ * instead of this one waiting behind it. */
+ const token = begin();
+ if (isLangfuse) {
+ showToast({ status: 'info', message: localize('com_ui_prompt_resolving') });
+ }
+ try {
+ const text = await resolvePromptContent(group);
+ /** The popover may have unmounted, or the active conversation may
+ * have changed, while the Langfuse resolve was in flight; a stale
+ * continuation must not submit, stage, or record for a chat the
+ * user left. */
+ if (!isMounted() || !isCurrent(token)) {
+ return;
}
- setVariableGroup(group);
- setVariableDialogOpen(true);
- return;
- } else {
- submitPrompt(group.productionPrompt?.prompt ?? '');
+ if (!text?.trim()) {
+ textAreaRef.current?.focus();
+ return;
+ }
+ if (detectVariables(text)) {
+ setVariableGroup(group);
+ setVariableText(text);
+ setVariableDialogOpen(true);
+ return;
+ }
+ submitPrompt(text);
if (group._id) {
recordUsage(group._id);
}
+ textAreaRef.current?.focus();
+ } catch (error) {
+ if (isMounted() && isCurrent(token)) {
+ showToast({ status: 'error', message: getPromptResolveErrorMessage(error, localize) });
+ textAreaRef.current?.focus();
+ }
}
},
[
@@ -135,6 +187,12 @@ function PromptsCommand({
promptsMap,
submitPrompt,
recordUsage,
+ resolvePromptContent,
+ showToast,
+ localize,
+ begin,
+ isCurrent,
+ isMounted,
],
);
@@ -146,6 +204,7 @@ function PromptsCommand({
/** Opening the picker before background warmup starts the fetch now */
activateCatalog('prompts');
setVariableGroup(null);
+ setVariableText(undefined);
}
}, [open, setSearchValue]);
@@ -213,6 +272,7 @@ function PromptsCommand({
index={index}
isVariableDialogOpen={isVariableDialogOpen}
variableGroup={variableGroup}
+ variableText={variableText}
setVariableDialogOpen={setVariableDialogOpen}
textAreaRef={textAreaRef}
>
diff --git a/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx b/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx
index f99647293d..4d5c5ef754 100644
--- a/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx
@@ -7,8 +7,13 @@
* non-empty list has to leave keyboard navigation working.
*/
import React from 'react';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { Cloud } from 'lucide-react';
+import { getDefaultStore } from 'jotai';
+import { MemoryRouter, useNavigate } from 'react-router-dom';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { TPromptGroup } from 'librechat-data-provider';
import type { PromptOption } from '~/common';
+import { navigationGenerationAtom } from '~/store/navigation';
const PLACEHOLDER = 'com_ui_command_usage_placeholder';
@@ -42,17 +47,49 @@ jest.mock('~/data-provider', () => ({
}));
const mockPromptGroupsContext = jest.fn();
+/** Only `conversationId` matters: a saved chat's invalidation effect keys on
+ * the id, and a draft chat's keys on the composer draft token instead of
+ * this object, so the mock just needs to return a stable reference until a
+ * test swaps it for a different id. */
+const mockConversation = { current: { conversationId: 'convo-1' as string | undefined } };
jest.mock('~/Providers', () => ({
usePromptGroupsContext: () => mockPromptGroupsContext(),
+ useChatContext: () => ({ conversation: mockConversation.current }),
+}));
+
+/** The real token lives in a module-level map keyed by composer index, which
+ * `useNewConvo` renews on a new-chat reset and keeps otherwise; the mock
+ * swaps in a plain symbol a test can renew by assignment. */
+const mockDraftToken = { current: Symbol('new-conversation-draft') };
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils'),
+ getNewConversationDraftToken: () => mockDraftToken.current,
}));
jest.mock('~/components/Prompts', () => ({
- VariableDialog: () => null,
+ VariableDialog: ({ open, promptText }: { open: boolean; promptText?: string }) =>
+ open ? <div data-testid="variable-dialog">{promptText}</div> : null,
}));
+const mockShowToast = jest.fn();
+jest.mock('@librechat/client', () => {
+ const actual = jest.requireActual('@librechat/client');
+ return {
+ ...actual,
+ useToastContext: () => ({ showToast: mockShowToast }),
+ };
+});
+
+/** Native groups resolve from local text with no request; a test overrides this
+ * per-call to drive the Langfuse resolve paths. */
+const mockResolve = jest.fn((group: TPromptGroup) =>
+ Promise.resolve(group.productionPrompt?.prompt ?? ''),
+);
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
activateCatalog: jest.fn(),
+ usePromptContentResolver: () => mockResolve,
}));
/* react-virtualized renders nothing in jsdom without a measured size; replace
@@ -119,8 +156,17 @@ beforeAll(() => {
beforeEach(() => {
jest.clearAllMocks();
+ /* `clearAllMocks` keeps a queued `mockResolvedValueOnce`/`mockRejectedValueOnce` from a
+ prior test; reset fully so each test starts from the plain pass-through resolver. */
+ mockResolve.mockReset();
+ mockResolve.mockImplementation((group: TPromptGroup) =>
+ Promise.resolve(group.productionPrompt?.prompt ?? ''),
+ );
document.body.innerHTML = '';
mockShowPromptsPopover.current = true;
+ mockConversation.current = { conversationId: 'convo-1' };
+ mockDraftToken.current = Symbol('new-conversation-draft');
+ getDefaultStore().set(navigationGenerationAtom, 0);
mockPromptGroupsContext.mockReturnValue({
hasAccess: true,
allPromptGroups: {
@@ -134,11 +180,35 @@ beforeEach(() => {
const renderCommand = () => {
const textAreaRef = makeTextarea('/');
const utils = render(
- <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={jest.fn()} />,
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={jest.fn()} />
+ </MemoryRouter>,
);
return { textAreaRef, ...utils };
};
+/** Renders `PromptsCommand` with a caller-supplied `textAreaRef`/`submitPrompt`,
+ * inside the same `MemoryRouter` the real app provides, since the component
+ * reads `useLocation()`. */
+const renderPromptsCommand = (
+ textAreaRef: React.MutableRefObject<HTMLTextAreaElement | null>,
+ submitPrompt: (textPrompt: string) => void,
+ initialPath = '/c/convo-1',
+) =>
+ render(
+ <MemoryRouter initialEntries={[initialPath]}>
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ </MemoryRouter>,
+ );
+
+/** Fires a route change to a different path, the way browser Back/Forward
+ * moves `/c/:id` directly through the router without the conversation
+ * object changing first. */
+function NavigateAwayTrigger({ to }: { to: string }) {
+ const navigate = useNavigate();
+ return <button type="button" data-testid="navigate-away" onClick={() => navigate(to)} />;
+}
+
describe('PromptsCommand keyboard navigation', () => {
it('renders nothing when the popover atom is false', () => {
mockShowPromptsPopover.current = false;
@@ -234,3 +304,426 @@ describe('PromptsCommand lazy prompt loading', () => {
expect(mockRequestAllPromptGroups).not.toHaveBeenCalled();
});
});
+
+describe('PromptsCommand Langfuse resolve', () => {
+ const langfuseGroup = {
+ _id: '3',
+ source: 'langfuse',
+ sourcePromptName: 'lf-prompt',
+ } as TPromptGroup;
+
+ const extendedPromptsMap = { ...promptsMap, '3': langfuseGroup };
+ const extendedPromptGroups: PromptOption[] = [
+ ...promptGroups,
+ makePrompt({
+ id: '3',
+ label: 'Gamma',
+ value: 'Gamma',
+ description: 'com_ui_prompt_source_langfuse',
+ icon: (
+ <span data-testid="cloud-icon">
+ <Cloud />
+ </span>
+ ),
+ }),
+ ];
+
+ beforeEach(() => {
+ mockPromptGroupsContext.mockReturnValue({
+ hasAccess: true,
+ allPromptGroups: {
+ data: { promptGroups: extendedPromptGroups, promptsMap: extendedPromptsMap },
+ isLoading: false,
+ },
+ requestAllPromptGroups: mockRequestAllPromptGroups,
+ });
+ });
+
+ it('renders a Cloud icon and the source description on a Langfuse row', () => {
+ renderCommand();
+ expect(screen.getByTestId('cloud-icon')).toBeInTheDocument();
+ expect(screen.getByText('com_ui_prompt_source_langfuse')).toBeInTheDocument();
+ });
+
+ it('shows the resolving toast, submits the resolved text, and records usage once', async () => {
+ mockResolve.mockResolvedValueOnce('Resolved Gamma text');
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'info',
+ message: 'com_ui_prompt_resolving',
+ });
+
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Resolved Gamma text'));
+ expect(mockRecordUsage).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsage).toHaveBeenCalledWith('3');
+ expect(textAreaRef.current).toBe(document.activeElement);
+ });
+
+ it('submits and records nothing, and refocuses the textarea, when a Langfuse resolve returns only whitespace', async () => {
+ mockResolve.mockResolvedValueOnce(' ');
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+
+ await waitFor(() => expect(mockResolve).toHaveBeenCalledTimes(1));
+ expect(submitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsage).not.toHaveBeenCalled();
+ expect(textAreaRef.current).toBe(document.activeElement);
+ });
+
+ it('shows the error toast and submits/records nothing when resolution fails', async () => {
+ mockResolve.mockRejectedValueOnce(new Error('boom'));
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message: 'com_ui_langfuse_prompt_error_fallback',
+ }),
+ );
+ expect(submitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsage).not.toHaveBeenCalled();
+ });
+
+ it('focuses the textarea when a Tab-selected Langfuse resolve fails', async () => {
+ mockResolve.mockRejectedValueOnce(new Error('boom'));
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ const input = getInput();
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.keyDown(input, { key: 'Tab' });
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message: 'com_ui_langfuse_prompt_error_fallback',
+ }),
+ );
+ expect(submitPrompt).not.toHaveBeenCalled();
+ expect(textAreaRef.current).toBe(document.activeElement);
+ });
+
+ it('discards a Langfuse resolve that completes after the popover unmounts', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ const { unmount } = renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ unmount();
+ resolveFn('Resolved Gamma text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsage).not.toHaveBeenCalled();
+ expect(mockShowToast).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'error' }));
+ });
+
+ it('discards a Langfuse resolve and clears the busy flag when a new-chat reset renews the draft token', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'new' };
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ const { rerender } = renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** `useNewConvo` renews the draft token on a new-chat reset, including
+ * when the composer is already on an unsaved chat; the invalidation
+ * must key on that, not on the conversation object, so a fresh
+ * selection is not blocked by the stale pending resolve. */
+ mockDraftToken.current = Symbol('new-conversation-draft');
+ rerender(
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ </MemoryRouter>,
+ );
+
+ /* Selecting Gamma closed the popover; reopen it the same way a user
+ would (focusing the input) before picking a fresh entry. */
+ fireEvent.focus(getInput());
+ fireEvent.click(screen.getByText('Alpha'));
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Alpha body'));
+ expect(mockRecordUsage).toHaveBeenCalledWith('1');
+
+ resolveFn('Resolved Gamma text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitPrompt).not.toHaveBeenCalledWith('Resolved Gamma text');
+ expect(mockRecordUsage).not.toHaveBeenCalledWith('3');
+ });
+
+ it('discards a Langfuse resolve and clears the busy flag when a navigation starts, before the target conversation commits', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** `navigateToConvo` bumps `navigationGenerationAtom` as soon as a
+ * navigation starts, before the target conversation's record is
+ * fetched and `conversationId` changes — simulate just that bump,
+ * with the conversation left untouched. `act` flushes the resulting
+ * re-render synchronously, the same way a real navigation's state
+ * update would land before this component's next render. */
+ act(() => {
+ getDefaultStore().set(navigationGenerationAtom, 1);
+ });
+
+ resolveFn('Resolved Gamma text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitPrompt).not.toHaveBeenCalledWith('Resolved Gamma text');
+ expect(mockRecordUsage).not.toHaveBeenCalledWith('3');
+
+ /* The busy flag was cleared by the generation bump, not just by the
+ discarded resolve's own `finally` block, so a fresh selection right
+ after is not blocked. */
+ fireEvent.focus(getInput());
+ fireEvent.click(screen.getByText('Alpha'));
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Alpha body'));
+ expect(mockRecordUsage).toHaveBeenCalledWith('1');
+ });
+
+ it('discards a Langfuse resolve and clears the busy flag when the route pathname changes, before the conversation updates', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ render(
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <NavigateAwayTrigger to="/c/convo-2" />
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** Browser Back/Forward moves `/c/:id` directly through the router;
+ * ChatRoute keeps the previous conversation mounted while the next one
+ * loads, so `conversationId` has not changed here even though the
+ * pathname has. */
+ fireEvent.click(screen.getByTestId('navigate-away'));
+
+ resolveFn('Resolved Gamma text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitPrompt).not.toHaveBeenCalledWith('Resolved Gamma text');
+ expect(mockRecordUsage).not.toHaveBeenCalledWith('3');
+
+ /* The busy flag was cleared by the pathname change, not just by the
+ discarded resolve's own `finally` block, so a fresh selection right
+ after is not blocked. */
+ fireEvent.focus(getInput());
+ fireEvent.click(screen.getByText('Alpha'));
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Alpha body'));
+ expect(mockRecordUsage).toHaveBeenCalledWith('1');
+ });
+
+ it('lets a pending Langfuse resolve complete when a same-path re-navigation leaves the pathname unchanged', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'new' };
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ render(
+ <MemoryRouter initialEntries={['/c/new']}>
+ <NavigateAwayTrigger to="/c/new" />
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** A same-path re-navigation to `/c/new`, such as a new-chat reset that
+ * lands back where it started, leaves the pathname unchanged and must
+ * not cancel the pending resolve. */
+ fireEvent.click(screen.getByTestId('navigate-away'));
+
+ resolveFn('Resolved Gamma text');
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Resolved Gamma text'));
+ expect(mockRecordUsage).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsage).toHaveBeenCalledWith('3');
+ });
+
+ it('lets a pending Langfuse resolve complete when a parameter edit replaces the conversation object on a draft chat', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'new' };
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ const { rerender } = renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** A parameter edit (e.g. `SidePanel/Parameters/Panel.tsx`) replaces the
+ * conversation object without renewing the draft token; the pending
+ * resolve must not be discarded. */
+ mockConversation.current = { conversationId: 'new' };
+ rerender(
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ </MemoryRouter>,
+ );
+
+ resolveFn('Resolved Gamma text');
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Resolved Gamma text'));
+ expect(mockRecordUsage).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsage).toHaveBeenCalledWith('3');
+ });
+
+ it('lets a pending Langfuse resolve complete when a same-chat update replaces the conversation object with the same id', async () => {
+ mockResolve.mockImplementationOnce(
+ () => new Promise<string>((resolve) => setTimeout(() => resolve('Resolved Gamma text'), 0)),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ const { rerender } = renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** Streaming sync, a pin, or a project change replaces the conversation
+ * object without changing its id; the pending resolve must not be
+ * discarded, since the chat identity (the id) has not changed. */
+ mockConversation.current = { conversationId: 'convo-1' };
+ rerender(
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <PromptsCommand index={0} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Resolved Gamma text'));
+ expect(mockRecordUsage).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsage).toHaveBeenCalledWith('3');
+
+ /* The busy flag clears normally through the resolve's own `finally`
+ block, so a fresh selection right after is not blocked. */
+ fireEvent.focus(getInput());
+ fireEvent.click(screen.getByText('Alpha'));
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Alpha body'));
+ expect(mockRecordUsage).toHaveBeenCalledWith('1');
+ });
+
+ it('shows no toast and submits immediately for a native entry', async () => {
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Alpha'));
+
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Alpha body'));
+ expect(mockShowToast).not.toHaveBeenCalled();
+ expect(mockRecordUsage).toHaveBeenCalledWith('1');
+ });
+
+ it('closes the variable dialog when a navigation starts while it is open', async () => {
+ mockResolve.mockResolvedValueOnce('Hello {{name}}');
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(await screen.findByTestId('variable-dialog')).toBeInTheDocument();
+
+ /** A dialog opened from a resolved Langfuse read must not survive a chat
+ * change and submit a variable fill into another chat. */
+ act(() => {
+ getDefaultStore().set(navigationGenerationAtom, 1);
+ });
+
+ await waitFor(() => expect(screen.queryByTestId('variable-dialog')).not.toBeInTheDocument());
+ });
+
+ it('supersedes a pending Langfuse resolve with a new selection, closing the popover and inserting the new prompt', async () => {
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ const submitPrompt = jest.fn();
+ const textAreaRef = makeTextarea('/');
+ renderPromptsCommand(textAreaRef, submitPrompt);
+
+ fireEvent.click(screen.getByText('Gamma'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ /** Gamma's own selection already closed the popover; reopen it the same
+ * way a user would before picking a different entry while Gamma's
+ * resolve is still pending. */
+ fireEvent.focus(getInput());
+ fireEvent.click(screen.getByText('Alpha'));
+
+ await waitFor(() => expect(submitPrompt).toHaveBeenCalledWith('Alpha body'));
+ expect(mockRecordUsage).toHaveBeenCalledWith('1');
+ expect(mockSetShowPromptsPopover).toHaveBeenLastCalledWith(false);
+
+ /** Gamma's late result is discarded: the second selection bumped the
+ * request token before this resolve settled. */
+ resolveFn('Resolved Gamma text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(submitPrompt).not.toHaveBeenCalledWith('Resolved Gamma text');
+ expect(mockRecordUsage).not.toHaveBeenCalledWith('3');
+ });
+});
diff --git a/client/src/components/Nav/SettingsTabs/Integrations/LangfuseConnection.tsx b/client/src/components/Nav/SettingsTabs/Integrations/LangfuseConnection.tsx
index 09026fbbc4..bd69d9978a 100644
--- a/client/src/components/Nav/SettingsTabs/Integrations/LangfuseConnection.tsx
+++ b/client/src/components/Nav/SettingsTabs/Integrations/LangfuseConnection.tsx
@@ -26,7 +26,7 @@ import {
useSyncLangfusePromptsMutation,
} from '~/data-provider';
import LangfusePromptsDialog from './LangfusePromptsDialog';
-import { getPromptErrorMessage } from './promptErrors';
+import { getPromptErrorMessage } from '~/utils';
import { useLocalize } from '~/hooks';
type ConnectionTestState = 'idle' | 'unverified' | 'checking' | 'connected' | 'failed';
diff --git a/client/src/components/Nav/SettingsTabs/Integrations/LangfusePromptsDialog.tsx b/client/src/components/Nav/SettingsTabs/Integrations/LangfusePromptsDialog.tsx
index e54fcd5d8f..b6480913ab 100644
--- a/client/src/components/Nav/SettingsTabs/Integrations/LangfusePromptsDialog.tsx
+++ b/client/src/components/Nav/SettingsTabs/Integrations/LangfusePromptsDialog.tsx
@@ -20,7 +20,7 @@ import {
import type { TLangfusePromptGetParams, TLangfusePromptListParams } from 'librechat-data-provider';
import type { FormEvent } from 'react';
import { useLangfusePromptQuery, useLangfusePromptsQuery } from '~/data-provider';
-import { getPromptErrorMessage } from './promptErrors';
+import { getPromptErrorMessage } from '~/utils';
import { useLocalize } from '~/hooks';
type LangfusePromptsDialogProps = {
diff --git a/client/src/components/Nav/SettingsTabs/Integrations/__tests__/promptErrors.spec.ts b/client/src/components/Nav/SettingsTabs/Integrations/__tests__/promptErrors.spec.ts
deleted file mode 100644
index 4b2262bcbc..0000000000
--- a/client/src/components/Nav/SettingsTabs/Integrations/__tests__/promptErrors.spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { getPromptErrorMessage } from '../promptErrors';
-
-/** An axios-style rejection the way the real backend sends one: an outer HTTP status plus a
- * `{ code, status? }` body. */
-function axiosError(outerStatus: number, data: { code?: string; status?: number } = {}) {
- return { isAxiosError: true, response: { status: outerStatus, data } };
-}
-
-const localize = (key: string, options?: Record<string, unknown>) =>
- options ? `${key}:${Object.values(options).join(',')}` : key;
-
-describe('getPromptErrorMessage', () => {
- it('returns the forbidden copy for a 403, ahead of any body code', () => {
- const error = axiosError(403, { message: 'Forbidden' } as { code?: string });
-
- expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_forbidden');
- });
-
- it('returns the forbidden copy for a 403 even when the body carries an unrelated code', () => {
- const error = axiosError(403, { code: 'unauthorized' });
-
- expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_forbidden');
- });
-
- it('maps the internal code to its localized copy', () => {
- const error = axiosError(500, { code: 'internal' });
-
- expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_internal');
- });
-
- it('maps a known code to its localized copy', () => {
- const error = axiosError(409, { code: 'already_running' });
-
- expect(getPromptErrorMessage(error, localize)).toBe(
- 'com_ui_langfuse_prompt_error_already_running',
- );
- });
-
- it('includes the Langfuse HTTP status for an upstream failure', () => {
- const error = axiosError(502, { code: 'upstream', status: 400 });
-
- expect(getPromptErrorMessage(error, localize)).toBe(
- 'com_ui_langfuse_prompt_error_upstream_status:400',
- );
- });
-
- it('falls back to the generic copy for an unmapped code', () => {
- const error = axiosError(500, { code: 'something_unexpected' });
-
- expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_fallback');
- });
-
- it('falls back to the generic copy for a non-axios error', () => {
- expect(getPromptErrorMessage(new Error('boom'), localize)).toBe(
- 'com_ui_langfuse_prompt_error_fallback',
- );
- });
-});
diff --git a/client/src/components/Nav/SettingsTabs/Integrations/promptErrors.ts b/client/src/components/Nav/SettingsTabs/Integrations/promptErrors.ts
deleted file mode 100644
index 18754cfde2..0000000000
--- a/client/src/components/Nav/SettingsTabs/Integrations/promptErrors.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import axios from 'axios';
-import type { TLangfusePromptErrorBody, TLangfusePromptErrorCode } from 'librechat-data-provider';
-import type { TranslationKeys, useLocalize } from '~/hooks';
-import { getResponseErrorCode, getResponseStatus } from '~/utils';
-
-/** Codes whose whole copy is one localized sentence; `upstream` is handled separately below
- * because its sentence needs the Langfuse HTTP status when the server sent one. */
-export const PROMPT_ERROR_MESSAGE_KEYS: Partial<Record<TLangfusePromptErrorCode, TranslationKeys>> =
- {
- not_configured: 'com_ui_langfuse_prompt_error_not_configured',
- unauthorized: 'com_ui_langfuse_prompt_error_unauthorized',
- timeout: 'com_ui_langfuse_prompt_error_timeout',
- invalid_response: 'com_ui_langfuse_prompt_error_invalid_response',
- not_found: 'com_ui_langfuse_prompt_error_not_found',
- unsupported_type: 'com_ui_langfuse_prompt_error_unsupported_type',
- invalid_request: 'com_ui_langfuse_prompt_error_invalid_request',
- already_running: 'com_ui_langfuse_prompt_error_already_running',
- lock_lost: 'com_ui_langfuse_prompt_error_lock_lost',
- internal: 'com_ui_langfuse_prompt_error_internal',
- };
-
-function getUpstreamStatus(error: unknown): number | undefined {
- if (!axios.isAxiosError<TLangfusePromptErrorBody>(error)) {
- return undefined;
- }
- const status = error.response?.data?.status;
- return typeof status === 'number' ? status : undefined;
-}
-
-/** Maps a failed Langfuse prompt call to one short localized line, with a generic fallback for
- * an unmapped or missing code (for example a bare 404 with no body, which means the feature is off).
- * A 403 is checked ahead of any body code: it means the caller lacks permission regardless of
- * what the body says, so it always wins. */
-export function getPromptErrorMessage(
- error: unknown,
- localize: ReturnType<typeof useLocalize>,
-): string {
- if (getResponseStatus(error) === 403) {
- return localize('com_ui_langfuse_prompt_error_forbidden');
- }
- const code = getResponseErrorCode<TLangfusePromptErrorCode>(error);
- if (code === 'upstream') {
- const status = getUpstreamStatus(error);
- return status != null
- ? localize('com_ui_langfuse_prompt_error_upstream_status', { 0: status })
- : localize('com_ui_langfuse_prompt_error_upstream');
- }
- const messageKey = code != null ? PROMPT_ERROR_MESSAGE_KEYS[code] : undefined;
- return localize(messageKey ?? 'com_ui_langfuse_prompt_error_fallback');
-}
diff --git a/client/src/components/Prompts/dialogs/PreviewPrompt.tsx b/client/src/components/Prompts/dialogs/PreviewPrompt.tsx
index 19cc9e6adb..6be4b2152b 100644
--- a/client/src/components/Prompts/dialogs/PreviewPrompt.tsx
+++ b/client/src/components/Prompts/dialogs/PreviewPrompt.tsx
@@ -5,11 +5,16 @@ import { useLocalize } from '~/hooks';
const PreviewPrompt = ({
group,
+ chatIndex,
open,
onOpenChange,
onCloseAutoFocus,
}: {
group: TPromptGroup;
+ /** The chat composer's index, forwarded to `PromptDetails` so its Use
+ * button can close a variable dialog opened from this preview on a
+ * chat change; undefined when this preview has no associated chat. */
+ chatIndex?: number;
open: boolean;
onOpenChange: (open: boolean) => void;
onCloseAutoFocus?: () => void;
@@ -22,7 +27,11 @@ const PreviewPrompt = ({
onCloseAutoFocus={onCloseAutoFocus}
>
<OGDialogTitle className="sr-only">{localize('com_ui_preview')}</OGDialogTitle>
- <PromptDetails group={group} onUsePrompt={() => onOpenChange(false)} />
+ <PromptDetails
+ group={group}
+ chatIndex={chatIndex}
+ onUsePrompt={() => onOpenChange(false)}
+ />
</OGDialogContent>
</OGDialog>
);
diff --git a/client/src/components/Prompts/dialogs/VariableDialog.tsx b/client/src/components/Prompts/dialogs/VariableDialog.tsx
index c8eb979bcd..8c03049021 100644
--- a/client/src/components/Prompts/dialogs/VariableDialog.tsx
+++ b/client/src/components/Prompts/dialogs/VariableDialog.tsx
@@ -8,19 +8,19 @@ import { detectVariables } from '~/utils';
interface VariableDialogProps extends Omit<DialogPrimitive.DialogProps, 'onOpenChange'> {
onClose: () => void;
group: TPromptGroup | null;
+ /** Resolved prompt text; falls back to the production prompt when absent. */
+ promptText?: string;
}
-const VariableDialog: React.FC<VariableDialogProps> = ({ open, onClose, group }) => {
+const VariableDialog: React.FC<VariableDialogProps> = ({ open, onClose, group, promptText }) => {
const handleOpenChange = (open: boolean) => {
if (!open) {
onClose();
}
};
- const hasVariables = useMemo(
- () => detectVariables(group?.productionPrompt?.prompt ?? ''),
- [group?.productionPrompt?.prompt],
- );
+ const mainText = promptText ?? group?.productionPrompt?.prompt ?? '';
+ const hasVariables = useMemo(() => detectVariables(mainText), [mainText]);
if (!group) {
return null;
}
@@ -33,7 +33,7 @@ const VariableDialog: React.FC<VariableDialogProps> = ({ open, onClose, group })
<OGDialog open={open} onOpenChange={handleOpenChange}>
<OGDialogContent className="text-text-primary max-h-[90vh] max-w-full overflow-y-auto md:max-w-[60vw]">
<OGDialogTitle>{group.name}</OGDialogTitle>
- <VariableForm group={group} onClose={onClose} />
+ <VariableForm group={group} onClose={onClose} promptText={promptText} />
</OGDialogContent>
</OGDialog>
);
diff --git a/client/src/components/Prompts/display/LangfusePromptMeta.tsx b/client/src/components/Prompts/display/LangfusePromptMeta.tsx
new file mode 100644
index 0000000000..202a949161
--- /dev/null
+++ b/client/src/components/Prompts/display/LangfusePromptMeta.tsx
@@ -0,0 +1,41 @@
+import { ExternalLink } from 'lucide-react';
+import type { TResolvedLangfusePrompt } from 'librechat-data-provider';
+import { useLocalize } from '~/hooks';
+
+interface LangfusePromptMetaProps {
+ resolved: TResolvedLangfusePrompt;
+}
+
+/**
+ * Version/labels line and deep link for a resolved Langfuse prompt, shared
+ * between `PromptDetails` and `PromptForm`'s `ExternalPromptGroupView` so the
+ * two surfaces render it identically. The server omits `sourceUrl` for a
+ * non-admin requester (`toResolveResponse` in `packages/api/src/prompts/handlers.ts`),
+ * so the link renders here whenever it is present.
+ */
+const LangfusePromptMeta = ({ resolved }: LangfusePromptMetaProps) => {
+ const localize = useLocalize();
+ const hasSourceUrl = Boolean(resolved.sourceUrl);
+
+ return (
+ <div className="text-text-secondary flex flex-wrap items-center gap-3 text-xs">
+ <span>
+ {localize('com_ui_prompt_version', { 0: resolved.version })}
+ {resolved.labels.length > 0 ? ` · ${resolved.labels.join(', ')}` : ''}
+ </span>
+ {hasSourceUrl && (
+ <a
+ href={resolved.sourceUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-link hover:text-link-hover inline-flex items-center gap-1 hover:underline"
+ >
+ <ExternalLink className="h-3 w-3" aria-hidden="true" />
+ {localize('com_ui_prompt_open_in_langfuse')}
+ </a>
+ )}
+ </div>
+ );
+};
+
+export default LangfusePromptMeta;
diff --git a/client/src/components/Prompts/display/PromptActions.tsx b/client/src/components/Prompts/display/PromptActions.tsx
index 5e8acc3a04..115ded6b50 100644
--- a/client/src/components/Prompts/display/PromptActions.tsx
+++ b/client/src/components/Prompts/display/PromptActions.tsx
@@ -1,65 +1,43 @@
-import { useState, useMemo, useCallback } from 'react';
-import { Send } from 'lucide-react';
-import { Button } from '@librechat/client';
import type { TPromptGroup } from 'librechat-data-provider';
-import { useLocalize, useSubmitMessage } from '~/hooks';
-import { useRecordPromptUsage } from '~/data-provider';
-import VariableDialog from '../dialogs/VariableDialog';
import SharePrompt from '../dialogs/SharePrompt';
-import { detectVariables } from '~/utils';
+import UsePromptButton from './UsePromptButton';
interface PromptActionsProps {
group: TPromptGroup;
- mainText: string;
+ /** The prompt text `UsePromptButton` submits or detects variables in. */
+ promptText: string;
+ /** Forwarded to `UsePromptButton`: true while `promptText` is still being
+ * resolved (e.g. a live Langfuse read). */
+ isLoading?: boolean;
+ /** Forwarded to `UsePromptButton`: true when resolving `promptText` failed. */
+ hasError?: boolean;
onUsePrompt?: () => void;
+ /** Forwarded to `UsePromptButton`: the chat composer's index, or undefined
+ * where there is no associated chat. */
+ chatIndex?: number;
}
-const PromptActions = ({ group, mainText, onUsePrompt }: PromptActionsProps) => {
- const localize = useLocalize();
- const { submitPrompt } = useSubmitMessage();
- const { mutate: recordUsage } = useRecordPromptUsage();
- const [showVariableDialog, setShowVariableDialog] = useState(false);
-
- const hasVariables = useMemo(
- () => detectVariables(group.productionPrompt?.prompt ?? ''),
- [group.productionPrompt?.prompt],
- );
-
- const handleUsePrompt = useCallback(() => {
- if (hasVariables) {
- setShowVariableDialog(true);
- } else {
- submitPrompt(mainText);
- if (group._id) {
- recordUsage(group._id);
- }
- onUsePrompt?.();
- }
- }, [hasVariables, submitPrompt, mainText, onUsePrompt, group._id, recordUsage]);
-
- const handleVariableDialogClose = useCallback(() => {
- setShowVariableDialog(false);
- onUsePrompt?.();
- }, [onUsePrompt]);
-
+const PromptActions = ({
+ group,
+ promptText,
+ isLoading = false,
+ hasError = false,
+ onUsePrompt,
+ chatIndex,
+}: PromptActionsProps) => {
return (
- <>
- <div className="flex w-full gap-2 sm:justify-end sm:gap-3">
- <SharePrompt group={group} disabled={false} />
-
- <Button
- variant="submit"
- onClick={handleUsePrompt}
- className="flex-1 sm:min-w-40 sm:flex-none"
- aria-label={localize('com_ui_use_prompt')}
- >
- <Send className="h-4 w-4" aria-hidden="true" />
- {localize('com_ui_use_prompt')}
- </Button>
- </div>
-
- <VariableDialog open={showVariableDialog} onClose={handleVariableDialogClose} group={group} />
- </>
+ <div className="flex w-full gap-2 sm:justify-end sm:gap-3">
+ <SharePrompt group={group} disabled={false} />
+
+ <UsePromptButton
+ group={group}
+ promptText={promptText}
+ isLoading={isLoading}
+ hasError={hasError}
+ onUsePrompt={onUsePrompt}
+ chatIndex={chatIndex}
+ />
+ </div>
);
};
diff --git a/client/src/components/Prompts/display/PromptDetailHeader.tsx b/client/src/components/Prompts/display/PromptDetailHeader.tsx
index 7bb0fb8e52..0cd2fd5c00 100644
--- a/client/src/components/Prompts/display/PromptDetailHeader.tsx
+++ b/client/src/components/Prompts/display/PromptDetailHeader.tsx
@@ -1,9 +1,10 @@
import { format } from 'date-fns';
import { TooltipAnchor } from '@librechat/client';
-import { User, Calendar, EarthIcon, BarChart3 } from 'lucide-react';
+import { User, Calendar, EarthIcon, BarChart3, Cloud } from 'lucide-react';
import type { TPromptGroup } from 'librechat-data-provider';
import { useLocalize, useAuthContext } from '~/hooks';
import CategoryIcon from '../utils/CategoryIcon';
+import { isExternalPromptGroup } from '~/utils';
interface PromptDetailHeaderProps {
group: TPromptGroup;
@@ -16,18 +17,19 @@ const PromptDetailHeader = ({ group }: PromptDetailHeaderProps) => {
const isSharedPrompt = group.author !== user?.id && Boolean(group.authorName);
const isGlobalGroup = group.isPublic === true;
+ const isExternal = isExternalPromptGroup(group);
return (
<div className="flex flex-col gap-3 py-2 sm:flex-row sm:items-center sm:gap-4">
{group.category && (
- <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-surface-secondary">
+ <div className="bg-surface-secondary flex h-12 w-12 shrink-0 items-center justify-center rounded-full">
<CategoryIcon category={group.category} className="h-6 w-6" />
</div>
)}
<div className="min-w-0 flex-1 overflow-hidden">
<div className="flex min-w-0 items-center gap-2">
- <h2 className="truncate text-xl font-bold text-text-primary" title={group.name}>
+ <h2 className="text-text-primary truncate text-xl font-bold" title={group.name}>
{group.name}
</h2>
{isGlobalGroup && (
@@ -36,20 +38,32 @@ const PromptDetailHeader = ({ group }: PromptDetailHeaderProps) => {
side="top"
render={
<EarthIcon
- className="h-5 w-5 shrink-0 text-accent-primary"
+ className="text-accent-primary h-5 w-5 shrink-0"
aria-label={localize('com_ui_sr_global_prompt')}
/>
}
/>
)}
+ {isExternal && (
+ <TooltipAnchor
+ description={localize('com_ui_prompt_source_langfuse')}
+ side="top"
+ render={
+ <Cloud
+ className="text-text-secondary h-5 w-5 shrink-0"
+ aria-label={localize('com_ui_prompt_source_langfuse')}
+ />
+ }
+ />
+ )}
</div>
{group.oneliner && (
- <p className="text-sm text-text-secondary sm:truncate">{group.oneliner}</p>
+ <p className="text-text-secondary text-sm sm:truncate">{group.oneliner}</p>
)}
- <div className="mt-1 flex flex-wrap items-center gap-3 text-xs text-text-secondary">
+ <div className="text-text-secondary mt-1 flex flex-wrap items-center gap-3 text-xs">
{isSharedPrompt && (
<span className="flex items-center gap-1">
- <User className="h-3 w-3 text-text-secondary" aria-hidden="true" />
+ <User className="text-text-secondary h-3 w-3" aria-hidden="true" />
{localize('com_ui_by_author', { 0: group.authorName })}
</span>
)}
diff --git a/client/src/components/Prompts/display/PromptDetails.tsx b/client/src/components/Prompts/display/PromptDetails.tsx
index 092faae6ce..4ad1505e4a 100644
--- a/client/src/components/Prompts/display/PromptDetails.tsx
+++ b/client/src/components/Prompts/display/PromptDetails.tsx
@@ -2,26 +2,37 @@ import { useMemo } from 'react';
import { SquareSlash } from 'lucide-react';
import { replaceSpecialVars } from 'librechat-data-provider';
import type { TPromptGroup } from 'librechat-data-provider';
-import { useLocalize, useAuthContext } from '~/hooks';
+import { useLocalize, useAuthContext, usePromptContent } from '~/hooks';
+import LangfusePromptMeta from './LangfusePromptMeta';
import PromptDetailHeader from './PromptDetailHeader';
+import PromptResolvedBody from './PromptResolvedBody';
import PromptVariables from './PromptVariables';
-import PromptTextCard from './PromptTextCard';
import PromptActions from './PromptActions';
interface PromptDetailsProps {
group?: TPromptGroup;
showActions?: boolean;
onUsePrompt?: () => void;
+ /** The chat composer's index, forwarded to `PromptActions` so its Use
+ * button can close a variable dialog opened from this view on a chat
+ * change; undefined where there is no associated chat (`PromptForm`'s
+ * `showActions={false}` read-only view). */
+ chatIndex?: number;
}
-const PromptDetails = ({ group, showActions = true, onUsePrompt }: PromptDetailsProps) => {
+const PromptDetails = ({
+ group,
+ showActions = true,
+ onUsePrompt,
+ chatIndex,
+}: PromptDetailsProps) => {
const localize = useLocalize();
const { user } = useAuthContext();
- const mainText = useMemo(() => {
- const initialText = group?.productionPrompt?.prompt ?? '';
- return replaceSpecialVars({ text: initialText, user });
- }, [group?.productionPrompt?.prompt, user]);
+ const { text, resolved, isLoading, error, refetch } = usePromptContent(group);
+ const hasError = Boolean(error);
+
+ const mainText = useMemo(() => replaceSpecialVars({ text, user }), [text, user]);
if (!group) {
return null;
@@ -36,19 +47,35 @@ const PromptDetails = ({ group, showActions = true, onUsePrompt }: PromptDetails
<PromptDetailHeader group={group} />
<div className="min-h-0 flex-1">
- <PromptTextCard mainText={mainText} />
+ <PromptResolvedBody
+ mainText={mainText}
+ isLoading={isLoading}
+ error={error}
+ onRetry={refetch}
+ />
</div>
- <PromptVariables promptText={mainText} />
+ {!isLoading && !hasError && <PromptVariables promptText={mainText} />}
+
+ {resolved?.source === 'langfuse' && <LangfusePromptMeta resolved={resolved} />}
{group.command && (
- <div className="flex items-center gap-2 rounded-xl border border-border-medium bg-transparent p-3">
- <SquareSlash className="h-4 w-4 text-text-secondary" aria-hidden="true" />
- <span className="font-mono text-sm text-text-primary">/{group.command}</span>
+ <div className="border-border-medium flex items-center gap-2 rounded-xl border bg-transparent p-3">
+ <SquareSlash className="text-text-secondary h-4 w-4" aria-hidden="true" />
+ <span className="text-text-primary font-mono text-sm">/{group.command}</span>
</div>
)}
- {showActions && <PromptActions group={group} mainText={mainText} onUsePrompt={onUsePrompt} />}
+ {showActions && (
+ <PromptActions
+ group={group}
+ promptText={mainText}
+ isLoading={isLoading}
+ hasError={hasError}
+ onUsePrompt={onUsePrompt}
+ chatIndex={chatIndex}
+ />
+ )}
</article>
);
};
diff --git a/client/src/components/Prompts/display/PromptResolvedBody.tsx b/client/src/components/Prompts/display/PromptResolvedBody.tsx
new file mode 100644
index 0000000000..6e4425000e
--- /dev/null
+++ b/client/src/components/Prompts/display/PromptResolvedBody.tsx
@@ -0,0 +1,49 @@
+import { Button, Spinner } from '@librechat/client';
+import { getPromptResolveErrorMessage } from '~/utils';
+import PromptTextCard from './PromptTextCard';
+import { useLocalize } from '~/hooks';
+
+interface PromptResolvedBodyProps {
+ mainText: string;
+ isLoading: boolean;
+ error: unknown;
+ /** Re-issues the resolve request. Omitted hides the retry button. */
+ onRetry?: () => void;
+}
+
+/**
+ * The loading / error / resolved-text block shared by `PromptDetails` and
+ * `PromptForm`'s `ExternalPromptGroupView`, so a pending or failed Langfuse
+ * resolve reads identically in both surfaces.
+ */
+const PromptResolvedBody = ({ mainText, isLoading, error, onRetry }: PromptResolvedBodyProps) => {
+ const localize = useLocalize();
+
+ if (isLoading) {
+ return (
+ <div className="text-text-secondary flex h-full flex-col items-center justify-center gap-2 text-sm">
+ <Spinner className="size-5" aria-hidden="true" />
+ <span>{localize('com_ui_prompt_resolving')}</span>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-2 p-3 text-sm">
+ <p role="alert" className="text-text-destructive text-center">
+ {getPromptResolveErrorMessage(error, localize)}
+ </p>
+ {onRetry && (
+ <Button type="button" variant="outline" onClick={onRetry}>
+ {localize('com_ui_retry')}
+ </Button>
+ )}
+ </div>
+ );
+ }
+
+ return <PromptTextCard mainText={mainText} />;
+};
+
+export default PromptResolvedBody;
diff --git a/client/src/components/Prompts/display/UsePromptButton.tsx b/client/src/components/Prompts/display/UsePromptButton.tsx
new file mode 100644
index 0000000000..188c5a2371
--- /dev/null
+++ b/client/src/components/Prompts/display/UsePromptButton.tsx
@@ -0,0 +1,111 @@
+import { useState, useMemo, useCallback } from 'react';
+import { Send } from 'lucide-react';
+import { Button } from '@librechat/client';
+import type { TPromptGroup } from 'librechat-data-provider';
+import useChatScopedRequest from '~/hooks/Prompts/useChatScopedRequest';
+import { useLocalize, useSubmitMessage } from '~/hooks';
+import { useRecordPromptUsage } from '~/data-provider';
+import VariableDialog from '../dialogs/VariableDialog';
+import { detectVariables } from '~/utils';
+
+interface UsePromptButtonProps {
+ group: TPromptGroup;
+ /** The prompt text to submit or detect variables in: production text for a
+ * native group, resolved text for an externally managed one. This button
+ * does not resolve content itself; the caller supplies it. */
+ promptText: string;
+ /** True while the caller is still resolving `promptText` (e.g. a live
+ * Langfuse read); disables the button so a stale or empty value can't be
+ * submitted. */
+ isLoading?: boolean;
+ /** True when resolving `promptText` failed; disables the button, since a
+ * failed resolution must record no usage. */
+ hasError?: boolean;
+ onUsePrompt?: () => void;
+ /** The chat composer's index; defined only when this button renders inside
+ * a chat (reached from `ChatGroupItem`'s preview dialog). Closes the
+ * variable dialog on a chat change, the same way `ChatGroupItem` and
+ * `PromptsCommand` do, via `useChatScopedRequest`. */
+ chatIndex?: number;
+}
+
+/** Mounted only when `chatIndex` is defined, since `useChatScopedRequest`
+ * reads `useChatContext`, which throws outside a chat. */
+const VariableDialogCanceller = ({
+ chatIndex,
+ onCancel,
+}: {
+ chatIndex: number;
+ onCancel: () => void;
+}) => {
+ useChatScopedRequest(chatIndex, onCancel);
+ return null;
+};
+
+const UsePromptButton = ({
+ group,
+ promptText,
+ isLoading = false,
+ hasError = false,
+ onUsePrompt,
+ chatIndex,
+}: UsePromptButtonProps) => {
+ const localize = useLocalize();
+ const { submitPrompt } = useSubmitMessage();
+ const { mutate: recordUsage } = useRecordPromptUsage();
+ const [showVariableDialog, setShowVariableDialog] = useState(false);
+
+ const hasVariables = useMemo(() => detectVariables(promptText), [promptText]);
+ const disabled = isLoading || hasError || promptText.trim().length === 0;
+
+ const handleUsePrompt = useCallback(() => {
+ if (disabled) {
+ return;
+ }
+ if (hasVariables) {
+ setShowVariableDialog(true);
+ } else {
+ submitPrompt(promptText);
+ if (group._id) {
+ recordUsage(group._id);
+ }
+ onUsePrompt?.();
+ }
+ }, [disabled, hasVariables, submitPrompt, promptText, onUsePrompt, group._id, recordUsage]);
+
+ const handleVariableDialogClose = useCallback(() => {
+ setShowVariableDialog(false);
+ onUsePrompt?.();
+ }, [onUsePrompt]);
+
+ return (
+ <>
+ <Button
+ variant="submit"
+ onClick={handleUsePrompt}
+ disabled={disabled}
+ className="flex-1 sm:min-w-40 sm:flex-none"
+ aria-label={localize('com_ui_use_prompt')}
+ >
+ <Send className="h-4 w-4" aria-hidden="true" />
+ {localize('com_ui_use_prompt')}
+ </Button>
+
+ <VariableDialog
+ open={showVariableDialog}
+ onClose={handleVariableDialogClose}
+ group={group}
+ promptText={promptText}
+ />
+
+ {chatIndex !== undefined && (
+ <VariableDialogCanceller
+ chatIndex={chatIndex}
+ onCancel={() => setShowVariableDialog(false)}
+ />
+ )}
+ </>
+ );
+};
+
+export default UsePromptButton;
diff --git a/client/src/components/Prompts/display/__tests__/PromptDetails.spec.tsx b/client/src/components/Prompts/display/__tests__/PromptDetails.spec.tsx
new file mode 100644
index 0000000000..3a32e96b43
--- /dev/null
+++ b/client/src/components/Prompts/display/__tests__/PromptDetails.spec.tsx
@@ -0,0 +1,201 @@
+import React from 'react';
+import '@testing-library/jest-dom/extend-expect';
+import { dataService, SystemRoles } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
+import type { TPromptGroup, TResolvedLangfusePrompt } from 'librechat-data-provider';
+import PromptDetails from '../PromptDetails';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ resolvePromptGroup: jest.fn(),
+ },
+ };
+});
+
+const resolvePromptGroup = dataService.resolvePromptGroup as jest.MockedFunction<
+ typeof dataService.resolvePromptGroup
+>;
+
+const mockSubmitPrompt = jest.fn();
+const mockRecordUsage = jest.fn();
+// Mutable so individual tests can exercise an admin vs. a regular user.
+let mockUser: { id: string; role?: string } = { id: 'user-1', role: SystemRoles.USER };
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, values?: Record<string, unknown>) =>
+ values ? `${key} ${JSON.stringify(values)}` : key,
+ useAuthContext: () => ({ user: mockUser }),
+ useSubmitMessage: () => ({ submitPrompt: mockSubmitPrompt }),
+ // The real hook: the point of these tests is to exercise its loading,
+ // success and error outcomes end-to-end, including the "no request for a
+ // native group" guarantee.
+ usePromptContent: jest.requireActual('~/hooks/Prompts/usePromptContent').default,
+}));
+
+jest.mock('~/data-provider', () => {
+ const actual = jest.requireActual('~/data-provider');
+ return {
+ ...actual,
+ useRecordPromptUsage: () => ({ mutate: mockRecordUsage }),
+ };
+});
+
+// SharePrompt pulls in ACL/resource-permission hooks unrelated to this
+// component's own behavior; stubbed the same way `PromptForm.spec.tsx` stubs
+// its sibling dialogs.
+jest.mock('../../dialogs/SharePrompt', () => ({
+ __esModule: true,
+ default: () => <button type="button" data-testid="share-prompt" />,
+}));
+
+function makeGroup(overrides: Partial<TPromptGroup> = {}): TPromptGroup {
+ return {
+ _id: 'group-1',
+ name: 'Example Group',
+ author: 'author-1',
+ authorName: 'Author',
+ source: 'native',
+ productionPrompt: { prompt: 'Native production text' },
+ ...overrides,
+ } as TPromptGroup;
+}
+
+function langfuseResolved(
+ overrides: Partial<TResolvedLangfusePrompt> = {},
+): TResolvedLangfusePrompt {
+ return {
+ source: 'langfuse',
+ groupId: 'group-1',
+ prompt: 'Live Langfuse text',
+ type: 'text',
+ version: 3,
+ labels: ['production', 'latest'],
+ sourceUrl: 'https://cloud.langfuse.test/project/project-1/prompts/greeting',
+ ...overrides,
+ };
+}
+
+const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+function renderDetails(group: TPromptGroup) {
+ const queryClient = createQueryClient();
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <PromptDetails group={group} />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockUser = { id: 'user-1', role: SystemRoles.USER };
+});
+
+// `PromptDetailHeader`'s source badge is a bare `<svg aria-label>` (matching
+// the existing `EarthIcon` global badge beside it); jsdom's role computation
+// has no implicit "img" mapping for a plain `<svg>`, so presence is checked
+// by its `aria-label` attribute directly rather than through `getByRole`.
+const findSourceBadge = (container: HTMLElement) =>
+ container.querySelector('[aria-label="com_ui_prompt_source_langfuse"]');
+
+describe('PromptDetails', () => {
+ it('renders a native group synchronously with no resolve request', () => {
+ const { container } = renderDetails(makeGroup());
+
+ expect(screen.getByText('Native production text')).toBeInTheDocument();
+ expect(resolvePromptGroup).not.toHaveBeenCalled();
+ expect(findSourceBadge(container)).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'com_ui_use_prompt' })).toBeEnabled();
+ });
+
+ it('shows the resolving label and disables Use while a Langfuse group is loading', () => {
+ resolvePromptGroup.mockReturnValue(new Promise(() => {}));
+ const { container } = renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ expect(screen.getByText('com_ui_prompt_resolving')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'com_ui_use_prompt' })).toBeDisabled();
+ expect(findSourceBadge(container)).toBeInTheDocument();
+ });
+
+ it('renders the resolved text, variables and version/labels line on success', async () => {
+ resolvePromptGroup.mockResolvedValue(langfuseResolved({ prompt: 'Hello {{name}}' }));
+ renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ await waitFor(() => expect(screen.getByText(/Hello/)).toBeInTheDocument());
+
+ expect(screen.getByRole('list', { name: 'com_ui_prompt_variables_list' })).toBeInTheDocument();
+ expect(
+ screen.getByText('com_ui_prompt_version {"0":3} · production, latest'),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'com_ui_use_prompt' })).toBeEnabled();
+ });
+
+ it('renders the error copy with role=alert and disables Use on a failed resolution', async () => {
+ resolvePromptGroup.mockRejectedValue(new Error('resolve failed'));
+ renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('com_ui_langfuse_prompt_error_fallback');
+ expect(screen.getByRole('button', { name: 'com_ui_use_prompt' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeInTheDocument();
+ });
+
+ it('retries the resolve on click, rendering the text and enabling Use on success', async () => {
+ resolvePromptGroup.mockRejectedValueOnce(new Error('resolve failed'));
+ resolvePromptGroup.mockResolvedValueOnce(langfuseResolved({ prompt: 'Recovered text' }));
+ renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ await screen.findByRole('alert');
+ expect(resolvePromptGroup).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));
+
+ await waitFor(() => expect(screen.getByText(/Recovered text/)).toBeInTheDocument());
+ expect(resolvePromptGroup).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole('button', { name: 'com_ui_use_prompt' })).toBeEnabled();
+ });
+
+ it('shows the Open in Langfuse link for an admin', async () => {
+ mockUser = { id: 'admin-1', role: SystemRoles.ADMIN };
+ resolvePromptGroup.mockResolvedValue(langfuseResolved());
+ renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ expect(
+ await screen.findByRole('link', { name: 'com_ui_prompt_open_in_langfuse' }),
+ ).toHaveAttribute('href', 'https://cloud.langfuse.test/project/project-1/prompts/greeting');
+ });
+
+ it('hides the Open in Langfuse link for a regular user, for whom the server strips sourceUrl', async () => {
+ const resolvedWithoutSourceUrl: TResolvedLangfusePrompt = {
+ ...langfuseResolved(),
+ sourceUrl: undefined,
+ };
+ resolvePromptGroup.mockResolvedValue(resolvedWithoutSourceUrl);
+ renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ await waitFor(() => expect(screen.getByText(/com_ui_prompt_version/)).toBeInTheDocument());
+ expect(
+ screen.queryByRole('link', { name: 'com_ui_prompt_open_in_langfuse' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('hides the Open in Langfuse link for an admin when the resolved response has no sourceUrl', async () => {
+ mockUser = { id: 'admin-1', role: SystemRoles.ADMIN };
+ const resolvedWithoutSourceUrl: TResolvedLangfusePrompt = {
+ ...langfuseResolved(),
+ sourceUrl: undefined,
+ };
+ resolvePromptGroup.mockResolvedValue(resolvedWithoutSourceUrl);
+ renderDetails(makeGroup({ source: 'langfuse', productionPrompt: null }));
+
+ await waitFor(() => expect(screen.getByText(/com_ui_prompt_version/)).toBeInTheDocument());
+ expect(
+ screen.queryByRole('link', { name: 'com_ui_prompt_open_in_langfuse' }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Prompts/display/__tests__/UsePromptButton.spec.tsx b/client/src/components/Prompts/display/__tests__/UsePromptButton.spec.tsx
new file mode 100644
index 0000000000..af01920f02
--- /dev/null
+++ b/client/src/components/Prompts/display/__tests__/UsePromptButton.spec.tsx
@@ -0,0 +1,87 @@
+import React from 'react';
+import { getDefaultStore } from 'jotai';
+import { MemoryRouter } from 'react-router-dom';
+import userEvent from '@testing-library/user-event';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import type { TPromptGroup } from 'librechat-data-provider';
+import { navigationGenerationAtom } from '~/store/navigation';
+import UsePromptButton from '../UsePromptButton';
+
+const mockSubmitPrompt = jest.fn();
+const mockRecordUsageMutate = jest.fn();
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+ useSubmitMessage: () => ({ submitPrompt: mockSubmitPrompt }),
+}));
+
+jest.mock('~/data-provider', () => ({
+ useRecordPromptUsage: () => ({ mutate: mockRecordUsageMutate }),
+}));
+
+/** Only `conversationId` matters here, the same way `ChatGroupItem.spec.tsx`
+ * mocks it: this test never changes the chat, it bumps the navigation
+ * generation instead. */
+const mockConversation = { current: { conversationId: 'convo-1' as string | undefined } };
+jest.mock('~/Providers', () => ({
+ useChatContext: () => ({ conversation: mockConversation.current }),
+}));
+
+jest.mock('../../dialogs/VariableDialog', () => ({
+ __esModule: true,
+ default: ({ open, promptText }: { open: boolean; promptText?: string }) =>
+ open ? <div data-testid="variable-dialog">{promptText}</div> : null,
+}));
+
+function makeGroup(overrides: Partial<TPromptGroup> = {}): TPromptGroup {
+ return {
+ _id: 'group-1',
+ name: 'Example Group',
+ source: 'langfuse',
+ ...overrides,
+ } as TPromptGroup;
+}
+
+function renderButton(chatIndex?: number) {
+ return render(
+ <MemoryRouter>
+ <UsePromptButton group={makeGroup()} promptText="Hello {{name}}" chatIndex={chatIndex} />
+ </MemoryRouter>,
+ );
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockConversation.current = { conversationId: 'convo-1' };
+ getDefaultStore().set(navigationGenerationAtom, 0);
+});
+
+describe('UsePromptButton chat-scoped variable dialog', () => {
+ it('closes the variable dialog when a navigation starts, for a button rendered inside a chat', async () => {
+ const user = userEvent.setup();
+ renderButton(0);
+
+ await user.click(screen.getByRole('button', { name: 'com_ui_use_prompt' }));
+ expect(await screen.findByTestId('variable-dialog')).toBeInTheDocument();
+
+ act(() => {
+ getDefaultStore().set(navigationGenerationAtom, 1);
+ });
+
+ await waitFor(() => expect(screen.queryByTestId('variable-dialog')).not.toBeInTheDocument());
+ });
+
+ it('leaves the variable dialog open on navigation when there is no associated chat', async () => {
+ const user = userEvent.setup();
+ renderButton(undefined);
+
+ await user.click(screen.getByRole('button', { name: 'com_ui_use_prompt' }));
+ expect(await screen.findByTestId('variable-dialog')).toBeInTheDocument();
+
+ act(() => {
+ getDefaultStore().set(navigationGenerationAtom, 1);
+ });
+
+ expect(screen.getByTestId('variable-dialog')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Prompts/display/index.ts b/client/src/components/Prompts/display/index.ts
index 02d7a40c78..28cf2b23b3 100644
--- a/client/src/components/Prompts/display/index.ts
+++ b/client/src/components/Prompts/display/index.ts
@@ -1,6 +1,9 @@
export { default as PromptDetails } from './PromptDetails';
export { default as PromptActions } from './PromptActions';
+export { default as UsePromptButton } from './UsePromptButton';
export { default as PromptTextCard } from './PromptTextCard';
export { default as PromptVersions } from './PromptVersions';
export { default as PromptVariables } from './PromptVariables';
export { default as PromptDetailHeader } from './PromptDetailHeader';
+export { default as LangfusePromptMeta } from './LangfusePromptMeta';
+export { default as PromptResolvedBody } from './PromptResolvedBody';
diff --git a/client/src/components/Prompts/forms/PromptForm.tsx b/client/src/components/Prompts/forms/PromptForm.tsx
index 01fa72bcab..943a213631 100644
--- a/client/src/components/Prompts/forms/PromptForm.tsx
+++ b/client/src/components/Prompts/forms/PromptForm.tsx
@@ -5,7 +5,7 @@ import { useParams } from 'react-router-dom';
import { Menu, Rocket, Info, X } from 'lucide-react';
import { useForm, FormProvider } from 'react-hook-form';
import { Button, Skeleton, useToastContext } from '@librechat/client';
-import { Permissions, PermissionTypes } from 'librechat-data-provider';
+import { Permissions, PermissionTypes, replaceSpecialVars } from 'librechat-data-provider';
import type { TCreatePrompt, TPrompt, TPromptGroup } from 'librechat-data-provider';
import {
useGetPrompts,
@@ -14,8 +14,17 @@ import {
useUpdatePromptGroup,
useMakePromptProduction,
} from '~/data-provider';
-import { useHasAccess, useLocalize, useFocusTrap, usePromptGroupPermissions } from '~/hooks';
+import {
+ useHasAccess,
+ useLocalize,
+ useFocusTrap,
+ useAuthContext,
+ usePromptContent,
+ usePromptGroupPermissions,
+} from '~/hooks';
import { cn, findPromptGroup, getPromptMutationErrorKey } from '~/utils';
+import LangfusePromptMeta from '../display/LangfusePromptMeta';
+import PromptResolvedBody from '../display/PromptResolvedBody';
import OpenSidebar from '~/components/Chat/Menus/OpenSidebar';
import useDrawerViewport from '~/hooks/Nav/useDrawerViewport';
import CategorySelector from '../fields/CategorySelector';
@@ -198,6 +207,11 @@ interface ExternalPromptGroupViewProps {
const ExternalPromptGroupView = React.memo(
({ group, isSmallScreen }: ExternalPromptGroupViewProps) => {
const localize = useLocalize();
+ const { user } = useAuthContext();
+ const { text, resolved, isLoading, error, refetch } = usePromptContent(group);
+ const hasError = Boolean(error);
+
+ const mainText = useMemo(() => replaceSpecialVars({ text, user }), [text, user]);
return (
<div className="flex h-full w-full flex-col">
@@ -206,9 +220,9 @@ const ExternalPromptGroupView = React.memo(
<OpenSidebar />
</div>
)}
- <div className="flex-1 overflow-hidden px-4">
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4">
<h1 className="sr-only">{localize('com_ui_prompt_details', { name: group.name })}</h1>
- <div className="mt-2 mb-3 flex items-center justify-between gap-2">
+ <div className="mt-2 mb-3 flex shrink-0 items-center justify-between gap-2">
<div className="flex min-w-0 flex-1 items-center gap-2">
<PromptName name={group.name} disabled onSave={() => {}} />
</div>
@@ -218,7 +232,7 @@ const ExternalPromptGroupView = React.memo(
</div>
</div>
- <div className="mb-2 flex h-full flex-col gap-3">
+ <div className="mb-2 flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">
<div
role="note"
className="border-status-warning-border bg-status-warning-subtle text-status-warning flex items-start gap-2 rounded-md border p-3 text-sm"
@@ -232,6 +246,19 @@ const ExternalPromptGroupView = React.memo(
</div>
<Description initialValue={group.oneliner ?? ''} disabled />
<Command initialValue={group.command ?? ''} disabled />
+
+ <div className="min-h-0 flex-1">
+ <PromptResolvedBody
+ mainText={mainText}
+ isLoading={isLoading}
+ error={error}
+ onRetry={refetch}
+ />
+ </div>
+
+ {!isLoading && !hasError && <PromptVariables promptText={mainText} />}
+
+ {resolved?.source === 'langfuse' && <LangfusePromptMeta resolved={resolved} />}
</div>
</div>
</div>
diff --git a/client/src/components/Prompts/forms/VariableForm.tsx b/client/src/components/Prompts/forms/VariableForm.tsx
index 7e76e7afb3..60974f87b6 100644
--- a/client/src/components/Prompts/forms/VariableForm.tsx
+++ b/client/src/components/Prompts/forms/VariableForm.tsx
@@ -65,17 +65,20 @@ const parseFieldConfig = (variable: string): FieldConfig => {
export default function VariableForm({
group,
onClose,
+ promptText,
}: {
group: TPromptGroup;
onClose: () => void;
+ /** Resolved prompt text; falls back to the production prompt when absent. */
+ promptText?: string;
}) {
const localize = useLocalize();
const { user } = useAuthContext();
const mainText = useMemo(() => {
- const initialText = group.productionPrompt?.prompt ?? '';
+ const initialText = promptText ?? group.productionPrompt?.prompt ?? '';
return replaceSpecialVars({ text: initialText, user });
- }, [group.productionPrompt?.prompt, user]);
+ }, [promptText, group.productionPrompt?.prompt, user]);
const { allVariables, uniqueVariables, variableIndexMap } = useMemo(
() => extractVariableInfo(mainText),
diff --git a/client/src/components/Prompts/forms/__tests__/PromptForm.spec.tsx b/client/src/components/Prompts/forms/__tests__/PromptForm.spec.tsx
index ae457eff48..1272786539 100644
--- a/client/src/components/Prompts/forms/__tests__/PromptForm.spec.tsx
+++ b/client/src/components/Prompts/forms/__tests__/PromptForm.spec.tsx
@@ -1,8 +1,8 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render, screen } from '@testing-library/react';
-import { PermissionBits } from 'librechat-data-provider';
-import type { TPromptGroup } from 'librechat-data-provider';
+import { PermissionBits, SystemRoles } from 'librechat-data-provider';
+import type { TPromptGroup, TResolvedPromptResponse } from 'librechat-data-provider';
import PromptForm from '../PromptForm';
const mockGroup: TPromptGroup = {
@@ -27,6 +27,25 @@ const mockAllBits =
let mockPermissionsLoading = false;
let mockPermissionBits = mockAllBits;
+// Mutable so individual tests can exercise `usePromptContent`'s loading,
+// resolved and error outcomes, and an admin vs. a regular user, without
+// re-mocking the module per test.
+let mockUser: { id: string; role?: string } = { id: 'user-1', role: SystemRoles.USER };
+const mockRefetchPromptContent = jest.fn();
+let mockPromptContent: {
+ text: string;
+ resolved?: TResolvedPromptResponse;
+ isLoading: boolean;
+ error: unknown;
+ refetch: () => void;
+} = {
+ text: '',
+ resolved: undefined,
+ isLoading: false,
+ error: undefined,
+ refetch: mockRefetchPromptContent,
+};
+
jest.mock('react-router-dom', () => ({
useParams: () => ({ promptId: 'group-1' }),
}));
@@ -55,6 +74,7 @@ jest.mock('~/data-provider', () => ({
useAddPromptToGroup: () => ({ mutate: jest.fn(), isLoading: false }),
useUpdatePromptGroup: () => ({ mutate: jest.fn(), isLoading: false, isError: false }),
useMakePromptProduction: () => ({ mutate: jest.fn(), isLoading: false }),
+ useRecordPromptUsage: () => ({ mutate: jest.fn() }),
}));
jest.mock('~/hooks', () => ({
@@ -62,6 +82,11 @@ jest.mock('~/hooks', () => ({
values ? `${key} ${JSON.stringify(values)}` : key,
useFocusTrap: () => undefined,
useHasAccess: () => true,
+ useAuthContext: () => ({ user: mockUser }),
+ // Mocked directly rather than through its own data fetch: these tests
+ // exercise the external view's rendering of each outcome, not the hook
+ // itself (covered by `usePromptContent.test.tsx`).
+ usePromptContent: () => mockPromptContent,
// Not mocked wholesale: the real hook runs so `isExternal` is derived from
// `group.source`, exercising the same logic the app ships.
usePromptGroupPermissions: jest.requireActual('~/hooks/Prompts/usePromptGroupPermissions')
@@ -96,6 +121,17 @@ jest.mock('../../display/PromptVariables', () => ({
default: () => <div data-testid="prompt-variables" />,
}));
+// `PromptTextCard` pulls in the shared Markdown/Artifacts dependency chain
+// (recoil atoms this suite's lightweight `recoil` mock doesn't define);
+// stubbed like `PromptVariables`/`PromptVersions` above, since the external
+// view's own rendering of each resolve outcome is what these tests cover.
+jest.mock('../../display/PromptTextCard', () => ({
+ __esModule: true,
+ default: ({ mainText }: { mainText: string }) => (
+ <div data-testid="prompt-text-card">{mainText}</div>
+ ),
+}));
+
jest.mock('../../display/PromptVersions', () => ({
__esModule: true,
default: () => <div data-testid="prompt-versions" />,
@@ -176,6 +212,10 @@ describe('PromptForm external (Langfuse) read-only view', () => {
expect(screen.queryByTestId('prompt-editor')).not.toBeInTheDocument();
expect(screen.queryByTestId('prompt-versions')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /com_ui_deploy|com_ui_production/ })).toBeNull();
+ // This standalone management page has no `ChatContext.Provider` ancestor
+ // (unlike the side-panel detail view), so it must not render a control
+ // that submits to the active chat.
+ expect(screen.queryByRole('button', { name: 'com_ui_use_prompt' })).toBeNull();
expect(screen.getByTestId('prompt-name')).toHaveAttribute('data-disabled', 'true');
expect(screen.getByTestId('category-selector')).toHaveAttribute('data-disabled', 'true');
@@ -203,3 +243,109 @@ describe('PromptForm external (Langfuse) read-only view', () => {
expect(screen.getByTestId('category-selector')).toHaveAttribute('data-disabled', 'false');
});
});
+
+function langfuseResolved(
+ overrides: Partial<TResolvedPromptResponse> = {},
+): TResolvedPromptResponse {
+ return {
+ source: 'langfuse',
+ groupId: 'group-1',
+ prompt: 'Live Langfuse text',
+ type: 'text',
+ version: 2,
+ labels: ['production'],
+ sourceUrl: 'https://cloud.langfuse.test/project/project-1/prompts/greeting',
+ ...overrides,
+ } as TResolvedPromptResponse;
+}
+
+describe('PromptForm external (Langfuse) resolved content', () => {
+ beforeEach(() => {
+ mockGroup.source = 'langfuse';
+ mockPermissionsLoading = false;
+ mockPermissionBits = mockAllBits;
+ mockUser = { id: 'user-1', role: SystemRoles.USER };
+ mockRefetchPromptContent.mockClear();
+ mockPromptContent = {
+ text: '',
+ resolved: undefined,
+ isLoading: false,
+ error: undefined,
+ refetch: mockRefetchPromptContent,
+ };
+ });
+
+ it('shows the resolving label while loading', async () => {
+ mockPromptContent = {
+ text: '',
+ resolved: undefined,
+ isLoading: true,
+ error: undefined,
+ refetch: mockRefetchPromptContent,
+ };
+ render(<PromptForm promptId="group-1" />);
+
+ expect(await screen.findByText('com_ui_prompt_resolving')).toBeInTheDocument();
+ });
+
+ it('renders the resolved text and variables', async () => {
+ mockPromptContent = {
+ text: 'Hello {{name}}',
+ resolved: langfuseResolved({ prompt: 'Hello {{name}}' }),
+ isLoading: false,
+ error: undefined,
+ refetch: mockRefetchPromptContent,
+ };
+ render(<PromptForm promptId="group-1" />);
+
+ expect(await screen.findByTestId('prompt-text-card')).toHaveTextContent('Hello');
+ expect(screen.getByTestId('prompt-variables')).toBeInTheDocument();
+ expect(screen.getByText('com_ui_prompt_version {"0":2} · production')).toBeInTheDocument();
+ });
+
+ it('renders the error copy with role=alert on a failed resolution', async () => {
+ mockPromptContent = {
+ text: '',
+ resolved: undefined,
+ isLoading: false,
+ error: new Error('resolve failed'),
+ refetch: mockRefetchPromptContent,
+ };
+ render(<PromptForm promptId="group-1" />);
+
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('com_ui_langfuse_prompt_error_fallback');
+ expect(screen.getByRole('button', { name: 'com_ui_retry' })).toBeInTheDocument();
+ });
+
+ it('shows the Open in Langfuse link when sourceUrl is present', async () => {
+ mockPromptContent = {
+ text: 'Live Langfuse text',
+ resolved: langfuseResolved(),
+ isLoading: false,
+ error: undefined,
+ refetch: mockRefetchPromptContent,
+ };
+ render(<PromptForm promptId="group-1" />);
+
+ expect(
+ await screen.findByRole('link', { name: 'com_ui_prompt_open_in_langfuse' }),
+ ).toHaveAttribute('href', 'https://cloud.langfuse.test/project/project-1/prompts/greeting');
+ });
+
+ it('hides the Open in Langfuse link for a regular user, for whom the server strips sourceUrl', async () => {
+ mockPromptContent = {
+ text: 'Live Langfuse text',
+ resolved: langfuseResolved({ sourceUrl: undefined }),
+ isLoading: false,
+ error: undefined,
+ refetch: mockRefetchPromptContent,
+ };
+ render(<PromptForm promptId="group-1" />);
+
+ await screen.findByTestId('prompt-text-card');
+ expect(
+ screen.queryByRole('link', { name: 'com_ui_prompt_open_in_langfuse' }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Prompts/lists/ChatGroupItem.tsx b/client/src/components/Prompts/lists/ChatGroupItem.tsx
index e9ded66b62..0a3349d1c6 100644
--- a/client/src/components/Prompts/lists/ChatGroupItem.tsx
+++ b/client/src/components/Prompts/lists/ChatGroupItem.tsx
@@ -18,15 +18,17 @@ import {
detectVariables,
getPromptMutationErrorKey,
getPromptGroupPermissions,
+ getPromptResolveErrorMessage,
rowActionClasses,
rowActionSlotClasses,
} from '~/utils';
+import { useLocalize, useAuthContext, useSubmitMessage, usePromptContentResolver } from '~/hooks';
import { useRecordPromptUsage, useDeletePromptGroup } from '~/data-provider';
-import { useLocalize, useAuthContext, useSubmitMessage } from '~/hooks';
+import useChatScopedRequest from '~/hooks/Prompts/useChatScopedRequest';
+import { useLiveAnnouncer, useChatContext } from '~/Providers';
import VariableDialog from '../dialogs/VariableDialog';
import PreviewPrompt from '../dialogs/PreviewPrompt';
import CategoryIcon from '../utils/CategoryIcon';
-import { useLiveAnnouncer } from '~/Providers';
const PROMPT_PATH = '/prompts';
@@ -45,7 +47,9 @@ function ChatGroupItem({
const { user } = useAuthContext();
const { submitPrompt } = useSubmitMessage();
const recordUsage = useRecordPromptUsage();
+ const resolvePromptContent = usePromptContentResolver();
const { announcePolite } = useLiveAnnouncer();
+ const { index } = useChatContext();
const { showToast } = useToastContext();
const menuId = useId();
@@ -53,8 +57,20 @@ function ChatGroupItem({
const [menuOpen, setMenuOpen] = useState(false);
const [isPreviewDialogOpen, setPreviewDialogOpen] = useState(false);
const [isVariableDialogOpen, setVariableDialogOpen] = useState(false);
+ const [variablePromptText, setVariablePromptText] = useState<string | undefined>(undefined);
+ const [isResolving, setIsResolving] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
+ /** A resolve that was started for one chat must not land on another; see
+ * `useChatScopedRequest` for the three cancellation keys. On cancel, the
+ * row's spinner clears (its own `finally` will not run for a discarded
+ * request) and a variable dialog opened from the stale read closes rather
+ * than surviving into the chat the user moved to. */
+ const { begin, isCurrent, isMounted } = useChatScopedRequest(index, () => {
+ setIsResolving(false);
+ setVariableDialogOpen(false);
+ });
+
const groupIsGlobal = group.isPublic === true;
const { isExternal, canEdit, canDelete } = getPromptGroupPermissions(group, permissionBits);
@@ -86,32 +102,76 @@ function ChatGroupItem({
deleteGroup.mutate({ id: group._id });
};
- const onCardClick = useCallback(() => {
+ const onCardClick = useCallback(async () => {
if (!isChatRoute) {
navigate(`${PROMPT_PATH}/${group._id}`, { replace: true });
return;
}
- const text = group.productionPrompt?.prompt;
- if (!text?.trim()) {
+ if (isResolving) {
return;
}
- if (detectVariables(text)) {
- setVariableDialogOpen(true);
- return;
+ const token = begin();
+ if (isExternal) {
+ setIsResolving(true);
}
+ try {
+ const text = await resolvePromptContent(group);
+ /** The row may have unmounted, or the active conversation may have
+ * changed, while the Langfuse resolve was in flight; a stale
+ * continuation must not submit, stage, or record for a chat the
+ * user left. */
+ if (!isMounted() || !isCurrent(token)) {
+ return;
+ }
+ if (!text?.trim()) {
+ return;
+ }
- submitPrompt(text);
- if (group._id) {
- recordUsage.mutate(group._id);
+ if (detectVariables(text)) {
+ setVariablePromptText(text);
+ setVariableDialogOpen(true);
+ return;
+ }
+
+ submitPrompt(text);
+ if (group._id) {
+ recordUsage.mutate(group._id);
+ }
+ } catch (error) {
+ if (isMounted() && isCurrent(token)) {
+ showToast({ status: 'error', message: getPromptResolveErrorMessage(error, localize) });
+ }
+ } finally {
+ if (isExternal && isMounted() && isCurrent(token)) {
+ setIsResolving(false);
+ }
}
- }, [group, submitPrompt, recordUsage, isChatRoute, navigate]);
+ }, [
+ group,
+ submitPrompt,
+ recordUsage,
+ isChatRoute,
+ navigate,
+ isResolving,
+ isExternal,
+ resolvePromptContent,
+ showToast,
+ localize,
+ begin,
+ isCurrent,
+ isMounted,
+ ]);
- const snippet =
- typeof group.oneliner === 'string' && group.oneliner.length > 0
- ? group.oneliner
- : (group.productionPrompt?.prompt ?? '');
+ const productionText = group.productionPrompt?.prompt ?? '';
+ const hasOneliner = typeof group.oneliner === 'string' && group.oneliner.length > 0;
+ let snippet = '';
+ if (hasOneliner) {
+ snippet = group.oneliner as string;
+ } else if (productionText.length > 0) {
+ snippet = productionText;
+ }
const ariaLabel = group.category
? localize('com_ui_prompt_group_button', { name: group.name, category: group.category })
@@ -151,6 +211,7 @@ function ChatGroupItem({
? 'bg-surface-nav-selected'
: 'hover:bg-surface-nav-hover',
)}
+ aria-busy={isResolving}
>
{/* Clickable overlay for card */}
<button
@@ -158,13 +219,18 @@ function ChatGroupItem({
className="focus-visible:ring-ring-primary absolute inset-0 z-0 rounded-xl focus:outline-hidden focus-visible:ring-2"
onClick={onCardClick}
aria-label={ariaLabel}
+ disabled={isResolving}
/>
<div className="flex items-start gap-2.5 px-3 py-2.5">
- <CategoryIcon
- category={group.category ?? ''}
- className="mt-0.5 size-4 shrink-0"
- aria-hidden="true"
- />
+ {isResolving ? (
+ <Spinner className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
+ ) : (
+ <CategoryIcon
+ category={group.category ?? ''}
+ className="mt-0.5 size-4 shrink-0"
+ aria-hidden="true"
+ />
+ )}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<TooltipAnchor
@@ -259,6 +325,7 @@ function ChatGroupItem({
</div>
<PreviewPrompt
group={group}
+ chatIndex={index}
open={isPreviewDialogOpen}
onOpenChange={setPreviewDialogOpen}
onCloseAutoFocus={() => {
@@ -272,6 +339,7 @@ function ChatGroupItem({
open={isVariableDialogOpen}
onClose={() => setVariableDialogOpen(false)}
group={group}
+ promptText={variablePromptText}
/>
)}
<OGDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
diff --git a/client/src/components/Prompts/lists/__tests__/ChatGroupItem.spec.tsx b/client/src/components/Prompts/lists/__tests__/ChatGroupItem.spec.tsx
index 394ba2bbe0..8f9464457d 100644
--- a/client/src/components/Prompts/lists/__tests__/ChatGroupItem.spec.tsx
+++ b/client/src/components/Prompts/lists/__tests__/ChatGroupItem.spec.tsx
@@ -1,15 +1,26 @@
import React from 'react';
-import { MemoryRouter } from 'react-router-dom';
+import { getDefaultStore } from 'jotai';
import userEvent from '@testing-library/user-event';
-import { render, screen } from '@testing-library/react';
import { PermissionBits } from 'librechat-data-provider';
+import { MemoryRouter, useNavigate } from 'react-router-dom';
+import { render, screen, waitFor } from '@testing-library/react';
import type { TPromptGroup } from 'librechat-data-provider';
+import { navigationGenerationAtom } from '~/store/navigation';
import ChatGroupItem from '../ChatGroupItem';
const mockMutate = jest.fn();
+const mockRecordUsageMutate = jest.fn();
+const mockSubmitPrompt = jest.fn();
+const mockShowToast = jest.fn();
+/** Native groups resolve from local text with no request; a test overrides this
+ * per-call (`mockResolvedValueOnce`/`mockRejectedValueOnce`/a controllable
+ * promise) to drive the Langfuse resolve paths. */
+const mockResolve = jest.fn((group: TPromptGroup) =>
+ Promise.resolve(group.productionPrompt?.prompt ?? ''),
+);
jest.mock('~/data-provider', () => ({
- useRecordPromptUsage: () => ({ mutate: jest.fn() }),
+ useRecordPromptUsage: () => ({ mutate: mockRecordUsageMutate }),
useDeletePromptGroup: () => ({ mutate: mockMutate, isLoading: false }),
}));
@@ -17,11 +28,27 @@ jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, values?: Record<number, string>) =>
values ? `${key} ${JSON.stringify(values)}` : key,
useAuthContext: () => ({ user: { id: 'user-owner' } }),
- useSubmitMessage: () => ({ submitPrompt: jest.fn() }),
+ useSubmitMessage: () => ({ submitPrompt: mockSubmitPrompt }),
+ usePromptContentResolver: () => mockResolve,
}));
+/** Only `conversationId` matters: a saved chat's invalidation effect keys on
+ * the id, and a draft chat's keys on the composer draft token instead of
+ * this object, so the mock just needs to return a stable reference until a
+ * test swaps it for a different id. */
+const mockConversation = { current: { conversationId: 'convo-1' as string | undefined } };
jest.mock('~/Providers', () => ({
useLiveAnnouncer: () => ({ announcePolite: jest.fn() }),
+ useChatContext: () => ({ conversation: mockConversation.current, index: 0 }),
+}));
+
+/** The real token lives in a module-level map keyed by composer index, which
+ * `useNewConvo` renews on a new-chat reset and keeps otherwise; the mock
+ * swaps in a plain symbol a test can renew by assignment. */
+const mockDraftToken = { current: Symbol('new-conversation-draft') };
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils'),
+ getNewConversationDraftToken: () => mockDraftToken.current,
}));
/** Keeps the real DropdownPopup/Ariakit menu behavior; only the tooltip
@@ -31,9 +58,19 @@ jest.mock('@librechat/client', () => {
return {
...actual,
TooltipAnchor: ({ render: content }: { render: React.ReactNode }) => content,
+ useToastContext: () => ({ showToast: mockShowToast }),
};
});
+/** Resolved relative to this test file, this is the same module ChatGroupItem
+ * imports via `../dialogs/VariableDialog`; stubbing it isolates the resolve/
+ * variables split from VariableForm's own rendering. */
+jest.mock('../../dialogs/VariableDialog', () => ({
+ __esModule: true,
+ default: ({ open, promptText }: { open: boolean; promptText?: string }) =>
+ open ? <div data-testid="variable-dialog">{promptText}</div> : null,
+}));
+
function makeGroup(overrides: Partial<TPromptGroup> = {}): TPromptGroup {
return {
_id: 'group-1',
@@ -53,14 +90,85 @@ function renderGroup(group: TPromptGroup, permissionBits: number) {
);
}
+function renderChatGroup(group: TPromptGroup, permissionBits = 0) {
+ return render(
+ <MemoryRouter>
+ <ChatGroupItem group={group} isChatRoute={true} permissionBits={permissionBits} />
+ </MemoryRouter>,
+ );
+}
+
+/** Fires the same kind of navigation `useNewConvo`'s reset performs on a new
+ * chat: a push to `/c/new`, which produces a fresh router location key even
+ * though the pathname is unchanged. */
+function NewChatResetTrigger() {
+ const navigate = useNavigate();
+ return (
+ <button
+ type="button"
+ data-testid="simulate-new-chat-reset"
+ onClick={() => navigate('/c/new')}
+ />
+ );
+}
+
+function renderDraftChatGroup(group: TPromptGroup, permissionBits = 0) {
+ return render(
+ <MemoryRouter initialEntries={['/c/new']}>
+ <NewChatResetTrigger />
+ <ChatGroupItem group={group} isChatRoute={true} permissionBits={permissionBits} />
+ </MemoryRouter>,
+ );
+}
+
+/** Fires a route change to a different path, the way browser Back/Forward
+ * moves `/c/:id` directly through the router without the conversation
+ * object changing first. */
+function NavigateAwayTrigger({ to }: { to: string }) {
+ const navigate = useNavigate();
+ return <button type="button" data-testid="navigate-away" onClick={() => navigate(to)} />;
+}
+
+function renderChatGroupWithNavigateAway(
+ group: TPromptGroup,
+ initialPath: string,
+ destinationPath: string,
+) {
+ return render(
+ <MemoryRouter initialEntries={[initialPath]}>
+ <NavigateAwayTrigger to={destinationPath} />
+ <ChatGroupItem group={group} isChatRoute={true} />
+ </MemoryRouter>,
+ );
+}
+
+/** The clickable overlay button; its accessible name always starts with this
+ * prefix regardless of whether the group has a category. */
+const getCardButton = () => screen.getByRole('button', { name: /com_ui_prompt_group_button/ });
+
const FULL_BITS =
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
+beforeEach(() => {
+ mockDraftToken.current = Symbol('new-conversation-draft');
+ getDefaultStore().set(navigationGenerationAtom, 0);
+});
+
describe('ChatGroupItem menu', () => {
beforeEach(() => {
mockMutate.mockClear();
});
+ afterEach(() => {
+ mockRecordUsageMutate.mockClear();
+ mockSubmitPrompt.mockClear();
+ mockShowToast.mockClear();
+ mockResolve.mockReset();
+ mockResolve.mockImplementation((group: TPromptGroup) =>
+ Promise.resolve(group.productionPrompt?.prompt ?? ''),
+ );
+ });
+
it('shows Edit and Delete for a native group owned by the caller', async () => {
const user = userEvent.setup();
renderGroup(makeGroup(), FULL_BITS);
@@ -93,3 +201,396 @@ describe('ChatGroupItem menu', () => {
).not.toBeInTheDocument();
});
});
+
+describe('ChatGroupItem chat-route click', () => {
+ afterEach(() => {
+ mockRecordUsageMutate.mockClear();
+ mockSubmitPrompt.mockClear();
+ mockShowToast.mockClear();
+ mockResolve.mockReset();
+ mockResolve.mockImplementation((group: TPromptGroup) =>
+ Promise.resolve(group.productionPrompt?.prompt ?? ''),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ });
+
+ it('resolves a Langfuse group before submitting, and records usage once', async () => {
+ const user = userEvent.setup();
+ mockResolve.mockResolvedValueOnce('Resolved text');
+ renderChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ await user.click(getCardButton());
+
+ await waitFor(() => expect(mockSubmitPrompt).toHaveBeenCalledWith('Resolved text'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsageMutate).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsageMutate).toHaveBeenCalledWith('group-1');
+ });
+
+ it('ignores a second click while a Langfuse resolve is pending', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ renderChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ const button = getCardButton();
+ await user.click(button);
+ await user.click(button);
+
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+
+ resolveFn('Resolved text');
+ await waitFor(() => expect(mockSubmitPrompt).toHaveBeenCalledTimes(1));
+ expect(mockSubmitPrompt).toHaveBeenCalledWith('Resolved text');
+ expect(mockRecordUsageMutate).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens the variable dialog with the resolved text and records nothing', async () => {
+ const user = userEvent.setup();
+ mockResolve.mockResolvedValueOnce('Hello {{name}}');
+ renderChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ await user.click(getCardButton());
+
+ expect(await screen.findByTestId('variable-dialog')).toHaveTextContent('Hello {{name}}');
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('closes the variable dialog when a navigation starts while it is open', async () => {
+ const user = userEvent.setup();
+ mockResolve.mockResolvedValueOnce('Hello {{name}}');
+ renderChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ await user.click(getCardButton());
+ expect(await screen.findByTestId('variable-dialog')).toBeInTheDocument();
+
+ /** A dialog opened from a resolved Langfuse read must not survive a chat
+ * change and submit a variable fill into another chat. */
+ getDefaultStore().set(navigationGenerationAtom, 1);
+
+ await waitFor(() => expect(screen.queryByTestId('variable-dialog')).not.toBeInTheDocument());
+ });
+
+ it('shows the resolve error toast and records nothing on failure', async () => {
+ const user = userEvent.setup();
+ mockResolve.mockRejectedValueOnce(new Error('boom'));
+ renderChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ await user.click(getCardButton());
+
+ await waitFor(() =>
+ expect(mockShowToast).toHaveBeenCalledWith({
+ status: 'error',
+ message: 'com_ui_langfuse_prompt_error_fallback',
+ }),
+ );
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('submits and records a native prompt with no spinner', async () => {
+ const user = userEvent.setup();
+ const { container } = renderChatGroup(
+ makeGroup({ productionPrompt: { prompt: 'Native text' } }),
+ );
+
+ await user.click(getCardButton());
+
+ await waitFor(() => expect(mockSubmitPrompt).toHaveBeenCalledWith('Native text'));
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(mockRecordUsageMutate).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('svg.spinner')).not.toBeInTheDocument();
+ });
+
+ it('discards a Langfuse resolve that completes after the row unmounts', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ const { unmount } = renderChatGroup(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ );
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+
+ unmount();
+ resolveFn('Resolved text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('discards a Langfuse resolve and clears the busy state when the conversation changes first', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ const { rerender } = renderChatGroup(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ );
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ mockConversation.current = { conversationId: 'convo-2' };
+ rerender(
+ <MemoryRouter>
+ <ChatGroupItem
+ group={makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' })}
+ isChatRoute={true}
+ />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+
+ resolveFn('Resolved text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('discards a Langfuse resolve and clears the busy state when a new-chat reset renews the draft token', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'new' };
+ const { rerender } = renderChatGroup(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ );
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ /** `useNewConvo` renews the draft token on a new-chat reset, including
+ * when the composer is already on an unsaved chat; the invalidation
+ * must key on that, not on the conversation object. */
+ mockDraftToken.current = Symbol('new-conversation-draft');
+ rerender(
+ <MemoryRouter>
+ <ChatGroupItem
+ group={makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' })}
+ isChatRoute={true}
+ />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+
+ resolveFn('Resolved text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('discards a Langfuse resolve and clears the busy state when a navigation starts, before the target conversation commits', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ renderChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ /** `navigateToConvo` bumps `navigationGenerationAtom` as soon as a
+ * navigation starts, before the target conversation's record is
+ * fetched and `conversationId` changes — simulate just that bump,
+ * with the conversation left untouched. */
+ getDefaultStore().set(navigationGenerationAtom, 1);
+
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+
+ resolveFn('Resolved text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('discards a Langfuse resolve and clears the busy state when the route pathname changes, before the conversation updates', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ renderChatGroupWithNavigateAway(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ '/c/convo-1',
+ '/c/convo-2',
+ );
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ /** Browser Back/Forward moves `/c/:id` directly through the router;
+ * ChatRoute keeps the previous conversation mounted while the next one
+ * loads, so `conversationId` has not changed here even though the
+ * pathname has. */
+ await user.click(screen.getByTestId('navigate-away'));
+
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+
+ resolveFn('Resolved text');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(mockSubmitPrompt).not.toHaveBeenCalled();
+ expect(mockRecordUsageMutate).not.toHaveBeenCalled();
+ });
+
+ it('lets a pending Langfuse resolve complete when a navigation changes the router location but keeps the same draft token', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'new' };
+ renderDraftChatGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }));
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ /** A plain navigation (unlike `useNewConvo`'s reset) never touches the
+ * draft token, so a pending resolve must survive it. */
+ await user.click(screen.getByTestId('simulate-new-chat-reset'));
+ expect(getCardButton()).toBeDisabled();
+
+ resolveFn('Resolved text');
+ await waitFor(() => expect(mockSubmitPrompt).toHaveBeenCalledWith('Resolved text'));
+ expect(mockRecordUsageMutate).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+ });
+
+ it('lets a pending Langfuse resolve complete when a parameter edit replaces the conversation object on a draft chat', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'new' };
+ const { rerender } = renderChatGroup(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ );
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ /** A parameter edit (e.g. `SidePanel/Parameters/Panel.tsx`) replaces the
+ * conversation object without renewing the draft token; the pending
+ * resolve must not be discarded. */
+ mockConversation.current = { conversationId: 'new' };
+ rerender(
+ <MemoryRouter>
+ <ChatGroupItem
+ group={makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' })}
+ isChatRoute={true}
+ />
+ </MemoryRouter>,
+ );
+
+ expect(getCardButton()).toBeDisabled();
+
+ resolveFn('Resolved text');
+ await waitFor(() => expect(mockSubmitPrompt).toHaveBeenCalledTimes(1));
+ expect(mockSubmitPrompt).toHaveBeenCalledWith('Resolved text');
+ expect(mockRecordUsageMutate).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+ });
+
+ it('lets a pending Langfuse resolve complete when a same-chat update replaces the conversation object with the same id', async () => {
+ const user = userEvent.setup();
+ let resolveFn: (value: string) => void = () => {};
+ mockResolve.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ resolveFn = resolve;
+ }),
+ );
+ mockConversation.current = { conversationId: 'convo-1' };
+ const { rerender } = renderChatGroup(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ );
+
+ await user.click(getCardButton());
+ expect(mockResolve).toHaveBeenCalledTimes(1);
+ expect(getCardButton()).toBeDisabled();
+
+ /** Streaming sync, a pin, or a project change replaces the conversation
+ * object without changing its id; the pending resolve must not be
+ * discarded, since the chat identity (the id) has not changed. */
+ mockConversation.current = { conversationId: 'convo-1' };
+ rerender(
+ <MemoryRouter>
+ <ChatGroupItem
+ group={makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' })}
+ isChatRoute={true}
+ />
+ </MemoryRouter>,
+ );
+
+ expect(getCardButton()).toBeDisabled();
+
+ resolveFn('Resolved text');
+ await waitFor(() => expect(mockSubmitPrompt).toHaveBeenCalledTimes(1));
+ expect(mockSubmitPrompt).toHaveBeenCalledWith('Resolved text');
+ expect(mockRecordUsageMutate).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(getCardButton()).not.toBeDisabled());
+ });
+});
+
+describe('ChatGroupItem snippet', () => {
+ it('renders no snippet text for an external group with no oneliner or text, since the Cloud badge already labels the source', () => {
+ const { container } = renderGroup(
+ makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }),
+ 0,
+ );
+ expect(screen.queryByText('com_ui_prompt_source_langfuse')).not.toBeInTheDocument();
+ expect(container.querySelector('p')).toHaveTextContent('');
+ });
+});
diff --git a/client/src/data-provider/prompts.ts b/client/src/data-provider/prompts.ts
index 629c4f56a4..8720452bf7 100644
--- a/client/src/data-provider/prompts.ts
+++ b/client/src/data-provider/prompts.ts
@@ -1,7 +1,8 @@
+import { useCallback } from 'react';
import { useRecoilValue } from 'recoil';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { dataService, QueryKeys, ResourceType } from 'librechat-data-provider';
-import type { UseMutationResult } from '@tanstack/react-query';
+import type { QueryObserverResult, UseMutationResult } from '@tanstack/react-query';
import type t from 'librechat-data-provider';
import {
/* Prompts */
@@ -365,3 +366,41 @@ export const useRecordPromptUsage = (): UseMutationResult<
},
});
};
+
+/**
+ * Resolves a prompt group's content: `/api/prompts/groups/:groupId/resolve`.
+ * No cache and no retry, since a Langfuse group's content can change between
+ * requests and a stale read should not linger or be retried silently.
+ */
+export const useResolvePromptGroup = (
+ id: string,
+ config?: { enabled?: boolean },
+): QueryObserverResult<t.TResolvedPromptResponse> => {
+ return useQuery<t.TResolvedPromptResponse>(
+ [QueryKeys.promptGroupContent, id],
+ () => dataService.resolvePromptGroup(id),
+ {
+ enabled: config?.enabled,
+ retry: false,
+ staleTime: 0,
+ cacheTime: 0,
+ refetchOnWindowFocus: 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. */
+export const useResolvePromptGroupFn = (): ((id: string) => Promise<t.TResolvedPromptResponse>) => {
+ const queryClient = useQueryClient();
+ return useCallback(
+ (id: string) =>
+ queryClient.fetchQuery<t.TResolvedPromptResponse>(
+ [QueryKeys.promptGroupContent, id],
+ () => dataService.resolvePromptGroup(id),
+ { retry: false, staleTime: 0, cacheTime: 0 },
+ ),
+ [queryClient],
+ );
+};
diff --git a/client/src/hooks/Conversations/useNavigateToConvo.tsx b/client/src/hooks/Conversations/useNavigateToConvo.tsx
index 5a491906f6..c7316f2ef6 100644
--- a/client/src/hooks/Conversations/useNavigateToConvo.tsx
+++ b/client/src/hooks/Conversations/useNavigateToConvo.tsx
@@ -1,6 +1,6 @@
import { useCallback } from 'react';
-import { useSetAtom } from 'jotai';
import { useNavigate } from 'react-router-dom';
+import { useSetAtom, getDefaultStore } from 'jotai';
import { submissionByIndex } from '@librechat/chat/react';
import { useQueryClient, isCancelledError } from '@tanstack/react-query';
import {
@@ -26,6 +26,7 @@ import {
updateConvoInAllQueries,
logger,
} from '~/utils';
+import { navigationGenerationAtom } from '~/store/navigation';
import { useApplyModelSpecEffects } from '~/hooks/Agents';
import { startupConfigKey } from '~/data-provider';
import store from '~/store';
@@ -66,11 +67,21 @@ const currentRoute = () => window.location.pathname + window.location.search;
* subsumes the other — the generation says "a newer intent replaced this one",
* the route says "the user left by some means this hook never saw".
*
- * Module-scoped for the same reason the route is read from the browser: every
- * sidebar row mounts its own `useNavigateToConvo`, so a ref would be private
- * to the row that was clicked and blind to the click that superseded it.
+ * Lives in `navigationGenerationAtom` (`~/store/navigation`), not a hook-local
+ * ref, for the same reason the route is read from the browser: every sidebar
+ * row mounts its own `useNavigateToConvo`, so a ref would be private to the
+ * row that was clicked and blind to the click that superseded it. The same
+ * atom lets a component outside this hook — a prompt card or the slash
+ * command, cancelling its own pending Langfuse resolve — treat a navigation
+ * that has only just started as supersession too, before the target
+ * conversation commits and its own identity changes.
*/
-let navigationGeneration = 0;
+const bumpNavigationGeneration = () => {
+ const defaultStore = getDefaultStore();
+ const generation = defaultStore.get(navigationGenerationAtom) + 1;
+ defaultStore.set(navigationGenerationAtom, generation);
+ return generation;
+};
/**
* Records that the user has asked for a different conversation, so a first
@@ -88,7 +99,7 @@ let navigationGeneration = 0;
* is not.
*/
export const supersedeNavigation = () => {
- navigationGeneration++;
+ bumpNavigationGeneration();
};
const useNavigateToConvo = (index = 0) => {
@@ -226,7 +237,8 @@ const useNavigateToConvo = (index = 0) => {
queryClient.removeQueries([QueryKeys.messages, conversationId]);
}
}
- if (generation !== navigationGeneration || currentRoute() !== routeAtStart) {
+ const isSuperseded = generation !== getDefaultStore().get(navigationGenerationAtom);
+ if (isSuperseded || currentRoute() !== routeAtStart) {
logger.log('conversation', 'Discarding superseded navigation', conversationId);
return;
}
@@ -249,7 +261,7 @@ const useNavigateToConvo = (index = 0) => {
hasSetConversation.current = true;
/** Claim this click's place in the order before any await, so a request
* still in flight for an earlier one cannot land on top of it. */
- const generation = ++navigationGeneration;
+ const generation = bumpNavigationGeneration();
setSubmission(null);
let convo = { ...conversation };
diff --git a/client/src/hooks/Prompts/__tests__/useChatScopedRequest.test.tsx b/client/src/hooks/Prompts/__tests__/useChatScopedRequest.test.tsx
new file mode 100644
index 0000000000..25a2cfc3b0
--- /dev/null
+++ b/client/src/hooks/Prompts/__tests__/useChatScopedRequest.test.tsx
@@ -0,0 +1,128 @@
+import { getDefaultStore } from 'jotai';
+import { MemoryRouter, useNavigate } from 'react-router-dom';
+import { act, fireEvent, render } from '@testing-library/react';
+import type { ChatScopedRequest } from '../useChatScopedRequest';
+import { navigationGenerationAtom } from '~/store/navigation';
+import useChatScopedRequest from '../useChatScopedRequest';
+
+const mockConversation = { current: { conversationId: 'convo-1' as string | undefined } };
+jest.mock('~/Providers', () => ({
+ useChatContext: () => ({ conversation: mockConversation.current }),
+}));
+
+/** The real token lives in a module-level map keyed by composer index; the
+ * mock swaps in a plain symbol a test can renew by assignment. */
+const mockDraftToken = { current: Symbol('new-conversation-draft') };
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils'),
+ getNewConversationDraftToken: () => mockDraftToken.current,
+}));
+
+let hookApi: ChatScopedRequest | null = null;
+const onCancel = jest.fn();
+
+function Harness() {
+ hookApi = useChatScopedRequest(0, onCancel);
+ return null;
+}
+
+function NavigateAwayTrigger({ to }: { to: string }) {
+ const navigate = useNavigate();
+ return <button type="button" data-testid="navigate-away" onClick={() => navigate(to)} />;
+}
+
+const renderHarness = (initialPath = '/c/convo-1') =>
+ render(
+ <MemoryRouter initialEntries={[initialPath]}>
+ <NavigateAwayTrigger to="/c/convo-2" />
+ <Harness />
+ </MemoryRouter>,
+ );
+
+beforeEach(() => {
+ hookApi = null;
+ onCancel.mockClear();
+ mockConversation.current = { conversationId: 'convo-1' };
+ mockDraftToken.current = Symbol('new-conversation-draft');
+ getDefaultStore().set(navigationGenerationAtom, 0);
+});
+
+describe('useChatScopedRequest', () => {
+ it('issues increasing tokens and reports only the latest as current', () => {
+ renderHarness();
+
+ const first = hookApi!.begin();
+ expect(hookApi!.isCurrent(first)).toBe(true);
+
+ const second = hookApi!.begin();
+ expect(hookApi!.isCurrent(first)).toBe(false);
+ expect(hookApi!.isCurrent(second)).toBe(true);
+ });
+
+ it('reports mounted while rendered and unmounted after unmount', () => {
+ const { unmount } = renderHarness();
+ expect(hookApi!.isMounted()).toBe(true);
+
+ unmount();
+ expect(hookApi!.isMounted()).toBe(false);
+ });
+
+ it('cancels a pending request when the chat identity changes', () => {
+ const { rerender } = renderHarness();
+ /** The initial mount also runs the cancellation effect once; only calls
+ * made after that first commit are this test's concern. */
+ onCancel.mockClear();
+ const token = hookApi!.begin();
+
+ mockConversation.current = { conversationId: 'convo-2' };
+ rerender(
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <NavigateAwayTrigger to="/c/convo-2" />
+ <Harness />
+ </MemoryRouter>,
+ );
+
+ expect(hookApi!.isCurrent(token)).toBe(false);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels a pending request when a navigation starts, via navigationGenerationAtom', () => {
+ renderHarness();
+ onCancel.mockClear();
+ const token = hookApi!.begin();
+
+ act(() => {
+ getDefaultStore().set(navigationGenerationAtom, 1);
+ });
+
+ expect(hookApi!.isCurrent(token)).toBe(false);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels a pending request when the route pathname changes', () => {
+ const { getByTestId } = renderHarness();
+ onCancel.mockClear();
+ const token = hookApi!.begin();
+
+ fireEvent.click(getByTestId('navigate-away'));
+
+ expect(hookApi!.isCurrent(token)).toBe(false);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not cancel a pending request when nothing relevant changes across a re-render', () => {
+ const { rerender } = renderHarness();
+ onCancel.mockClear();
+ const token = hookApi!.begin();
+
+ rerender(
+ <MemoryRouter initialEntries={['/c/convo-1']}>
+ <NavigateAwayTrigger to="/c/convo-2" />
+ <Harness />
+ </MemoryRouter>,
+ );
+
+ expect(hookApi!.isCurrent(token)).toBe(true);
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/Prompts/__tests__/usePromptContent.test.tsx b/client/src/hooks/Prompts/__tests__/usePromptContent.test.tsx
new file mode 100644
index 0000000000..9ce170b513
--- /dev/null
+++ b/client/src/hooks/Prompts/__tests__/usePromptContent.test.tsx
@@ -0,0 +1,206 @@
+import { createElement } from 'react';
+import { dataService } from 'librechat-data-provider';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TPromptGroup, TResolvedPromptResponse } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import usePromptContent, { usePromptContentResolver } from '../usePromptContent';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ resolvePromptGroup: jest.fn(),
+ },
+ };
+});
+
+const resolvePromptGroup = dataService.resolvePromptGroup as jest.MockedFunction<
+ typeof dataService.resolvePromptGroup
+>;
+
+function makeGroup(overrides: Partial<TPromptGroup> = {}): TPromptGroup {
+ return {
+ _id: 'group-1',
+ name: 'Example Group',
+ author: 'author-1',
+ authorName: 'Author',
+ source: 'native',
+ productionPrompt: { prompt: 'Native production text' },
+ ...overrides,
+ } as TPromptGroup;
+}
+
+function langfuseResolved(
+ overrides: Partial<TResolvedPromptResponse> = {},
+): TResolvedPromptResponse {
+ return {
+ source: 'langfuse',
+ groupId: 'group-1',
+ prompt: 'Live Langfuse text',
+ type: 'text',
+ version: 1,
+ labels: ['production'],
+ sourceUrl: 'https://cloud.langfuse.test/project/project-1/prompts/greeting',
+ ...overrides,
+ } as TResolvedPromptResponse;
+}
+
+const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+const createWrapper = (queryClient: QueryClient) =>
+ function Wrapper({ children }: { children: ReactNode }) {
+ return createElement(QueryClientProvider, { client: queryClient }, children);
+ };
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+describe('usePromptContent', () => {
+ it('returns the production prompt synchronously for a native group, with no request', () => {
+ const queryClient = createQueryClient();
+ const group = makeGroup();
+
+ const { result } = renderHook(() => usePromptContent(group), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ expect(result.current.text).toBe('Native production text');
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.error).toBeUndefined();
+ expect(result.current.resolved).toBeUndefined();
+ expect(resolvePromptGroup).not.toHaveBeenCalled();
+ });
+
+ it('fetches and returns the resolved prompt for a Langfuse group', async () => {
+ const queryClient = createQueryClient();
+ const resolved = langfuseResolved();
+ resolvePromptGroup.mockResolvedValue(resolved);
+ const group = makeGroup({ source: 'langfuse', productionPrompt: null });
+
+ const { result } = renderHook(() => usePromptContent(group), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ expect(result.current.isLoading).toBe(true);
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(resolvePromptGroup).toHaveBeenCalledWith('group-1');
+ expect(result.current.text).toBe('Live Langfuse text');
+ expect(result.current.resolved).toEqual(resolved);
+ // React Query reports "no error" as `null`, not `undefined`, once a query has run.
+ expect(result.current.error).toBeNull();
+ });
+
+ it('passes a resolve error through', async () => {
+ const queryClient = createQueryClient();
+ const error = new Error('resolve failed');
+ resolvePromptGroup.mockRejectedValue(error);
+ const group = makeGroup({ source: 'langfuse', productionPrompt: null });
+
+ const { result } = renderHook(() => usePromptContent(group), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(result.current.error).toBe(error);
+ expect(result.current.text).toBe('');
+ });
+
+ it('issues a second resolve request when refetch is called after an error', async () => {
+ const queryClient = createQueryClient();
+ const error = new Error('resolve failed');
+ resolvePromptGroup.mockRejectedValueOnce(error).mockResolvedValueOnce(langfuseResolved());
+ const group = makeGroup({ source: 'langfuse', productionPrompt: null });
+
+ const { result } = renderHook(() => usePromptContent(group), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await waitFor(() => expect(result.current.error).toBe(error));
+ expect(resolvePromptGroup).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ result.current.refetch();
+ });
+
+ await waitFor(() => expect(result.current.text).toBe('Live Langfuse text'));
+ expect(resolvePromptGroup).toHaveBeenCalledTimes(2);
+ });
+
+ it('never requests when disabled, even for a Langfuse group', () => {
+ const queryClient = createQueryClient();
+ const group = makeGroup({ source: 'langfuse', productionPrompt: null });
+
+ const { result } = renderHook(() => usePromptContent(group, { enabled: false }), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ expect(result.current.isLoading).toBe(false);
+ expect(resolvePromptGroup).not.toHaveBeenCalled();
+ });
+});
+
+describe('usePromptContentResolver', () => {
+ it('resolves a native group synchronously with no request', async () => {
+ const queryClient = createQueryClient();
+ const group = makeGroup();
+
+ const { result } = renderHook(() => usePromptContentResolver(), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ let text: string | undefined;
+ await act(async () => {
+ text = await result.current(group);
+ });
+
+ expect(text).toBe('Native production text');
+ expect(resolvePromptGroup).not.toHaveBeenCalled();
+ });
+
+ it('resolves a Langfuse group with one request', async () => {
+ const queryClient = createQueryClient();
+ const resolved = langfuseResolved({ prompt: 'Fetched text' });
+ resolvePromptGroup.mockResolvedValue(resolved);
+ const group = makeGroup({ source: 'langfuse', productionPrompt: null });
+
+ const { result } = renderHook(() => usePromptContentResolver(), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ let text: string | undefined;
+ await act(async () => {
+ text = await result.current(group);
+ });
+
+ expect(text).toBe('Fetched text');
+ expect(resolvePromptGroup).toHaveBeenCalledTimes(1);
+ expect(resolvePromptGroup).toHaveBeenCalledWith('group-1');
+ });
+
+ it('does not retry a failed resolve, even with a QueryClient that retries by default', async () => {
+ // Uses the QueryClient's own defaults (unlike `createQueryClient`, which
+ // already sets `retry: false`), so this only passes because the
+ // imperative fetch itself passes `retry: false`.
+ const queryClient = new QueryClient();
+ const error = new Error('resolve failed');
+ resolvePromptGroup.mockRejectedValue(error);
+ const group = makeGroup({ source: 'langfuse', productionPrompt: null });
+
+ const { result } = renderHook(() => usePromptContentResolver(), {
+ wrapper: createWrapper(queryClient),
+ });
+
+ await act(async () => {
+ await expect(result.current(group)).rejects.toThrow('resolve failed');
+ });
+
+ expect(resolvePromptGroup).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/hooks/Prompts/index.ts b/client/src/hooks/Prompts/index.ts
index cde5a62504..71520fa586 100644
--- a/client/src/hooks/Prompts/index.ts
+++ b/client/src/hooks/Prompts/index.ts
@@ -2,3 +2,7 @@ export { default as useCategories } from './useCategories';
export { default as usePromptGroupsNav } from './usePromptGroupsNav';
export { default as usePromptGroupPermissions } from './usePromptGroupPermissions';
export type { PromptGroupPermissions } from './usePromptGroupPermissions';
+export { default as usePromptContent, usePromptContentResolver } from './usePromptContent';
+export type { PromptContent } from './usePromptContent';
+export { default as useChatScopedRequest } from './useChatScopedRequest';
+export type { ChatScopedRequest } from './useChatScopedRequest';
diff --git a/client/src/hooks/Prompts/useChatScopedRequest.ts b/client/src/hooks/Prompts/useChatScopedRequest.ts
new file mode 100644
index 0000000000..37e0ba98d3
--- /dev/null
+++ b/client/src/hooks/Prompts/useChatScopedRequest.ts
@@ -0,0 +1,66 @@
+import { useRef, useEffect, useCallback } from 'react';
+import { useAtomValue } from 'jotai';
+import { useLocation } from 'react-router-dom';
+import { Constants } from 'librechat-data-provider';
+import { navigationGenerationAtom } from '~/store/navigation';
+import { getNewConversationDraftToken } from '~/utils';
+import { useChatContext } from '~/Providers';
+
+export interface ChatScopedRequest {
+ /** Claims the next token for a request this call starts. */
+ begin: () => number;
+ /** Whether `token` is still the most recent one `begin` issued. */
+ isCurrent: (token: number) => boolean;
+ /** Whether the component is still mounted. */
+ isMounted: () => boolean;
+}
+
+/**
+ * Cancellation for an async prompt resolve (a Langfuse read) that must not
+ * land on a chat other than the one it started for. Three independent keys
+ * decide that: `chatIdentity` (a saved chat's id, or — since a draft keeps
+ * the id `"new"` — the composer's draft token, which `useNewConvo` renews on
+ * a new-chat reset but keeps across same-chat updates such as a parameter
+ * edit); `navigationGeneration` (bumped the instant `navigateToConvo` starts,
+ * before the target conversation's record arrives and `chatIdentity` itself
+ * changes); and `pathname` (set by a browser Back/Forward move, which updates
+ * the URL before the target conversation replaces the one still mounted).
+ * Any of the three changing bumps the request token, so a pending resolve's
+ * own `isCurrent` check discards it, and runs `onCancel` because that
+ * resolve's `finally` block will not run for a request already discarded.
+ */
+export default function useChatScopedRequest(
+ index: number,
+ onCancel?: () => void,
+): ChatScopedRequest {
+ const { conversation } = useChatContext();
+ const { pathname } = useLocation();
+ const navigationGeneration = useAtomValue(navigationGenerationAtom);
+
+ const mountedRef = useRef(true);
+ const requestRef = useRef(0);
+ const onCancelRef = useRef(onCancel);
+ onCancelRef.current = onCancel;
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ const conversationId = conversation?.conversationId;
+ const chatIdentity =
+ conversationId === Constants.NEW_CONVO ? getNewConversationDraftToken(index) : conversationId;
+
+ useEffect(() => {
+ requestRef.current += 1;
+ onCancelRef.current?.();
+ }, [chatIdentity, navigationGeneration, pathname]);
+
+ const begin = useCallback(() => ++requestRef.current, []);
+ const isCurrent = useCallback((token: number) => token === requestRef.current, []);
+ const isMounted = useCallback(() => mountedRef.current, []);
+
+ return { begin, isCurrent, isMounted };
+}
diff --git a/client/src/hooks/Prompts/usePromptContent.ts b/client/src/hooks/Prompts/usePromptContent.ts
new file mode 100644
index 0000000000..228f29146f
--- /dev/null
+++ b/client/src/hooks/Prompts/usePromptContent.ts
@@ -0,0 +1,79 @@
+import { useCallback } from 'react';
+import type { TPromptGroup, TResolvedPromptResponse } from 'librechat-data-provider';
+import { useResolvePromptGroup, useResolvePromptGroupFn } from '~/data-provider';
+import { isExternalPromptGroup } from '~/utils';
+
+export interface PromptContent {
+ /** The prompt text to use: production text for a native group, the live
+ * Langfuse read for an external one. */
+ text: string;
+ /** The raw `/resolve` response, present only for an externally managed
+ * group; callers read `version`, `labels` and `sourceUrl` from it when
+ * `resolved.source === 'langfuse'`. */
+ resolved?: TResolvedPromptResponse;
+ isLoading: boolean;
+ error: unknown;
+ /** Re-issues the live Langfuse resolve after a failure. A no-op for a native
+ * group, which never requests the server. */
+ refetch: () => void;
+}
+
+/**
+ * Switches a prompt group's content between its two sources: a native
+ * group's `productionPrompt` is already loaded with the group, so this
+ * reads it directly with no request; an externally managed group (for
+ * example Langfuse) has no stored content, so this resolves it live through
+ * `useResolvePromptGroup`. `useResolvePromptGroup` is always called, since
+ * hook calls cannot be conditional, but it is disabled for a native group so
+ * no request is made.
+ */
+export default function usePromptContent(
+ group: TPromptGroup | undefined,
+ options?: { enabled?: boolean },
+): PromptContent {
+ const enabled = options?.enabled ?? true;
+ const isExternal = isExternalPromptGroup(group);
+
+ const query = useResolvePromptGroup(group?._id ?? '', {
+ enabled: enabled && isExternal && Boolean(group?._id),
+ });
+
+ if (!isExternal) {
+ return {
+ text: group?.productionPrompt?.prompt ?? '',
+ resolved: undefined,
+ isLoading: false,
+ error: undefined,
+ refetch: () => {},
+ };
+ }
+
+ return {
+ text: query.data?.prompt ?? '',
+ resolved: query.data,
+ // `isInitialLoading` (unlike `isLoading`) is false while the query is
+ // disabled, so a native group or a not-yet-enabled Langfuse one never
+ // reads as loading.
+ isLoading: query.isInitialLoading,
+ error: query.error,
+ refetch: () => void query.refetch(),
+ };
+}
+
+/**
+ * Imperative counterpart to `usePromptContent`, for a caller that resolves a
+ * group's text once (for example a slash-command submit) rather than
+ * rendering against a query. Native resolution never requests the server.
+ */
+export function usePromptContentResolver(): (group: TPromptGroup) => Promise<string> {
+ const fetchResolved = useResolvePromptGroupFn();
+ return useCallback(
+ (group: TPromptGroup): Promise<string> => {
+ if (!isExternalPromptGroup(group)) {
+ return Promise.resolve(group.productionPrompt?.prompt ?? '');
+ }
+ return fetchResolved(group._id ?? '').then((resolved) => resolved.prompt);
+ },
+ [fetchResolved],
+ );
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index ed1a12d90f..5f0c51b3b6 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2612,13 +2612,22 @@
"com_ui_prompt_langfuse_read_only": "Managed in Langfuse (prompt {{0}}). Edit it in Langfuse.",
"com_ui_prompt_name": "Prompt Name",
"com_ui_prompt_name_required": "Prompt Name is required",
+ "com_ui_prompt_open_in_langfuse": "Open in Langfuse",
"com_ui_prompt_preview_not_shared": "The author has not allowed collaboration for this prompt.",
"com_ui_prompt_read_only_error": "This prompt is managed externally and can't be changed here.",
+ "com_ui_prompt_resolve_error_blocked": "This prompt contains content blocked by this deployment and cannot be used.",
+ "com_ui_prompt_resolve_error_forbidden": "You no longer have access to this prompt.",
+ "com_ui_prompt_resolve_error_not_available": "Langfuse prompts are turned off.",
+ "com_ui_prompt_resolve_error_not_found": "This prompt was not found in Langfuse.",
+ "com_ui_prompt_resolve_error_rate_limited": "Too many prompt requests. Wait a minute and try again.",
+ "com_ui_prompt_resolve_error_source_changed": "The Langfuse connection changed. Ask an admin to sync prompts again.",
+ "com_ui_prompt_resolving": "Loading prompt from Langfuse…",
"com_ui_prompt_source_langfuse": "Managed in Langfuse",
"com_ui_prompt_text": "Text",
"com_ui_prompt_text_required": "Text is required",
"com_ui_prompt_update_error": "There was an error updating the prompt",
"com_ui_prompt_variables_list": "Prompt variables list",
+ "com_ui_prompt_version": "v{{0}}",
"com_ui_prompts": "Prompts",
"com_ui_prompts_allow_create": "Allow creating Prompts",
"com_ui_prompts_allow_share": "Allow sharing Prompts",
diff --git a/client/src/store/navigation.ts b/client/src/store/navigation.ts
new file mode 100644
index 0000000000..8f371c8200
--- /dev/null
+++ b/client/src/store/navigation.ts
@@ -0,0 +1,11 @@
+import { atom } from 'jotai';
+
+/**
+ * Bumped by `useNavigateToConvo` every time it starts a navigation —
+ * `navigateToConvo` itself and `supersedeNavigation`. A component with its
+ * own cancellation guard (keyed on a saved chat's id or a draft's composer
+ * token) subscribes to this value so a navigation that has only just
+ * started, before the target conversation commits, also cancels a pending
+ * continuation.
+ */
+export const navigationGenerationAtom = atom(0);
diff --git a/client/src/utils/__tests__/promptErrors.test.ts b/client/src/utils/__tests__/promptErrors.test.ts
new file mode 100644
index 0000000000..8302d16256
--- /dev/null
+++ b/client/src/utils/__tests__/promptErrors.test.ts
@@ -0,0 +1,150 @@
+import type { LocalizeFunction } from '~/common';
+import { getPromptErrorMessage, getPromptResolveErrorMessage } from '../promptErrors';
+
+/** The mock interpolates `{{0}}`-style i18next options by appending their values, so a test
+ * can assert that a localized line actually carried the HTTP status it was given. */
+const localize: LocalizeFunction = (key, options) =>
+ options ? `${key}:${Object.values(options).join(',')}` : key;
+
+/** An axios-style rejection the way the real backend sends one: an outer HTTP status plus a
+ * JSON body. Both mappers read `error.response.data`. */
+function axiosError(outerStatus: number, data: Record<string, unknown>) {
+ return { isAxiosError: true, response: { status: outerStatus, data } };
+}
+
+describe('getPromptResolveErrorMessage', () => {
+ it('maps a content-filter block, which has no code, before checking status or code', () => {
+ const error = axiosError(400, { error: 'content_filter_block' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_blocked',
+ );
+ });
+
+ it('maps a 403 (ACL middleware body, no code) to the forbidden message', () => {
+ const error = axiosError(403, { error: 'Forbidden' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_forbidden',
+ );
+ });
+
+ it('maps a 403 to the forbidden message even when the body carries an unrelated code', () => {
+ const error = axiosError(403, { code: 'not_found' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_forbidden',
+ );
+ });
+
+ it('maps a 429 (no code in the body) to the rate-limited message', () => {
+ const error = axiosError(429, { message: 'Too many requests' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_rate_limited',
+ );
+ });
+
+ it('maps not_found to its own resolve-specific key, not the dialog mapper key', () => {
+ const error = axiosError(404, { code: 'not_found' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_not_found',
+ );
+ });
+
+ it('maps not_available to the resolve-specific "turned off" key', () => {
+ const error = axiosError(404, { code: 'not_available' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_not_available',
+ );
+ });
+
+ it('maps source_changed to the resolve-specific key', () => {
+ const error = axiosError(409, { code: 'source_changed' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_prompt_resolve_error_source_changed',
+ );
+ });
+
+ it.each([
+ ['invalid_request', 'com_ui_langfuse_prompt_error_invalid_request'],
+ ['unsupported_type', 'com_ui_langfuse_prompt_error_unsupported_type'],
+ ['not_configured', 'com_ui_langfuse_prompt_error_not_configured'],
+ ['unauthorized', 'com_ui_langfuse_prompt_error_unauthorized'],
+ ['timeout', 'com_ui_langfuse_prompt_error_timeout'],
+ ['invalid_response', 'com_ui_langfuse_prompt_error_invalid_response'],
+ ])('reuses the dialog mapper key for the shared transport code %s', (code, key) => {
+ const error = axiosError(409, { code });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(key);
+ });
+
+ it('maps upstream with a status to the status-carrying key', () => {
+ const error = axiosError(502, { code: 'upstream', status: 503 });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_langfuse_prompt_error_upstream_status:503',
+ );
+ });
+
+ it('maps upstream with no status to the plain upstream key', () => {
+ const error = axiosError(502, { code: 'upstream' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_langfuse_prompt_error_upstream',
+ );
+ });
+
+ it('falls back for an unexpected 500 with no code', () => {
+ const error = axiosError(500, { message: 'Error resolving prompt' });
+ expect(getPromptResolveErrorMessage(error, localize)).toBe(
+ 'com_ui_langfuse_prompt_error_fallback',
+ );
+ });
+
+ it('falls back for a non-axios error', () => {
+ expect(getPromptResolveErrorMessage(new Error('network down'), localize)).toBe(
+ 'com_ui_langfuse_prompt_error_fallback',
+ );
+ });
+});
+
+describe('getPromptErrorMessage', () => {
+ it('keeps its own not_found copy, distinct from the resolve mapper key', () => {
+ const error = axiosError(404, { code: 'not_found' });
+ expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_not_found');
+ });
+
+ it('returns the forbidden copy for a 403, ahead of any body code', () => {
+ const error = axiosError(403, { message: 'Forbidden' });
+ expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_forbidden');
+ });
+
+ it('returns the forbidden copy for a 403 even when the body carries an unrelated code', () => {
+ const error = axiosError(403, { code: 'unauthorized' });
+ expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_forbidden');
+ });
+
+ it('maps the internal code to its localized copy', () => {
+ const error = axiosError(500, { code: 'internal' });
+ expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_internal');
+ });
+
+ it('maps a known code to its localized copy', () => {
+ const error = axiosError(409, { code: 'already_running' });
+ expect(getPromptErrorMessage(error, localize)).toBe(
+ 'com_ui_langfuse_prompt_error_already_running',
+ );
+ });
+
+ it('maps upstream with a status to the status-carrying key', () => {
+ const error = axiosError(502, { code: 'upstream', status: 503 });
+ expect(getPromptErrorMessage(error, localize)).toBe(
+ 'com_ui_langfuse_prompt_error_upstream_status:503',
+ );
+ });
+
+ it('falls back for an unmapped code', () => {
+ const error = axiosError(500, { code: 'something_new' });
+ expect(getPromptErrorMessage(error, localize)).toBe('com_ui_langfuse_prompt_error_fallback');
+ });
+
+ it('falls back to the generic copy for a non-axios error', () => {
+ expect(getPromptErrorMessage(new Error('boom'), localize)).toBe(
+ 'com_ui_langfuse_prompt_error_fallback',
+ );
+ });
+});
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index 5f46643a8a..7151bb078f 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -21,6 +21,7 @@ export * from './morph';
export * from './forms';
export * from './roles';
export * from './errors';
+export * from './promptErrors';
export * from './agents';
export * from './drafts';
export * from './convos';
diff --git a/client/src/utils/promptErrors.ts b/client/src/utils/promptErrors.ts
new file mode 100644
index 0000000000..8c78df0363
--- /dev/null
+++ b/client/src/utils/promptErrors.ts
@@ -0,0 +1,116 @@
+import axios from 'axios';
+import type {
+ TLangfusePromptErrorBody,
+ TLangfusePromptErrorCode,
+ TPromptResolveErrorCode,
+} from 'librechat-data-provider';
+import type { LocalizeFunction } from '~/common';
+import type { TranslationKeys } from '~/hooks';
+import { getResponseErrorCode, getResponseStatus } from './errors';
+
+/** The transport-failure codes `/resolve` and the Langfuse prompt-sync dialog share: both
+ * surface them from the same `LangfusePromptRequestError`/`toLangfusePromptErrorResponse`
+ * path, so they read as the same localized sentence in either surface. */
+const SHARED_LANGFUSE_TRANSPORT_ERROR_KEYS: Record<
+ | 'not_configured'
+ | 'unauthorized'
+ | 'timeout'
+ | 'invalid_response'
+ | 'unsupported_type'
+ | 'invalid_request',
+ TranslationKeys
+> = {
+ not_configured: 'com_ui_langfuse_prompt_error_not_configured',
+ unauthorized: 'com_ui_langfuse_prompt_error_unauthorized',
+ timeout: 'com_ui_langfuse_prompt_error_timeout',
+ invalid_response: 'com_ui_langfuse_prompt_error_invalid_response',
+ unsupported_type: 'com_ui_langfuse_prompt_error_unsupported_type',
+ invalid_request: 'com_ui_langfuse_prompt_error_invalid_request',
+};
+
+/** Codes whose whole copy is one localized sentence; `upstream` is handled separately below
+ * because its sentence needs the Langfuse HTTP status when the server sent one. */
+export const PROMPT_ERROR_MESSAGE_KEYS: Partial<Record<TLangfusePromptErrorCode, TranslationKeys>> =
+ {
+ ...SHARED_LANGFUSE_TRANSPORT_ERROR_KEYS,
+ not_found: 'com_ui_langfuse_prompt_error_not_found',
+ already_running: 'com_ui_langfuse_prompt_error_already_running',
+ lock_lost: 'com_ui_langfuse_prompt_error_lock_lost',
+ internal: 'com_ui_langfuse_prompt_error_internal',
+ };
+
+function getUpstreamStatus(error: unknown): number | undefined {
+ if (!axios.isAxiosError<TLangfusePromptErrorBody>(error)) {
+ return undefined;
+ }
+ const status = error.response?.data?.status;
+ return typeof status === 'number' ? status : undefined;
+}
+
+/** Maps a failed Langfuse prompt call to one short localized line, with a generic fallback for
+ * an unmapped or missing code (for example a bare 404 with no body, which means the feature is off).
+ * A 403 is checked ahead of any body code: it means the caller lacks permission regardless of
+ * what the body says, so it always wins. */
+export function getPromptErrorMessage(error: unknown, localize: LocalizeFunction): string {
+ if (getResponseStatus(error) === 403) {
+ return localize('com_ui_langfuse_prompt_error_forbidden');
+ }
+ const code = getResponseErrorCode<TLangfusePromptErrorCode>(error);
+ if (code === 'upstream') {
+ const status = getUpstreamStatus(error);
+ return status != null
+ ? localize('com_ui_langfuse_prompt_error_upstream_status', { 0: status })
+ : localize('com_ui_langfuse_prompt_error_upstream');
+ }
+ const messageKey = code != null ? PROMPT_ERROR_MESSAGE_KEYS[code] : undefined;
+ return localize(messageKey ?? 'com_ui_langfuse_prompt_error_fallback');
+}
+
+/** Codes whose whole copy is one localized sentence; `upstream` is handled separately,
+ * the same way `getPromptErrorMessage` handles it, with the Langfuse HTTP status. */
+const PROMPT_RESOLVE_ERROR_MESSAGE_KEYS: Partial<Record<TPromptResolveErrorCode, TranslationKeys>> =
+ {
+ ...SHARED_LANGFUSE_TRANSPORT_ERROR_KEYS,
+ not_found: 'com_ui_prompt_resolve_error_not_found',
+ not_available: 'com_ui_prompt_resolve_error_not_available',
+ source_changed: 'com_ui_prompt_resolve_error_source_changed',
+ };
+
+function isContentFilterBlock(error: unknown): boolean {
+ if (!axios.isAxiosError<{ error?: string }>(error)) {
+ return false;
+ }
+ return error.response?.data?.error === 'content_filter_block';
+}
+
+/**
+ * Maps a failed `GET /api/prompts/groups/:groupId/resolve` call to one short localized
+ * line. Checked in order: a content-filter block (`{ error: 'content_filter_block', ... }`,
+ * no `code`), a 403 (`{ error: 'Forbidden' }` from the ACL middleware, no `code`), a
+ * rate-limited 429 (`{ message }`, no `code`), then the response's `code`
+ * (`TPromptResolveErrorCode`). `unauthorized`, `timeout`, `upstream`, `invalid_response`,
+ * `unsupported_type`, `invalid_request` and `not_configured` reuse the exact keys
+ * `getPromptErrorMessage` already uses for them, since both read the same server error
+ * shapes; `not_found`, `not_available` and `source_changed` are resolve-specific. Falls
+ * back to the dialog mapper's generic fallback key for an unmapped or missing code.
+ */
+export function getPromptResolveErrorMessage(error: unknown, localize: LocalizeFunction): string {
+ if (isContentFilterBlock(error)) {
+ return localize('com_ui_prompt_resolve_error_blocked');
+ }
+ if (getResponseStatus(error) === 403) {
+ return localize('com_ui_prompt_resolve_error_forbidden');
+ }
+ if (getResponseStatus(error) === 429) {
+ return localize('com_ui_prompt_resolve_error_rate_limited');
+ }
+ const code = getResponseErrorCode<TPromptResolveErrorCode>(error);
+ if (code === 'upstream') {
+ const status = getUpstreamStatus(error);
+ return status != null
+ ? localize('com_ui_langfuse_prompt_error_upstream_status', { 0: status })
+ : localize('com_ui_langfuse_prompt_error_upstream');
+ }
+ const messageKey = code != null ? PROMPT_RESOLVE_ERROR_MESSAGE_KEYS[code] : undefined;
+ return localize(messageKey ?? 'com_ui_langfuse_prompt_error_fallback');
+}
diff --git a/packages/api/src/langfuse/index.ts b/packages/api/src/langfuse/index.ts
index af96a758c1..6d7629ce36 100644
--- a/packages/api/src/langfuse/index.ts
+++ b/packages/api/src/langfuse/index.ts
@@ -1,5 +1,6 @@
export * from './destinations';
export * from './feedback';
+export * from './links';
export * from './policy';
export * from './promptCatalogSync';
export * from './promptSyncRunner';
diff --git a/packages/api/src/langfuse/links.spec.ts b/packages/api/src/langfuse/links.spec.ts
new file mode 100644
index 0000000000..11b4365e21
--- /dev/null
+++ b/packages/api/src/langfuse/links.spec.ts
@@ -0,0 +1,27 @@
+import { getLangfusePromptUrl } from './links';
+
+describe('getLangfusePromptUrl', () => {
+ it('builds a prompt URL from a plain base URL', () => {
+ expect(getLangfusePromptUrl('https://cloud.langfuse.test', 'project-1', 'greeting')).toBe(
+ 'https://cloud.langfuse.test/project/project-1/prompts/greeting',
+ );
+ });
+
+ it('preserves a path prefix on the base URL and drops its trailing slash', () => {
+ expect(getLangfusePromptUrl('https://host.test/lf/', 'project-1', 'greeting')).toBe(
+ 'https://host.test/lf/project/project-1/prompts/greeting',
+ );
+ });
+
+ it('encodes a prompt name with spaces and slashes', () => {
+ expect(
+ getLangfusePromptUrl('https://cloud.langfuse.test', 'project-1', 'support/greeting one'),
+ ).toBe('https://cloud.langfuse.test/project/project-1/prompts/support%2Fgreeting%20one');
+ });
+
+ it('encodes the project id', () => {
+ expect(getLangfusePromptUrl('https://cloud.langfuse.test', 'project one', 'greeting')).toBe(
+ 'https://cloud.langfuse.test/project/project%20one/prompts/greeting',
+ );
+ });
+});
diff --git a/packages/api/src/langfuse/links.ts b/packages/api/src/langfuse/links.ts
new file mode 100644
index 0000000000..21c80adaf1
--- /dev/null
+++ b/packages/api/src/langfuse/links.ts
@@ -0,0 +1,13 @@
+/**
+ * Builds the Langfuse console URL for a prompt. Mirrors `resolveLangfuseSession`
+ * in `./session`: `new URL(baseUrl)`, trim any trailing slash from the existing
+ * path, then append the new segment, so a base URL with a path prefix (for
+ * example `https://host/lf/`) produces `https://host/lf/project/...` rather
+ * than discarding the prefix.
+ */
+export function getLangfusePromptUrl(baseUrl: string, projectId: string, name: string): string {
+ const promptUrl = new URL(baseUrl);
+ const basePath = promptUrl.pathname.replace(/\/+$/, '');
+ promptUrl.pathname = `${basePath}/project/${encodeURIComponent(projectId)}/prompts/${encodeURIComponent(name)}`;
+ return promptUrl.toString();
+}
diff --git a/packages/api/src/prompts/handlers.spec.ts b/packages/api/src/prompts/handlers.spec.ts
index 5d5e96e6a2..fa2076682f 100644
--- a/packages/api/src/prompts/handlers.spec.ts
+++ b/packages/api/src/prompts/handlers.spec.ts
@@ -1,10 +1,12 @@
import { logger } from '@librechat/data-schemas';
+import { SystemRoles } from 'librechat-data-provider';
import type { Response } from 'express';
import type { PromptRequest, PromptHandlersDeps } from './handlers';
import type { PromptService } from './service';
+import type { ResolvedPrompt } from './types';
import { contentFilterBlockResponse } from '../middleware/contentFilter';
+import { createPromptHandlers, toResolveResponse } from './handlers';
import { LangfusePromptRequestError } from '../langfuse/prompts';
-import { createPromptHandlers } from './handlers';
import { PromptStoreError } from './errors';
function mockReq(overrides: Record<string, unknown> = {}): PromptRequest {
@@ -865,4 +867,87 @@ describe('createPromptHandlers resolvePrompt', () => {
expect(res.statusCode).toBe(500);
expect(res.body).toEqual({ message: 'Error resolving prompt' });
});
+
+ it('sends sourceUrl for an admin resolving a Langfuse group', async () => {
+ const resolvePrompt = jest.fn().mockResolvedValue({
+ ok: true,
+ value: {
+ source: 'langfuse',
+ groupId,
+ prompt: 'Hi',
+ type: 'text',
+ version: 3,
+ labels: ['production'],
+ sourceUrl: 'https://langfuse.test/project/p1/prompts/greeting',
+ },
+ });
+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ resolvePrompt }) }));
+ const res = mockRes();
+
+ await handlers.resolvePrompt(
+ mockReq({ user: { id: 'admin-1', role: SystemRoles.ADMIN } }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toMatchObject({
+ sourceUrl: 'https://langfuse.test/project/p1/prompts/greeting',
+ });
+ });
+
+ it('omits sourceUrl for a non-admin resolving a Langfuse group', async () => {
+ const resolvePrompt = jest.fn().mockResolvedValue({
+ ok: true,
+ value: {
+ source: 'langfuse',
+ groupId,
+ prompt: 'Hi',
+ type: 'text',
+ version: 3,
+ labels: ['production'],
+ sourceUrl: 'https://langfuse.test/project/p1/prompts/greeting',
+ },
+ });
+ const handlers = createPromptHandlers(makeDeps({ service: makeService({ resolvePrompt }) }));
+ const res = mockRes();
+
+ await handlers.resolvePrompt(mockReq({ user: { id: 'u1', role: SystemRoles.USER } }), res);
+
+ expect(res.statusCode).toBe(200);
+ expect((res.body as Record<string, unknown>).sourceUrl).toBeUndefined();
+ });
+});
+
+describe('toResolveResponse', () => {
+ const langfuseValue: ResolvedPrompt = {
+ source: 'langfuse',
+ groupId,
+ prompt: 'Hi',
+ type: 'text',
+ version: 1,
+ labels: ['production'],
+ sourceUrl: 'https://langfuse.test/project/p1/prompts/greeting',
+ };
+ const nativeValue: ResolvedPrompt = {
+ source: 'native',
+ groupId,
+ promptId,
+ prompt: 'Hi',
+ type: 'text',
+ };
+
+ it('keeps sourceUrl for an admin', () => {
+ expect(toResolveResponse(langfuseValue, { isAdmin: true })).toEqual(langfuseValue);
+ });
+
+ it('strips sourceUrl for a non-admin', () => {
+ const result = toResolveResponse(langfuseValue, { isAdmin: false });
+ expect(result).not.toHaveProperty('sourceUrl');
+ expect(result).toEqual({ ...langfuseValue, sourceUrl: undefined });
+ });
+
+ it('leaves a native group unaffected either way', () => {
+ expect(toResolveResponse(nativeValue, { isAdmin: false })).toEqual(nativeValue);
+ expect(toResolveResponse(nativeValue, { isAdmin: true })).toEqual(nativeValue);
+ });
});
diff --git a/packages/api/src/prompts/handlers.ts b/packages/api/src/prompts/handlers.ts
index 90b3e7e2e9..5294515de8 100644
--- a/packages/api/src/prompts/handlers.ts
+++ b/packages/api/src/prompts/handlers.ts
@@ -3,10 +3,17 @@ import { logger, isValidObjectIdString } from '@librechat/data-schemas';
import {
PermissionBits,
ResourceType,
+ SystemRoles,
DEFAULT_CACHE_CLEAR_TIMEOUT_MS,
} from 'librechat-data-provider';
import type { Response } from 'express';
-import type { PromptGroupRecord, PromptSelection, PromptServiceError, StoredId } from './types';
+import type {
+ PromptGroupRecord,
+ PromptSelection,
+ PromptServiceError,
+ ResolvedPrompt,
+ StoredId,
+} from './types';
import type { PromptViaGroupResource } from './access';
import type { PromptService } from './service';
import type { ServerRequest } from '~/types';
@@ -115,6 +122,21 @@ function sendRejection(res: Response, error: PromptServiceError): Response {
return res.status(400).send({ error: 'Prompt operation is not available' });
}
+/**
+ * Omits `sourceUrl` from a resolved Langfuse prompt for a non-admin requester. A native
+ * result carries no `sourceUrl` and is returned unchanged either way.
+ */
+export function toResolveResponse(
+ value: ResolvedPrompt,
+ { isAdmin }: { isAdmin: boolean },
+): ResolvedPrompt {
+ if (value.source !== 'langfuse' || isAdmin) {
+ return value;
+ }
+ const { sourceUrl: _sourceUrl, ...rest } = value;
+ return rest;
+}
+
/**
* Maps a `resolvePrompt` rejection to its `/resolve` response. `unsupported_source` only
* comes from the `allowedSources` check, which this route never passes, and
@@ -250,7 +272,9 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {
if (!result.ok) {
return sendResolveRejection(res, result.error);
}
- return res.status(200).send(result.value);
+ return res
+ .status(200)
+ .send(toResolveResponse(result.value, { isAdmin: req.user?.role === SystemRoles.ADMIN }));
} catch (error) {
if (error instanceof LangfusePromptRequestError) {
logger.error('[prompts] Langfuse request failed while resolving a prompt', error);
diff --git a/packages/api/src/prompts/langfuse.spec.ts b/packages/api/src/prompts/langfuse.spec.ts
index 3089b23f36..9d6e037d06 100644
--- a/packages/api/src/prompts/langfuse.spec.ts
+++ b/packages/api/src/prompts/langfuse.spec.ts
@@ -68,6 +68,7 @@ function makeGroup(overrides: Partial<PromptGroupRecord> = {}): PromptGroupRecor
authorName: 'Author',
source: 'langfuse',
sourcePromptName: 'greeting',
+ sourceProjectId: 'project-1',
tenantId: 'tenant-1',
...overrides,
};
@@ -121,6 +122,40 @@ describe('createLangfusePromptAdapter', () => {
type: 'text',
version: 4,
labels: ['production'],
+ sourceUrl: 'https://cloud.langfuse.test/project/project-1/prompts/greeting',
+ },
+ });
+ });
+
+ it('builds sourceUrl from the connection base URL, the project id and the encoded prompt name', async () => {
+ const scopedConnection: LangfusePromptConnection = {
+ baseUrl: 'https://host.test/lf/',
+ authorization: 'Basic cGs6c2s=',
+ };
+ const resolveSource = jest.fn().mockResolvedValue({
+ ok: true,
+ connection: scopedConnection,
+ } satisfies LangfuseSourceResolution);
+ const adapter = createLangfusePromptAdapter({ resolveSource, timeoutMs: () => 5000 });
+ fetchMock.mockResolvedValue(
+ jsonResponse({
+ name: 'support/greeting one',
+ version: 1,
+ type: 'text',
+ labels: ['production'],
+ prompt: 'Hi',
+ }),
+ );
+
+ const result = await adapter.resolvePrompt({
+ group: makeGroup({ sourcePromptName: 'support/greeting one', sourceProjectId: 'proj 1' }),
+ selection: { type: 'production' },
+ });
+
+ expect(result).toMatchObject({
+ ok: true,
+ value: {
+ sourceUrl: 'https://host.test/lf/project/proj%201/prompts/support%2Fgreeting%20one',
},
});
});
@@ -148,6 +183,7 @@ describe('createLangfusePromptAdapter', () => {
type: 'text',
version: 3,
labels: [],
+ sourceUrl: 'https://cloud.langfuse.test/project/project-1/prompts/greeting',
},
});
});
diff --git a/packages/api/src/prompts/langfuse.ts b/packages/api/src/prompts/langfuse.ts
index 0061801b35..42c2b2311b 100644
--- a/packages/api/src/prompts/langfuse.ts
+++ b/packages/api/src/prompts/langfuse.ts
@@ -3,6 +3,7 @@ import type { LangfuseTextPromptSelector } from '../langfuse/prompts';
import type { PromptSourceAdapter } from './types';
import { getLangfusePromptSyncTimeoutMs } from '../langfuse/policy';
import { getLangfuseTextPrompt } from '../langfuse/prompts';
+import { getLangfusePromptUrl } from '../langfuse/links';
export interface CreateLangfusePromptAdapterDependencies {
/** Checks the deployment gate, tenant match and prompt-sync switch; builds the
@@ -71,6 +72,11 @@ export function createLangfusePromptAdapter({
type: 'text',
version: result.value.version,
labels: result.value.labels,
+ sourceUrl: getLangfusePromptUrl(
+ resolution.connection.baseUrl,
+ group.sourceProjectId ?? '',
+ group.sourcePromptName,
+ ),
},
};
},
diff --git a/packages/api/src/prompts/service.spec.ts b/packages/api/src/prompts/service.spec.ts
index 6dd54575a2..7f77beb824 100644
--- a/packages/api/src/prompts/service.spec.ts
+++ b/packages/api/src/prompts/service.spec.ts
@@ -787,6 +787,7 @@ describe('createPromptService', () => {
type: 'text',
version: 3,
labels: ['production'],
+ sourceUrl: 'https://cloud.langfuse.test/project/project-1/prompts/langfuse-prompt',
...overrides,
};
}
diff --git a/packages/api/src/prompts/types.ts b/packages/api/src/prompts/types.ts
index 21778a88bc..c5721d676d 100644
--- a/packages/api/src/prompts/types.ts
+++ b/packages/api/src/prompts/types.ts
@@ -80,6 +80,10 @@ export interface LangfuseResolvedPrompt {
readonly type: 'text';
readonly version: number;
readonly labels: readonly string[];
+ /** Deep link to this prompt in the Langfuse console (`getLangfusePromptUrl`). Present
+ * only when the adapter resolves it; the `/resolve` handler also strips it from a
+ * non-admin response. */
+ readonly sourceUrl?: string;
}
export type ResolvedPrompt = NativeResolvedPrompt | LangfuseResolvedPrompt;
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 7e1eda2fcf..901e5669dd 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -60,6 +60,7 @@ export enum QueryKeys {
promptGroups = 'promptGroups',
allPromptGroups = 'allPromptGroups',
promptGroup = 'promptGroup',
+ promptGroupContent = 'promptGroupContent',
projects = 'projects',
project = 'project',
projectFiles = 'projectFiles',
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index c4bc145da5..89fe4851b1 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -1265,6 +1265,9 @@ export type TResolvedLangfusePrompt = {
type: 'text';
version: number;
labels: string[];
+ /** Deep link to this prompt in the Langfuse console. Present only when the
+ * requesting user is an admin. */
+ sourceUrl?: string;
};
export type TResolvedPromptResponse = TResolvedNativePrompt | TResolvedLangfusePrompt;