🛰️ feat: Status on the Avatar, a Finished Group, and Project Chats in the Sidebar List

- Running chats ring their avatar instead of a trailing spinner, so the row menu stays reachable mid-run.
- A reply that lands unseen lifts its chat into a Finished group under Running until it is opened; chats marked unread by hand keep their date.
- Running and Finished headings show their counts and announce them.
- Project chats now list under Chats with their folder badge; a persisted Show project chats toggle in the chat list menu restores the project-only view.
- Badges read project names from the loaded project list before fetching one by id.
- Spinner takes a strokeWidth for the thin ring.
This commit is contained in:
Danny Avila 2026-10-03 07:20:57 -04:00 • committed by Danny Avila
parent 2b4e5b5acd
commit 10e9cb90e7
19 changed files with 623 additions and 105 deletions

View file

@ -1,6 +1,6 @@
import { memo, useCallback, useId, useMemo, useRef, useState } from 'react';
import * as Ariakit from '@ariakit/react';
import { useAtomValue, useSetAtom } from 'jotai';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
import { BookmarkFilledIcon, BookmarkIcon } from '@radix-ui/react-icons';
import { TooltipAnchor, buttonVariants, usePopoverZIndex } from '@librechat/client';
import { alternateName, PermissionTypes, Permissions } from 'librechat-data-provider';
@ -13,6 +13,7 @@ import {
Check,
ChevronRight,
Clock,
Folder,
ListFilter,
MessagesSquare,
Paperclip,
@ -35,6 +36,7 @@ import {
resetChatFiltersAtom,
selectableBookmarks,
setChatFilterStatusAtom,
showProjectChatsAtom,
sortFieldsFor,
toggleChatFilterTagAtom,
} from './chatFilters';
@ -785,6 +787,7 @@ const ChatFilterMenu = () => {
const facetCount = useAtomValue(facetFilterCountAtom);
const setStatus = useSetAtom(setChatFilterStatusAtom);
const setSort = useSetAtom(chatSortAtom);
const [showProjectChats, setShowProjectChats] = useAtom(showProjectChatsAtom);
const resetFilters = useSetAtom(resetChatFiltersAtom);
const resetAllFacets = useSetAtom(resetFacetsAtom);
@ -977,6 +980,19 @@ const ChatFilterMenu = () => {
>
<FilterFacets showBookmarks={hasAccessToBookmarks} searchRef={facetSearchRef} />
</PropertyRow>
{/* The archive and search already list every chat, project or not. */}
{status === 'active' && (
<>
<Ariakit.MenuSeparator className="border-border-medium my-1 h-px" />
<Toggle
label={localize('com_ui_show_project_chats')}
icon={<Folder className="size-4" />}
checked={showProjectChats}
onSelect={() => setShowProjectChats(!showProjectChats)}
/>
</>
)}
</Ariakit.Menu>
</Ariakit.MenuProvider>
);

View file

@ -32,7 +32,13 @@ import {
useEffectiveProjectId,
useUnpinDroppedConversation,
} from './dnd';
import { unlistedRunningIds, RUNNING_CHATS_GROUP, groupConversationsWithRunning } from './running';
import {
isStatusGroup,
unlistedRunningIds,
RUNNING_CHATS_GROUP,
FINISHED_CHATS_GROUP,
groupConversationsByStatus,
} from './running';
import { useLocalize, TranslationKeys, useElementSize, useOuterScrollWindow } from '~/hooks';
import { useActiveJobs, useRunningConversationsQuery } from '~/data-provider';
import { facetFilterCountAtom, resetFacetsAtom } from './facets';
@ -167,26 +173,42 @@ const ChatsHeader: FC<ChatsHeaderProps> = memo(({ isExpanded, onToggle, trailing
ChatsHeader.displayName = 'ChatsHeader';
const DateLabel: FC<{ groupName: string; isFirst?: boolean; isAlphabetical?: boolean }> = memo(
({ groupName, isFirst, isAlphabetical = false }) => {
type DateLabelProps = {
groupName: string;
isFirst?: boolean;
isAlphabetical?: boolean;
/** Status groups show how many chats they hold; date groups leave this out. */
count?: number;
};
const statusSectionLabels: Record<string, TranslationKeys> = {
[RUNNING_CHATS_GROUP]: 'com_a11y_chats_running_section',
[FINISHED_CHATS_GROUP]: 'com_a11y_chats_finished_section',
};
const DateLabel: FC<DateLabelProps> = memo(
({ groupName, isFirst, isAlphabetical = false, count }) => {
const localize = useLocalize();
const displayName = localize(groupName as TranslationKeys) || groupName;
const statusLabel = statusSectionLabels[groupName] as TranslationKeys | undefined;
let ariaLabel: string;
if (statusLabel) {
ariaLabel = localize(statusLabel, { count: count ?? 0 });
} else if (isAlphabetical) {
ariaLabel = localize('com_a11y_chats_alpha_section', { letter: displayName });
} else {
ariaLabel = localize('com_a11y_chats_date_section', { date: displayName });
}
return (
<h2
aria-label={
groupName === RUNNING_CHATS_GROUP
? localize('com_a11y_chats_running_section')
: localize(
isAlphabetical ? 'com_a11y_chats_alpha_section' : 'com_a11y_chats_date_section',
isAlphabetical ? { letter: displayName } : { date: displayName },
)
}
aria-label={ariaLabel}
className={cn(
'text-text-secondary pt-0.5 pl-1 text-xs',
isFirst === true ? 'mt-0' : 'mt-1.5',
)}
>
{displayName}
{count != null && <span className="text-text-tertiary"> · {count}</span>}
</h2>
);
},
@ -195,8 +217,8 @@ const DateLabel: FC<{ groupName: string; isFirst?: boolean; isAlphabetical?: boo
DateLabel.displayName = 'DateLabel';
type FlattenedItem =
| { type: 'header'; groupName: string }
| { type: 'convo'; convo: TConversation; inRunningGroup: boolean }
| { type: 'header'; groupName: string; count?: number }
| { type: 'convo'; convo: TConversation }
| { type: 'loading' };
const Conversations: FC<ConversationsProps> = ({
@ -341,7 +363,7 @@ const Conversations: FC<ConversationsProps> = ({
/** The archive keeps its server order, while search still promotes active matches. */
const groupedConversations = useMemo(
() =>
groupConversationsWithRunning(
groupConversationsByStatus(
datedConversations,
activeJobIds,
{
@ -402,9 +424,12 @@ const Conversations: FC<ConversationsProps> = ({
const items: FlattenedItem[] = [];
if (isChatsExpanded) {
groupedConversations.forEach(([groupName, convos]) => {
const inRunningGroup = groupName === RUNNING_CHATS_GROUP;
items.push({ type: 'header', groupName });
items.push(...convos.map((convo) => ({ type: 'convo' as const, convo, inRunningGroup })));
items.push({
type: 'header',
groupName,
count: isStatusGroup(groupName) ? convos.length : undefined,
});
items.push(...convos.map((convo) => ({ type: 'convo' as const, convo })));
});
if (isLoading) {
@ -503,6 +528,7 @@ const Conversations: FC<ConversationsProps> = ({
groupName={item.groupName}
isFirst={index === 0}
isAlphabetical={isAlphabeticalSort(sort.field)}
count={item.count}
/>
</MeasuredRow>
);
@ -517,7 +543,7 @@ const Conversations: FC<ConversationsProps> = ({
retainView={moveToTop}
toggleNav={toggleNav}
isGenerating={isGenerating}
showProjectBadge={item.inRunningGroup}
showProjectBadge
draggable
/>
</MeasuredRow>

View file

@ -277,12 +277,6 @@ function Conversation({
isShiftHeld: isActiveConvo ? isShiftHeld : false,
};
const generatingSpinner = (
<span role="img" aria-label={localize('com_ui_generating')}>
<Spinner className="text-text-primary h-5 w-5 shrink-0" />
</span>
);
/* The slot takes its width from the row's hover, not from its content. The
* overflow menu mounts a tick after the pointer arrives (see `ConvoActions`),
* and a content-sized slot grew at that moment, pulling the unpin badge a
@ -294,10 +288,7 @@ function Conversation({
let actionWidthClassName = isSmallScreen
? 'group-focus-within:w-9 group-hover:w-9'
: 'group-focus-within:w-7 group-hover:w-7';
if (isGenerating) {
actionVisibilityClassName = 'pointer-events-none w-5 scale-x-100 opacity-100';
actionWidthClassName = '';
} else if (isPopoverActive || isActiveConvo || isSmallScreen) {
if (isPopoverActive || isActiveConvo || isSmallScreen) {
/** Touch has no hover, so a reveal-on-hover menu is unreachable there. */
actionVisibilityClassName = 'pointer-events-auto scale-x-100 opacity-100';
/** Shift over the active row swaps the menu for archive and delete. */
@ -308,12 +299,9 @@ function Conversation({
}
}
let actionContent: React.ReactNode = null;
if (isGenerating) {
actionContent = generatingSpinner;
} else if (!renaming) {
actionContent = <ConvoActions {...convoOptionsProps} hasInteracted={hasInteracted} />;
}
const actionContent = renaming ? null : (
<ConvoActions {...convoOptionsProps} hasInteracted={hasInteracted} />
);
return (
<div
@ -359,6 +347,7 @@ function Conversation({
isHovered={isHovered}
isSharedBadgeVisible={isSharedBadgeVisible}
isUnseen={isUnseen}
isGenerating={isGenerating}
title={title}
onRename={handleRename}
isSmallScreen={isSmallScreen}
@ -366,14 +355,33 @@ function Conversation({
keyShortcuts={keyShortcuts}
describedBy={projectBadgeProjectId ? projectLabelId : undefined}
>
<ConversationEndpointIcon conversation={conversation} size={20} context="menu-item" />
{/* Status sits on the avatar so the row's trailing edge stays free for its badges
and menu. The ring is 34px around the 20px icon: offset by half the difference. */}
<span className="relative flex size-5 shrink-0 items-center justify-center">
<ConversationEndpointIcon conversation={conversation} size={20} context="menu-item" />
{isGenerating && (
<Spinner
size={34}
strokeWidth={1.9}
bgOpacity={0.14}
className="text-text-primary pointer-events-none absolute -top-[7px] -left-[7px]"
/>
)}
{isUnseen && !isGenerating && (
/* `ConvoLink`'s aria-label carries the text equivalent of the ring and the dot. */
<span
aria-hidden="true"
className={cn(
'bg-status-info pointer-events-none absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2',
isActiveConvo || isPopoverActive
? 'ring-surface-active-alt'
: 'ring-surface-primary-alt group-hover:ring-surface-active-alt',
)}
/>
)}
</span>
</ConvoLink>
)}
{isUnseen && (
/* `ConvoLink`'s aria-label carries the text equivalent, so the dot itself stays
decorative rather than announcing a second time outside the row's button. */
<span className="bg-status-info mr-1 size-2 shrink-0 rounded-full" aria-hidden="true" />
)}
{isSharedBadgeVisible && (
<Link2 className="icon-sm text-text-secondary mr-1 shrink-0" aria-hidden="true" />
)}

View file

@ -9,6 +9,8 @@ interface ConvoLinkProps {
isHovered: boolean;
isSharedBadgeVisible: boolean;
isUnseen: boolean;
/** The avatar's ring is decorative, so the label carries the running state. */
isGenerating?: boolean;
title: string | null;
onRename: () => void;
isSmallScreen: boolean;
@ -42,6 +44,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
isHovered,
isSharedBadgeVisible,
isUnseen,
isGenerating = false,
title,
onRename,
isSmallScreen,
@ -131,7 +134,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
<button
type="button"
className={cn(
'focus-visible:ring-text-primary flex w-full min-w-0 grow cursor-pointer items-center gap-2 overflow-hidden rounded-lg px-2 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-inset',
'focus-visible:ring-text-primary flex w-full min-w-0 grow cursor-pointer items-center gap-2 self-stretch overflow-hidden rounded-lg px-2 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-inset',
isActiveConvo || isPopoverActive ? 'bg-surface-active-alt' : '',
)}
aria-current={isActiveConvo ? 'page' : undefined}
@ -144,13 +147,16 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
})
: localize('com_ui_conversation_label', {
title: title || localize('com_ui_untitled'),
})) + (isUnseen ? `, ${localize('com_ui_unread')}` : '')
})) +
(isGenerating ? `, ${localize('com_ui_generating')}` : '') +
(isUnseen && !isGenerating ? `, ${localize('com_ui_unread')}` : '')
}
>
{children}
<span
ref={titleRef}
className={cn(
isUnseen && !isGenerating && 'font-semibold',
'min-w-0 flex-1 overflow-hidden [mask-size:100%_100%] [mask-position:left] [mask-repeat:no-repeat] [text-align:start] whitespace-nowrap [transition-property:mask-size] [transition-duration:0ms] [transition-timing-function:linear] [--convo-title-fade-width:24px] [--convo-title-reveal-duration:800ms] [&:dir(rtl)]:[mask-position:right]',
isOverflowing &&
'[mask-image:linear-gradient(to_right,currentColor_calc(100%_-_var(--convo-title-fade-width)),transparent)] [&:dir(rtl)]:[mask-image:linear-gradient(to_left,currentColor_calc(100%_-_var(--convo-title-fade-width)),transparent)]',

View file

@ -1,16 +1,14 @@
import { memo } from 'react';
import { Folder } from 'lucide-react';
import { useProjectQuery } from '~/data-provider';
import { useProjectName } from '~/data-provider';
import { useLocalize } from '~/hooks';
/** Marks a row listed outside its project, such as a project chat in the Running group,
* so it reads as filed elsewhere rather than as a chat with no project. */
/** Marks a row listed outside its project, such as a project chat under Chats, so it
* reads as filed elsewhere rather than as a chat with no project. */
function ProjectBadge({ projectId, labelId }: { projectId: string; labelId: string }) {
const localize = useLocalize();
const { data: project } = useProjectQuery(projectId);
const label = project?.name
? localize('com_ui_in_project', { name: project.name })
: localize('com_ui_project');
const name = useProjectName(projectId);
const label = name ? localize('com_ui_in_project', { name }) : localize('com_ui_project');
return (
<span

View file

@ -565,7 +565,9 @@ describe('Conversations: Running lists chats outside the Chats list', () => {
).toBeInTheDocument();
const rows = screen.getAllByTestId('convo');
expect(rows.map((row) => row.textContent)).toEqual(['Project chat', 'Idle chat']);
expect(rows.map((row) => row.getAttribute('data-project-badge'))).toEqual(['true', 'false']);
/* Project chats list under Chats too, so every row may badge; the row draws it only
for a chat that is filed in a project. */
expect(rows.map((row) => row.getAttribute('data-project-badge'))).toEqual(['true', 'true']);
});
it('fetches nothing under a sort that has no Running group', () => {

View file

@ -0,0 +1,142 @@
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { render, screen, fireEvent } from '@testing-library/react';
import type { TConversation } from 'librechat-data-provider';
let mockIsUnseen = false;
jest.mock('@librechat/client', () => ({
useMediaQuery: () => false,
useToastContext: () => ({ showToast: jest.fn() }),
Spinner: ({ className }: { className?: string }) => (
<svg data-testid="status-ring" className={className} />
),
Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
<button {...props}>{children}</button>
),
}));
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
useNavigateToConvo: () => ({ navigateToConvo: jest.fn() }),
useShiftKey: () => false,
}));
jest.mock('~/data-provider', () => ({
useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),
useUpdateConversationMutation: () => ({ mutateAsync: jest.fn() }),
usePinConversationMutation: () => ({ mutate: jest.fn() }),
useProjectName: () => 'Scheduling',
}));
jest.mock('react-router-dom', () => ({
useParams: () => ({ conversationId: 'other-convo' }),
}));
jest.mock('recoil', () => ({
useRecoilValue: () => [],
}));
jest.mock('~/store', () => ({
__esModule: true,
default: { allConversationsSelector: 'allConversationsSelector' },
}));
jest.mock('~/utils', () => ({
cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
logger: { error: jest.fn() },
setDocumentTitle: jest.fn(),
isConversationUnseen: () => mockIsUnseen,
}));
jest.mock('../ConvoOptions', () => ({
ConvoOptions: () => <div data-testid="convo-options" />,
}));
jest.mock('../ConversationEndpointIcon', () => ({
__esModule: true,
default: () => <div data-testid="convo-icon" />,
}));
jest.mock('../RenameForm', () => ({
__esModule: true,
default: () => <form data-testid="rename-form" />,
}));
import Conversation from '../Convo';
const conversation = {
conversationId: 'convo-1',
title: 'Tool Approval UI',
} as TConversation;
const renderRow = (props: { isGenerating?: boolean; convo?: TConversation } = {}) =>
render(
<DndProvider backend={HTML5Backend}>
<Conversation
conversation={props.convo ?? conversation}
retainView={jest.fn()}
toggleNav={jest.fn()}
isGenerating={props.isGenerating}
showProjectBadge
/>
</DndProvider>,
);
const rowButton = () => screen.getByRole('button', { name: /^com_ui_conversation_label/ });
const unreadDot = (container: HTMLElement) =>
container.querySelector('span[aria-hidden="true"].bg-status-info');
describe('Conversation row status', () => {
beforeEach(() => {
mockIsUnseen = false;
});
it('rings the avatar while running and keeps the row menu reachable', () => {
renderRow({ isGenerating: true });
const ring = screen.getByTestId('status-ring');
expect(rowButton()).toContainElement(ring);
expect(rowButton()).toHaveAccessibleName('com_ui_conversation_label, com_ui_generating');
/* The trailing slot used to hold the spinner in place of the menu, so a running chat
could not be renamed or archived from the list. */
fireEvent.mouseEnter(screen.getByTestId('convo-item'));
expect(screen.getByTestId('convo-options')).toBeInTheDocument();
});
it('marks an unseen reply on the avatar and in the title weight', () => {
mockIsUnseen = true;
const { container } = renderRow();
const dot = unreadDot(container);
expect(dot).not.toBeNull();
expect(rowButton()).toContainElement(dot as HTMLElement);
expect(rowButton()).toHaveAccessibleName('com_ui_conversation_label, com_ui_unread');
expect(screen.getByText('Tool Approval UI').parentElement).toHaveClass('font-semibold');
});
it('shows only the ring when a chat with an unseen reply runs again', () => {
mockIsUnseen = true;
const { container } = renderRow({ isGenerating: true });
expect(screen.getByTestId('status-ring')).toBeInTheDocument();
expect(unreadDot(container)).toBeNull();
expect(rowButton()).toHaveAccessibleName('com_ui_conversation_label, com_ui_generating');
expect(screen.getByText('Tool Approval UI').parentElement).not.toHaveClass('font-semibold');
});
it('draws no status on an idle, read chat', () => {
const { container } = renderRow();
expect(screen.queryByTestId('status-ring')).not.toBeInTheDocument();
expect(unreadDot(container)).toBeNull();
expect(rowButton()).toHaveAccessibleName('com_ui_conversation_label');
});
it('names the project of a filed chat listed under Chats', () => {
renderRow({ convo: { ...conversation, chatProjectId: 'project-1' } as TConversation });
expect(screen.getByTestId('convo-project-badge')).toHaveAttribute('title', 'com_ui_in_project');
expect(rowButton()).toHaveAccessibleDescription('com_ui_in_project');
});
});

View file

@ -4,12 +4,14 @@ import '@testing-library/jest-dom/extend-expect';
import { DateLabel } from '../Conversations';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, params?: Record<string, string>) => {
useLocalize: () => (key: string, params?: Record<string, string | number>) => {
const translations: Record<string, string> = {
com_a11y_chats_date_section: `Chats from ${params?.date ?? ''}`,
com_a11y_chats_alpha_section: `Chats with titles starting with ${params?.letter ?? ''}`,
com_a11y_chats_running_section: 'Running chats',
com_a11y_chats_running_section: `${params?.count} running chats`,
com_a11y_chats_finished_section: `${params?.count} finished chats with unread replies`,
com_ui_running_chats: 'Running',
com_ui_finished_chats: 'Finished',
com_ui_date_today: 'Today',
com_ui_date_yesterday: 'Yesterday',
com_ui_date_previous_7_days: 'Previous 7 days',
@ -24,13 +26,25 @@ describe('DateLabel', () => {
expect(screen.getByRole('heading', { level: 2, name: 'Chats from Today' })).toBeInTheDocument();
});
it('announces the running group without describing it as a date', () => {
render(<DateLabel groupName="com_ui_running_chats" />);
expect(screen.getByRole('heading', { level: 2, name: 'Running chats' })).toHaveTextContent(
'Running',
it('announces the running group with its count, not as a date', () => {
render(<DateLabel groupName="com_ui_running_chats" count={4} />);
expect(screen.getByRole('heading', { level: 2, name: '4 running chats' })).toHaveTextContent(
'Running · 4',
);
});
it('announces the finished group with its count', () => {
render(<DateLabel groupName="com_ui_finished_chats" count={2} />);
expect(
screen.getByRole('heading', { level: 2, name: '2 finished chats with unread replies' }),
).toHaveTextContent('Finished · 2');
});
it('leaves the count off date groups', () => {
render(<DateLabel groupName="com_ui_date_today" />);
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent(/^Today$/);
});
it('uses the alphabetical accessible name for title groups', () => {
render(<DateLabel groupName="A" isAlphabetical />);
expect(

View file

@ -4,7 +4,9 @@ import {
chatFilterCountAtom,
chatFilterStatusAtom,
chatFilterTagsAtom,
resetChatFiltersAtom,
selectableBookmarks,
showProjectChatsAtom,
} from '../chatFilters';
describe('chatFilterCountAtom', () => {
@ -26,6 +28,46 @@ describe('chatFilterCountAtom', () => {
});
});
describe('showProjectChatsAtom', () => {
afterEach(() => {
localStorage.clear();
});
it('lists project chats under Chats by default', () => {
expect(createStore().get(showProjectChatsAtom)).toBe(true);
});
it('counts hiding them as one change the menu badge and Reset own', () => {
const store = createStore();
store.set(showProjectChatsAtom, false);
expect(store.get(chatFilterCountAtom)).toBe(1);
store.set(resetChatFiltersAtom);
expect(store.get(showProjectChatsAtom)).toBe(true);
expect(store.get(chatFilterCountAtom)).toBe(0);
});
/** Storage is read once, when the module loads, which is what a new visit does. */
const onNextVisit = (stored: unknown): boolean => {
localStorage.setItem('chatListShowProjectChats', JSON.stringify(stored));
let value: boolean | undefined;
jest.isolateModules(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const filters = require('../chatFilters') as typeof import('../chatFilters');
value = createStore().get(filters.showProjectChatsAtom);
});
return value as boolean;
};
it('keeps the choice to hide them across visits', () => {
expect(onNextVisit(false)).toBe(false);
});
it('reads a stored value that is not a boolean as the default', () => {
expect(onNextVisit('no')).toBe(true);
});
});
describe('selectableBookmarks', () => {
const tag = (name: string, count: number): TConversationTag => ({
_id: name,

View file

@ -3,7 +3,8 @@ import type { ConversationGroupOptions } from '~/utils/convos';
import {
unlistedRunningIds,
RUNNING_CHATS_GROUP,
groupConversationsWithRunning as partitionGroups,
FINISHED_CHATS_GROUP,
groupConversationsByStatus as partitionGroups,
} from '../running';
import { groupConversations } from '~/utils/convos';
@ -26,7 +27,7 @@ const groupConversationsWithRunning = (
options: ConversationGroupOptions,
) => partitionGroups(groupConversations(conversations, options), activeJobIds, options);
describe('groupConversationsWithRunning', () => {
describe('groupConversationsByStatus', () => {
it('returns the same date groups when the polled jobs do not affect loaded rows', () => {
const dated = groupConversations([convo('idle', 1)], newestFirst);
expect(partitionGroups(dated, new Set(), newestFirst)).toBe(dated);
@ -196,3 +197,76 @@ describe('running chats the loaded rows do not hold', () => {
expect(partitionGroups(dated, new Set(['in-project']), options, unlisted)).toBe(dated);
});
});
describe('groupConversationsByStatus finished chats', () => {
const replied = (
conversationId: string,
daysAgo: number,
read: Partial<TConversation> = {},
): TConversation =>
({
...convo(conversationId, daysAgo),
lastResponseAt: new Date(Date.now() - daysAgo * 86_400_000).toISOString(),
...read,
}) as TConversation;
it('lists a reply that arrived unseen under Finished, after Running and before the dates', () => {
const newest = convo('newest', 0);
const running = convo('running', 1);
const unseen = replied('unseen', 3);
const seen = replied('seen', 2, { lastSeenAt: new Date().toISOString() });
const groups = groupConversationsWithRunning(
[newest, running, seen, unseen],
new Set(['running']),
newestFirst,
);
expect(groups[0]).toEqual([RUNNING_CHATS_GROUP, [running]]);
expect(groups[1]).toEqual([FINISHED_CHATS_GROUP, [unseen]]);
expect(ids(groups)).toEqual(['running', 'unseen', 'newest', 'seen']);
});
it('shows Finished with no chat running', () => {
const groups = groupConversationsWithRunning(
[convo('newest', 0), replied('unseen', 2)],
new Set(),
newestFirst,
);
expect(groups.map(([name]) => name)[0]).toBe(FINISHED_CHATS_GROUP);
expect(ids(groups)).toEqual(['unseen', 'newest']);
});
it('keeps a running chat under Running even while its previous reply is unseen', () => {
const groups = groupConversationsWithRunning(
[replied('busy', 1)],
new Set(['busy']),
newestFirst,
);
expect(groups).toEqual([
[RUNNING_CHATS_GROUP, [expect.objectContaining({ conversationId: 'busy' })]],
]);
});
it('leaves a chat marked unread by hand in its date group', () => {
const manual = replied('manual', 1, { lastResponseIsManual: true });
const dated = groupConversations([manual], newestFirst);
expect(partitionGroups(dated, new Set(), newestFirst)).toBe(dated);
});
it.each([
{ field: 'updatedAt' as const, direction: 'asc' as const },
{ field: 'title' as const, direction: 'asc' as const },
])('keeps unseen chats in place under the $field $direction order', (options) => {
const dated = groupConversations([replied('unseen', 1), convo('other', 0)], options);
expect(partitionGroups(dated, new Set(), options)).toBe(dated);
});
it('keeps unseen chats in place when the list includes pins', () => {
const options = { ...newestFirst, includePinned: true };
const dated = groupConversations([replied('unseen', 1)], options);
expect(partitionGroups(dated, new Set(), options)).toBe(dated);
});
});

View file

@ -66,6 +66,18 @@ export const chatSortAtom = atom(
},
);
const storedShowProjectChatsAtom = createStorageAtom<boolean>('chatListShowProjectChats', true);
/** Whether chats filed in a project also list under Chats, where recent work is looked
* for first. A display preference, so it is kept like the sort; anything but an explicit
* `false` reads as the default. */
export const showProjectChatsAtom = atom(
(get) => get(storedShowProjectChatsAtom) !== false,
(_get, set, next: boolean) => {
set(storedShowProjectChatsAtom, next);
},
);
/** Read by conversation rows to offer restoring instead of archiving. */
export const isArchivedChatViewAtom = atom((get) => get(chatFilterStatusAtom) === 'archived');
@ -81,6 +93,9 @@ export const chatFilterCountAtom = atom((get) => {
if (sort.field !== DEFAULT_CHAT_SORT.field || sort.direction !== DEFAULT_CHAT_SORT.direction) {
count += 1;
}
if (!get(showProjectChatsAtom)) {
count += 1;
}
return count;
});
@ -88,6 +103,7 @@ export const resetChatFiltersAtom = atom(null, (_get, set) => {
set(chatFilterStatusAtom, 'active');
set(chatFilterTagsAtom, []);
set(storedChatSortAtom, DEFAULT_CHAT_SORT);
set(storedShowProjectChatsAtom, true);
});
/**

View file

@ -1,21 +1,28 @@
import type { TConversation, GroupedConversations } from 'librechat-data-provider';
import type { ConversationGroupOptions } from '~/utils/convos';
import { isTemporaryConversation } from '~/utils/conversation';
import { isConversationUnseen } from '~/utils/convos';
export const RUNNING_CHATS_GROUP = 'com_ui_running_chats';
export const FINISHED_CHATS_GROUP = 'com_ui_finished_chats';
/** Groups that hold chats by what they are doing rather than by date; their headings
* carry a count. */
export const isStatusGroup = (groupName: string): boolean =>
groupName === RUNNING_CHATS_GROUP || groupName === FINISHED_CHATS_GROUP;
const noUnlistedIds: string[] = [];
function showsRunningGroup(
activeJobIds: ReadonlySet<string>,
options: ConversationGroupOptions,
): boolean {
return (
!options.includePinned &&
options.field === 'updatedAt' &&
options.direction === 'desc' &&
activeJobIds.size > 0
);
/** Status groups only make sense over the newest-first list: under any other order a
* chat lifted to the top would read as the first by title or by creation. */
function showsStatusGroups(options: ConversationGroupOptions): boolean {
return !options.includePinned && options.field === 'updatedAt' && options.direction === 'desc';
}
/** A reply that landed while the user was elsewhere. "Mark as unread" sets the same
* stamp as a reminder, not as a finished run, so that chat keeps its date. */
function isFinishedUnseen(conversation: TConversation): boolean {
return conversation.lastResponseIsManual !== true && isConversationUnseen(conversation);
}
function newestFirst(a: TConversation, b: TConversation): number {
@ -44,20 +51,23 @@ export function unlistedRunningIds(
/**
* Partition the existing server-ordered groups without re-sorting them on every job update.
* `unlisted` adds running chats those groups never held, so the Running group lists every
* running chat; the date groups are still built only from the rows they were given.
* Running chats lead; chats whose reply arrived unseen follow as Finished, so a run that
* ends while the user is elsewhere stays near the top until it is opened. `unlisted` adds
* running chats those groups never held, so the Running group lists every running chat;
* the date groups are still built only from the rows they were given.
*/
export function groupConversationsWithRunning(
export function groupConversationsByStatus(
groups: GroupedConversations,
activeJobIds: ReadonlySet<string>,
options: ConversationGroupOptions,
unlisted: readonly TConversation[] = [],
): GroupedConversations {
if (!showsRunningGroup(activeJobIds, options)) {
if (!showsStatusGroups(options)) {
return groups;
}
const running: TConversation[] = [];
const finished: TConversation[] = [];
const runningIds = new Set<string>();
const remaining: GroupedConversations = [];
for (const [groupName, conversations] of groups) {
@ -67,6 +77,8 @@ export function groupConversationsWithRunning(
if (id && activeJobIds.has(id)) {
running.push(conversation);
runningIds.add(id);
} else if (isFinishedUnseen(conversation)) {
finished.push(conversation);
} else {
idle.push(conversation);
}
@ -76,24 +88,35 @@ export function groupConversationsWithRunning(
}
}
const added = unlisted.filter((conversation) => {
const id = conversation.conversationId;
if (
!id ||
conversation.isArchived === true ||
isTemporaryConversation(conversation) ||
!activeJobIds.has(id) ||
runningIds.has(id)
) {
return false;
}
runningIds.add(id);
return true;
});
const added =
activeJobIds.size === 0
? []
: unlisted.filter((conversation) => {
const id = conversation.conversationId;
if (
!id ||
conversation.isArchived === true ||
isTemporaryConversation(conversation) ||
!activeJobIds.has(id) ||
runningIds.has(id)
) {
return false;
}
runningIds.add(id);
return true;
});
if (running.length === 0 && added.length === 0) {
if (running.length === 0 && finished.length === 0 && added.length === 0) {
return groups;
}
const runningGroup = added.length === 0 ? running : [...running, ...added].sort(newestFirst);
return [[RUNNING_CHATS_GROUP, runningGroup], ...(running.length === 0 ? groups : remaining)];
const statusGroups: GroupedConversations = [];
if (running.length > 0 || added.length > 0) {
const runningGroup = added.length === 0 ? running : [...running, ...added].sort(newestFirst);
statusGroups.push([RUNNING_CHATS_GROUP, runningGroup]);
}
if (finished.length > 0) {
statusGroups.push([FINISHED_CHATS_GROUP, finished]);
}
const pulled = running.length > 0 || finished.length > 0;
return [...statusGroups, ...(pulled ? remaining : groups)];
}

View file

@ -15,6 +15,7 @@ import {
chatFilterTagsAtom,
chatSortAtom,
isArchivedChatViewAtom,
showProjectChatsAtom,
} from '~/components/Conversations/chatFilters';
import {
useLocalize,
@ -47,6 +48,7 @@ const ConversationsSection = memo(() => {
const tags = useAtomValue(chatFilterTagsAtom);
const sort = useAtomValue(chatSortAtom);
const isArchivedView = useAtomValue(isArchivedChatViewAtom);
const showProjectChats = useAtomValue(showProjectChatsAtom);
/** Date, endpoint and attachment facets, already shaped as list parameters. */
const facetParams = useAtomValue(chatFacetParamsAtom);
/** Keeps the date facets' midnight anchor advancing while the list is mounted. */
@ -67,13 +69,17 @@ const ConversationsSection = memo(() => {
* projects are loading or failed to load, an empty Chats list claims no more than
* that nothing sits outside a project. */
const hasProjects = !projectsLoaded || (projectsData?.pages[0]?.projects?.length ?? 0) > 0;
/** A chat that belongs to a project is shown under that project, not twice. Search and
* the archived view stay whole: both are places the user goes to find something, and a
* project chat that appears in neither list nor result would have no way back. So does
* a list whose projects failed to load, which would otherwise hide every project chat
* behind a section that cannot show them. */
/** Project chats list under Chats too, badged with their folder, because Chats is where
* recent work is looked for first. Turning that off shows each one only under its
* project. Search and the archived view stay whole either way: both are places the user
* goes to find something, and a project chat that appears in neither list nor result
* would have no way back. So does a list whose projects failed to load, which would
* otherwise hide every project chat behind a section that cannot show them. */
const scopeToUnassigned =
!isArchivedView && !search.debouncedQuery && !(projectsFailed && projectsData == null);
!showProjectChats &&
!isArchivedView &&
!search.debouncedQuery &&
!(projectsFailed && projectsData == null);
const {
data,

View file

@ -1,4 +1,5 @@
import React from 'react';
import { getDefaultStore } from 'jotai';
import { DndProvider } from 'react-dnd';
import { BrowserRouter } from 'react-router-dom';
import { HTML5Backend } from 'react-dnd-html5-backend';
@ -180,6 +181,7 @@ jest.mock('~/components/Nav/Favorites/FavoriteItem', () => ({
default: () => <div data-testid="favorite-item-stub" />,
}));
import { showProjectChatsAtom } from '~/components/Conversations/chatFilters';
import ConversationsSection from '../ConversationsSection';
import store from '~/store';
@ -307,19 +309,33 @@ describe('ConversationsSection project chats', () => {
mockListParams.mockClear();
});
/** A chat that belongs to a project is shown under that project. Listing it in
* Chats as well puts the same conversation in two places in one sidebar. */
it('asks only for chats that belong to no project', async () => {
afterEach(() => {
act(() => getDefaultStore().set(showProjectChatsAtom, true));
});
/** Chats is where recent work is looked for first, so a chat filed in a project is
* listed there too, carrying its folder badge. */
it('lists project chats under Chats by default', async () => {
renderSection();
await settleRenders();
expect(mockListParams).toHaveBeenCalled();
expect(mockListParams.mock.calls.at(-1)?.[0]).toMatchObject({ projectId: undefined });
});
/** Turned off, a project chat is shown only under its project, not twice. */
it('asks only for chats that belong to no project once project chats are hidden', async () => {
act(() => getDefaultStore().set(showProjectChatsAtom, false));
renderSection();
await settleRenders();
expect(mockListParams.mock.calls.at(-1)?.[0]).toMatchObject({ projectId: 'unassigned' });
});
/** Searching is how a chat is found, and Projects is not rendered while a search
* is on: excluding project chats there would make them unreachable. */
it('searches across every chat, project or not', async () => {
act(() => getDefaultStore().set(showProjectChatsAtom, false));
let setSearch: SetterOrUpdater<SearchState>;
function SearchController() {
@ -363,9 +379,16 @@ describe('ConversationsSection empty Chats wording', () => {
(mockConversationsRender.mock.calls.at(-1)?.[0] as { accountHasProjects?: boolean })
.accountHasProjects;
/** The empty wording only distinguishes an empty account while Chats leaves project
* chats to their projects. */
beforeEach(() => {
mockConversationsRender.mockClear();
mockUseProjectsInfiniteQuery.mockReset();
act(() => getDefaultStore().set(showProjectChatsAtom, false));
});
afterEach(() => {
act(() => getDefaultStore().set(showProjectChatsAtom, true));
});
it('calls the account empty only once its projects have loaded and there are none', async () => {

View file

@ -1,5 +1,5 @@
import { dataService, QueryKeys } from 'librechat-data-provider';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query';
import type {
ProjectAvailableFilesParams,
ProjectAvailableFilesResponse,
@ -9,6 +9,7 @@ import type {
TChatProjectFile,
} from 'librechat-data-provider';
import type {
InfiniteData,
UseInfiniteQueryOptions,
QueryObserverResult,
UseQueryOptions,
@ -54,6 +55,32 @@ export const useProjectQuery = (
},
);
};
/**
* A project's name for a row that only carries its id. The sidebar already holds the
* recent projects, so a name found there costs no request; only a project past that
* list is fetched, once per id. A record written by id (a rename) still wins.
*/
export const useProjectName = (projectId?: string | null): string | undefined => {
const queryClient = useQueryClient();
let listedName: string | undefined;
if (projectId) {
for (const [, data] of queryClient.getQueriesData<InfiniteData<ProjectListResponse>>([
QueryKeys.projects,
])) {
for (const page of data?.pages ?? []) {
listedName = page?.projects?.find((project) => project._id === projectId)?.name;
if (listedName != null) {
break;
}
}
if (listedName != null) {
break;
}
}
}
const { data: project } = useProjectQuery(projectId, { enabled: listedName == null });
return project?.name ?? listedName;
};
export const useProjectFilesQuery = (
projectId?: string | null,
config?: UseQueryOptions<TChatProjectFile[]>,

View file

@ -0,0 +1,80 @@
import { QueryKeys, dataService } from 'librechat-data-provider';
import { renderHook, waitFor, act } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ProjectListResponse, TChatProject } from 'librechat-data-provider';
import type { InfiniteData } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { useProjectName } from '../Projects';
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
dataService: { ...actual.dataService, getProjectById: jest.fn() },
};
});
const getProjectById = dataService.getProjectById as jest.MockedFunction<
typeof dataService.getProjectById
>;
const project = (id: string, name: string) =>
({ _id: id, name, conversationCount: 1 }) as TChatProject;
const renderName = (queryClient: QueryClient, projectId: string) =>
renderHook(() => useProjectName(projectId), {
wrapper: ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
});
const seedList = (queryClient: QueryClient, projects: TChatProject[]) =>
queryClient.setQueryData<InfiniteData<ProjectListResponse>>(
[QueryKeys.projects, { sortBy: 'lastConversationAt', sortDirection: 'desc', limit: 25 }],
{ pages: [{ projects, nextCursor: null } as ProjectListResponse], pageParams: [undefined] },
);
describe('useProjectName', () => {
let queryClient: QueryClient;
beforeEach(() => {
jest.resetAllMocks();
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => {
queryClient.clear();
});
/* Every project chat under Chats carries a badge; a request per project would turn the
list into a burst of reads the sidebar's own project list already answers. */
it('names a project the sidebar has listed without asking the server', () => {
seedList(queryClient, [project('p1', 'Scheduling'), project('p2', 'Subagents')]);
const { result } = renderName(queryClient, 'p2');
expect(result.current).toBe('Subagents');
expect(getProjectById).not.toHaveBeenCalled();
});
it('fetches a project past the listed ones', async () => {
seedList(queryClient, [project('p1', 'Scheduling')]);
getProjectById.mockResolvedValue(project('p9', 'Speed Chess'));
const { result } = renderName(queryClient, 'p9');
await waitFor(() => expect(result.current).toBe('Speed Chess'));
expect(getProjectById).toHaveBeenCalledTimes(1);
expect(getProjectById).toHaveBeenCalledWith('p9');
});
it('prefers a record written by id, such as a rename', async () => {
seedList(queryClient, [project('p1', 'Scheduling')]);
const { result } = renderName(queryClient, 'p1');
act(() => {
queryClient.setQueryData([QueryKeys.project, 'p1'], project('p1', 'Cron jobs'));
});
await waitFor(() => expect(result.current).toBe('Cron jobs'));
expect(getProjectById).not.toHaveBeenCalled();
});
});

View file

@ -152,7 +152,10 @@
"com_a11y_ai_composing": "The AI is still composing.",
"com_a11y_chats_date_section": "Chats from {{date}}",
"com_a11y_chats_alpha_section": "Chats with titles starting with {{letter}}",
"com_a11y_chats_running_section": "Running chats",
"com_a11y_chats_running_section": "{{count}} running chats",
"com_a11y_chats_running_section_one": "1 running chat",
"com_a11y_chats_finished_section": "{{count}} finished chats with unread replies",
"com_a11y_chats_finished_section_one": "1 finished chat with an unread reply",
"com_a11y_end": "The AI has finished their reply.",
"com_a11y_selected": "selected",
"com_a11y_start": "The AI has started their reply.",
@ -2394,6 +2397,7 @@
"com_ui_run_code_error": "There was an error running the code",
"com_ui_running": "Running...",
"com_ui_running_chats": "Running",
"com_ui_finished_chats": "Finished",
"com_ui_running_command": "Running command",
"com_ui_preparing_n_actions": "Preparing {{0}} actions",
"com_ui_preparing_one_action": "Preparing 1 action",
@ -2604,6 +2608,7 @@
"com_ui_shared_link_bulk_delete_success": "Successfully deleted shared links",
"com_ui_shared_link_delete_success": "Successfully deleted shared link",
"com_ui_shared_only": "Shared only",
"com_ui_show_project_chats": "Show project chats",
"com_ui_shared_link_manage_access": "Manage Access",
"com_ui_shared_link_not_found": "Shared link not found",
"com_ui_shared_link_updated": "This shared link was updated. Reloading the latest version, then try again",

View file

@ -238,7 +238,7 @@ test.describe('chat list properties menu', () => {
await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 2');
});
test('a project chat is listed under its project, not in Chats, and stays reachable from the archive @scenario:project-chat-listed-under-project-only', async ({
test('a project chat is listed in Chats with its folder and under its project, hides from Chats on request, and stays reachable from the archive @scenario:project-chat-listed-in-chats-and-project', async ({
page,
}) => {
const projectName = `Menu project ${randomUUID().slice(0, 8)}`;
@ -255,7 +255,7 @@ test.describe('chat list properties menu', () => {
await showSidebar(page);
await expect(chatsRow(page, unassigned)).toBeVisible();
await expect(chatsRow(page, inProject)).toHaveCount(0);
await expect(chatsRow(page, inProject).getByTestId('convo-project-badge')).toBeVisible();
const projectRow = page.getByRole('button', { name: projectName }).first();
if ((await projectRow.getAttribute('aria-expanded')) !== 'true') {
@ -267,6 +267,13 @@ test.describe('chat list properties menu', () => {
}),
).toBeVisible();
await trigger(page).click();
await page.getByRole('menuitemcheckbox', { name: 'Show project chats' }).click();
await closeMenus(page);
await expect(chatsRow(page, inProject)).toHaveCount(0);
await expect(chatsRow(page, unassigned)).toBeVisible();
await expect(trigger(page)).toHaveAttribute('aria-label', 'Filters active: 1');
await trigger(page).click();
await page.getByTestId('chat-filter-show').click();
await page.getByRole('menuitemradio', { name: 'Archived chats' }).click();

View file

@ -8,6 +8,8 @@ interface SpinnerProps {
color?: string;
bgOpacity?: number;
speed?: number;
/** Stroke width in viewBox units (the box is 40 wide); thinner reads as a quieter ring. */
strokeWidth?: number;
}
/**
@ -24,6 +26,7 @@ export default function Spinner({
color = 'currentColor',
bgOpacity = 0.1,
speed = 0.75,
strokeWidth = 5,
}: SpinnerProps): JSX.Element {
const cssVars = {
'--spinner-speed': `${speed}s`,
@ -46,7 +49,7 @@ export default function Spinner({
cy="20"
r="14.5"
pathLength="100"
strokeWidth="5"
strokeWidth={strokeWidth}
fill="none"
stroke={color}
strokeOpacity={bgOpacity}
@ -56,7 +59,7 @@ export default function Spinner({
cy="20"
r="14.5"
pathLength="100"
strokeWidth="5"
strokeWidth={strokeWidth}
fill="none"
stroke={color}
strokeDasharray="25 75"