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: Verify Sidebar Status and Project Name Loading

Liaad99250a3520
diff --git a/.github/workflows/static-checks.yml b/.github/workflows/static-checks.yml
index af88f1e2e1..64fd631e62 100644
--- a/.github/workflows/static-checks.yml
+++ b/.github/workflows/static-checks.yml
@@ -101,6 +101,8 @@ jobs:
- '.github/workflows/static-checks.yml'
- '!**.md'
i18n:
+ - 'scripts/i18n*.mts'
+ - 'scripts/static-checks.mts'
- 'api/**'
- 'client/src/**'
- 'packages/client/**'
@@ -109,6 +111,7 @@ jobs:
- '.github/workflows/static-checks.yml'
- '!**.md'
runner:
+ - 'scripts/i18n*.mts'
- 'scripts/static-checks.mts'
- '.github/workflows/static-checks.yml'
unused_packages:
@@ -377,98 +380,9 @@ jobs:
if: always() && steps.paths.outputs.i18n == 'true'
continue-on-error: true
run: |
- echo "🔍 Scanning for unused i18next keys..."
-
- # Define paths
- I18N_FILE="client/src/locales/en/translation.json"
- SOURCE_DIRS=("client/src" "api" "packages/data-provider/src" "packages/client" "packages/data-schemas/src")
-
- # Check if translation file exists
- if [[ ! -f "$I18N_FILE" ]]; then
- echo "::error title=Missing i18n File::Translation file not found: $I18N_FILE"
- exit 1
- fi
-
- # Extract all keys from the JSON file
- KEYS=$(jq -r 'keys[]' "$I18N_FILE")
-
- # Track unused keys
- UNUSED_KEYS=()
-
- # Check if each key is used in the source code
- for KEY in $KEYS; do
- FOUND=false
-
- # Special case for dynamically constructed special variable keys
- if [[ "$KEY" == com_ui_special_var_* ]]; then
- # Check if TSpecialVarLabel is used in the codebase
- for DIR in "${SOURCE_DIRS[@]}"; do
- if grep -r --include=\*.{js,jsx,ts,tsx} -q "TSpecialVarLabel" "$DIR"; then
- FOUND=true
- break
- fi
- done
-
- # Also check if the key is directly used somewhere
- if [[ "$FOUND" == false ]]; then
- for DIR in "${SOURCE_DIRS[@]}"; do
- if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
- FOUND=true
- break
- fi
- done
- fi
- # Special case for agent category keys that are dynamically used from database
- elif [[ "$KEY" == com_agents_category_* ]]; then
- # Check if agent category localization is being used
- for DIR in "${SOURCE_DIRS[@]}"; do
- # Check for dynamic category label/description usage
- if grep -r --include=\*.{js,jsx,ts,tsx} -E "category\.(label|description).*startsWith.*['\"]com_" "$DIR" > /dev/null 2>&1 || \
- # Check for the method that defines these keys
- grep -r --include=\*.{js,jsx,ts,tsx} "ensureDefaultCategories" "$DIR" > /dev/null 2>&1 || \
- # Check for direct usage in agentCategory.ts
- grep -r --include=\*.ts -E "label:.*['\"]$KEY['\"]" "$DIR" > /dev/null 2>&1 || \
- grep -r --include=\*.ts -E "description:.*['\"]$KEY['\"]" "$DIR" > /dev/null 2>&1; then
- FOUND=true
- break
- fi
- done
-
- # Also check if the key is directly used somewhere
- if [[ "$FOUND" == false ]]; then
- for DIR in "${SOURCE_DIRS[@]}"; do
- if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
- FOUND=true
- break
- fi
- done
- fi
- else
- # Regular check for other keys
- for DIR in "${SOURCE_DIRS[@]}"; do
- if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
- FOUND=true
- break
- fi
- done
- fi
-
- if [[ "$FOUND" == false ]]; then
- UNUSED_KEYS+=("$KEY")
- fi
- done
-
- # Output results
- if [[ ${#UNUSED_KEYS[@]} -gt 0 ]]; then
- echo "🛑 Found ${#UNUSED_KEYS[@]} unused i18n keys:"
- echo "unused_keys=$(echo "${UNUSED_KEYS[@]}" | jq -R -s -c 'split(" ")')" >> $GITHUB_ENV
- for KEY in "${UNUSED_KEYS[@]}"; do
- echo "::warning title=Unused i18n Key::'$KEY' is defined but not used in the codebase."
- done
- else
- echo "✅ No unused i18n keys detected!"
- echo "unused_keys=[]" >> $GITHUB_ENV
- fi
+ echo "unused_keys=[]" >> "$GITHUB_ENV"
+ node --test scripts/i18n.test.mts
+ node scripts/static-checks.mts client/src/locales/en/translation.json --only i18n
- name: Fail workflow if unused keys found
id: i18n
diff --git a/client/src/Providers/ProjectNamesContext.tsx b/client/src/Providers/ProjectNamesContext.tsx
new file mode 100644
index 0000000000..bbb5014456
--- /dev/null
+++ b/client/src/Providers/ProjectNamesContext.tsx
@@ -0,0 +1,31 @@
+import { createContext, useMemo } from 'react';
+import type { ProjectListResponse } from 'librechat-data-provider';
+import type { InfiniteData } from '@tanstack/react-query';
+import type { ReactNode } from 'react';
+
+export const ProjectNamesContext = createContext<{
+ names: ReadonlyMap<string, string>;
+ isPending: boolean;
+} | null>(null);
+
+export default function ProjectNamesProvider({
+ data,
+ isPending,
+ children,
+}: {
+ data?: InfiniteData<ProjectListResponse>;
+ isPending: boolean;
+ children: ReactNode;
+}) {
+ const names = useMemo(() => {
+ const result = new Map<string, string>();
+ for (const page of data?.pages ?? []) {
+ for (const project of page.projects) {
+ result.set(project._id, project.name);
+ }
+ }
+ return result;
+ }, [data]);
+ const value = useMemo(() => ({ names, isPending }), [names, isPending]);
+ return <ProjectNamesContext.Provider value={value}>{children}</ProjectNamesContext.Provider>;
+}
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index 62a472b2d2..6e2f38a488 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -306,6 +306,7 @@ function Conversation({
return (
<div
ref={containerRef}
+ data-conversation-id={conversationId}
className={cn(
'group focus-visible:ring-text-primary relative flex h-12 w-full items-center rounded-lg outline-hidden focus-visible:ring-2 focus-visible:outline-hidden focus-visible:ring-inset md:h-9',
isActiveConvo || isPopoverActive
diff --git a/client/src/components/UnifiedSidebar/ConversationsSection.tsx b/client/src/components/UnifiedSidebar/ConversationsSection.tsx
index ebd67adafa..7a769f9066 100644
--- a/client/src/components/UnifiedSidebar/ConversationsSection.tsx
+++ b/client/src/components/UnifiedSidebar/ConversationsSection.tsx
@@ -28,6 +28,7 @@ import { chatFacetParamsAtom, useFreshLocalDay } from '~/components/Conversation
import ProjectsSection from '~/components/Conversations/ProjectsSection';
import ChatFilterMenu from '~/components/Conversations/ChatFilterMenu';
import PinnedSection from '~/components/Conversations/PinnedSection';
+import ProjectNamesProvider from '~/Providers/ProjectNamesContext';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
import { Conversations } from '~/components/Conversations';
import { cn, collectPinnedConversations } from '~/utils';
@@ -217,75 +218,77 @@ const ConversationsSection = memo(() => {
}, [isSearching, scrollViewport]);
return (
- <div
- className="flex h-full min-h-0 flex-col overflow-hidden pt-2 pb-3"
- role="region"
- aria-label={localize('com_ui_chat_history')}
- >
- {/* The search field owns this row alone; filtering and ordering moved beside the
+ <ProjectNamesProvider data={projectsData} isPending={!projectsLoaded && !projectsFailed}>
+ <div
+ className="flex h-full min-h-0 flex-col overflow-hidden pt-2 pb-3"
+ role="region"
+ aria-label={localize('com_ui_chat_history')}
+ >
+ {/* The search field owns this row alone; filtering and ordering moved beside the
Chats heading, where the list they act on is labelled. On mobile the field
itself lives in the drawer's bottom bar, within thumb reach. */}
- {!isSmallScreen && search.enabled && (
- <div className="flex items-center px-3">
- <SearchBar isSmallScreen={isSmallScreen} />
- </div>
- )}
- <div className="relative flex min-h-0 flex-1 flex-col">
- <div
- ref={setScrollViewportNode}
- className="min-h-0 flex-1 scrollbar-gutter-stable overflow-x-hidden overflow-y-auto"
- >
- {/* `min-h-full` keeps the sections filling a tall sidebar, so the chats
+ {!isSmallScreen && search.enabled && (
+ <div className="flex items-center px-3">
+ <SearchBar isSmallScreen={isSmallScreen} />
+ </div>
+ )}
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ <div
+ ref={setScrollViewportNode}
+ className="min-h-0 flex-1 scrollbar-gutter-stable overflow-x-hidden overflow-y-auto"
+ >
+ {/* `min-h-full` keeps the sections filling a tall sidebar, so the chats
list still claims the space below them when there is little to show. */}
- <div ref={setScrollContent} className="flex min-h-full flex-col">
- {!search.query && (
- <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />
- )}
- {!search.query && (
- <PinnedSection
- conversations={pinnedConversations}
- toggleNav={toggleNav}
- isSmallScreen={isSmallScreen}
- /* Only a successful drain proves the list is whole: a failed later
+ <div ref={setScrollContent} className="flex min-h-full flex-col">
+ {!search.query && (
+ <ProjectsSection toggleNav={toggleNav} isAuthenticated={isAuthenticated} />
+ )}
+ {!search.query && (
+ <PinnedSection
+ conversations={pinnedConversations}
+ toggleNav={toggleNav}
+ isSmallScreen={isSmallScreen}
+ /* Only a successful drain proves the list is whole: a failed later
page still publishes partial data and stops fetching. The Chats filters
never reach this query, so nothing else can truncate it. */
- membershipComplete={isPinnedComplete}
- /* When that drain last ran, which decides whether it is current
+ membershipComplete={isPinnedComplete}
+ /* When that drain last ran, which decides whether it is current
enough to prune the stored order against. */
- membershipUpdatedAt={pinnedUpdatedAt}
+ membershipUpdatedAt={pinnedUpdatedAt}
+ />
+ )}
+ <Conversations
+ conversations={conversations}
+ moveToTop={moveToTop}
+ toggleNav={toggleNav}
+ containerRef={conversationsRef}
+ loadMoreConversations={loadMoreConversations}
+ isLoading={isFetchingNextPage || isLoading}
+ isSearchLoading={isSearchLoading || isPreviousData}
+ isChatsExpanded={isChatsExpanded}
+ setIsChatsExpanded={setIsChatsExpanded}
+ hasNextPage={computedHasNextPage}
+ isError={isError}
+ onRetry={retryConversations}
+ chatsHeaderTrailing={chatsHeaderTrailing}
+ accountHasProjects={scopeToUnassigned && hasProjects}
+ scrollViewport={scrollViewport}
+ scrollContent={scrollContent}
/>
- )}
- <Conversations
- conversations={conversations}
- moveToTop={moveToTop}
- toggleNav={toggleNav}
- containerRef={conversationsRef}
- loadMoreConversations={loadMoreConversations}
- isLoading={isFetchingNextPage || isLoading}
- isSearchLoading={isSearchLoading || isPreviousData}
- isChatsExpanded={isChatsExpanded}
- setIsChatsExpanded={setIsChatsExpanded}
- hasNextPage={computedHasNextPage}
- isError={isError}
- onRetry={retryConversations}
- chatsHeaderTrailing={chatsHeaderTrailing}
- accountHasProjects={scopeToUnassigned && hasProjects}
- scrollViewport={scrollViewport}
- scrollContent={scrollContent}
- />
+ </div>
</div>
- </div>
- {/* The last row fades rather than being cut off, so a list that continues
+ {/* The last row fades rather than being cut off, so a list that continues
below the fold says so without a scrollbar having to appear. */}
- <div
- aria-hidden="true"
- className={cn(
- 'from-surface-primary-alt pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t to-transparent transition-opacity duration-200 motion-reduce:transition-none',
- hasMoreBelow ? 'opacity-100' : 'opacity-0',
- )}
- />
+ <div
+ aria-hidden="true"
+ className={cn(
+ 'from-surface-primary-alt pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t to-transparent transition-opacity duration-200 motion-reduce:transition-none',
+ hasMoreBelow ? 'opacity-100' : 'opacity-0',
+ )}
+ />
+ </div>
</div>
- </div>
+ </ProjectNamesProvider>
);
});
diff --git a/client/src/data-provider/Projects/queries.ts b/client/src/data-provider/Projects/queries.ts
index ed5fb688ec..2a5cd01497 100644
--- a/client/src/data-provider/Projects/queries.ts
+++ b/client/src/data-provider/Projects/queries.ts
@@ -1,5 +1,6 @@
+import { useContext } from 'react';
import { dataService, QueryKeys } from 'librechat-data-provider';
-import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query';
+import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import type {
ProjectAvailableFilesParams,
ProjectAvailableFilesResponse,
@@ -9,12 +10,13 @@ import type {
TChatProjectFile,
} from 'librechat-data-provider';
import type {
- InfiniteData,
UseInfiniteQueryOptions,
QueryObserverResult,
UseQueryOptions,
} from '@tanstack/react-query';
+import { ProjectNamesContext } from '~/Providers/ProjectNamesContext';
+
export const useProjectsInfiniteQuery = (
params: ProjectListParams = {},
config?: UseInfiniteQueryOptions<ProjectListResponse, unknown>,
@@ -61,24 +63,11 @@ export const useProjectQuery = (
* 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 });
+ const listed = useContext(ProjectNamesContext);
+ const listedName = projectId ? listed?.names.get(projectId) : undefined;
+ const { data: project } = useProjectQuery(projectId, {
+ enabled: Boolean(projectId) && !listed?.isPending && listedName == null,
+ });
return project?.name ?? listedName;
};
export const useProjectFilesQuery = (
diff --git a/client/src/data-provider/__tests__/projectName.spec.tsx b/client/src/data-provider/__tests__/projectName.spec.tsx
index 39e7c4dc55..7e2df89bc7 100644
--- a/client/src/data-provider/__tests__/projectName.spec.tsx
+++ b/client/src/data-provider/__tests__/projectName.spec.tsx
@@ -4,13 +4,14 @@ 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';
+import { useProjectName, useProjectsInfiniteQuery } from '../Projects';
+import ProjectNamesProvider from '~/Providers/ProjectNamesContext';
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
...actual,
- dataService: { ...actual.dataService, getProjectById: jest.fn() },
+ dataService: { ...actual.dataService, getProjectById: jest.fn(), listProjects: jest.fn() },
};
});
@@ -18,27 +19,44 @@ const getProjectById = dataService.getProjectById as jest.MockedFunction<
typeof dataService.getProjectById
>;
+const listProjects = dataService.listProjects as jest.MockedFunction<
+ typeof dataService.listProjects
+>;
+const listParams = { sortBy: 'lastConversationAt', sortDirection: 'desc', limit: 25 } as const;
+
+function SidebarProjects({ children }: { children: ReactNode }) {
+ const { data, isLoading, isError } = useProjectsInfiniteQuery(listParams);
+ return (
+ <ProjectNamesProvider data={data} isPending={isLoading && !isError}>
+ {children}
+ </ProjectNamesProvider>
+ );
+}
+
const project = (id: string, name: string) =>
({ _id: id, name, conversationCount: 1 }) as TChatProject;
-const renderName = (queryClient: QueryClient, projectId: string) =>
+const renderName = (queryClient: QueryClient, projectId?: string | null) =>
renderHook(() => useProjectName(projectId), {
wrapper: ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ <QueryClientProvider client={queryClient}>
+ <SidebarProjects>{children}</SidebarProjects>
+ </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] },
- );
+ queryClient.setQueryData<InfiniteData<ProjectListResponse>>([QueryKeys.projects, listParams], {
+ pages: [{ projects, nextCursor: null } as ProjectListResponse],
+ pageParams: [undefined],
+ });
describe('useProjectName', () => {
let queryClient: QueryClient;
beforeEach(() => {
jest.resetAllMocks();
+ listProjects.mockResolvedValue({ projects: [], nextCursor: null });
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
@@ -46,8 +64,6 @@ describe('useProjectName', () => {
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');
@@ -77,4 +93,65 @@ describe('useProjectName', () => {
await waitFor(() => expect(result.current).toBe('Cron jobs'));
expect(getProjectById).not.toHaveBeenCalled();
});
+ it('waits for the shared list on a cold load and reacts when it arrives', async () => {
+ let resolveList!: (value: ProjectListResponse) => void;
+ listProjects.mockReturnValue(
+ new Promise((resolve) => {
+ resolveList = resolve;
+ }),
+ );
+ const { result } = renderName(queryClient, 'p1');
+ expect(result.current).toBeUndefined();
+ expect(getProjectById).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveList({ projects: [project('p1', 'Scheduling')], nextCursor: null });
+ });
+ await waitFor(() => expect(result.current).toBe('Scheduling'));
+ expect(getProjectById).not.toHaveBeenCalled();
+ expect(listProjects).toHaveBeenCalledTimes(1);
+ });
+
+ it('reacts to a project name updated in the list', async () => {
+ seedList(queryClient, [project('p1', 'Scheduling')]);
+ const { result } = renderName(queryClient, 'p1');
+ act(() => {
+ seedList(queryClient, [project('p1', 'Cron jobs')]);
+ });
+ await waitFor(() => expect(result.current).toBe('Cron jobs'));
+ expect(getProjectById).not.toHaveBeenCalled();
+ });
+
+ it.each([undefined, null, ''])('never fetches an absent project ID (%s)', async (id) => {
+ seedList(queryClient, []);
+ const { result } = renderName(queryClient, id);
+ expect(result.current).toBeUndefined();
+ expect(getProjectById).not.toHaveBeenCalled();
+ });
+
+ it('falls back after the list fails', async () => {
+ listProjects.mockRejectedValue(new Error('List unavailable'));
+ queryClient.setDefaultOptions({ queries: { retry: false } });
+ getProjectById.mockResolvedValue(project('p9', 'Speed Chess'));
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const { result } = renderName(queryClient, 'p9');
+ await waitFor(() => expect(result.current).toBe('Speed Chess'));
+ expect(getProjectById).toHaveBeenCalledTimes(1);
+ } finally {
+ consoleError.mockRestore();
+ }
+ });
+
+ it('deduplicates fallback requests for multiple rows of the same project', async () => {
+ seedList(queryClient, []);
+ getProjectById.mockResolvedValue(project('p9', 'Speed Chess'));
+ const first = renderName(queryClient, 'p9');
+ const second = renderName(queryClient, 'p9');
+ await waitFor(() => {
+ expect(first.result.current).toBe('Speed Chess');
+ expect(second.result.current).toBe('Speed Chess');
+ });
+ expect(getProjectById).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/e2e/specs/mock/bookmarks.spec.ts b/e2e/specs/mock/bookmarks.spec.ts
index 6b05c61fc8..fb0ae727f7 100644
--- a/e2e/specs/mock/bookmarks.spec.ts
+++ b/e2e/specs/mock/bookmarks.spec.ts
@@ -1,6 +1,8 @@
+import { randomUUID } from 'node:crypto';
import { expect, test } from '@playwright/test';
import type { Locator, Page } from '@playwright/test';
import {
+ conversationRow,
selectMockEndpoint,
getAccessToken,
MOCK_ENDPOINTS,
@@ -9,13 +11,14 @@ import {
fetchJson,
} from './helpers';
+import { getE2EUser } from '../../setup/user';
+import { deleteConversations, seedConversations, withMongo } from './db';
+
type TagCount = { tag: string; count: number };
const uniqueName = (prefix: string) =>
`${prefix}-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e4)}`;
-const firstConversation = (page: Page) => page.getByTestId('convo-item').first();
-
/** The header bookmark menu (the nav filter button shares the `bookmark-menu` testid). */
const headerBookmarkButton = (page: Page) => page.locator('#bookmark-menu-button');
@@ -103,6 +106,31 @@ async function deleteConversation(page: Page, conversation: Locator): Promise<vo
test.describe('bookmark counts', () => {
test.describe.configure({ timeout: 120_000 });
+ let unreadId: string;
+
+ test.beforeEach(async () => {
+ unreadId = randomUUID();
+ const previous = new Date(Date.now() - 86_400_000);
+ await seedConversations(getE2EUser().email, [
+ {
+ conversationId: unreadId,
+ title: 'Finished sidebar decoy',
+ updatedAt: previous,
+ },
+ ]);
+ await withMongo(async (db) => {
+ await db.collection('conversations').updateOne(
+ { conversationId: unreadId },
+ {
+ $set: { lastResponseAt: previous, lastSeenAt: new Date(previous.getTime() - 1000) },
+ },
+ );
+ });
+ });
+
+ test.afterEach(async () => {
+ await deleteConversations([unreadId]);
+ });
test('drops a bookmark count to zero when its only conversation is deleted', async ({ page }) => {
const tag = uniqueName('E2E Bookmark');
@@ -110,8 +138,12 @@ test.describe('bookmark counts', () => {
await startBookmarkableChat(page);
await createBookmarkForActiveChat(page, tag);
expect(await getTagCount(page, tag)).toBe(1);
+ await expect(page.getByTestId('convo-item').first()).not.toHaveAttribute(
+ 'data-conversation-id',
+ new URL(page.url()).pathname.split('/c/')[1],
+ );
- await deleteConversation(page, firstConversation(page));
+ await deleteConversation(page, conversationRow(page));
await expect.poll(() => getTagCount(page, tag), { timeout: 15000 }).toBe(0);
});
@@ -124,19 +156,20 @@ test.describe('bookmark counts', () => {
// Conversation A: create the bookmark (count -> 1).
await startBookmarkableChat(page);
await createBookmarkForActiveChat(page, tag);
+ const conversationAUrl = page.url();
const titleA = uniqueName('Bookmark A');
- await renameConversation(page, firstConversation(page), titleA);
+ await renameConversation(page, conversationRow(page), titleA);
expect(await getTagCount(page, tag)).toBe(1);
// Conversation B: attach the same bookmark (count -> 2).
await startBookmarkableChat(page);
await addExistingBookmarkToActiveChat(page, tag);
const titleB = uniqueName('Bookmark B');
- await renameConversation(page, firstConversation(page), titleB);
+ await renameConversation(page, conversationRow(page), titleB);
expect(await getTagCount(page, tag)).toBe(2);
// Deleting A leaves the count at 1 because B still carries the bookmark.
- const conversationA = page.getByTestId('convo-item').filter({ hasText: titleA });
+ const conversationA = conversationRow(page, conversationAUrl);
await deleteConversation(page, conversationA);
await expect.poll(() => getTagCount(page, tag), { timeout: 15000 }).toBe(1);
diff --git a/e2e/specs/mock/conversation-management.spec.ts b/e2e/specs/mock/conversation-management.spec.ts
index 80869a16be..633d98b02a 100644
--- a/e2e/specs/mock/conversation-management.spec.ts
+++ b/e2e/specs/mock/conversation-management.spec.ts
@@ -1,6 +1,7 @@
import { expect, test } from '@playwright/test';
import type { Locator, Page } from '@playwright/test';
import {
+ conversationRow,
MOCK_ENDPOINTS,
NEW_CHAT_PATH,
messagesView,
@@ -10,8 +11,6 @@ import {
sendMessageAndWaitForCompletion,
} from './helpers';
-const firstConversation = (page: Page) => page.getByTestId('convo-item').first();
-
function uniqueLabel(prefix: string) {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
@@ -58,14 +57,14 @@ test.describe('conversation management', () => {
const conversationUrl = page.url();
await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/);
- await expect(firstConversation(page)).toBeVisible();
+ await expect(conversationRow(page)).toBeVisible();
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await expect(page).toHaveURL(/\/c\/new$/);
await expect(messagesView(page).getByText(firstTurn.prompt)).toHaveCount(0);
await expect(messagesView(page).getByText(secondTurn.prompt)).toHaveCount(0);
- await firstConversation(page).click();
+ await conversationRow(page, conversationUrl).click();
await expect(page).toHaveURL(conversationUrl);
await expect(messagesView(page).getByText(firstTurn.prompt)).toBeVisible();
await expect(messagesView(page).getByText(firstTurn.reply)).toBeVisible();
@@ -81,7 +80,7 @@ test.describe('conversation management', () => {
await openMockChat(page);
await sendAndExpectReply(page, label);
- await renameConversation(page, firstConversation(page), renamedTitle);
+ await renameConversation(page, conversationRow(page), renamedTitle);
await page.reload({ timeout: 10000 });
await expect(page.getByTestId('convo-item').filter({ hasText: renamedTitle })).toBeVisible();
});
@@ -97,7 +96,7 @@ test.describe('conversation management', () => {
const turn = await sendAndExpectReply(page, label);
const conversationUrl = page.url();
- const conversation = firstConversation(page);
+ const conversation = conversationRow(page);
await renameConversation(page, conversation, renamedTitle);
await openConversationMenu(conversation);
await page.getByRole('menuitem', { name: 'Delete' }).click();
diff --git a/e2e/specs/mock/helpers.ts b/e2e/specs/mock/helpers.ts
index fcd7cd4192..9c16acef00 100644
--- a/e2e/specs/mock/helpers.ts
+++ b/e2e/specs/mock/helpers.ts
@@ -529,3 +529,13 @@ export async function uploadViaLegacyOption(page: Page, optionName: string, file
});
return uploadResponse;
}
+
+/** Identity stays stable when Running and Finished reorder the sidebar. */
+export const conversationRow = (page: Page, conversationUrl: string = page.url()) => {
+ const id = new URL(conversationUrl).pathname.split('/c/')[1];
+ expect(id).toMatch(/^[0-9a-f-]{36}$/i);
+ return page
+ .getByTestId('convo-item')
+ .and(page.locator(`[data-conversation-id="${id}"]`))
+ .first();
+};
diff --git a/scripts/i18n.mts b/scripts/i18n.mts
new file mode 100644
index 0000000000..dd44187c86
--- /dev/null
+++ b/scripts/i18n.mts
@@ -0,0 +1,9 @@
+/** i18next selects cardinal and ordinal suffixes from the base key's count. */
+export function isTranslationReferenced(
+ key: string,
+ isReferenced: (key: string) => boolean,
+): boolean {
+ if (isReferenced(key)) return true;
+ const base = key.replace(/(?:_ordinal)?_(zero|one|two|few|many|other)$/, '');
+ return base !== key && isReferenced(base);
+}
diff --git a/scripts/i18n.test.mts b/scripts/i18n.test.mts
new file mode 100644
index 0000000000..c04ae1db3e
--- /dev/null
+++ b/scripts/i18n.test.mts
@@ -0,0 +1,26 @@
+import { test } from 'node:test';
+import { strict as assert } from 'node:assert';
+import { isTranslationReferenced } from './i18n.mts';
+
+test('recognizes direct references and count-selected plural forms', () => {
+ const references = new Set(['com_chat_count', 'com_direct_one']);
+ const isReferenced = (key: string) => references.has(key);
+ assert.equal(isTranslationReferenced('com_chat_count', isReferenced), true);
+ assert.equal(isTranslationReferenced('com_direct_one', isReferenced), true);
+ for (const suffix of ['zero', 'one', 'two', 'few', 'many', 'other']) {
+ assert.equal(isTranslationReferenced(`com_chat_count_${suffix}`, isReferenced), true);
+ assert.equal(isTranslationReferenced(`com_chat_count_ordinal_${suffix}`, isReferenced), true);
+ }
+});
+
+test('does not exempt unused plural families or unrelated suffixes', () => {
+ const isReferenced = (key: string) => key === 'com_chat_count';
+ for (const key of [
+ 'com_unused',
+ 'com_unused_one',
+ 'com_unused_ordinal_other',
+ 'com_chat_count_single',
+ ]) {
+ assert.equal(isTranslationReferenced(key, isReferenced), false);
+ }
+});
diff --git a/scripts/static-checks.mts b/scripts/static-checks.mts
index f0e6d1b36d..f6caff49f7 100644
--- a/scripts/static-checks.mts
+++ b/scripts/static-checks.mts
@@ -57,6 +57,7 @@ import {
} from 'node:fs';
import type { Dirent } from 'node:fs';
+import { isTranslationReferenced } from './i18n.mts';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -109,6 +110,8 @@ const FILTERS = {
],
config: ['api/**', 'config/**', 'packages/**', '.github/workflows/static-checks.yml', '!**.md'],
i18n: [
+ 'scripts/i18n*.mts',
+ 'scripts/static-checks.mts',
'api/**',
'client/src/**',
'packages/client/**',
@@ -1799,7 +1802,7 @@ async function findUnusedI18nKeys(): Promise<CheckOutcome> {
) {
return false;
}
- return !isReferenced(key);
+ return !isTranslationReferenced(key, isReferenced);
});
if (unused.length === 0) return { ok: true };