🔧 refactor: Organize Sharing/Agent Components and Improve Type Safety

refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids, rename enums to PascalCase

refactor: organize Sharing/Agent components, improve type safety for resource types and access role ids

chore: move sharing related components to dedicated "Sharing" directory

chore: remove PublicSharingToggle component and update index exports

chore: move non-sidepanel agent components to `~/components/Agents`

chore: move AgentCategoryDisplay component with tests

chore: remove commented out code

refactor: change PERMISSION_BITS from const to enum for better type safety

refactor: reorganize imports in GenericGrantAccessDialog and update index exports for hooks

refactor: update type definitions to use ACCESS_ROLE_IDS for improved type safety

refactor: remove unused canAccessPromptResource middleware and related code

refactor: remove unused prompt access roles from createAccessRoleMethods

refactor: update resourceType in AclEntry type definition to remove unused 'prompt' value

refactor: introduce ResourceType enum and update resourceType usage across data provider files for improved type safety

refactor: update resourceType usage to ResourceType enum across sharing and permissions components for improved type safety

refactor: standardize resourceType usage to ResourceType enum across agent and prompt models, permissions controller, and middleware for enhanced type safety

refactor: update resourceType references from PROMPT_GROUP to PROMPTGROUP for consistency across models, middleware, and components

refactor: standardize access role IDs and resource type usage across agent, file, and prompt models for improved type safety and consistency

chore: add typedefs for TUpdateResourcePermissionsRequest and TUpdateResourcePermissionsResponse to enhance type definitions

chore: move SearchPicker to PeoplePicker dir

refactor: implement debouncing for query changes in SearchPicker for improved performance

chore: fix typing, import order for agent admin settings

fix: agent admin settings, prevent agent form submission

refactor: rename `ACCESS_ROLE_IDS` to `AccessRoleIds`

refactor: replace PermissionBits with PERMISSION_BITS

refactor: replace PERMISSION_BITS with PermissionBits
This commit is contained in:
Danny Avila 2025-07-28 17:52:36 -04:00
parent ae732b2ebc
commit 81b32e400a
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956
96 changed files with 781 additions and 798 deletions

View file

@ -0,0 +1,103 @@
import React, { useState, useMemo } from 'react';
import type { TPrincipal, PrincipalSearchParams } from 'librechat-data-provider';
import { useSearchPrincipalsQuery } from 'librechat-data-provider/react-query';
import PeoplePickerSearchItem from './PeoplePickerSearchItem';
import SelectedPrincipalsList from './SelectedPrincipalsList';
import { SearchPicker } from './SearchPicker';
import { useLocalize } from '~/hooks';
interface PeoplePickerProps {
onSelectionChange: (principals: TPrincipal[]) => void;
placeholder?: string;
className?: string;
typeFilter?: 'user' | 'group' | null;
}
export default function PeoplePicker({
onSelectionChange,
placeholder,
className = '',
typeFilter = null,
}: PeoplePickerProps) {
const localize = useLocalize();
const [searchQuery, setSearchQuery] = useState('');
const [selectedShares, setSelectedShares] = useState<TPrincipal[]>([]);
const searchParams: PrincipalSearchParams = useMemo(
() => ({
q: searchQuery,
limit: 30,
...(typeFilter && { type: typeFilter }),
}),
[searchQuery, typeFilter],
);
const {
data: searchResponse,
isLoading: queryIsLoading,
error,
} = useSearchPrincipalsQuery(searchParams, {
enabled: searchQuery.length >= 2,
});
const isLoading = searchQuery.length >= 2 && queryIsLoading;
const selectableResults = useMemo(() => {
const results = searchResponse?.results || [];
return results.filter(
(result) => !selectedShares.some((share) => share.idOnTheSource === result.idOnTheSource),
);
}, [searchResponse?.results, selectedShares]);
if (error) {
console.error('Principal search error:', error);
}
return (
<div className={`space-y-3 ${className}`}>
<div className="relative">
<SearchPicker<TPrincipal & { key: string; value: string }>
options={selectableResults.map((s) => {
const key = s.idOnTheSource || 'unknown' + 'picker_key';
const value = s.idOnTheSource || 'Unknown';
return {
...s,
id: s.id ?? undefined,
key,
value,
};
})}
renderOptions={(o) => <PeoplePickerSearchItem principal={o} />}
placeholder={placeholder || localize('com_ui_search_default_placeholder')}
query={searchQuery}
onQueryChange={(query: string) => {
setSearchQuery(query);
}}
onPick={(principal) => {
console.log('Selected Principal:', principal);
setSelectedShares((prev) => {
const newArray = [...prev, principal];
onSelectionChange([...newArray]);
return newArray;
});
setSearchQuery('');
}}
label={localize('com_ui_search_users_groups')}
isLoading={isLoading}
/>
</div>
<SelectedPrincipalsList
principles={selectedShares}
onRemoveHandler={(idOnTheSource: string) => {
setSelectedShares((prev) => {
const newArray = prev.filter((share) => share.idOnTheSource !== idOnTheSource);
onSelectionChange(newArray);
return newArray;
});
}}
/>
</div>
);
}

