From ab6b01b51cd65c821287229104f4944e8a54977d Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:18:52 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8D=B4=20refactor:=20Move=20the=20Fork=20?= =?UTF-8?q?and=20Feedback=20Actions=20into=20@librechat/chat=20(#17561)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: Move the Fork and Feedback Actions into @librechat/chat Fork reads the viewer's fork defaults and starts the fork through two new MessagesHost members, keeping its toasts and rate-limit copy in the package; the app supplies them from its settings atoms and the fork mutation, whose own callbacks open the copy so a row that unmounts mid-request still lands there. Feedback moves as is. @ariakit/react becomes a peer dependency of the package. * test: Cover Fork and Feedback in the Mock Harness * chore: Sort MessageRow Spec Imports * fix: Resolve Fork Labels Per Call and Pin the Fork Toast Locator * test: Give the Consumer Spec Messages Host the Fork Members --- client/src/Providers/MessagesHostContext.tsx | 58 ++++++- .../components/Chat/Messages/HoverButtons.tsx | 4 +- .../Chat/Messages/__tests__/Fork.spec.tsx | 94 ---------- client/src/components/Conversations/index.ts | 1 - .../mock/scenarios/fork-feedback.spec.ts | 83 +++++++++ eslint-suppressions.json | 32 ++-- eslint.config.mjs | 1 + .../chat/src/__fixtures__/messagesHost.ts | 20 +++ packages/chat/src/components.ts | 2 + .../src/components/messages}/Feedback.tsx | 14 +- .../chat/src/components/messages}/Fork.tsx | 151 +++++++++------- .../messages/__tests__/Fork.spec.tsx | 164 ++++++++++++++++++ .../messages/__tests__/MessageRow.spec.tsx | 7 +- packages/chat/src/react.ts | 7 +- packages/chat/src/react/messages/host.tsx | 43 ++++- packages/chat/test/consumer.spec.tsx | 9 + 16 files changed, 492 insertions(+), 198 deletions(-) delete mode 100644 client/src/components/Chat/Messages/__tests__/Fork.spec.tsx create mode 100644 e2e/specs/mock/scenarios/fork-feedback.spec.ts create mode 100644 packages/chat/src/__fixtures__/messagesHost.ts rename {client/src/components/Chat/Messages => packages/chat/src/components/messages}/Feedback.tsx (96%) rename {client/src/components/Chat/Messages => packages/chat/src/components/messages}/Fork.tsx (81%) create mode 100644 packages/chat/src/components/messages/__tests__/Fork.spec.tsx 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(null); + const { mutate } = useForkConvoMutation({ + onSuccess: (data) => { + navigateToConvo(data.conversation); + events.current?.onSuccess(); + }, + onError: (error) => events.current?.onError(error), + }); + return useCallback( + (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) => , + 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( - { - set(store.rememberDefaultFork, true); - set(store.forkSetting, ForkOptions.TARGET_LEVEL); - set(store.splitAtTarget, true); - }} - > - latestMessageId} - /> - , - ); - - 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( - - - , - ); - - 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( - - - , - ); - - 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 { + 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 = 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.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 = ({ 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 = ({ 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 = ({ ); }; -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(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: