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

🪢 fix: Withhold the Editor's Rerun Where No User Turn Can Be Replayed (#15887)

Marco Beretta566e0a826685
diff --git a/client/src/components/Chat/Messages/Content/EditContentParts.tsx b/client/src/components/Chat/Messages/Content/EditContentParts.tsx
index facf42e0b6..e6857dfd99 100644
--- a/client/src/components/Chat/Messages/Content/EditContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/EditContentParts.tsx
@@ -11,6 +11,7 @@ import type { TMessageContentParts } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import { useMessagesConversation, useMessagesOperations } from '~/Providers';
import { getPartText, isEditablePart, withPartText } from './editableParts';
+import { findRerunParent } from './rerunParent';
import { useGetAddedConvo } from '~/hooks/Chat';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -100,13 +101,13 @@ export default function EditContentParts({
);
const editedMessage = findMessageById(getMessages(), messageId);
const isBusy = isSubmitting || isSaving;
- /** A rerun replays the parent as the turn's user message, so a model turn chained
- * onto another model turn — an imported or restored thread — has none. The action
- * is withheld rather than offered and silently refused; Save still applies. An
- * unresolvable parent keeps it, matching the hover row. */
+ /** A rerun replays the parent as the turn's user message, so a model turn with no
+ * user turn behind it — chained onto another model turn, or left at the root by an
+ * import — has none. The action is withheld rather than offered and silently
+ * refused, the footer says why, and Save still applies. */
const canRerun =
editedMessage?.isCreatedByUser === true ||
- findMessageById(getMessages(), editedMessage?.parentMessageId)?.isCreatedByUser !== false;
+ findRerunParent(getMessages(), editedMessage?.parentMessageId) != null;
/** Only meaningful while a rerun is on offer: it explains why this one is held
* back until the edits are saved. A save-only editor reports unsaved changes
* instead of an unavailable action's precondition. */
@@ -248,14 +249,10 @@ export default function EditContentParts({
},
) === false;
} else {
- const parentMessage = messages?.find(
- (item) => item.messageId === editedMessage.parentMessageId,
- );
- /** A rerun replays the parent as the turn's user message. A manual compaction
- * hangs off the leaf it summarized and never opens this editor, but an
- * imported chain can also put a model turn under a model turn; refuse rather
- * than submit that parent in the user slot. */
- if (!parentMessage || parentMessage.isCreatedByUser !== true) {
+ /** The same resolution the withheld button is gated on, so a rendered Rerun and
+ * the submission it runs cannot disagree about the turn being replayed. */
+ const parentMessage = findRerunParent(messages, editedMessage.parentMessageId);
+ if (!parentMessage) {
return;
}
if (!firstChange) {
@@ -349,8 +346,10 @@ export default function EditContentParts({
[canRerun, enterEdit, saveChanges, updateAndRerun],
);
- /** Both states share the footer's status slot so neither can add a row and
- * shift the message below it. */
+ /** Every state shares the footer's one status slot so none can add a row and
+ * shift the message below it, which orders them by how actionable they are:
+ * a blocked or pending save first, then why the footer offers no rerun — the
+ * question a Save-only editor otherwise leaves unanswered. */
const getStatusMessage = () => {
if (hasBlankEdit) {
return localize('com_ui_message_part_empty');
@@ -361,6 +360,9 @@ export default function EditContentParts({
if (changedParts.length > 0) {
return localize('com_ui_unsaved_changes');
}
+ if (!canRerun) {
+ return localize('com_ui_rerun_needs_user_turn');
+ }
return '';
};
diff --git a/client/src/components/Chat/Messages/Content/EditMessage.tsx b/client/src/components/Chat/Messages/Content/EditMessage.tsx
index faf0db9463..0920950cd9 100644
--- a/client/src/components/Chat/Messages/Content/EditMessage.tsx
+++ b/client/src/components/Chat/Messages/Content/EditMessage.tsx
@@ -1,11 +1,11 @@
import { useRef, useEffect, useCallback, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { useForm } from 'react-hook-form';
-import { findMessageById } from 'librechat-data-provider';
import { Alert, Button, TextareaAutosize } from '@librechat/client';
import { useUpdateMessageMutation } from 'librechat-data-provider/react-query';
import type { TEditProps } from '~/common';
import { useMessagesOperations, useMessagesConversation } from '~/Providers';
+import { findRerunParent } from './rerunParent';
import { useGetAddedConvo } from '~/hooks/Chat';
import { useLocalize } from '~/hooks';
import Container from './Container';
@@ -33,12 +33,11 @@ const EditMessage = ({
/** Only a user turn's draft becomes the submission; an assistant turn's is discarded
* by the rerun (see `resubmitMessage`), so it must not be labelled as an update. */
const isUserTurn = message.isCreatedByUser === true;
- /** A rerun replays the parent as the turn's user message, so a model turn chained
- * onto another model turn — an imported or restored thread — has none. The action
- * is withheld rather than offered and silently refused; Save still applies. An
- * unresolvable parent keeps it, matching the hover row. */
- const canRerun =
- isUserTurn || findMessageById(getMessages(), parentMessageId)?.isCreatedByUser !== false;
+ /** A rerun replays the parent as the turn's user message, so a model turn with no
+ * user turn behind it — chained onto another model turn, or left at the root by an
+ * import — has none. The action is withheld rather than offered and silently
+ * refused, the footer says why, and Save still applies. */
+ const canRerun = isUserTurn || findRerunParent(getMessages(), parentMessageId) != null;
const updateMessageMutation = useUpdateMessageMutation(conversationId ?? '');
const localize = useLocalize();
@@ -107,13 +106,10 @@ const EditMessage = ({
* required so Save cannot blank a response, and a response that is already empty (a
* cancellation before the first token) is exactly what needs rerunning. */
const rerunResponse = () => {
- const parentMessage = getMessages()?.find((msg) => msg.messageId === parentMessageId);
-
- /** A rerun replays the parent as the turn's user message. A manual compaction
- * hangs off the leaf it summarized and never opens this editor, but an imported
- * chain can also put a model turn under a model turn; refuse rather than submit
- * that parent in the user slot. */
- if (!parentMessage || parentMessage.isCreatedByUser !== true) {
+ /** The same resolution the withheld button is gated on, so a rendered Rerun and
+ * the submission it runs cannot disagree about the turn being replayed. */
+ const parentMessage = findRerunParent(getMessages(), parentMessageId);
+ if (!parentMessage) {
return;
}
const submitted = ask(
@@ -212,6 +208,21 @@ const EditMessage = ({
},
});
+ /** The footer carries one status line, so it reports the most actionable state:
+ * an unsaved draft first, because Cancel discards it, then why the footer offers
+ * no rerun — the question a Save-only editor otherwise leaves unanswered. */
+ const getStatusMessage = () => {
+ if (isDirty) {
+ return localize(
+ isUserTurn || !canRerun ? 'com_ui_unsaved_changes' : 'com_ui_rerun_discards_changes',
+ );
+ }
+ if (!canRerun) {
+ return localize('com_ui_rerun_needs_user_turn');
+ }
+ return '';
+ };
+
return (
<Container message={message}>
<section
@@ -252,15 +263,7 @@ const EditMessage = ({
className="line-clamp-2 min-w-0 flex-1 text-xs text-text-secondary"
aria-live="polite"
>
- {/* An answer's draft is discarded by the rerun, which is worth saying only
- while a rerun is on offer; a save-only editor reports unsaved changes. */}
- {isDirty
- ? localize(
- isUserTurn || !canRerun
- ? 'com_ui_unsaved_changes'
- : 'com_ui_rerun_discards_changes',
- )
- : ''}
+ {getStatusMessage()}
</span>
<div className="flex flex-wrap items-center justify-end gap-2">
<Button
diff --git a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx
index 9a15df725c..264066978a 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { ContentTypes } from 'librechat-data-provider';
+import { Constants, ContentTypes } from 'librechat-data-provider';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { FileCitation, TMessage, TMessageContentParts } from 'librechat-data-provider';
import EditContentParts from '../EditContentParts';
@@ -127,6 +127,41 @@ describe('EditContentParts', () => {
expect(screen.queryByRole('button', { name: 'com_ui_rerun' })).toBeNull();
expect(screen.queryByRole('button', { name: 'com_ui_update_rerun' })).toBeNull();
expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeInTheDocument();
+ /** The footer's status slot answers why the action it usually carries is gone. */
+ expect(screen.getByText('com_ui_rerun_needs_user_turn')).toBeInTheDocument();
+
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', ctrlKey: true });
+ expect(mockAsk).not.toHaveBeenCalled();
+ });
+
+ /** The importer chains each saved message onto the previous one, so a thread whose
+ * first human message was empty leaves its reply at the root: the rerun has no
+ * parent in the thread at all, not merely a model one. */
+ it('offers no rerun when the response has no parent turn in the thread', () => {
+ const rootAnswer = {
+ messageId: 'assistant-root',
+ parentMessageId: Constants.NO_PARENT,
+ conversationId: 'conversation-1',
+ isCreatedByUser: false,
+ } as TMessage;
+ mockThread = [rootAnswer];
+
+ render(
+ <EditContentParts
+ content={content}
+ messageId={rootAnswer.messageId}
+ isSubmitting={false}
+ enterEdit={jest.fn()}
+ siblingIdx={0}
+ setSiblingIdx={jest.fn()}
+ renderReadOnlyPart={() => null}
+ />,
+ );
+
+ expect(screen.queryByRole('button', { name: 'com_ui_rerun' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'com_ui_update_rerun' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeInTheDocument();
+ expect(screen.getByText('com_ui_rerun_needs_user_turn')).toBeInTheDocument();
fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', ctrlKey: true });
expect(mockAsk).not.toHaveBeenCalled();
diff --git a/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx
index cba96fc248..6cb0126658 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx
@@ -1,5 +1,6 @@
import React from 'react';
import userEvent from '@testing-library/user-event';
+import { Constants } from 'librechat-data-provider';
import { render, screen, waitFor } from '@testing-library/react';
import type { TMessage } from 'librechat-data-provider';
import EditMessage from '../EditMessage';
@@ -326,6 +327,8 @@ describe('EditMessage', () => {
expect(screen.queryByRole('button', { name: 'com_ui_rerun' })).toBeNull();
expect(screen.queryByRole('button', { name: 'com_ui_update_rerun' })).toBeNull();
expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeInTheDocument();
+ /** The footer's status slot answers why the action it usually carries is gone. */
+ expect(screen.getByText('com_ui_rerun_needs_user_turn')).toBeInTheDocument();
/** The shortcut cannot reach it either. */
const editor = screen.getByTestId('message-text-editor');
@@ -336,6 +339,36 @@ describe('EditMessage', () => {
expect(editor).toHaveAttribute('aria-keyshortcuts', 'Control+S Meta+S Escape');
});
+ /** The importer chains each saved message onto the previous one, so a thread whose
+ * first human message was empty leaves its reply at the root: the rerun has no
+ * parent in the thread at all, not merely a model one. Offering the action there
+ * ran a submission that resolved no parent and returned without feedback. */
+ it('offers no rerun when the response has no parent turn in the thread', async () => {
+ const user = userEvent.setup();
+ const rootAnswer = {
+ messageId: 'assistant-3',
+ parentMessageId: Constants.NO_PARENT,
+ conversationId: 'conversation-1',
+ isCreatedByUser: false,
+ text: 'An imported reply with nothing before it',
+ } as TMessage;
+ mockGetMessages.mockReturnValue([rootAnswer]);
+ const ask = jest.fn();
+ renderEditor({ ask, editedMessage: rootAnswer });
+
+ expect(screen.queryByRole('button', { name: 'com_ui_rerun' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'com_ui_update_rerun' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeInTheDocument();
+ expect(screen.getByText('com_ui_rerun_needs_user_turn')).toBeInTheDocument();
+
+ const editor = screen.getByTestId('message-text-editor');
+ await user.click(editor);
+ await user.keyboard('{Control>}{Enter}{/Control}');
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(editor).toHaveAttribute('aria-keyshortcuts', 'Control+S Meta+S Escape');
+ });
+
/** The rerun-discards-changes warning describes an action this editor does not
* offer, so a save-only editor reports unsaved changes instead. */
it('reports unsaved changes rather than a discarded rerun when no rerun is offered', async () => {
diff --git a/client/src/components/Chat/Messages/Content/rerunParent.ts b/client/src/components/Chat/Messages/Content/rerunParent.ts
new file mode 100644
index 0000000000..9626a92625
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/rerunParent.ts
@@ -0,0 +1,26 @@
+import { findMessageById } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+
+/**
+ * The user turn a rerun would replay, or `undefined` when the message has none.
+ *
+ * A rerun submits the edited message's parent as the turn's user message, so that
+ * parent has to be in the thread and be the user's. Two imported shapes have
+ * neither: a reply chained onto another reply, when the empty human message
+ * between them was skipped, and a reply the importer left at the root, when the
+ * skipped message was the first one. Restored or migrated conversations carry the
+ * same shapes.
+ *
+ * Both editors resolve the parent through this call at render and again at submit,
+ * so the action they offer and the submission they run cannot disagree. Unlike the
+ * hover row, which also renders where no thread is loaded, an unresolved parent
+ * here means absent rather than unknown: an editor only opens over the messages
+ * view, where `getMessages` is the whole conversation.
+ */
+export const findRerunParent = (
+ messages: (TMessage | undefined)[] | null | undefined,
+ parentMessageId?: string | null,
+): TMessage | undefined => {
+ const parent = findMessageById(messages, parentMessageId);
+ return parent?.isCreatedByUser === true ? parent : undefined;
+};
diff --git a/client/src/components/Chat/Messages/HoverButtons.tsx b/client/src/components/Chat/Messages/HoverButtons.tsx
index 6244faa96c..97133fa06f 100644
--- a/client/src/components/Chat/Messages/HoverButtons.tsx
+++ b/client/src/components/Chat/Messages/HoverButtons.tsx
@@ -152,13 +152,19 @@ const HoverButtons = ({
* indexed once for all its rows rather than scanned once per row, and the memo
* is keyed on the parent id: `getMessages` is a cache read, not a subscription,
* and a parent's authorship never changes. Outside the messages view (a search
- * row) the thread is unavailable and the answer stays unknown. */
+ * row) the thread is unavailable and the answer stays unknown; with the thread
+ * in hand a parent that does not resolve is absent — an imported reply the
+ * lineage left at the root — and there is no turn to replay, which `regenerate`
+ * can only log about once the button is pressed. */
const parentIsUserMessage = useMemo(() => {
- if (message.isCreatedByUser === true || message.parentMessageId == null) {
+ if (message.isCreatedByUser === true) {
return undefined;
}
- const parent = findMessageById(getMessages(), message.parentMessageId);
- return parent == null ? undefined : parent.isCreatedByUser === true;
+ const messages = getMessages();
+ if (messages == null) {
+ return undefined;
+ }
+ return findMessageById(messages, message.parentMessageId)?.isCreatedByUser === true;
}, [getMessages, message.isCreatedByUser, message.parentMessageId]);
/** Resolved only if the row has nothing to replay, because the artifact check
diff --git a/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx
index 4e887f7c23..54cbb01bb8 100644
--- a/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx
+++ b/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx
@@ -4,6 +4,7 @@ import { render, screen } from '@testing-library/react';
import { RecoilRoot, type MutableSnapshot } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
+ Constants,
ContentTypes,
EModelEndpoint,
type TConversation,
@@ -387,6 +388,33 @@ describe('HoverButtons edit affordance', () => {
expect(screen.queryByTestId('continue-generation-button')).toBeNull();
});
+ /** The same imported shape with the skipped human message first: the reply is
+ * chained onto nothing, so the thread holds no parent at all. `regenerate` can
+ * only log that when the button is pressed, so the row withholds it. */
+ it('withholds the rerun shapes on a model turn left at the root', () => {
+ const rootReply = {
+ ...userMessage,
+ messageId: 'assistant-1',
+ parentMessageId: Constants.NO_PARENT,
+ isCreatedByUser: false,
+ text: 'An imported reply with nothing before it',
+ finish_reason: 'length',
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: rootReply,
+ isLast: true,
+ latestMessageId: rootReply.messageId,
+ thread: [rootReply],
+ });
+
+ /** Its stored text is still saved directly, so the editor stays. */
+ expect(container.querySelector(`#edit-${rootReply.messageId}`)).not.toBeNull();
+ expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
+ expect(screen.queryByTestId('continue-generation-button')).toBeNull();
+ });
+
/** An artifact keeps its own read-only renderer, so a chained reply made only of
* one has no field to type in and no turn to replay: its editor would be dead. */
it('withholds the editor on a chained model turn whose only content is an artifact', () => {
diff --git a/client/src/hooks/useGenerationsByLatest.ts b/client/src/hooks/useGenerationsByLatest.ts
index f5427fd50d..422cfc7f49 100644
--- a/client/src/hooks/useGenerationsByLatest.ts
+++ b/client/src/hooks/useGenerationsByLatest.ts
@@ -15,8 +15,8 @@ type TUseGenerations = {
* replay needs the answer. */
getHasEditablePart?: () => boolean;
/** For a model turn: whether the message it hangs off is the user turn a rerun
- * would replay. `undefined` when the thread is unavailable (a search or share
- * row) or the parent was not resolved, which withholds nothing. */
+ * would replay, `false` when no such turn is in the thread. `undefined` when the
+ * thread is unavailable (a search or share row), which withholds nothing. */
parentIsUserMessage?: boolean;
/** The turn carries the server's manual-compaction marker. Compact runs on
* whatever leaf the branch ends with, so such a turn can hang off a user
@@ -52,12 +52,12 @@ export default function useGenerationsByLatest({
);
/** Every rerun shape replays the message's parent as the turn's user message, so
- * a model turn hanging off another model turn has none: the submission would
- * mint a user message under an existing response's id and run on empty text.
- * An imported or restored thread reaches that shape whenever a reply is chained
- * onto a reply, and a manual compaction reaches it whenever it summarized an
- * answer. A marked compaction is excluded whatever it hangs off. An unknown
- * parent withholds nothing, and the rerun paths refuse it on their own. */
+ * a model turn with no user turn behind it has none: the submission would mint a
+ * user message under an existing response's id and run on empty text. An imported
+ * or restored thread reaches that shape whenever a reply is chained onto a reply
+ * or left at the root, and a manual compaction reaches it whenever it summarized
+ * an answer. A marked compaction is excluded whatever it hangs off. Only a row
+ * that cannot see the thread at all withholds nothing. */
const hasNoTurnToReplay =
!isCreatedByUser && (parentIsUserMessage === false || isUserInitiatedCompaction);
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 75bd3c872f..2c8142cc60 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1962,6 +1962,7 @@
"com_ui_requires_auth": "Requires Authentication",
"com_ui_rerun": "Rerun",
"com_ui_rerun_discards_changes": "Rerunning discards these changes and generates a new response. Save to keep them.",
+ "com_ui_rerun_needs_user_turn": "Rerunning replays the user message before a response, and this one has none. Your edits can still be saved.",
"com_ui_reset": "Reset",
"com_ui_reset_adjustments": "Reset adjustments",
"com_ui_reset_var": "Reset {{0}}",
diff --git a/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts b/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts
index 79d098f072..49fb188f8d 100644
--- a/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts
+++ b/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts
@@ -240,6 +240,46 @@ test.describe('compaction rerun controls', () => {
await expect(page.getByRole('button', { name: 'Save' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Rerun', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Update & rerun' })).toHaveCount(0);
+ /* ...and the footer says why the action it usually carries is gone. */
+ await expect(
+ page.getByText('Rerunning replays the user message before a response', { exact: false }),
+ ).toBeVisible();
+ await expect(editor).toHaveAttribute('aria-keyshortcuts', 'Control+S Meta+S Escape');
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a reply left at the root keeps its editor without a rerun @scenario:root-reply-keeps-editor-without-rerun', async ({
+ page,
+ }) => {
+ const rootReplyId = randomUUID();
+ const conversationId = await seedBranch([
+ {
+ messageId: rootReplyId,
+ parentMessageId: ROOT_PARENT,
+ text: 'An imported reply with nothing before it',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ finish_reason: 'length',
+ },
+ ]);
+ try {
+ await openRow(page, conversationId, rootReplyId);
+
+ /* The importer chains each saved message onto the previous one, so a skipped
+ first human message leaves its reply with no parent in the thread at all. */
+ await expect(page.getByTestId('regenerate-generation-button')).toHaveCount(0);
+ await expect(page.getByTestId('continue-generation-button')).toHaveCount(0);
+
+ await page.locator(`[id="edit-${rootReplyId}"]`).click();
+ const editor = page.getByTestId('message-text-editor');
+ await expect(editor).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Save' })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Rerun', exact: true })).toHaveCount(0);
+ await expect(
+ page.getByText('Rerunning replays the user message before a response', { exact: false }),
+ ).toBeVisible();
await expect(editor).toHaveAttribute('aria-keyshortcuts', 'Control+S Meta+S Escape');
} finally {
await cleanup(conversationId);