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

🍴 refactor: Move the Fork and Feedback Actions into @librechat/chat (#17561)

Marco Berettaab6b01b51cd6
diff --git a/client/src/Providers/MessagesHostContext.tsx b/client/src/Providers/MessagesHostContext.tsx
index a98ae8b4a8..1ee355def8 100644
--- a/client/src/Providers/MessagesHostContext.tsx
+++ b/client/src/Providers/MessagesHostContext.tsx
@@ -1,14 +1,64 @@
+import { useCallback, useMemo, useRef } from 'react';
+import { useRecoilState } from 'recoil';
import { setDefaultMessagesHost } from '@librechat/chat/react';
-import type { MessagesHost } from '@librechat/chat/react';
+import type {
+ ForkEvents,
+ MessagesHost,
+ ForkPreferences,
+ ForkConversation,
+} from '@librechat/chat/react';
import Files from '~/components/Chat/Messages/Content/Files';
+import { useForkConvoMutation } from '~/data-provider';
import useClockFormat from '~/hooks/useClockFormat';
+import { useNavigateToConvo } from '~/hooks';
+import store from '~/store';
-/** What the message list reads from the app: the viewer's clock format and the row pieces that
- * still live here. Registered as the default when this module loads, so rows read it on every
- * route, the shared view included. */
+function useAppForkPreferences(): ForkPreferences {
+ const [option, setOption] = useRecoilState(store.forkSetting);
+ const [splitAtTarget, setSplitAtTarget] = useRecoilState(store.splitAtTarget);
+ const [rememberOption, setRememberOption] = useRecoilState(store.rememberDefaultFork);
+ return useMemo(
+ () => ({
+ option,
+ setOption,
+ splitAtTarget,
+ setSplitAtTarget,
+ rememberOption,
+ setRememberOption,
+ }),
+ [option, setOption, splitAtTarget, setSplitAtTarget, rememberOption, setRememberOption],
+ );
+}
+
+/** The events ride on the mutation's own callbacks, not `mutate`'s, so the fork still opens and
+ * reports when the row that started it unmounted before the server answered. */
+function useAppForkConversation(): ForkConversation {
+ const { navigateToConvo } = useNavigateToConvo();
+ const events = useRef<ForkEvents | null>(null);
+ const { mutate } = useForkConvoMutation({
+ onSuccess: (data) => {
+ navigateToConvo(data.conversation);
+ events.current?.onSuccess();
+ },
+ onError: (error) => events.current?.onError(error),
+ });
+ return useCallback<ForkConversation>(
+ (request, next) => {
+ events.current = next;
+ mutate(request);
+ },
+ [mutate],
+ );
+}
+
+/** What the message list reads from the app: the viewer's clock format and fork defaults, the
+ * fork request, and the row pieces that still live here. Registered as the default when this
+ * module loads, so rows read it on every route, the shared view included. */
export const appMessagesHost: MessagesHost = {
useHour12: useClockFormat,
renderFiles: (message) => <Files message={message} />,
+ useForkPreferences: useAppForkPreferences,
+ useForkConversation: useAppForkConversation,
};
setDefaultMessagesHost(appMessagesHost);
diff --git a/client/src/components/Chat/Messages/HoverButtons.tsx b/client/src/components/Chat/Messages/HoverButtons.tsx
index fd3f549115..75f2984f46 100644
--- a/client/src/components/Chat/Messages/HoverButtons.tsx
+++ b/client/src/components/Chat/Messages/HoverButtons.tsx
@@ -3,8 +3,8 @@ import { Copy, Check } from 'lucide';
import { useAtomValue } from 'jotai';
import { useRecoilState } from 'recoil';
import { hasEditablePart } from '@librechat/chat';
-import { hoverButtonClasses } from '@librechat/chat/components';
import { revealedQueuedTurnFamily } from '@librechat/chat/react';
+import { hoverButtonClasses, Fork, Feedback } from '@librechat/chat/components';
import { getSpeechText, findMessageById, isUserInitiatedCompaction } from 'librechat-data-provider';
import {
Button,
@@ -17,9 +17,7 @@ import {
import type { TConversation, TMessage, TFeedback } from 'librechat-data-provider';
import { useMessagesIsSubmitting, useOptionalMessagesOperations } from '~/Providers';
import { useGenerationsByLatest, useLocalize } from '~/hooks';
-import { Fork } from '~/components/Conversations';
import MessageAudio from './MessageAudio';
-import Feedback from './Feedback';
import { cn } from '~/utils';
import store from '~/store';
diff --git a/client/src/components/Chat/Messages/__tests__/Fork.spec.tsx b/client/src/components/Chat/Messages/__tests__/Fork.spec.tsx
deleted file mode 100644
index c30f8b1f63..0000000000
--- a/client/src/components/Chat/Messages/__tests__/Fork.spec.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import React from 'react';
-import { RecoilRoot } from 'recoil';
-import { ForkOptions } from 'librechat-data-provider';
-import { fireEvent, render, screen } from '@testing-library/react';
-import store from '~/store';
-import Fork from '../Fork';
-
-const mockMutate = jest.fn();
-
-jest.mock('~/data-provider', () => ({
- useForkConvoMutation: () => ({ mutate: mockMutate }),
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useNavigateToConvo: () => ({ navigateToConvo: jest.fn() }),
-}));
-
-jest.mock('@librechat/client', () => ({
- ...jest.requireActual('@librechat/client'),
- useToastContext: () => ({ showToast: jest.fn() }),
-}));
-
-describe('Fork', () => {
- beforeEach(() => {
- mockMutate.mockClear();
- });
-
- /** The row holding this button does not re-render when the tail moves, so the
- * split target is read when the fork starts rather than captured at render. */
- it('sends the tail current at click time as the split target', () => {
- let latestMessageId = 'assistant-2';
- render(
- <RecoilRoot
- initializeState={({ set }) => {
- set(store.rememberDefaultFork, true);
- set(store.forkSetting, ForkOptions.TARGET_LEVEL);
- set(store.splitAtTarget, true);
- }}
- >
- <Fork
- messageId="user-1"
- conversationId="convo-1"
- forkingSupported={true}
- getLatestMessageId={() => latestMessageId}
- />
- </RecoilRoot>,
- );
-
- latestMessageId = 'assistant-3';
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
-
- expect(mockMutate).toHaveBeenCalledWith(
- expect.objectContaining({
- messageId: 'user-1',
- splitAtTarget: true,
- latestMessageId: 'assistant-3',
- }),
- );
- });
-
- it('copies without files only when that box is checked for this fork', async () => {
- render(
- <RecoilRoot>
- <Fork messageId="assistant-1" conversationId="convo-1" forkingSupported={true} />
- </RecoilRoot>,
- );
-
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
- fireEvent.click(await screen.findByRole('checkbox', { name: 'com_ui_fork_exclude_files' }));
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_visible' }));
-
- expect(mockMutate).toHaveBeenLastCalledWith(
- expect.objectContaining({
- messageId: 'assistant-1',
- option: ForkOptions.DIRECT_PATH,
- excludeFiles: true,
- }),
- );
- });
-
- it('keeps files by default', async () => {
- render(
- <RecoilRoot>
- <Fork messageId="assistant-1" conversationId="convo-1" forkingSupported={true} />
- </RecoilRoot>,
- );
-
- fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
- fireEvent.click(await screen.findByRole('button', { name: 'com_ui_fork_visible' }));
-
- expect(mockMutate.mock.calls.at(-1)?.[0]).not.toHaveProperty('excludeFiles');
- });
-});
diff --git a/client/src/components/Conversations/index.ts b/client/src/components/Conversations/index.ts
index e9e5daddbf..e092041b8b 100644
--- a/client/src/components/Conversations/index.ts
+++ b/client/src/components/Conversations/index.ts
@@ -1,3 +1,2 @@
-export { default as Fork } from '../Chat/Messages/Fork';
export { default as Conversations } from './Conversations';
export * from './ConvoOptions';
diff --git a/e2e/specs/mock/scenarios/fork-feedback.spec.ts b/e2e/specs/mock/scenarios/fork-feedback.spec.ts
new file mode 100644
index 0000000000..0833455bf4
--- /dev/null
+++ b/e2e/specs/mock/scenarios/fork-feedback.spec.ts
@@ -0,0 +1,83 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { MOCK_ENDPOINTS, NEW_CHAT_PATH, selectMockEndpoint, sendMessage } from '../helpers';
+
+/** The fork and feedback actions `@librechat/chat` now renders on a reply, with the fork request
+ * and the viewer's fork defaults supplied by the app's messages host. */
+
+const uniqueLabel = (name: string) => `${name}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
+
+const messagesView = (page: Page) => page.getByTestId('messages-view');
+const messageRender = (page: Page, text: string) =>
+ page.locator('.message-render').filter({ hasText: text }).last();
+
+async function replyInNewChat(page: Page, label: string) {
+ const reply = `E2E reply ${label}`;
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ const response = await sendMessage(page, `E2E_REPLY:${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(reply)).toBeVisible({ timeout: 30000 });
+ await expect(page).toHaveURL(/\/c\/(?!new)[^/]+$/);
+ return reply;
+}
+
+test.describe('fork and feedback actions', () => {
+ test.setTimeout(120000);
+
+ test('forking the visible branch opens the copy @scenario:fork-visible-branch-opens-copy', async ({
+ page,
+ }) => {
+ const reply = await replyInNewChat(page, uniqueLabel('actions-fork'));
+ const sourceUrl = page.url();
+
+ const row = messageRender(page, reply);
+ await row.hover();
+ await row.getByRole('button', { name: 'Open Fork Menu' }).click();
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) => res.request().method() === 'POST' && res.url().includes('/api/convos/fork'),
+ { timeout: 30000 },
+ ),
+ page.getByRole('button', { name: 'Visible messages only', exact: true }).click(),
+ ]);
+ expect(response.ok()).toBeTruthy();
+ const { conversation } = (await response.json()) as {
+ conversation: { conversationId: string };
+ };
+
+ await expect(page).toHaveURL(new RegExp(`/c/${conversation.conversationId}$`));
+ expect(page.url()).not.toBe(sourceUrl);
+ await expect(page.getByText('Successfully forked conversation', { exact: true })).toBeVisible();
+ await expect(messagesView(page).getByText(reply)).toBeVisible();
+ });
+
+ test('a positive rating is saved and survives a reload @scenario:feedback-rating-persists', async ({
+ page,
+ }) => {
+ const reply = await replyInNewChat(page, uniqueLabel('actions-feedback'));
+
+ const row = messageRender(page, reply);
+ await row.hover();
+ await row.getByRole('button', { name: 'Love this' }).click();
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) => res.request().method() === 'PUT' && res.url().includes('/feedback'),
+ { timeout: 30000 },
+ ),
+ page.locator('.popover-animate').getByRole('button').first().click(),
+ ]);
+ expect(response.ok()).toBeTruthy();
+
+ const rated = row.getByRole('button', { name: 'Love this' });
+ await expect(rated).toHaveAttribute('aria-pressed', 'true');
+
+ await page.reload();
+ const reloaded = messageRender(page, reply);
+ await reloaded.hover();
+ await expect(reloaded.getByRole('button', { name: 'Love this' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ });
+});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 0b377579d8..bbe69d111f 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -410,22 +410,6 @@
"count": 1
}
},
- "client/src/components/Chat/Messages/Feedback.tsx": {
- "shadcn/no-restyle": {
- "count": 10
- },
- "shadcn/require-static-classes": {
- "count": 3
- }
- },
- "client/src/components/Chat/Messages/Fork.tsx": {
- "shadcn/no-restyle": {
- "count": 4
- },
- "shadcn/require-static-classes": {
- "count": 1
- }
- },
"client/src/components/Chat/Messages/HoverButtons.tsx": {
"shadcn/require-static-classes": {
"count": 1
@@ -1414,6 +1398,22 @@
"count": 1
}
},
+ "packages/chat/src/components/messages/Feedback.tsx": {
+ "shadcn/no-restyle": {
+ "count": 10
+ },
+ "shadcn/require-static-classes": {
+ "count": 3
+ }
+ },
+ "packages/chat/src/components/messages/Fork.tsx": {
+ "shadcn/no-restyle": {
+ "count": 4
+ },
+ "shadcn/require-static-classes": {
+ "count": 1
+ }
+ },
"packages/chat/src/components/messages/HeaderLabel.tsx": {
"shadcn/no-arbitrary-values": {
"count": 5
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 60e9768e07..bdf3f9ea02 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -360,6 +360,7 @@ export default [
'tool-status-text',
'message-render',
'message-timestamp',
+ 'popover-animate',
],
},
],
diff --git a/packages/chat/src/__fixtures__/messagesHost.ts b/packages/chat/src/__fixtures__/messagesHost.ts
new file mode 100644
index 0000000000..e45c1d76d9
--- /dev/null
+++ b/packages/chat/src/__fixtures__/messagesHost.ts
@@ -0,0 +1,20 @@
+import type { MessagesHost } from '../react/messages/host';
+
+/** A messages host for specs: locale clock, no slots, no forking, with the members a spec needs
+ * overridden. */
+export function createMessagesHost(overrides: Partial<MessagesHost> = {}): MessagesHost {
+ return {
+ useHour12: () => undefined,
+ renderFiles: () => null,
+ useForkPreferences: () => ({
+ option: '',
+ setOption: () => undefined,
+ splitAtTarget: false,
+ setSplitAtTarget: () => undefined,
+ rememberOption: false,
+ setRememberOption: () => undefined,
+ }),
+ useForkConversation: () => null,
+ ...overrides,
+ };
+}
diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts
index 89c9b17c46..29d22dbfbe 100644
--- a/packages/chat/src/components.ts
+++ b/packages/chat/src/components.ts
@@ -70,6 +70,8 @@ export { default as MessageTimestamp } from './components/messages/MessageTimest
export { getMessageRowWidthClass } from './components/messages/width';
export { isValidTimestamp, getMessageTimestamp } from './components/messages/time';
export type { MessageTimestamp as MessageTimestampParts } from './components/messages/time';
+export { default as Fork } from './components/messages/Fork';
+export { default as Feedback } from './components/messages/Feedback';
/** Parts: the leaf components and row classes tool cards share. */
export { default as Stdout } from './components/parts/Stdout';
diff --git a/client/src/components/Chat/Messages/Feedback.tsx b/packages/chat/src/components/messages/Feedback.tsx
similarity index 96%
rename from client/src/components/Chat/Messages/Feedback.tsx
rename to packages/chat/src/components/messages/Feedback.tsx
index 113b637beb..90a430ee3d 100644
--- a/client/src/components/Chat/Messages/Feedback.tsx
+++ b/packages/chat/src/components/messages/Feedback.tsx
@@ -1,7 +1,6 @@
import React, { memo, useState, useCallback, useMemo, useEffect } from 'react';
import * as Ariakit from '@ariakit/react';
-import { hoverButtonClasses } from '@librechat/chat/components';
-import { TFeedback, TFeedbackTag, getTagsForRating } from 'librechat-data-provider';
+import { getTagsForRating } from 'librechat-data-provider';
import {
AlertCircle,
PenTool,
@@ -21,9 +20,12 @@ import {
TooltipAnchor,
ThumbUpIcon,
ThumbDownIcon,
+ cn,
+ useLocalize,
} from '@librechat/client';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
+import type { TFeedback, TFeedbackTag } from 'librechat-data-provider';
+import type { NamedExoticComponent } from 'react';
+import { hoverButtonClasses } from './styles';
interface FeedbackProps {
handleFeedback: ({ feedback }: { feedback: TFeedback | undefined }) => void;
@@ -340,4 +342,6 @@ function Feedback({ isLast = false, handleFeedback, feedback: initialFeedback }:
}
/** Memoized: a send re-renders every row's toolbar, and nothing here depends on it. */
-export default memo(Feedback);
+const MemoFeedback: NamedExoticComponent<FeedbackProps> = memo(Feedback);
+
+export default MemoFeedback;
diff --git a/client/src/components/Chat/Messages/Fork.tsx b/packages/chat/src/components/messages/Fork.tsx
similarity index 81%
rename from client/src/components/Chat/Messages/Fork.tsx
rename to packages/chat/src/components/messages/Fork.tsx
index c9a30f547f..b17488470c 100644
--- a/client/src/components/Chat/Messages/Fork.tsx
+++ b/packages/chat/src/components/messages/Fork.tsx
@@ -1,15 +1,15 @@
import React, { memo, useState, useRef } from 'react';
-import { useRecoilState } from 'recoil';
import * as Ariakit from '@ariakit/react';
import { VisuallyHidden } from '@ariakit/react';
import { GitFork, InfoIcon } from 'lucide-react';
import { ForkOptions } from 'librechat-data-provider';
-import { hoverButtonClasses } from '@librechat/chat/components';
import { GitCommit, GitBranchPlus, ListTree } from 'lucide-react';
-import { Button, Label, Checkbox, useToastContext } from '@librechat/client';
-import { TranslationKeys, useLocalize, useNavigateToConvo } from '~/hooks';
-import { useForkConvoMutation } from '~/data-provider';
-import store from '~/store';
+import { Button, Label, Checkbox, useLocalize, useToastContext } from '@librechat/client';
+import type { TForkConvoRequest } from 'librechat-data-provider';
+import type { TranslationKeys } from '@librechat/client';
+import type { NamedExoticComponent } from 'react';
+import { useMessagesHost } from '../../react/messages/host';
+import { hoverButtonClasses } from './styles';
interface PopoverButtonProps {
children: React.ReactNode;
@@ -23,11 +23,18 @@ interface PopoverButtonProps {
label: string;
}
-const optionLabels: Record<ForkOptions, TranslationKeys> = {
- [ForkOptions.DIRECT_PATH]: 'com_ui_fork_visible',
- [ForkOptions.INCLUDE_BRANCHES]: 'com_ui_fork_branches',
- [ForkOptions.TARGET_LEVEL]: 'com_ui_fork_all_target',
- [ForkOptions.DEFAULT]: 'com_ui_fork_from_message',
+/** Resolved per call: a module-scope map keyed by the enum crashes hosts that mock the data provider. */
+const optionLabel = (setting: ForkOptions): TranslationKeys => {
+ switch (setting) {
+ case ForkOptions.DIRECT_PATH:
+ return 'com_ui_fork_visible';
+ case ForkOptions.INCLUDE_BRANCHES:
+ return 'com_ui_fork_branches';
+ case ForkOptions.TARGET_LEVEL:
+ return 'com_ui_fork_all_target';
+ default:
+ return 'com_ui_fork_from_message';
+ }
};
const chevronDown = (
@@ -65,14 +72,14 @@ const PopoverButton: React.FC<PopoverButtonProps> = ({
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
- setActiveSetting(optionLabels[setting]);
+ setActiveSetting(optionLabel(setting));
}}
onMouseLeave={() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
- setActiveSetting(optionLabels[ForkOptions.DEFAULT]);
+ setActiveSetting(optionLabel(ForkOptions.DEFAULT));
}, 175);
}}
onFocus={() => {
@@ -80,14 +87,14 @@ const PopoverButton: React.FC<PopoverButtonProps> = ({
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
- setActiveSetting(optionLabels[setting]);
+ setActiveSetting(optionLabel(setting));
}}
onBlur={() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
- setActiveSetting(optionLabels[ForkOptions.DEFAULT]);
+ setActiveSetting(optionLabel(ForkOptions.DEFAULT));
}, 175);
}}
className="border-border-medium bg-surface-secondary text-text-secondary hover:bg-surface-hover hover:text-text-primary mx-0.5 w-14 flex-1 rounded-xl border-2 transition duration-200 ease-in-out"
@@ -200,31 +207,52 @@ const CheckboxOption: React.FC<CheckboxOptionProps> = ({
);
};
-function Fork({
- messageId,
- conversationId: _convoId,
- forkingSupported = false,
- getLatestMessageId,
- isLast = false,
-}: {
+type ForkProps = {
messageId: string;
conversationId: string | null;
forkingSupported?: boolean;
/** Read when a fork starts: the split target must be the tail at click time. */
getLatestMessageId?: () => string | undefined;
isLast?: boolean;
-}) {
+};
+
+/** Whether a failed fork was refused by the rate limiter, however the transport reports it. */
+function isRateLimited(error: unknown): boolean {
+ if (typeof error !== 'object' || error == null) {
+ return false;
+ }
+ const { status, statusCode, response } = error as {
+ status?: number;
+ statusCode?: number;
+ response?: { status?: number };
+ };
+ return response?.status === 429 || status === 429 || statusCode === 429;
+}
+
+function Fork({
+ messageId,
+ conversationId: _convoId,
+ forkingSupported = false,
+ getLatestMessageId,
+ isLast = false,
+}: ForkProps) {
const localize = useLocalize();
const { showToast } = useToastContext();
const [remember, setRemember] = useState(false);
/** Per fork, never remembered: a copy without files is a recovery step, not a preference. */
const [excludeFiles, setExcludeFiles] = useState(false);
- const { navigateToConvo } = useNavigateToConvo();
+ const host = useMessagesHost();
+ const forkConversation = host.useForkConversation();
+ const {
+ option: forkSetting,
+ setOption: setForkSetting,
+ splitAtTarget,
+ setSplitAtTarget,
+ rememberOption: rememberGlobal,
+ setRememberOption: setRememberGlobal,
+ } = host.useForkPreferences();
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
- const [forkSetting, setForkSetting] = useRecoilState(store.forkSetting);
- const [activeSetting, setActiveSetting] = useState(optionLabels.default);
- const [splitAtTarget, setSplitAtTarget] = useRecoilState(store.splitAtTarget);
- const [rememberGlobal, setRememberGlobal] = useRecoilState(store.rememberDefaultFork);
+ const [activeSetting, setActiveSetting] = useState(optionLabel(ForkOptions.DEFAULT));
const popoverStore = Ariakit.usePopoverStore({
placement: 'bottom',
});
@@ -235,38 +263,25 @@ function Fork({
const buttonStyle = hoverButtonClasses({ isActive, isLast });
- const forkConvo = useForkConvoMutation({
- onSuccess: (data) => {
- navigateToConvo(data.conversation);
- showToast({
- message: localize('com_ui_fork_success'),
- status: 'success',
- });
- },
- onMutate: () => {
- showToast({
- message: localize('com_ui_fork_processing'),
- status: 'info',
- });
- },
- onError: (error) => {
- /** Rate limit error (429 status code) */
- const isRateLimitError =
- (error as any)?.response?.status === 429 ||
- (error as any)?.status === 429 ||
- (error as any)?.statusCode === 429;
-
- showToast({
- message: isRateLimitError
- ? localize('com_ui_fork_error_rate_limit')
- : localize('com_ui_fork_error'),
- status: 'error',
- });
- },
- });
+ const startFork = (request: TForkConvoRequest) => {
+ if (forkConversation == null) {
+ return;
+ }
+ showToast({ message: localize('com_ui_fork_processing'), status: 'info' });
+ forkConversation(request, {
+ onSuccess: () => showToast({ message: localize('com_ui_fork_success'), status: 'success' }),
+ onError: (error) =>
+ showToast({
+ message: isRateLimited(error)
+ ? localize('com_ui_fork_error_rate_limit')
+ : localize('com_ui_fork_error'),
+ status: 'error',
+ }),
+ });
+ };
const conversationId = _convoId ?? '';
- if (!forkingSupported || !conversationId || !messageId) {
+ if (!forkingSupported || forkConversation == null || !conversationId || !messageId) {
return null;
}
@@ -276,7 +291,7 @@ function Fork({
setForkSetting(option);
}
- forkConvo.mutate({
+ startFork({
messageId,
conversationId,
option,
@@ -289,36 +304,36 @@ function Fork({
const forkOptionsConfig = [
{
setting: ForkOptions.DIRECT_PATH,
- label: localize(optionLabels[ForkOptions.DIRECT_PATH]),
+ label: localize(optionLabel(ForkOptions.DIRECT_PATH)),
icon: <GitCommit className="h-full w-full rotate-90 p-2" aria-hidden="true" />,
hoverTitle: (
<>
<GitCommit className="h-5 w-5 rotate-90" aria-hidden="true" />
- {localize(optionLabels[ForkOptions.DIRECT_PATH])}
+ {localize(optionLabel(ForkOptions.DIRECT_PATH))}
</>
),
hoverDescription: localize('com_ui_fork_info_visible'),
},
{
setting: ForkOptions.INCLUDE_BRANCHES,
- label: localize(optionLabels[ForkOptions.INCLUDE_BRANCHES]),
+ label: localize(optionLabel(ForkOptions.INCLUDE_BRANCHES)),
icon: <GitBranchPlus className="h-full w-full rotate-180 p-2" aria-hidden="true" />,
hoverTitle: (
<>
<GitBranchPlus className="h-4 w-4 rotate-180" aria-hidden="true" />
- {localize(optionLabels[ForkOptions.INCLUDE_BRANCHES])}
+ {localize(optionLabel(ForkOptions.INCLUDE_BRANCHES))}
</>
),
hoverDescription: localize('com_ui_fork_info_branches'),
},
{
setting: ForkOptions.TARGET_LEVEL,
- label: localize(optionLabels[ForkOptions.TARGET_LEVEL]),
+ label: localize(optionLabel(ForkOptions.TARGET_LEVEL)),
icon: <ListTree className="h-full w-full p-2" aria-hidden="true" />,
hoverTitle: (
<>
<ListTree className="h-5 w-5" aria-hidden="true" />
- {`${localize(optionLabels[ForkOptions.TARGET_LEVEL])} (${localize('com_endpoint_default')})`}
+ {`${localize(optionLabel(ForkOptions.TARGET_LEVEL))} (${localize('com_endpoint_default')})`}
</>
),
hoverDescription: localize('com_ui_fork_info_target'),
@@ -337,7 +352,7 @@ function Fork({
onClick={(e) => {
if (rememberGlobal) {
e.preventDefault();
- forkConvo.mutate({
+ startFork({
messageId,
splitAtTarget,
conversationId,
@@ -450,4 +465,6 @@ function Fork({
}
/** Memoized: a send re-renders every row's toolbar, and nothing here depends on it. */
-export default memo(Fork);
+const MemoFork: NamedExoticComponent<ForkProps> = memo(Fork);
+
+export default MemoFork;
diff --git a/packages/chat/src/components/messages/__tests__/Fork.spec.tsx b/packages/chat/src/components/messages/__tests__/Fork.spec.tsx
new file mode 100644
index 0000000000..82e7e579a5
--- /dev/null
+++ b/packages/chat/src/components/messages/__tests__/Fork.spec.tsx
@@ -0,0 +1,164 @@
+/**
+ * @jest-environment jsdom
+ */
+import { useState } from 'react';
+import { ForkOptions } from 'librechat-data-provider';
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import type { ForkConversation, ForkPreferences } from '../../../react/messages/host';
+import { createMessagesHost } from '../../../__fixtures__/messagesHost';
+import { MessagesHostProvider } from '../../../react/messages/host';
+import Fork from '../Fork';
+
+const mockShowToast = jest.fn();
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useLocalize: () => (key: string) => key,
+ useToastContext: () => ({ showToast: mockShowToast }),
+}));
+
+type Defaults = Pick<ForkPreferences, 'option' | 'splitAtTarget' | 'rememberOption'>;
+
+function ForkHost({
+ defaults,
+ forkConversation,
+ children,
+}: {
+ defaults?: Partial<Defaults>;
+ forkConversation: ForkConversation | null;
+ children: ReactNode;
+}) {
+ const [option, setOption] = useState(defaults?.option ?? '');
+ const [splitAtTarget, setSplitAtTarget] = useState(defaults?.splitAtTarget ?? false);
+ const [rememberOption, setRememberOption] = useState(defaults?.rememberOption ?? false);
+ const preferences: ForkPreferences = {
+ option,
+ setOption,
+ splitAtTarget,
+ setSplitAtTarget,
+ rememberOption,
+ setRememberOption,
+ };
+ const [host] = useState(() => ({ current: preferences }));
+ host.current = preferences;
+ const [messagesHost] = useState(() =>
+ createMessagesHost({
+ useForkPreferences: () => host.current,
+ useForkConversation: () => forkConversation,
+ }),
+ );
+ return <MessagesHostProvider host={messagesHost}>{children}</MessagesHostProvider>;
+}
+
+describe('Fork', () => {
+ const forkConversation = jest.fn<ReturnType<ForkConversation>, Parameters<ForkConversation>>();
+
+ beforeEach(() => {
+ forkConversation.mockReset();
+ mockShowToast.mockReset();
+ });
+
+ /** The row holding this button does not re-render when the tail moves, so the
+ * split target is read when the fork starts rather than captured at render. */
+ it('sends the tail current at click time as the split target', () => {
+ let latestMessageId = 'assistant-2';
+ render(
+ <ForkHost
+ forkConversation={forkConversation}
+ defaults={{ rememberOption: true, option: ForkOptions.TARGET_LEVEL, splitAtTarget: true }}
+ >
+ <Fork
+ messageId="user-1"
+ conversationId="convo-1"
+ forkingSupported={true}
+ getLatestMessageId={() => latestMessageId}
+ />
+ </ForkHost>,
+ );
+
+ latestMessageId = 'assistant-3';
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
+
+ expect(forkConversation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messageId: 'user-1',
+ splitAtTarget: true,
+ latestMessageId: 'assistant-3',
+ }),
+ expect.anything(),
+ );
+ });
+
+ it('copies without files only when that box is checked for this fork', async () => {
+ render(
+ <ForkHost forkConversation={forkConversation}>
+ <Fork messageId="assistant-1" conversationId="convo-1" forkingSupported={true} />
+ </ForkHost>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
+ fireEvent.click(await screen.findByRole('checkbox', { name: 'com_ui_fork_exclude_files' }));
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_visible' }));
+
+ expect(forkConversation).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ messageId: 'assistant-1',
+ option: ForkOptions.DIRECT_PATH,
+ excludeFiles: true,
+ }),
+ expect.anything(),
+ );
+ });
+
+ it('keeps files by default', async () => {
+ render(
+ <ForkHost forkConversation={forkConversation}>
+ <Fork messageId="assistant-1" conversationId="convo-1" forkingSupported={true} />
+ </ForkHost>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_fork_visible' }));
+
+ const calls = forkConversation.mock.calls;
+ expect(calls[calls.length - 1]?.[0]).not.toHaveProperty('excludeFiles');
+ });
+
+ it('reports progress, success and a rate-limited failure through toasts', async () => {
+ render(
+ <ForkHost forkConversation={forkConversation}>
+ <Fork messageId="assistant-1" conversationId="convo-1" forkingSupported={true} />
+ </ForkHost>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_fork_open_menu' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_fork_visible' }));
+ expect(mockShowToast).toHaveBeenLastCalledWith(
+ expect.objectContaining({ message: 'com_ui_fork_processing' }),
+ );
+
+ const [, events] = forkConversation.mock.calls[0];
+ events.onSuccess();
+ expect(mockShowToast).toHaveBeenLastCalledWith(
+ expect.objectContaining({ message: 'com_ui_fork_success', status: 'success' }),
+ );
+ events.onError({ response: { status: 429 } });
+ expect(mockShowToast).toHaveBeenLastCalledWith(
+ expect.objectContaining({ message: 'com_ui_fork_error_rate_limit', status: 'error' }),
+ );
+ events.onError(new Error('boom'));
+ expect(mockShowToast).toHaveBeenLastCalledWith(
+ expect.objectContaining({ message: 'com_ui_fork_error', status: 'error' }),
+ );
+ });
+
+ it('renders nothing where the host cannot fork', () => {
+ const { container } = render(
+ <ForkHost forkConversation={null}>
+ <Fork messageId="assistant-1" conversationId="convo-1" forkingSupported={true} />
+ </ForkHost>,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx b/packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx
index 044fcb60a2..6534dc998b 100644
--- a/packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx
+++ b/packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx
@@ -3,7 +3,7 @@
*/
import { render, screen } from '@testing-library/react';
import type { TMessage } from 'librechat-data-provider';
-import type { MessagesHost } from '../../../react/messages/host';
+import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { MessagesHostProvider } from '../../../react/messages/host';
import { initEnglish } from '../../../__fixtures__/i18n';
import MessageRow from '../MessageRow';
@@ -17,10 +17,7 @@ jest.mock('../MessageTimestamp', () => ({
beforeAll(initEnglish);
-const host: MessagesHost = {
- useHour12: () => undefined,
- renderFiles: () => <button data-testid="attached-file" />,
-};
+const host = createMessagesHost({ renderFiles: () => <button data-testid="attached-file" /> });
const MESSAGE_BODY = 'Message body';
const attachedMessage = (overrides: Partial<TMessage> = {}) =>
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index c0d75780d8..998a3f7405 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -128,7 +128,12 @@ export {
MessagesHostProvider,
setDefaultMessagesHost,
} from './react/messages/host';
-export type { MessagesHost } from './react/messages/host';
+export type {
+ ForkEvents,
+ MessagesHost,
+ ForkPreferences,
+ ForkConversation,
+} from './react/messages/host';
export {
SoleToolContext,
LoneGroupContext,
diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx
index 8c2b1c443e..52b82f4bcf 100644
--- a/packages/chat/src/react/messages/host.tsx
+++ b/packages/chat/src/react/messages/host.tsx
@@ -1,7 +1,29 @@
import { createContext, useContext } from 'react';
-import type { TMessage } from 'librechat-data-provider';
+import type { TMessage, TForkConvoRequest } from 'librechat-data-provider';
import type { ReactNode } from 'react';
+/** The viewer's fork defaults, kept across sessions. */
+export type ForkPreferences = {
+ /** The fork option used without asking, when `rememberOption` is set. */
+ option: string;
+ setOption: (option: string) => void;
+ /** Whether a fork starts its branch at the target message. */
+ splitAtTarget: boolean;
+ setSplitAtTarget: (value: boolean) => void;
+ /** Whether the fork button forks at once with `option` instead of opening the menu. */
+ rememberOption: boolean;
+ setRememberOption: (value: boolean) => void;
+};
+
+/** What a fork reports back. `onSuccess` runs once the app has opened the new conversation. */
+export type ForkEvents = {
+ onSuccess: () => void;
+ onError: (error: unknown) => void;
+};
+
+/** Starts a fork of a conversation. */
+export type ForkConversation = (request: TForkConvoRequest, events: ForkEvents) => void;
+
/**
* Everything the message list reads from the app: viewer preferences, and render slots for the
* pieces of a row that have not moved into this package yet. Members are hooks or slots, called
@@ -15,12 +37,29 @@ export interface MessagesHost {
useHour12: () => boolean | undefined;
/** Renders the files attached to a user message, above its text. */
renderFiles: (message: TMessage) => ReactNode;
+ /** The viewer's fork defaults. */
+ useForkPreferences: () => ForkPreferences;
+ /** Forks a conversation and opens the copy; `null` where forking is unavailable. */
+ useForkConversation: () => ForkConversation | null;
}
-/** The host rows read outside any provider before an app registers one: locale clock, no slots. */
+const noop = (): void => undefined;
+
+const fallbackForkPreferences: ForkPreferences = {
+ option: '',
+ setOption: noop,
+ splitAtTarget: false,
+ setSplitAtTarget: noop,
+ rememberOption: false,
+ setRememberOption: noop,
+};
+
+/** The host rows read outside any provider before an app registers one: locale clock, no slots, no forking. */
const fallbackHost: MessagesHost = {
useHour12: () => undefined,
renderFiles: () => null,
+ useForkPreferences: () => fallbackForkPreferences,
+ useForkConversation: () => null,
};
const MessagesHostContext = createContext<MessagesHost | null>(null);
diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx
index dca5a19524..664a8908d8 100644
--- a/packages/chat/test/consumer.spec.tsx
+++ b/packages/chat/test/consumer.spec.tsx
@@ -178,6 +178,15 @@ const host: MessagePartsHost = {
const messagesHost: MessagesHost = {
useHour12: () => false,
renderFiles: () => null,
+ useForkPreferences: () => ({
+ option: '',
+ setOption: () => undefined,
+ splitAtTarget: false,
+ setSplitAtTarget: () => undefined,
+ rememberOption: false,
+ setRememberOption: () => undefined,
+ }),
+ useForkConversation: () => null,
};
const renderers: PartRenderers = {