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

🏃 fix: List Every Running Chat in the Sidebar's Running Group (#16668)

Danny Avilac945cafa3456
diff --git a/client/src/components/Conversations/Conversations.tsx b/client/src/components/Conversations/Conversations.tsx
index 4e21b8307b..6d05b7d467 100644
--- a/client/src/components/Conversations/Conversations.tsx
+++ b/client/src/components/Conversations/Conversations.tsx
@@ -32,11 +32,11 @@ import {
useEffectiveProjectId,
useUnpinDroppedConversation,
} from './dnd';
+import { unlistedRunningIds, RUNNING_CHATS_GROUP, groupConversationsWithRunning } from './running';
import { useLocalize, TranslationKeys, useElementSize, useOuterScrollWindow } from '~/hooks';
-import { groupConversationsWithRunning, RUNNING_CHATS_GROUP } from './running';
+import { useActiveJobs, useRunningConversationsQuery } from '~/data-provider';
import { facetFilterCountAtom, resetFacetsAtom } from './facets';
import { groupConversations, cn } from '~/utils';
-import { useActiveJobs } from '~/data-provider';
import Convo from './Convo';
import store from '~/store';
@@ -196,7 +196,7 @@ DateLabel.displayName = 'DateLabel';
type FlattenedItem =
| { type: 'header'; groupName: string }
- | { type: 'convo'; convo: TConversation }
+ | { type: 'convo'; convo: TConversation; inRunningGroup: boolean }
| { type: 'loading' };
const Conversations: FC<ConversationsProps> = ({
@@ -324,15 +324,42 @@ const Conversations: FC<ConversationsProps> = ({
}),
[filteredConversations, includePinned, sort.direction, sort.field],
);
+ /** Running chats this list holds no row for — filed in a project, pinned, or past the
+ * loaded pages — join the Running group only while nothing narrows the list: a search
+ * or filter result that grew rows it did not match would stop reading as that result. */
+ const isUnnarrowed =
+ !search.query && !isArchivedView && filterTags.length === 0 && facetFilterCount === 0;
+ const listsNewestFirst = sort.field === 'updatedAt' && sort.direction === 'desc';
+ const runningIdsToFetch = useMemo(
+ () =>
+ isUnnarrowed && isChatsExpanded && listsNewestFirst
+ ? unlistedRunningIds(datedConversations, activeJobIds)
+ : [],
+ [isUnnarrowed, isChatsExpanded, listsNewestFirst, datedConversations, activeJobIds],
+ );
+ const unlistedRunning = useRunningConversationsQuery(runningIdsToFetch);
/** The archive keeps its server order, while search still promotes active matches. */
const groupedConversations = useMemo(
() =>
- groupConversationsWithRunning(datedConversations, activeJobIds, {
- field: sort.field,
- direction: sort.direction,
- includePinned: isArchivedView,
- }),
- [datedConversations, activeJobIds, isArchivedView, sort.direction, sort.field],
+ groupConversationsWithRunning(
+ datedConversations,
+ activeJobIds,
+ {
+ field: sort.field,
+ direction: sort.direction,
+ includePinned: isArchivedView,
+ },
+ isUnnarrowed ? unlistedRunning : undefined,
+ ),
+ [
+ datedConversations,
+ activeJobIds,
+ isArchivedView,
+ isUnnarrowed,
+ unlistedRunning,
+ sort.direction,
+ sort.field,
+ ],
);
/* Outside search, pins are stripped from the date groups. An all-pin page leaves
@@ -375,8 +402,9 @@ 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 })));
+ items.push(...convos.map((convo) => ({ type: 'convo' as const, convo, inRunningGroup })));
});
if (isLoading) {
@@ -489,6 +517,7 @@ const Conversations: FC<ConversationsProps> = ({
retainView={moveToTop}
toggleNav={toggleNav}
isGenerating={isGenerating}
+ showProjectBadge={item.inRunningGroup}
draggable
/>
</MeasuredRow>
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index 30b8cd21cc..6892302862 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -1,4 +1,4 @@
-import React, { memo, useState, useEffect, useRef, useMemo, useCallback } from 'react';
+import React, { memo, useId, useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { useDrag } from 'react-dnd';
import { Link2 } from 'lucide-react';
import { useRecoilValue } from 'recoil';
@@ -19,6 +19,7 @@ import { focusableInRow, resolveRowBeside } from './focus';
import { areConversationRenderPropsEqual } from './utils';
import { NotificationSeverity } from '~/common';
import { CONVERSATION_DRAG_TYPE } from './dnd';
+import ProjectBadge from './ProjectBadge';
import ConvoActions from './ConvoActions';
import UnpinButton from './UnpinButton';
import RenameForm from './RenameForm';
@@ -39,6 +40,8 @@ interface ConversationProps {
/** Shortcuts an owning list handles for this row, declared on its focusable
* element so they are announced rather than left to be discovered. */
keyShortcuts?: string;
+ /** Names the chat's project on rows listed outside that project. */
+ showProjectBadge?: boolean;
}
function Conversation({
@@ -49,6 +52,7 @@ function Conversation({
draggable = false,
onRenamingChange,
keyShortcuts,
+ showProjectBadge = false,
}: ConversationProps) {
const params = useParams();
const localize = useLocalize();
@@ -64,6 +68,8 @@ function Conversation({
const { data: startupConfig } = useGetStartupConfig();
const sharedLinksEnabled = startupConfig?.sharedLinksEnabled === true;
const isSharedBadgeVisible = conversation.isShared === true && sharedLinksEnabled;
+ const projectLabelId = useId();
+ const projectBadgeProjectId = showProjectBadge ? conversation.chatProjectId : undefined;
const isUnseen = isConversationUnseen(conversation);
const isShiftHeld = useShiftKey();
const { conversationId, title = '' } = conversation;
@@ -359,6 +365,7 @@ function Conversation({
isSmallScreen={isSmallScreen}
localize={localize}
keyShortcuts={keyShortcuts}
+ describedBy={projectBadgeProjectId ? projectLabelId : undefined}
>
<ConversationEndpointIcon conversation={conversation} size={20} context="menu-item" />
</ConvoLink>
@@ -371,6 +378,9 @@ function Conversation({
{isSharedBadgeVisible && (
<Link2 className="icon-sm text-text-secondary mr-1 shrink-0" aria-hidden="true" />
)}
+ {projectBadgeProjectId && (
+ <ProjectBadge projectId={projectBadgeProjectId} labelId={projectLabelId} />
+ )}
{conversation.pinned === true && (
<UnpinButton
testId="convo-unpin-button"
diff --git a/client/src/components/Conversations/ConvoLink.tsx b/client/src/components/Conversations/ConvoLink.tsx
index bed937532b..5150f3b20a 100644
--- a/client/src/components/Conversations/ConvoLink.tsx
+++ b/client/src/components/Conversations/ConvoLink.tsx
@@ -16,6 +16,8 @@ interface ConvoLinkProps {
/** Shortcuts the row responds to, declared on the element that takes focus so
* assistive tech announces them when the user arrives here. */
keyShortcuts?: string;
+ /** Id of text that adds context the title does not carry, such as the chat's project. */
+ describedBy?: string;
children: React.ReactNode;
}
@@ -45,6 +47,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
isSmallScreen,
localize,
keyShortcuts,
+ describedBy,
children,
}) => {
const [isOverflowing, setIsOverflowing] = useState(false);
@@ -133,6 +136,7 @@ const ConvoLink: React.FC<ConvoLinkProps> = ({
)}
aria-current={isActiveConvo ? 'page' : undefined}
aria-keyshortcuts={keyShortcuts}
+ aria-describedby={describedBy}
aria-label={
(isSharedBadgeVisible
? localize('com_ui_conversation_label_shared', {
diff --git a/client/src/components/Conversations/ProjectBadge.tsx b/client/src/components/Conversations/ProjectBadge.tsx
new file mode 100644
index 0000000000..cfbcd8625d
--- /dev/null
+++ b/client/src/components/Conversations/ProjectBadge.tsx
@@ -0,0 +1,29 @@
+import { memo } from 'react';
+import { Folder } from 'lucide-react';
+import { useProjectQuery } 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. */
+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');
+
+ return (
+ <span
+ className="text-text-secondary mr-1 flex shrink-0 items-center"
+ title={label}
+ data-testid="convo-project-badge"
+ >
+ <Folder className="icon-sm" aria-hidden="true" />
+ <span id={labelId} className="sr-only">
+ {label}
+ </span>
+ </span>
+ );
+}
+
+export default memo(ProjectBadge);
diff --git a/client/src/components/Conversations/__tests__/Conversations.test.tsx b/client/src/components/Conversations/__tests__/Conversations.test.tsx
index a297b3332c..a8d2c628ce 100644
--- a/client/src/components/Conversations/__tests__/Conversations.test.tsx
+++ b/client/src/components/Conversations/__tests__/Conversations.test.tsx
@@ -9,6 +9,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { CellMeasurerCache, List } from 'react-virtualized';
import type { TConversation } from 'librechat-data-provider';
import { hasAttachmentsAtom, resetFacetsAtom } from '../facets';
+import { chatSortAtom } from '../chatFilters';
import Conversations from '../Conversations';
import store from '~/store';
@@ -16,6 +17,10 @@ import store from '~/store';
* tree needs a client even though the data hooks themselves are mocked. */
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
let mockActiveJobIds: string[] = [];
+let mockRunningRows: TConversation[] = [];
+const mockRunningConversationsQuery = jest.fn((ids: readonly string[]) =>
+ mockRunningRows.filter((row) => ids.includes(row.conversationId ?? '')),
+);
jest.mock('react-virtualized', () => {
const actual = jest.requireActual('react-virtualized');
@@ -104,6 +109,7 @@ jest.mock('@librechat/client', () => ({
jest.mock('~/data-provider', () => ({
useActiveJobs: () => ({ data: { activeJobIds: mockActiveJobIds } }),
+ useRunningConversationsQuery: (ids: readonly string[]) => mockRunningConversationsQuery(ids),
useAssignConversationToProjectMutation: () => ({ mutate: jest.fn() }),
usePinConversationMutation: () => ({ mutate: jest.fn() }),
}));
@@ -115,8 +121,16 @@ jest.mock('~/utils', () => ({
jest.mock('../Convo', () => ({
__esModule: true,
- default: ({ conversation }: { conversation: TConversation }) => (
- <div data-testid="convo">{conversation.title}</div>
+ default: ({
+ conversation,
+ showProjectBadge,
+ }: {
+ conversation: TConversation;
+ showProjectBadge?: boolean;
+ }) => (
+ <div data-testid="convo" data-project-badge={String(showProjectBadge === true)}>
+ {conversation.title}
+ </div>
),
}));
@@ -480,3 +494,99 @@ describe('Conversations: the empty state offers the way back', () => {
expect(jotaiStore.get(hasAttachmentsAtom)).toBe(false);
});
});
+
+describe('Conversations: Running lists chats outside the Chats list', () => {
+ const containerRef = createRef<List>();
+ const idle = {
+ conversationId: 'idle',
+ title: 'Idle chat',
+ endpoint: 'openAI',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-03T00:00:00.000Z',
+ } as TConversation;
+ const projectChat = {
+ ...idle,
+ conversationId: 'project-chat',
+ title: 'Project chat',
+ chatProjectId: 'project-1',
+ updatedAt: '2026-01-02T00:00:00.000Z',
+ } as TConversation;
+
+ const renderList = (searchQuery = '') =>
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DndProvider backend={HTML5Backend}>
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.search, {
+ query: searchQuery,
+ enabled: true,
+ debouncedQuery: searchQuery,
+ isSearching: searchQuery.length > 0,
+ isTyping: false,
+ });
+ }}
+ >
+ <Conversations
+ conversations={[idle]}
+ moveToTop={jest.fn()}
+ toggleNav={jest.fn()}
+ containerRef={containerRef}
+ loadMoreConversations={jest.fn()}
+ isLoading={false}
+ isSearchLoading={false}
+ isChatsExpanded={true}
+ setIsChatsExpanded={jest.fn()}
+ scrollViewport={null}
+ scrollContent={null}
+ />
+ </RecoilRoot>
+ </DndProvider>
+ </QueryClientProvider>,
+ );
+
+ beforeEach(() => {
+ mockActiveJobIds = ['project-chat'];
+ mockRunningRows = [projectChat];
+ mockRunningConversationsQuery.mockClear();
+ });
+
+ afterEach(() => {
+ mockActiveJobIds = [];
+ mockRunningRows = [];
+ });
+
+ it('shows a running project chat in Running with its project badge', () => {
+ renderList();
+
+ expect(mockRunningConversationsQuery).toHaveBeenLastCalledWith(['project-chat']);
+ expect(
+ screen.getByRole('heading', { name: 'com_a11y_chats_running_section' }),
+ ).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']);
+ });
+
+ it('fetches nothing under a sort that has no Running group', () => {
+ const jotaiStore = getDefaultStore();
+ const previous = jotaiStore.get(chatSortAtom);
+ jotaiStore.set(chatSortAtom, { field: 'title', direction: 'asc' });
+ try {
+ renderList();
+
+ expect(mockRunningConversationsQuery).toHaveBeenLastCalledWith([]);
+ expect(screen.queryByRole('heading', { name: 'com_a11y_chats_running_section' })).toBeNull();
+ } finally {
+ jotaiStore.set(chatSortAtom, previous);
+ }
+ });
+
+ it('keeps a search result to its own matches', () => {
+ renderList('Idle');
+
+ expect(mockRunningConversationsQuery).toHaveBeenLastCalledWith([]);
+ expect(screen.queryByRole('heading', { name: 'com_a11y_chats_running_section' })).toBeNull();
+ expect(screen.getAllByTestId('convo').map((row) => row.textContent)).toEqual(['Idle chat']);
+ });
+});
diff --git a/client/src/components/Conversations/__tests__/running.spec.ts b/client/src/components/Conversations/__tests__/running.spec.ts
index 42996ed427..544b6d7a6a 100644
--- a/client/src/components/Conversations/__tests__/running.spec.ts
+++ b/client/src/components/Conversations/__tests__/running.spec.ts
@@ -1,6 +1,10 @@
import type { TConversation } from 'librechat-data-provider';
import type { ConversationGroupOptions } from '~/utils/convos';
-import { groupConversationsWithRunning as partitionGroups, RUNNING_CHATS_GROUP } from '../running';
+import {
+ unlistedRunningIds,
+ RUNNING_CHATS_GROUP,
+ groupConversationsWithRunning as partitionGroups,
+} from '../running';
import { groupConversations } from '~/utils/convos';
const convo = (conversationId: string, daysAgo: number, pinned = false): TConversation =>
@@ -89,3 +93,106 @@ describe('groupConversationsWithRunning', () => {
);
});
});
+
+describe('running chats the loaded rows do not hold', () => {
+ const projectChat = (conversationId: string, daysAgo: number): TConversation =>
+ ({ ...convo(conversationId, daysAgo), chatProjectId: 'project-1' }) as TConversation;
+
+ it('names only the running chats the groups do not already list', () => {
+ const dated = groupConversations([convo('listed', 1), convo('idle', 2)], newestFirst);
+ expect(unlistedRunningIds(dated, new Set(['listed', 'in-project']))).toEqual(['in-project']);
+ });
+
+ it('returns one shared empty list when nothing is missing', () => {
+ const dated = groupConversations([convo('listed', 1)], newestFirst);
+ const none = unlistedRunningIds(dated, new Set());
+ expect(none).toEqual([]);
+ expect(unlistedRunningIds(dated, new Set(['listed']))).toBe(none);
+ });
+
+ it('lists a running project chat above the date groups without touching them', () => {
+ const dated = groupConversations([convo('newer', 0), convo('older', 40)], newestFirst);
+ const inProject = projectChat('in-project', 10);
+
+ const groups = partitionGroups(dated, new Set(['in-project']), newestFirst, [inProject]);
+
+ expect(groups[0]).toEqual([RUNNING_CHATS_GROUP, [inProject]]);
+ expect(groups.slice(1)).toEqual(dated);
+ expect(groups[1]).toBe(dated[0]);
+ });
+
+ it('merges unlisted and loaded running chats newest first', () => {
+ const dated = groupConversations([convo('idle', 0), convo('loaded-running', 30)], newestFirst);
+ const recentProject = projectChat('recent-project', 5);
+ const oldPinned = convo('old-pinned', 60, true);
+
+ const groups = partitionGroups(
+ dated,
+ new Set(['loaded-running', 'recent-project', 'old-pinned']),
+ newestFirst,
+ [oldPinned, recentProject],
+ );
+
+ expect(groups[0][0]).toBe(RUNNING_CHATS_GROUP);
+ expect(groups[0][1].map((c) => c.conversationId)).toEqual([
+ 'recent-project',
+ 'loaded-running',
+ 'old-pinned',
+ ]);
+ expect(ids(groups.slice(1))).toEqual(['idle']);
+ });
+
+ it('drops unlisted rows whose run finished or that the groups already list', () => {
+ const loaded = convo('loaded-running', 3);
+ const dated = groupConversations([loaded], newestFirst);
+ const finished = projectChat('finished', 1);
+ const duplicate = { ...loaded, title: 'stale copy' } as TConversation;
+
+ const groups = partitionGroups(dated, new Set(['loaded-running']), newestFirst, [
+ finished,
+ duplicate,
+ ]);
+
+ expect(groups).toEqual([[RUNNING_CHATS_GROUP, [loaded]]]);
+ });
+
+ it.each([{ isTemporary: true }, { expiredAt: '2026-12-31T00:00:00.000Z' }])(
+ 'leaves a temporary chat out while its run continues: %j',
+ (retention) => {
+ const dated = groupConversations([convo('idle', 0)], newestFirst);
+ const temporary = { ...projectChat('temporary', 1), ...retention } as TConversation;
+
+ expect(partitionGroups(dated, new Set(['temporary']), newestFirst, [temporary])).toBe(dated);
+ },
+ );
+
+ it('keeps an explicitly non-temporary chat eligible even when it expires', () => {
+ const dated = groupConversations([convo('idle', 0)], newestFirst);
+ const expiring = {
+ ...projectChat('expiring', 1),
+ isTemporary: false,
+ expiredAt: '2026-12-31T00:00:00.000Z',
+ } as TConversation;
+
+ expect(partitionGroups(dated, new Set(['expiring']), newestFirst, [expiring])[0]).toEqual([
+ RUNNING_CHATS_GROUP,
+ [expiring],
+ ]);
+ });
+
+ it('leaves an archived chat out even while its run continues', () => {
+ const dated = groupConversations([convo('idle', 0)], newestFirst);
+ const archived = { ...projectChat('archived', 1), isArchived: true } as TConversation;
+
+ expect(partitionGroups(dated, new Set(['archived']), newestFirst, [archived])).toBe(dated);
+ });
+
+ it.each([
+ { field: 'createdAt' as const, direction: 'desc' as const },
+ { ...newestFirst, includePinned: true },
+ ])('adds nothing under $field $direction (includePinned: $includePinned)', (options) => {
+ const dated = groupConversations([convo('idle', 0)], options);
+ const unlisted = [projectChat('in-project', 1)];
+ expect(partitionGroups(dated, new Set(['in-project']), options, unlisted)).toBe(dated);
+ });
+});
diff --git a/client/src/components/Conversations/running.ts b/client/src/components/Conversations/running.ts
index 9d874ec771..3198dac069 100644
--- a/client/src/components/Conversations/running.ts
+++ b/client/src/components/Conversations/running.ts
@@ -1,24 +1,64 @@
import type { TConversation, GroupedConversations } from 'librechat-data-provider';
import type { ConversationGroupOptions } from '~/utils/convos';
+import { isTemporaryConversation } from '~/utils/conversation';
export const RUNNING_CHATS_GROUP = 'com_ui_running_chats';
-/** Partition the existing server-ordered groups without re-sorting them on every job update. */
+const noUnlistedIds: string[] = [];
+
+function showsRunningGroup(
+ activeJobIds: ReadonlySet<string>,
+ options: ConversationGroupOptions,
+): boolean {
+ return (
+ !options.includePinned &&
+ options.field === 'updatedAt' &&
+ options.direction === 'desc' &&
+ activeJobIds.size > 0
+ );
+}
+
+function newestFirst(a: TConversation, b: TConversation): number {
+ return (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '');
+}
+
+/** Running chats the grouped rows do not hold: chats filed in a project, pinned chats,
+ * which the date groups leave to their own section, and chats past the loaded pages. */
+export function unlistedRunningIds(
+ groups: GroupedConversations,
+ activeJobIds: ReadonlySet<string>,
+): string[] {
+ if (activeJobIds.size === 0) {
+ return noUnlistedIds;
+ }
+ const unlisted = new Set(activeJobIds);
+ for (const [, conversations] of groups) {
+ for (const conversation of conversations) {
+ if (conversation.conversationId) {
+ unlisted.delete(conversation.conversationId);
+ }
+ }
+ }
+ return unlisted.size === 0 ? noUnlistedIds : [...unlisted];
+}
+
+/**
+ * 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.
+ */
export function groupConversationsWithRunning(
groups: GroupedConversations,
activeJobIds: ReadonlySet<string>,
options: ConversationGroupOptions,
+ unlisted: readonly TConversation[] = [],
): GroupedConversations {
- if (
- options.includePinned ||
- options.field !== 'updatedAt' ||
- options.direction !== 'desc' ||
- activeJobIds.size === 0
- ) {
+ if (!showsRunningGroup(activeJobIds, options)) {
return groups;
}
const running: TConversation[] = [];
+ const runningIds = new Set<string>();
const remaining: GroupedConversations = [];
for (const [groupName, conversations] of groups) {
const idle: TConversation[] = [];
@@ -26,6 +66,7 @@ export function groupConversationsWithRunning(
const id = conversation.conversationId;
if (id && activeJobIds.has(id)) {
running.push(conversation);
+ runningIds.add(id);
} else {
idle.push(conversation);
}
@@ -35,5 +76,24 @@ export function groupConversationsWithRunning(
}
}
- return running.length === 0 ? groups : [[RUNNING_CHATS_GROUP, running], ...remaining];
+ 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;
+ });
+
+ if (running.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)];
}
diff --git a/client/src/components/Conversations/utils.ts b/client/src/components/Conversations/utils.ts
index d95c8f5a99..62c1ef2b0f 100644
--- a/client/src/components/Conversations/utils.ts
+++ b/client/src/components/Conversations/utils.ts
@@ -6,6 +6,7 @@ export type ConversationRenderProps = {
/** Announced on the row's focusable element, and it appears only once the
* owning list can act on it, so a change here has to reach the DOM. */
keyShortcuts?: string;
+ showProjectBadge?: boolean;
};
export function areConversationIconFieldsEqual(
@@ -54,6 +55,7 @@ export function areConversationRenderPropsEqual(
return (
areConversationListItemFieldsEqual(prevProps.conversation, nextProps.conversation) &&
prevProps.isGenerating === nextProps.isGenerating &&
- prevProps.keyShortcuts === nextProps.keyShortcuts
+ prevProps.keyShortcuts === nextProps.keyShortcuts &&
+ prevProps.showProjectBadge === nextProps.showProjectBadge
);
}
diff --git a/client/src/data-provider/Projects/mutations.ts b/client/src/data-provider/Projects/mutations.ts
index ba6eb8ddea..1e2f7996e2 100644
--- a/client/src/data-provider/Projects/mutations.ts
+++ b/client/src/data-provider/Projects/mutations.ts
@@ -11,7 +11,7 @@ import type {
TAssignConversationToProjectResponse,
} from 'librechat-data-provider';
import type { QueryClient, UseMutationResult } from '@tanstack/react-query';
-import { enqueue, invalidateConversationLists } from '~/utils';
+import { enqueue, updateConvoInAllQueries, invalidateConversationLists } from '~/utils';
import { getSessionPrincipal } from '~/utils/session';
import store from '~/store';
@@ -182,6 +182,10 @@ export const useAssignConversationToProjectMutation = (): UseMutationResult<
? { ...previous, chatProjectId: result.conversation.chatProjectId ?? null }
: result.conversation,
);
+ updateConvoInAllQueries(queryClient, conversationId, (previous) => ({
+ ...previous,
+ chatProjectId: result.conversation.chatProjectId ?? null,
+ }));
return result;
} finally {
/* Only the newest write clears the entry; by now the conversation
diff --git a/client/src/data-provider/__tests__/runningConversations.spec.tsx b/client/src/data-provider/__tests__/runningConversations.spec.tsx
new file mode 100644
index 0000000000..7d3071a729
--- /dev/null
+++ b/client/src/data-provider/__tests__/runningConversations.spec.tsx
@@ -0,0 +1,595 @@
+import { RecoilRoot } from 'recoil';
+import { renderHook, act, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { QueryKeys, dataService, setTokenHeader } from 'librechat-data-provider';
+import type { TConversation, TSharedLinkGetResponse } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import {
+ findConvoInAllQueries,
+ markRunningRemoval,
+ removeConvoFromAllQueries,
+ updateConvoInAllQueries,
+} from '~/utils/convos';
+import {
+ useArchiveConvoMutation,
+ useUpdateConversationMutation,
+ useArchiveAllConversationsMutation,
+} from '../mutations';
+import { useAssignConversationToProjectMutation } from '../Projects/mutations';
+import { useRunningConversationsQuery } from '../queries';
+
+jest.mock('librechat-data-provider', () => {
+ const actual = jest.requireActual('librechat-data-provider');
+ return {
+ ...actual,
+ dataService: {
+ ...actual.dataService,
+ getConversationById: jest.fn(),
+ getSharedLink: jest.fn(),
+ assignConversationToProject: jest.fn(),
+ archiveAllConversations: jest.fn(),
+ updateConversation: jest.fn(),
+ archiveConversation: jest.fn(),
+ },
+ };
+});
+
+const getConversationById = dataService.getConversationById as jest.MockedFunction<
+ typeof dataService.getConversationById
+>;
+const getSharedLink = dataService.getSharedLink as jest.MockedFunction<
+ typeof dataService.getSharedLink
+>;
+
+const record = (overrides: Partial<TConversation> = {}): TConversation =>
+ ({
+ conversationId: 'c1',
+ title: 'Running project chat',
+ chatProjectId: 'project-1',
+ updatedAt: '2026-01-02T00:00:00.000Z',
+ ...overrides,
+ }) as TConversation;
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+};
+
+const notFound = () => Object.assign(new Error('Not found'), { status: 404 });
+
+let queryClient: QueryClient;
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <RecoilRoot>
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ </RecoilRoot>
+);
+
+describe('useRunningConversationsQuery', () => {
+ beforeEach(() => {
+ jest.resetAllMocks();
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ getSharedLink.mockResolvedValue({ shareId: null, success: true } as TSharedLinkGetResponse);
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ setTokenHeader(undefined);
+ });
+
+ it('returns the record with its shared-link state and seeds an empty conversation cache', async () => {
+ getConversationById.mockResolvedValue(record());
+ getSharedLink.mockResolvedValue({
+ shareId: 'share-1',
+ success: true,
+ } as TSharedLinkGetResponse);
+
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ expect(result.current[0]).toMatchObject({ conversationId: 'c1', isShared: true });
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'c1'])).toEqual({
+ ...record(),
+ isShared: true,
+ });
+ });
+
+ it('returns sidebar fields without chat-owned settings while retaining the full navigation record', async () => {
+ const full = record({
+ codeApprovalMode: 'fullAccess',
+ codeEnvironmentMode: 'without_attached',
+ promptPrefix: 'Original prompt',
+ temperature: 0.2,
+ max_tokens: 2048,
+ codeWorkspaces: [{ environmentId: 'env-old', workspaceId: 'workspace-old' }],
+ });
+ getConversationById.mockResolvedValue(full);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+
+ expect(result.current[0]).toMatchObject({
+ conversationId: 'c1',
+ title: full.title,
+ chatProjectId: 'project-1',
+ });
+ for (const field of [
+ 'codeApprovalMode',
+ 'codeEnvironmentMode',
+ 'codeWorkspaces',
+ 'promptPrefix',
+ 'temperature',
+ 'max_tokens',
+ ]) {
+ expect(result.current[0]).not.toHaveProperty(field);
+ }
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'c1'])).toMatchObject(full);
+ });
+
+ it('keeps the sidebar projection stable while the underlying records are unchanged', async () => {
+ getConversationById.mockResolvedValue(record({ codeApprovalMode: 'fullAccess' }));
+ const { result, rerender } = renderHook(() => useRunningConversationsQuery(['c1']), {
+ wrapper,
+ });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ const rows = result.current;
+ rerender();
+ expect(result.current).toBe(rows);
+ expect(result.current[0]).toBe(rows[0]);
+ });
+
+ it('leaves a conversation the chat view already cached untouched', async () => {
+ const cached = record({ title: 'Edited locally' });
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], cached);
+ getConversationById.mockResolvedValue(record());
+
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'c1'])).toBe(cached);
+ });
+
+ it('asks again within seconds for a record that is not written yet', async () => {
+ getConversationById.mockRejectedValueOnce(notFound()).mockResolvedValue(record());
+
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+ expect(result.current).toEqual([]);
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'c1'])).toBeUndefined();
+ await waitFor(() => expect(result.current).toHaveLength(1), { timeout: 4000 });
+ expect(getConversationById).toHaveBeenCalledTimes(2);
+ });
+
+ it('follows renames and removals made through the shared cache helpers', async () => {
+ getConversationById.mockResolvedValue(record());
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+
+ updateConvoInAllQueries(queryClient, 'c1', (c) => ({ ...c, title: 'Renamed' }));
+ await waitFor(() => expect(result.current[0]?.title).toBe('Renamed'));
+
+ removeConvoFromAllQueries(queryClient, 'c1');
+ await waitFor(() => expect(result.current).toEqual([]));
+ });
+ it('does not let an older poll overwrite a local update', async () => {
+ const poll = deferred<TConversation>();
+ getConversationById.mockResolvedValueOnce(record()).mockReturnValueOnce(poll.promise);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ const refetch = queryClient.refetchQueries([QueryKeys.runningConversation, 'c1']);
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(2));
+
+ act(() => updateConvoInAllQueries(queryClient, 'c1', (c) => ({ ...c, title: 'Renamed' })));
+ await act(async () => {
+ poll.resolve(record());
+ await refetch;
+ });
+ await waitFor(() => expect(result.current[0]?.title).toBe('Renamed'));
+ });
+
+ it.each(['pending', 'missing'] as const)(
+ 'shows a renamed pin immediately with a %s Running row',
+ async (state) => {
+ const initial = deferred<TConversation>();
+ const newerReply = '2026-01-03T00:00:00.000Z';
+ queryClient.setQueryData([QueryKeys.pinnedConversations], {
+ conversations: [record({ pinned: true, isShared: true })],
+ });
+ if (state === 'pending') {
+ getConversationById.mockReturnValue(initial.promise);
+ } else {
+ getConversationById.mockRejectedValueOnce(notFound());
+ }
+ jest
+ .mocked(dataService.updateConversation)
+ .mockResolvedValue(record({ title: 'Renamed', pinned: true, lastResponseAt: newerReply }));
+ const { result } = renderHook(
+ () => ({
+ rows: useRunningConversationsQuery(['c1']),
+ rename: useUpdateConversationMutation('c1'),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+ if (state === 'missing') {
+ await waitFor(() =>
+ expect(queryClient.getQueryData([QueryKeys.runningConversation, 'c1'])).toBeNull(),
+ );
+ }
+ expect(result.current.rows).toEqual([]);
+
+ await act(async () => {
+ await result.current.rename.mutateAsync({ conversationId: 'c1', title: 'Renamed' });
+ });
+ await waitFor(() =>
+ expect(result.current.rows[0]).toMatchObject({
+ title: 'Renamed',
+ pinned: true,
+ isShared: true,
+ lastResponseAt: newerReply,
+ }),
+ );
+ expect(getConversationById).toHaveBeenCalledTimes(1);
+
+ await act(async () => initial.resolve(record()));
+ expect(result.current.rows[0]?.title).toBe('Renamed');
+ },
+ );
+
+ it('restarts an interrupted initial fetch when no local row is available', async () => {
+ const initial = deferred<TConversation>();
+ getConversationById.mockReturnValueOnce(initial.promise).mockResolvedValue(record());
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+
+ act(() => updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Changed' })));
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ await act(async () => initial.resolve(record({ title: 'Stale' })));
+ expect(result.current[0]?.title).not.toBe('Stale');
+ });
+
+ it('does not create a Running query just because an unrelated cached chat changes', () => {
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], record());
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Changed' }));
+ expect(queryClient.getQueryState([QueryKeys.runningConversation, 'c1'])).toBeUndefined();
+ });
+
+ it('preserves sidebar flags and read state when replacing a running row', async () => {
+ const stamps = {
+ lastResponseAt: '2026-01-02T00:00:00.000Z',
+ lastSeenAt: '2026-01-01T00:00:00.000Z',
+ };
+ getConversationById.mockResolvedValue(record({ pinned: true, ...stamps }));
+ getSharedLink.mockResolvedValue({
+ shareId: 'share-1',
+ success: true,
+ } as TSharedLinkGetResponse);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+
+ act(() => updateConvoInAllQueries(queryClient, 'c1', () => record({ title: 'New title' })));
+ await waitFor(() =>
+ expect(result.current[0]).toMatchObject({
+ title: 'New title',
+ pinned: true,
+ isShared: true,
+ ...stamps,
+ }),
+ );
+ });
+
+ it('does not seed the navigation cache after its last observer leaves', async () => {
+ const pending = deferred<TConversation>();
+ getConversationById.mockReturnValue(pending.promise);
+ const { unmount } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalled());
+ unmount();
+ await act(async () => pending.resolve(record()));
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'c1'])).toBeUndefined();
+ });
+
+ it('drops a removed row without allowing an older poll to restore it', async () => {
+ const poll = deferred<TConversation>();
+ getConversationById.mockResolvedValueOnce(record()).mockReturnValueOnce(poll.promise);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ const refetch = queryClient.refetchQueries([QueryKeys.runningConversation, 'c1']);
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(2));
+
+ act(() => removeConvoFromAllQueries(queryClient, 'c1'));
+ await act(async () => {
+ poll.resolve(record());
+ await refetch;
+ });
+ await waitFor(() => expect(result.current).toEqual([]));
+ });
+
+ it('does not restore an archived row when an older navigation request completes', async () => {
+ const navigation = deferred<TConversation>();
+ getConversationById.mockResolvedValueOnce(record()).mockReturnValueOnce(navigation.promise);
+ jest.mocked(dataService.archiveConversation).mockResolvedValue(record({ isArchived: true }));
+ const { result } = renderHook(
+ () => ({
+ rows: useRunningConversationsQuery(['c1']),
+ archive: useArchiveConvoMutation(),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.rows).toHaveLength(1));
+ const refresh = queryClient
+ .fetchQuery([QueryKeys.conversation, 'c1'], () => dataService.getConversationById('c1'))
+ .then((data) =>
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({
+ ...row,
+ endpoint: data.endpoint,
+ model: data.model,
+ spec: data.spec,
+ })),
+ );
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(2));
+
+ await act(async () => {
+ await result.current.archive.mutateAsync({ conversationId: 'c1', isArchived: true });
+ });
+ await waitFor(() => expect(result.current.rows).toEqual([]));
+ await act(async () => {
+ navigation.resolve(record({ isArchived: false }));
+ await refresh;
+ });
+ expect(queryClient.getQueryData([QueryKeys.runningConversation, 'c1'])).toBeNull();
+ await waitFor(() => expect(result.current.rows).toEqual([]));
+ expect(getConversationById).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(['single', 'all'] as const)(
+ 'fences %s archive before a Running query is created',
+ async (mode) => {
+ const ordinary = record({ chatProjectId: null });
+ queryClient.setQueryData([QueryKeys.allConversations], {
+ pages: [{ conversations: [ordinary], nextCursor: null }],
+ pageParams: [undefined],
+ });
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], ordinary);
+ const navigation = deferred<TConversation>();
+ const running = deferred<TConversation>();
+ getConversationById
+ .mockReturnValueOnce(navigation.promise)
+ .mockReturnValueOnce(running.promise);
+ jest
+ .mocked(dataService.archiveConversation)
+ .mockResolvedValue({ ...ordinary, isArchived: true });
+ jest.mocked(dataService.archiveAllConversations).mockResolvedValue({ archivedCount: 1 });
+ const { result, rerender } = renderHook(
+ ({ ids }: { ids: string[] }) => ({
+ rows: useRunningConversationsQuery(ids),
+ archive: useArchiveConvoMutation(),
+ archiveAll: useArchiveAllConversationsMutation(),
+ }),
+ { wrapper, initialProps: { ids: [] as string[] } },
+ );
+ expect(queryClient.getQueryState([QueryKeys.runningConversation, 'c1'])).toBeUndefined();
+ const refresh = queryClient
+ .fetchQuery([QueryKeys.conversation, 'c1'], () => dataService.getConversationById('c1'))
+ .then((data) =>
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, model: data.model })),
+ )
+ .catch(() => undefined);
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ if (mode === 'single') {
+ await result.current.archive.mutateAsync({ conversationId: 'c1', isArchived: true });
+ } else {
+ await result.current.archiveAll.mutateAsync();
+ }
+ });
+ rerender({ ids: ['c1'] });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(2));
+ await act(async () => {
+ navigation.resolve(ordinary);
+ await refresh;
+ });
+ expect(queryClient.getQueryData([QueryKeys.runningConversation, 'c1'])).toBeUndefined();
+ expect(getConversationById.mock.calls[1][1]?.aborted).toBe(false);
+ await act(async () => running.resolve({ ...ordinary, isArchived: true }));
+ await waitFor(() => expect(result.current.rows[0]?.isArchived).toBe(true));
+ },
+ );
+
+ it('keeps a removed initial row absent until a fresh visible record arrives', async () => {
+ const initial = deferred<TConversation>();
+ getConversationById
+ .mockReturnValueOnce(initial.promise)
+ .mockResolvedValue(record({ title: 'Restored' }));
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+ act(() => {
+ removeConvoFromAllQueries(queryClient, 'c1');
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], record());
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Stale update' }));
+ });
+ await waitFor(() => expect(result.current).toEqual([]));
+ expect(getConversationById).toHaveBeenCalledTimes(1);
+ await act(async () => initial.resolve(record()));
+ expect(result.current).toEqual([]);
+
+ await act(async () => {
+ await queryClient.refetchQueries([QueryKeys.runningConversation, 'c1']);
+ });
+ await waitFor(() => expect(result.current[0]?.title).toBe('Restored'));
+ act(() =>
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Current update' })),
+ );
+ await waitFor(() => expect(result.current[0]?.title).toBe('Current update'));
+ });
+
+ it('does not let local updates make an authoritatively archived record visible again', async () => {
+ getConversationById
+ .mockResolvedValueOnce(record())
+ .mockResolvedValue(record({ isArchived: true }));
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ act(() => removeConvoFromAllQueries(queryClient, 'c1'));
+ await act(async () => {
+ await queryClient.refetchQueries([QueryKeys.runningConversation, 'c1']);
+ });
+ await waitFor(() => expect(result.current[0]?.isArchived).toBe(true));
+
+ act(() => updateConvoInAllQueries(queryClient, 'c1', () => record({ isArchived: false })));
+ expect(
+ queryClient.getQueryData<TConversation>([QueryKeys.runningConversation, 'c1'])?.isArchived,
+ ).toBe(true);
+ await waitFor(() => expect(result.current[0]?.isArchived).toBe(true));
+ });
+
+ it.each([{ isArchived: true }, { isTemporary: true }, { expiredAt: '2026-12-31T00:00:00.000Z' }])(
+ 'keeps invisible server records from being revived by local state: %j',
+ async (visibility) => {
+ const invisible = record(visibility);
+ getConversationById.mockResolvedValue(invisible);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ expect(queryClient.getQueryData([QueryKeys.conversation, 'c1'])).toBeUndefined();
+ act(() => updateConvoInAllQueries(queryClient, 'c1', () => record()));
+ expect(
+ queryClient.getQueryData<TConversation>([QueryKeys.runningConversation, 'c1']),
+ ).toMatchObject(visibility);
+ },
+ );
+
+ it.each(['single', 'all'] as const)(
+ 'releases a %s removal only after a visible server result',
+ async (mode) => {
+ const pending = deferred<TConversation>();
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], record());
+ if (mode === 'single') {
+ markRunningRemoval(queryClient, 'c1');
+ } else {
+ markRunningRemoval(queryClient);
+ }
+ getConversationById.mockReturnValue(pending.promise);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+ act(() =>
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Stale update' })),
+ );
+ expect(queryClient.getQueryData([QueryKeys.runningConversation, 'c1'])).toBeUndefined();
+ await act(async () => pending.resolve(record({ title: 'Restored' })));
+ await waitFor(() => expect(result.current[0]?.title).toBe('Restored'));
+ act(() =>
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Current update' })),
+ );
+ await waitFor(() => expect(result.current[0]?.title).toBe('Current update'));
+ },
+ );
+
+ it.each(['cache-clear', 'new-account'] as const)(
+ 'does not retain removal state across %s',
+ async (reset) => {
+ const signIn = (id: string) =>
+ setTokenHeader(`header.${btoa(JSON.stringify({ id }))}.signature`);
+ signIn('old-user');
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], record());
+ markRunningRemoval(queryClient, 'c1');
+ if (reset === 'cache-clear') {
+ queryClient.clear();
+ } else {
+ signIn('new-user');
+ }
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], record());
+ const pending = deferred<TConversation>();
+ getConversationById.mockReturnValue(pending.promise);
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(1));
+ act(() =>
+ updateConvoInAllQueries(queryClient, 'c1', (row) => ({ ...row, title: 'Current session' })),
+ );
+ await waitFor(() => expect(result.current[0]?.title).toBe('Current session'));
+ await act(async () => pending.resolve(record()));
+ expect(result.current[0]?.title).toBe('Current session');
+ },
+ );
+
+ it('uses the newest running row when reading cached reply state', () => {
+ queryClient.setQueryData([QueryKeys.conversation, 'c1'], record());
+ const running = record({ lastResponseAt: '2026-01-03T00:00:00.000Z' });
+ queryClient.setQueryData([QueryKeys.runningConversation, 'c1'], running);
+ expect(findConvoInAllQueries(queryClient, 'c1')?.lastResponseAt).toBe(running.lastResponseAt);
+ });
+
+ it('uses a newer Running poll over an older point-query read snapshot', async () => {
+ let now = 1000;
+ const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
+ const reply = { lastResponseAt: '2026-01-03T00:00:00.000Z' };
+ try {
+ getConversationById.mockResolvedValue(record(reply));
+ const { result } = renderHook(() => useRunningConversationsQuery(['c1']), { wrapper });
+ await waitFor(() => expect(result.current).toHaveLength(1));
+ findConvoInAllQueries(queryClient, 'c1');
+ now += 1000;
+ await act(async () => {
+ await queryClient.fetchQuery([QueryKeys.conversation, 'c1'], () =>
+ dataService.getConversationById('c1'),
+ );
+ });
+ now += 1000;
+ const seen = '2026-01-04T00:00:00.000Z';
+ getConversationById.mockResolvedValue(record({ ...reply, lastSeenAt: seen }));
+ await act(async () => {
+ await queryClient.refetchQueries([QueryKeys.runningConversation, 'c1']);
+ });
+ expect(findConvoInAllQueries(queryClient, 'c1')?.lastSeenAt).toBe(seen);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
+ it('publishes a project assignment to the running row immediately', async () => {
+ const claims = btoa(JSON.stringify({ id: 'user-a' })).replace(/=+$/, '');
+ setTokenHeader(`header.${claims}.signature`);
+ getConversationById.mockResolvedValue(record());
+ jest.mocked(dataService.assignConversationToProject).mockResolvedValue({
+ conversation: record({ chatProjectId: 'project-2' }),
+ projectId: 'project-2',
+ previousProjectId: 'project-1',
+ });
+ const { result } = renderHook(
+ () => ({
+ rows: useRunningConversationsQuery(['c1']),
+ assignment: useAssignConversationToProjectMutation(),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.rows).toHaveLength(1));
+ getConversationById.mockResolvedValue(record({ chatProjectId: 'project-2' }));
+
+ await act(async () => {
+ await result.current.assignment.mutateAsync({ conversationId: 'c1', projectId: 'project-2' });
+ });
+ await waitFor(() => expect(result.current.rows[0]?.chatProjectId).toBe('project-2'));
+ });
+
+ it('refreshes running rows immediately after Archive All', async () => {
+ getConversationById
+ .mockResolvedValueOnce(record())
+ .mockResolvedValue(record({ isArchived: true }));
+ jest.mocked(dataService.archiveAllConversations).mockResolvedValue({ archivedCount: 1 });
+ const { result } = renderHook(
+ () => ({
+ rows: useRunningConversationsQuery(['c1']),
+ archive: useArchiveAllConversationsMutation(),
+ }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.rows).toHaveLength(1));
+
+ await act(async () => {
+ await result.current.archive.mutateAsync();
+ });
+ await waitFor(() => expect(getConversationById).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(result.current.rows[0]?.isArchived).toBe(true));
+ });
+});
diff --git a/client/src/data-provider/mutations.ts b/client/src/data-provider/mutations.ts
index dc25b0b431..cdc3e18162 100644
--- a/client/src/data-provider/mutations.ts
+++ b/client/src/data-provider/mutations.ts
@@ -12,6 +12,7 @@ import {
logger,
/* Conversations */
addConvoToAllQueries,
+ markRunningRemoval,
findPinnedConversation,
findConvoInAllQueries,
findConversationInInfinite,
@@ -182,6 +183,10 @@ export const useArchiveAllConversationsMutation = (
const { onSuccess, onError, ..._options } = options || {};
const reconcileCaches = () => {
+ markRunningRemoval(queryClient);
+ void queryClient.cancelQueries([QueryKeys.runningConversation]);
+ queryClient.setQueriesData<t.TConversation | null>([QueryKeys.runningConversation], null);
+ queryClient.invalidateQueries([QueryKeys.runningConversation]);
/* Archiving everything leaves no cached list trustworthy, but only the mounted ones are
worth the round trips: the rest are dropped, so a remembered sort or bookmark variant
cannot render chats that are all archived now and refetches from scratch when mounted. */
@@ -295,6 +300,7 @@ const cancelConvoReadFetches = async (
const roots = [
...CONVERSATION_LIST_KEYS.map((listKey) => [listKey]),
[QueryKeys.pinnedConversations],
+ [QueryKeys.runningConversation, conversationId],
];
const cache = queryClient.getQueryCache();
/* Recorded before the cancellation, because a cancelled fetch was carrying rows this
@@ -346,6 +352,7 @@ const refreshConvoReadCaches = (queryClient: QueryClient, conversationId: string
queryClient.invalidateQueries([listKey]);
}
queryClient.invalidateQueries([QueryKeys.pinnedConversations]);
+ queryClient.invalidateQueries([QueryKeys.runningConversation, conversationId]);
const pointKey = [QueryKeys.conversation, conversationId];
if (queryClient.getQueryData(pointKey) !== undefined) {
queryClient.invalidateQueries(pointKey);
diff --git a/client/src/data-provider/queries.ts b/client/src/data-provider/queries.ts
index 2a3fd1c9c2..a42e33cb4a 100644
--- a/client/src/data-provider/queries.ts
+++ b/client/src/data-provider/queries.ts
@@ -1,4 +1,5 @@
-import { useQuery, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
+import { useRef } from 'react';
+import { useQuery, useQueries, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import {
QueryKeys,
dataService,
@@ -31,7 +32,12 @@ import type {
} from '@tanstack/react-query';
import type t from 'librechat-data-provider';
import type { ConversationCursorData } from '~/utils/convos';
-import { findConversationInInfinite, isNotFoundError } from '~/utils';
+import {
+ acceptRunningConversation,
+ findConversationInInfinite,
+ isNotFoundError,
+ toSidebarConversation,
+} from '~/utils';
export const useGetPresetsQuery = (
config?: UseQueryOptions<TPreset[]>,
@@ -82,6 +88,92 @@ export const useGetConvoIdQuery = (
);
};
+const RUNNING_CONVERSATION_REFRESH_MS = 15_000;
+const RUNNING_CONVERSATION_MISSING_RETRY_MS = 2_000;
+const noRunningConversations: t.TConversation[] = [];
+
+/** The list endpoints derive `isShared` from active shared links; the record alone lacks it. */
+async function hasActiveSharedLink(
+ conversationId: string,
+ signal?: AbortSignal,
+): Promise<boolean | undefined> {
+ try {
+ const link = await dataService.getSharedLink(conversationId, signal);
+ return link.shareId != null;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Rows for running chats that no loaded sidebar list holds: chats filed in a project,
+ * pinned chats, and chats past the pages fetched so far. Each row refreshes while it is
+ * shown, so a title generated mid-run reaches it. A chat whose record is not written yet
+ * reads as absent and is asked again within seconds, so a short run is not missed.
+ *
+ * The rows live under their own key so a pending or absent result never lands in the
+ * cache the chat view reads; a complete record seeds that cache only where it is empty.
+ */
+export const useRunningConversationsQuery = (
+ conversationIds: readonly string[],
+): t.TConversation[] => {
+ const queryClient = useQueryClient();
+ const results = useQueries({
+ queries: conversationIds.map(
+ (conversationId): UseQueryOptions<t.TConversation | null> => ({
+ queryKey: [QueryKeys.runningConversation, conversationId],
+ queryFn: async ({ signal }): Promise<t.TConversation | null> => {
+ try {
+ const [conversation, isShared] = await Promise.all([
+ dataService.getConversationById(conversationId, signal),
+ hasActiveSharedLink(conversationId, signal),
+ ]);
+ signal?.throwIfAborted();
+ return isShared === undefined ? conversation : { ...conversation, isShared };
+ } catch (error) {
+ if (isNotFoundError(error)) {
+ return null;
+ }
+ throw error;
+ }
+ },
+ onSuccess: (conversation: t.TConversation | null) => {
+ if (
+ !conversation ||
+ !acceptRunningConversation(queryClient, conversationId, conversation)
+ ) {
+ return;
+ }
+ const conversationKey = [QueryKeys.conversation, conversationId];
+ if (queryClient.getQueryData(conversationKey) === undefined) {
+ queryClient.setQueryData(conversationKey, conversation);
+ }
+ },
+ staleTime: RUNNING_CONVERSATION_REFRESH_MS,
+ refetchInterval: (data: t.TConversation | null | undefined) =>
+ data === null ? RUNNING_CONVERSATION_MISSING_RETRY_MS : RUNNING_CONVERSATION_REFRESH_MS,
+ refetchOnWindowFocus: false,
+ }),
+ ),
+ });
+
+ const recordsRef = useRef<t.TConversation[]>(noRunningConversations);
+ const rowsRef = useRef<t.TConversation[]>(noRunningConversations);
+ const records = results
+ .map((result) => result.data)
+ .filter((record): record is t.TConversation => record != null);
+ const previous = recordsRef.current;
+ if (
+ records.length !== previous.length ||
+ records.some((record, index) => record !== previous[index])
+ ) {
+ recordsRef.current = records;
+ rowsRef.current =
+ records.length === 0 ? noRunningConversations : records.map(toSidebarConversation);
+ }
+ return rowsRef.current;
+};
+
export const useConversationsInfiniteQuery = (
params: ConversationListParams,
config?: UseInfiniteQueryOptions<ConversationListResponse, unknown>,
diff --git a/client/src/hooks/Conversations/__tests__/useNavigateToConvo.spec.tsx b/client/src/hooks/Conversations/__tests__/useNavigateToConvo.spec.tsx
index da092bc20e..cf1764956f 100644
--- a/client/src/hooks/Conversations/__tests__/useNavigateToConvo.spec.tsx
+++ b/client/src/hooks/Conversations/__tests__/useNavigateToConvo.spec.tsx
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter, useLocation, useNavigate } from 'react-router-dom';
import type { TConversation, TEndpointsConfig } from 'librechat-data-provider';
import useNavigateToConvo, { supersedeNavigation } from '../useNavigateToConvo';
+import { useRunningConversationsQuery } from '~/data-provider/queries';
import { SetConvoProvider } from '~/Providers';
import store from '~/store';
@@ -27,6 +28,7 @@ jest.mock('librechat-data-provider', () => ({
dataService: {
...jest.requireActual('librechat-data-provider').dataService,
getConversationById: (...args: unknown[]) => mockGetConversationById(...(args as [string])),
+ getSharedLink: jest.fn().mockResolvedValue({ shareId: null, success: true }),
},
}));
@@ -71,7 +73,8 @@ const endpointsConfig = { openAI: {} } as unknown as TEndpointsConfig;
const notFound = () => ({ status: 404, message: 'not found' });
-function Harness() {
+function Harness({ runningIds = [] }: { runningIds?: string[] }) {
+ const runningRows = useRunningConversationsQuery(runningIds);
const { navigateToConvo } = useNavigateToConvo();
const conversation = useRecoilValue(store.conversationByIndex(0));
const { setConversation } = store.useSetConversationAtom(0);
@@ -85,6 +88,11 @@ function Harness() {
onClick={() => navigateToConvo(rowB, { currentConvoId: 'convo-a' })}
/>
<button data-testid="go-c" onClick={() => navigateToConvo(rowC, { currentConvoId: B })} />
+ <button
+ data-testid="go-running-b"
+ disabled={runningRows.length === 0}
+ onClick={() => navigateToConvo(runningRows[0], { currentConvoId: 'convo-a' })}
+ />
{/* Every other way out of a conversation — "New chat", a link, a
redirect, the back button — moves the route without going through
`navigateToConvo`, exactly like `useNewConvo` does. */}
@@ -125,7 +133,7 @@ function Harness() {
/** A real history, not `MemoryRouter`: the hook abandons superseded work by
* reading the browser's own location, so the test has to move it for real. */
-function renderHarness(cached: TConversation[] = []) {
+function renderHarness(cached: TConversation[] = [], runningIds: string[] = []) {
window.history.pushState({}, '', '/c/convo-a');
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -143,7 +151,7 @@ function renderHarness(cached: TConversation[] = []) {
<RecoilRoot>
<QueryClientProvider client={queryClient}>
<SetConvoProvider>
- <Harness />
+ <Harness runningIds={runningIds} />
</SetConvoProvider>
</QueryClientProvider>
</RecoilRoot>
@@ -188,6 +196,56 @@ describe('useNavigateToConvo', () => {
mockPending.clear();
});
+ describe('with a fetched Running row', () => {
+ it('keeps a newer approval choice when reopening a running project chat', async () => {
+ const queryClient = renderHarness([], [B]);
+ await waitFor(() =>
+ expect(mockGetConversationById).toHaveBeenCalledWith(B, expect.any(AbortSignal)),
+ );
+ await settle(B, { ...recordB, chatProjectId: 'project-1', codeApprovalMode: 'fullAccess' });
+ await waitFor(() => expect(screen.getByTestId('go-running-b')).not.toBeDisabled());
+
+ act(() =>
+ queryClient.setQueryData<TConversation>([QueryKeys.conversation, B], (record) => ({
+ ...record!,
+ codeApprovalMode: 'ask',
+ })),
+ );
+ click('go-running-b');
+
+ expect(currentPath()).toBe(`/c/${B}`);
+ expect(currentConvo()?.codeApprovalMode).toBe('ask');
+ expect(currentConvo()?.chatProjectId).toBe('project-1');
+ });
+
+ it('keeps chat-owned prompt, sampling and workspace choices while accepting fresh row metadata', async () => {
+ const queryClient = renderHarness([], [B]);
+ await waitFor(() => expect(mockGetConversationById).toHaveBeenCalled());
+ await settle(B, {
+ ...recordB,
+ title: 'Fresh running title',
+ codeEnvironmentMode: 'without_attached',
+ });
+ await waitFor(() => expect(screen.getByTestId('go-running-b')).not.toBeDisabled());
+ act(() =>
+ queryClient.setQueryData<TConversation>([QueryKeys.conversation, B], (record) => ({
+ ...record!,
+ promptPrefix: 'New local instructions',
+ temperature: 0.7,
+ codeEnvironmentMode: 'attached',
+ })),
+ );
+ click('go-running-b');
+
+ expect(currentConvo()).toMatchObject({
+ title: 'Fresh running title',
+ promptPrefix: 'New local instructions',
+ temperature: 0.7,
+ codeEnvironmentMode: 'attached',
+ });
+ });
+ });
+
describe('with the full record already cached', () => {
it('changes the route and the conversation together, without waiting on the fetch', () => {
renderHarness([recordB]);
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 08c019bc6b..7aea121390 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -82,6 +82,9 @@ const mockFetchQuery = jest.fn();
const mockInvalidateQueries = jest.fn();
const mockRemoveQueries = jest.fn();
const mockBackingQueryClient = new QueryClient();
+const mockCancelQueries = jest.fn(
+ mockBackingQueryClient.cancelQueries.bind(mockBackingQueryClient),
+);
const mockQueryCache = mockBackingQueryClient.getQueryCache();
const mockFindAll = jest.fn((_queryKey?: QueryKey): Query[] => []);
const mockQueryClient = {
@@ -90,6 +93,8 @@ const mockQueryClient = {
fetchQuery: mockFetchQuery,
invalidateQueries: mockInvalidateQueries,
removeQueries: mockRemoveQueries,
+ cancelQueries: mockCancelQueries,
+ getQueryState: mockBackingQueryClient.getQueryState.bind(mockBackingQueryClient),
getQueryCache: () => ({
findAll: mockFindAll,
getAll: mockQueryCache.getAll.bind(mockQueryCache),
@@ -426,6 +431,7 @@ describe('useResumableSSE', () => {
);
mockInvalidateQueries.mockClear();
mockRemoveQueries.mockClear();
+ mockCancelQueries.mockClear();
mockFindAll.mockReset();
mockFindAll.mockReturnValue([]);
mockBackingQueryClient.clear();
@@ -782,6 +788,11 @@ describe('useResumableSSE', () => {
queryKey: ['streamStatus', 'stream-123'],
});
+ expect(mockCancelQueries).toHaveBeenCalledWith({
+ queryKey: [QueryKeys.runningConversation, 'stream-123'],
+ exact: true,
+ });
+
const allConversationWrites = mockSetQueryData.mock.calls.filter(
([queryKey]) => Array.isArray(queryKey) && queryKey[0] === QueryKeys.allConversations,
);
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index d6d04718e3..1dca5f0bae 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2184,6 +2184,7 @@
"com_ui_pro": "Pro",
"com_ui_production": "Production",
"com_ui_project": "Project",
+ "com_ui_in_project": "In {{name}}",
"com_ui_project_add_files": "Add files",
"com_ui_project_files_info": "About project files",
"com_ui_project_instructions_info": "About project instructions",
diff --git a/client/src/utils/conversation.ts b/client/src/utils/conversation.ts
index 31cdc39ebe..1675d2cecf 100644
--- a/client/src/utils/conversation.ts
+++ b/client/src/utils/conversation.ts
@@ -1,5 +1,38 @@
+import { pick } from 'lodash';
import type { TConversation } from 'librechat-data-provider';
export const isTemporaryConversation = (conversation?: Partial<TConversation> | null): boolean =>
conversation?.isTemporary === true ||
(conversation?.isTemporary === undefined && conversation?.expiredAt != null);
+
+const sidebarFields = [
+ 'conversationId',
+ 'title',
+ 'endpoint',
+ 'endpointType',
+ 'model',
+ 'modelLabel',
+ 'chatGptLabel',
+ 'agent_id',
+ 'assistant_id',
+ 'spec',
+ 'iconURL',
+ 'user',
+ 'chatProjectId',
+ 'pinned',
+ 'isArchived',
+ 'isShared',
+ 'createdAt',
+ 'updatedAt',
+ 'archivedAt',
+ 'lastResponseAt',
+ 'lastResponseMessageId',
+ 'lastResponseIsManual',
+ 'lastSeenAt',
+ 'isTemporary',
+ 'expiredAt',
+] as const satisfies readonly (keyof TConversation)[];
+
+/** Sidebar metadata may overlay navigation records; chat-owned settings must not. */
+export const toSidebarConversation = (conversation: TConversation): TConversation =>
+ pick(conversation, sidebarFields);
diff --git a/client/src/utils/convos.ts b/client/src/utils/convos.ts
index 35384836ea..f050dc30f3 100644
--- a/client/src/utils/convos.ts
+++ b/client/src/utils/convos.ts
@@ -14,6 +14,7 @@ import type { TConversation, TMessage, GroupedConversations } from 'librechat-da
import type { InvalidateQueryFilters } from '@tanstack/react-query';
import type { InfiniteData, Query } from '@tanstack/react-query';
import { isTemporaryConversation } from './conversation';
+import { getSessionPrincipal } from './session';
/**
* A conversation is unseen when a reply landed after the user last caught up with it.
@@ -313,7 +314,7 @@ export function invalidateConversationLists(
filters?: Omit<InvalidateQueryFilters, 'queryKey'>,
): Promise<void> {
return Promise.all(
- CONVERSATION_LIST_KEYS.map((listKey) =>
+ [...CONVERSATION_LIST_KEYS, QueryKeys.runningConversation].map((listKey) =>
queryClient.invalidateQueries({ queryKey: [listKey], ...filters }),
),
).then(() => undefined);
@@ -883,6 +884,7 @@ export const trackConvoQueryAuthority = (
if (
root !== QueryKeys.allConversations &&
root !== QueryKeys.pinnedConversations &&
+ root !== QueryKeys.runningConversation &&
root !== QueryKeys.conversation
) {
return;
@@ -1435,6 +1437,19 @@ export function findConvoInAllQueries(
}
freshest = freshestCandidate(freshest, findPinnedCandidate(queryClient, conversationId));
+ const runningKey = [QueryKeys.runningConversation, conversationId];
+ const runningQuery = queryClient.getQueryCache().find(runningKey);
+ if (runningQuery) {
+ freshest = freshestCandidate(
+ freshest,
+ candidateFrom(
+ queryClient,
+ runningQuery,
+ queryClient.getQueryData<TConversation | null>(runningKey) ?? undefined,
+ ),
+ );
+ }
+
/* The conversation opened by URL is loaded into its own point query, and an old one need not
appear in any loaded list page at all. Without this it would read as absent, absent reads
as caught up, and the reply the user is looking at would never be acknowledged. */
@@ -1448,15 +1463,141 @@ export function findConvoInAllQueries(
)?.convo;
}
+type RunningRemovalState = {
+ owner?: string;
+ all: boolean;
+ removed: Set<string>;
+ visible: Set<string>;
+};
+
+const removedRunningQueries = new WeakMap<QueryClient, RunningRemovalState>();
+
+function runningRemovalState(queryClient: QueryClient): RunningRemovalState {
+ const owner = getSessionPrincipal();
+ const existing = removedRunningQueries.get(queryClient);
+ if (existing) {
+ if (existing.owner !== owner) {
+ existing.owner = owner;
+ existing.all = false;
+ existing.removed.clear();
+ existing.visible.clear();
+ }
+ return existing;
+ }
+ const state: RunningRemovalState = {
+ owner,
+ all: false,
+ removed: new Set(),
+ visible: new Set(),
+ };
+ removedRunningQueries.set(queryClient, state);
+ const cache = queryClient.getQueryCache();
+ cache.subscribe((event) => {
+ if (event.type === 'removed' && cache.getAll().length === 0) {
+ state.all = false;
+ state.removed.clear();
+ state.visible.clear();
+ }
+ });
+ return state;
+}
+
+function runningWasRemoved(queryClient: QueryClient, conversationId: string): boolean {
+ const existing = removedRunningQueries.get(queryClient);
+ if (
+ !existing ||
+ (!existing.removed.has(conversationId) &&
+ (!existing.all || existing.visible.has(conversationId)))
+ ) {
+ return false;
+ }
+ const state = runningRemovalState(queryClient);
+ return state.removed.has(conversationId) || (state.all && !state.visible.has(conversationId));
+}
+
+/** Records explicit removal independently of whether a Running query exists. */
+export function markRunningRemoval(queryClient: QueryClient, conversationId?: string): void {
+ const state = runningRemovalState(queryClient);
+ if (conversationId === undefined) {
+ state.all = true;
+ state.removed.clear();
+ state.visible.clear();
+ return;
+ }
+ if (state.all) {
+ state.visible.delete(conversationId);
+ } else {
+ state.removed.add(conversationId);
+ }
+}
+
+/** Accepts only the current server result; a visible result releases a removal fence. */
+export function acceptRunningConversation(
+ queryClient: QueryClient,
+ conversationId: string,
+ conversation: TConversation,
+): boolean {
+ const query = queryClient.getQueryCache().find([QueryKeys.runningConversation, conversationId]);
+ if (!query || query.state.data !== conversation) {
+ return false;
+ }
+ if (conversation.isArchived === true || isTemporaryConversation(conversation)) {
+ markRunningRemoval(queryClient, conversationId);
+ return false;
+ }
+ const existing = removedRunningQueries.get(queryClient);
+ if (existing) {
+ const state = runningRemovalState(queryClient);
+ state.removed.delete(conversationId);
+ if (state.all) {
+ state.visible.add(conversationId);
+ }
+ }
+ return true;
+}
+
export function updateConvoInAllQueries(
queryClient: QueryClient,
conversationId: string,
updater: (c: TConversation) => TConversation,
moveToTop = false,
) {
+ const runningKey = [QueryKeys.runningConversation, conversationId];
+ const runningState = queryClient.getQueryState<TConversation | null>(runningKey);
+ const removed = runningState != null && runningWasRemoved(queryClient, conversationId);
+ const cached =
+ !removed && runningState && runningState.data == null
+ ? findConvoInAllQueries(queryClient, conversationId)
+ : undefined;
+ const cachedPin = cached && findPinnedConversation(queryClient, conversationId);
+ const initialRow =
+ cached && cachedPin
+ ? { ...cached, pinned: cachedPin.pinned, isShared: cachedPin.isShared ?? cached.isShared }
+ : cached;
+ const restartInitialFetch =
+ !removed &&
+ runningState?.fetchStatus === 'fetching' &&
+ runningState.data == null &&
+ !initialRow;
+
+ if (!removed) {
+ void queryClient.cancelQueries({ queryKey: runningKey, exact: true });
+ }
queryClient.setQueryData<TConversation>([QueryKeys.conversation, conversationId], (current) =>
current ? updater(current) : current,
);
+ if (!removed) {
+ queryClient.setQueryData<TConversation | null>(runningKey, (current) => {
+ const previous = current ?? initialRow;
+ if (!previous) {
+ return current;
+ }
+ const next = preserveReadState(preserveListFlags(updater(previous), previous), previous);
+ return moveToTop && next.updatedAt === previous.updatedAt
+ ? { ...next, updatedAt: new Date().toISOString() }
+ : next;
+ });
+ }
updatePinnedConvosQuery(queryClient, conversationId, updater, moveToTop);
const queries = findConversationListQueries(queryClient);
@@ -1554,11 +1695,20 @@ export function updateConvoInAllQueries(
queryClient.invalidateQueries({ queryKey: query.queryKey, refetchType: 'active' });
}
}
+ if (restartInitialFetch) {
+ void queryClient.invalidateQueries({ queryKey: runningKey, exact: true });
+ }
}
// Remove
export function removeConvoFromAllQueries(queryClient: QueryClient, conversationId: string) {
+ const runningKey = [QueryKeys.runningConversation, conversationId];
+ markRunningRemoval(queryClient, conversationId);
+ void queryClient.cancelQueries({ queryKey: runningKey, exact: true });
updatePinnedConvosQuery(queryClient, conversationId, () => null);
+ queryClient.setQueryData<TConversation | null>(runningKey, (current) =>
+ current === undefined ? current : null,
+ );
const queries = findConversationListQueries(queryClient);
diff --git a/packages/client/src/components/SelectDropDown.tsx b/packages/client/src/components/SelectDropDown.tsx
index 6cad33796c..954fee3ceb 100644
--- a/packages/client/src/components/SelectDropDown.tsx
+++ b/packages/client/src/components/SelectDropDown.tsx
@@ -1,4 +1,4 @@
-import React, { useRef } from 'react';
+import React from 'react';
import { JSX } from 'react/jsx-runtime';
import {
Label,
@@ -99,8 +99,6 @@ function SelectDropDown({
const options = hasSearchRender ? filteredValues : values;
const renderIcon = showOptionIcon && value != null && (value as OptionWithIcon).icon != null;
- const buttonRef = useRef<HTMLButtonElement>(null);
-
return (
<div className={cn('flex items-center justify-center gap-2', containerClassName ?? '')}>
<div className={cn('relative w-full', subContainerClassName ?? '')}>
@@ -108,14 +106,16 @@ function SelectDropDown({
{({ open }) => (
<>
<ListboxButton
- ref={buttonRef}
data-testid="select-dropdown-button"
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- if (!open && buttonRef.current) {
- buttonRef.current.click();
- }
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter') {
+ return;
+ }
+ event.preventDefault();
+ if (!open) {
+ event.currentTarget.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }),
+ );
}
}}
className={cn(
diff --git a/packages/client/src/components/__tests__/SelectDropDown.spec.tsx b/packages/client/src/components/__tests__/SelectDropDown.spec.tsx
index b55effe9ed..1711f7f737 100644
--- a/packages/client/src/components/__tests__/SelectDropDown.spec.tsx
+++ b/packages/client/src/components/__tests__/SelectDropDown.spec.tsx
@@ -1,5 +1,7 @@
+import { useState } from 'react';
import userEvent from '@testing-library/user-event';
-import { render, screen } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import type { FormEvent } from 'react';
import SelectDropDown from '../SelectDropDown';
const OPTIONS = [
@@ -12,6 +14,53 @@ async function openList() {
}
describe('SelectDropDown', () => {
+ it.each(['{Enter}', ' '])(
+ 'reopens an empty picker with %s after clearing its value',
+ async (key) => {
+ function Picker() {
+ const [value, setValue] = useState<(typeof OPTIONS)[number] | null>(OPTIONS[1]);
+ return (
+ <SelectDropDown
+ value={value}
+ setValue={(next) => setValue(next as typeof value)}
+ availableValues={OPTIONS}
+ placeholder="Create Assistant"
+ renderOption={() => <span>Create Assistant</span>}
+ showLabel={false}
+ emptyTitle={true}
+ />
+ );
+ }
+ const user = userEvent.setup();
+ const onSubmit = jest.fn((event: FormEvent<HTMLFormElement>) => event.preventDefault());
+ render(
+ <form onSubmit={onSubmit}>
+ <Picker />
+ </form>,
+ );
+ const button = screen.getByTestId('select-dropdown-button');
+ await act(async () => {
+ await user.click(button);
+ });
+ await act(async () => {
+ await user.click(await screen.findByRole('option', { name: 'Create Assistant' }));
+ });
+ expect(button).toHaveTextContent('Create Assistant');
+
+ await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument());
+ act(() => button.focus());
+ await act(async () => {
+ await user.keyboard(key);
+ });
+ await waitFor(() => expect(screen.getByRole('listbox')).toBeVisible());
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(screen.getByRole('option', { name: 'Second' }).querySelector('svg')).toBeNull();
+ await act(async () => {
+ await user.keyboard('{Escape}');
+ });
+ await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument());
+ },
+ );
it('renders the placeholder in the muted tone when no value is chosen', () => {
render(
<SelectDropDown
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 42f273add2..cc19d747a1 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -206,8 +206,11 @@ export const listSharedLinks = async (
return request.get(endpoints.getSharedLinks(pageSize, sortBy, sortDirection, search, cursor));
};
-export function getSharedLink(conversationId: string): Promise<t.TSharedLinkGetResponse> {
- return request.get(endpoints.getSharedLink(conversationId));
+export function getSharedLink(
+ conversationId: string,
+ signal?: AbortSignal,
+): Promise<t.TSharedLinkGetResponse> {
+ return request.get(endpoints.getSharedLink(conversationId), signal ? { signal } : undefined);
}
export function createSharedLink(
@@ -1002,8 +1005,8 @@ export function getConversations(cursor: string): Promise<t.TGetConversationsRes
return request.get(endpoints.conversations({ cursor }));
}
-export function getConversationById(id: string): Promise<s.TConversation> {
- return request.get(endpoints.conversationById(id));
+export function getConversationById(id: string, signal?: AbortSignal): Promise<s.TConversation> {
+ return request.get(endpoints.conversationById(id), signal ? { signal } : undefined);
}
export function updateConversation(
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index 2d7a60f4a3..eb876ff2ce 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -82,6 +82,8 @@ export enum QueryKeys {
mcpServer = 'mcpServer',
/* Active Jobs */
activeJobs = 'activeJobs',
+ /** A running chat's sidebar row, for chats no loaded conversation list holds. */
+ runningConversation = 'runningConversation',
/* Agent API Keys */
agentApiKeys = 'agentApiKeys',
/* Skills */