mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 23:13:35 +00:00
🔑 feat: Expose the Messages Key on the Chat Contract (#16395)
* feat: expose the messages key and the submitted response on the chat contract
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GQdLgSaTheiBFHYnUDgobw
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 77a1cfa31d)
Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16395
This commit is contained in:
parent
e232b1b398
commit
1cc4277d1b
4 changed files with 172 additions and 0 deletions
70
client/src/hooks/Chat/__tests__/contract.spec.tsx
Normal file
70
client/src/hooks/Chat/__tests__/contract.spec.tsx
Normal file
|
|
@ -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 }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RecoilRoot initializeState={initializeState}>{children}</RecoilRoot>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
94
e2e/specs/mock/scenarios/contract.spec.ts
Normal file
94
e2e/specs/mock/scenarios/contract.spec.ts
Normal file
|
|
@ -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<string | null | undefined>;
|
||||
};
|
||||
|
||||
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<ContractView | null> {
|
||||
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<string, Fiber | undefined>)[fiberKey] ?? null)
|
||||
: null;
|
||||
while (fiber) {
|
||||
const value = fiber.memoizedProps?.value as Partial<Contract> | 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');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue