mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-19 22:43:38 +00:00
🖐️ feat: Make External Prompt Groups Read-Only (#17008)
Reject edits, deletes, new revisions, promotion and revision deletes on prompt groups whose source is not native with a read_only service error, mapped to 403 "Externally managed prompts are read-only". The guard reads the stored group, so the MANAGE_PROMPTS bypass is covered. Sharing, usage counts and resolution are unchanged. The client hides Edit and Delete for external groups, shows a read-only detail view with a Langfuse notice and keeps Share.
This commit is contained in:
parent
02613ce212
commit
bf0b8a9031
25 changed files with 1682 additions and 132 deletions
|
|
@ -49,6 +49,9 @@ jest.mock('~/server/middleware', () => ({
|
|||
canAccessPromptViaGroup: jest.requireActual('~/server/middleware').canAccessPromptViaGroup,
|
||||
canAccessPromptGroupResource:
|
||||
jest.requireActual('~/server/middleware').canAccessPromptGroupResource,
|
||||
checkBan: (_req, _res, next) => next(),
|
||||
uaParser: (_req, _res, next) => next(),
|
||||
canAccessResource: jest.requireActual('~/server/middleware').canAccessResource,
|
||||
}));
|
||||
|
||||
const { configMiddleware } = require('~/server/middleware');
|
||||
|
|
@ -56,6 +59,7 @@ const { configMiddleware } = require('~/server/middleware');
|
|||
let app;
|
||||
let mongoServer;
|
||||
let promptRoutes;
|
||||
let accessPermissionsRoutes;
|
||||
let Prompt, PromptGroup, AclEntry, AccessRole, User, SystemGrant, Config;
|
||||
let testUsers, testRoles;
|
||||
let grantPermission;
|
||||
|
|
@ -114,6 +118,11 @@ beforeAll(async () => {
|
|||
// Import routes after middleware is set up
|
||||
promptRoutes = require('./prompts');
|
||||
app.use('/api/prompts', promptRoutes);
|
||||
|
||||
// Mounted so the sharing test below can call the real access-permissions router
|
||||
// (and its real `updateResourcePermissions` controller) instead of the service layer.
|
||||
accessPermissionsRoutes = require('./accessPermissions');
|
||||
app.use('/api/permissions', accessPermissionsRoutes);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
|
@ -204,7 +213,7 @@ async function setupTestData() {
|
|||
getRoleByName.mockImplementation((roleName) => {
|
||||
switch (roleName) {
|
||||
case SystemRoles.USER:
|
||||
return { permissions: { PROMPTS: { USE: true, CREATE: true } } };
|
||||
return { permissions: { PROMPTS: { USE: true, CREATE: true, SHARE: true } } };
|
||||
case SystemRoles.ADMIN:
|
||||
return { permissions: { PROMPTS: { USE: true, CREATE: true, SHARE: true } } };
|
||||
default:
|
||||
|
|
@ -1628,6 +1637,243 @@ describe('GET /api/prompts/groups/:groupId/resolve', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('Externally managed (Langfuse) prompt groups are read-only', () => {
|
||||
const readOnlyBody = { code: 'read_only', error: 'Externally managed prompts are read-only' };
|
||||
let group;
|
||||
|
||||
async function seedLangfuseGroup(owner = testUsers.owner) {
|
||||
const langfuseGroup = await PromptGroup.create({
|
||||
name: 'Read-only Langfuse group',
|
||||
category: 'langfuse-read-only',
|
||||
author: owner._id,
|
||||
authorName: owner.name,
|
||||
source: 'langfuse',
|
||||
sourcePromptName: 'greeting',
|
||||
sourceProjectId: 'ro-project',
|
||||
sourceDestination: 'env',
|
||||
});
|
||||
await grantPermission({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: owner._id,
|
||||
resourceType: ResourceType.PROMPTGROUP,
|
||||
resourceId: langfuseGroup._id,
|
||||
accessRoleId: AccessRoleIds.PROMPTGROUP_OWNER,
|
||||
grantedBy: owner._id,
|
||||
});
|
||||
return langfuseGroup;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
group = await seedLangfuseGroup();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Prompt.deleteMany({});
|
||||
await PromptGroup.deleteMany({});
|
||||
await AclEntry.deleteMany({});
|
||||
});
|
||||
|
||||
it('rejects PATCH /groups/:groupId with 403 and leaves the group unchanged', async () => {
|
||||
const before = await PromptGroup.findById(group._id).lean();
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${group._id}`)
|
||||
.send({ name: 'Hacked name' })
|
||||
.expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
const after = await PromptGroup.findById(group._id).lean();
|
||||
expect(after).toEqual(before);
|
||||
});
|
||||
|
||||
it('rejects DELETE /groups/:groupId with 403 and leaves the group in place', async () => {
|
||||
const response = await request(app).delete(`/api/prompts/groups/${group._id}`).expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
await expect(PromptGroup.findById(group._id)).resolves.not.toBeNull();
|
||||
const ownerEntry = await AclEntry.findOne({
|
||||
resourceType: ResourceType.PROMPTGROUP,
|
||||
resourceId: group._id,
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: testUsers.owner._id,
|
||||
});
|
||||
expect(ownerEntry).toBeTruthy();
|
||||
});
|
||||
|
||||
it('rejects POST /groups/:groupId/prompts (new revision) with 403 and adds no revision', async () => {
|
||||
const response = await request(app)
|
||||
.post(`/api/prompts/groups/${group._id}/prompts`)
|
||||
.send({ prompt: { prompt: 'New text', type: 'text' } })
|
||||
.expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
await expect(Prompt.countDocuments({ groupId: group._id })).resolves.toBe(0);
|
||||
});
|
||||
|
||||
it('rejects PATCH /groups/:groupId for an admin too (MANAGE_PROMPTS ACL bypass still hits the service guard)', async () => {
|
||||
setTestUser(app, testUsers.admin);
|
||||
const before = await PromptGroup.findById(group._id).lean();
|
||||
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${group._id}`)
|
||||
.send({ name: 'Admin hack' })
|
||||
.expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
const after = await PromptGroup.findById(group._id).lean();
|
||||
expect(after).toEqual(before);
|
||||
});
|
||||
|
||||
it('rejects DELETE /groups/:groupId for an admin too (MANAGE_PROMPTS ACL bypass still hits the service guard)', async () => {
|
||||
setTestUser(app, testUsers.admin);
|
||||
|
||||
const response = await request(app).delete(`/api/prompts/groups/${group._id}`).expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
await expect(PromptGroup.findById(group._id)).resolves.not.toBeNull();
|
||||
});
|
||||
|
||||
describe('with a Prompt row inserted directly for the group', () => {
|
||||
let revision;
|
||||
|
||||
beforeEach(async () => {
|
||||
revision = await Prompt.create({
|
||||
prompt: 'Synced from Langfuse',
|
||||
author: testUsers.owner._id,
|
||||
type: 'text',
|
||||
groupId: group._id,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects PATCH /:promptId/tags/production with 403 and does not promote', async () => {
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/${revision._id}/tags/production`)
|
||||
.expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
const after = await PromptGroup.findById(group._id).lean();
|
||||
expect(after.productionId ?? null).toBeNull();
|
||||
await expect(Prompt.findById(revision._id)).resolves.not.toBeNull();
|
||||
});
|
||||
|
||||
it('rejects DELETE /:promptId with 403 and keeps the revision', async () => {
|
||||
const response = await request(app)
|
||||
.delete(`/api/prompts/${revision._id}`)
|
||||
.query({ groupId: group._id.toString() })
|
||||
.expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
await expect(Prompt.findById(revision._id)).resolves.not.toBeNull();
|
||||
await expect(PromptGroup.findById(group._id)).resolves.not.toBeNull();
|
||||
});
|
||||
|
||||
it('rejects DELETE /:promptId for an admin too (MANAGE_PROMPTS ACL bypass still hits the service guard)', async () => {
|
||||
setTestUser(app, testUsers.admin);
|
||||
|
||||
const response = await request(app)
|
||||
.delete(`/api/prompts/${revision._id}`)
|
||||
.query({ groupId: group._id.toString() })
|
||||
.expect(403);
|
||||
|
||||
expect(response.body).toEqual(readOnlyBody);
|
||||
await expect(Prompt.findById(revision._id)).resolves.not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps POST /groups/:groupId/use working: it increments numberOfGenerations', async () => {
|
||||
const response = await request(app).post(`/api/prompts/groups/${group._id}/use`).expect(200);
|
||||
|
||||
expect(response.body).toEqual({ numberOfGenerations: 1 });
|
||||
const after = await PromptGroup.findById(group._id).lean();
|
||||
expect(after.numberOfGenerations).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps sharing working through the access-permissions routes', async () => {
|
||||
setTestUser(app, testUsers.owner);
|
||||
|
||||
const response = await request(app)
|
||||
.put(`/api/permissions/${ResourceType.PROMPTGROUP}/${group._id}`)
|
||||
.send({
|
||||
updated: [
|
||||
{
|
||||
type: PrincipalType.USER,
|
||||
id: testUsers.viewer._id.toString(),
|
||||
accessRoleId: AccessRoleIds.PROMPTGROUP_VIEWER,
|
||||
},
|
||||
],
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.message).toBe('Permissions updated successfully');
|
||||
|
||||
const sharedEntry = await AclEntry.findOne({
|
||||
resourceType: ResourceType.PROMPTGROUP,
|
||||
resourceId: group._id,
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: testUsers.viewer._id,
|
||||
});
|
||||
expect(sharedEntry).toBeTruthy();
|
||||
|
||||
// Sharing an externally managed group only grants an ACL entry; it never touches
|
||||
// the read-only group document itself.
|
||||
const after = await PromptGroup.findById(group._id).lean();
|
||||
expect(after.name).toBe(group.name);
|
||||
});
|
||||
});
|
||||
|
||||
describe('A stored prompt group with no source (predates the field) stays editable', () => {
|
||||
let group;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Bypasses the schema's `source: 'native'` default to reproduce a group
|
||||
// written before the field existed.
|
||||
const inserted = await PromptGroup.collection.insertOne({
|
||||
name: 'Pre-source Group',
|
||||
category: 'legacy-no-source',
|
||||
author: testUsers.owner._id,
|
||||
authorName: testUsers.owner.name,
|
||||
productionId: new ObjectId(),
|
||||
});
|
||||
group = { _id: inserted.insertedId };
|
||||
|
||||
await grantPermission({
|
||||
principalType: PrincipalType.USER,
|
||||
principalId: testUsers.owner._id,
|
||||
resourceType: ResourceType.PROMPTGROUP,
|
||||
resourceId: group._id,
|
||||
accessRoleId: AccessRoleIds.PROMPTGROUP_OWNER,
|
||||
grantedBy: testUsers.owner._id,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Prompt.deleteMany({});
|
||||
await PromptGroup.deleteMany({});
|
||||
await AclEntry.deleteMany({});
|
||||
});
|
||||
|
||||
it('allows PATCH /groups/:groupId to rename it, same as a native group', async () => {
|
||||
const response = await request(app)
|
||||
.patch(`/api/prompts/groups/${group._id}`)
|
||||
.send({ name: 'Renamed legacy group' })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.name).toBe('Renamed legacy group');
|
||||
const stored = await PromptGroup.findById(group._id).lean();
|
||||
expect(stored.name).toBe('Renamed legacy group');
|
||||
});
|
||||
|
||||
it('allows POST /groups/:groupId/prompts to add a text prompt, same as a native group', async () => {
|
||||
const response = await request(app)
|
||||
.post(`/api/prompts/groups/${group._id}/prompts`)
|
||||
.send({ prompt: { prompt: 'New legacy prompt text', type: 'text' } })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.prompt.prompt).toBe('New legacy prompt text');
|
||||
await expect(Prompt.countDocuments({ groupId: group._id })).resolves.toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Prompt Routes - response and failure compatibility', () => {
|
||||
let consoleErrorSpy;
|
||||
let group;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,9 @@ import {
|
|||
OGDialogTrigger,
|
||||
TooltipAnchor,
|
||||
OGDialogTemplate,
|
||||
useToastContext,
|
||||
} from '@librechat/client';
|
||||
import { getPromptMutationErrorKey } from '~/utils';
|
||||
import { useDeletePrompt } from '~/data-provider';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
|
|
@ -75,7 +77,16 @@ interface DeletePromptProps {
|
|||
|
||||
const DeletePrompt = React.memo(
|
||||
({ promptId, groupId, promptName, disabled }: DeletePromptProps) => {
|
||||
const deletePromptMutation = useDeletePrompt();
|
||||
const localize = useLocalize();
|
||||
const { showToast } = useToastContext();
|
||||
const deletePromptMutation = useDeletePrompt({
|
||||
onError: (error) => {
|
||||
showToast({
|
||||
status: 'error',
|
||||
message: localize(getPromptMutationErrorKey(error, 'com_ui_prompt_delete_error')),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleDelete = useCallback(() => {
|
||||
if (!promptId) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,97 @@
|
|||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import DeletePrompt from '../DeletePrompt';
|
||||
|
||||
const mockShowToast = jest.fn();
|
||||
const mockMutate = jest.fn();
|
||||
let capturedOnError: ((error: unknown) => void) | undefined;
|
||||
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useDeletePrompt: (options?: { onError?: (error: unknown) => void }) => {
|
||||
capturedOnError = options?.onError;
|
||||
return { mutate: mockMutate, isLoading: false };
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
jest.mock('@librechat/client', () => {
|
||||
const React = jest.requireActual('react');
|
||||
return {
|
||||
Button: ({ children, ...rest }: any) => React.createElement('button', rest, children),
|
||||
TooltipAnchor: ({ render }: { render: React.ReactNode }) => render,
|
||||
OGDialog: ({ children }: any) => React.createElement(React.Fragment, null, children),
|
||||
OGDialogTrigger: ({ children }: any) => children,
|
||||
OGDialogTemplate: ({ selection }: any) =>
|
||||
React.createElement(
|
||||
'button',
|
||||
{ 'data-testid': 'delete-confirm-button', onClick: selection?.selectHandler },
|
||||
selection?.selectText ?? 'Confirm',
|
||||
),
|
||||
useToastContext: () => ({ showToast: mockShowToast }),
|
||||
};
|
||||
});
|
||||
|
||||
describe('DeletePrompt', () => {
|
||||
beforeEach(() => {
|
||||
mockShowToast.mockClear();
|
||||
mockMutate.mockClear();
|
||||
capturedOnError = undefined;
|
||||
});
|
||||
|
||||
it('deletes the revision on confirm', () => {
|
||||
render(
|
||||
<DeletePrompt
|
||||
promptId="prompt-1"
|
||||
groupId="group-1"
|
||||
promptName="My Prompt"
|
||||
disabled={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByTestId('delete-confirm-button'));
|
||||
|
||||
expect(mockMutate).toHaveBeenCalledWith({ _id: 'prompt-1', groupId: 'group-1' });
|
||||
});
|
||||
|
||||
it('shows the externally-managed message when the server rejects a read-only revision delete', () => {
|
||||
render(
|
||||
<DeletePrompt
|
||||
promptId="prompt-1"
|
||||
groupId="group-1"
|
||||
promptName="My Prompt"
|
||||
disabled={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(capturedOnError).toBeDefined();
|
||||
capturedOnError?.({
|
||||
isAxiosError: true,
|
||||
response: { status: 403, data: { code: 'read_only' } },
|
||||
});
|
||||
|
||||
expect(mockShowToast).toHaveBeenCalledWith({
|
||||
status: 'error',
|
||||
message: 'com_ui_prompt_read_only_error',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to the generic delete-error message for a non-read-only failure', () => {
|
||||
render(
|
||||
<DeletePrompt
|
||||
promptId="prompt-1"
|
||||
groupId="group-1"
|
||||
promptName="My Prompt"
|
||||
disabled={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
capturedOnError?.({ isAxiosError: true, response: { status: 500, data: {} } });
|
||||
|
||||
expect(mockShowToast).toHaveBeenCalledWith({
|
||||
status: 'error',
|
||||
message: 'com_ui_prompt_delete_error',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import React, { useId, useMemo, useState } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { DropdownPopup } from '@librechat/client';
|
||||
import { LocalStorageKeys } from 'librechat-data-provider';
|
||||
import { useFormContext, Controller } from 'react-hook-form';
|
||||
import { DropdownPopup, disabledFillClasses } from '@librechat/client';
|
||||
import type { MenuItemProps } from '@librechat/client';
|
||||
import type { ReactNode } from 'react';
|
||||
import { usePromptGroupsContext } from '~/Providers';
|
||||
|
|
@ -16,6 +16,8 @@ interface CategorySelectorProps {
|
|||
className?: string;
|
||||
/** Portaled menus are unclickable inside a modal dialog, which locks pointer events on the body */
|
||||
portal?: boolean;
|
||||
/** Disables the trigger for a read-only group */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const CategorySelector: React.FC<CategorySelectorProps> = ({
|
||||
|
|
@ -23,6 +25,7 @@ const CategorySelector: React.FC<CategorySelectorProps> = ({
|
|||
onValueChange,
|
||||
className = '',
|
||||
portal = true,
|
||||
disabled = false,
|
||||
}) => {
|
||||
const instanceId = useId();
|
||||
const menuId = `${instanceId}-category-menu`;
|
||||
|
|
@ -79,11 +82,14 @@ const CategorySelector: React.FC<CategorySelectorProps> = ({
|
|||
const trigger = (
|
||||
<Ariakit.MenuButton
|
||||
className={cn(
|
||||
'relative inline-flex h-9 items-center justify-between rounded-xl border border-border-medium bg-transparent px-3 text-sm text-text-primary transition-all duration-200 ease-in-out hover:bg-surface-hover hover:text-text-primary focus:ring-2 focus:ring-ring-primary',
|
||||
'border-border-medium text-text-primary hover:bg-surface-hover hover:text-text-primary focus:ring-ring-primary relative inline-flex h-9 items-center justify-between rounded-xl border bg-transparent px-3 text-sm transition-all duration-200 ease-in-out focus:ring-2',
|
||||
'gap-2 sm:w-fit',
|
||||
'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent',
|
||||
disabledFillClasses,
|
||||
className,
|
||||
)}
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
disabled={disabled}
|
||||
onClick={() => !disabled && setIsOpen(!isOpen)}
|
||||
aria-label={t('com_ui_prompt_category_selector_aria')}
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
|
@ -92,7 +98,7 @@ const CategorySelector: React.FC<CategorySelectorProps> = ({
|
|||
)}
|
||||
<span>{displayCategory.value ? displayCategory.label : t('com_ui_category')}</span>
|
||||
</div>
|
||||
<Ariakit.MenuButtonArrow />
|
||||
{!disabled && <Ariakit.MenuButtonArrow />}
|
||||
</Ariakit.MenuButton>
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -7,12 +7,20 @@ type Props = {
|
|||
name?: string;
|
||||
isLoading?: boolean;
|
||||
isError?: boolean;
|
||||
/** Hides the edit affordance and keeps the name read-only */
|
||||
disabled?: boolean;
|
||||
onSave: (newName: string) => void;
|
||||
};
|
||||
|
||||
type SaveStatus = 'idle' | 'saving' | 'saved' | 'error';
|
||||
|
||||
const PromptName: React.FC<Props> = ({ name, isLoading = false, isError = false, onSave }) => {
|
||||
const PromptName: React.FC<Props> = ({
|
||||
name,
|
||||
isLoading = false,
|
||||
isError = false,
|
||||
disabled = false,
|
||||
onSave,
|
||||
}) => {
|
||||
const localize = useLocalize();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const wasLoadingRef = useRef(false);
|
||||
|
|
@ -99,7 +107,11 @@ const PromptName: React.FC<Props> = ({ name, isLoading = false, isError = false,
|
|||
};
|
||||
}, []);
|
||||
|
||||
const displayButton = (
|
||||
const displayButton = disabled ? (
|
||||
<span className="text-text-primary h-8 min-w-0 flex-1 truncate pl-2 text-left text-base font-semibold">
|
||||
{newName}
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
|
|
@ -131,7 +143,7 @@ const PromptName: React.FC<Props> = ({ name, isLoading = false, isError = false,
|
|||
onKeyDown={handleKeyDown}
|
||||
onBlur={saveName}
|
||||
disabled={isLoading}
|
||||
className="text-text-primary focus:border-border-medium h-8 min-w-0 flex-1 rounded-md border-transparent pr-0 pl-2 text-base font-semibold disabled:opacity-60"
|
||||
className="text-text-primary focus:border-border-medium h-8 min-w-0 flex-1 rounded-md border-transparent pr-0 pl-2 text-base font-semibold"
|
||||
aria-label={localize('com_ui_name')}
|
||||
/>
|
||||
) : (
|
||||
|
|
@ -156,7 +168,7 @@ const PromptName: React.FC<Props> = ({ name, isLoading = false, isError = false,
|
|||
aria-label={localize('com_ui_error')}
|
||||
/>
|
||||
)}
|
||||
{saveStatus === 'idle' && !isEditing && (
|
||||
{saveStatus === 'idle' && !isEditing && !disabled && (
|
||||
<Pencil
|
||||
className="text-text-secondary size-3.5 opacity-0 transition-opacity group-hover/title:opacity-100"
|
||||
aria-hidden="true"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,66 @@
|
|||
import React from 'react';
|
||||
import '@testing-library/jest-dom/extend-expect';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import CategorySelector from '../CategorySelector';
|
||||
|
||||
jest.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
useCategories: () => ({
|
||||
categories: [{ value: 'general', label: 'General' }],
|
||||
emptyCategory: { value: '', label: 'Empty' },
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('~/Providers', () => ({
|
||||
usePromptGroupsContext: () => ({ hasAccess: true }),
|
||||
}));
|
||||
|
||||
describe('CategorySelector disabled', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('disables the trigger so it cannot be opened', () => {
|
||||
const onValueChange = jest.fn();
|
||||
|
||||
render(
|
||||
<CategorySelector portal={false} disabled onValueChange={onValueChange} currentCategory="" />,
|
||||
);
|
||||
|
||||
const trigger = screen.getByRole('button', {
|
||||
name: 'com_ui_prompt_category_selector_aria',
|
||||
});
|
||||
// A real `disabled` button rejects pointer interaction entirely (userEvent
|
||||
// throws rather than opening the menu), so the trigger truly can't be used.
|
||||
expect(trigger).toBeDisabled();
|
||||
|
||||
expect(screen.queryByRole('menuitem', { name: 'General' })).not.toBeInTheDocument();
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
expect(window.localStorage.getItem('lastPromptCategory')).toBeNull();
|
||||
});
|
||||
|
||||
it('opens the menu and writes to localStorage when not disabled', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onValueChange = jest.fn();
|
||||
|
||||
render(<CategorySelector portal={false} onValueChange={onValueChange} currentCategory="" />);
|
||||
|
||||
const trigger = screen.getByRole('button', {
|
||||
name: 'com_ui_prompt_category_selector_aria',
|
||||
});
|
||||
expect(trigger).not.toBeDisabled();
|
||||
|
||||
await user.click(trigger);
|
||||
const item = await screen.findByRole('menuitem', { name: 'General' });
|
||||
await user.click(item);
|
||||
|
||||
expect(onValueChange).toHaveBeenCalledWith('general');
|
||||
expect(window.localStorage.getItem('lastPromptCategory')).toBe('general');
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import React from 'react';
|
||||
import '@testing-library/jest-dom/extend-expect';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import PromptName from '../PromptName';
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
jest.mock('@librechat/client', () => ({
|
||||
Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
|
||||
TooltipAnchor: ({ render: content }: { render: React.ReactNode }) => content,
|
||||
}));
|
||||
|
||||
describe('PromptName disabled', () => {
|
||||
it('keeps the name read-only: clicking it does not open a textbox', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = jest.fn();
|
||||
render(<PromptName name="Example" disabled onSave={onSave} />);
|
||||
|
||||
expect(screen.getByText('Example')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/com_ui_edit/)).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('Example'));
|
||||
|
||||
expect(screen.queryByRole('textbox')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking the name opens a textbox when not disabled', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = jest.fn();
|
||||
render(<PromptName name="Example" onSave={onSave} />);
|
||||
|
||||
await user.click(screen.getByText('Example'));
|
||||
|
||||
expect(screen.getByRole('textbox')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -2,15 +2,10 @@ import React, { useEffect, useState, useMemo, useCallback, useRef } from 'react'
|
|||
import debounce from 'lodash/debounce';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Menu, Rocket, X } from 'lucide-react';
|
||||
import { Menu, Rocket, Info, X } from 'lucide-react';
|
||||
import { useForm, FormProvider } from 'react-hook-form';
|
||||
import { Button, Skeleton, useToastContext } from '@librechat/client';
|
||||
import {
|
||||
Permissions,
|
||||
ResourceType,
|
||||
PermissionBits,
|
||||
PermissionTypes,
|
||||
} from 'librechat-data-provider';
|
||||
import { Permissions, PermissionTypes } from 'librechat-data-provider';
|
||||
import type { TCreatePrompt, TPrompt, TPromptGroup } from 'librechat-data-provider';
|
||||
import {
|
||||
useGetPrompts,
|
||||
|
|
@ -19,7 +14,8 @@ import {
|
|||
useUpdatePromptGroup,
|
||||
useMakePromptProduction,
|
||||
} from '~/data-provider';
|
||||
import { useResourcePermissions, useHasAccess, useLocalize, useFocusTrap } from '~/hooks';
|
||||
import { useHasAccess, useLocalize, useFocusTrap, usePromptGroupPermissions } from '~/hooks';
|
||||
import { cn, findPromptGroup, getPromptMutationErrorKey } from '~/utils';
|
||||
import OpenSidebar from '~/components/Chat/Menus/OpenSidebar';
|
||||
import useDrawerViewport from '~/hooks/Nav/useDrawerViewport';
|
||||
import CategorySelector from '../fields/CategorySelector';
|
||||
|
|
@ -34,7 +30,6 @@ import SkeletonForm from '../utils/SkeletonForm';
|
|||
import SharePrompt from '../dialogs/SharePrompt';
|
||||
import Description from '../fields/Description';
|
||||
import PromptName from '../fields/PromptName';
|
||||
import { cn, findPromptGroup } from '~/utils';
|
||||
import { PromptsEditorMode } from '~/common';
|
||||
import Command from '../fields/Command';
|
||||
import store from '~/store';
|
||||
|
|
@ -60,7 +55,15 @@ const VersionsPanel = React.memo(
|
|||
setSelectionIndex,
|
||||
}: VersionsPanelProps) => {
|
||||
const localize = useLocalize();
|
||||
const makeProductionMutation = useMakePromptProduction();
|
||||
const { showToast } = useToastContext();
|
||||
const makeProductionMutation = useMakePromptProduction({
|
||||
onError: (error) => {
|
||||
showToast({
|
||||
status: 'error',
|
||||
message: localize(getPromptMutationErrorKey(error, 'com_ui_prompt_update_error')),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const groupId = group?._id || '';
|
||||
const isLoadingGroup = !group;
|
||||
|
|
@ -180,6 +183,64 @@ const HeaderActions = React.memo(
|
|||
|
||||
HeaderActions.displayName = 'HeaderActions';
|
||||
|
||||
interface ExternalPromptGroupViewProps {
|
||||
group: TPromptGroup;
|
||||
isSmallScreen: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only view for an externally managed (e.g. Langfuse) prompt group.
|
||||
* Name, category, description and command are shown but not editable;
|
||||
* sharing stays available, since Langfuse owns the content but not who
|
||||
* inside LibreChat may view or share it. No editor, versions panel, deploy
|
||||
* button or delete action: those stay native-only.
|
||||
*/
|
||||
const ExternalPromptGroupView = React.memo(
|
||||
({ group, isSmallScreen }: ExternalPromptGroupViewProps) => {
|
||||
const localize = useLocalize();
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col">
|
||||
{isSmallScreen && (
|
||||
<div className="flex shrink-0 items-center px-4 pt-3">
|
||||
<OpenSidebar />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 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="flex min-w-0 flex-1 items-center gap-2">
|
||||
<PromptName name={group.name} disabled onSave={() => {}} />
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<CategorySelector className="h-10" currentCategory={group.category || ''} disabled />
|
||||
<SharePrompt group={group} disabled={false} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-2 flex h-full flex-col gap-3">
|
||||
<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"
|
||||
>
|
||||
<Info className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||
<span>
|
||||
{localize('com_ui_prompt_langfuse_read_only', {
|
||||
0: group.sourcePromptName ?? '',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<Description initialValue={group.oneliner ?? ''} disabled />
|
||||
<Command initialValue={group.command ?? ''} disabled />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ExternalPromptGroupView.displayName = 'ExternalPromptGroupView';
|
||||
|
||||
const PromptForm = ({ promptId: promptIdProp }: { promptId?: string }) => {
|
||||
const params = useParams();
|
||||
const localize = useLocalize();
|
||||
|
|
@ -213,14 +274,13 @@ const PromptForm = ({ promptId: promptIdProp }: { promptId?: string }) => {
|
|||
{ enabled: hasAccess && !!promptId },
|
||||
);
|
||||
|
||||
const { hasPermission, isLoading: permissionsLoading } = useResourcePermissions(
|
||||
ResourceType.PROMPTGROUP,
|
||||
group?._id || '',
|
||||
);
|
||||
|
||||
const canEdit = hasPermission(PermissionBits.EDIT);
|
||||
const canDelete = hasPermission(PermissionBits.DELETE);
|
||||
const canView = hasPermission(PermissionBits.VIEW);
|
||||
const {
|
||||
isLoading: permissionsLoading,
|
||||
isExternal,
|
||||
canView,
|
||||
canEdit,
|
||||
canDelete,
|
||||
} = usePromptGroupPermissions(group);
|
||||
|
||||
const methods = useForm({
|
||||
defaultValues: {
|
||||
|
|
@ -240,15 +300,22 @@ const PromptForm = ({ promptId: promptIdProp }: { promptId?: string }) => {
|
|||
const selectedPromptId = useMemo(() => selectedPrompt?._id, [selectedPrompt?._id]);
|
||||
|
||||
const updateGroupMutation = useUpdatePromptGroup({
|
||||
onError: () => {
|
||||
onError: (error) => {
|
||||
showToast({
|
||||
status: 'error',
|
||||
message: localize('com_ui_prompt_update_error'),
|
||||
message: localize(getPromptMutationErrorKey(error, 'com_ui_prompt_update_error')),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const makeProductionMutation = useMakePromptProduction();
|
||||
const makeProductionMutation = useMakePromptProduction({
|
||||
onError: (error) => {
|
||||
showToast({
|
||||
status: 'error',
|
||||
message: localize(getPromptMutationErrorKey(error, 'com_ui_prompt_update_error')),
|
||||
});
|
||||
},
|
||||
});
|
||||
const addPromptToGroupMutation = useAddPromptToGroup({
|
||||
onMutate: (variables) => {
|
||||
reset(
|
||||
|
|
@ -259,6 +326,12 @@ const PromptForm = ({ promptId: promptIdProp }: { promptId?: string }) => {
|
|||
{ keepDirtyValues: true },
|
||||
);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast({
|
||||
status: 'error',
|
||||
message: localize(getPromptMutationErrorKey(error, 'com_ui_prompt_update_error')),
|
||||
});
|
||||
},
|
||||
onSuccess(data) {
|
||||
if (alwaysMakeProd && data.prompt._id != null && data.prompt._id && data.prompt.groupId) {
|
||||
makeProductionMutation.mutate({
|
||||
|
|
@ -432,6 +505,13 @@ const PromptForm = ({ promptId: promptIdProp }: { promptId?: string }) => {
|
|||
return <SkeletonForm />;
|
||||
}
|
||||
|
||||
// Externally managed groups (e.g. Langfuse) are always read-only locally,
|
||||
// regardless of ACL bits, and need their own notice instead of the
|
||||
// generic read-only view below (which hides Share and strips prompt text).
|
||||
if (isExternal && group) {
|
||||
return <ExternalPromptGroupView group={group} isSmallScreen={isSmallScreen} />;
|
||||
}
|
||||
|
||||
// Show read-only view if user doesn't have edit permission
|
||||
if (!canEdit && !permissionsLoading && groupsQuery?.data) {
|
||||
const fetchedPrompt = findPromptGroup(groupsQuery?.data, (group) => group._id === promptId);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,205 @@
|
|||
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 PromptForm from '../PromptForm';
|
||||
|
||||
const mockGroup: TPromptGroup = {
|
||||
_id: 'group-1',
|
||||
name: 'Example Group',
|
||||
author: 'user-owner',
|
||||
authorName: 'Owner',
|
||||
source: 'langfuse',
|
||||
sourcePromptName: 'my-langfuse-prompt',
|
||||
category: 'general',
|
||||
oneliner: 'A one-liner',
|
||||
command: 'example-cmd',
|
||||
} as TPromptGroup;
|
||||
|
||||
// Prefixed with `mock` because `jest.mock()` factories may only close over
|
||||
// out-of-scope variables whose names start with `mock` (enforced by
|
||||
// babel-plugin-jest-hoist).
|
||||
const mockAllBits =
|
||||
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
|
||||
|
||||
// Mutable so individual tests can exercise the ACL query's loading state.
|
||||
let mockPermissionsLoading = false;
|
||||
let mockPermissionBits = mockAllBits;
|
||||
|
||||
jest.mock('react-router-dom', () => ({
|
||||
useParams: () => ({ promptId: 'group-1' }),
|
||||
}));
|
||||
|
||||
jest.mock('recoil', () => ({
|
||||
useRecoilValue: () => undefined,
|
||||
}));
|
||||
|
||||
jest.mock('~/store', () => ({
|
||||
__esModule: true,
|
||||
default: { alwaysMakeProd: 'alwaysMakeProd-atom', promptsEditorMode: 'promptsEditorMode-atom' },
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks/Nav/useDrawerViewport', () => ({
|
||||
__esModule: true,
|
||||
default: () => false,
|
||||
}));
|
||||
|
||||
jest.mock('~/Providers', () => ({
|
||||
usePromptGroupsContext: () => ({ hasAccess: true, groupsQuery: { data: undefined } }),
|
||||
}));
|
||||
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useGetPrompts: () => ({ data: [], isLoading: false }),
|
||||
useGetPromptGroup: () => ({ data: mockGroup, isLoading: false }),
|
||||
useAddPromptToGroup: () => ({ mutate: jest.fn(), isLoading: false }),
|
||||
useUpdatePromptGroup: () => ({ mutate: jest.fn(), isLoading: false, isError: false }),
|
||||
useMakePromptProduction: () => ({ mutate: jest.fn(), isLoading: false }),
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string, values?: Record<number, string>) =>
|
||||
values ? `${key} ${JSON.stringify(values)}` : key,
|
||||
useFocusTrap: () => undefined,
|
||||
useHasAccess: () => true,
|
||||
// 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')
|
||||
.default,
|
||||
}));
|
||||
|
||||
// The real `usePromptGroupPermissions` reads ACL bits through this hook; by
|
||||
// default it is stubbed with full access so permission outcomes are driven
|
||||
// only by `group.source`. Tests that need to exercise the loading state
|
||||
// adjust `mockPermissionsLoading` / `mockPermissionBits` beforehand.
|
||||
jest.mock('~/hooks/useResourcePermissions', () => ({
|
||||
__esModule: true,
|
||||
default: () => ({
|
||||
hasPermission: (required: number) => (mockPermissionBits & required) === required,
|
||||
isLoading: mockPermissionsLoading,
|
||||
permissionBits: mockPermissionBits,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('~/components/Chat/Menus/OpenSidebar', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="open-sidebar" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../editor/PromptEditor', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="prompt-editor" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../display/PromptVariables', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="prompt-variables" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../display/PromptVersions', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="prompt-versions" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../display/PromptDetails', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="prompt-details" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../lists/NoPromptGroup', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="no-prompt-group" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../utils/SkeletonForm', () => ({
|
||||
__esModule: true,
|
||||
default: () => <div data-testid="skeleton-form" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../dialogs/DeletePrompt', () => ({
|
||||
__esModule: true,
|
||||
default: () => <button type="button" data-testid="delete-prompt" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../dialogs/SharePrompt', () => ({
|
||||
__esModule: true,
|
||||
default: () => <button type="button" data-testid="share-prompt" />,
|
||||
}));
|
||||
|
||||
jest.mock('../../fields/PromptName', () => ({
|
||||
__esModule: true,
|
||||
default: ({ name, disabled }: { name?: string; disabled?: boolean }) => (
|
||||
<span data-testid="prompt-name" data-disabled={String(Boolean(disabled))}>
|
||||
{name}
|
||||
</span>
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('../../fields/CategorySelector', () => ({
|
||||
__esModule: true,
|
||||
default: ({ disabled }: { disabled?: boolean }) => (
|
||||
<span data-testid="category-selector" data-disabled={String(Boolean(disabled))} />
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('../../fields/Description', () => ({
|
||||
__esModule: true,
|
||||
default: ({ disabled }: { disabled?: boolean }) => (
|
||||
<span data-testid="description" data-disabled={String(Boolean(disabled))} />
|
||||
),
|
||||
}));
|
||||
|
||||
jest.mock('../../fields/Command', () => ({
|
||||
__esModule: true,
|
||||
default: ({ disabled }: { disabled?: boolean }) => (
|
||||
<span data-testid="command" data-disabled={String(Boolean(disabled))} />
|
||||
),
|
||||
}));
|
||||
|
||||
describe('PromptForm external (Langfuse) read-only view', () => {
|
||||
beforeEach(() => {
|
||||
mockGroup.source = 'langfuse';
|
||||
mockPermissionsLoading = false;
|
||||
mockPermissionBits = mockAllBits;
|
||||
});
|
||||
|
||||
it('shows the Langfuse notice, keeps Share, and renders fields read-only without an editor or delete', async () => {
|
||||
render(<PromptForm promptId="group-1" />);
|
||||
|
||||
const notice = await screen.findByRole('note');
|
||||
expect(notice).toHaveTextContent('com_ui_prompt_langfuse_read_only');
|
||||
expect(notice).toHaveTextContent('my-langfuse-prompt');
|
||||
|
||||
expect(screen.getByTestId('share-prompt')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('delete-prompt')).not.toBeInTheDocument();
|
||||
|
||||
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();
|
||||
|
||||
expect(screen.getByTestId('prompt-name')).toHaveAttribute('data-disabled', 'true');
|
||||
expect(screen.getByTestId('category-selector')).toHaveAttribute('data-disabled', 'true');
|
||||
expect(screen.getByTestId('description')).toHaveAttribute('data-disabled', 'true');
|
||||
expect(screen.getByTestId('command')).toHaveAttribute('data-disabled', 'true');
|
||||
});
|
||||
|
||||
it('renders the normal editable form (no notice) for a native group', async () => {
|
||||
mockGroup.source = 'native';
|
||||
render(<PromptForm promptId="group-1" />);
|
||||
|
||||
expect(screen.queryByRole('note')).not.toBeInTheDocument();
|
||||
expect(await screen.findByTestId('prompt-name')).toHaveAttribute('data-disabled', 'false');
|
||||
});
|
||||
|
||||
it('does not disable the name or category controls for a native group while the ACL query is still loading', async () => {
|
||||
mockGroup.source = 'native';
|
||||
mockPermissionsLoading = true;
|
||||
mockPermissionBits = 0;
|
||||
|
||||
render(<PromptForm promptId="group-1" />);
|
||||
|
||||
expect(screen.queryByRole('note')).not.toBeInTheDocument();
|
||||
expect(await screen.findByTestId('prompt-name')).toHaveAttribute('data-disabled', 'false');
|
||||
expect(screen.getByTestId('category-selector')).toHaveAttribute('data-disabled', 'false');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,9 +1,7 @@
|
|||
import { useState, memo, useRef, useCallback, useId, useMemo } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { PermissionBits } from 'librechat-data-provider';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { hasPermissions } from 'librechat-data-provider/react-query';
|
||||
import { Ellipsis, Eye, SquarePen, Trash, EarthIcon, User } from 'lucide-react';
|
||||
import { Ellipsis, Eye, SquarePen, Trash, EarthIcon, Cloud, User } from 'lucide-react';
|
||||
import {
|
||||
Label,
|
||||
Button,
|
||||
|
|
@ -15,7 +13,14 @@ import {
|
|||
useToastContext,
|
||||
} from '@librechat/client';
|
||||
import type { TPromptGroup } from 'librechat-data-provider';
|
||||
import { detectVariables, cn, rowActionClasses, rowActionSlotClasses } from '~/utils';
|
||||
import {
|
||||
cn,
|
||||
detectVariables,
|
||||
getPromptMutationErrorKey,
|
||||
getPromptGroupPermissions,
|
||||
rowActionClasses,
|
||||
rowActionSlotClasses,
|
||||
} from '~/utils';
|
||||
import { useRecordPromptUsage, useDeletePromptGroup } from '~/data-provider';
|
||||
import { useLocalize, useAuthContext, useSubmitMessage } from '~/hooks';
|
||||
import VariableDialog from '../dialogs/VariableDialog';
|
||||
|
|
@ -51,9 +56,7 @@ function ChatGroupItem({
|
|||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
|
||||
const groupIsGlobal = group.isPublic === true;
|
||||
|
||||
const canEdit = hasPermissions(permissionBits, PermissionBits.EDIT);
|
||||
const canDelete = hasPermissions(permissionBits, PermissionBits.DELETE);
|
||||
const { isExternal, canEdit, canDelete } = getPromptGroupPermissions(group, permissionBits);
|
||||
|
||||
const menuButtonRef = useRef<HTMLButtonElement | null>(null);
|
||||
|
||||
|
|
@ -68,8 +71,11 @@ function ChatGroupItem({
|
|||
navigate(PROMPT_PATH, { replace: true });
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
showToast({ status: 'error', message: localize('com_ui_prompt_delete_error') });
|
||||
onError: (error) => {
|
||||
showToast({
|
||||
status: 'error',
|
||||
message: localize(getPromptMutationErrorKey(error, 'com_ui_prompt_delete_error')),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -202,6 +208,22 @@ function ChatGroupItem({
|
|||
}
|
||||
/>
|
||||
)}
|
||||
{isExternal && (
|
||||
<TooltipAnchor
|
||||
description={localize('com_ui_prompt_source_langfuse')}
|
||||
side="top"
|
||||
render={
|
||||
<span
|
||||
tabIndex={0}
|
||||
role="img"
|
||||
aria-label={localize('com_ui_prompt_source_langfuse')}
|
||||
className="flex shrink-0 items-center"
|
||||
>
|
||||
<Cloud className="text-text-secondary size-3.5" aria-hidden="true" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{/* The menu shares the title's line, so only the title gives way to it.
|
||||
The snippet below keeps the full width of the row either way. */}
|
||||
<div
|
||||
|
|
|
|||
|
|
@ -0,0 +1,95 @@
|
|||
import React from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { PermissionBits } from 'librechat-data-provider';
|
||||
import type { TPromptGroup } from 'librechat-data-provider';
|
||||
import ChatGroupItem from '../ChatGroupItem';
|
||||
|
||||
const mockMutate = jest.fn();
|
||||
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useRecordPromptUsage: () => ({ mutate: jest.fn() }),
|
||||
useDeletePromptGroup: () => ({ mutate: mockMutate, isLoading: false }),
|
||||
}));
|
||||
|
||||
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() }),
|
||||
}));
|
||||
|
||||
jest.mock('~/Providers', () => ({
|
||||
useLiveAnnouncer: () => ({ announcePolite: jest.fn() }),
|
||||
}));
|
||||
|
||||
/** Keeps the real DropdownPopup/Ariakit menu behavior; only the tooltip
|
||||
* popup (framer-motion driven) is stubbed to a plain pass-through. */
|
||||
jest.mock('@librechat/client', () => {
|
||||
const actual = jest.requireActual('@librechat/client');
|
||||
return {
|
||||
...actual,
|
||||
TooltipAnchor: ({ render: content }: { render: React.ReactNode }) => content,
|
||||
};
|
||||
});
|
||||
|
||||
function makeGroup(overrides: Partial<TPromptGroup> = {}): TPromptGroup {
|
||||
return {
|
||||
_id: 'group-1',
|
||||
name: 'Example Group',
|
||||
author: 'user-owner',
|
||||
authorName: 'Owner',
|
||||
source: 'native',
|
||||
...overrides,
|
||||
} as TPromptGroup;
|
||||
}
|
||||
|
||||
function renderGroup(group: TPromptGroup, permissionBits: number) {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<ChatGroupItem group={group} isChatRoute={false} permissionBits={permissionBits} />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
const FULL_BITS =
|
||||
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
|
||||
|
||||
describe('ChatGroupItem menu', () => {
|
||||
beforeEach(() => {
|
||||
mockMutate.mockClear();
|
||||
});
|
||||
|
||||
it('shows Edit and Delete for a native group owned by the caller', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderGroup(makeGroup(), FULL_BITS);
|
||||
await user.click(screen.getByRole('button', { name: 'com_nav_convo_menu_options' }));
|
||||
|
||||
expect(await screen.findByRole('menuitem', { name: /com_ui_edit/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole('menuitem', { name: /com_ui_delete/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides Edit and Delete for a Langfuse-managed group even with full ACL bits', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }), FULL_BITS);
|
||||
await user.click(screen.getByRole('button', { name: 'com_nav_convo_menu_options' }));
|
||||
|
||||
// Preview always stays available.
|
||||
expect(await screen.findByRole('menuitem', { name: /com_ui_preview/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('menuitem', { name: /com_ui_edit/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('menuitem', { name: /com_ui_delete/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a Langfuse badge for an externally managed group', () => {
|
||||
renderGroup(makeGroup({ source: 'langfuse', sourcePromptName: 'my-prompt' }), FULL_BITS);
|
||||
expect(screen.getByRole('img', { name: 'com_ui_prompt_source_langfuse' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show a Langfuse badge for a native group', () => {
|
||||
renderGroup(makeGroup(), FULL_BITS);
|
||||
expect(
|
||||
screen.queryByRole('img', { name: 'com_ui_prompt_source_langfuse' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import { renderHook } from '@testing-library/react';
|
||||
import { PermissionBits } from 'librechat-data-provider';
|
||||
import type { TPromptGroup } from 'librechat-data-provider';
|
||||
import usePromptGroupPermissions from '../usePromptGroupPermissions';
|
||||
|
||||
jest.mock('~/hooks/useResourcePermissions', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
|
||||
import useResourcePermissions from '~/hooks/useResourcePermissions';
|
||||
|
||||
const useResourcePermissionsMock = useResourcePermissions as unknown as jest.Mock;
|
||||
|
||||
function makeGroup(overrides: Partial<TPromptGroup> = {}): TPromptGroup {
|
||||
return {
|
||||
_id: 'group-1',
|
||||
name: 'Example Group',
|
||||
author: 'user-owner',
|
||||
authorName: 'Owner',
|
||||
source: 'native',
|
||||
...overrides,
|
||||
} as TPromptGroup;
|
||||
}
|
||||
|
||||
function mockPermissions(bits: number, isLoading = false) {
|
||||
useResourcePermissionsMock.mockReturnValue({
|
||||
hasPermission: (required: number) => (bits & required) === required,
|
||||
isLoading,
|
||||
permissionBits: bits,
|
||||
});
|
||||
}
|
||||
|
||||
const ALL_BITS =
|
||||
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
|
||||
|
||||
describe('usePromptGroupPermissions', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('grants full control for a native group with full ACL bits', () => {
|
||||
mockPermissions(ALL_BITS);
|
||||
const { result } = renderHook(() => usePromptGroupPermissions(makeGroup()));
|
||||
expect(result.current.isExternal).toBe(false);
|
||||
expect(result.current.canView).toBe(true);
|
||||
expect(result.current.canEdit).toBe(true);
|
||||
expect(result.current.canDelete).toBe(true);
|
||||
});
|
||||
|
||||
it('denies edit and delete for an external (Langfuse) group even with full ACL bits', () => {
|
||||
mockPermissions(ALL_BITS);
|
||||
const { result } = renderHook(() =>
|
||||
usePromptGroupPermissions(makeGroup({ source: 'langfuse' })),
|
||||
);
|
||||
expect(result.current.isExternal).toBe(true);
|
||||
expect(result.current.canEdit).toBe(false);
|
||||
expect(result.current.canDelete).toBe(false);
|
||||
// Viewing stays governed by ACL bits, not the external flag.
|
||||
expect(result.current.canView).toBe(true);
|
||||
});
|
||||
|
||||
it('grants view-only when the ACL only carries VIEW bits', () => {
|
||||
mockPermissions(PermissionBits.VIEW);
|
||||
const { result } = renderHook(() => usePromptGroupPermissions(makeGroup()));
|
||||
expect(result.current.canView).toBe(true);
|
||||
expect(result.current.canEdit).toBe(false);
|
||||
expect(result.current.canDelete).toBe(false);
|
||||
});
|
||||
|
||||
it('returns denied permissions while the ACL query is still loading', () => {
|
||||
mockPermissions(0, /* isLoading */ true);
|
||||
const { result } = renderHook(() => usePromptGroupPermissions(makeGroup()));
|
||||
expect(result.current.isLoading).toBe(true);
|
||||
expect(result.current.canEdit).toBe(false);
|
||||
expect(result.current.canDelete).toBe(false);
|
||||
});
|
||||
|
||||
it('handles an undefined group gracefully', () => {
|
||||
mockPermissions(0);
|
||||
const { result } = renderHook(() => usePromptGroupPermissions(undefined));
|
||||
expect(result.current.isExternal).toBe(false);
|
||||
expect(result.current.canEdit).toBe(false);
|
||||
expect(result.current.canDelete).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,2 +1,4 @@
|
|||
export { default as useCategories } from './useCategories';
|
||||
export { default as usePromptGroupsNav } from './usePromptGroupsNav';
|
||||
export { default as usePromptGroupPermissions } from './usePromptGroupPermissions';
|
||||
export type { PromptGroupPermissions } from './usePromptGroupPermissions';
|
||||
|
|
|
|||
39
client/src/hooks/Prompts/usePromptGroupPermissions.ts
Normal file
39
client/src/hooks/Prompts/usePromptGroupPermissions.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { ResourceType } from 'librechat-data-provider';
|
||||
import type { TPromptGroup } from 'librechat-data-provider';
|
||||
import useResourcePermissions from '~/hooks/useResourcePermissions';
|
||||
import { getPromptGroupPermissions } from '~/utils/promptGroups';
|
||||
|
||||
export interface PromptGroupPermissions {
|
||||
/** Permission query is still resolving */
|
||||
isLoading: boolean;
|
||||
/** Group is externally managed (e.g. Langfuse) and read-only locally */
|
||||
isExternal: boolean;
|
||||
/** Caller can view the group */
|
||||
canView: boolean;
|
||||
/** Caller can modify the group's prompts, name, category, description or command */
|
||||
canEdit: boolean;
|
||||
/** Caller can delete the group entirely */
|
||||
canDelete: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives per-prompt-group permissions from the group's ACL bits, used by
|
||||
* the prompt form and related UI. `getPromptGroupPermissions` holds the
|
||||
* rule (an external group, e.g. Langfuse, is always read-only locally
|
||||
* regardless of ACL bits); list rows call that helper directly rather than
|
||||
* going through this hook, since they already have `permissionBits` from
|
||||
* their own `useResourcePermissions` call.
|
||||
*/
|
||||
export default function usePromptGroupPermissions(
|
||||
group: TPromptGroup | undefined,
|
||||
): PromptGroupPermissions {
|
||||
const { permissionBits, isLoading } = useResourcePermissions(
|
||||
ResourceType.PROMPTGROUP,
|
||||
group?._id ?? '',
|
||||
);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
...getPromptGroupPermissions(group, permissionBits),
|
||||
};
|
||||
}
|
||||
|
|
@ -2601,9 +2601,12 @@
|
|||
"com_ui_prompt_groups": "Prompt Groups List",
|
||||
"com_ui_prompt_input": "Prompt input",
|
||||
"com_ui_prompt_input_field": "Prompt text input field",
|
||||
"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_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_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",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { QueryClient, QueryObserver } from '@tanstack/react-query';
|
||||
import { InfiniteCollections, QueryKeys } from 'librechat-data-provider';
|
||||
import { InfiniteCollections, QueryKeys, PermissionBits } from 'librechat-data-provider';
|
||||
import type { PromptGroupListResponse, TPromptGroup } from 'librechat-data-provider';
|
||||
import type { InfiniteData } from '@tanstack/react-query';
|
||||
import {
|
||||
|
|
@ -12,6 +12,8 @@ import {
|
|||
updateGroupInAll,
|
||||
updatePromptGroup,
|
||||
findPromptGroup,
|
||||
isExternalPromptGroup,
|
||||
getPromptGroupPermissions,
|
||||
} from '../promptGroups';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
@ -324,6 +326,77 @@ describe('findPromptGroup', () => {
|
|||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isExternalPromptGroup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('isExternalPromptGroup', () => {
|
||||
it('returns false for a native group', () => {
|
||||
expect(isExternalPromptGroup(makeGroup({ source: 'native' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for a Langfuse-sourced group', () => {
|
||||
expect(isExternalPromptGroup(makeGroup({ source: 'langfuse' }))).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for undefined or null', () => {
|
||||
expect(isExternalPromptGroup(undefined)).toBe(false);
|
||||
expect(isExternalPromptGroup(null)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for a group without a source (older server during a rolling deploy)', () => {
|
||||
const { source: _source, ...rest } = makeGroup({ source: 'native' });
|
||||
const groupWithoutSource = rest as { source?: TPromptGroup['source'] };
|
||||
expect(isExternalPromptGroup(groupWithoutSource)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// getPromptGroupPermissions
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('getPromptGroupPermissions', () => {
|
||||
const ALL_BITS =
|
||||
PermissionBits.VIEW | PermissionBits.EDIT | PermissionBits.DELETE | PermissionBits.SHARE;
|
||||
|
||||
it('grants full control for a native group with full ACL bits', () => {
|
||||
const result = getPromptGroupPermissions(makeGroup({ source: 'native' }), ALL_BITS);
|
||||
expect(result).toEqual({
|
||||
isExternal: false,
|
||||
canView: true,
|
||||
canEdit: true,
|
||||
canDelete: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('denies edit and delete for a Langfuse group even with full ACL bits', () => {
|
||||
const result = getPromptGroupPermissions(makeGroup({ source: 'langfuse' }), ALL_BITS);
|
||||
expect(result.isExternal).toBe(true);
|
||||
expect(result.canView).toBe(true);
|
||||
expect(result.canEdit).toBe(false);
|
||||
expect(result.canDelete).toBe(false);
|
||||
});
|
||||
|
||||
it('treats a group with no source as native (older server during a rolling deploy)', () => {
|
||||
const { source: _source, ...rest } = makeGroup({ source: 'native' });
|
||||
const groupWithoutSource = rest as { source?: TPromptGroup['source'] };
|
||||
const result = getPromptGroupPermissions(groupWithoutSource, ALL_BITS);
|
||||
expect(result.isExternal).toBe(false);
|
||||
expect(result.canEdit).toBe(true);
|
||||
expect(result.canDelete).toBe(true);
|
||||
});
|
||||
|
||||
it('denies view, edit and delete when permission bits are 0', () => {
|
||||
const result = getPromptGroupPermissions(makeGroup({ source: 'native' }), 0);
|
||||
expect(result).toEqual({
|
||||
isExternal: false,
|
||||
canView: false,
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// addGroupToAll
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
32
client/src/utils/__tests__/prompts.test.ts
Normal file
32
client/src/utils/__tests__/prompts.test.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { getPromptMutationErrorKey } from '../prompts';
|
||||
|
||||
const axiosError = (status: number, code?: string) => ({
|
||||
isAxiosError: true,
|
||||
response: { status, data: code ? { code } : {} },
|
||||
});
|
||||
|
||||
describe('getPromptMutationErrorKey', () => {
|
||||
it('maps a read_only response code to the externally-managed message', () => {
|
||||
expect(
|
||||
getPromptMutationErrorKey(axiosError(403, 'read_only'), 'com_ui_prompt_update_error'),
|
||||
).toBe('com_ui_prompt_read_only_error');
|
||||
});
|
||||
|
||||
it('falls back to the caller message when the response carries a different code', () => {
|
||||
expect(
|
||||
getPromptMutationErrorKey(axiosError(400, 'invalid_request'), 'com_ui_prompt_update_error'),
|
||||
).toBe('com_ui_prompt_update_error');
|
||||
});
|
||||
|
||||
it('falls back to the caller message when the response carries no code', () => {
|
||||
expect(getPromptMutationErrorKey(axiosError(500), 'com_ui_prompt_delete_error')).toBe(
|
||||
'com_ui_prompt_delete_error',
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to the caller message for a non-axios error', () => {
|
||||
expect(getPromptMutationErrorKey(new Error('network down'), 'com_ui_prompt_update_error')).toBe(
|
||||
'com_ui_prompt_update_error',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { InfiniteCollections, QueryKeys } from 'librechat-data-provider';
|
||||
import { hasPermissions } from 'librechat-data-provider/react-query';
|
||||
import { InfiniteCollections, QueryKeys, PermissionBits } from 'librechat-data-provider';
|
||||
import type {
|
||||
PromptGroupListResponse,
|
||||
PromptGroupListData,
|
||||
|
|
@ -78,6 +79,48 @@ export const updateGroupFieldsInPlace = (
|
|||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A group is externally managed when its `source` is present and not `native`
|
||||
* (e.g. `langfuse`). An older server predating the `source` field omits it, so
|
||||
* a missing `source` is treated as native rather than external.
|
||||
*/
|
||||
export const isExternalPromptGroup = (
|
||||
group?: { source?: TPromptGroup['source'] } | null,
|
||||
): boolean => {
|
||||
return group?.source != null && group.source !== 'native';
|
||||
};
|
||||
|
||||
export interface PromptGroupPermissionFlags {
|
||||
/** Group is externally managed (e.g. Langfuse) and read-only locally */
|
||||
isExternal: boolean;
|
||||
/** Caller can view the group */
|
||||
canView: boolean;
|
||||
/** Caller can modify the group's prompts, name, category, description or command */
|
||||
canEdit: boolean;
|
||||
/** Caller can delete the group entirely */
|
||||
canDelete: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for per-prompt-group permission checks, derived from
|
||||
* a group's source and its ACL bits. External groups (e.g. Langfuse) are
|
||||
* always read-only locally regardless of ACL bits: `canEdit` and `canDelete`
|
||||
* are forced false. Viewing is unaffected, since Langfuse owns the content
|
||||
* but not who inside LibreChat may see it.
|
||||
*/
|
||||
export const getPromptGroupPermissions = (
|
||||
group: { source?: TPromptGroup['source'] } | null | undefined,
|
||||
permissionBits: number,
|
||||
): PromptGroupPermissionFlags => {
|
||||
const isExternal = isExternalPromptGroup(group);
|
||||
return {
|
||||
isExternal,
|
||||
canView: hasPermissions(permissionBits, PermissionBits.VIEW),
|
||||
canEdit: !isExternal && hasPermissions(permissionBits, PermissionBits.EDIT),
|
||||
canDelete: !isExternal && hasPermissions(permissionBits, PermissionBits.DELETE),
|
||||
};
|
||||
};
|
||||
|
||||
export const findPromptGroup = (
|
||||
data: InfiniteData<PromptGroupListResponse>,
|
||||
findProperty: (group: TPromptGroup) => boolean,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { specialVariables } from 'librechat-data-provider';
|
||||
import type { TPromptGroup } from 'librechat-data-provider';
|
||||
import type { TranslationKeys } from '~/hooks';
|
||||
import { getResponseErrorCode } from './errors';
|
||||
|
||||
/**
|
||||
* Detects the presence of variables in the given text, excluding those found in `specialVariables`.
|
||||
|
|
@ -94,3 +96,17 @@ export const mapPromptGroups = (groups: TPromptGroup[]): Record<string, TPromptG
|
|||
{} as Record<string, TPromptGroup>,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps a failed prompt mutation to a localized toast message. The server rejects a write
|
||||
* to an externally managed (e.g. Langfuse) prompt group with `{ code: 'read_only' }`
|
||||
* (`packages/api/src/prompts/handlers.ts`); every other failure keeps the caller's
|
||||
* existing generic message.
|
||||
*/
|
||||
export const getPromptMutationErrorKey = (
|
||||
error: unknown,
|
||||
fallbackKey: TranslationKeys,
|
||||
): TranslationKeys => {
|
||||
const code = getResponseErrorCode<'read_only'>(error);
|
||||
return code === 'read_only' ? 'com_ui_prompt_read_only_error' : fallbackKey;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -931,7 +931,7 @@
|
|||
},
|
||||
"client/src/components/Prompts/fields/PromptName.tsx": {
|
||||
"shadcn/no-restyle": {
|
||||
"count": 9
|
||||
"count": 8
|
||||
}
|
||||
},
|
||||
"client/src/components/Prompts/forms/CreatePromptForm.tsx": {
|
||||
|
|
|
|||
|
|
@ -195,69 +195,47 @@ describe('createPromptHandlers linked-instructions cache clearing', () => {
|
|||
});
|
||||
|
||||
describe('deletePromptGroup', () => {
|
||||
it('reads every revision before deleting and clears an exact key for each', async () => {
|
||||
it('asks the service to collect revision ids and clears an exact key for each', async () => {
|
||||
const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);
|
||||
const callOrder: string[] = [];
|
||||
const service = makeService({
|
||||
getPrompts: jest.fn().mockImplementation(async () => {
|
||||
callOrder.push('getPrompts');
|
||||
return [{ _id: 'prompt-1' }, { _id: 'prompt-2' }];
|
||||
}),
|
||||
deletePromptGroup: jest.fn().mockImplementation(async () => {
|
||||
callOrder.push('deletePromptGroup');
|
||||
return { message: 'Prompt group deleted successfully' };
|
||||
}),
|
||||
const deletePromptGroup = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
value: {
|
||||
message: 'Prompt group deleted successfully',
|
||||
promptIds: ['prompt-1', 'prompt-2'],
|
||||
},
|
||||
});
|
||||
const service = makeService({ deletePromptGroup });
|
||||
const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);
|
||||
|
||||
expect(service.getPrompts).toHaveBeenCalledWith({ groupId });
|
||||
expect(deletePromptGroup).toHaveBeenCalledWith({
|
||||
groupId,
|
||||
loadedGroup: undefined,
|
||||
collectPromptIds: true,
|
||||
});
|
||||
expect(invalidateLinkedPrompt).toHaveBeenCalledTimes(1);
|
||||
expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, ['prompt-1', 'prompt-2']);
|
||||
// The revisions are read before the group (and its prompts) are deleted.
|
||||
expect(callOrder).toEqual(['getPrompts', 'deletePromptGroup']);
|
||||
// The wire shape is unchanged: promptIds is for cache clearing only.
|
||||
expect(res.body).toEqual({ message: 'Prompt group deleted successfully' });
|
||||
});
|
||||
|
||||
it('does not read revisions when no cache dependency is wired', async () => {
|
||||
const service = makeService({
|
||||
deletePromptGroup: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ message: 'Prompt group deleted successfully' }),
|
||||
});
|
||||
it('does not ask the service to collect revision ids when no cache dependency is wired', async () => {
|
||||
const deletePromptGroup = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: true, value: { message: 'Prompt group deleted successfully' } });
|
||||
const service = makeService({ deletePromptGroup });
|
||||
const handlers = createPromptHandlers(makeDeps({ service }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);
|
||||
|
||||
expect(service.getPrompts).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still deletes the group and clears the cache with no ids when reading revisions rejects', async () => {
|
||||
const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);
|
||||
const invalidateLinkedPrompt = jest.fn().mockResolvedValue(undefined);
|
||||
const service = makeService({
|
||||
getPrompts: jest.fn().mockRejectedValue(new Error('read failed')),
|
||||
deletePromptGroup: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ message: 'Prompt group deleted successfully' }),
|
||||
expect(deletePromptGroup).toHaveBeenCalledWith({
|
||||
groupId,
|
||||
loadedGroup: undefined,
|
||||
collectPromptIds: false,
|
||||
});
|
||||
const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);
|
||||
|
||||
expect(service.deletePromptGroup).toHaveBeenCalledWith(groupId);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(invalidateLinkedPrompt).toHaveBeenCalledWith(groupId, []);
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
'[prompts] Failed to read revisions before deleting the group',
|
||||
{
|
||||
groupId,
|
||||
type: 'Error',
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -320,6 +298,133 @@ describe('createPromptHandlers linked-instructions cache clearing', () => {
|
|||
expect.objectContaining({ loadedGroup: loadedGroupRecord }),
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards the loaded group to updatePromptGroup', async () => {
|
||||
const loadedGroupRecord = { _id: groupId, source: 'native' };
|
||||
const updatePromptGroup = jest.fn().mockResolvedValue({ ok: true, value: { _id: groupId } });
|
||||
const service = makeService({ updatePromptGroup });
|
||||
const handlers = createPromptHandlers(makeDeps({ service }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.updatePromptGroup(
|
||||
mockReq({
|
||||
params: { groupId },
|
||||
body: { name: 'Renamed' },
|
||||
resourceAccess: { resourceInfo: loadedGroupRecord },
|
||||
}),
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(updatePromptGroup).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ loadedGroup: loadedGroupRecord }),
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards the loaded group to deletePromptGroup', async () => {
|
||||
const loadedGroupRecord = { _id: groupId, source: 'native' };
|
||||
const deletePromptGroup = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: true, value: { message: 'Prompt group deleted successfully' } });
|
||||
const service = makeService({ deletePromptGroup });
|
||||
const handlers = createPromptHandlers(makeDeps({ service }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.deletePromptGroup(
|
||||
mockReq({ params: { groupId }, resourceAccess: { resourceInfo: loadedGroupRecord } }),
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(deletePromptGroup).toHaveBeenCalledWith({
|
||||
groupId,
|
||||
loadedGroup: loadedGroupRecord,
|
||||
collectPromptIds: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('read_only rejection', () => {
|
||||
it('maps read_only to 403 with the externally-managed message', async () => {
|
||||
const service = makeService({
|
||||
updatePromptGroup: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: false, error: { type: 'read_only', source: 'langfuse' } }),
|
||||
});
|
||||
const handlers = createPromptHandlers(makeDeps({ service }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.updatePromptGroup(
|
||||
mockReq({ params: { groupId }, body: { name: 'Renamed' } }),
|
||||
res,
|
||||
);
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.body).toEqual({
|
||||
code: 'read_only',
|
||||
error: 'Externally managed prompts are read-only',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not clear the cache when deletePromptGroup is rejected as read_only', async () => {
|
||||
const invalidateLinkedPrompt = jest.fn();
|
||||
const service = makeService({
|
||||
deletePromptGroup: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: false, error: { type: 'read_only', source: 'langfuse' } }),
|
||||
});
|
||||
const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.deletePromptGroup(mockReq({ params: { groupId } }), res);
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.body).toEqual({
|
||||
code: 'read_only',
|
||||
error: 'Externally managed prompts are read-only',
|
||||
});
|
||||
expect(invalidateLinkedPrompt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not clear the cache when makePromptProduction is rejected as read_only', async () => {
|
||||
const invalidateLinkedPrompt = jest.fn();
|
||||
const service = makeService({
|
||||
makePromptProduction: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: false, error: { type: 'read_only', source: 'langfuse' } }),
|
||||
});
|
||||
const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.makePromptProduction(withLoadedRevision(), res);
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.body).toEqual({
|
||||
code: 'read_only',
|
||||
error: 'Externally managed prompts are read-only',
|
||||
});
|
||||
expect(invalidateLinkedPrompt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not clear the cache when deletePrompt is rejected as read_only', async () => {
|
||||
const invalidateLinkedPrompt = jest.fn();
|
||||
const service = makeService({
|
||||
deletePrompt: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ ok: false, error: { type: 'read_only', source: 'langfuse' } }),
|
||||
});
|
||||
const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));
|
||||
const res = mockRes();
|
||||
|
||||
await handlers.deletePrompt(mockReq({ params: { promptId }, query: { groupId } }), res);
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.body).toEqual({
|
||||
code: 'read_only',
|
||||
error: 'Externally managed prompts are read-only',
|
||||
});
|
||||
expect(invalidateLinkedPrompt).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('cache clear failures', () => {
|
||||
|
|
@ -446,10 +551,10 @@ describe('createPromptHandlers linked-instructions cache clearing', () => {
|
|||
const errorSpy = jest.spyOn(logger, 'error').mockImplementation(() => logger);
|
||||
const invalidateLinkedPrompt = jest.fn().mockReturnValue(new Promise(() => {}));
|
||||
const service = makeService({
|
||||
getPrompts: jest.fn().mockResolvedValue([{ _id: 'prompt-1' }]),
|
||||
deletePromptGroup: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ message: 'Prompt group deleted successfully' }),
|
||||
deletePromptGroup: jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
value: { message: 'Prompt group deleted successfully', promptIds: ['prompt-1'] },
|
||||
}),
|
||||
});
|
||||
const handlers = createPromptHandlers(makeDeps({ service, invalidateLinkedPrompt }));
|
||||
const res = mockRes();
|
||||
|
|
|
|||
|
|
@ -107,6 +107,11 @@ function sendRejection(res: Response, error: PromptServiceError): Response {
|
|||
: { error: error.message, details: error.details },
|
||||
);
|
||||
}
|
||||
if (error.type === 'read_only') {
|
||||
return res
|
||||
.status(403)
|
||||
.send({ code: 'read_only', error: 'Externally managed prompts are read-only' });
|
||||
}
|
||||
return res.status(400).send({ error: 'Prompt operation is not available' });
|
||||
}
|
||||
|
||||
|
|
@ -387,6 +392,7 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {
|
|||
groupId: param(req, 'groupId'),
|
||||
updates: req.body,
|
||||
filters: req.config?.filters,
|
||||
loadedGroup: loadedGroup(req),
|
||||
});
|
||||
if (!result.ok) {
|
||||
return sendRejection(res, result.error);
|
||||
|
|
@ -486,7 +492,11 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {
|
|||
return res.status(400).send({ error: 'Invalid or missing groupId' });
|
||||
}
|
||||
const promptId = param(req, 'promptId');
|
||||
const result = await service.deletePrompt({ groupId, promptId });
|
||||
const result = await service.deletePrompt({
|
||||
groupId,
|
||||
promptId,
|
||||
loadedRevision: loadedRevision(req),
|
||||
});
|
||||
if (!result.ok) {
|
||||
return sendRejection(res, result.error);
|
||||
}
|
||||
|
|
@ -501,23 +511,18 @@ export function createPromptHandlers(deps: PromptHandlersDeps): PromptHandlers {
|
|||
async deletePromptGroup(req, res) {
|
||||
try {
|
||||
const groupId = param(req, 'groupId');
|
||||
/* Revisions are gone once the group is deleted, so their IDs are read first —
|
||||
* only when a cache is wired, since otherwise nothing is cleared. A read failure
|
||||
* leaves exact-revision cache entries to expire by TTL; it is logged and the
|
||||
* delete proceeds. */
|
||||
let promptIds: readonly string[] = [];
|
||||
if (deps.invalidateLinkedPrompt) {
|
||||
try {
|
||||
promptIds = (await service.getPrompts({ groupId })).map((revision) => revision._id);
|
||||
} catch (error) {
|
||||
logger.error('[prompts] Failed to read revisions before deleting the group', {
|
||||
groupId,
|
||||
...getSafeErrorMetadata(error),
|
||||
});
|
||||
}
|
||||
const result = await service.deletePromptGroup({
|
||||
groupId,
|
||||
loadedGroup: loadedGroup(req),
|
||||
// Only the service needs to read revision IDs before the group (and its
|
||||
// revisions) are gone; it is pointless when no cache is wired to clear.
|
||||
collectPromptIds: Boolean(deps.invalidateLinkedPrompt),
|
||||
});
|
||||
if (!result.ok) {
|
||||
return sendRejection(res, result.error);
|
||||
}
|
||||
const value = await service.deletePromptGroup(groupId);
|
||||
await clearLinkedPromptCache(deps, req, groupId, promptIds);
|
||||
const { promptIds, ...value } = result.value;
|
||||
await clearLinkedPromptCache(deps, req, groupId, promptIds ?? []);
|
||||
return res.send(value);
|
||||
} catch (error) {
|
||||
logger.error('Error deleting prompt group', error);
|
||||
|
|
|
|||
|
|
@ -676,10 +676,63 @@ describe('createPromptService', () => {
|
|||
await expect(service.incrementPromptGroupUsage(group._id)).resolves.toEqual({
|
||||
numberOfGenerations: 1,
|
||||
});
|
||||
await expect(service.deletePromptGroup(group._id)).resolves.toEqual({
|
||||
message: 'Prompt group deleted successfully',
|
||||
await expect(service.deletePromptGroup({ groupId: group._id })).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { message: 'Prompt group deleted successfully' },
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes a native revision', async () => {
|
||||
const draft = await addRevision('Draft');
|
||||
|
||||
await expect(
|
||||
service.deletePrompt({ groupId: group._id, promptId: draft._id }),
|
||||
).resolves.toEqual({ ok: true, value: { prompt: 'Prompt deleted successfully' } });
|
||||
await expect(db.getPrompt({ _id: draft._id })).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('collects revision ids after the guard when requested', async () => {
|
||||
const draft = await addRevision('Draft');
|
||||
|
||||
const result = await service.deletePromptGroup({
|
||||
groupId: group._id,
|
||||
collectPromptIds: true,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.ok && result.value).toMatchObject({
|
||||
message: 'Prompt group deleted successfully',
|
||||
promptIds: expect.arrayContaining([production._id, draft._id]),
|
||||
});
|
||||
await expect(db.getPromptGroup({ _id: group._id })).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('does not collect revision ids when not requested', async () => {
|
||||
await expect(service.deletePromptGroup({ groupId: group._id })).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { message: 'Prompt group deleted successfully' },
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes the group with no revision ids and logs when reading revisions fails', async () => {
|
||||
const logError = jest.spyOn(logger, 'error').mockImplementation(() => logger);
|
||||
jest.spyOn(db, 'getPrompts').mockRejectedValueOnce(new Error('database unavailable'));
|
||||
|
||||
const result = await service.deletePromptGroup({
|
||||
groupId: group._id,
|
||||
collectPromptIds: true,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: { message: 'Prompt group deleted successfully', promptIds: [] },
|
||||
});
|
||||
await expect(db.getPromptGroup({ _id: group._id })).resolves.toBeNull();
|
||||
expect(logError).toHaveBeenCalledWith(
|
||||
expect.stringContaining('[deletePromptGroup] Failed to read revisions'),
|
||||
{ groupId: group._id, type: 'Error' },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a source without mutations', () => {
|
||||
|
|
@ -738,6 +791,32 @@ describe('createPromptService', () => {
|
|||
};
|
||||
}
|
||||
|
||||
/** A real stored group and revision, unlike `makeLangfuseGroup`'s in-memory record:
|
||||
* this is what `readGroup` falls back to reading from the database when no
|
||||
* `loadedGroup` matches, which includes the `MANAGE_PROMPTS` bypass path where
|
||||
* `req.resourceAccess` is unset. */
|
||||
async function createPersistedLangfuseGroupWithPrompt() {
|
||||
const persistedGroup = await mongoose.models.PromptGroup.create({
|
||||
name: 'Persisted Langfuse group',
|
||||
author,
|
||||
authorName: 'Author',
|
||||
source: 'langfuse',
|
||||
sourcePromptName: 'langfuse-prompt',
|
||||
sourceProjectId: 'project-1',
|
||||
sourceDestination: 'destination-1',
|
||||
});
|
||||
const promptDoc = await mongoose.models.Prompt.create({
|
||||
groupId: persistedGroup._id,
|
||||
author,
|
||||
prompt: 'Synced from Langfuse',
|
||||
type: 'text',
|
||||
});
|
||||
return {
|
||||
groupId: persistedGroup._id.toString(),
|
||||
promptId: promptDoc._id.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
it('dispatches a Langfuse group to the Langfuse adapter', async () => {
|
||||
const langfuseGroup = makeLangfuseGroup();
|
||||
const resolved = makeLangfuseResolved({ groupId: langfuseGroup._id });
|
||||
|
|
@ -814,8 +893,9 @@ describe('createPromptService', () => {
|
|||
).resolves.toMatchObject({ ok: false, error: { type: 'blocked_content' } });
|
||||
});
|
||||
|
||||
it('returns unsupported for savePrompt on a Langfuse group', async () => {
|
||||
it('returns read_only for savePrompt on a Langfuse group', async () => {
|
||||
const langfuseGroup = makeLangfuseGroup();
|
||||
const save = jest.spyOn(db, 'savePrompt');
|
||||
|
||||
await expect(
|
||||
service.savePrompt({
|
||||
|
|
@ -824,7 +904,124 @@ describe('createPromptService', () => {
|
|||
author,
|
||||
loadedGroup: langfuseGroup,
|
||||
}),
|
||||
).resolves.toEqual({ ok: false, error: { type: 'unsupported', operation: 'savePrompt' } });
|
||||
).resolves.toEqual({ ok: false, error: { type: 'read_only', source: 'langfuse' } });
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns read_only, not invalid_input, for an invalid payload on a Langfuse group', async () => {
|
||||
const langfuseGroup = makeLangfuseGroup();
|
||||
const save = jest.spyOn(db, 'savePrompt');
|
||||
|
||||
await expect(
|
||||
service.savePrompt({
|
||||
groupId: langfuseGroup._id,
|
||||
prompt: { prompt: ' ', type: 'text' },
|
||||
author,
|
||||
loadedGroup: langfuseGroup,
|
||||
}),
|
||||
).resolves.toEqual({ ok: false, error: { type: 'read_only', source: 'langfuse' } });
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns read_only for updatePromptGroup on a Langfuse group', async () => {
|
||||
const langfuseGroup = makeLangfuseGroup();
|
||||
const update = jest.spyOn(db, 'updatePromptGroup');
|
||||
|
||||
await expect(
|
||||
service.updatePromptGroup({
|
||||
groupId: langfuseGroup._id,
|
||||
updates: { name: 'Renamed' },
|
||||
loadedGroup: langfuseGroup,
|
||||
}),
|
||||
).resolves.toEqual({ ok: false, error: { type: 'read_only', source: 'langfuse' } });
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns read_only for deletePromptGroup on a Langfuse group', async () => {
|
||||
const langfuseGroup = makeLangfuseGroup();
|
||||
const deleteGroup = jest.spyOn(db, 'deletePromptGroup');
|
||||
|
||||
await expect(
|
||||
service.deletePromptGroup({ groupId: langfuseGroup._id, loadedGroup: langfuseGroup }),
|
||||
).resolves.toEqual({ ok: false, error: { type: 'read_only', source: 'langfuse' } });
|
||||
expect(deleteGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no loaded group (the MANAGE_PROMPTS bypass path)', undefined],
|
||||
['a loaded group whose _id differs', { ...group, _id: missingId() }],
|
||||
])(
|
||||
'returns read_only for updatePromptGroup on a persisted Langfuse group with %s',
|
||||
async (_case, mismatchedLoadedGroup) => {
|
||||
const { groupId: langfuseGroupId } = await createPersistedLangfuseGroupWithPrompt();
|
||||
const update = jest.spyOn(db, 'updatePromptGroup');
|
||||
|
||||
await expect(
|
||||
service.updatePromptGroup({
|
||||
groupId: langfuseGroupId,
|
||||
updates: { name: 'Renamed' },
|
||||
loadedGroup: mismatchedLoadedGroup,
|
||||
}),
|
||||
).resolves.toEqual({ ok: false, error: { type: 'read_only', source: 'langfuse' } });
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
await expect(db.getPromptGroup({ _id: langfuseGroupId })).resolves.toMatchObject({
|
||||
name: 'Persisted Langfuse group',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['no loaded group (the MANAGE_PROMPTS bypass path)', undefined],
|
||||
['a loaded group whose _id differs', { ...group, _id: missingId() }],
|
||||
])(
|
||||
'returns read_only for deletePromptGroup on a persisted Langfuse group with %s',
|
||||
async (_case, mismatchedLoadedGroup) => {
|
||||
const { groupId: langfuseGroupId, promptId } =
|
||||
await createPersistedLangfuseGroupWithPrompt();
|
||||
const deleteGroup = jest.spyOn(db, 'deletePromptGroup');
|
||||
|
||||
await expect(
|
||||
service.deletePromptGroup({
|
||||
groupId: langfuseGroupId,
|
||||
loadedGroup: mismatchedLoadedGroup,
|
||||
}),
|
||||
).resolves.toEqual({ ok: false, error: { type: 'read_only', source: 'langfuse' } });
|
||||
expect(deleteGroup).not.toHaveBeenCalled();
|
||||
await expect(db.getPromptGroup({ _id: langfuseGroupId })).resolves.toMatchObject({
|
||||
name: 'Persisted Langfuse group',
|
||||
});
|
||||
await expect(db.getPrompt({ _id: promptId })).resolves.not.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
describe('mutations keyed by revision on a Langfuse group', () => {
|
||||
it('returns read_only for makePromptProduction on a revision of a Langfuse group', async () => {
|
||||
const { groupId: langfuseGroupId, promptId } =
|
||||
await createPersistedLangfuseGroupWithPrompt();
|
||||
const promote = jest.spyOn(db, 'makePromptProduction');
|
||||
|
||||
await expect(service.makePromptProduction({ promptId })).resolves.toEqual({
|
||||
ok: false,
|
||||
error: { type: 'read_only', source: 'langfuse' },
|
||||
});
|
||||
expect(promote).not.toHaveBeenCalled();
|
||||
const storedGroup = (await db.getPromptGroup({ _id: langfuseGroupId })) as {
|
||||
productionId?: unknown;
|
||||
} | null;
|
||||
expect(storedGroup?.productionId).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns read_only for deletePrompt on a revision of a Langfuse group', async () => {
|
||||
const { groupId: langfuseGroupId, promptId } =
|
||||
await createPersistedLangfuseGroupWithPrompt();
|
||||
const deletePromptSpy = jest.spyOn(db, 'deletePrompt');
|
||||
|
||||
await expect(service.deletePrompt({ groupId: langfuseGroupId, promptId })).resolves.toEqual(
|
||||
{ ok: false, error: { type: 'read_only', source: 'langfuse' } },
|
||||
);
|
||||
expect(deletePromptSpy).not.toHaveBeenCalled();
|
||||
await expect(db.getPrompt({ _id: promptId })).resolves.not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('returns unsupported_selection for a version selection on a native group', async () => {
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ import {
|
|||
import { safeValidatePromptGroupUpdate, safeValidatePromptPayload } from './schemas';
|
||||
import { createLangfuseSourceResolver } from '../langfuse/promptSync';
|
||||
import { createLangfusePromptAdapter } from './langfuse';
|
||||
import { getSafeErrorMetadata } from '~/utils';
|
||||
import { withPromptStage } from './errors';
|
||||
|
||||
type WithPromptFilters<T> = T & { readonly filters?: FiltersConfig };
|
||||
|
|
@ -91,7 +92,11 @@ export interface PromptService {
|
|||
): Promise<PromptServiceResult<PromptRecord> | null>;
|
||||
incrementPromptGroupUsage(groupId: string): Promise<{ readonly numberOfGenerations: number }>;
|
||||
updatePromptGroup(
|
||||
input: WithPromptFilters<{ readonly groupId: string; readonly updates: unknown }>,
|
||||
input: WithPromptFilters<{
|
||||
readonly groupId: string;
|
||||
readonly updates: unknown;
|
||||
readonly loadedGroup?: PromptGroupRecord | null;
|
||||
}>,
|
||||
): Promise<PromptServiceResult<PromptGroupRecord>>;
|
||||
makePromptProduction(
|
||||
input: WithPromptFilters<{
|
||||
|
|
@ -102,21 +107,38 @@ export interface PromptService {
|
|||
deletePrompt(input: {
|
||||
readonly groupId: string;
|
||||
readonly promptId: string;
|
||||
readonly loadedRevision?: PromptRecord | null;
|
||||
}): Promise<PromptServiceResult<TDeletePromptResponse>>;
|
||||
deletePromptGroup(groupId: string): Promise<{ readonly message: string }>;
|
||||
deletePromptGroup(input: {
|
||||
readonly groupId: string;
|
||||
readonly loadedGroup?: PromptGroupRecord | null;
|
||||
/** Reads the group's revision IDs after the read-only guard, for a caller that
|
||||
* clears a per-revision cache once the group (and its revisions) are gone. */
|
||||
readonly collectPromptIds?: boolean;
|
||||
}): Promise<
|
||||
PromptServiceResult<{ readonly message: string; readonly promptIds?: readonly string[] }>
|
||||
>;
|
||||
}
|
||||
|
||||
function invalidInput<T>(message: string, details?: unknown): PromptServiceResult<T> {
|
||||
return { ok: false, error: { type: 'invalid_input', message, details } };
|
||||
}
|
||||
|
||||
function unsupported(operation: PromptOperation): {
|
||||
readonly ok: false;
|
||||
readonly error: PromptServiceError;
|
||||
} {
|
||||
function unsupported(operation: PromptOperation): PromptServiceResult<never> {
|
||||
return { ok: false, error: { type: 'unsupported', operation } };
|
||||
}
|
||||
|
||||
function readOnly(source: PromptGroupRecord['source']): PromptServiceResult<never> {
|
||||
return { ok: false, error: { type: 'read_only', source } };
|
||||
}
|
||||
|
||||
/** A group not sourced from the native adapter is managed externally and rejects
|
||||
* every mutation. A missing group is left to the write or read it guards; only a
|
||||
* group that is known and external triggers the rejection. */
|
||||
function isExternal(group: PromptGroupRecord): boolean {
|
||||
return group.source !== 'native';
|
||||
}
|
||||
|
||||
function inspect(
|
||||
input: Parameters<typeof inspectPromptContent>[0],
|
||||
filters: FiltersConfig | undefined,
|
||||
|
|
@ -253,16 +275,14 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)
|
|||
if (!prompt) {
|
||||
return invalidInput('Prompt is required');
|
||||
}
|
||||
const group = await readGroup(groupId, loadedGroup);
|
||||
if (group != null && isExternal(group)) {
|
||||
return readOnly(group.source);
|
||||
}
|
||||
const validation = safeValidatePromptPayload(prompt);
|
||||
if (!validation.success) {
|
||||
return invalidInput(validation.error.issues[0]?.message ?? 'Invalid prompt');
|
||||
}
|
||||
// A missing group is left to the write below; only a group that is known and not
|
||||
// native blocks a native revision from being added to it.
|
||||
const group = await readGroup(groupId, loadedGroup);
|
||||
if (group != null && group.source !== 'native') {
|
||||
return unsupported('savePrompt');
|
||||
}
|
||||
const rejection = inspect({ prompt: validation.data }, filters);
|
||||
if (rejection != null) {
|
||||
return rejection;
|
||||
|
|
@ -297,7 +317,11 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)
|
|||
|
||||
incrementPromptGroupUsage: (groupId) => catalog.incrementPromptGroupUsage(groupId),
|
||||
|
||||
async updatePromptGroup({ groupId, updates, filters }) {
|
||||
async updatePromptGroup({ groupId, updates, filters, loadedGroup }) {
|
||||
const group = await readGroup(groupId, loadedGroup);
|
||||
if (group != null && isExternal(group)) {
|
||||
return readOnly(group.source);
|
||||
}
|
||||
const validation = safeValidatePromptGroupUpdate(updates);
|
||||
if (!validation.success) {
|
||||
return invalidInput('Invalid request body', validation.error.errors);
|
||||
|
|
@ -317,6 +341,12 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)
|
|||
return unsupported('makePromptProduction');
|
||||
}
|
||||
const revision = await readPrompt(promptId, loadedRevision);
|
||||
if (revision != null) {
|
||||
const group = await readGroup(revision.groupId);
|
||||
if (group != null && isExternal(group)) {
|
||||
return readOnly(group.source);
|
||||
}
|
||||
}
|
||||
const rejection = inspect({ prompt: revision ?? undefined }, filters);
|
||||
if (rejection != null) {
|
||||
return rejection;
|
||||
|
|
@ -330,10 +360,41 @@ export function createPromptServiceFromAdapters(adapters: PromptServiceAdapters)
|
|||
if (!native.deletePrompt) {
|
||||
return unsupported('deletePrompt');
|
||||
}
|
||||
const revision = await readPrompt(input.promptId, input.loadedRevision);
|
||||
if (revision != null) {
|
||||
const group = await readGroup(revision.groupId);
|
||||
if (group != null && isExternal(group)) {
|
||||
return readOnly(group.source);
|
||||
}
|
||||
}
|
||||
return { ok: true, value: await native.deletePrompt(input) };
|
||||
},
|
||||
|
||||
deletePromptGroup: (groupId) => catalog.deletePromptGroup(groupId),
|
||||
async deletePromptGroup({ groupId, loadedGroup, collectPromptIds }) {
|
||||
const group = await readGroup(groupId, loadedGroup);
|
||||
if (group != null && isExternal(group)) {
|
||||
return readOnly(group.source);
|
||||
}
|
||||
// Revisions are gone once the group is deleted, so their IDs are read here, after
|
||||
// the guard, while they still exist. A read failure is logged and left empty
|
||||
// rather than blocking the delete; exact-revision cache entries then expire by TTL.
|
||||
let promptIds: readonly string[] | undefined;
|
||||
if (collectPromptIds) {
|
||||
try {
|
||||
promptIds = (await withPromptStage('read', () => native.getPrompts(groupId))).map(
|
||||
(revision) => revision._id,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('[deletePromptGroup] Failed to read revisions for group', {
|
||||
groupId,
|
||||
...getSafeErrorMetadata(error),
|
||||
});
|
||||
promptIds = [];
|
||||
}
|
||||
}
|
||||
const value = await catalog.deletePromptGroup(groupId);
|
||||
return { ok: true, value: promptIds == null ? value : { ...value, promptIds } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -129,6 +129,10 @@ export type PromptServiceError =
|
|||
readonly reason: 'production' | 'revision';
|
||||
}
|
||||
| { readonly type: 'unsupported'; readonly operation: PromptOperation }
|
||||
/** The group is not `native`: an externally managed group rejects every mutation,
|
||||
* including `savePrompt`, `updatePromptGroup`, `deletePromptGroup`,
|
||||
* `makePromptProduction` and `deletePrompt`. */
|
||||
| { readonly type: 'read_only'; readonly source: PromptGroupSource }
|
||||
/** The selection is not valid for `source` (for example `version` on a native group,
|
||||
* or `exact` on a Langfuse group). */
|
||||
| { readonly type: 'unsupported_selection'; readonly source: PromptGroupSource }
|
||||
|
|
@ -181,9 +185,10 @@ export interface PromptSourceAdapter {
|
|||
|
||||
/**
|
||||
* The native adapter additionally performs every operation that is keyed by revision ID
|
||||
* rather than by group — those stay native-only by construction, since a Langfuse group
|
||||
* has no local `Prompt` rows. Mutations are optional: a source that cannot perform one
|
||||
* leaves it out, and the service returns an `unsupported` result.
|
||||
* rather than by group. Mutations are optional: a source that cannot perform one leaves
|
||||
* it out, and the service returns an `unsupported` result. The service also guards
|
||||
* `savePrompt`, `makePromptProduction` and `deletePrompt` against an external group,
|
||||
* returning `read_only` before any of these are called.
|
||||
*/
|
||||
export interface NativePromptAdapter extends PromptSourceAdapter {
|
||||
getPrompt(promptId: string): Promise<PromptRecord | null>;
|
||||
|
|
@ -198,7 +203,11 @@ export interface NativePromptAdapter extends PromptSourceAdapter {
|
|||
}): Promise<TDeletePromptResponse>;
|
||||
}
|
||||
|
||||
/** Local catalog operations that do not depend on the content source. */
|
||||
/**
|
||||
* Local catalog operations that do not depend on the content source. The service guards
|
||||
* `updatePromptGroup` and `deletePromptGroup` against an external group, returning
|
||||
* `read_only` before either reaches here.
|
||||
*/
|
||||
export interface PromptCatalogStore {
|
||||
getPromptGroup(groupId: string): Promise<PromptGroupRecord | null>;
|
||||
getListPromptGroupsByAccess(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue