diff --git a/client/src/hooks/Chat/__tests__/contract.spec.tsx b/client/src/hooks/Chat/__tests__/contract.spec.tsx new file mode 100644 index 0000000000..4ddc7bd13c --- /dev/null +++ b/client/src/hooks/Chat/__tests__/contract.spec.tsx @@ -0,0 +1,70 @@ +import React from 'react'; +import { RecoilRoot } from 'recoil'; +import { renderHook } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { TConversation } from 'librechat-data-provider'; +import type { MutableSnapshot } from 'recoil'; +import useChatHelpers from '../useChatHelpers'; +import store from '~/store'; + +jest.mock('~/data-provider', () => ({ + useGetStartupConfig: () => ({ data: undefined }), + useAbortStreamMutation: () => ({ mutateAsync: jest.fn() }), + supportsGenerationProtocolV2: () => false, +})); + +jest.mock('~/hooks/Messages/useLatestMessage', () => ({ + useLatestMessage: () => null, + useLatestMessageId: () => null, +})); + +jest.mock('~/hooks/Chat/useChatFunctions', () => ({ + __esModule: true, + default: () => ({ ask: jest.fn(), regenerate: jest.fn() }), +})); + +jest.mock('~/hooks/useNewConvo', () => ({ + __esModule: true, + default: () => ({ newConversation: jest.fn() }), +})); + +jest.mock('~/hooks/Chat/useSteerConvert', () => ({ + __esModule: true, + default: () => jest.fn(), +})); + +function renderChatHelpers( + paramId?: string, + initializeState?: (snapshot: MutableSnapshot) => void, +) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const wrapper = ({ children }: { children: React.ReactNode }) => ( + + {children} + + ); + return renderHook(() => useChatHelpers(0, paramId), { wrapper }); +} + +describe('useChatHelpers contract members', () => { + it('reports the route id as the messages key before the conversation catches up', () => { + const { result } = renderChatHelpers('convo-2', ({ set }) => { + set(store.conversationByIndex(0), { conversationId: 'convo-1' } as TConversation); + }); + + expect(result.current.conversation?.conversationId).toBe('convo-1'); + expect(result.current.messagesKey).toBe('convo-2'); + }); + + it('reports an empty messages key before the pane has a conversation', () => { + expect(renderChatHelpers().result.current.messagesKey).toBe(''); + }); + + it('falls back to the conversation id without a route id', () => { + const { result } = renderChatHelpers(undefined, ({ set }) => { + set(store.conversationByIndex(0), { conversationId: 'convo-1' } as TConversation); + }); + + expect(result.current.messagesKey).toBe('convo-1'); + }); +}); diff --git a/client/src/hooks/Chat/contract.ts b/client/src/hooks/Chat/contract.ts index bbf7a3277f..f5d7e6b674 100644 --- a/client/src/hooks/Chat/contract.ts +++ b/client/src/hooks/Chat/contract.ts @@ -45,6 +45,12 @@ export type ChatMessagesContract = { * AI SDK: `messages`, read on demand instead of subscribed. */ getMessages: (targetConversationId?: string | null) => TMessage[] | undefined; + /** + * The conversation key `getMessages()` reads when called without one: the route's id, which + * can run ahead of `conversation` while navigation settles, or `''` before the pane has either. + * AI SDK: the chat `id`. + */ + messagesKey: string; /** Writes the full message list to every cache key this pane reads. AI SDK: `setMessages`. */ setMessages: (messages: TMessage[]) => void; /** Selects the visible sibling under the latest message's parent. */ diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.ts index 159ca4c113..5fbcd77c8b 100644 --- a/client/src/hooks/Chat/useChatHelpers.ts +++ b/client/src/hooks/Chat/useChatHelpers.ts @@ -404,6 +404,7 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContrac isSubmitting, setIsSubmitting, getMessages, + messagesKey: queryParam, setMessages, setSiblingIdx, latestMessageId, @@ -436,6 +437,7 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContrac isSubmitting, setIsSubmitting, getMessages, + queryParam, setMessages, setSiblingIdx, latestMessageId, diff --git a/e2e/specs/mock/scenarios/contract.spec.ts b/e2e/specs/mock/scenarios/contract.spec.ts new file mode 100644 index 0000000000..855d21a29d --- /dev/null +++ b/e2e/specs/mock/scenarios/contract.spec.ts @@ -0,0 +1,94 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { + sendMessageAndWaitForCompletion, + selectMockEndpoint, + MOCK_ENDPOINTS, + NEW_CHAT_PATH, + messagesView, + replyPrompt, + replyText, +} from '../helpers'; + +type ContractView = { + messagesKey: string; + conversationIds: Array; +}; + +const uniqueLabel = (prefix: string) => + `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + +/** + * No component renders `messagesKey` yet, so the pane's chat contract is read where the app + * serves it: the `ChatContext` value on the nearest provider above the messages or composer. + */ +async function readChatContract(page: Page): Promise { + return page.evaluate(() => { + type Fiber = { memoizedProps?: { value?: unknown }; return: Fiber | null }; + type Contract = { + messagesKey: string; + getMessages: () => Array<{ conversationId?: string | null }> | undefined; + }; + const node = + document.querySelector('[data-testid="screenshot-target"]') ?? + document.querySelector('#prompt-textarea'); + if (!node) { + return null; + } + const fiberKey = Object.keys(node).find((key) => key.startsWith('__reactFiber$')); + let fiber = fiberKey + ? ((node as unknown as Record)[fiberKey] ?? null) + : null; + while (fiber) { + const value = fiber.memoizedProps?.value as Partial | undefined; + if (value && typeof value === 'object' && 'messagesKey' in value && value.getMessages) { + return { + messagesKey: value.messagesKey as string, + conversationIds: (value.getMessages() ?? []).map((message) => message.conversationId), + }; + } + fiber = fiber.return; + } + return null; + }); +} + +const conversationIdOf = (page: Page) => new URL(page.url()).pathname.replace('/c/', ''); + +async function startConversation(page: Page, label: string) { + await page.goto(NEW_CHAT_PATH, { timeout: 10_000 }); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + const response = await sendMessageAndWaitForCompletion(page, replyPrompt(label)); + expect(response.ok()).toBeTruthy(); + await expect(messagesView(page).locator('.message-render').last()).toContainText( + replyText(label), + { timeout: 30_000 }, + ); + await expect(page).toHaveURL(/\/c\/(?!new$)[^/]+$/, { timeout: 30_000 }); + return conversationIdOf(page); +} + +test.describe('chat contract', () => { + test('names the conversation its messages are read from as the pane moves between chats @scenario:chat-contract-names-the-messages-key', async ({ + page, + }) => { + test.setTimeout(120_000); + const first = await startConversation(page, uniqueLabel('contract-first')); + await expect.poll(() => readChatContract(page)).toMatchObject({ messagesKey: first }); + + const second = await startConversation(page, uniqueLabel('contract-second')); + expect(second).not.toBe(first); + await expect.poll(() => readChatContract(page)).toMatchObject({ messagesKey: second }); + + await page.goto(`/c/${first}`, { timeout: 10_000 }); + await expect(messagesView(page).locator('.message-render')).toHaveCount(2, { + timeout: 30_000, + }); + await expect + .poll(() => readChatContract(page)) + .toEqual({ messagesKey: first, conversationIds: [first, first] }); + + await page.goto(NEW_CHAT_PATH, { timeout: 10_000 }); + await expect.poll(async () => (await readChatContract(page))?.messagesKey).toBe('new'); + }); +});