View file

@ -0,0 +1,57 @@
import React, { forwardRef } from 'react';
import type { TPrincipal } from 'librechat-data-provider';
import { cn } from '~/utils';
import { useLocalize } from '~/hooks';
import PrincipalAvatar from '../PrincipalAvatar';
interface PeoplePickerSearchItemProps extends React.HTMLAttributes<HTMLDivElement> {
principal: TPrincipal;
}
const PeoplePickerSearchItem = forwardRef<HTMLDivElement, PeoplePickerSearchItemProps>(
function PeoplePickerSearchItem(
{ principal, className, style, onClick, ...props },
forwardedRef,
) {
const localize = useLocalize();
const { name, email, type } = principal;
// Display name with fallback
const displayName = name || localize('com_ui_unknown');
const subtitle = email || `${type} (${principal.source || 'local'})`;
return (
<div
{...props}
ref={forwardedRef}
className={cn('flex items-center gap-3 p-2', className)}
style={style}
onClick={(event) => {
onClick?.(event);
}}
>
<PrincipalAvatar principal={principal} size="md" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-text-primary">{displayName}</div>
<div className="truncate text-xs text-text-secondary">{subtitle}</div>
</div>
<div className="flex-shrink-0">
<span
className={cn(
'inline-flex items-center rounded-full px-2 py-1 text-xs font-medium',
type === 'user'
? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300'
: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',
)}
>
{type === 'user' ? localize('com_ui_user') : localize('com_ui_group')}
</span>
</div>
</div>
);
},
);
export default PeoplePickerSearchItem;

View file

