From 1cc4277d1b720eb284e6c6e0f9926fef4afef06e Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sun, 27 Sep 2026 02:35:34 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=91=20feat:=20Expose=20the=20Messages?= =?UTF-8?q?=20Key=20on=20the=20Chat=20Contract=20(#16395)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: expose the messages key and the submitted response on the chat contract Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * fix: keep the submitted response in the chat host instead of reading the submission atom The contract's initialResponse is now the response ask submitted, held beside the host's own state and exposed only while the turn is in flight, so a settled turn and a run restored after a reload report none, and the submission atom gains no reader. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * fix: take the submission ask builds as a value and document the empty messages key Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * fix: scope the submitted response to its chat and promise seeded positions, not identity Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * docs: note that a new chat's submitted response ends at its saved id Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * fix: end the submitted response with its turn and note that the stream can continue the last seeded part Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * refactor: drop the submitted response from the chat contract A run can be restored, replaced or torn down outside ask, so a copy of the submitted response kept in the host describes the wrong run on those paths. The contract keeps messagesKey only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw * test: cover the messages key across chat switches in the mock e2e harness Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 77a1cfa31d19a0047a659b191f218b56674eb9fb) Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16395 --- .../hooks/Chat/__tests__/contract.spec.tsx | 70 ++++++++++++++ client/src/hooks/Chat/contract.ts | 6 ++ client/src/hooks/Chat/useChatHelpers.ts | 2 + e2e/specs/mock/scenarios/contract.spec.ts | 94 +++++++++++++++++++ 4 files changed, 172 insertions(+) create mode 100644 client/src/hooks/Chat/__tests__/contract.spec.tsx create mode 100644 e2e/specs/mock/scenarios/contract.spec.ts 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'); + }); +});