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 Rerun Controls on Compaction Turns (#15797)

Marco Berettaafaf22f608b7
diff --git a/client/src/components/Chat/Messages/Content/EditContentParts.tsx b/client/src/components/Chat/Messages/Content/EditContentParts.tsx
index ac227b6d97..facf42e0b6 100644
--- a/client/src/components/Chat/Messages/Content/EditContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/EditContentParts.tsx
@@ -1,12 +1,16 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { Alert, Button, TextareaAutosize } from '@librechat/client';
-import { ContentTypes, stripReasoningLabelMetadata } from 'librechat-data-provider';
import { useUpdateMessageContentMutation } from 'librechat-data-provider/react-query';
-import type { TMessageContentParts, TextData } from 'librechat-data-provider';
+import {
+ ContentTypes,
+ findMessageById,
+ stripReasoningLabelMetadata,
+} from 'librechat-data-provider';
+import type { TMessageContentParts } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import { useMessagesConversation, useMessagesOperations } from '~/Providers';
-import { splitMarkdownIntoBlocks } from './splitMarkdown';
+import { getPartText, isEditablePart, withPartText } from './editableParts';
import { useGetAddedConvo } from '~/hooks/Chat';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -32,41 +36,6 @@ type EditContentPartsProps = {
renderReadOnlyPart: (part: TMessageContentParts, index: number, isLastPart: boolean) => ReactNode;
};
-/** An editable part holds either a bare string or a `{ value, annotations }` object,
- * which is how the Assistants thread sync stores a response that carries file
- * citations. Both the read and the write below go through this, so an edit lands in
- * the same shape it was read from. */
-const getPartValue = (part: TMessageContentParts): string | TextData => {
- if (part.type === ContentTypes.TEXT) {
- return part.text;
- }
- if (part.type === ContentTypes.THINK) {
- return part.think;
- }
- return undefined;
-};
-
-const getPartText = (part: TMessageContentParts): string | undefined => {
- const value = getPartValue(part);
- return typeof value === 'string' ? value : value?.value;
-};
-
-const withPartText = (part: TMessageContentParts, text: string): string | TextData => {
- const value = getPartValue(part);
- return value != null && typeof value === 'object' ? { ...value, value: text } : text;
-};
-
-const containsArtifact = (text: string): boolean => {
- if (!text.includes('artifact')) {
- return false;
- }
- try {
- return splitMarkdownIntoBlocks(text).some((block) => block.artifactCount > 0);
- } catch {
- return false;
- }
-};
-
export default function EditContentParts({
content,
contentIndexOffset = 0,
@@ -92,20 +61,17 @@ export default function EditContentParts({
const editableParts = useMemo<EditablePart[]>(() => {
const result: EditablePart[] = [];
content.forEach((part, localIndex) => {
- if (!part || (part.type !== ContentTypes.TEXT && part.type !== ContentTypes.THINK)) {
- return;
- }
- if (part.type === ContentTypes.TEXT && part.tool_call_ids != null) {
+ if (!part || !isEditablePart(part)) {
return;
}
const original = getPartText(part);
- if (original == null || containsArtifact(original)) {
+ if (original == null) {
return;
}
result.push({
index: localIndex + contentIndexOffset,
localIndex,
- type: part.type,
+ type: part.type as EditableType,
original,
});
});
@@ -132,9 +98,20 @@ export default function EditContentParts({
() => changedParts.some((part) => (drafts[part.index] ?? '').trim() === ''),
[changedParts, drafts],
);
- const editedMessage = getMessages()?.find((item) => item.messageId === messageId);
- const rerunRequiresSave = editedMessage?.isCreatedByUser !== true && changedParts.length > 1;
+ 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. */
+ const canRerun =
+ editedMessage?.isCreatedByUser === true ||
+ findMessageById(getMessages(), editedMessage?.parentMessageId)?.isCreatedByUser !== false;
+ /** 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. */
+ const rerunRequiresSave =
+ canRerun && editedMessage?.isCreatedByUser !== true && changedParts.length > 1;
useEffect(() => {
const editor = firstEditorRef.current;
@@ -274,7 +251,11 @@ export default function EditContentParts({
const parentMessage = messages?.find(
(item) => item.messageId === editedMessage.parentMessageId,
);
- if (!parentMessage) {
+ /** 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) {
return;
}
if (!firstChange) {
@@ -355,7 +336,7 @@ export default function EditContentParts({
enterEdit(true);
return;
}
- if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ if (canRerun && event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
updateAndRerun();
return;
@@ -365,7 +346,7 @@ export default function EditContentParts({
void saveChanges();
}
},
- [enterEdit, saveChanges, updateAndRerun],
+ [canRerun, enterEdit, saveChanges, updateAndRerun],
);
/** Both states share the footer's status slot so neither can add a row and
@@ -426,7 +407,11 @@ export default function EditContentParts({
}
onKeyDown={handleKeyDown}
aria-label={`${localize('com_ui_editable_message')}: ${label}`}
- aria-keyshortcuts="Control+Enter Meta+Enter Control+S Meta+S Escape"
+ aria-keyshortcuts={
+ canRerun
+ ? 'Control+Enter Meta+Enter Control+S Meta+S Escape'
+ : 'Control+S Meta+S Escape'
+ }
disabled={isBusy}
minRows={3}
dir={isRTL ? 'rtl' : 'ltr'}
@@ -466,14 +451,16 @@ export default function EditContentParts({
>
{isSaving ? localize('com_ui_saving') : localize('com_ui_save')}
</Button>
- <Button
- size="sm"
- variant="submit"
- onClick={updateAndRerun}
- disabled={rerunRequiresSave || hasBlankEdit || isBusy}
- >
- {changedParts.length > 0 ? localize('com_ui_update_rerun') : localize('com_ui_rerun')}
- </Button>
+ {canRerun && (
+ <Button
+ size="sm"
+ variant="submit"
+ onClick={updateAndRerun}
+ disabled={rerunRequiresSave || hasBlankEdit || isBusy}
+ >
+ {changedParts.length > 0 ? localize('com_ui_update_rerun') : localize('com_ui_rerun')}
+ </Button>
+ )}
</div>
</footer>
</section>
diff --git a/client/src/components/Chat/Messages/Content/EditMessage.tsx b/client/src/components/Chat/Messages/Content/EditMessage.tsx
index 976347a6b2..faf0db9463 100644
--- a/client/src/components/Chat/Messages/Content/EditMessage.tsx
+++ b/client/src/components/Chat/Messages/Content/EditMessage.tsx
@@ -1,6 +1,7 @@
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';
@@ -32,6 +33,12 @@ 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;
const updateMessageMutation = useUpdateMessageMutation(conversationId ?? '');
const localize = useLocalize();
@@ -102,7 +109,11 @@ const EditMessage = ({
const rerunResponse = () => {
const parentMessage = getMessages()?.find((msg) => msg.messageId === parentMessageId);
- if (!parentMessage) {
+ /** 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) {
return;
}
const submitted = ask(
@@ -225,7 +236,11 @@ const EditMessage = ({
'disabled:opacity-50 md:max-h-[75vh]',
)}
aria-label={localize('com_ui_message_input')}
- aria-keyshortcuts="Control+Enter Meta+Enter Control+S Meta+S Escape"
+ aria-keyshortcuts={
+ canRerun
+ ? 'Control+Enter Meta+Enter Control+S Meta+S Escape'
+ : 'Control+S Meta+S Escape'
+ }
disabled={isSubmitting || updateMessageMutation.isLoading}
dir={isRTL ? 'rtl' : 'ltr'}
/>
@@ -237,8 +252,14 @@ 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 ? 'com_ui_unsaved_changes' : 'com_ui_rerun_discards_changes')
+ ? localize(
+ isUserTurn || !canRerun
+ ? 'com_ui_unsaved_changes'
+ : 'com_ui_rerun_discards_changes',
+ )
: ''}
</span>
<div className="flex flex-wrap items-center justify-end gap-2">
@@ -268,19 +289,21 @@ const EditMessage = ({
persisted message, already submittable by construction, `isValid` is
false for a tick after mount while the form's first validation pass
settles, and an answer's draft is never sent at all. */}
- <Button
- ref={submitButtonRef}
- size="sm"
- variant="submit"
- disabled={
- isSubmitting ||
- updateMessageMutation.isLoading ||
- (isUserTurn && isDirty && !isValid)
- }
- onClick={isUserTurn ? handleSubmit(resubmitMessage) : rerunResponse}
- >
- {isDirty && isUserTurn ? localize('com_ui_update_rerun') : localize('com_ui_rerun')}
- </Button>
+ {canRerun && (
+ <Button
+ ref={submitButtonRef}
+ size="sm"
+ variant="submit"
+ disabled={
+ isSubmitting ||
+ updateMessageMutation.isLoading ||
+ (isUserTurn && isDirty && !isValid)
+ }
+ onClick={isUserTurn ? handleSubmit(resubmitMessage) : rerunResponse}
+ >
+ {isDirty && isUserTurn ? localize('com_ui_update_rerun') : localize('com_ui_rerun')}
+ </Button>
+ )}
</div>
</footer>
</section>
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 4c69c8d49c..9a15df725c 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx
@@ -32,6 +32,9 @@ const parentMessage = {
text: 'Check the service',
} as TMessage;
+/** The rows the editor resolves this message and its parent from. */
+let mockThread: TMessage[] = [parentMessage, message];
+
jest.mock('librechat-data-provider/react-query', () => ({
useUpdateMessageContentMutation: () => ({
mutateAsync: mockMutateAsync,
@@ -45,7 +48,7 @@ jest.mock('~/Providers', () => ({
}),
useMessagesOperations: () => ({
ask: mockAsk,
- getMessages: () => [parentMessage, message],
+ getMessages: () => mockThread,
setMessages: mockSetMessages,
}),
}));
@@ -75,6 +78,7 @@ describe('EditContentParts', () => {
mockMutateAsync.mockResolvedValue({});
mockChatDirection = 'LTR';
message.content = undefined;
+ mockThread = [parentMessage, message];
});
it('uses one editor footer and keeps non-editable parts visible', () => {
@@ -96,6 +100,38 @@ describe('EditContentParts', () => {
expect(screen.getAllByRole('button')).toHaveLength(3);
});
+ /** A rerun replays the parent as the turn's user message. A model turn chained
+ * onto another model turn has none, so the action is withheld instead of offered
+ * and silently refused; Save still applies. */
+ it('offers no rerun when the parent to replay is not a user turn', () => {
+ const chainedAnswer = {
+ messageId: 'assistant-2',
+ parentMessageId: message.messageId,
+ conversationId: 'conversation-1',
+ isCreatedByUser: false,
+ } as TMessage;
+ mockThread = [parentMessage, message, chainedAnswer];
+
+ render(
+ <EditContentParts
+ content={content}
+ messageId={chainedAnswer.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();
+
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter', ctrlKey: true });
+ expect(mockAsk).not.toHaveBeenCalled();
+ });
+
it('saves changed text parts before closing the editor', async () => {
const enterEdit = jest.fn();
render(
@@ -339,6 +375,42 @@ describe('EditContentParts', () => {
expect(screen.getByText('com_ui_save_before_rerun')).toBeInTheDocument();
});
+ /** The save-before-rerun precondition describes an action this editor does not
+ * offer, so a save-only editor reports unsaved changes instead. */
+ it('reports unsaved changes rather than a rerun precondition when no rerun is offered', () => {
+ const chainedAnswer = {
+ messageId: 'assistant-2',
+ parentMessageId: message.messageId,
+ conversationId: 'conversation-1',
+ isCreatedByUser: false,
+ } as TMessage;
+ mockThread = [parentMessage, message, chainedAnswer];
+ const multiPartContent = [
+ { type: ContentTypes.TEXT, text: 'First response' },
+ { type: ContentTypes.TEXT, text: 'Second response' },
+ ] as TMessageContentParts[];
+
+ render(
+ <EditContentParts
+ content={multiPartContent}
+ messageId={chainedAnswer.messageId}
+ isSubmitting={false}
+ enterEdit={jest.fn()}
+ siblingIdx={0}
+ setSiblingIdx={jest.fn()}
+ renderReadOnlyPart={() => null}
+ />,
+ );
+
+ const editors = screen.getAllByRole('textbox');
+ fireEvent.change(editors[0], { target: { value: 'Updated first response' } });
+ fireEvent.change(editors[1], { target: { value: 'Updated second response' } });
+
+ expect(screen.getByText('com_ui_unsaved_changes')).toBeInTheDocument();
+ expect(screen.queryByText('com_ui_save_before_rerun')).toBeNull();
+ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeEnabled();
+ });
+
it('reconciles the parts that were persisted when a later part is refused', async () => {
const enterEdit = jest.fn();
const multiPartContent = [
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 a6ba8ea908..cba96fc248 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/EditMessage.spec.tsx
@@ -305,6 +305,57 @@ describe('EditMessage', () => {
expect(enterEdit).toHaveBeenCalledWith(true);
});
+ /** A rerun replays the parent as the turn's user message. A model turn chained
+ * onto another model turn — an imported thread with no user message between two
+ * replies — has no such parent, and submitting one would mint a user message
+ * under an existing response's id. The editor withholds the action instead of
+ * offering one that silently refuses, and Save still applies. */
+ it('offers no rerun when the parent to replay is not a user turn', async () => {
+ const user = userEvent.setup();
+ const chainedAnswer = {
+ messageId: 'assistant-2',
+ parentMessageId: assistantMessage.messageId,
+ conversationId: 'conversation-1',
+ isCreatedByUser: false,
+ text: 'A second answer with no user turn behind it',
+ } as TMessage;
+ mockGetMessages.mockReturnValue([message, assistantMessage, chainedAnswer]);
+ const ask = jest.fn();
+ renderEditor({ ask, editedMessage: chainedAnswer });
+
+ 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 shortcut cannot reach it either. */
+ 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 () => {
+ const user = userEvent.setup();
+ const chainedAnswer = {
+ messageId: 'assistant-2',
+ parentMessageId: assistantMessage.messageId,
+ conversationId: 'conversation-1',
+ isCreatedByUser: false,
+ text: 'A second answer with no user turn behind it',
+ } as TMessage;
+ mockGetMessages.mockReturnValue([message, assistantMessage, chainedAnswer]);
+ renderEditor({ editedMessage: chainedAnswer });
+
+ await user.type(screen.getByTestId('message-text-editor'), ' edited');
+
+ expect(screen.getByText('com_ui_unsaved_changes')).toBeInTheDocument();
+ expect(screen.queryByText('com_ui_rerun_discards_changes')).toBeNull();
+ });
+
/** A response cancelled before its first token is exactly what needs rerunning, and
* the form marks text required so Save cannot blank a message. Routing the rerun
* through that validation left the enabled button inert. */
diff --git a/client/src/components/Chat/Messages/Content/__tests__/editableParts.spec.ts b/client/src/components/Chat/Messages/Content/__tests__/editableParts.spec.ts
new file mode 100644
index 0000000000..ee9686e4b0
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/editableParts.spec.ts
@@ -0,0 +1,54 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+import { hasEditablePart } from '../editableParts';
+
+const artifactText = ':::artifact{identifier="demo" type="text/html" title="Demo"}\n<div />\n:::';
+
+describe('hasEditablePart', () => {
+ it.each([
+ ['a message with no content array', undefined],
+ ['a text part', [{ type: ContentTypes.TEXT, text: 'an answer' }]],
+ ['a reasoning part', [{ type: ContentTypes.THINK, think: 'thinking out loud' }]],
+ [
+ 'a text part beside a tool call',
+ [
+ { type: ContentTypes.TOOL_CALL, tool_call: {} },
+ { type: ContentTypes.TEXT, text: 'an answer' },
+ ],
+ ],
+ [
+ 'prose beside an artifact',
+ [
+ { type: ContentTypes.TEXT, text: artifactText },
+ { type: ContentTypes.TEXT, text: 'and here is what it does' },
+ ],
+ ],
+ ])('is true for %s', (_label, content) => {
+ expect(hasEditablePart({ content } as TMessage)).toBe(true);
+ });
+
+ /** Every turn whose editor would open with no field: a compaction that finished,
+ * one that persisted an error part instead, tool output, and an answer that is
+ * only an artifact — `EditContentParts` keeps that one in its read-only
+ * renderer. */
+ it.each([
+ ['an empty content array', []],
+ [
+ 'a summary-only turn',
+ [
+ {
+ type: ContentTypes.SUMMARY,
+ content: [{ type: ContentTypes.TEXT, text: 'compacted' }],
+ },
+ ],
+ ],
+ ['an error-only turn', [{ type: ContentTypes.ERROR, error: 'failed' }]],
+ [
+ 'text that belongs to a tool call',
+ [{ type: ContentTypes.TEXT, text: 'tool output', tool_call_ids: ['call-1'] }],
+ ],
+ ['an artifact-only answer', [{ type: ContentTypes.TEXT, text: artifactText }]],
+ ])('is false for %s', (_label, content) => {
+ expect(hasEditablePart({ content } as TMessage)).toBe(false);
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/editableParts.ts b/client/src/components/Chat/Messages/Content/editableParts.ts
new file mode 100644
index 0000000000..6e54913ba1
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/editableParts.ts
@@ -0,0 +1,71 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessage, TMessageContentParts, TextData } from 'librechat-data-provider';
+import { splitMarkdownIntoBlocks } from './splitMarkdown';
+
+/** An editable part holds either a bare string or a `{ value, annotations }` object,
+ * which is how the Assistants thread sync stores a response that carries file
+ * citations. Reads and writes both go through this, so an edit lands in the same
+ * shape it was read from. */
+export const getPartValue = (part: TMessageContentParts): string | TextData | undefined => {
+ if (part.type === ContentTypes.TEXT) {
+ return part.text;
+ }
+ if (part.type === ContentTypes.THINK) {
+ return part.think;
+ }
+ return undefined;
+};
+
+export const getPartText = (part: TMessageContentParts): string | undefined => {
+ const value = getPartValue(part);
+ return typeof value === 'string' ? value : value?.value;
+};
+
+export const withPartText = (part: TMessageContentParts, text: string): string | TextData => {
+ const value = getPartValue(part);
+ return value != null && typeof value === 'object' ? { ...value, value: text } : text;
+};
+
+const containsArtifact = (text: string): boolean => {
+ if (!text.includes('artifact')) {
+ return false;
+ }
+ try {
+ return splitMarkdownIntoBlocks(text).some((block) => block.artifactCount > 0);
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Whether the editor gives this part a field to type in. Tool-call output and
+ * artifact-bearing text keep their specialized renderers and stay read-only, so
+ * neither becomes a textarea.
+ */
+export const isEditablePart = (part?: TMessageContentParts | null): boolean => {
+ if (!part || (part.type !== ContentTypes.TEXT && part.type !== ContentTypes.THINK)) {
+ return false;
+ }
+ if (part.type === ContentTypes.TEXT && part.tool_call_ids != null) {
+ return false;
+ }
+ const text = getPartText(part);
+ return text != null && !containsArtifact(text);
+};
+
+/**
+ * Whether opening the editor on this message would show any field at all. A
+ * message with no content array is edited as plain text, so it always would; a
+ * turn made only of a summary, an error, tool calls or an artifact would not, and
+ * on a turn that also has no user turn to replay its editor is inert.
+ *
+ * The artifact check parses markdown, so callers resolve this only for the rows
+ * that can act on the answer.
+ */
+export const hasEditablePart = (message?: Pick<TMessage, 'content'> | null): boolean => {
+ const content = message?.content;
+ if (!Array.isArray(content)) {
+ return true;
+ }
+ return content.some(isEditablePart);
+};
diff --git a/client/src/components/Chat/Messages/HoverButtons.tsx b/client/src/components/Chat/Messages/HoverButtons.tsx
index b6e8a0a80e..6244faa96c 100644
--- a/client/src/components/Chat/Messages/HoverButtons.tsx
+++ b/client/src/components/Chat/Messages/HoverButtons.tsx
@@ -1,6 +1,7 @@
-import React, { useState, useMemo, memo } from 'react';
+import React, { useState, useMemo, useCallback, memo } from 'react';
import { Copy, Check } from 'lucide';
import { useRecoilState } from 'recoil';
+import { findMessageById, isUserInitiatedCompaction } from 'librechat-data-provider';
import {
Button,
EditIcon,
@@ -11,6 +12,8 @@ import {
} from '@librechat/client';
import type { TConversation, TMessage, TFeedback } from 'librechat-data-provider';
import { useGenerationsByLatest, useLocalize } from '~/hooks';
+import { useOptionalMessagesOperations } from '~/Providers';
+import { hasEditablePart } from './Content/editableParts';
import { Fork } from '~/components/Conversations';
import { hoverButtonClasses } from './styles';
import MessageAudio from './MessageAudio';
@@ -135,6 +138,7 @@ const HoverButtons = ({
const localize = useLocalize();
const [isCopied, setIsCopied] = useState(false);
const [TextToSpeech] = useRecoilState<boolean>(store.textToSpeech);
+ const { getMessages } = useOptionalMessagesOperations();
const endpoint = useMemo(() => {
if (!conversation) {
@@ -143,6 +147,24 @@ const HoverButtons = ({
return conversation.endpointType ?? conversation.endpoint;
}, [conversation]);
+ /** Which turn a rerun would replay, resolved for a model turn only. The lookup
+ * goes through the messages array's memoized id index, so a conversation is
+ * 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. */
+ const parentIsUserMessage = useMemo(() => {
+ if (message.isCreatedByUser === true || message.parentMessageId == null) {
+ return undefined;
+ }
+ const parent = findMessageById(getMessages(), message.parentMessageId);
+ return parent == null ? undefined : parent.isCreatedByUser === true;
+ }, [getMessages, message.isCreatedByUser, message.parentMessageId]);
+
+ /** Resolved only if the row has nothing to replay, because the artifact check
+ * inside parses markdown. */
+ const getHasEditablePart = useCallback(() => hasEditablePart(message), [message]);
+
const generationCapabilities = useGenerationsByLatest({
isEditing,
isSubmitting,
@@ -152,6 +174,9 @@ const HoverButtons = ({
searchResult: message.searchResult,
finish_reason: message.finish_reason,
isCreatedByUser: message.isCreatedByUser,
+ getHasEditablePart,
+ parentIsUserMessage,
+ isUserInitiatedCompaction: isUserInitiatedCompaction(message),
latestMessageId: latestMessageId,
});
diff --git a/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx
index 6c44d5f9c1..4e887f7c23 100644
--- a/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx
+++ b/client/src/components/Chat/Messages/__tests__/HoverButtons.spec.tsx
@@ -9,6 +9,10 @@ import {
type TConversation,
type TMessage,
} from 'librechat-data-provider';
+import {
+ MessagesViewContext,
+ type MessagesViewContextValue,
+} from '~/Providers/MessagesViewContext';
import { hasCopyableText } from '~/hooks/Messages/useCopyToClipboard';
import HoverButtons from '~/components/Chat/Messages/HoverButtons';
import store from '~/store';
@@ -35,6 +39,7 @@ function renderHoverButtons({
latestMessageId = 'assistant-1',
getCanCopy = () => hasCopyableText({ text: message.text, content: message.content }),
handleFeedback,
+ thread,
}: {
isSubmitting: boolean;
message?: TMessage;
@@ -43,6 +48,9 @@ function renderHoverButtons({
latestMessageId?: string;
getCanCopy?: () => boolean;
handleFeedback?: () => void;
+ /** The rows the hover controls resolve the message's parent from. Omitted, the
+ * thread is unavailable, as on a search row. */
+ thread?: TMessage[];
}) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -53,23 +61,27 @@ function renderHoverButtons({
const { container } = render(
<QueryClientProvider client={queryClient}>
<RecoilRoot initializeState={initializeState}>
- <MemoryRouter>
- <HoverButtons
- index={0}
- isLast={isLast}
- isEditing={false}
- message={message}
- conversation={targetConversation}
- isSubmitting={isSubmitting}
- enterEdit={jest.fn()}
- regenerate={jest.fn()}
- handleContinue={jest.fn()}
- copyToClipboard={jest.fn()}
- getCanCopy={getCanCopy}
- latestMessageId={latestMessageId}
- handleFeedback={handleFeedback}
- />
- </MemoryRouter>
+ <MessagesViewContext.Provider
+ value={{ getMessages: () => thread } as unknown as MessagesViewContextValue}
+ >
+ <MemoryRouter>
+ <HoverButtons
+ index={0}
+ isLast={isLast}
+ isEditing={false}
+ message={message}
+ conversation={targetConversation}
+ isSubmitting={isSubmitting}
+ enterEdit={jest.fn()}
+ regenerate={jest.fn()}
+ handleContinue={jest.fn()}
+ copyToClipboard={jest.fn()}
+ getCanCopy={getCanCopy}
+ latestMessageId={latestMessageId}
+ handleFeedback={handleFeedback}
+ />
+ </MemoryRouter>
+ </MessagesViewContext.Provider>
</RecoilRoot>
</QueryClientProvider>,
);
@@ -214,6 +226,257 @@ describe('HoverButtons edit affordance', () => {
expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
expect(screen.queryByTestId('continue-generation-button')).toBeNull();
});
+
+ /** A compaction turn parents onto the leaf it summarized, so every rerun shape
+ * would replay a model turn in the user slot: the submission mints a user
+ * message under an existing response's id and runs on empty text. Its editor
+ * has nothing to show either — neither a summary nor the error part a skipped
+ * or failed compaction persists is an editable part type. */
+ it.each([
+ [
+ 'a finished compaction',
+ [
+ {
+ type: ContentTypes.SUMMARY,
+ content: [{ type: ContentTypes.TEXT, text: 'Earlier turns, compacted.' }],
+ },
+ ],
+ ],
+ [
+ 'a failed compaction',
+ [
+ {
+ type: ContentTypes.SUMMARY,
+ failed: true,
+ content: [{ type: ContentTypes.TEXT, text: 'Earlier turns, compacted.' }],
+ },
+ ],
+ ],
+ ['a compaction that persisted an error part', [{ type: ContentTypes.ERROR, error: 'failed' }]],
+ ])('withholds rerun controls on %s', (_label, content) => {
+ const summarizedLeaf = {
+ ...userMessage,
+ messageId: 'assistant-1',
+ parentMessageId: 'user-1',
+ isCreatedByUser: false,
+ text: 'The long answer',
+ } as TMessage;
+ const compactionMessage = {
+ ...userMessage,
+ messageId: 'compaction-1',
+ parentMessageId: summarizedLeaf.messageId,
+ isCreatedByUser: false,
+ text: '',
+ finish_reason: 'length',
+ content,
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: compactionMessage,
+ isLast: true,
+ latestMessageId: compactionMessage.messageId,
+ thread: [userMessage, summarizedLeaf, compactionMessage],
+ });
+
+ /** The row itself is intact — only the rerun shapes are withheld. */
+ expect(screen.getByTestId('copy-response-button')).not.toBeNull();
+ expect(container.querySelector(`#edit-${compactionMessage.messageId}`)).toBeNull();
+ expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
+ expect(screen.queryByTestId('continue-generation-button')).toBeNull();
+ });
+
+ /** Compact runs on whatever leaf the branch ends with, so its summary can hang
+ * off a user message. Replaying that message would answer it again instead of
+ * redoing the compaction, so the server's marker withholds the rerun shapes
+ * there too. */
+ it('withholds rerun controls on a marked compaction hanging off a user message', () => {
+ const compactionMessage = {
+ ...userMessage,
+ messageId: 'compaction-1',
+ parentMessageId: userMessage.messageId,
+ isCreatedByUser: false,
+ text: '',
+ finish_reason: 'length',
+ content: [
+ {
+ type: ContentTypes.SUMMARY,
+ initiatedBy: 'user',
+ content: [{ type: ContentTypes.TEXT, text: 'Earlier turns, compacted.' }],
+ },
+ ],
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: compactionMessage,
+ isLast: true,
+ latestMessageId: compactionMessage.messageId,
+ thread: [userMessage, compactionMessage],
+ });
+
+ expect(screen.getByTestId('copy-response-button')).not.toBeNull();
+ expect(container.querySelector(`#edit-${compactionMessage.messageId}`)).toBeNull();
+ expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
+ expect(screen.queryByTestId('continue-generation-button')).toBeNull();
+ });
+
+ /** An ordinary turn that auto-summarized and was cancelled before its first
+ * answer token persists the same summary-only content, but it hangs off the
+ * user's message and is exactly the turn a user needs to rerun. */
+ it('keeps rerun controls on a cancelled turn that only auto-summarized', () => {
+ const summarizedResponse = {
+ ...userMessage,
+ messageId: 'assistant-1',
+ parentMessageId: userMessage.messageId,
+ isCreatedByUser: false,
+ text: '',
+ finish_reason: 'length',
+ content: [
+ {
+ type: ContentTypes.SUMMARY,
+ content: [{ type: ContentTypes.TEXT, text: 'Older turns were summarized.' }],
+ },
+ ],
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: summarizedResponse,
+ isLast: true,
+ latestMessageId: summarizedResponse.messageId,
+ thread: [userMessage, summarizedResponse],
+ });
+
+ expect(container.querySelector(`#edit-${summarizedResponse.messageId}`)).not.toBeNull();
+ expect(screen.getByTestId('regenerate-generation-button')).toBeEnabled();
+ expect(screen.getByTestId('continue-generation-button')).toBeEnabled();
+ });
+
+ /** An imported or restored conversation can chain one model turn onto another
+ * without a user message between them. That reply has no user turn to replay,
+ * so the rerun shapes go, but its stored content is saved directly by the
+ * editor and stays editable. */
+ it('keeps the editor, not the rerun shapes, on a model turn chained onto another', () => {
+ const firstReply = {
+ ...userMessage,
+ messageId: 'assistant-1',
+ parentMessageId: userMessage.messageId,
+ isCreatedByUser: false,
+ text: 'The first half of the answer',
+ } as TMessage;
+ const chainedReply = {
+ ...userMessage,
+ messageId: 'assistant-2',
+ parentMessageId: firstReply.messageId,
+ isCreatedByUser: false,
+ text: 'The second half of the answer',
+ finish_reason: 'length',
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: chainedReply,
+ isLast: true,
+ latestMessageId: chainedReply.messageId,
+ thread: [userMessage, firstReply, chainedReply],
+ });
+
+ expect(container.querySelector(`#edit-${chainedReply.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', () => {
+ const firstReply = {
+ ...userMessage,
+ messageId: 'assistant-1',
+ parentMessageId: userMessage.messageId,
+ isCreatedByUser: false,
+ text: 'Here it comes',
+ } as TMessage;
+ const artifactReply = {
+ ...userMessage,
+ messageId: 'assistant-2',
+ parentMessageId: firstReply.messageId,
+ isCreatedByUser: false,
+ text: '',
+ content: [
+ {
+ type: ContentTypes.TEXT,
+ text: ':::artifact{identifier="demo" type="text/html" title="Demo"}\n<div />\n:::',
+ },
+ ],
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: artifactReply,
+ isLast: true,
+ latestMessageId: artifactReply.messageId,
+ thread: [userMessage, firstReply, artifactReply],
+ });
+
+ expect(screen.getByTestId('copy-response-button')).not.toBeNull();
+ expect(container.querySelector(`#edit-${artifactReply.messageId}`)).toBeNull();
+ expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
+ });
+
+ /** A response whose parts the editor cannot show a field for still opens the
+ * editor when there is a user turn behind it: its Rerun is the point. */
+ it('keeps the editor on an uneditable response that still has a user turn behind it', () => {
+ const toolOnlyReply = {
+ ...userMessage,
+ messageId: 'assistant-1',
+ parentMessageId: userMessage.messageId,
+ isCreatedByUser: false,
+ text: '',
+ content: [{ type: ContentTypes.ERROR, error: 'failed' }],
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: toolOnlyReply,
+ isLast: true,
+ latestMessageId: toolOnlyReply.messageId,
+ thread: [userMessage, toolOnlyReply],
+ });
+
+ expect(container.querySelector(`#edit-${toolOnlyReply.messageId}`)).not.toBeNull();
+ expect(screen.getByTestId('regenerate-generation-button')).toBeEnabled();
+ });
+
+ /** A row rendered outside the messages view cannot resolve its parent. Withholding
+ * on an unknown parent would strip the controls from every such row, so the gate
+ * stays open and the rerun paths refuse a non-user parent on their own. */
+ it('keeps rerun controls when the thread is unavailable', () => {
+ const compactionMessage = {
+ ...userMessage,
+ messageId: 'compaction-1',
+ parentMessageId: 'assistant-1',
+ isCreatedByUser: false,
+ text: '',
+ finish_reason: 'length',
+ content: [
+ {
+ type: ContentTypes.SUMMARY,
+ content: [{ type: ContentTypes.TEXT, text: 'Earlier turns, compacted.' }],
+ },
+ ],
+ } as TMessage;
+
+ const container = renderHoverButtons({
+ isSubmitting: false,
+ message: compactionMessage,
+ isLast: true,
+ latestMessageId: compactionMessage.messageId,
+ });
+
+ expect(container.querySelector(`#edit-${compactionMessage.messageId}`)).not.toBeNull();
+ expect(screen.getByTestId('regenerate-generation-button')).toBeEnabled();
+ });
});
describe('HoverButtons feedback affordance', () => {
diff --git a/client/src/hooks/useGenerationsByLatest.ts b/client/src/hooks/useGenerationsByLatest.ts
index 4349291177..f5427fd50d 100644
--- a/client/src/hooks/useGenerationsByLatest.ts
+++ b/client/src/hooks/useGenerationsByLatest.ts
@@ -10,6 +10,19 @@ type TUseGenerations = {
finish_reason?: string;
latestMessageId?: string;
isCreatedByUser?: boolean;
+ /** Whether the editor would show a field for this message, resolved lazily: it
+ * parses markdown to spot a read-only artifact, and only a turn with nothing to
+ * 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. */
+ 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
+ * message; replaying that message would answer it again instead of redoing the
+ * compaction, which is the context indicator's Compact action. */
+ isUserInitiatedCompaction?: boolean;
};
export default function useGenerationsByLatest({
@@ -22,6 +35,9 @@ export default function useGenerationsByLatest({
finish_reason = '',
latestMessageId,
isCreatedByUser = false,
+ getHasEditablePart,
+ parentIsUserMessage,
+ isUserInitiatedCompaction = false,
}: TUseGenerations) {
const isEditableEndpoint = Boolean(
[
@@ -35,6 +51,16 @@ export default function useGenerationsByLatest({
].find((e) => e === endpoint),
);
+ /** 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. */
+ const hasNoTurnToReplay =
+ !isCreatedByUser && (parentIsUserMessage === false || isUserInitiatedCompaction);
+
/** The tool-call-limit notice already offers Keep going / Answer now. The hover
* Continue would re-submit the parent user turn with `isContinued`, a different
* and weaker path sitting next to the intended one. */
@@ -46,6 +72,7 @@ export default function useGenerationsByLatest({
!isEditing &&
!isSubmitting &&
!searchResult &&
+ !hasNoTurnToReplay &&
isEditableEndpoint;
const branchingSupported = Boolean(
@@ -61,15 +88,26 @@ export default function useGenerationsByLatest({
);
const regenerateEnabled =
- !isCreatedByUser && !searchResult && !isEditing && !isSubmitting && branchingSupported;
+ !isCreatedByUser &&
+ !searchResult &&
+ !isEditing &&
+ !isSubmitting &&
+ !hasNoTurnToReplay &&
+ branchingSupported;
const isActiveStreamingMessage =
isSubmitting && (latestMessageId == null || messageId === latestMessageId);
+ /** The editor stays available on a model turn with nothing to replay as long as
+ * it has a part to edit — an imported chain's reply is still saved directly,
+ * which needs no rerun. A turn with neither, the compaction shape whether it
+ * finished or persisted an error part instead, would open an editor with no
+ * field and one inert Rerun. */
const hideEditButton =
isActiveStreamingMessage ||
error ||
searchResult ||
+ (hasNoTurnToReplay && getHasEditablePart?.() === false) ||
!branchingSupported ||
(!isEditableEndpoint && !isCreatedByUser);
diff --git a/e2e/specs/mock/db.ts b/e2e/specs/mock/db.ts
index 0ec6ad44a5..66cb5c9362 100644
--- a/e2e/specs/mock/db.ts
+++ b/e2e/specs/mock/db.ts
@@ -87,6 +87,12 @@ export interface SeedMessage {
text: string;
isCreatedByUser: boolean;
sender: string;
+ /** Structured parts, for turns the mock model cannot produce: a summary a
+ * compaction persisted, an error part, an artifact. */
+ content?: Record<string, unknown>[];
+ /** Why the turn stopped; the hover Continue is offered only for some values. */
+ finish_reason?: string;
+ model?: string;
}
/**
diff --git a/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts b/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts
new file mode 100644
index 0000000000..79d098f072
--- /dev/null
+++ b/e2e/specs/mock/scenarios/compaction-rerun-controls.spec.ts
@@ -0,0 +1,342 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { randomUUID } from 'node:crypto';
+import { getE2EUser } from '../../../setup/user';
+import {
+ deleteConversations,
+ deleteMessagesByConversation,
+ seedConversations,
+ seedMessages,
+} from '../db';
+import type { SeedMessage } from '../db';
+import { messagesView } from '../helpers';
+
+const userEmail = getE2EUser().email;
+const ROOT_PARENT = '00000000-0000-0000-0000-000000000000';
+const ARTIFACT_TEXT =
+ ':::artifact{identifier="compaction-demo" type="text/html" title="Demo"}\n```html\n<div>demo</div>\n```\n:::';
+
+type Part = Record<string, unknown>;
+
+const summaryPart = (text: string, extra: Part = {}): Part => ({
+ type: 'summary',
+ content: [{ type: 'text', text }],
+ ...extra,
+});
+
+/** A branch, seeded straight into Mongo: these turn shapes (a compaction's
+ * summary, a persisted error part, a reply chained onto a reply) cannot be
+ * produced through the composer against the mock model. */
+async function seedBranch(messages: SeedMessage[]) {
+ const conversationId = randomUUID();
+ await seedConversations(userEmail, [
+ { conversationId, title: `Compaction ${conversationId.slice(0, 8)}`, updatedAt: new Date() },
+ ]);
+ await seedMessages(userEmail, conversationId, messages);
+ return conversationId;
+}
+
+async function cleanup(conversationId: string) {
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+}
+
+/** The hover actions fade in with the row on pointer devices, so bring the
+ * pointer onto the turn under test before reading its controls. */
+async function openRow(page: Page, conversationId: string, messageId: string) {
+ await page.goto(`/c/${conversationId}`);
+ const row = page.locator(`[id="${messageId}"]`);
+ await expect(row).toBeVisible();
+ await row.hover();
+ return row;
+}
+
+/** A user turn and the answer a compaction would summarize. */
+function precedingTurns(label: string) {
+ const userMessageId = randomUUID();
+ const answerId = randomUUID();
+ return {
+ userMessageId,
+ answerId,
+ messages: [
+ {
+ messageId: userMessageId,
+ parentMessageId: ROOT_PARENT,
+ text: `Tell me about ${label}`,
+ isCreatedByUser: true,
+ sender: 'User',
+ },
+ {
+ messageId: answerId,
+ parentMessageId: userMessageId,
+ text: `The long answer about ${label}`,
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ },
+ ] satisfies SeedMessage[],
+ };
+}
+
+test.describe('compaction rerun controls', () => {
+ test('a finished compaction offers no rerun controls @scenario:compaction-turn-offers-no-rerun-controls', async ({
+ page,
+ }) => {
+ const { answerId, messages } = precedingTurns('finished compaction');
+ const compactionId = randomUUID();
+ const conversationId = await seedBranch([
+ ...messages,
+ {
+ messageId: compactionId,
+ parentMessageId: answerId,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ finish_reason: 'length',
+ content: [summaryPart('Earlier turns, compacted.', { initiatedBy: 'user' })],
+ },
+ ]);
+ try {
+ const row = await openRow(page, conversationId, compactionId);
+
+ await expect(row.getByText('You compacted the context')).toBeVisible();
+ /* The row itself stays intact — only the rerun shapes are withheld. */
+ await expect(row.getByTestId('copy-response-button')).toBeVisible();
+ await expect(page.locator(`[id="edit-${compactionId}"]`)).toHaveCount(0);
+ await expect(page.getByTestId('regenerate-generation-button')).toHaveCount(0);
+ await expect(page.getByTestId('continue-generation-button')).toHaveCount(0);
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a compaction that failed offers no rerun controls @scenario:failed-compaction-offers-no-rerun-controls', async ({
+ page,
+ }) => {
+ const { answerId, messages } = precedingTurns('failed compaction');
+ const compactionId = randomUUID();
+ const conversationId = await seedBranch([
+ ...messages,
+ {
+ messageId: compactionId,
+ parentMessageId: answerId,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ finish_reason: 'length',
+ content: [summaryPart('Partial summary before the failure.', { failed: true })],
+ },
+ ]);
+ try {
+ const row = await openRow(page, conversationId, compactionId);
+
+ await expect(row.getByText('Summarization failed')).toBeVisible();
+ await expect(page.locator(`[id="edit-${compactionId}"]`)).toHaveCount(0);
+ await expect(page.getByTestId('regenerate-generation-button')).toHaveCount(0);
+ await expect(page.getByTestId('continue-generation-button')).toHaveCount(0);
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a compaction hanging off a user turn offers no rerun controls @scenario:compaction-on-user-turn-offers-no-rerun-controls', async ({
+ page,
+ }) => {
+ const userMessageId = randomUUID();
+ const compactionId = randomUUID();
+ const conversationId = await seedBranch([
+ {
+ messageId: userMessageId,
+ parentMessageId: ROOT_PARENT,
+ text: 'Compact this before I continue',
+ isCreatedByUser: true,
+ sender: 'User',
+ },
+ {
+ messageId: compactionId,
+ parentMessageId: userMessageId,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ finish_reason: 'length',
+ content: [summaryPart('Everything so far, compacted.', { initiatedBy: 'user' })],
+ },
+ ]);
+ try {
+ const row = await openRow(page, conversationId, compactionId);
+
+ await expect(row.getByText('You compacted the context')).toBeVisible();
+ /* Replaying the user turn behind it would answer that message again rather
+ than redo the compaction, so the marker withholds the controls here too. */
+ await expect(page.locator(`[id="edit-${compactionId}"]`)).toHaveCount(0);
+ await expect(page.getByTestId('regenerate-generation-button')).toHaveCount(0);
+ await expect(page.getByTestId('continue-generation-button')).toHaveCount(0);
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a turn that only auto-summarized keeps its rerun controls @scenario:auto-summarized-turn-keeps-rerun-controls', async ({
+ page,
+ }) => {
+ const userMessageId = randomUUID();
+ const responseId = randomUUID();
+ const conversationId = await seedBranch([
+ {
+ messageId: userMessageId,
+ parentMessageId: ROOT_PARENT,
+ text: 'Answer after summarizing the older turns',
+ isCreatedByUser: true,
+ sender: 'User',
+ },
+ {
+ messageId: responseId,
+ parentMessageId: userMessageId,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ finish_reason: 'length',
+ content: [summaryPart('Older turns were summarized.')],
+ },
+ ]);
+ try {
+ const row = await openRow(page, conversationId, responseId);
+
+ await expect(row.getByText('Conversation summarized')).toBeVisible();
+ /* Cancelled before its first answer token: this is the turn a rerun is for. */
+ await expect(page.locator(`[id="edit-${responseId}"]`)).toBeVisible();
+ await expect(page.getByTestId('regenerate-generation-button')).toBeVisible();
+ await expect(page.getByTestId('continue-generation-button')).toBeVisible();
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a reply chained onto another reply keeps its editor without a rerun @scenario:chained-reply-keeps-editor-without-rerun', async ({
+ page,
+ }) => {
+ const { answerId, messages } = precedingTurns('an imported thread');
+ const chainedId = randomUUID();
+ const conversationId = await seedBranch([
+ ...messages,
+ {
+ messageId: chainedId,
+ parentMessageId: answerId,
+ text: 'The second half of the answer',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ finish_reason: 'length',
+ },
+ ]);
+ try {
+ const row = await openRow(page, conversationId, chainedId);
+
+ /* No user turn to replay, so the rerun shapes go... */
+ await expect(page.getByTestId('regenerate-generation-button')).toHaveCount(0);
+ await expect(page.getByTestId('continue-generation-button')).toHaveCount(0);
+ /* ...but the stored content is saved directly, so the editor stays. */
+ await page.locator(`[id="edit-${chainedId}"]`).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.getByRole('button', { name: 'Update & rerun' })).toHaveCount(0);
+ await expect(editor).toHaveAttribute('aria-keyshortcuts', 'Control+S Meta+S Escape');
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a chained reply made only of an artifact offers no editor @scenario:artifact-only-chained-reply-offers-no-editor', async ({
+ page,
+ }) => {
+ const { answerId, messages } = precedingTurns('an artifact');
+ const artifactId = randomUUID();
+ const conversationId = await seedBranch([
+ ...messages,
+ {
+ messageId: artifactId,
+ parentMessageId: answerId,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ content: [{ type: 'text', text: ARTIFACT_TEXT }],
+ },
+ ]);
+ try {
+ const row = await openRow(page, conversationId, artifactId);
+
+ /* The artifact keeps its read-only renderer, so the editor would open with
+ no field and one inert Rerun. */
+ await expect(row.getByTestId('copy-response-button')).toBeVisible();
+ await expect(page.locator(`[id="edit-${artifactId}"]`)).toHaveCount(0);
+ await expect(page.getByTestId('regenerate-generation-button')).toHaveCount(0);
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('a save-only editor reports unsaved changes @scenario:save-only-editor-reports-unsaved-changes', async ({
+ page,
+ }) => {
+ const { answerId, messages } = precedingTurns('a save-only editor');
+ const chainedId = randomUUID();
+ const conversationId = await seedBranch([
+ ...messages,
+ {
+ messageId: chainedId,
+ parentMessageId: answerId,
+ text: 'The second half of the answer',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ },
+ ]);
+ try {
+ await openRow(page, conversationId, chainedId);
+ await page.locator(`[id="edit-${chainedId}"]`).click();
+ const editor = page.getByTestId('message-text-editor');
+ await expect(editor).toBeVisible();
+
+ await editor.click();
+ await editor.pressSequentially(' and a correction');
+
+ /* The warning about a discarded rerun describes an action this editor does
+ not offer. */
+ await expect(page.getByText('Unsaved changes')).toBeVisible();
+ await expect(
+ page.getByText('Rerunning discards these changes and generates a new response.', {
+ exact: false,
+ }),
+ ).toHaveCount(0);
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+
+ test('Compact context stays available after a failed compaction @scenario:compact-action-available-on-failed-compaction', async ({
+ page,
+ }) => {
+ const { answerId, messages } = precedingTurns('a retried compaction');
+ const compactionId = randomUUID();
+ const conversationId = await seedBranch([
+ ...messages,
+ {
+ messageId: compactionId,
+ parentMessageId: answerId,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'OpenAI',
+ content: [summaryPart('Partial summary before the failure.', { failed: true })],
+ },
+ ]);
+ try {
+ await page.goto(`/c/${conversationId}`);
+ await expect(messagesView(page).getByText('Summarization failed')).toBeVisible();
+
+ /* The redo path a compaction turn keeps: the context indicator's action. */
+ await page.getByTestId('token-usage').click();
+ await expect(page.getByRole('button', { name: 'Compact context' })).toBeEnabled();
+ } finally {
+ await cleanup(conversationId);
+ }
+ });
+});
diff --git a/packages/data-provider/src/messages.spec.ts b/packages/data-provider/src/messages.spec.ts
index 0fc50d5b55..67d865893c 100644
--- a/packages/data-provider/src/messages.spec.ts
+++ b/packages/data-provider/src/messages.spec.ts
@@ -1,7 +1,7 @@
import type { ParentMessage } from './messages';
import type { TFile } from './types/files';
import type { TMessage } from './types';
-import { buildTree, isCompactedLeaf } from './messages';
+import { buildTree, findMessageById, isCompactedLeaf, isUserInitiatedCompaction } from './messages';
import { ContentTypes } from './types/runs';
const msg = (messageId: string, parentMessageId: string, over: Partial<TMessage> = {}): TMessage =>
@@ -220,3 +220,56 @@ describe('isCompactedLeaf', () => {
expect(isCompactedLeaf({ content } as TMessage)).toBe(false);
});
});
+
+describe('findMessageById', () => {
+ const thread = () => [
+ msg('u1', '00000000-0000-0000-0000-000000000000', { isCreatedByUser: true }),
+ msg('a1', 'u1'),
+ ];
+
+ it('resolves a message by id and reports a missing one', () => {
+ const messages = thread();
+ expect(findMessageById(messages, 'a1')).toBe(messages[1]);
+ expect(findMessageById(messages, 'absent')).toBeUndefined();
+ expect(findMessageById(messages, null)).toBeUndefined();
+ expect(findMessageById(null, 'a1')).toBeUndefined();
+ });
+
+ /** The index is memoized per array identity, and a cache write replaces the
+ * array. Answering a later lookup from the previous array's rows would hand
+ * the caller a message the thread no longer holds. */
+ it('answers from the array it was given, not from a previous one', () => {
+ const before = thread();
+ expect(findMessageById(before, 'a1')).toBe(before[1]);
+
+ const edited = { ...before[1], text: 'edited' };
+ const after = [before[0], edited];
+
+ expect(findMessageById(after, 'a1')).toBe(edited);
+ expect(findMessageById(before, 'a1')).toBe(before[1]);
+ });
+});
+
+describe('isUserInitiatedCompaction', () => {
+ const summary = (overrides: Record<string, unknown> = {}) => ({
+ type: ContentTypes.SUMMARY,
+ content: [{ type: ContentTypes.TEXT, text: 'checkpoint' }],
+ ...overrides,
+ });
+
+ it('is true for the summary a Compact action produced', () => {
+ expect(
+ isUserInitiatedCompaction({ content: [summary({ initiatedBy: 'user' })] } as TMessage),
+ ).toBe(true);
+ });
+
+ /** An automatic summary detour carries no marker: that turn answers a user
+ * message and stays rerunnable. */
+ it.each([
+ ['an unmarked summary', [summary()]],
+ ['a plain answer', [{ type: ContentTypes.TEXT, text: 'reply' }]],
+ ['no content', undefined],
+ ])('is false for %s', (_label, content) => {
+ expect(isUserInitiatedCompaction({ content } as TMessage)).toBe(false);
+ });
+});
diff --git a/packages/data-provider/src/messages.ts b/packages/data-provider/src/messages.ts
index 554e97173c..14465bd803 100644
--- a/packages/data-provider/src/messages.ts
+++ b/packages/data-provider/src/messages.ts
@@ -156,10 +156,58 @@ export function buildTree({
return tree;
}
+/**
+ * Memoizes a messages array's id index. Every row that needs to look another
+ * message up (the hover controls resolving the turn a rerun would replay) would
+ * otherwise scan the whole array, which is quadratic in the conversation. A
+ * cache write replaces the array, so the index dies with the array it indexes
+ * and can never answer from stale rows.
+ */
+const indexCache = new WeakMap<(TMessage | undefined)[], Map<string, TMessage>>();
+
+/** The message with this id, resolved through the array's memoized index. */
+export function findMessageById(
+ messages: (TMessage | undefined)[] | null | undefined,
+ messageId?: string | null,
+): TMessage | undefined {
+ if (messages == null || messageId == null) {
+ return undefined;
+ }
+ let index = indexCache.get(messages);
+ if (index == null) {
+ index = new Map<string, TMessage>();
+ for (const message of messages) {
+ if (message?.messageId != null && !index.has(message.messageId)) {
+ index.set(message.messageId, message);
+ }
+ }
+ indexCache.set(messages, index);
+ }
+ return index.get(messageId);
+}
+
+/**
+ * True when a turn carries the marker the server stamps on a manual compaction:
+ * `markCompactionSummary` sets `initiatedBy: 'user'` on the summary a Compact
+ * action produced, and nothing else writes it, so an automatic summary detour is
+ * not one. This is the compaction's own identity, independent of where it hangs:
+ * Compact runs on whatever leaf the branch ends with, so its response can parent
+ * onto a user message as easily as onto the answer it summarized. Redoing one is
+ * the context indicator's Compact action, never a rerun of the turn behind it.
+ */
+export function isUserInitiatedCompaction(message?: Pick<TMessage, 'content'> | null): boolean {
+ const content = message?.content;
+ if (!Array.isArray(content)) {
+ return false;
+ }
+ return content.some((part) => part?.type === ContentTypes.SUMMARY && part.initiatedBy === 'user');
+}
+
/**
* True when a message is a finished manual compaction: every content part is a
- * summary and at least one of them carries text. A summary still streaming or
- * one that failed does not count, so an interrupted compaction can be retried.
+ * summary and at least one of them carries text. A part that is still streaming
+ * or that failed contributes no text of its own, so an interrupted compaction
+ * can be retried.
*/
export function isCompactedLeaf(message?: Pick<TMessage, 'content'> | null): boolean {
const content = message?.content;