@ -0,0 +1,217 @@
import * as React from 'react';
import debounce from 'lodash/debounce';
import { Search, X } from 'lucide-react';
import * as Ariakit from '@ariakit/react';
import { Spinner, Skeleton } from '@librechat/client';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
type SearchPickerProps<TOption extends { key: string }> = {
options: TOption[];
renderOptions: (option: TOption) => React.ReactElement;
query: string;
onQueryChange: (query: string) => void;
onPick: (pickedOption: TOption) => void;
placeholder?: string;
inputClassName?: string;
label: string;
resetValueOnHide?: boolean;
isSmallScreen?: boolean;
isLoading?: boolean;
minQueryLengthForNoResults?: number;
};
export function SearchPicker<TOption extends { key: string; value: string }>({
options,
renderOptions,
onPick,
onQueryChange,
query,
label,
isSmallScreen = false,
placeholder,
resetValueOnHide = false,
isLoading = false,
minQueryLengthForNoResults = 2,
}: SearchPickerProps<TOption>) {
const localize = useLocalize();
const [_open, setOpen] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement>(null);
const [localQuery, setLocalQuery] = React.useState(query);
const combobox = Ariakit.useComboboxStore({
resetValueOnHide,
});
React.useEffect(() => {
setLocalQuery(query);
}, [query]);
const debouncedOnQueryChange = React.useMemo(
() =>
debounce((value: string) => {
onQueryChange(value);
}, 500),
[onQueryChange],
);
React.useEffect(() => {
return () => {
debouncedOnQueryChange.cancel();
};
}, [debouncedOnQueryChange]);
const onPickHandler = (option: TOption) => {
setLocalQuery('');
onQueryChange('');
onPick(option);
setOpen(false);
if (inputRef.current) {
inputRef.current.focus();
}
};
const showClearIcon = localQuery.trim().length > 0;
const clearText = () => {
setLocalQuery('');
onQueryChange('');
debouncedOnQueryChange.cancel();
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<Ariakit.ComboboxProvider store={combobox}>
<Ariakit.ComboboxLabel className="text-token-text-primary mb-2 block font-medium">
{label}
</Ariakit.ComboboxLabel>
<div className="py-1.5">
<div
className={cn(
'group relative mt-1 flex h-10 cursor-pointer items-center gap-3 rounded-lg border-border-medium px-3 py-2 text-text-primary transition-colors duration-200 focus-within:bg-surface-hover hover:bg-surface-hover',
isSmallScreen === true ? 'mb-2 h-14 rounded-2xl' : '',
)}
>
{isLoading ? (
<Spinner className="absolute left-3 h-4 w-4 text-text-primary" />
) : (
<Search className="absolute left-3 h-4 w-4 text-text-secondary group-focus-within:text-text-primary group-hover:text-text-primary" />
)}
<Ariakit.Combobox
ref={inputRef}
onKeyDown={(e) => {
if (e.key === 'Escape' && combobox.getState().open) {
e.preventDefault();
e.stopPropagation();
setLocalQuery('');
onQueryChange('');
debouncedOnQueryChange.cancel();
setOpen(false);
}
}}
store={combobox}
setValueOnClick={false}
setValueOnChange={false}
onChange={(e) => {
const value = e.target.value;
setLocalQuery(value);
debouncedOnQueryChange(value);
}}
value={localQuery}
// autoSelect
placeholder={placeholder || localize('com_ui_select_options')}
className="m-0 mr-0 w-full rounded-md border-none bg-transparent p-0 py-2 pl-9 pr-3 text-sm leading-tight text-text-primary placeholder-text-secondary placeholder-opacity-100 focus:outline-none focus-visible:outline-none group-focus-within:placeholder-text-primary group-hover:placeholder-text-primary"
/>
<button
type="button"
aria-label={`${localize('com_ui_clear')} ${localize('com_ui_search')}`}
className={cn(
'absolute right-[7px] flex h-5 w-5 items-center justify-center rounded-full border-none bg-transparent p-0 transition-opacity duration-200',
showClearIcon ? 'opacity-100' : 'opacity-0',
isSmallScreen === true ? 'right-[16px]' : '',
)}
onClick={clearText}
tabIndex={showClearIcon ? 0 : -1}
disabled={!showClearIcon}
>
<X className="h-5 w-5 cursor-pointer" />
</button>
</div>
</div>
<Ariakit.ComboboxPopover
portal={false} //todo fix focus when set to true
gutter={10}
// sameWidth
open={
isLoading ||
options.length > 0 ||
(localQuery.trim().length >= minQueryLengthForNoResults && !isLoading)
}
store={combobox}
unmountOnHide
autoFocusOnShow={false}
modal={false}
className={cn(
'animate-popover z-[9999] min-w-64 overflow-hidden rounded-xl border border-border-light bg-surface-secondary shadow-lg',
'[pointer-events:auto]', // Override body's pointer-events:none when in modal
)}
>
{(() => {
if (isLoading) {
return (
<div className="space-y-2 p-2">
{Array.from({ length: 3 }).map((_, index) => (
<div key={index} className="flex items-center gap-3 px-3 py-2">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="flex-1 space-y-1">
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-3 w-1/2" />
</div>
</div>
))}
</div>
);
}
if (options.length > 0) {
return options.map((o) => (
<Ariakit.ComboboxItem
key={o.key}
focusOnHover
// hideOnClick
value={o.value}
selectValueOnClick={false}
onClick={() => onPickHandler(o)}
className={cn(
'flex w-full cursor-pointer items-center px-3 text-sm',
'text-text-primary hover:bg-surface-tertiary',
'data-[active-item]:bg-surface-tertiary',
)}
render={renderOptions(o)}
></Ariakit.ComboboxItem>
));
}
if (localQuery.trim().length >= minQueryLengthForNoResults) {
return (
<div
className={cn(
'flex items-center justify-center px-4 py-8 text-center',
'text-sm text-text-secondary',
)}
>
<div className="flex flex-col items-center gap-2">
<Search className="h-8 w-8 text-text-tertiary opacity-50" />
<div className="font-medium">{localize('com_ui_no_results_found')}</div>
<div className="text-xs text-text-tertiary">
{localize('com_ui_try_adjusting_search')}
</div>
</div>
</div>
);
}
return null;
})()}
</Ariakit.ComboboxPopover>
</Ariakit.ComboboxProvider>
);
}

View file

