Skip to content

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

🗂️ feat: Merge Change and Remove Project Into One Submenu (#16844)

Marco Beretta0e1a758072d7
diff --git a/client/src/common/menus.ts b/client/src/common/menus.ts
index 1aeb70d644..3082884194 100644
--- a/client/src/common/menus.ts
+++ b/client/src/common/menus.ts
@@ -19,6 +19,8 @@ export interface MenuItemProps {
ariaControls?: string;
ariaLabel?: string;
ariaChecked?: boolean;
+ /** Role of an item that has `ariaChecked`: a checkbox by default, a radio for an exclusive choice. */
+ ariaRole?: 'menuitemcheckbox' | 'menuitemradio';
ref?: React.Ref<any>;
className?: string;
render?:
diff --git a/client/src/components/Chat/ExportAndShareMenu.tsx b/client/src/components/Chat/ExportAndShareMenu.tsx
index 7b69f4fd99..e0a2fc5f8c 100644
--- a/client/src/components/Chat/ExportAndShareMenu.tsx
+++ b/client/src/components/Chat/ExportAndShareMenu.tsx
@@ -19,6 +19,7 @@ export default function ExportAndShareMenu({
const { show, items, hasSharedLink, dialogs } = useChatOptions({
isSharedButtonEnabled,
readOnly,
+ isMenuOpen: isPopoverActive,
closeMenu: () => setIsPopoverActive(false),
});
diff --git a/client/src/components/Chat/Menus/HeaderMenu.tsx b/client/src/components/Chat/Menus/HeaderMenu.tsx
index 4e6a481b6a..fd6fbc989b 100644
--- a/client/src/components/Chat/Menus/HeaderMenu.tsx
+++ b/client/src/components/Chat/Menus/HeaderMenu.tsx
@@ -62,6 +62,7 @@ export default function HeaderMenu({
const exportShare = useChatOptions({
isSharedButtonEnabled: startupConfig?.sharedLinksEnabled ?? false,
readOnly,
+ isMenuOpen: isOpen,
closeMenu: () => setIsOpen(false),
});
diff --git a/client/src/components/Chat/__tests__/ExportAndShareMenu.test.tsx b/client/src/components/Chat/__tests__/ExportAndShareMenu.test.tsx
index fb40c0aae0..d776a01621 100644
--- a/client/src/components/Chat/__tests__/ExportAndShareMenu.test.tsx
+++ b/client/src/components/Chat/__tests__/ExportAndShareMenu.test.tsx
@@ -1,9 +1,11 @@
import React from 'react';
-import { render, screen } from '@testing-library/react';
+import { render, screen, act } from '@testing-library/react';
import '@testing-library/jest-dom';
import ExportAndShareMenu from '../ExportAndShareMenu';
const mockOptions = { show: true, hasSharedLink: false };
+const mockUseChatOptions = jest.fn();
+const mockDropdown: { current?: { setIsOpen: (open: boolean) => void } } = {};
jest.mock('@ariakit/react', () => ({
MenuButton: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
@@ -12,7 +14,10 @@ jest.mock('@ariakit/react', () => ({
}));
jest.mock('@librechat/client', () => ({
- DropdownPopup: ({ trigger }: { trigger: React.ReactNode }) => trigger,
+ DropdownPopup: (props: { trigger: React.ReactNode; setIsOpen: (open: boolean) => void }) => {
+ mockDropdown.current = props;
+ return props.trigger;
+ },
TooltipAnchor: ({ render }: { render: React.ReactNode }) => render,
useMediaQuery: () => false,
}));
@@ -23,13 +28,17 @@ jest.mock('~/hooks', () => ({
jest.mock('~/hooks/Chat/useChatOptions', () => ({
__esModule: true,
- default: () => ({ ...mockOptions, items: [], dialogs: null }),
+ default: (args: unknown) => {
+ mockUseChatOptions(args);
+ return { ...mockOptions, items: [], dialogs: null };
+ },
}));
describe('ExportAndShareMenu link status', () => {
beforeEach(() => {
mockOptions.show = true;
mockOptions.hasSharedLink = false;
+ mockUseChatOptions.mockClear();
});
it('shows a blue circular indicator when the conversation has a link', () => {
@@ -57,6 +66,19 @@ describe('ExportAndShareMenu link status', () => {
expect(screen.getByRole('button')).toHaveAttribute('aria-label', 'com_ui_chat_options');
});
+ it('tells the options hook when the menu is open so the project list can load', () => {
+ render(<ExportAndShareMenu isSharedButtonEnabled={true} />);
+ expect(mockUseChatOptions).toHaveBeenLastCalledWith(
+ expect.objectContaining({ isMenuOpen: false }),
+ );
+
+ act(() => mockDropdown.current?.setIsOpen(true));
+
+ expect(mockUseChatOptions).toHaveBeenLastCalledWith(
+ expect.objectContaining({ isMenuOpen: true }),
+ );
+ });
+
it('renders nothing for a conversation that has not been saved', () => {
mockOptions.show = false;
diff --git a/client/src/components/Conversations/ConvoOptions/ProjectButton.tsx b/client/src/components/Conversations/ConvoOptions/ProjectButton.tsx
deleted file mode 100644
index 67a93d4c8e..0000000000
--- a/client/src/components/Conversations/ConvoOptions/ProjectButton.tsx
+++ /dev/null
@@ -1,191 +0,0 @@
-import { useMemo, useState, type RefObject } from 'react';
-import { Folder } from 'lucide-react';
-import {
- Button,
- ControlCombobox,
- Label,
- OGDialog,
- OGDialogClose,
- OGDialogContent,
- OGDialogHeader,
- OGDialogTitle,
- Spinner,
- useToastContext,
-} from '@librechat/client';
-import type { TChatProject } from 'librechat-data-provider';
-import type { OptionWithIcon } from '~/common';
-import { useAssignConversationToProjectMutation, useProjectsInfiniteQuery } from '~/data-provider';
-import { NotificationSeverity } from '~/common';
-import { useLocalize } from '~/hooks';
-
-type ProjectButtonProps = {
- conversationId: string;
- chatProjectId?: string | null;
- showProjectDialog?: boolean;
- setShowProjectDialog?: (value: boolean) => void;
- triggerRef?: RefObject<HTMLButtonElement>;
- setMenuOpen?: (open: boolean) => void;
- /** Called with the new project once the assignment has landed. */
- onAssigned?: (projectId: string) => void;
-};
-
-function ProjectConversationDialog({
- conversationId,
- chatProjectId,
- setMenuOpen,
- setShowProjectDialog,
- onAssigned,
-}: {
- conversationId: string;
- chatProjectId?: string | null;
- setMenuOpen?: (open: boolean) => void;
- setShowProjectDialog: (value: boolean) => void;
- onAssigned?: (projectId: string) => void;
-}) {
- const localize = useLocalize();
- const { showToast } = useToastContext();
- const [selectedProjectId, setSelectedProjectId] = useState(chatProjectId ?? '');
- const assignConversation = useAssignConversationToProjectMutation();
- const { data, fetchNextPage, isFetchingNextPage } = useProjectsInfiniteQuery({
- sortBy: 'name',
- sortDirection: 'asc',
- limit: 100,
- });
-
- const projects = useMemo<TChatProject[]>(
- () => data?.pages.flatMap((page) => page.projects) ?? [],
- [data?.pages],
- );
- const hasNextPage = data?.pages[data.pages.length - 1]?.nextCursor != null;
- const selectedProject = projects.find((project) => project._id === selectedProjectId);
- const projectItems = useMemo<OptionWithIcon[]>(
- () =>
- projects.map((project) => ({
- label: project.name,
- value: project._id,
- icon: <Folder className="text-text-secondary h-4 w-4" aria-hidden="true" />,
- })),
- [projects],
- );
- const canSave =
- Boolean(selectedProjectId) &&
- selectedProjectId !== (chatProjectId ?? '') &&
- !assignConversation.isLoading;
-
- const saveProject = () => {
- if (!canSave) {
- return;
- }
- assignConversation.mutate(
- {
- conversationId,
- projectId: selectedProjectId,
- },
- {
- onSuccess: () => {
- onAssigned?.(selectedProjectId);
- setShowProjectDialog(false);
- setMenuOpen?.(false);
- showToast({
- message: localize('com_ui_project_updated'),
- severity: NotificationSeverity.SUCCESS,
- showIcon: true,
- });
- },
- onError: () => {
- showToast({
- message: localize('com_ui_project_update_error'),
- severity: NotificationSeverity.ERROR,
- showIcon: true,
- });
- },
- },
- );
- };
-
- return (
- <OGDialogContent
- id="project-conversation-dialog"
- className="w-11/12 max-w-md overflow-visible"
- showCloseButton={false}
- >
- <OGDialogHeader>
- <OGDialogTitle>{localize('com_ui_change_project')}</OGDialogTitle>
- </OGDialogHeader>
- <div className="flex flex-col gap-2">
- <Label htmlFor="change-project-select" className="text-sm font-medium">
- {localize('com_ui_select_project')}
- </Label>
- <ControlCombobox
- selectId="change-project-select"
- selectedValue={selectedProjectId}
- displayValue={selectedProject?.name}
- items={projectItems}
- setValue={setSelectedProjectId}
- SelectIcon={<Folder className="text-text-secondary h-4 w-4" aria-hidden="true" />}
- ariaLabel={localize('com_ui_select_project')}
- searchPlaceholder={localize('com_ui_search_projects')}
- selectPlaceholder={localize('com_ui_select_project')}
- isCollapsed={false}
- showCarat={true}
- placement="bottom-start"
- portal={false}
- matchTriggerWidth={true}
- containerClassName="w-full px-0"
- className="border-border-light bg-surface-tertiary text-text-primary hover:bg-surface-hover h-10 w-full justify-start gap-2 rounded-xl border px-3 text-sm"
- />
- {hasNextPage ? (
- <Button
- type="button"
- variant="link"
- className="h-auto justify-start px-0"
- onClick={() => fetchNextPage()}
- disabled={isFetchingNextPage}
- >
- {isFetchingNextPage ? localize('com_ui_loading') : localize('com_ui_load_more')}
- </Button>
- ) : null}
- </div>
- <div className="flex justify-end gap-2 pt-4">
- <OGDialogClose asChild>
- <Button type="button" variant="outline">
- {localize('com_ui_cancel')}
- </Button>
- </OGDialogClose>
- <Button type="button" variant="submit" onClick={saveProject} disabled={!canSave}>
- {assignConversation.isLoading ? <Spinner /> : localize('com_ui_save')}
- </Button>
- </div>
- </OGDialogContent>
- );
-}
-
-export default function ProjectButton({
- conversationId,
- chatProjectId,
- setMenuOpen,
- showProjectDialog,
- setShowProjectDialog,
- triggerRef,
- onAssigned,
-}: ProjectButtonProps) {
- if (showProjectDialog === undefined || setShowProjectDialog === undefined) {
- return null;
- }
-
- if (!conversationId) {
- return null;
- }
-
- return (
- <OGDialog open={showProjectDialog} onOpenChange={setShowProjectDialog} triggerRef={triggerRef}>
- <ProjectConversationDialog
- conversationId={conversationId}
- chatProjectId={chatProjectId}
- setMenuOpen={setMenuOpen}
- setShowProjectDialog={setShowProjectDialog}
- onAssigned={onAssigned}
- />
- </OGDialog>
- );
-}
diff --git a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
index da1d891947..ee292e0fee 100644
--- a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
+++ b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
@@ -99,7 +99,6 @@ jest.mock('react-router-dom', () => {
};
});
-jest.mock('../ProjectButton', () => () => null);
jest.mock('../DeleteButton', () => () => null);
jest.mock('../ShareButton', () => () => null);
diff --git a/client/src/components/Conversations/ConvoOptions/index.js b/client/src/components/Conversations/ConvoOptions/index.js
index 44a5e2c9d3..c294bb45ce 100644
--- a/client/src/components/Conversations/ConvoOptions/index.js
+++ b/client/src/components/Conversations/ConvoOptions/index.js
@@ -1,5 +1,4 @@
export * from './DeleteButton';
-export { default as ProjectButton } from './ProjectButton';
export { default as ShareButton } from './ShareButton';
export { default as SharedLinkButton } from './SharedLinkButton';
export { default as ConvoOptions } from './ConvoOptions';
diff --git a/client/src/components/Conversations/ConvoOptions/index.ts b/client/src/components/Conversations/ConvoOptions/index.ts
index 44a5e2c9d3..c294bb45ce 100644
--- a/client/src/components/Conversations/ConvoOptions/index.ts
+++ b/client/src/components/Conversations/ConvoOptions/index.ts
@@ -1,5 +1,4 @@
export * from './DeleteButton';
-export { default as ProjectButton } from './ProjectButton';
export { default as ShareButton } from './ShareButton';
export { default as SharedLinkButton } from './SharedLinkButton';
export { default as ConvoOptions } from './ConvoOptions';
diff --git a/client/src/components/Projects/ProjectChatOptions.tsx b/client/src/components/Projects/ProjectChatOptions.tsx
index 0503fe437c..9973857cfc 100644
--- a/client/src/components/Projects/ProjectChatOptions.tsx
+++ b/client/src/components/Projects/ProjectChatOptions.tsx
@@ -1,13 +1,11 @@
import { memo, useId, useMemo, useRef, useState } from 'react';
import * as Ariakit from '@ariakit/react';
-import { Ellipsis, FolderInput, FolderX, Trash2 } from 'lucide-react';
-import { Spinner, DropdownPopup, buttonVariants, useToastContext } from '@librechat/client';
+import { Ellipsis, Trash2 } from 'lucide-react';
+import { DropdownPopup, buttonVariants } from '@librechat/client';
import type { TConversation } from 'librechat-data-provider';
import type { MenuItemProps } from '~/common';
-import ProjectButton from '~/components/Conversations/ConvoOptions/ProjectButton';
import DeleteButton from '~/components/Conversations/ConvoOptions/DeleteButton';
-import { useAssignConversationToProjectMutation } from '~/data-provider';
-import { NotificationSeverity } from '~/common';
+import useProjectMenuItem from '~/hooks/Chat/useProjectMenuItem';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -21,15 +19,18 @@ const noop = () => {};
function ProjectChatOptions({ conversation, isMenuOpen, setIsMenuOpen }: ProjectChatOptionsProps) {
const localize = useLocalize();
- const { showToast } = useToastContext();
const menuId = useId();
const menuButtonRef = useRef<HTMLButtonElement>(null);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
- const [showProjectDialog, setShowProjectDialog] = useState(false);
const conversationId = conversation.conversationId ?? '';
const chatProjectId = conversation.chatProjectId ?? null;
- const assignConversationToProject = useAssignConversationToProjectMutation();
+ const projectItem = useProjectMenuItem({
+ conversationId,
+ chatProjectId,
+ enabled: isMenuOpen && conversationId !== '',
+ onAssigned: () => setIsMenuOpen(false),
+ });
const menuItems = useMemo<MenuItemProps[]>(() => {
if (!conversationId) {
@@ -37,48 +38,7 @@ function ProjectChatOptions({ conversation, isMenuOpen, setIsMenuOpen }: Project
}
return [
- {
- label: localize('com_ui_change_project'),
- onClick: () => setShowProjectDialog(true),
- icon: <FolderInput className="text-text-secondary size-4" aria-hidden="true" />,
- /** Hiding the menu here restores focus to the trigger, which the dialog
- * mounting alongside it reads as an outside interaction and closes on.
- * Both dialogs receive setIsMenuOpen and close the menu themselves. */
- hideOnClick: false,
- render: (props) => <button {...props} />,
- },
- {
- label: localize('com_ui_remove_from_project'),
- show: Boolean(chatProjectId),
- onClick: () => {
- assignConversationToProject.mutate(
- { conversationId, projectId: null },
- {
- onSuccess: () => {
- setIsMenuOpen(false);
- showToast({
- message: localize('com_ui_project_updated'),
- severity: NotificationSeverity.SUCCESS,
- showIcon: true,
- });
- },
- onError: () => {
- showToast({
- message: localize('com_ui_project_update_error'),
- severity: NotificationSeverity.ERROR,
- showIcon: true,
- });
- },
- },
- );
- },
- hideOnClick: false,
- icon: assignConversationToProject.isLoading ? (
- <Spinner className="size-4" />
- ) : (
- <FolderX className="text-text-secondary size-4" aria-hidden="true" />
- ),
- },
+ projectItem,
{
label: localize('com_ui_delete'),
onClick: () => setShowDeleteDialog(true),
@@ -87,14 +47,7 @@ function ProjectChatOptions({ conversation, isMenuOpen, setIsMenuOpen }: Project
icon: <Trash2 className="text-text-secondary size-4" aria-hidden="true" />,
},
];
- }, [
- assignConversationToProject,
- chatProjectId,
- conversationId,
- localize,
- setIsMenuOpen,
- showToast,
- ]);
+ }, [conversationId, localize, projectItem]);
return (
<>
@@ -123,16 +76,6 @@ function ProjectChatOptions({ conversation, isMenuOpen, setIsMenuOpen }: Project
}
items={menuItems}
/>
- {showProjectDialog ? (
- <ProjectButton
- conversationId={conversationId}
- chatProjectId={chatProjectId}
- setMenuOpen={setIsMenuOpen}
- triggerRef={menuButtonRef}
- showProjectDialog={showProjectDialog}
- setShowProjectDialog={setShowProjectDialog}
- />
- ) : null}
{showDeleteDialog ? (
<DeleteButton
title={conversation.title ?? ''}
diff --git a/client/src/components/SidePanel/Schedules/useScheduleProjects.tsx b/client/src/components/SidePanel/Schedules/useScheduleProjects.tsx
index 0fa41a641f..14f3718ef5 100644
--- a/client/src/components/SidePanel/Schedules/useScheduleProjects.tsx
+++ b/client/src/components/SidePanel/Schedules/useScheduleProjects.tsx
@@ -4,8 +4,8 @@ import type { TChatProject } from 'librechat-data-provider';
import type { OptionWithIcon } from '~/common';
import { useProjectsInfiniteQuery } from '~/data-provider';
-/** Shared with `ProjectButton`, so every project surface reads one cached page set
- * instead of each card and dialog opening its own list. */
+/** Shared with `useProjectMenuItem`, so every project surface reads one cached page set
+ * instead of each card and menu opening its own list. */
const PROJECT_LIST_PARAMS = {
sortBy: 'name',
sortDirection: 'asc',
@@ -69,7 +69,7 @@ export function useChatProjectPicker(enabled = true): ChatProjectPicker {
options.push({
label: project.name,
value: project._id,
- icon: <Folder className="h-4 w-4 text-text-secondary" aria-hidden="true" />,
+ icon: <Folder className="text-text-secondary h-4 w-4" aria-hidden="true" />,
});
}
return { items: options, namesById: names };
diff --git a/client/src/hooks/Chat/__tests__/useChatOptions.spec.tsx b/client/src/hooks/Chat/__tests__/useChatOptions.spec.tsx
index fbb918e55b..e2d597a1c5 100644
--- a/client/src/hooks/Chat/__tests__/useChatOptions.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatOptions.spec.tsx
@@ -14,7 +14,17 @@ const mockState = {
route: 'convo-1' as string | undefined,
activeJobs: [] as string[],
startupConfig: undefined as Record<string, unknown> | undefined,
+ projects: undefined as { _id: string; name: string }[] | undefined,
+ projectsError: false,
+ hasNextPage: false,
+ exportShow: true,
+ fetching: false,
+ fetchingNext: false,
+ assigning: undefined as { projectId: string | null } | undefined,
};
+const mockFetchNextPage = jest.fn(() => Promise.resolve({ isError: false }));
+const mockRefetch = jest.fn(() => Promise.resolve({ isError: false }));
+const mockProjectsConfig: { current?: { enabled?: boolean } } = {};
const mockClient: { current: QueryClient | null } = { current: null };
const mockCloseMenu = jest.fn();
const mockPin = jest.fn();
@@ -32,7 +42,10 @@ jest.mock('react-router-dom', () => ({
useNavigate: () => mockNavigate,
useParams: () => ({ conversationId: mockState.route }),
}));
-jest.mock('@librechat/client', () => ({ useToastContext: () => ({ showToast: jest.fn() }) }));
+jest.mock('@librechat/client', () => ({
+ Spinner: () => null,
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
jest.mock('~/store', () => ({ __esModule: true, default: { conversationByIndex: () => ({}) } }));
jest.mock('~/common', () => ({ NotificationSeverity: { SUCCESS: 'success', ERROR: 'error' } }));
jest.mock('~/hooks', () => ({
@@ -50,11 +63,24 @@ jest.mock('~/data-provider', () => ({
useActiveJobs: () => ({ data: { activeJobIds: mockState.activeJobs } }),
usePinConversationMutation: () => ({ mutate: mockPin }),
useArchiveConvoMutation: () => ({ mutate: mockArchive }),
- useAssignConversationToProjectMutation: () => ({ mutate: mockAssign }),
+ useAssignConversationToProjectMutation: () => ({
+ mutate: mockAssign,
+ isLoading: mockState.assigning != null,
+ variables: mockState.assigning,
+ }),
useDuplicateConversationMutation: () => ({ mutate: mockDuplicate }),
-}));
-jest.mock('~/components/Conversations/ConvoOptions', () => ({
- ProjectButton: () => <div data-testid="project-dialog" />,
+ useProjectsInfiniteQuery: (_params: unknown, config?: { enabled?: boolean }) => {
+ mockProjectsConfig.current = config;
+ return {
+ data: mockState.projects && { pages: [{ projects: mockState.projects }] },
+ isError: mockState.projectsError,
+ hasNextPage: mockState.hasNextPage,
+ fetchNextPage: mockFetchNextPage,
+ refetch: mockRefetch,
+ isFetching: mockState.fetching,
+ isFetchingNextPage: mockState.fetchingNext,
+ };
+ },
}));
const mockDeleteProps: {
current?: {
@@ -77,16 +103,16 @@ jest.mock('~/components/Chat/Rename', () => ({
jest.mock('../useExportShare', () => ({
__esModule: true,
default: () => ({
- show: true,
+ show: mockState.exportShow,
hasSharedLink: false,
items: [{ label: 'share' }, { label: 'export' }],
dialogs: null,
}),
}));
-const setup = (readOnly = false) =>
+const setup = (readOnly = false, isMenuOpen = false) =>
renderHook(() =>
- useChatOptions({ isSharedButtonEnabled: true, closeMenu: mockCloseMenu, readOnly }),
+ useChatOptions({ isSharedButtonEnabled: true, closeMenu: mockCloseMenu, readOnly, isMenuOpen }),
);
const labels = (items: MenuItemProps[]) =>
items.filter((item) => item.show !== false && item.separate !== true).map((item) => item.label);
@@ -107,6 +133,14 @@ describe('useChatOptions', () => {
mockState.route = 'convo-1';
mockState.activeJobs = [];
mockState.startupConfig = undefined;
+ mockState.projects = undefined;
+ mockState.projectsError = false;
+ mockState.hasNextPage = false;
+ mockState.exportShow = true;
+ mockState.fetching = false;
+ mockState.fetchingNext = false;
+ mockState.assigning = undefined;
+ mockProjectsConfig.current = undefined;
});
it('lists share and export first, then the sidebar actions for the open chat', () => {
@@ -133,7 +167,7 @@ describe('useChatOptions', () => {
it('keeps the dialog-opening items open and anchored so their dialogs can restore focus', () => {
const { result } = setup();
- for (const label of ['com_ui_rename', 'com_ui_change_project', 'com_ui_delete']) {
+ for (const label of ['com_ui_rename', 'com_ui_delete']) {
const item = find(result.current.items, label);
expect(item.hideOnClick).toBe(false);
expect(item.ref).toBeDefined();
@@ -149,13 +183,291 @@ describe('useChatOptions', () => {
);
});
- it('offers removal from a project only when the chat is in one', () => {
- const { result, rerender } = setup();
+ it('folds project removal into the change project submenu instead of a top-level item', () => {
+ mockState.cached = { conversationId: 'convo-1', chatProjectId: 'project-1' };
+ const { result } = setup(false, true);
+
expect(labels(result.current.items)).not.toContain('com_ui_remove_from_project');
+ expect(labels(find(result.current.items, 'com_ui_change_project').subItems ?? [])).toContain(
+ 'com_ui_remove_from_project',
+ );
+ });
+
+ it('offers removal inside the submenu only when the chat is in a project', () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ const { result } = setup(false, true);
+
+ expect(
+ labels(find(result.current.items, 'com_ui_change_project').subItems ?? []),
+ ).not.toContain('com_ui_remove_from_project');
+ });
+
+ it('lists every project in the submenu and marks the current one', () => {
+ mockState.projects = [
+ { _id: 'project-1', name: 'Alpha' },
+ { _id: 'project-2', name: 'Beta' },
+ ];
+ mockState.cached = { conversationId: 'convo-1', chatProjectId: 'project-2' };
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ expect(find(subItems, 'Alpha').ariaChecked).toBe(false);
+ expect(find(subItems, 'Beta')).toMatchObject({ ariaChecked: true });
+ });
+
+ it('keeps the checked project in the arrow-key order and does not reassign it', () => {
+ mockState.projects = [
+ { _id: 'project-1', name: 'Alpha' },
+ { _id: 'project-2', name: 'Beta' },
+ ];
+ mockState.cached = { conversationId: 'convo-1', chatProjectId: 'project-2' };
+ const { result } = setup(false, true);
+ const beta = find(find(result.current.items, 'com_ui_change_project').subItems ?? [], 'Beta');
+
+ /** Ariakit drops a `disabled` item from keyboard navigation, and this is the row a keyboard
+ * or screen-reader user has to find. */
+ expect(beta.disabled).not.toBe(true);
+ act(() => beta.onClick?.({} as never));
+ expect(mockAssign).not.toHaveBeenCalled();
+ });
+
+ it('offers the projects as one exclusive choice', () => {
+ mockState.projects = [
+ { _id: 'project-1', name: 'Alpha' },
+ { _id: 'project-2', name: 'Beta' },
+ ];
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ expect(find(subItems, 'Alpha').ariaRole).toBe('menuitemradio');
+ expect(find(subItems, 'Beta').ariaRole).toBe('menuitemradio');
+ });
+
+ it('assigns the picked project and mirrors it into the open chat', () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ act(() => find(subItems, 'Alpha').onClick?.({} as never));
+ act(() => mockAssign.mock.calls[0][1].onSuccess());
+
+ expect(mockAssign.mock.calls[0][0]).toEqual({
+ conversationId: 'convo-1',
+ projectId: 'project-1',
+ });
+ const [updater] = mockSetConversation.mock.calls[0];
+ expect(updater({ conversationId: 'convo-1' })).toEqual({
+ conversationId: 'convo-1',
+ chatProjectId: 'project-1',
+ });
+ });
+
+ it('fetches the project list only while the menu is open', () => {
+ const { rerender } = renderHook(
+ ({ isMenuOpen }) =>
+ useChatOptions({ isSharedButtonEnabled: true, closeMenu: mockCloseMenu, isMenuOpen }),
+ { initialProps: { isMenuOpen: false } },
+ );
+ expect(mockProjectsConfig.current?.enabled).toBe(false);
+
+ rerender({ isMenuOpen: true });
+ expect(mockProjectsConfig.current?.enabled).toBe(true);
+ });
+
+ it('builds no project rows while the menu is closed, even when the list is cached', () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ const { result, rerender } = renderHook(
+ ({ isMenuOpen }) =>
+ useChatOptions({ isSharedButtonEnabled: true, closeMenu: mockCloseMenu, isMenuOpen }),
+ { initialProps: { isMenuOpen: false } },
+ );
+ const rows = () => labels(find(result.current.items, 'com_ui_change_project').subItems ?? []);
+ expect(rows()).not.toContain('Alpha');
+
+ rerender({ isMenuOpen: true });
+ expect(rows()).toContain('Alpha');
+ });
+
+ it('keeps the loaded projects and offers a retry when the next page fails', () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ mockState.hasNextPage = true;
+ mockState.projectsError = true;
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ expect(labels(subItems)).toEqual(
+ expect.arrayContaining(['Alpha', 'com_ui_projects_load_error', 'com_ui_retry']),
+ );
+ expect(labels(subItems)).not.toContain('com_ui_load_more');
+ expect(find(subItems, 'com_ui_retry').hideOnClick).toBe(false);
+ });
+
+ it('retries with a refetch when an automatic refresh failed after a failed Load more', async () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ mockState.hasNextPage = true;
+ const { result, rerender } = setup(false, true);
+ const rows = () => find(result.current.items, 'com_ui_change_project').subItems ?? [];
+ mockFetchNextPage.mockResolvedValueOnce({ isError: true });
+ await act(async () => {
+ find(rows(), 'com_ui_load_more').onClick?.({} as never);
+ });
+
+ /** A remount or a window focus refetches the held pages without anyone clicking: that, not
+ * the earlier page request, is what failed when the error shows up now. */
+ mockState.fetching = true;
+ rerender();
+ mockState.fetching = false;
+ mockState.projectsError = true;
+ rerender();
+ await act(async () => {
+ find(rows(), 'com_ui_retry').onClick?.({} as never);
+ });
+ expect(mockFetchNextPage).toHaveBeenCalledTimes(1);
+ expect(mockRefetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('offers a retry when the first page fails', async () => {
+ mockState.projectsError = true;
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ await act(async () => {
+ find(subItems, 'com_ui_retry').onClick?.({} as never);
+ });
+ expect(mockRefetch).toHaveBeenCalledTimes(1);
+ expect(mockFetchNextPage).not.toHaveBeenCalled();
+ });
+
+ it('retries a failed refresh with a refetch when there is no next page to ask for', async () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ mockState.hasNextPage = false;
+ mockState.projectsError = true;
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ await act(async () => {
+ find(subItems, 'com_ui_retry').onClick?.({} as never);
+ });
+
+ expect(mockRefetch).toHaveBeenCalledTimes(1);
+ expect(mockFetchNextPage).not.toHaveBeenCalled();
+ });
+
+ it('retries the page request that failed, not a refetch of the pages already held', async () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ mockState.hasNextPage = true;
+ const { result, rerender } = setup(false, true);
+ const rows = () => find(result.current.items, 'com_ui_change_project').subItems ?? [];
+ mockFetchNextPage.mockResolvedValueOnce({ isError: true });
+ await act(async () => {
+ find(rows(), 'com_ui_load_more').onClick?.({} as never);
+ });
+ mockState.projectsError = true;
+ rerender();
+
+ await act(async () => {
+ find(rows(), 'com_ui_retry').onClick?.({} as never);
+ });
+
+ expect(mockFetchNextPage).toHaveBeenCalledTimes(2);
+ expect(mockRefetch).not.toHaveBeenCalled();
+ });
+
+ it('ignores Retry while its request is already running and says so', async () => {
+ mockState.projects = [];
+ mockState.projectsError = true;
+ mockState.fetching = true;
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ await act(async () => {
+ find(subItems, 'com_ui_loading').onClick?.({} as never);
+ });
+
+ expect(mockRefetch).not.toHaveBeenCalled();
+ expect(labels(subItems)).not.toContain('com_ui_retry');
+ });
+
+ it('keeps Load more focusable and inert while the next page loads', async () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ mockState.hasNextPage = true;
+ mockState.fetchingNext = true;
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+ const paging = find(subItems, 'com_ui_loading');
+
+ /** A disabled item is dropped from keyboard navigation, taking the focus off the control the
+ * user just activated. */
+ expect(paging.disabled).not.toBe(true);
+ await act(async () => {
+ paging.onClick?.({} as never);
+ });
+ expect(mockFetchNextPage).not.toHaveBeenCalled();
+ });
+
+ it('gives every row a stable id so a focused control survives appended pages', () => {
+ mockState.projects = [{ _id: 'project-1', name: 'Alpha' }];
+ mockState.hasNextPage = true;
mockState.cached = { conversationId: 'convo-1', chatProjectId: 'project-1' };
+ const { result, rerender } = setup(false, true);
+ const rows = () => find(result.current.items, 'com_ui_change_project').subItems ?? [];
+ const idOf = (label: string) => find(rows(), label).id;
+ const before = { alpha: idOf('Alpha'), more: idOf('com_ui_load_more') };
+
+ mockState.projects = [
+ { _id: 'project-1', name: 'Alpha' },
+ { _id: 'project-2', name: 'Beta' },
+ { _id: 'project-3', name: 'Gamma' },
+ ];
+ rerender();
+
+ expect(before.alpha).toBeDefined();
+ expect(idOf('Alpha')).toBe(before.alpha);
+ expect(idOf('com_ui_load_more')).toBe(before.more);
+ const ids = rows()
+ .filter((row) => row.separate !== true)
+ .map((row) => row.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('disables every destination and shows the pending one while an assignment runs', () => {
+ mockState.projects = [
+ { _id: 'project-1', name: 'Alpha' },
+ { _id: 'project-2', name: 'Beta' },
+ ];
+ mockState.cached = { conversationId: 'convo-1', chatProjectId: 'project-2' };
+ mockState.assigning = { projectId: 'project-1' };
+ const { result } = setup(false, true);
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+
+ expect(find(subItems, 'Alpha').disabled).toBe(true);
+ expect(find(subItems, 'Beta').disabled).toBe(true);
+ expect(find(subItems, 'com_ui_remove_from_project').disabled).toBe(true);
+ });
+
+ it('does not fetch projects for a chat whose options group is not shown', () => {
+ mockState.exportShow = false;
+ renderHook(() =>
+ useChatOptions({ isSharedButtonEnabled: true, closeMenu: mockCloseMenu, isMenuOpen: true }),
+ );
+
+ expect(mockProjectsConfig.current?.enabled).toBe(false);
+ });
+
+ it('shows a loading row, then an empty row, then a failed row in the submenu', () => {
+ const { result, rerender } = setup(false, true);
+ const rows = () => find(result.current.items, 'com_ui_change_project').subItems ?? [];
+ expect(rows()[0]).toMatchObject({ label: 'com_ui_loading', disabled: true });
+
+ mockState.projects = [];
rerender();
- expect(labels(result.current.items)).toContain('com_ui_remove_from_project');
+ expect(rows()[0]).toMatchObject({ label: 'com_ui_no_projects', disabled: true });
+
+ mockState.projects = undefined;
+ mockState.projectsError = true;
+ rerender();
+ expect(rows()[0]).toMatchObject({ label: 'com_ui_projects_load_error', disabled: true });
});
it('pins an unpinned chat', () => {
@@ -196,9 +508,10 @@ describe('useChatOptions', () => {
it('mirrors a landed project removal into the open chat', () => {
mockState.cached = { conversationId: 'convo-1', chatProjectId: 'project-1' };
- const { result } = setup();
+ const { result } = setup(false, true);
- act(() => find(result.current.items, 'com_ui_remove_from_project').onClick?.({} as never));
+ const subItems = find(result.current.items, 'com_ui_change_project').subItems ?? [];
+ act(() => find(subItems, 'com_ui_remove_from_project').onClick?.({} as never));
act(() => mockAssign.mock.calls[0][1].onSuccess());
expect(mockAssign.mock.calls[0][0]).toEqual({ conversationId: 'convo-1', projectId: null });
@@ -276,10 +589,6 @@ describe('useChatOptions', () => {
ariaHasPopup: 'dialog',
ariaControls: 'rename-conversation-dialog',
});
- expect(find(result.current.items, 'com_ui_change_project')).toMatchObject({
- ariaHasPopup: 'dialog',
- ariaControls: 'project-conversation-dialog',
- });
expect(find(result.current.items, 'com_ui_delete')).toMatchObject({
ariaHasPopup: 'dialog',
ariaControls: 'delete-conversation-dialog',
@@ -313,20 +622,6 @@ describe('useChatOptions', () => {
expect(screen.queryByTestId('delete-dialog')).not.toBeInTheDocument();
});
- it('renders no mutating dialog once the thread turns read-only', () => {
- let readOnly = false;
- const { result, rerender } = renderHook(() =>
- useChatOptions({ isSharedButtonEnabled: true, closeMenu: mockCloseMenu, readOnly }),
- );
-
- act(() => find(result.current.items, 'com_ui_change_project').onClick?.({} as never));
- readOnly = true;
- rerender();
- render(<>{result.current.dialogs}</>);
-
- expect(screen.queryByTestId('project-dialog')).not.toBeInTheDocument();
- });
-
it('tells the delete dialog which chat is open when the request settles', () => {
const { result, rerender } = setup();
diff --git a/client/src/hooks/Chat/useChatOptions.tsx b/client/src/hooks/Chat/useChatOptions.tsx
index 6d053bc2ce..40dba9cf8c 100644
--- a/client/src/hooks/Chat/useChatOptions.tsx
+++ b/client/src/hooks/Chat/useChatOptions.tsx
@@ -4,16 +4,7 @@ import { useToastContext } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router-dom';
import { supportsConversationTitleOwnership } from 'librechat-data-provider';
-import {
- Pen,
- Pin,
- Trash,
- Archive,
- FolderX,
- CopyPlus,
- FolderInput,
- ArchiveRestore,
-} from 'lucide-react';
+import { Pen, Pin, Trash, Archive, CopyPlus, ArchiveRestore } from 'lucide-react';
import type { TConversation } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import type * as t from '~/common';
@@ -24,13 +15,12 @@ import {
useArchiveConvoMutation,
usePinConversationMutation,
useDuplicateConversationMutation,
- useAssignConversationToProjectMutation,
} from '~/data-provider';
import { findConvoInAllQueries, isTemporaryConversation, hasRealTitle } from '~/utils';
import DeleteButton from '~/components/Conversations/ConvoOptions/DeleteButton';
-import { ProjectButton } from '~/components/Conversations/ConvoOptions';
import { useLocalize, useNavigateToConvo, useNewConvo } from '~/hooks';
import { useChatContext, useLiveAnnouncer } from '~/Providers';
+import useProjectMenuItem from './useProjectMenuItem';
import { NotificationSeverity } from '~/common';
import useExportShare from './useExportShare';
import Rename from '~/components/Chat/Rename';
@@ -44,7 +34,7 @@ export type UseChatOptionsResult = {
dialogs: ReactNode;
};
-type DialogKind = 'rename' | 'project' | 'delete';
+type DialogKind = 'rename' | 'delete';
const iconClass = 'size-4 text-text-secondary';
const noop = () => {};
@@ -57,10 +47,13 @@ const noop = () => {};
export default function useChatOptions({
isSharedButtonEnabled,
closeMenu,
+ isMenuOpen = false,
readOnly = false,
}: {
isSharedButtonEnabled: boolean;
closeMenu: () => void;
+ /** The project list behind "Change project" is only fetched while the menu is open. */
+ isMenuOpen?: boolean;
/** A durable subagent thread is a canonical record of its parent's run: only share and export apply. */
readOnly?: boolean;
}): UseChatOptionsResult {
@@ -102,7 +95,6 @@ export default function useChatOptions({
(!isGenerating && (current?.titleSetByUser === true || hasRealTitle(title)));
const renameRef = useRef<HTMLButtonElement>(null);
- const projectRef = useRef<HTMLButtonElement>(null);
const deleteRef = useRef<HTMLButtonElement>(null);
/** ChatView stays mounted across a route change, so a dialog is tied to the chat it was opened
* for rather than to whichever chat is open when it renders. */
@@ -127,7 +119,6 @@ export default function useChatOptions({
openDialog.id === conversationId &&
(routeConversationId == null || routeConversationId === conversationId);
const showRename = isDialogOpen('rename');
- const showProject = isDialogOpen('project');
const showDelete = isDialogOpen('delete');
/** A close only clears the dialog it belongs to: a delete that settles after another chat
* opened its own dialog must not take that one down. */
@@ -139,12 +130,10 @@ export default function useChatOptions({
return prev?.kind === kind && prev.id === conversationId ? null : prev;
});
const setShowRename = toggleDialog('rename');
- const setShowProject = toggleDialog('project');
const setShowDelete = toggleDialog('delete');
const pinMutation = usePinConversationMutation();
const archiveMutation = useArchiveConvoMutation();
- const assignMutation = useAssignConversationToProjectMutation();
const duplicateMutation = useDuplicateConversationMutation({
onSuccess: (data) => {
navigateToConvo(data.conversation);
@@ -181,22 +170,13 @@ export default function useChatOptions({
);
};
- const removeFromProject = () => {
- assignMutation.mutate(
- { conversationId, projectId: null },
- {
- onSuccess: () => {
- mirrorToOpenChat({ chatProjectId: null });
- showToast({
- message: localize('com_ui_project_updated'),
- severity: NotificationSeverity.SUCCESS,
- showIcon: true,
- });
- },
- onError: () => showError('com_ui_project_update_error'),
- },
- );
- };
+ const projectItem = useProjectMenuItem({
+ conversationId,
+ chatProjectId,
+ /** The header omits this whole group for a conversation that is not saved yet. */
+ enabled: isMenuOpen && exportShare.show && !readOnly && !isTemporary,
+ onAssigned: (projectId) => mirrorToOpenChat({ chatProjectId: projectId }),
+ });
const toggleArchive = () => {
archiveMutation.mutate(
@@ -246,24 +226,7 @@ export default function useChatOptions({
show: canOrganize,
icon: <Pin className={iconClass} aria-hidden="true" />,
},
- {
- label: localize('com_ui_change_project'),
- onClick: () => setShowProject(true),
- show: canOrganize,
- icon: <FolderInput className={iconClass} aria-hidden="true" />,
- ariaHasPopup: 'dialog',
- ariaControls: 'project-conversation-dialog',
- /** NOTE: THE FOLLOWING PROPS ARE REQUIRED FOR MENU ITEMS THAT OPEN DIALOGS */
- hideOnClick: false,
- ref: projectRef,
- render: (props) => <button {...props} />,
- },
- {
- label: localize('com_ui_remove_from_project'),
- onClick: removeFromProject,
- show: canOrganize && chatProjectId != null,
- icon: <FolderX className={iconClass} aria-hidden="true" />,
- },
+ { ...projectItem, show: canOrganize },
{
label: localize('com_ui_duplicate'),
onClick: () => duplicateMutation.mutate({ conversationId }),
@@ -310,17 +273,6 @@ export default function useChatOptions({
triggerRef={renameRef}
/>
)}
- {showProject && (
- <ProjectButton
- conversationId={conversationId}
- chatProjectId={chatProjectId}
- setMenuOpen={closeMenu}
- triggerRef={projectRef}
- onAssigned={(projectId) => mirrorToOpenChat({ chatProjectId: projectId })}
- showProjectDialog={showProject}
- setShowProjectDialog={setShowProject}
- />
- )}
{showDelete && (
<DeleteButton
title={title}
diff --git a/client/src/hooks/Chat/useProjectMenuItem.tsx b/client/src/hooks/Chat/useProjectMenuItem.tsx
new file mode 100644
index 0000000000..4f656a5c97
--- /dev/null
+++ b/client/src/hooks/Chat/useProjectMenuItem.tsx
@@ -0,0 +1,182 @@
+import { useEffect, useId, useRef } from 'react';
+import { Spinner, useToastContext } from '@librechat/client';
+import { Check, Folder, FolderInput, FolderX } from 'lucide-react';
+import type * as t from '~/common';
+import { useAssignConversationToProjectMutation, useProjectsInfiniteQuery } from '~/data-provider';
+import { NotificationSeverity } from '~/common';
+import { useLocalize } from '~/hooks';
+
+const iconClass = 'size-4 text-text-secondary';
+
+type ProjectMenuItemParams = {
+ conversationId: string;
+ chatProjectId: string | null;
+ /** The project list is only fetched, and its rows only built, while the menu that shows it is open. */
+ enabled: boolean;
+ /** Called once an assignment has landed, with `null` when the chat left its project. */
+ onAssigned: (projectId: string | null) => void;
+};
+
+/**
+ * One "Change project" menu item whose submenu lists every project, marks the current one,
+ * and offers removal from it. Picking a project assigns it immediately.
+ */
+export default function useProjectMenuItem({
+ conversationId,
+ chatProjectId,
+ enabled,
+ onAssigned,
+}: ProjectMenuItemParams): t.MenuItemProps {
+ const localize = useLocalize();
+ const idPrefix = useId();
+ const { showToast } = useToastContext();
+ const assignMutation = useAssignConversationToProjectMutation();
+ const { data, isError, isFetching, isFetchingNextPage, hasNextPage, fetchNextPage, refetch } =
+ useProjectsInfiniteQuery({ sortBy: 'name', sortDirection: 'asc', limit: 100 }, { enabled });
+ /** `isError` alone cannot say whether a page request or a refresh of the loaded pages failed,
+ * and Retry has to repeat the one that did. */
+ const failedPageRequest = useRef(false);
+ const requestInFlight = useRef(false);
+ /** A refetch nobody asked for here (a remount, a window focus) replaces whatever the last request
+ * left behind: when it fails, it is the refresh that Retry has to repeat. */
+ useEffect(() => {
+ if (isFetching && !requestInFlight.current) {
+ failedPageRequest.current = false;
+ }
+ }, [isFetching]);
+
+ const pending = assignMutation.isLoading;
+ const pendingProjectId = assignMutation.variables?.projectId;
+ const busy = isFetching || isFetchingNextPage;
+ /** Ids are the row identity: positions shift as pages are appended, and a focused control has
+ * to stay the same element when that happens. */
+ const rowId = (suffix: string) => `${idPrefix}-${suffix}`;
+
+ const assign = (projectId: string | null) => {
+ if (pending) {
+ return;
+ }
+ assignMutation.mutate(
+ { conversationId, projectId },
+ {
+ onSuccess: () => {
+ onAssigned(projectId);
+ showToast({
+ message: localize('com_ui_project_updated'),
+ severity: NotificationSeverity.SUCCESS,
+ showIcon: true,
+ });
+ },
+ onError: () =>
+ showToast({
+ message: localize('com_ui_project_update_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ }),
+ },
+ );
+ };
+
+ const request = async (nextPage: boolean) => {
+ requestInFlight.current = true;
+ try {
+ const result = await (nextPage ? fetchNextPage() : refetch());
+ failedPageRequest.current = nextPage && result.isError;
+ } finally {
+ requestInFlight.current = false;
+ }
+ };
+
+ const trigger: t.MenuItemProps = {
+ label: localize('com_ui_change_project'),
+ icon: <FolderInput className={iconClass} aria-hidden="true" />,
+ };
+ /** A disabled query still exposes cached data, and every row of the project page mounts this hook,
+ * so a closed menu builds nothing: the items exist only while their menu is open. */
+ if (!enabled) {
+ return { ...trigger, subItems: [{ label: localize('com_ui_loading'), disabled: true }] };
+ }
+
+ const projects = data?.pages.flatMap((page) => page.projects) ?? [];
+ const subItems: t.MenuItemProps[] = [];
+ if (projects.length > 0) {
+ for (const project of projects) {
+ const isCurrent = project._id === chatProjectId;
+ const isPendingTarget = pending && pendingProjectId === project._id;
+ let icon = <Folder className={iconClass} aria-hidden="true" />;
+ if (isPendingTarget) {
+ icon = <Spinner className="size-4" />;
+ } else if (isCurrent) {
+ icon = <Check className={iconClass} aria-hidden="true" />;
+ }
+ subItems.push({
+ id: rowId(`project-${project._id}`),
+ label: project.name,
+ /** The current project stays in the arrow-key order, which a disabled item would leave. */
+ onClick: () => {
+ if (!isCurrent) {
+ assign(project._id);
+ }
+ },
+ disabled: pending,
+ ariaChecked: isCurrent,
+ ariaRole: 'menuitemradio',
+ icon,
+ });
+ }
+ } else {
+ let statusKey: Parameters<typeof localize>[0] = 'com_ui_loading';
+ if (isError && !busy) {
+ statusKey = 'com_ui_projects_load_error';
+ } else if (data != null && !isError) {
+ statusKey = 'com_ui_no_projects';
+ }
+ subItems.push({ id: rowId('status'), label: localize(statusKey), disabled: true });
+ }
+
+ /** One paging row with one id, whatever it currently says, so the focus the user put on it
+ * follows it from "Load more" to the loading state to "Retry". While a request runs it stays
+ * focusable and does nothing: a disabled item would be dropped from keyboard navigation. */
+ if (isError && !busy) {
+ if (projects.length > 0) {
+ subItems.push({
+ id: rowId('status'),
+ label: localize('com_ui_projects_load_error'),
+ disabled: true,
+ });
+ }
+ subItems.push({
+ id: rowId('paging'),
+ label: localize('com_ui_retry'),
+ onClick: () => request(failedPageRequest.current),
+ hideOnClick: false,
+ });
+ } else if (projects.length > 0 && (hasNextPage || isError)) {
+ subItems.push({
+ id: rowId('paging'),
+ label: localize(busy ? 'com_ui_loading' : 'com_ui_load_more'),
+ onClick: busy ? undefined : () => request(true),
+ hideOnClick: false,
+ });
+ }
+
+ if (chatProjectId != null) {
+ subItems.push(
+ { separate: true },
+ {
+ id: rowId('remove'),
+ label: localize('com_ui_remove_from_project'),
+ onClick: () => assign(null),
+ disabled: pending,
+ icon:
+ pending && pendingProjectId === null ? (
+ <Spinner className="size-4" />
+ ) : (
+ <FolderX className={iconClass} aria-hidden="true" />
+ ),
+ },
+ );
+ }
+
+ return { ...trigger, subItems };
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index c5f7a04caf..10b2879b68 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2504,6 +2504,7 @@
"com_ui_project_update_error": "Failed to update project assignment",
"com_ui_project_updated": "Project assignment updated",
"com_ui_projects": "Projects",
+ "com_ui_projects_load_error": "Could not load projects",
"com_ui_prompt": "Prompt",
"com_ui_prompt_category_selector_aria": "Prompt's category selector",
"com_ui_prompt_delete_confirm": "Are you sure you want to delete the '{{0}}' prompt?",
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 144c42dd84..98f88944de 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -797,11 +797,6 @@
"count": 4
}
},
- "client/src/components/Conversations/ConvoOptions/ProjectButton.tsx": {
- "shadcn/no-restyle": {
- "count": 11
- }
- },
"client/src/components/Conversations/ConvoOptions/ShareButton.tsx": {
"shadcn/no-restyle": {
"count": 10
diff --git a/packages/client/src/common/menus.ts b/packages/client/src/common/menus.ts
index 99f98c1a49..459aa25b4e 100644
--- a/packages/client/src/common/menus.ts
+++ b/packages/client/src/common/menus.ts
@@ -29,6 +29,8 @@ export interface MenuItemProps {
ariaControls?: string;
ariaLabel?: string;
ariaChecked?: boolean;
+ /** Role of an item that has `ariaChecked`: a checkbox by default, a radio for an exclusive choice. */
+ ariaRole?: 'menuitemcheckbox' | 'menuitemradio';
ref?: React.Ref<any>;
className?: string;
render?:
diff --git a/packages/client/src/components/DropdownPopup.spec.tsx b/packages/client/src/components/DropdownPopup.spec.tsx
index 5fe9f47875..1b031bbdef 100644
--- a/packages/client/src/components/DropdownPopup.spec.tsx
+++ b/packages/client/src/components/DropdownPopup.spec.tsx
@@ -1,8 +1,21 @@
import React, { useRef, useState } from 'react';
import * as Ariakit from '@ariakit/react';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react';
import DropdownPopup from './DropdownPopup';
+/** `user-event` resolves its own copy of `@testing-library/dom`, so the wrapper React Testing
+ * Library installs around events never reaches it: Ariakit's animation-frame updates then land
+ * outside `act`. Wrapping each interaction here keeps them inside it. */
+const press = (user: ReturnType<typeof userEvent.setup>, keys: string) =>
+ act(async () => {
+ await user.keyboard(keys);
+ });
+const click = (user: ReturnType<typeof userEvent.setup>, element: HTMLElement) =>
+ act(async () => {
+ await user.click(element);
+ });
+
describe('DropdownPopup', () => {
it('restores pointer events on portaled menus so they stay clickable inside modal dialogs', () => {
// A modal Radix dialog (OGDialog) sets `pointer-events: none` on body and only
@@ -33,6 +46,272 @@ describe('DropdownPopup', () => {
unmount();
document.body.style.pointerEvents = '';
});
+ describe('submenu', () => {
+ /** Keyboard, not pointer: jsdom has no layout, so Ariakit's hover tracking between a trigger
+ * and its submenu is meaningless here, while Enter takes the same click path as a pointer pick. */
+ const openSubmenu = async (onPick: jest.Mock, hideOnClick?: boolean) => {
+ const user = userEvent.setup();
+ const onOpenChange = jest.fn();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownPopup
+ menuId="submenu-test"
+ isOpen={open}
+ setIsOpen={(next) => {
+ onOpenChange(next);
+ setOpen(next);
+ }}
+ unmountOnHide={true}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ { label: 'Rename', onClick: jest.fn() },
+ {
+ label: 'Change project',
+ subItems: [{ label: 'Alpha', onClick: onPick, hideOnClick }],
+ },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+ await press(user, '{ArrowDown}{ArrowDown}');
+ expect(await screen.findByRole('menuitem', { name: /Change project/ })).toHaveFocus();
+ await press(user, '{ArrowRight}');
+ const item = await screen.findByRole('menuitem', { name: 'Alpha' });
+ await waitFor(() => expect(item).toHaveFocus());
+ return { user, item, onOpenChange };
+ };
+
+ it('closes the whole menu when a submenu item is picked', async () => {
+ const onPick = jest.fn();
+ const { user, onOpenChange } = await openSubmenu(onPick);
+
+ await press(user, '{Enter}');
+
+ expect(onPick).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onOpenChange).toHaveBeenLastCalledWith(false));
+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());
+ });
+
+ it('reaches the submenu trigger with the arrow keys and opens it with ArrowRight', async () => {
+ const user = userEvent.setup();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownPopup
+ menuId="submenu-keys"
+ isOpen={open}
+ setIsOpen={setOpen}
+ unmountOnHide={true}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ { label: 'Rename', onClick: jest.fn() },
+ { label: 'Change project', subItems: [{ label: 'Alpha', onClick: jest.fn() }] },
+ { label: 'Delete', onClick: jest.fn() },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+ await press(user, '{ArrowDown}');
+ expect(await screen.findByRole('menuitem', { name: 'Rename' })).toHaveFocus();
+ await press(user, '{ArrowDown}');
+ expect(screen.getByRole('menuitem', { name: /Change project/ })).toHaveFocus();
+
+ await press(user, '{ArrowRight}');
+ expect(await screen.findByRole('menuitem', { name: 'Alpha' })).toBeInTheDocument();
+ });
+
+ it('opens only the submenu whose trigger was activated when a menu has several', async () => {
+ const user = userEvent.setup();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownPopup
+ menuId="two-submenus"
+ isOpen={open}
+ setIsOpen={setOpen}
+ unmountOnHide={true}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ { label: 'Bookmarks', subItems: [{ label: 'Work', onClick: jest.fn() }] },
+ { label: 'Change project', subItems: [{ label: 'Alpha', onClick: jest.fn() }] },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+ await press(user, '{ArrowDown}{ArrowDown}');
+ expect(await screen.findByRole('menuitem', { name: /Change project/ })).toHaveFocus();
+ await press(user, '{ArrowRight}');
+
+ expect(await screen.findByRole('menuitem', { name: 'Alpha' })).toBeInTheDocument();
+ expect(screen.queryByRole('menuitem', { name: 'Work' })).not.toBeInTheDocument();
+ });
+
+ it('keeps a custom render on the submenu trigger able to open its submenu', async () => {
+ const user = userEvent.setup();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownPopup
+ menuId="custom-trigger"
+ isOpen={open}
+ setIsOpen={setOpen}
+ unmountOnHide={true}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ { label: 'Rename', onClick: jest.fn() },
+ {
+ label: 'Change project',
+ render: (props) => <button {...props} />,
+ subItems: [{ label: 'Alpha', onClick: jest.fn() }],
+ },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+ await press(user, '{ArrowDown}{ArrowDown}');
+ const trigger = await screen.findByRole('menuitem', { name: /Change project/ });
+ expect(trigger.tagName).toBe('BUTTON');
+ expect(trigger).toHaveFocus();
+
+ await press(user, '{ArrowRight}');
+ expect(await screen.findByRole('menuitem', { name: 'Alpha' })).toBeInTheDocument();
+ });
+
+ it('hides the submenu too when a pick closes a menu that stays mounted', async () => {
+ const user = userEvent.setup();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownPopup
+ menuId="stays-mounted"
+ isOpen={open}
+ setIsOpen={setOpen}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ { label: 'Rename', onClick: jest.fn() },
+ { label: 'Change project', subItems: [{ label: 'Alpha', onClick: jest.fn() }] },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+ await press(user, '{ArrowDown}{ArrowDown}');
+ expect(await screen.findByRole('menuitem', { name: /Change project/ })).toHaveFocus();
+ await press(user, '{ArrowRight}');
+ const alpha = await screen.findByRole('menuitem', { name: 'Alpha' });
+ await waitFor(() => expect(alpha).toHaveFocus());
+
+ await press(user, '{Enter}');
+
+ await waitFor(() => expect(screen.queryByRole('menuitem', { name: 'Rename' })).toBeNull());
+ expect(screen.queryByRole('menuitem', { name: 'Alpha' })).toBeNull();
+ });
+
+ it('exposes an item as a radio when it asks for one', async () => {
+ const user = userEvent.setup();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownPopup
+ menuId="radio-items"
+ isOpen={open}
+ setIsOpen={setOpen}
+ unmountOnHide={true}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ { label: 'Alpha', ariaChecked: true, ariaRole: 'menuitemradio' },
+ { label: 'Beta', ariaChecked: false, ariaRole: 'menuitemradio' },
+ { label: 'Pin', ariaChecked: false },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+
+ expect(await screen.findByRole('menuitemradio', { name: 'Alpha' })).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect(screen.getByRole('menuitemradio', { name: 'Beta' })).toHaveAttribute(
+ 'aria-checked',
+ 'false',
+ );
+ expect(screen.getByRole('menuitemcheckbox', { name: 'Pin' })).toBeInTheDocument();
+ });
+
+ it('keeps the same element for an item with an id when items are added before it', async () => {
+ const user = userEvent.setup();
+ function Example() {
+ const [open, setOpen] = useState(false);
+ const [count, setCount] = useState(1);
+ const projects = Array.from({ length: count }, (_, i) => ({
+ id: `project-${i}`,
+ label: `Project ${i}`,
+ onClick: jest.fn(),
+ }));
+ return (
+ <DropdownPopup
+ menuId="stable-focus"
+ isOpen={open}
+ setIsOpen={setOpen}
+ unmountOnHide={true}
+ trigger={<Ariakit.MenuButton>Options</Ariakit.MenuButton>}
+ items={[
+ ...projects,
+ {
+ id: 'paging',
+ label: 'Load more',
+ hideOnClick: false,
+ onClick: () => setCount((n) => n + 2),
+ },
+ ]}
+ />
+ );
+ }
+ render(<Example />);
+
+ await click(user, screen.getByRole('button', { name: 'Options' }));
+ await press(user, '{ArrowDown}{ArrowDown}');
+ const loadMore = await screen.findByRole('menuitem', { name: 'Load more' });
+ expect(loadMore).toHaveFocus();
+
+ await press(user, '{Enter}');
+
+ expect(await screen.findByRole('menuitem', { name: 'Project 2' })).toBeInTheDocument();
+ /** Keyed by position, the appended project took over this element and the user's next Enter
+ * would have picked it. The element the user activated has to still be the paging control. */
+ expect(screen.getByRole('menuitem', { name: 'Load more' })).toBe(loadMore);
+ expect(loadMore.isConnected).toBe(true);
+ });
+
+ it('keeps the menu open when a submenu item opts out of hiding', async () => {
+ const onPick = jest.fn();
+ const { user, onOpenChange } = await openSubmenu(onPick, false);
+
+ await press(user, '{Enter}');
+
+ expect(onPick).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).not.toHaveBeenCalledWith(false);
+ expect(screen.getByRole('menuitem', { name: 'Rename' })).toBeInTheDocument();
+ });
+ });
+
it('focuses an externally opened menu', async () => {
function Example() {
const [open, setOpen] = useState(false);
diff --git a/packages/client/src/components/DropdownPopup.tsx b/packages/client/src/components/DropdownPopup.tsx
index c42b713cca..2580b29dbf 100644
--- a/packages/client/src/components/DropdownPopup.tsx
+++ b/packages/client/src/components/DropdownPopup.tsx
@@ -36,7 +36,10 @@ type MenuProps = Omit<
DropdownProps,
'trigger' | 'isOpen' | 'setIsOpen' | 'focusLoop' | 'mountByState'
> &
- Ariakit.MenuProps;
+ Ariakit.MenuProps & {
+ /** Closes the outermost menu, so a pick made inside a submenu does not leave its parent open. */
+ hideAll?: () => void;
+ };
const DropdownPopup: React.FC<DropdownProps> = ({
trigger,
@@ -53,18 +56,19 @@ const DropdownPopup: React.FC<DropdownProps> = ({
menu.setAutoFocusOnShow(true);
}
}, [isOpen, autoFocusOnShow, menu]);
+ const hideAll = () => menu.hide();
if (mountByState) {
return (
<Ariakit.MenuProvider store={menu}>
{trigger}
- {isOpen && <Menu {...props} autoFocusOnShow={autoFocusOnShow} />}
+ {isOpen && <Menu {...props} hideAll={hideAll} autoFocusOnShow={autoFocusOnShow} />}
</Ariakit.MenuProvider>
);
}
return (
<Ariakit.MenuProvider store={menu}>
{trigger}
- <Menu {...props} autoFocusOnShow={autoFocusOnShow} />
+ <Menu {...props} hideAll={hideAll} autoFocusOnShow={autoFocusOnShow} />
</Ariakit.MenuProvider>
);
};
@@ -84,12 +88,22 @@ const Menu: React.FC<MenuProps> = ({
finalFocus,
unmountOnHide,
preserveTabOrder,
+ hideAll,
style,
...props
}) => {
- const menuStore = Ariakit.useMenuStore();
const menu = Ariakit.useMenuContext();
const zIndex = usePopoverZIndex();
+ /** An item with an id is keyed by it, so a focused row stays the same element when items are added
+ * before it. A missing or repeated id falls back to the position, which cannot collide. */
+ const seenIds = new Set<string>();
+ const itemKey = (item: t.MenuItemProps, index: number) => {
+ if (item.id != null && !seenIds.has(item.id)) {
+ seenIds.add(item.id);
+ return `${keyPrefix ?? ''}${item.id}`;
+ }
+ return `${keyPrefix ?? ''}${index}-${item.id ?? ''}`;
+ };
return (
<Ariakit.Menu
id={menuId}
@@ -124,49 +138,21 @@ const Menu: React.FC<MenuProps> = ({
}
if (subItems && subItems.length > 0) {
return (
- <Ariakit.MenuProvider
- store={menuStore}
- key={`${keyPrefix ?? ''}${index}-${item.id ?? ''}-provider`}
- >
- <Ariakit.MenuButton
- className={cn(
- 'group text-text-primary hover:bg-surface-hover focus:bg-surface-hover flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-3.5 text-sm outline-hidden md:px-2.5 md:py-2',
- disabledInkClasses,
- itemClassName,
- )}
- disabled={item.disabled}
- id={item.id}
- render={item.render}
- ref={item.ref}
- // hideOnClick={item.hideOnClick}
- >
- <span className="flex items-center gap-2">
- {item.icon != null && (
- <span
- className={cn('size-theme-icon mr-2 [&>svg]:size-full', iconClassName)}
- aria-hidden="true"
- >
- {item.icon}
- </span>
- )}
- {item.label}
- </span>
- <Ariakit.MenuButtonArrow className="stroke-1 text-base opacity-75" />
- </Ariakit.MenuButton>
- <Menu
- items={subItems}
- menuId={`${menuId}-${index}`}
- key={`${keyPrefix ?? ''}${index}-${item.id ?? ''}`}
- gutter={12}
- portal={true}
- />
- </Ariakit.MenuProvider>
+ <SubMenuItem
+ key={itemKey(item, index)}
+ item={item}
+ subItems={subItems}
+ menuId={`${menuId}-${index}`}
+ hideAll={hideAll ?? (() => menu?.hide())}
+ iconClassName={iconClassName}
+ itemClassName={itemClassName}
+ />
);
}
return (
<Ariakit.MenuItem
- key={`${keyPrefix ?? ''}${index}-${item.id ?? ''}`}
+ key={itemKey(item, index)}
id={item.id}
className={cn(
'group text-text-primary hover:bg-surface-hover focus:bg-surface-hover flex w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-3.5 text-sm outline-hidden md:px-2.5 md:py-2',
@@ -182,7 +168,9 @@ const Menu: React.FC<MenuProps> = ({
aria-controls={item.ariaControls}
aria-label={item.ariaLabel}
aria-checked={item.ariaChecked}
- {...(item.ariaChecked !== undefined ? { role: 'menuitemcheckbox' } : {})}
+ {...(item.ariaChecked !== undefined
+ ? { role: item.ariaRole ?? 'menuitemcheckbox' }
+ : {})}
onClick={(event) => {
event.preventDefault();
if (item.onClick) {
@@ -191,6 +179,10 @@ const Menu: React.FC<MenuProps> = ({
if (item.hideOnClick === false) {
return;
}
+ if (hideAll) {
+ hideAll();
+ return;
+ }
menu?.hide();
}}
>
@@ -215,4 +207,60 @@ const Menu: React.FC<MenuProps> = ({
);
};
+/** Owns its store: sharing one across siblings would open every submenu of a menu together. */
+const SubMenuItem: React.FC<{
+ item: t.MenuItemProps;
+ subItems: t.MenuItemProps[];
+ menuId: string;
+ hideAll: () => void;
+ iconClassName?: string;
+ itemClassName?: string;
+}> = ({ item, subItems, menuId, hideAll, iconClassName, itemClassName }) => {
+ const store = Ariakit.useMenuStore();
+ /** The parent's `hideAll` closes only its own store: a submenu that stays mounted would be left
+ * open in its portal, so this store is closed with it. */
+ const hideSubmenuAndParents = () => {
+ store.hide();
+ hideAll();
+ };
+ return (
+ <Ariakit.MenuProvider store={store}>
+ {/* A submenu trigger is a MenuItem and a MenuButton in one element: as a bare
+ MenuButton it is not part of the parent menu's arrow-key order. */}
+ <Ariakit.MenuItem
+ className={cn(
+ 'group text-text-primary hover:bg-surface-hover focus:bg-surface-hover flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-3.5 text-sm outline-hidden md:px-2.5 md:py-2',
+ disabledInkClasses,
+ itemClassName,
+ )}
+ disabled={item.disabled}
+ id={item.id}
+ ref={item.ref}
+ render={<Ariakit.MenuButton render={item.render} />}
+ >
+ <span className="flex items-center gap-2">
+ {item.icon != null && (
+ <span
+ className={cn('size-theme-icon mr-2 [&>svg]:size-full', iconClassName)}
+ aria-hidden="true"
+ >
+ {item.icon}
+ </span>
+ )}
+ {item.label}
+ </span>
+ <Ariakit.MenuButtonArrow className="stroke-1 text-base opacity-75" />
+ </Ariakit.MenuItem>
+ <Menu
+ items={subItems}
+ menuId={menuId}
+ gutter={20}
+ portal={true}
+ hideAll={hideSubmenuAndParents}
+ style={{ maxHeight: 'min(24rem, var(--popover-available-height, 24rem))' }}
+ />
+ </Ariakit.MenuProvider>
+ );
+};
+
export default DropdownPopup;