@ -0,0 +1,139 @@
import React, { useState, useId } from 'react';
import * as Menu from '@ariakit/react/menu';
import { Button, DropdownPopup } from '@librechat/client';
import { Users, X, ExternalLink, ChevronDown } from 'lucide-react';
import type { TPrincipal, TAccessRole, AccessRoleIds } from 'librechat-data-provider';
import { getRoleLocalizationKeys } from '~/utils';
import PrincipalAvatar from '../PrincipalAvatar';
import { useLocalize } from '~/hooks';
interface SelectedPrincipalsListProps {
principles: TPrincipal[];
onRemoveHandler: (idOnTheSource: string) => void;
onRoleChange?: (idOnTheSource: string, newRoleId: AccessRoleIds) => void;
availableRoles?: Omit<TAccessRole, 'resourceType'>[];
className?: string;
}
export default function SelectedPrincipalsList({
principles,
onRemoveHandler,
className = '',
onRoleChange,
availableRoles,
}: SelectedPrincipalsListProps) {
const localize = useLocalize();
const getPrincipalDisplayInfo = (principal: TPrincipal) => {
const displayName = principal.name || localize('com_ui_unknown');
const subtitle = principal.email || `${principal.type} (${principal.source || 'local'})`;
return { displayName, subtitle };
};
if (principles.length === 0) {
return (
<div className={`space-y-3 ${className}`}>
<div className="rounded-lg border border-dashed border-border py-8 text-center text-muted-foreground">
<Users className="mx-auto mb-2 h-8 w-8 opacity-50" />
<p className="mt-1 text-xs">{localize('com_ui_search_above_to_add')}</p>
</div>
</div>
);
}
return (
<div className={`space-y-3 ${className}`}>
<div className="space-y-2">
{principles.map((share) => {
const { displayName, subtitle } = getPrincipalDisplayInfo(share);
return (
<div
key={share.idOnTheSource + '-principalList'}
className="bg-surface flex items-center justify-between rounded-lg border border-border p-3"
>
<div className="flex min-w-0 flex-1 items-center gap-3">
<PrincipalAvatar principal={share} size="md" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">{displayName}</div>
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<span>{subtitle}</span>
{share.source === 'entra' && (
<>
<ExternalLink className="h-3 w-3" />
<span>{localize('com_ui_azure_ad')}</span>
</>
)}
</div>
</div>
</div>
<div className="flex flex-shrink-0 items-center gap-2">
{!!share.accessRoleId && !!onRoleChange && (
<RoleSelector
currentRole={share.accessRoleId}
onRoleChange={(newRole) => {
onRoleChange?.(share.idOnTheSource!, newRole);
}}
availableRoles={availableRoles ?? []}
/>
)}
<Button
variant="ghost"
size="sm"
onClick={() => onRemoveHandler(share.idOnTheSource!)}
className="h-8 w-8 p-0 hover:bg-destructive/10 hover:text-destructive"
aria-label={localize('com_ui_remove_user', { 0: displayName })}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
);
})}
</div>
</div>
);
}
interface RoleSelectorProps {
currentRole: AccessRoleIds;
onRoleChange: (newRole: AccessRoleIds) => void;
availableRoles: Omit<TAccessRole, 'resourceType'>[];
}
function RoleSelector({ currentRole, onRoleChange, availableRoles }: RoleSelectorProps) {
const menuId = useId();
const [isMenuOpen, setIsMenuOpen] = useState(false);
const localize = useLocalize();
const getLocalizedRoleName = (roleId: AccessRoleIds) => {
const keys = getRoleLocalizationKeys(roleId);
return localize(keys.name);
};
return (
<DropdownPopup
portal={true}
mountByState={true}
unmountOnHide={true}
preserveTabOrder={true}
isOpen={isMenuOpen}
setIsOpen={setIsMenuOpen}
trigger={
<Menu.MenuButton className="flex h-8 items-center gap-2 rounded-md border border-border-medium bg-surface-secondary px-2 py-1 text-sm font-medium transition-colors duration-200 hover:bg-surface-tertiary">
<span className="hidden sm:inline">{getLocalizedRoleName(currentRole)}</span>
<ChevronDown className="h-3 w-3" />
</Menu.MenuButton>
}
items={availableRoles?.map((role) => ({
id: role.accessRoleId,
label: getLocalizedRoleName(role.accessRoleId),
onClick: () => onRoleChange(role.accessRoleId),
}))}
menuId={menuId}
className="z-50 [pointer-events:auto]"
/>
);
}

View file

@ -0,0 +1,3 @@
export { default as PeoplePicker } from './PeoplePicker';
export { default as PeoplePickerSearchItem } from './PeoplePickerSearchItem';
export { default as SelectedPrincipalsList } from './SelectedPrincipalsList';